{"id":"JanG7L1cZ61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/introduction/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Introduction","summary":"What Total.js framework v5 is, what the total5 package includes and the main concepts of a Total.js application.","markdown":"---\ntitle: Introduction\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/introduction/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# Introduction\n\n> What Total.js framework v5 is, what the total5 package includes and the main concepts of a Total.js application.\n\nTotal.js framework v5 is a framework for the Node.js platform, written in pure JavaScript. The package README compares it with PHP's Laravel, Python's Django and ASP.NET MVC, and says it can be used for a web, desktop, service or IoT application.\n\nIt is published on npm as `total5`, under the MIT license, by Peter Širka. The source code lives in the `totaljs/framework5` repository on GitHub.\n\n```bash\n$ npm install total5@beta\n```\n\n## One package, no dependencies\n\nThe `total5` package does not declare any npm dependency. Everything the framework needs is inside the package: the HTTP server, the router, the view engine, the database layers, the mailer, the image processing, the workers and the Flow engine. You load it once with `require('total5')` and the framework registers its API as globals (`ROUTE()`, `NEWACTION()`, `NOSQL()`, `CONF`, `F` and many more), so application files can use them without any `require()`.\n\n```js\nrequire('total5');\n\nROUTE('GET /', function($) {\n\t$.plain('Hello world');\n});\n\nF.http({ port: 8000 });\n```\n\nThe package also installs two command-line tools, `total5` and `flow5`. They are described in [Command line](../command-line/).\n\n## What the package includes\n\nThe package is a set of modules. Each module covers one area of a typical application:\n| Area | Modules | Main API |\n|------|---------|----------|\n| HTTP server and routing | `http.js`, `routing.js`, `controller.js` | `ROUTE()`, the controller `$` |\n| Actions and schemas | `builders.js`, `jsonschema.js` | `NEWACTION()`, `ACTION()`, `NEWSCHEMA()` |\n| Views and templates | `viewengine.js`, `tangular.js`, `templates.js`, `markdown.js` | `$.view()`, `TEMPLATE()` |\n| WebSocket | `websocket.js` | `ROUTE('SOCKET ...')`, `WEBSOCKETCLIENT()` |\n| NoSQL embedded database | `nosql.js`, `nosql-*.js` | `NOSQL()` |\n| Query builder for SQL databases | `querybuilder.js` | `DATA`, `DB()`, `NEWDB()` |\n| File storage | `filestorage.js` | `FILESTORAGE()` |\n| Outgoing HTTP requests | `utils.js`, `builders.js` | `REQUEST()`, `RESTBuilder`, `AJAX()` |\n| Mail | `mail.js` | `MAIL()`, `HTMLMAIL()`, `Mail` |\n| Scheduling | `cron.js` | `CRON()` |\n| Images | `images.js` | `Image` |\n| Plugins and components | `index.js`, `components.js` | `plugins/` directory, `NEWCOMPONENT()` |\n| Flow engine | `flow.js`, `flowstream.js`, `flow-flowstream.js` | FlowStream, `flow5` |\n| Total.js Message Service | `tms.js` | `NEWPUBLISH()`, `NEWSUBSCRIBE()`, `PUBLISH()`, `SUBSCRIBE()` |\n| API services | `api.js` | `API()`, `NEWAPI()` |\n| Workers and threads | `workers.js`, `cluster.js` | `NEWTHREAD()`, `NEWTHREADPOOL()` |\n| Python scripts | `pypeline.js` | `PYPELINE()` |\n| Utilities | `utils.js`, `htmlparser.js`, `minificators.js`, `macros.js` | `U`, `NEWMACRO()` |\n| AI models | `aimodel.js` | `NEWAIMODEL()`, `AIMODEL()`, `AIPARSER()` |\n| Proxy | `proxy.js` | `PROXYSERVER()`, `PROXYCLIENT()` |\n| Other modules | `ldap.js`, `cms.js`, `uibuilder.js`, `openclient.js`, `bundles.js`, `edit.js` | `LDAP()`, `OPENCLIENT()`, bundles, remote editing |\n| Start and watcher | `debug.js`, `release.js` | `Total.run()` (`F.run()`) |\n\n## Main concepts\n\n### Application directory\n\nA Total.js application is a directory with a start script and a set of known subdirectories (`controllers`, `actions`, `schemas`, `plugins`, `public`, `views` and others). The framework loads them automatically when it starts. See [Installation and first app](../installation/) and [Application structure](../application-structure/).\n\n### Routes and the controller\n\nA route maps an HTTP method and a URL to a handler. The handler receives the controller `$`, which holds the request and has the methods for the response (`$.plain()`, `$.json()`, `$.html()`, `$.view()`, `$.file()` and others).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', function($) {\n\t\t$.plain('Hello world');\n\t});\n};\n```\n\nSee [Routing](../routing/) and [Controller](../controller/). Static files, middleware and authorization are in [Middleware](../middleware/), [Static files](../static-files/) and [Authorization](../authorization/).\n\n### Actions\n\nActions are the business logic of the application. An action has a name, an optional input schema and a handler. Routes can call actions directly with the `-->` operator, so the same logic is reachable from HTTP, from other actions and from code.\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nROUTE('GET /api/hello/ --> hello');\n```\n\nSee [Actions](../actions/) and [JSON schemas](../json-schemas/).\n\n### Views\n\nThe view engine renders HTML templates from the `views` directory with models, layouts and helpers. See [Views](../views/) and [Localization](../localization/).\n\n### Configuration\n\nThe `config` file in the application root holds key/value settings, read into the global `CONF` object. See [Configuration](../configuration/).\n\n### Data\n\nThe framework includes an embedded NoSQL database stored in the `databases` directory (`NOSQL()`), a query builder for SQL databases (`DATA`, `DB()`, `NEWDB()`) and a file storage (`FILESTORAGE()`). See [NoSQL](../nosql/), [QueryBuilder](../querybuilder/) and [File storage](../file-storage/).\n\n### Plugins and components\n\nA plugin is a self-contained part of an application in `plugins/<name>/`, with its own controllers, actions, schemas and definitions. Components (`NEWCOMPONENT()`) compile reusable HTML components. See [Plugins and components](../plugins-and-components/).\n\n### FlowStream\n\nFlowStream is the Total.js visual programming engine: data flows between connected components in a flow schema. The `flow5` binary runs flow schemas directly. See [FlowStream](../flowstream/).\n\n### TMS and APIs\n\nThe Total.js Message Service (TMS) publishes and subscribes messages between Total.js applications over WebSocket, and `API()` calls remote API services. See [Message Service (TMS)](../message-service-and-apis/) and [APIs](../apis/).\n\n### AI models\n\nThe `aimodel.js` module registers AI model handlers with `NEWAIMODEL()` and builds requests for them with `AIMODEL()`: system and user messages, tools, streaming and callbacks. `AIPARSER()` parses AI responses. See [AI models](../ai-models/).\n\n### Everything else\n\nWebSocket, outgoing HTTP requests, mail, scheduling and events, workers and threads, images and utilities each have their own guide: [WebSockets](../websockets/), [HTTP requests](../http-requests/), [Mail](../mail/), [Scheduling and events](../scheduling-and-events/), [Workers and threads](../workers-and-threads/), [Images](../images/), [Utilities](../utilities/), [Prototypes](../prototypes/), [Proxy](../proxy/), [LDAP](../ldap/), [Markdown](../markdown/), [HTML and XML parser](../html-parser/), [Macros](../macros/), [Tangular](../tangular/), [Minification](../minification/) and [CMS compiler](../cms/).\n\n## Where to go next\n\n1. [Installation and first app](../installation/): install the package, write the start script and the first route.\n2. [Application structure](../application-structure/): the full list of directories and files.\n3. [Routing](../routing/) and [Actions](../actions/): the two parts every application uses.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JanG7L1cZ61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/introduction/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Einführung","summary":"Was das Total.js framework v5 ist, was das Paket total5 enthält und die wichtigsten Konzepte einer Total.js-Anwendung.","markdown":"---\ntitle: \"Einführung\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/introduction/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# Einführung\n\n> Was das Total.js framework v5 ist, was das Paket total5 enthält und die wichtigsten Konzepte einer Total.js-Anwendung.\n\nTotal.js framework v5 ist ein Framework für die Node.js-Plattform, geschrieben in reinem JavaScript. Das README des Pakets vergleicht es mit Laravel für PHP, Django für Python und ASP.NET MVC und sagt, dass es für eine Web-, Desktop-, Service- oder IoT-Anwendung verwendet werden kann.\n\nEs wird auf npm als `total5` unter der MIT-Lizenz von Peter Širka veröffentlicht. Der Quellcode liegt im Repository `totaljs/framework5` auf GitHub.\n\n```bash\n$ npm install total5@beta\n```\n\n## Ein Paket, keine Abhängigkeiten\n\nDas Paket `total5` deklariert keine npm-Abhängigkeit. Alles, was das Framework braucht, steckt im Paket: der HTTP-Server, der Router, die View-Engine, die Datenbankschichten, der Mailer, die Bildverarbeitung, die Worker und die Flow-Engine. Du lädst es einmal mit `require('total5')`, und das Framework registriert seine API als globale Werte (`ROUTE()`, `NEWACTION()`, `NOSQL()`, `CONF`, `F` und viele mehr), sodass die Dateien der Anwendung sie ohne `require()` verwenden können.\n\n```js\nrequire('total5');\n\nROUTE('GET /', function($) {\n\t$.plain('Hello world');\n});\n\nF.http({ port: 8000 });\n```\n\nDas Paket installiert außerdem zwei Kommandozeilenwerkzeuge, `total5` und `flow5`. Sie werden in [Kommandozeile](../command-line/) beschrieben.\n\n## Was das Paket enthält\n\nDas Paket ist eine Menge von Modulen. Jedes Modul deckt einen Bereich einer typischen Anwendung ab:\n| Bereich | Module | Haupt-API |\n|------|---------|----------|\n| HTTP-Server und Routing | `http.js`, `routing.js`, `controller.js` | `ROUTE()`, der Controller `$` |\n| Aktionen und Schemas | `builders.js`, `jsonschema.js` | `NEWACTION()`, `ACTION()`, `NEWSCHEMA()` |\n| Views und Templates | `viewengine.js`, `tangular.js`, `templates.js`, `markdown.js` | `$.view()`, `TEMPLATE()` |\n| WebSocket | `websocket.js` | `ROUTE('SOCKET ...')`, `WEBSOCKETCLIENT()` |\n| Eingebettete NoSQL-Datenbank | `nosql.js`, `nosql-*.js` | `NOSQL()` |\n| Query Builder für SQL-Datenbanken | `querybuilder.js` | `DATA`, `DB()`, `NEWDB()` |\n| Dateispeicher | `filestorage.js` | `FILESTORAGE()` |\n| Ausgehende HTTP-Anfragen | `utils.js`, `builders.js` | `REQUEST()`, `RESTBuilder`, `AJAX()` |\n| Mail | `mail.js` | `MAIL()`, `HTMLMAIL()`, `Mail` |\n| Zeitplanung | `cron.js` | `CRON()` |\n| Bilder | `images.js` | `Image` |\n| Plugins und Komponenten | `index.js`, `components.js` | Verzeichnis `plugins/`, `NEWCOMPONENT()` |\n| Flow-Engine | `flow.js`, `flowstream.js`, `flow-flowstream.js` | FlowStream, `flow5` |\n| Total.js Message Service | `tms.js` | `NEWPUBLISH()`, `NEWSUBSCRIBE()`, `PUBLISH()`, `SUBSCRIBE()` |\n| API-Dienste | `api.js` | `API()`, `NEWAPI()` |\n| Worker und Threads | `workers.js`, `cluster.js` | `NEWTHREAD()`, `NEWTHREADPOOL()` |\n| Python-Skripte | `pypeline.js` | `PYPELINE()` |\n| Hilfsfunktionen | `utils.js`, `htmlparser.js`, `minificators.js`, `macros.js` | `U`, `NEWMACRO()` |\n| KI-Modelle | `aimodel.js` | `NEWAIMODEL()`, `AIMODEL()`, `AIPARSER()` |\n| Proxy | `proxy.js` | `PROXYSERVER()`, `PROXYCLIENT()` |\n| Weitere Module | `ldap.js`, `cms.js`, `uibuilder.js`, `openclient.js`, `bundles.js`, `edit.js` | `LDAP()`, `OPENCLIENT()`, Bundles, entfernte Bearbeitung |\n| Start und Watcher | `debug.js`, `release.js` | `Total.run()` (`F.run()`) |\n\n## Wichtige Konzepte\n\n### Verzeichnis der Anwendung\n\nEine Total.js-Anwendung ist ein Verzeichnis mit einem Startskript und einer Reihe bekannter Unterverzeichnisse (`controllers`, `actions`, `schemas`, `plugins`, `public`, `views` und andere). Das Framework lädt sie beim Start automatisch. Siehe [Installation und erste Anwendung](../installation/) und [Aufbau der Anwendung](../application-structure/).\n\n### Routen und der Controller\n\nEine Route ordnet eine HTTP-Methode und eine URL einem Handler zu. Der Handler erhält den Controller `$`, der die Anfrage enthält und die Methoden für die Antwort hat (`$.plain()`, `$.json()`, `$.html()`, `$.view()`, `$.file()` und andere).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', function($) {\n\t\t$.plain('Hello world');\n\t});\n};\n```\n\nSiehe [Routing](../routing/) und [Controller](../controller/). Statische Dateien, Middleware und Autorisierung stehen in [Middleware](../middleware/), [Statische Dateien](../static-files/) und [Autorisierung](../authorization/).\n\n### Aktionen\n\nAktionen sind die Geschäftslogik der Anwendung. Eine Aktion hat einen Namen, ein optionales Eingabeschema und einen Handler. Routen können Aktionen direkt mit dem Operator `-->` aufrufen, sodass dieselbe Logik über HTTP, aus anderen Aktionen und aus Code erreichbar ist.\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nROUTE('GET /api/hello/ --> hello');\n```\n\nSiehe [Aktionen](../actions/) und [JSON-Schemas](../json-schemas/).\n\n### Views\n\nDie View-Engine rendert HTML-Templates aus dem Verzeichnis `views` mit Modellen, Layouts und Helfern. Siehe [Views](../views/) und [Lokalisierung](../localization/).\n\n### Konfiguration\n\nDie Datei `config` im Stammverzeichnis der Anwendung enthält Schlüssel/Wert-Einstellungen, die in das globale Objekt `CONF` eingelesen werden. Siehe [Konfiguration](../configuration/).\n\n### Daten\n\nDas Framework enthält eine eingebettete NoSQL-Datenbank, die im Verzeichnis `databases` gespeichert wird (`NOSQL()`), einen Query Builder für SQL-Datenbanken (`DATA`, `DB()`, `NEWDB()`) und einen Dateispeicher (`FILESTORAGE()`). Siehe [NoSQL](../nosql/), [QueryBuilder](../querybuilder/) und [Dateispeicher](../file-storage/).\n\n### Plugins und Komponenten\n\nEin Plugin ist ein eigenständiger Teil einer Anwendung in `plugins/<name>/`, mit eigenen Controllern, Aktionen, Schemas und Definitionen. Komponenten (`NEWCOMPONENT()`) kompilieren wiederverwendbare HTML-Komponenten. Siehe [Plugins und Komponenten](../plugins-and-components/).\n\n### FlowStream\n\nFlowStream ist die Engine für visuelle Programmierung von Total.js: Daten fließen zwischen verbundenen Komponenten in einem Flow-Schema. Das Programm `flow5` führt Flow-Schemas direkt aus. Siehe [FlowStream](../flowstream/).\n\n### TMS und APIs\n\nDer Total.js Message Service (TMS) veröffentlicht und abonniert Nachrichten zwischen Total.js-Anwendungen über WebSocket, und `API()` ruft entfernte API-Dienste auf. Siehe [Message Service (TMS)](../message-service-and-apis/) und [APIs](../apis/).\n\n### KI-Modelle\n\nDas Modul `aimodel.js` registriert KI-Modell-Handler mit `NEWAIMODEL()` und erstellt mit `AIMODEL()` Anfragen für sie: System- und Benutzernachrichten, Tools, Streaming und Callbacks. `AIPARSER()` parst KI-Antworten. Siehe [KI-Modelle](../ai-models/).\n\n### Alles andere\n\nWebSocket, ausgehende HTTP-Anfragen, Mail, Zeitplanung und Events, Worker und Threads, Bilder und Hilfsfunktionen haben jeweils einen eigenen Leitfaden: [WebSockets](../websockets/), [HTTP-Anfragen](../http-requests/), [Mail](../mail/), [Zeitplanung und Events](../scheduling-and-events/), [Worker und Threads](../workers-and-threads/), [Bilder](../images/), [Hilfsfunktionen](../utilities/), [Prototypen](../prototypes/), [Proxy](../proxy/), [LDAP](../ldap/), [Markdown](../markdown/), [HTML- und XML-Parser](../html-parser/), [Makros](../macros/), [Tangular](../tangular/), [Minifizierung](../minification/) und [CMS-Compiler](../cms/).\n\n## Wie es weitergeht\n\n1. [Installation und erste Anwendung](../installation/): das Paket installieren, das Startskript und die erste Route schreiben.\n2. [Aufbau der Anwendung](../application-structure/): die vollständige Liste der Verzeichnisse und Dateien.\n3. [Routing](../routing/) und [Aktionen](../actions/): die zwei Teile, die jede Anwendung verwendet.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JanG7L1cZ61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/introduction/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Introducción","summary":"Qué es Total.js framework v5, qué incluye el paquete total5 y los conceptos principales de una aplicación Total.js.","markdown":"---\ntitle: \"Introducción\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/introduction/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# Introducción\n\n> Qué es Total.js framework v5, qué incluye el paquete total5 y los conceptos principales de una aplicación Total.js.\n\nTotal.js framework v5 es un framework para la plataforma Node.js, escrito en JavaScript puro. El README del paquete lo compara con Laravel de PHP, Django de Python y ASP.NET MVC, y dice que se puede usar para una aplicación web, de escritorio, de servicio o IoT.\n\nEstá publicado en npm como `total5`, bajo la licencia MIT, por Peter Širka. El código fuente está en el repositorio `totaljs/framework5` de GitHub.\n\n```bash\n$ npm install total5@beta\n```\n\n## Un paquete, sin dependencias\n\nEl paquete `total5` no declara ninguna dependencia de npm. Todo lo que necesita el framework está dentro del paquete: el servidor HTTP, el router, el motor de vistas, las capas de base de datos, el envío de correo, el procesamiento de imágenes, los workers y el motor Flow. Lo cargas una vez con `require('total5')` y el framework registra su API como globales (`ROUTE()`, `NEWACTION()`, `NOSQL()`, `CONF`, `F` y muchas más), así los archivos de la aplicación pueden usarlas sin ningún `require()`.\n\n```js\nrequire('total5');\n\nROUTE('GET /', function($) {\n\t$.plain('Hello world');\n});\n\nF.http({ port: 8000 });\n```\n\nEl paquete también instala dos herramientas de línea de comandos, `total5` y `flow5`. Se describen en [Línea de comandos](../command-line/).\n\n## Qué incluye el paquete\n\nEl paquete es un conjunto de módulos. Cada módulo cubre un área de una aplicación típica:\n| Área | Módulos | API principal |\n|------|---------|----------|\n| Servidor HTTP y enrutamiento | `http.js`, `routing.js`, `controller.js` | `ROUTE()`, el controlador `$` |\n| Acciones y esquemas | `builders.js`, `jsonschema.js` | `NEWACTION()`, `ACTION()`, `NEWSCHEMA()` |\n| Vistas y plantillas | `viewengine.js`, `tangular.js`, `templates.js`, `markdown.js` | `$.view()`, `TEMPLATE()` |\n| WebSocket | `websocket.js` | `ROUTE('SOCKET ...')`, `WEBSOCKETCLIENT()` |\n| Base de datos NoSQL embebida | `nosql.js`, `nosql-*.js` | `NOSQL()` |\n| Query builder para bases de datos SQL | `querybuilder.js` | `DATA`, `DB()`, `NEWDB()` |\n| Almacenamiento de archivos | `filestorage.js` | `FILESTORAGE()` |\n| Peticiones HTTP salientes | `utils.js`, `builders.js` | `REQUEST()`, `RESTBuilder`, `AJAX()` |\n| Correo | `mail.js` | `MAIL()`, `HTMLMAIL()`, `Mail` |\n| Programación | `cron.js` | `CRON()` |\n| Imágenes | `images.js` | `Image` |\n| Plugins y componentes | `index.js`, `components.js` | directorio `plugins/`, `NEWCOMPONENT()` |\n| Motor Flow | `flow.js`, `flowstream.js`, `flow-flowstream.js` | FlowStream, `flow5` |\n| Total.js Message Service | `tms.js` | `NEWPUBLISH()`, `NEWSUBSCRIBE()`, `PUBLISH()`, `SUBSCRIBE()` |\n| Servicios API | `api.js` | `API()`, `NEWAPI()` |\n| Workers e hilos | `workers.js`, `cluster.js` | `NEWTHREAD()`, `NEWTHREADPOOL()` |\n| Scripts de Python | `pypeline.js` | `PYPELINE()` |\n| Utilidades | `utils.js`, `htmlparser.js`, `minificators.js`, `macros.js` | `U`, `NEWMACRO()` |\n| Modelos de IA | `aimodel.js` | `NEWAIMODEL()`, `AIMODEL()`, `AIPARSER()` |\n| Proxy | `proxy.js` | `PROXYSERVER()`, `PROXYCLIENT()` |\n| Otros módulos | `ldap.js`, `cms.js`, `uibuilder.js`, `openclient.js`, `bundles.js`, `edit.js` | `LDAP()`, `OPENCLIENT()`, bundles, edición remota |\n| Inicio y watcher | `debug.js`, `release.js` | `Total.run()` (`F.run()`) |\n\n## Conceptos principales\n\n### Directorio de la aplicación\n\nUna aplicación Total.js es un directorio con un script de inicio y un conjunto de subdirectorios conocidos (`controllers`, `actions`, `schemas`, `plugins`, `public`, `views` y otros). El framework los carga automáticamente al iniciarse. Consulta [Instalación y primera aplicación](../installation/) y [Estructura de la aplicación](../application-structure/).\n\n### Rutas y el controlador\n\nUna ruta asocia un método HTTP y una URL a un handler. El handler recibe el controlador `$`, que contiene la petición y tiene los métodos para la respuesta (`$.plain()`, `$.json()`, `$.html()`, `$.view()`, `$.file()` y otros).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', function($) {\n\t\t$.plain('Hello world');\n\t});\n};\n```\n\nConsulta [Enrutamiento](../routing/) y [Controlador](../controller/). Los archivos estáticos, el middleware y la autorización están en [Middleware](../middleware/), [Archivos estáticos](../static-files/) y [Autorización](../authorization/).\n\n### Acciones\n\nLas acciones son la lógica de negocio de la aplicación. Una acción tiene un nombre, un esquema de entrada opcional y un handler. Las rutas pueden llamar a las acciones directamente con el operador `-->`, así la misma lógica es accesible desde HTTP, desde otras acciones y desde el código.\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nROUTE('GET /api/hello/ --> hello');\n```\n\nConsulta [Acciones](../actions/) y [Esquemas JSON](../json-schemas/).\n\n### Vistas\n\nEl motor de vistas renderiza plantillas HTML del directorio `views` con modelos, plantillas (layouts) y helpers. Consulta [Vistas](../views/) y [Localización](../localization/).\n\n### Configuración\n\nEl archivo `config` de la raíz de la aplicación contiene ajustes clave/valor, que se leen en el objeto global `CONF`. Consulta [Configuración](../configuration/).\n\n### Datos\n\nEl framework incluye una base de datos NoSQL embebida guardada en el directorio `databases` (`NOSQL()`), un query builder para bases de datos SQL (`DATA`, `DB()`, `NEWDB()`) y un almacenamiento de archivos (`FILESTORAGE()`). Consulta [NoSQL](../nosql/), [QueryBuilder](../querybuilder/) y [Almacenamiento de archivos](../file-storage/).\n\n### Plugins y componentes\n\nUn plugin es una parte autónoma de una aplicación en `plugins/<name>/`, con sus propios controladores, acciones, esquemas y definiciones. Los componentes (`NEWCOMPONENT()`) compilan componentes HTML reutilizables. Consulta [Plugins y componentes](../plugins-and-components/).\n\n### FlowStream\n\nFlowStream es el motor de programación visual de Total.js: los datos fluyen entre componentes conectados en un esquema de flujo. El binario `flow5` ejecuta esquemas de flujo directamente. Consulta [FlowStream](../flowstream/).\n\n### TMS y APIs\n\nTotal.js Message Service (TMS) publica y suscribe mensajes entre aplicaciones Total.js mediante WebSocket, y `API()` llama a servicios API remotos. Consulta [Message Service (TMS)](../message-service-and-apis/) y [APIs](../apis/).\n\n### Modelos de IA\n\nEl módulo `aimodel.js` registra handlers de modelos de IA con `NEWAIMODEL()` y construye peticiones para ellos con `AIMODEL()`: mensajes de sistema y de usuario, herramientas, streaming y callbacks. `AIPARSER()` parsea las respuestas de IA. Consulta [Modelos de IA](../ai-models/).\n\n### Todo lo demás\n\nWebSocket, las peticiones HTTP salientes, el correo, la programación y los eventos, los workers y los hilos, las imágenes y las utilidades tienen cada uno su propia guía: [WebSockets](../websockets/), [Peticiones HTTP](../http-requests/), [Correo](../mail/), [Programación y eventos](../scheduling-and-events/), [Workers e hilos](../workers-and-threads/), [Imágenes](../images/), [Utilidades](../utilities/), [Prototipos](../prototypes/), [Proxy](../proxy/), [LDAP](../ldap/), [Markdown](../markdown/), [Parser de HTML y XML](../html-parser/), [Macros](../macros/), [Tangular](../tangular/), [Minificación](../minification/) y [Compilador del CMS](../cms/).\n\n## Por dónde seguir\n\n1. [Instalación y primera aplicación](../installation/): instala el paquete, escribe el script de inicio y la primera ruta.\n2. [Estructura de la aplicación](../application-structure/): la lista completa de directorios y archivos.\n3. [Enrutamiento](../routing/) y [Acciones](../actions/): las dos partes que usa toda aplicación.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JanG7L1cZ61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/introduction/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Introduction","summary":"Ce qu'est le framework Total.js v5, ce que contient le paquet total5 et les principaux concepts d'une application Total.js.","markdown":"---\ntitle: Introduction\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/introduction/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# Introduction\n\n> Ce qu'est le framework Total.js v5, ce que contient le paquet total5 et les principaux concepts d'une application Total.js.\n\nLe framework Total.js v5 est un framework pour la plateforme Node.js, écrit en JavaScript pur. Le README du paquet le compare à Laravel de PHP, à Django de Python et à ASP.NET MVC, et indique qu'il peut être utilisé pour une application web, de bureau, de service ou IoT.\n\nIl est publié sur npm sous le nom `total5`, sous licence MIT, par Peter Širka. Le code source se trouve dans le dépôt `totaljs/framework5` sur GitHub.\n\n```bash\n$ npm install total5@beta\n```\n\n## Un seul paquet, aucune dépendance\n\nLe paquet `total5` ne déclare aucune dépendance npm. Tout ce dont le framework a besoin se trouve dans le paquet : le serveur HTTP, le routeur, le moteur de vues, les couches de base de données, le mailer, le traitement d'images, les workers et le moteur Flow. Tu le charges une fois avec `require('total5')` et le framework enregistre son API sous forme de globales (`ROUTE()`, `NEWACTION()`, `NOSQL()`, `CONF`, `F` et bien d'autres) : les fichiers de l'application peuvent donc les utiliser sans aucun `require()`.\n\n```js\nrequire('total5');\n\nROUTE('GET /', function($) {\n\t$.plain('Hello world');\n});\n\nF.http({ port: 8000 });\n```\n\nLe paquet installe aussi deux outils en ligne de commande, `total5` et `flow5`. Ils sont décrits dans [Ligne de commande](../command-line/).\n\n## Ce que contient le paquet\n\nLe paquet est un ensemble de modules. Chaque module couvre un domaine d'une application typique :\n| Domaine | Modules | API principale |\n|------|---------|----------|\n| Serveur HTTP et routage | `http.js`, `routing.js`, `controller.js` | `ROUTE()`, le contrôleur `$` |\n| Actions et schémas | `builders.js`, `jsonschema.js` | `NEWACTION()`, `ACTION()`, `NEWSCHEMA()` |\n| Vues et templates | `viewengine.js`, `tangular.js`, `templates.js`, `markdown.js` | `$.view()`, `TEMPLATE()` |\n| WebSocket | `websocket.js` | `ROUTE('SOCKET ...')`, `WEBSOCKETCLIENT()` |\n| Base de données NoSQL embarquée | `nosql.js`, `nosql-*.js` | `NOSQL()` |\n| Query builder pour les bases de données SQL | `querybuilder.js` | `DATA`, `DB()`, `NEWDB()` |\n| Stockage de fichiers | `filestorage.js` | `FILESTORAGE()` |\n| Requêtes HTTP sortantes | `utils.js`, `builders.js` | `REQUEST()`, `RESTBuilder`, `AJAX()` |\n| E-mail | `mail.js` | `MAIL()`, `HTMLMAIL()`, `Mail` |\n| Planification | `cron.js` | `CRON()` |\n| Images | `images.js` | `Image` |\n| Plugins et composants | `index.js`, `components.js` | répertoire `plugins/`, `NEWCOMPONENT()` |\n| Moteur Flow | `flow.js`, `flowstream.js`, `flow-flowstream.js` | FlowStream, `flow5` |\n| Total.js Message Service | `tms.js` | `NEWPUBLISH()`, `NEWSUBSCRIBE()`, `PUBLISH()`, `SUBSCRIBE()` |\n| Services d'API | `api.js` | `API()`, `NEWAPI()` |\n| Workers et threads | `workers.js`, `cluster.js` | `NEWTHREAD()`, `NEWTHREADPOOL()` |\n| Scripts Python | `pypeline.js` | `PYPELINE()` |\n| Utilitaires | `utils.js`, `htmlparser.js`, `minificators.js`, `macros.js` | `U`, `NEWMACRO()` |\n| Modèles d'IA | `aimodel.js` | `NEWAIMODEL()`, `AIMODEL()`, `AIPARSER()` |\n| Proxy | `proxy.js` | `PROXYSERVER()`, `PROXYCLIENT()` |\n| Autres modules | `ldap.js`, `cms.js`, `uibuilder.js`, `openclient.js`, `bundles.js`, `edit.js` | `LDAP()`, `OPENCLIENT()`, bundles, édition à distance |\n| Démarrage et watcher | `debug.js`, `release.js` | `Total.run()` (`F.run()`) |\n\n## Concepts principaux\n\n### Répertoire de l'application\n\nUne application Total.js est un répertoire contenant un script de démarrage et un ensemble de sous-répertoires connus (`controllers`, `actions`, `schemas`, `plugins`, `public`, `views` et d'autres). Le framework les charge automatiquement au démarrage. Voir [Installation et première application](../installation/) et [Structure de l'application](../application-structure/).\n\n### Les routes et le contrôleur\n\nUne route associe une méthode HTTP et une URL à un handler. Le handler reçoit le contrôleur `$`, qui contient la requête et possède les méthodes pour la réponse (`$.plain()`, `$.json()`, `$.html()`, `$.view()`, `$.file()` et d'autres).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', function($) {\n\t\t$.plain('Hello world');\n\t});\n};\n```\n\nVoir [Routage](../routing/) et [Contrôleur](../controller/). Les fichiers statiques, le middleware et l'autorisation sont décrits dans [Middleware](../middleware/), [Fichiers statiques](../static-files/) et [Autorisation](../authorization/).\n\n### Actions\n\nLes actions constituent la logique métier de l'application. Une action a un nom, un schéma d'entrée facultatif et un handler. Les routes peuvent appeler directement des actions avec l'opérateur `-->` : la même logique est donc accessible depuis HTTP, depuis d'autres actions et depuis le code.\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nROUTE('GET /api/hello/ --> hello');\n```\n\nVoir [Actions](../actions/) et [Schémas JSON](../json-schemas/).\n\n### Vues\n\nLe moteur de vues effectue le rendu des templates HTML du répertoire `views` avec des modèles, des layouts et des helpers. Voir [Vues](../views/) et [Localisation](../localization/).\n\n### Configuration\n\nLe fichier `config` à la racine de l'application contient des paramètres clé/valeur, lus dans l'objet global `CONF`. Voir [Configuration](../configuration/).\n\n### Données\n\nLe framework inclut une base de données NoSQL embarquée stockée dans le répertoire `databases` (`NOSQL()`), un query builder pour les bases de données SQL (`DATA`, `DB()`, `NEWDB()`) et un stockage de fichiers (`FILESTORAGE()`). Voir [NoSQL](../nosql/), [QueryBuilder](../querybuilder/) et [Stockage de fichiers](../file-storage/).\n\n### Plugins et composants\n\nUn plugin est une partie autonome d'une application dans `plugins/<name>/`, avec ses propres contrôleurs, actions, schémas et définitions. Les composants (`NEWCOMPONENT()`) compilent des composants HTML réutilisables. Voir [Plugins et composants](../plugins-and-components/).\n\n### FlowStream\n\nFlowStream est le moteur de programmation visuelle de Total.js : les données circulent entre des composants connectés dans un schéma de flux. Le binaire `flow5` exécute directement les schémas de flux. Voir [FlowStream](../flowstream/).\n\n### TMS et API\n\nLe Total.js Message Service (TMS) publie des messages et s'y abonne entre applications Total.js via WebSocket, et `API()` appelle des services d'API distants. Voir [Message Service (TMS)](../message-service-and-apis/) et [API](../apis/).\n\n### Modèles d'IA\n\nLe module `aimodel.js` enregistre des handlers de modèles d'IA avec `NEWAIMODEL()` et construit des requêtes pour eux avec `AIMODEL()` : messages système et utilisateur, outils, streaming et callbacks. `AIPARSER()` analyse les réponses d'IA. Voir [Modèles d'IA](../ai-models/).\n\n### Tout le reste\n\nWebSocket, les requêtes HTTP sortantes, l'e-mail, la planification et les événements, les workers et les threads, les images et les utilitaires ont chacun leur propre guide : [WebSockets](../websockets/), [Requêtes HTTP](../http-requests/), [E-mail](../mail/), [Planification et événements](../scheduling-and-events/), [Workers et threads](../workers-and-threads/), [Images](../images/), [Utilitaires](../utilities/), [Prototypes](../prototypes/), [Proxy](../proxy/), [LDAP](../ldap/), [Markdown](../markdown/), [Parseur HTML et XML](../html-parser/), [Macros](../macros/), [Tangular](../tangular/), [Minification](../minification/) et [Compilateur CMS](../cms/).\n\n## Pour aller plus loin\n\n1. [Installation et première application](../installation/) : installe le paquet, écris le script de démarrage et la première route.\n2. [Structure de l'application](../application-structure/) : la liste complète des répertoires et des fichiers.\n3. [Routage](../routing/) et [Actions](../actions/) : les deux parties que toute application utilise.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JanG7L1cZ61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/introduction/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Introduzione","summary":"Cos'è il framework Total.js v5, cosa include il pacchetto total5 e i concetti principali di un'applicazione Total.js.","markdown":"---\ntitle: Introduzione\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/introduction/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# Introduzione\n\n> Cos'è il framework Total.js v5, cosa include il pacchetto total5 e i concetti principali di un'applicazione Total.js.\n\nIl framework Total.js v5 è un framework per la piattaforma Node.js, scritto in puro JavaScript. Il README del pacchetto lo paragona a Laravel per PHP, a Django per Python e ad ASP.NET MVC, e afferma che può essere usato per un'applicazione web, desktop, di servizio o IoT.\n\nÈ pubblicato su npm come `total5`, con licenza MIT, da Peter Širka. Il codice sorgente si trova nel repository `totaljs/framework5` su GitHub.\n\n```bash\n$ npm install total5@beta\n```\n\n## Un solo pacchetto, nessuna dipendenza\n\nIl pacchetto `total5` non dichiara alcuna dipendenza npm. Tutto ciò di cui il framework ha bisogno è dentro il pacchetto: il server HTTP, il router, il motore delle viste, i livelli di database, il mailer, l'elaborazione delle immagini, i worker e il motore Flow. Lo carichi una volta con `require('total5')` e il framework registra la sua API come globali (`ROUTE()`, `NEWACTION()`, `NOSQL()`, `CONF`, `F` e molti altri), così i file dell'applicazione possono usarli senza alcun `require()`.\n\n```js\nrequire('total5');\n\nROUTE('GET /', function($) {\n\t$.plain('Hello world');\n});\n\nF.http({ port: 8000 });\n```\n\nIl pacchetto installa anche due strumenti da riga di comando, `total5` e `flow5`. Sono descritti in [Riga di comando](../command-line/).\n\n## Cosa include il pacchetto\n\nIl pacchetto è un insieme di moduli. Ogni modulo copre un'area di un'applicazione tipica:\n| Area | Moduli | API principale |\n|------|---------|----------|\n| Server HTTP e routing | `http.js`, `routing.js`, `controller.js` | `ROUTE()`, il controller `$` |\n| Azioni e schemi | `builders.js`, `jsonschema.js` | `NEWACTION()`, `ACTION()`, `NEWSCHEMA()` |\n| Viste e template | `viewengine.js`, `tangular.js`, `templates.js`, `markdown.js` | `$.view()`, `TEMPLATE()` |\n| WebSocket | `websocket.js` | `ROUTE('SOCKET ...')`, `WEBSOCKETCLIENT()` |\n| Database NoSQL integrato | `nosql.js`, `nosql-*.js` | `NOSQL()` |\n| Query builder per database SQL | `querybuilder.js` | `DATA`, `DB()`, `NEWDB()` |\n| Archiviazione file | `filestorage.js` | `FILESTORAGE()` |\n| Richieste HTTP in uscita | `utils.js`, `builders.js` | `REQUEST()`, `RESTBuilder`, `AJAX()` |\n| Posta | `mail.js` | `MAIL()`, `HTMLMAIL()`, `Mail` |\n| Pianificazione | `cron.js` | `CRON()` |\n| Immagini | `images.js` | `Image` |\n| Plugin e componenti | `index.js`, `components.js` | directory `plugins/`, `NEWCOMPONENT()` |\n| Motore Flow | `flow.js`, `flowstream.js`, `flow-flowstream.js` | FlowStream, `flow5` |\n| Total.js Message Service | `tms.js` | `NEWPUBLISH()`, `NEWSUBSCRIBE()`, `PUBLISH()`, `SUBSCRIBE()` |\n| Servizi API | `api.js` | `API()`, `NEWAPI()` |\n| Worker e thread | `workers.js`, `cluster.js` | `NEWTHREAD()`, `NEWTHREADPOOL()` |\n| Script Python | `pypeline.js` | `PYPELINE()` |\n| Utility | `utils.js`, `htmlparser.js`, `minificators.js`, `macros.js` | `U`, `NEWMACRO()` |\n| Modelli AI | `aimodel.js` | `NEWAIMODEL()`, `AIMODEL()`, `AIPARSER()` |\n| Proxy | `proxy.js` | `PROXYSERVER()`, `PROXYCLIENT()` |\n| Altri moduli | `ldap.js`, `cms.js`, `uibuilder.js`, `openclient.js`, `bundles.js`, `edit.js` | `LDAP()`, `OPENCLIENT()`, bundle, modifica remota |\n| Avvio e watcher | `debug.js`, `release.js` | `Total.run()` (`F.run()`) |\n\n## Concetti principali\n\n### Directory dell'applicazione\n\nUn'applicazione Total.js è una directory con uno script di avvio e un insieme di sottodirectory note (`controllers`, `actions`, `schemas`, `plugins`, `public`, `views` e altre). Il framework le carica automaticamente all'avvio. Vedi [Installazione e prima app](../installation/) e [Struttura dell'applicazione](../application-structure/).\n\n### Route e controller\n\nUna route associa un metodo HTTP e un URL a un handler. L'handler riceve il controller `$`, che contiene la richiesta e ha i metodi per la risposta (`$.plain()`, `$.json()`, `$.html()`, `$.view()`, `$.file()` e altri).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', function($) {\n\t\t$.plain('Hello world');\n\t});\n};\n```\n\nVedi [Routing](../routing/) e [Controller](../controller/). File statici, middleware e autorizzazione sono in [Middleware](../middleware/), [File statici](../static-files/) e [Autorizzazione](../authorization/).\n\n### Azioni\n\nLe azioni sono la logica di business dell'applicazione. Un'azione ha un nome, uno schema di input facoltativo e un handler. Le route possono chiamare le azioni direttamente con l'operatore `-->`, così la stessa logica è raggiungibile da HTTP, da altre azioni e dal codice.\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nROUTE('GET /api/hello/ --> hello');\n```\n\nVedi [Azioni](../actions/) e [Schemi JSON](../json-schemas/).\n\n### Viste\n\nIl motore delle viste renderizza template HTML dalla directory `views` con modelli, layout e helper. Vedi [Viste](../views/) e [Localizzazione](../localization/).\n\n### Configurazione\n\nIl file `config` nella radice dell'applicazione contiene impostazioni chiave/valore, lette nell'oggetto globale `CONF`. Vedi [Configurazione](../configuration/).\n\n### Dati\n\nIl framework include un database NoSQL integrato salvato nella directory `databases` (`NOSQL()`), un query builder per database SQL (`DATA`, `DB()`, `NEWDB()`) e un'archiviazione file (`FILESTORAGE()`). Vedi [NoSQL](../nosql/), [QueryBuilder](../querybuilder/) e [Archiviazione file](../file-storage/).\n\n### Plugin e componenti\n\nUn plugin è una parte autonoma di un'applicazione in `plugins/<name>/`, con i propri controller, azioni, schemi e definizioni. I componenti (`NEWCOMPONENT()`) compilano componenti HTML riutilizzabili. Vedi [Plugin e componenti](../plugins-and-components/).\n\n### FlowStream\n\nFlowStream è il motore di programmazione visuale di Total.js: i dati scorrono tra componenti collegati in uno schema di flusso. Il binario `flow5` esegue direttamente gli schemi di flusso. Vedi [FlowStream](../flowstream/).\n\n### TMS e API\n\nIl Total.js Message Service (TMS) pubblica e sottoscrive messaggi tra applicazioni Total.js tramite WebSocket, e `API()` chiama servizi API remoti. Vedi [Message Service (TMS)](../message-service-and-apis/) e [API](../apis/).\n\n### Modelli AI\n\nIl modulo `aimodel.js` registra handler di modelli AI con `NEWAIMODEL()` e costruisce richieste per essi con `AIMODEL()`: messaggi di sistema e dell'utente, tool, streaming e callback. `AIPARSER()` interpreta le risposte AI. Vedi [Modelli AI](../ai-models/).\n\n### Tutto il resto\n\nWebSocket, richieste HTTP in uscita, posta, pianificazione ed eventi, worker e thread, immagini e utility hanno ciascuno la propria guida: [WebSocket](../websockets/), [Richieste HTTP](../http-requests/), [Posta](../mail/), [Pianificazione ed eventi](../scheduling-and-events/), [Worker e thread](../workers-and-threads/), [Immagini](../images/), [Utility](../utilities/), [Prototipi](../prototypes/), [Proxy](../proxy/), [LDAP](../ldap/), [Markdown](../markdown/), [Parser HTML e XML](../html-parser/), [Macro](../macros/), [Tangular](../tangular/), [Minificazione](../minification/) e [Compilatore CMS](../cms/).\n\n## Dove andare dopo\n\n1. [Installazione e prima app](../installation/): installa il pacchetto, scrivi lo script di avvio e la prima route.\n2. [Struttura dell'applicazione](../application-structure/): l'elenco completo di directory e file.\n3. [Routing](../routing/) e [Azioni](../actions/): le due parti che ogni applicazione usa.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JanG7L1cZ61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/introduction/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Úvod","summary":"Čo je Total.js framework v5, čo obsahuje balík total5 a hlavné koncepty Total.js aplikácie.","markdown":"---\ntitle: \"Úvod\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/introduction/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# Úvod\n\n> Čo je Total.js framework v5, čo obsahuje balík total5 a hlavné koncepty Total.js aplikácie.\n\nTotal.js framework v5 je framework pre platformu Node.js napísaný v čistom JavaScripte. README balíka ho porovnáva s Laravelom pre PHP, Djangom pre Python a ASP.NET MVC a uvádza, že sa dá použiť pre webovú, desktopovú, servisnú alebo IoT aplikáciu.\n\nJe publikovaný na npm ako `total5` pod licenciou MIT, autorom je Peter Širka. Zdrojový kód je v repozitári `totaljs/framework5` na GitHube.\n\n```bash\n$ npm install total5@beta\n```\n\n## Jeden balík, žiadne závislosti\n\nBalík `total5` nedeklaruje žiadnu npm závislosť. Všetko, čo framework potrebuje, je v balíku: HTTP server, router, engine pohľadov, databázové vrstvy, mailer, spracovanie obrázkov, workery a engine Flow. Načítaš ho raz cez `require('total5')` a framework zaregistruje svoje API ako globálne (`ROUTE()`, `NEWACTION()`, `NOSQL()`, `CONF`, `F` a mnoho ďalších), takže súbory aplikácie ich môžu používať bez akéhokoľvek `require()`.\n\n```js\nrequire('total5');\n\nROUTE('GET /', function($) {\n\t$.plain('Hello world');\n});\n\nF.http({ port: 8000 });\n```\n\nBalík tiež inštaluje dva nástroje príkazového riadka, `total5` a `flow5`. Sú opísané v [Príkazový riadok](../command-line/).\n\n## Čo balík obsahuje\n\nBalík je sada modulov. Každý modul pokrýva jednu oblasť typickej aplikácie:\n| Oblasť | Moduly | Hlavné API |\n|------|---------|----------|\n| HTTP server a smerovanie | `http.js`, `routing.js`, `controller.js` | `ROUTE()`, kontrolér `$` |\n| Akcie a schémy | `builders.js`, `jsonschema.js` | `NEWACTION()`, `ACTION()`, `NEWSCHEMA()` |\n| Pohľady a šablóny | `viewengine.js`, `tangular.js`, `templates.js`, `markdown.js` | `$.view()`, `TEMPLATE()` |\n| WebSocket | `websocket.js` | `ROUTE('SOCKET ...')`, `WEBSOCKETCLIENT()` |\n| Vstavaná NoSQL databáza | `nosql.js`, `nosql-*.js` | `NOSQL()` |\n| Query builder pre SQL databázy | `querybuilder.js` | `DATA`, `DB()`, `NEWDB()` |\n| File storage | `filestorage.js` | `FILESTORAGE()` |\n| Odchádzajúce HTTP požiadavky | `utils.js`, `builders.js` | `REQUEST()`, `RESTBuilder`, `AJAX()` |\n| Pošta | `mail.js` | `MAIL()`, `HTMLMAIL()`, `Mail` |\n| Plánovanie | `cron.js` | `CRON()` |\n| Obrázky | `images.js` | `Image` |\n| Pluginy a komponenty | `index.js`, `components.js` | adresár `plugins/`, `NEWCOMPONENT()` |\n| Engine Flow | `flow.js`, `flowstream.js`, `flow-flowstream.js` | FlowStream, `flow5` |\n| Total.js Message Service | `tms.js` | `NEWPUBLISH()`, `NEWSUBSCRIBE()`, `PUBLISH()`, `SUBSCRIBE()` |\n| API služby | `api.js` | `API()`, `NEWAPI()` |\n| Workery a vlákna | `workers.js`, `cluster.js` | `NEWTHREAD()`, `NEWTHREADPOOL()` |\n| Python skripty | `pypeline.js` | `PYPELINE()` |\n| Utility | `utils.js`, `htmlparser.js`, `minificators.js`, `macros.js` | `U`, `NEWMACRO()` |\n| AI modely | `aimodel.js` | `NEWAIMODEL()`, `AIMODEL()`, `AIPARSER()` |\n| Proxy | `proxy.js` | `PROXYSERVER()`, `PROXYCLIENT()` |\n| Ďalšie moduly | `ldap.js`, `cms.js`, `uibuilder.js`, `openclient.js`, `bundles.js`, `edit.js` | `LDAP()`, `OPENCLIENT()`, bundly, vzdialené úpravy |\n| Štart a watcher | `debug.js`, `release.js` | `Total.run()` (`F.run()`) |\n\n## Hlavné koncepty\n\n### Adresár aplikácie\n\nTotal.js aplikácia je adresár so štartovacím skriptom a sadou známych podadresárov (`controllers`, `actions`, `schemas`, `plugins`, `public`, `views` a ďalšie). Framework ich pri štarte automaticky načíta. Pozri [Inštalácia a prvá aplikácia](../installation/) a [Štruktúra aplikácie](../application-structure/).\n\n### Trasy a kontrolér\n\nTrasa priraďuje HTTP metódu a URL k handleru. Handler dostane kontrolér `$`, ktorý obsahuje požiadavku a má metódy pre odpoveď (`$.plain()`, `$.json()`, `$.html()`, `$.view()`, `$.file()` a ďalšie).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', function($) {\n\t\t$.plain('Hello world');\n\t});\n};\n```\n\nPozri [Smerovanie](../routing/) a [Kontrolér](../controller/). Statické súbory, middleware a autorizácia sú v [Middleware](../middleware/), [Statické súbory](../static-files/) a [Autorizácia](../authorization/).\n\n### Akcie\n\nAkcie sú biznis logika aplikácie. Akcia má názov, voliteľnú vstupnú schému a handler. Trasy môžu volať akcie priamo operátorom `-->`, takže tá istá logika je dostupná z HTTP, z iných akcií aj z kódu.\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nROUTE('GET /api/hello/ --> hello');\n```\n\nPozri [Akcie](../actions/) a [JSON schémy](../json-schemas/).\n\n### Pohľady\n\nEngine pohľadov vykresľuje HTML šablóny z adresára `views` s modelmi, layoutmi a pomocnými funkciami. Pozri [Pohľady](../views/) a [Lokalizácia](../localization/).\n\n### Konfigurácia\n\nSúbor `config` v koreni aplikácie obsahuje nastavenia kľúč/hodnota, načítané do globálneho objektu `CONF`. Pozri [Konfigurácia](../configuration/).\n\n### Dáta\n\nFramework obsahuje vstavanú NoSQL databázu uloženú v adresári `databases` (`NOSQL()`), query builder pre SQL databázy (`DATA`, `DB()`, `NEWDB()`) a file storage (`FILESTORAGE()`). Pozri [NoSQL](../nosql/), [QueryBuilder](../querybuilder/) a [File storage](../file-storage/).\n\n### Pluginy a komponenty\n\nPlugin je samostatná časť aplikácie v `plugins/<name>/` s vlastnými kontrolérmi, akciami, schémami a definíciami. Komponenty (`NEWCOMPONENT()`) kompilujú opakovane použiteľné HTML komponenty. Pozri [Pluginy a komponenty](../plugins-and-components/).\n\n### FlowStream\n\nFlowStream je engine vizuálneho programovania v Total.js: dáta tečú medzi prepojenými komponentmi v schéme toku. Binárka `flow5` spúšťa schémy tokov priamo. Pozri [FlowStream](../flowstream/).\n\n### TMS a API\n\nTotal.js Message Service (TMS) publikuje a odoberá správy medzi Total.js aplikáciami cez WebSocket a `API()` volá vzdialené API služby. Pozri [Message Service (TMS)](../message-service-and-apis/) a [API](../apis/).\n\n### AI modely\n\nModul `aimodel.js` registruje handlery AI modelov cez `NEWAIMODEL()` a zostavuje pre ne požiadavky cez `AIMODEL()`: systémové a používateľské správy, nástroje, streamovanie a callbacky. `AIPARSER()` spracúva AI odpovede. Pozri [AI modely](../ai-models/).\n\n### Všetko ostatné\n\nWebSocket, odchádzajúce HTTP požiadavky, pošta, plánovanie a udalosti, workery a vlákna, obrázky a utility majú každé vlastnú príručku: [WebSockety](../websockets/), [HTTP požiadavky](../http-requests/), [Pošta](../mail/), [Plánovanie a udalosti](../scheduling-and-events/), [Workery a vlákna](../workers-and-threads/), [Obrázky](../images/), [Utility](../utilities/), [Prototypy](../prototypes/), [Proxy](../proxy/), [LDAP](../ldap/), [Markdown](../markdown/), [HTML a XML parser](../html-parser/), [Makrá](../macros/), [Tangular](../tangular/), [Minifikácia](../minification/) a [CMS kompilátor](../cms/).\n\n## Kam ďalej\n\n1. [Inštalácia a prvá aplikácia](../installation/): nainštaluj balík, napíš štartovací skript a prvú trasu.\n2. [Štruktúra aplikácie](../application-structure/): úplný zoznam adresárov a súborov.\n3. [Smerovanie](../routing/) a [Akcie](../actions/): dve časti, ktoré používa každá aplikácia.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JanG7m1pZ60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/installation/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Installation and first app","summary":"Install the total5 package, write the start script, add a first route and action, and run the app in debug and release mode.","markdown":"---\ntitle: Installation and first app\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/installation/\nupdated: 2026-11-18T16:59:54.646Z\n---\n\n# Installation and first app\n\n> Install the total5 package, write the start script, add a first route and action, and run the app in debug and release mode.\n\nThis guide installs the `total5` package, writes the start script, adds a first route and a first action, and runs the application in debug and in release mode.\n\n## Requirements\n\nTotal.js 5 runs on [Node.js](https://nodejs.org/). Install the current LTS version, which also installs `npm`. Then open a terminal and check that both commands answer with a version number:\n\n```bash\n$ node --version\n$ npm --version\n```\n\n## Install the package\n\nCreate a directory for the application and install the package from npm:\n\n```bash\n$ mkdir myapp\n$ cd myapp\n$ npm init -y\n$ npm install total5@beta\n```\n\nThe package has no dependencies of its own, so this installs only the framework. It also installs the `total5` and `flow5` command-line tools (see [Command line](../command-line/)).\n\n## The start script\n\nCreate `index.js` in the application root. This is the official start script of Total.js 5:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket');\n// options.unixsocket777 = true;\n// options.config = { name: 'Total.js' };\n// options.inspector = 9229;\n// options.watch = ['private'];\n// options.livereload = 'https://yourhostname';\n// options.watcher = false; // disables watcher\n// options.edit = 'wss://www.yourcodeinstance.com/?id=projectname'\n\noptions.release = process.argv.includes('--release');\n\n// Service mode:\noptions.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode');\n// options.servicemode = 'definitions,modules,config';\n\n// Cluster:\n// options.tz = 'utc';\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nStart it with `node index.js` in debug mode, with `node index.js --release` in release mode, or with `node index.js --service` to load the application without the HTTP server.\n\n`Total.run()` (the same function as `F.run()`) starts the debug watcher: the application runs in a child process that restarts when a file changes. `options.release` only switches `DEBUG` to `false`, so with `--release` the watcher still restarts the application on changes. With `options.watcher = false` the application runs in release mode in the current process, without the watcher.\n\nThe commented lines are the other start options:\n\n| Option | Description |\n|--------|-------------|\n| `ip` | IP address to listen on. Default `0.0.0.0` (`CONF.$ip`). |\n| `port` | Port number. When it is not set, the port comes from the `$port` configuration key. When that is `auto` (the default), the port comes from the `PORT` environment variable, then from the first command-line argument of 3 to 5 digits, and falls back to `8000`. |\n| `unixsocket` | Listen on a Unix socket instead of an IP and port. |\n| `unixsocket777` | Gives the Unix socket the permissions 777. |\n| `config` | An object with configuration keys applied before the app loads, for example `{ name: 'My app' }`. |\n| `inspector` | With the watcher: starts the app with the Node.js inspector on this port (`--inspect=9229`). |\n| `watch` | With the watcher: an array of extra directories the watcher observes. |\n| `livereload` | With the watcher: `true` starts a live reload WebSocket server on port `35729` and also watches `public` and `views`, a number sets the port, and a hostname sends the changed files to the Total.js live reload service. |\n| `watcher` | `false` runs the application in release mode in the current process, without the watcher. |\n| `edit` | Connects the application to the Total.js Code Editor. |\n| `release` | `true` runs the application with `DEBUG = false`. |\n| `servicemode` | `true` loads the application without the HTTP server. A comma-separated string (for example `'config,modules,definitions'`) loads only those parts. |\n| `cluster` | A number of processes, or `'auto'` (see [Workers and threads](../workers-and-threads/)). |\n| `limit` | With `cluster: 'auto'`: the maximum number of processes. |\n| `tz` | With `cluster`: the time zone of the processes (`process.env.TZ`), `'utc'` by default. |\n\nEvery option is described in the [reference](../../reference/application-structure/).\n\nThe framework switches the working directory to the directory of the start script. With the watcher the application runs in a child process, so the application root is the directory that contains `index.js` even when you start it from another place (`node /www/myapp/index.js`). With `options.watcher = false` the application root is the directory you start the script from, so start it from the application directory.\n\n## Folder structure\n\nThe framework loads these files and directories from the application root when it starts. All of them are optional: create only the ones you use.\n\n```text\nmyapp/\n├── index.js          start script\n├── config            configuration (key : value per line)\n├── .env              environment variables\n├── version           application version (first line)\n├── controllers/      routes: *.js files with exports.install\n├── actions/          NEWACTION() definitions\n├── schemas/          NEWSCHEMA() definitions\n├── models/           business logic\n├── definitions/      startup code: delegates, helpers, globals\n├── modules/          modules with exports.install\n├── extensions/       extensions of the framework\n├── middleware/       NEWMIDDLEWARE() definitions\n├── plugins/          plugins: plugins/<name>/index.js\n├── jsonschemas/      JSON schemas (*.json or *.txt)\n├── resources/        localization (*.resource)\n├── views/            HTML views\n├── public/           static files (CSS, JS, images)\n├── flowstreams/      FlowStream schemas\n├── databases/        NoSQL databases and file storages\n├── logs/             log files\n└── tmp/              temporary files\n```\n\nEvery `.js` file in `controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `extensions` and `middleware` is required, and when it exports an `install()` function the framework calls it. Subdirectories are read too. A file or directory whose name contains `-bk` or `_bk` is skipped. The full description of each directory is in [Application structure](../application-structure/).\n\n## First route\n\nCreate `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/hello/ --> hello');\n\tROUTE('POST /api/greet/ --> greet');\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n```\n\n`ROUTE('GET /', index)` sends a plain text response from a function. The other two routes have no function: the `-->` operator runs the named action and sends its result as JSON. Routing is explained in [Routing](../routing/) and the `$` object in [Controller](../controller/).\n\n## First action\n\nCreate `actions/hello.js`:\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nNEWACTION('greet', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.callback({ message: 'Hello ' + model.name });\n\t}\n});\n```\n\nThe `hello` action answers with `$.success()`, which sends `{\"success\":true,\"value\":\"Hello from an action\"}`. The `greet` action declares an inline input schema: `*name:String` means a required string field. The framework validates the request body before the action runs, and `model` is the validated data. A request without `name` gets an error response:\n\n```bash\n$ curl -X POST -H 'Content-Type: application/json' -d '{\"name\":\"Peter\"}' http://127.0.0.1:8000/api/greet/\n{\"message\":\"Hello Peter\"}\n\n$ curl -X POST -H 'Content-Type: application/json' -d '{}' http://127.0.0.1:8000/api/greet/\n[{\"name\":\"name\",\"error\":\"The field \\\"name\\\" is invalid\",\"path\":\"name\"}]\n```\n\nActions and inline schemas are covered in [Actions](../actions/) and [JSON schemas](../json-schemas/).\n\n## Configuration\n\nCreate a `config` file with one `key : value` pair per line:\n\n```text\nname          : My first app\n```\n\nThe value is available as `CONF.name` and is printed when the app starts. See [Configuration](../configuration/).\n\n## Run in debug mode\n\n```bash\n$ node index.js\n```\n\nThe debug module starts a watcher process (`Total.js watcher PID: ...`), which starts the application in a child process and prints the start information:\n\n```text\n====================================================\nPID           : 75692\n...\nName          : My first app\nVersion       : 1.0.0\nMode          : debug\nCompiled      : 2 files (4ms)\n====================================================\n\nhttp://0.0.0.0:8000/\n```\n\nOpen `http://127.0.0.1:8000/` in the browser: the page shows `Hello world`. Press `Ctrl+C` in the terminal to stop the application.\n\nIn debug mode:\n\n- `DEBUG` is `true`.\n- The watcher checks the application directories (`controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `plugins` and the others) and the `config` and `version` files in the root. When a file changes, it prints a line such as `--- UPD --- [ ... ] --------> /actions/hello.js` and restarts the application.\n- The watcher writes an `index.pid` file with its process ID. Deleting the file stops the watcher and the application.\n- The framework writes `index.js.map`, a JSON list of the registered routes and actions.\n\nPass a port as an argument when the start script does not set one:\n\n```bash\n$ node index.js 8001\n```\n\n## Run in release mode\n\n```bash\n$ node index.js --release\n```\n\nWith the start script above, `--release` switches `DEBUG` to `false`, but the watcher keeps running and restarts the application when a file changes.\n\nFor production, uncomment the line `options.watcher = false` in the start script and start the application with `node index.js`. The application then runs in release mode in the current process, without the watcher, and changes to source files have no effect until you start it again.\n\n## Next steps\n\n- [Your first form](../first-form/): show a form, receive its data and answer with a new page.\n- [Application structure](../application-structure/) describes every directory.\n- [Routing](../routing/), [Controller](../controller/) and [Actions](../actions/) cover the request flow.\n- [Views](../views/) renders HTML pages from the `views` directory.\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:54.646Z"}
{"id":"JanG7m1pZ60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/installation/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Installation und erste App","summary":"Das Paket total5 installieren, das Startskript schreiben, eine erste Route und Aktion hinzufügen und die App im Debug- und Release-Modus ausführen.","markdown":"---\ntitle: Installation und erste App\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/installation/\nupdated: 2026-11-18T16:59:54.646Z\n---\n\n# Installation und erste App\n\n> Das Paket total5 installieren, das Startskript schreiben, eine erste Route und Aktion hinzufügen und die App im Debug- und Release-Modus ausführen.\n\nDiese Anleitung installiert das Paket `total5`, schreibt das Startskript, fügt eine erste Route und eine erste Aktion hinzu und führt die Anwendung im Debug- und im Release-Modus aus.\n\n## Voraussetzungen\n\nTotal.js 5 läuft auf [Node.js](https://nodejs.org/). Installiere die aktuelle LTS-Version, die auch `npm` mitbringt. Öffne dann ein Terminal und prüfe, ob beide Befehle mit einer Versionsnummer antworten:\n\n```bash\n$ node --version\n$ npm --version\n```\n\n## Das Paket installieren\n\nErstelle ein Verzeichnis für die Anwendung und installiere das Paket von npm:\n\n```bash\n$ mkdir myapp\n$ cd myapp\n$ npm init -y\n$ npm install total5@beta\n```\n\nDas Paket hat keine eigenen Abhängigkeiten, daher wird nur das Framework installiert. Es installiert außerdem die Kommandozeilen-Tools `total5` und `flow5` (siehe [Kommandozeile](../command-line/)).\n\n## Das Startskript\n\nErstelle `index.js` im Stammverzeichnis der Anwendung. Das ist das offizielle Startskript von Total.js 5:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket');\n// options.unixsocket777 = true;\n// options.config = { name: 'Total.js' };\n// options.inspector = 9229;\n// options.watch = ['private'];\n// options.livereload = 'https://yourhostname';\n// options.watcher = false; // disables watcher\n// options.edit = 'wss://www.yourcodeinstance.com/?id=projectname'\n\noptions.release = process.argv.includes('--release');\n\n// Service mode:\noptions.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode');\n// options.servicemode = 'definitions,modules,config';\n\n// Cluster:\n// options.tz = 'utc';\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nStarte es mit `node index.js` im Debug-Modus, mit `node index.js --release` im Release-Modus oder mit `node index.js --service`, um die Anwendung ohne den HTTP-Server zu laden.\n\n`Total.run()` (dieselbe Funktion wie `F.run()`) startet den Debug-Watcher: Die Anwendung läuft in einem Kindprozess, der neu startet, wenn sich eine Datei ändert. `options.release` setzt nur `DEBUG` auf `false`, mit `--release` startet der Watcher die Anwendung bei Änderungen also weiterhin neu. Mit `options.watcher = false` läuft die Anwendung im Release-Modus im aktuellen Prozess, ohne den Watcher.\n\nDie auskommentierten Zeilen sind die übrigen Startoptionen:\n\n| Option | Beschreibung |\n|--------|-------------|\n| `ip` | IP-Adresse, auf der gelauscht wird. Standard `0.0.0.0` (`CONF.$ip`). |\n| `port` | Portnummer. Ist sie nicht gesetzt, stammt der Port aus dem Konfigurationsschlüssel `$port`. Ist dieser `auto` (der Standard), stammt der Port aus der Umgebungsvariable `PORT`, dann aus dem ersten Kommandozeilenargument mit 3 bis 5 Ziffern, und fällt auf `8000` zurück. |\n| `unixsocket` | Auf einem Unix-Socket statt auf einer IP und einem Port lauschen. |\n| `unixsocket777` | Gibt dem Unix-Socket die Rechte 777. |\n| `config` | Ein Objekt mit Konfigurationsschlüsseln, die vor dem Laden der App angewendet werden, zum Beispiel `{ name: 'My app' }`. |\n| `inspector` | Mit dem Watcher: startet die App mit dem Node.js-Inspector auf diesem Port (`--inspect=9229`). |\n| `watch` | Mit dem Watcher: ein Array zusätzlicher Verzeichnisse, die der Watcher beobachtet. |\n| `livereload` | Mit dem Watcher: `true` startet einen Live-Reload-WebSocket-Server auf Port `35729` und überwacht zusätzlich `public` und `views`, eine Zahl legt den Port fest, und ein Hostname schickt die geänderten Dateien an den Live-Reload-Dienst von Total.js. |\n| `watcher` | `false` führt die Anwendung im Release-Modus im aktuellen Prozess aus, ohne den Watcher. |\n| `edit` | Verbindet die Anwendung mit dem Total.js Code Editor. |\n| `release` | `true` führt die Anwendung mit `DEBUG = false` aus. |\n| `servicemode` | `true` lädt die Anwendung ohne den HTTP-Server. Ein kommagetrennter String (zum Beispiel `'config,modules,definitions'`) lädt nur diese Teile. |\n| `cluster` | Eine Anzahl von Prozessen oder `'auto'` (siehe [Worker, Threads und Cluster](../workers-and-threads/)). |\n| `limit` | Mit `cluster: 'auto'`: die höchste Anzahl von Prozessen. |\n| `tz` | Mit `cluster`: die Zeitzone der Prozesse (`process.env.TZ`), standardmäßig `'utc'`. |\n\nJede Option ist in der [Referenz](../../reference/application-structure/) beschrieben.\n\nDas Framework wechselt das Arbeitsverzeichnis in das Verzeichnis des Startskripts. Mit dem Watcher läuft die Anwendung in einem Kindprozess, daher ist das Stammverzeichnis der Anwendung das Verzeichnis mit `index.js`, auch wenn du sie von einem anderen Ort startest (`node /www/myapp/index.js`). Mit `options.watcher = false` ist das Stammverzeichnis der Anwendung das Verzeichnis, aus dem du das Skript startest, also starte es aus dem Verzeichnis der Anwendung.\n\n## Ordnerstruktur\n\nDas Framework lädt beim Start diese Dateien und Verzeichnisse aus dem Stammverzeichnis der Anwendung. Alle sind optional: Erstelle nur die, die du verwendest.\n\n```text\nmyapp/\n├── index.js          start script\n├── config            configuration (key : value per line)\n├── .env              environment variables\n├── version           application version (first line)\n├── controllers/      routes: *.js files with exports.install\n├── actions/          NEWACTION() definitions\n├── schemas/          NEWSCHEMA() definitions\n├── models/           business logic\n├── definitions/      startup code: delegates, helpers, globals\n├── modules/          modules with exports.install\n├── extensions/       extensions of the framework\n├── middleware/       NEWMIDDLEWARE() definitions\n├── plugins/          plugins: plugins/<name>/index.js\n├── jsonschemas/      JSON schemas (*.json or *.txt)\n├── resources/        localization (*.resource)\n├── views/            HTML views\n├── public/           static files (CSS, JS, images)\n├── flowstreams/      FlowStream schemas\n├── databases/        NoSQL databases and file storages\n├── logs/             log files\n└── tmp/              temporary files\n```\n\nJede `.js`-Datei in `controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `extensions` und `middleware` wird per require geladen, und wenn sie eine `install()`-Funktion exportiert, ruft das Framework sie auf. Unterverzeichnisse werden ebenfalls gelesen. Eine Datei oder ein Verzeichnis, dessen Name `-bk` oder `_bk` enthält, wird übersprungen. Die vollständige Beschreibung jedes Verzeichnisses steht in [Anwendungsstruktur](../application-structure/).\n\n## Erste Route\n\nErstelle `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/hello/ --> hello');\n\tROUTE('POST /api/greet/ --> greet');\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n```\n\n`ROUTE('GET /', index)` sendet eine Klartextantwort aus einer Funktion. Die anderen beiden Routen haben keine Funktion: Der Operator `-->` führt die benannte Aktion aus und sendet ihr Ergebnis als JSON. Das Routing wird in [Routing](../routing/) erklärt und das Objekt `$` in [Controller](../controller/).\n\n## Erste Aktion\n\nErstelle `actions/hello.js`:\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nNEWACTION('greet', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.callback({ message: 'Hello ' + model.name });\n\t}\n});\n```\n\nDie Aktion `hello` antwortet mit `$.success()`, das `{\"success\":true,\"value\":\"Hello from an action\"}` sendet. Die Aktion `greet` deklariert ein Inline-Eingabeschema: `*name:String` bedeutet ein Pflichtfeld vom Typ String. Das Framework validiert den Body der Anfrage, bevor die Aktion läuft, und `model` sind die validierten Daten. Eine Anfrage ohne `name` erhält eine Fehlerantwort:\n\n```bash\n$ curl -X POST -H 'Content-Type: application/json' -d '{\"name\":\"Peter\"}' http://127.0.0.1:8000/api/greet/\n{\"message\":\"Hello Peter\"}\n\n$ curl -X POST -H 'Content-Type: application/json' -d '{}' http://127.0.0.1:8000/api/greet/\n[{\"name\":\"name\",\"error\":\"The field \\\"name\\\" is invalid\",\"path\":\"name\"}]\n```\n\nAktionen und Inline-Schemas werden in [Aktionen](../actions/) und [JSON-Schemas](../json-schemas/) behandelt.\n\n## Konfiguration\n\nErstelle eine Datei `config` mit einem `key : value`-Paar pro Zeile:\n\n```text\nname          : My first app\n```\n\nDer Wert ist als `CONF.name` verfügbar und wird beim Start der App ausgegeben. Siehe [Konfiguration](../configuration/).\n\n## Im Debug-Modus ausführen\n\n```bash\n$ node index.js\n```\n\nDas Debug-Modul startet einen Watcher-Prozess (`Total.js watcher PID: ...`), der die Anwendung in einem Kindprozess startet und die Startinformationen ausgibt:\n\n```text\n====================================================\nPID           : 75692\n...\nName          : My first app\nVersion       : 1.0.0\nMode          : debug\nCompiled      : 2 files (4ms)\n====================================================\n\nhttp://0.0.0.0:8000/\n```\n\nÖffne `http://127.0.0.1:8000/` im Browser: Die Seite zeigt `Hello world`. Drücke `Ctrl+C` im Terminal, um die Anwendung zu beenden.\n\nIm Debug-Modus:\n\n- `DEBUG` ist `true`.\n- Der Watcher prüft die Anwendungsverzeichnisse (`controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `plugins` und die übrigen) sowie die Dateien `config` und `version` im Stammverzeichnis. Wenn sich eine Datei ändert, gibt er eine Zeile wie `--- UPD --- [ ... ] --------> /actions/hello.js` aus und startet die Anwendung neu.\n- Der Watcher schreibt eine Datei `index.pid` mit seiner Prozess-ID. Das Löschen der Datei beendet den Watcher und die Anwendung.\n- Das Framework schreibt `index.js.map`, eine JSON-Liste der registrierten Routen und Aktionen.\n\nÜbergib einen Port als Argument, wenn das Startskript keinen setzt:\n\n```bash\n$ node index.js 8001\n```\n\n## Im Release-Modus ausführen\n\n```bash\n$ node index.js --release\n```\n\nMit dem Startskript oben setzt `--release` `DEBUG` auf `false`, der Watcher läuft aber weiter und startet die Anwendung neu, wenn sich eine Datei ändert.\n\nFür die Produktion entferne im Startskript den Kommentar vor der Zeile `options.watcher = false` und starte die Anwendung mit `node index.js`. Die Anwendung läuft dann im Release-Modus im aktuellen Prozess, ohne den Watcher, und Änderungen an Quelldateien wirken sich erst aus, wenn du sie erneut startest.\n\n## Nächste Schritte\n\n- [Dein erstes Formular](../first-form/): Zeige ein Formular an, empfange seine Daten und antworte mit einer neuen Seite.\n- [Anwendungsstruktur](../application-structure/) beschreibt jedes Verzeichnis.\n- [Routing](../routing/), [Controller](../controller/) und [Aktionen](../actions/) behandeln den Ablauf einer Anfrage.\n- [Views](../views/) rendert HTML-Seiten aus dem Verzeichnis `views`.\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:54.646Z"}
{"id":"JanG7m1pZ60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/installation/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Instalación y primera app","summary":"Instala el paquete total5, escribe el script de arranque, añade una primera ruta y una primera acción, y ejecuta la aplicación en modo debug y release.","markdown":"---\ntitle: \"Instalación y primera app\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/installation/\nupdated: 2026-11-18T16:59:54.646Z\n---\n\n# Instalación y primera app\n\n> Instala el paquete total5, escribe el script de arranque, añade una primera ruta y una primera acción, y ejecuta la aplicación en modo debug y release.\n\nEsta guía instala el paquete `total5`, escribe el script de arranque, añade una primera ruta y una primera acción, y ejecuta la aplicación en modo debug y en modo release.\n\n## Requisitos\n\nTotal.js 5 funciona sobre [Node.js](https://nodejs.org/). Instala la versión LTS actual, que también instala `npm`. Después abre una terminal y comprueba que los dos comandos responden con un número de versión:\n\n```bash\n$ node --version\n$ npm --version\n```\n\n## Instalar el paquete\n\nCrea un directorio para la aplicación e instala el paquete desde npm:\n\n```bash\n$ mkdir myapp\n$ cd myapp\n$ npm init -y\n$ npm install total5@beta\n```\n\nEl paquete no tiene dependencias propias, así que esto instala solo el framework. También instala las herramientas de línea de comandos `total5` y `flow5` (consulta [Línea de comandos](../command-line/)).\n\n## El script de arranque\n\nCrea `index.js` en la raíz de la aplicación. Este es el script de arranque oficial de Total.js 5:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket');\n// options.unixsocket777 = true;\n// options.config = { name: 'Total.js' };\n// options.inspector = 9229;\n// options.watch = ['private'];\n// options.livereload = 'https://yourhostname';\n// options.watcher = false; // disables watcher\n// options.edit = 'wss://www.yourcodeinstance.com/?id=projectname'\n\noptions.release = process.argv.includes('--release');\n\n// Service mode:\noptions.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode');\n// options.servicemode = 'definitions,modules,config';\n\n// Cluster:\n// options.tz = 'utc';\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nArráncalo con `node index.js` en modo debug, con `node index.js --release` en modo release, o con `node index.js --service` para cargar la aplicación sin el servidor HTTP.\n\n`Total.run()` (la misma función que `F.run()`) arranca el watcher de debug: la aplicación se ejecuta en un proceso hijo que se reinicia cuando cambia un archivo. `options.release` solo cambia `DEBUG` a `false`, así que con `--release` el watcher sigue reiniciando la aplicación cuando hay cambios. Con `options.watcher = false` la aplicación se ejecuta en modo release en el proceso actual, sin el watcher.\n\nLas líneas comentadas son las demás opciones de arranque:\n\n| Opción | Descripción |\n|--------|-------------|\n| `ip` | Dirección IP en la que escuchar. Por defecto `0.0.0.0` (`CONF.$ip`). |\n| `port` | Número de puerto. Cuando no se indica, el puerto se toma de la clave de configuración `$port`. Cuando esta es `auto` (el valor por defecto), el puerto se toma de la variable de entorno `PORT`, luego del primer argumento de la línea de comandos de 3 a 5 dígitos, y si no, es `8000`. |\n| `unixsocket` | Escucha en un socket Unix en lugar de en una IP y un puerto. |\n| `unixsocket777` | Da al socket Unix los permisos 777. |\n| `config` | Un objeto con claves de configuración que se aplican antes de cargar la aplicación, por ejemplo `{ name: 'My app' }`. |\n| `inspector` | Con el watcher: arranca la aplicación con el inspector de Node.js en este puerto (`--inspect=9229`). |\n| `watch` | Con el watcher: un array de directorios adicionales que vigila el watcher. |\n| `livereload` | Con el watcher: `true` arranca un servidor WebSocket de live reload en el puerto `35729` y además vigila `public` y `views`, un número establece el puerto, y un nombre de host envía los archivos cambiados al servicio de live reload de Total.js. |\n| `watcher` | `false` ejecuta la aplicación en modo release en el proceso actual, sin el watcher. |\n| `edit` | Conecta la aplicación al Total.js Code Editor. |\n| `release` | `true` ejecuta la aplicación con `DEBUG = false`. |\n| `servicemode` | `true` carga la aplicación sin el servidor HTTP. Una cadena separada por comas (por ejemplo `'config,modules,definitions'`) carga solo esas partes. |\n| `cluster` | Un número de procesos, o `'auto'` (consulta [Workers, hilos y clúster](../workers-and-threads/)). |\n| `limit` | Con `cluster: 'auto'`: el número máximo de procesos. |\n| `tz` | Con `cluster`: la zona horaria de los procesos (`process.env.TZ`), `'utc'` por defecto. |\n\nTodas las opciones están descritas en la [referencia](../../reference/application-structure/).\n\nEl framework cambia el directorio de trabajo al directorio del script de arranque. Con el watcher la aplicación se ejecuta en un proceso hijo, así que la raíz de la aplicación es el directorio que contiene `index.js` aunque la arranques desde otro sitio (`node /www/myapp/index.js`). Con `options.watcher = false` la raíz de la aplicación es el directorio desde el que arrancas el script, así que arráncalo desde el directorio de la aplicación.\n\n## Estructura de carpetas\n\nEl framework carga estos archivos y directorios desde la raíz de la aplicación al arrancar. Todos son opcionales: crea solo los que uses.\n\n```text\nmyapp/\n├── index.js          start script\n├── config            configuration (key : value per line)\n├── .env              environment variables\n├── version           application version (first line)\n├── controllers/      routes: *.js files with exports.install\n├── actions/          NEWACTION() definitions\n├── schemas/          NEWSCHEMA() definitions\n├── models/           business logic\n├── definitions/      startup code: delegates, helpers, globals\n├── modules/          modules with exports.install\n├── extensions/       extensions of the framework\n├── middleware/       NEWMIDDLEWARE() definitions\n├── plugins/          plugins: plugins/<name>/index.js\n├── jsonschemas/      JSON schemas (*.json or *.txt)\n├── resources/        localization (*.resource)\n├── views/            HTML views\n├── public/           static files (CSS, JS, images)\n├── flowstreams/      FlowStream schemas\n├── databases/        NoSQL databases and file storages\n├── logs/             log files\n└── tmp/              temporary files\n```\n\nCada archivo `.js` de `controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `extensions` y `middleware` se carga con require y, cuando exporta una función `install()`, el framework la llama. También se leen los subdirectorios. Un archivo o directorio cuyo nombre contiene `-bk` o `_bk` se omite. La descripción completa de cada directorio está en [Estructura de la aplicación](../application-structure/).\n\n## Primera ruta\n\nCrea `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/hello/ --> hello');\n\tROUTE('POST /api/greet/ --> greet');\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n```\n\n`ROUTE('GET /', index)` envía una respuesta de texto plano desde una función. Las otras dos rutas no tienen función: el operador `-->` ejecuta la acción indicada y envía su resultado como JSON. El enrutamiento se explica en [Enrutamiento](../routing/) y el objeto `$` en [Controlador](../controller/).\n\n## Primera acción\n\nCrea `actions/hello.js`:\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nNEWACTION('greet', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.callback({ message: 'Hello ' + model.name });\n\t}\n});\n```\n\nLa acción `hello` responde con `$.success()`, que envía `{\"success\":true,\"value\":\"Hello from an action\"}`. La acción `greet` declara un esquema de entrada en línea: `*name:String` significa un campo de cadena obligatorio. El framework valida el cuerpo de la petición antes de que se ejecute la acción, y `model` son los datos validados. Una petición sin `name` recibe una respuesta de error:\n\n```bash\n$ curl -X POST -H 'Content-Type: application/json' -d '{\"name\":\"Peter\"}' http://127.0.0.1:8000/api/greet/\n{\"message\":\"Hello Peter\"}\n\n$ curl -X POST -H 'Content-Type: application/json' -d '{}' http://127.0.0.1:8000/api/greet/\n[{\"name\":\"name\",\"error\":\"The field \\\"name\\\" is invalid\",\"path\":\"name\"}]\n```\n\nLas acciones y los esquemas en línea se tratan en [Acciones](../actions/) y [Esquemas JSON](../json-schemas/).\n\n## Configuración\n\nCrea un archivo `config` con un par `key : value` por línea:\n\n```text\nname          : My first app\n```\n\nEl valor está disponible como `CONF.name` y se imprime al arrancar la aplicación. Consulta [Configuración](../configuration/).\n\n## Ejecutar en modo debug\n\n```bash\n$ node index.js\n```\n\nEl módulo de debug arranca un proceso watcher (`Total.js watcher PID: ...`), que arranca la aplicación en un proceso hijo e imprime la información de arranque:\n\n```text\n====================================================\nPID           : 75692\n...\nName          : My first app\nVersion       : 1.0.0\nMode          : debug\nCompiled      : 2 files (4ms)\n====================================================\n\nhttp://0.0.0.0:8000/\n```\n\nAbre `http://127.0.0.1:8000/` en el navegador: la página muestra `Hello world`. Pulsa `Ctrl+C` en la terminal para detener la aplicación.\n\nEn modo debug:\n\n- `DEBUG` es `true`.\n- El watcher comprueba los directorios de la aplicación (`controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `plugins` y los demás) y los archivos `config` y `version` de la raíz. Cuando cambia un archivo, imprime una línea como `--- UPD --- [ ... ] --------> /actions/hello.js` y reinicia la aplicación.\n- El watcher escribe un archivo `index.pid` con su ID de proceso. Borrar el archivo detiene el watcher y la aplicación.\n- El framework escribe `index.js.map`, una lista JSON de las rutas y acciones registradas.\n\nPasa un puerto como argumento cuando el script de arranque no indica ninguno:\n\n```bash\n$ node index.js 8001\n```\n\n## Ejecutar en modo release\n\n```bash\n$ node index.js --release\n```\n\nCon el script de arranque anterior, `--release` cambia `DEBUG` a `false`, pero el watcher sigue en marcha y reinicia la aplicación cuando cambia un archivo.\n\nPara producción, descomenta la línea `options.watcher = false` en el script de arranque e inicia la aplicación con `node index.js`. La aplicación se ejecuta entonces en modo release en el proceso actual, sin el watcher, y los cambios en los archivos fuente no tienen efecto hasta que vuelvas a iniciarla.\n\n## Próximos pasos\n\n- [Tu primer formulario](../first-form/): muestra un formulario, recibe sus datos y responde con una página nueva.\n- [Estructura de la aplicación](../application-structure/) describe cada directorio.\n- [Enrutamiento](../routing/), [Controlador](../controller/) y [Acciones](../actions/) cubren el flujo de la petición.\n- [Vistas](../views/) renderiza páginas HTML desde el directorio `views`.\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:54.646Z"}
{"id":"JanG7m1pZ60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/installation/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Installation et première application","summary":"Installe le paquet total5, écris le script de démarrage, ajoute une première route et une première action, et exécute l'application en mode debug et en mode release.","markdown":"---\ntitle: \"Installation et première application\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/installation/\nupdated: 2026-11-18T16:59:54.646Z\n---\n\n# Installation et première application\n\n> Installe le paquet total5, écris le script de démarrage, ajoute une première route et une première action, et exécute l'application en mode debug et en mode release.\n\nCe guide installe le paquet `total5`, écrit le script de démarrage, ajoute une première route et une première action, et exécute l'application en mode debug et en mode release.\n\n## Prérequis\n\nTotal.js 5 fonctionne sur [Node.js](https://nodejs.org/). Installe la version LTS actuelle, qui installe aussi `npm`. Ouvre ensuite un terminal et vérifie que les deux commandes répondent avec un numéro de version :\n\n```bash\n$ node --version\n$ npm --version\n```\n\n## Installer le paquet\n\nCrée un répertoire pour l'application et installe le paquet depuis npm :\n\n```bash\n$ mkdir myapp\n$ cd myapp\n$ npm init -y\n$ npm install total5@beta\n```\n\nLe paquet n'a pas de dépendances propres : cette commande n'installe donc que le framework. Elle installe aussi les outils en ligne de commande `total5` et `flow5` (voir [Ligne de commande](../command-line/)).\n\n## Le script de démarrage\n\nCrée `index.js` à la racine de l'application. Voici le script de démarrage officiel de Total.js 5 :\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket');\n// options.unixsocket777 = true;\n// options.config = { name: 'Total.js' };\n// options.inspector = 9229;\n// options.watch = ['private'];\n// options.livereload = 'https://yourhostname';\n// options.watcher = false; // disables watcher\n// options.edit = 'wss://www.yourcodeinstance.com/?id=projectname'\n\noptions.release = process.argv.includes('--release');\n\n// Service mode:\noptions.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode');\n// options.servicemode = 'definitions,modules,config';\n\n// Cluster:\n// options.tz = 'utc';\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nLance-le avec `node index.js` en mode debug, avec `node index.js --release` en mode release, ou avec `node index.js --service` pour charger l'application sans le serveur HTTP.\n\n`Total.run()` (la même fonction que `F.run()`) démarre le watcher de debug : l'application s'exécute dans un processus enfant qui redémarre quand un fichier change. `options.release` passe seulement `DEBUG` à `false`, donc avec `--release` le watcher redémarre toujours l'application quand il y a des changements. Avec `options.watcher = false`, l'application s'exécute en mode release dans le processus courant, sans le watcher.\n\nLes lignes commentées sont les autres options de démarrage :\n\n| Option | Description |\n|--------|-------------|\n| `ip` | Adresse IP d'écoute. Par défaut `0.0.0.0` (`CONF.$ip`). |\n| `port` | Numéro de port. S'il n'est pas défini, le port provient de la clé de configuration `$port`. Quand celle-ci vaut `auto` (la valeur par défaut), le port provient de la variable d'environnement `PORT`, puis du premier argument de la ligne de commande de 3 à 5 chiffres, et vaut `8000` à défaut. |\n| `unixsocket` | Écoute sur un socket Unix au lieu d'une IP et d'un port. |\n| `unixsocket777` | Donne au socket Unix les permissions 777. |\n| `config` | Un objet de clés de configuration appliquées avant le chargement de l'application, par exemple `{ name: 'My app' }`. |\n| `inspector` | Avec le watcher : démarre l'application avec l'inspecteur de Node.js sur ce port (`--inspect=9229`). |\n| `watch` | Avec le watcher : un tableau de répertoires supplémentaires que le watcher surveille. |\n| `livereload` | Avec le watcher : `true` démarre un serveur WebSocket de live reload sur le port `35729` et surveille aussi `public` et `views`, un nombre définit le port, et un nom d'hôte envoie les fichiers modifiés au service de live reload de Total.js. |\n| `watcher` | `false` exécute l'application en mode release dans le processus courant, sans le watcher. |\n| `edit` | Connecte l'application au Total.js Code Editor. |\n| `release` | `true` exécute l'application avec `DEBUG = false`. |\n| `servicemode` | `true` charge l'application sans le serveur HTTP. Une chaîne séparée par des virgules (par exemple `'config,modules,definitions'`) ne charge que ces parties. |\n| `cluster` | Un nombre de processus, ou `'auto'` (voir [Workers, threads et cluster](../workers-and-threads/)). |\n| `limit` | Avec `cluster: 'auto'` : le nombre maximal de processus. |\n| `tz` | Avec `cluster` : le fuseau horaire des processus (`process.env.TZ`), `'utc'` par défaut. |\n\nChaque option est décrite dans la [référence](../../reference/application-structure/).\n\nLe framework bascule le répertoire de travail vers le répertoire du script de démarrage. Avec le watcher, l'application s'exécute dans un processus enfant, donc la racine de l'application est le répertoire qui contient `index.js`, même si tu la lances depuis un autre endroit (`node /www/myapp/index.js`). Avec `options.watcher = false`, la racine de l'application est le répertoire depuis lequel tu lances le script : lance-le donc depuis le répertoire de l'application.\n\n## Structure des dossiers\n\nAu démarrage, le framework charge ces fichiers et répertoires depuis la racine de l'application. Tous sont facultatifs : ne crée que ceux que tu utilises.\n\n```text\nmyapp/\n├── index.js          start script\n├── config            configuration (key : value per line)\n├── .env              environment variables\n├── version           application version (first line)\n├── controllers/      routes: *.js files with exports.install\n├── actions/          NEWACTION() definitions\n├── schemas/          NEWSCHEMA() definitions\n├── models/           business logic\n├── definitions/      startup code: delegates, helpers, globals\n├── modules/          modules with exports.install\n├── extensions/       extensions of the framework\n├── middleware/       NEWMIDDLEWARE() definitions\n├── plugins/          plugins: plugins/<name>/index.js\n├── jsonschemas/      JSON schemas (*.json or *.txt)\n├── resources/        localization (*.resource)\n├── views/            HTML views\n├── public/           static files (CSS, JS, images)\n├── flowstreams/      FlowStream schemas\n├── databases/        NoSQL databases and file storages\n├── logs/             log files\n└── tmp/              temporary files\n```\n\nChaque fichier `.js` de `controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `extensions` et `middleware` est chargé avec require, et lorsqu'il exporte une fonction `install()`, le framework l'appelle. Les sous-répertoires sont aussi lus. Un fichier ou un répertoire dont le nom contient `-bk` ou `_bk` est ignoré. La description complète de chaque répertoire se trouve dans [Structure de l'application](../application-structure/).\n\n## Première route\n\nCrée `controllers/default.js` :\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/hello/ --> hello');\n\tROUTE('POST /api/greet/ --> greet');\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n```\n\n`ROUTE('GET /', index)` envoie une réponse en texte brut depuis une fonction. Les deux autres routes n'ont pas de fonction : l'opérateur `-->` exécute l'action nommée et envoie son résultat en JSON. Le routage est expliqué dans [Routage](../routing/) et l'objet `$` dans [Contrôleur](../controller/).\n\n## Première action\n\nCrée `actions/hello.js` :\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nNEWACTION('greet', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.callback({ message: 'Hello ' + model.name });\n\t}\n});\n```\n\nL'action `hello` répond avec `$.success()`, qui envoie `{\"success\":true,\"value\":\"Hello from an action\"}`. L'action `greet` déclare un schéma d'entrée en ligne : `*name:String` signifie un champ chaîne obligatoire. Le framework valide le corps de la requête avant l'exécution de l'action, et `model` contient les données validées. Une requête sans `name` reçoit une réponse d'erreur :\n\n```bash\n$ curl -X POST -H 'Content-Type: application/json' -d '{\"name\":\"Peter\"}' http://127.0.0.1:8000/api/greet/\n{\"message\":\"Hello Peter\"}\n\n$ curl -X POST -H 'Content-Type: application/json' -d '{}' http://127.0.0.1:8000/api/greet/\n[{\"name\":\"name\",\"error\":\"The field \\\"name\\\" is invalid\",\"path\":\"name\"}]\n```\n\nLes actions et les schémas en ligne sont traités dans [Actions](../actions/) et [Schémas JSON](../json-schemas/).\n\n## Configuration\n\nCrée un fichier `config` avec une paire `key : value` par ligne :\n\n```text\nname          : My first app\n```\n\nLa valeur est disponible sous `CONF.name` et est affichée au démarrage de l'application. Voir [Configuration](../configuration/).\n\n## Exécuter en mode debug\n\n```bash\n$ node index.js\n```\n\nLe module debug démarre un processus watcher (`Total.js watcher PID: ...`), qui démarre l'application dans un processus enfant et affiche les informations de démarrage :\n\n```text\n====================================================\nPID           : 75692\n...\nName          : My first app\nVersion       : 1.0.0\nMode          : debug\nCompiled      : 2 files (4ms)\n====================================================\n\nhttp://0.0.0.0:8000/\n```\n\nOuvre `http://127.0.0.1:8000/` dans le navigateur : la page affiche `Hello world`. Appuie sur `Ctrl+C` dans le terminal pour arrêter l'application.\n\nEn mode debug :\n\n- `DEBUG` vaut `true`.\n- Le watcher vérifie les répertoires de l'application (`controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `plugins` et les autres) ainsi que les fichiers `config` et `version` de la racine. Quand un fichier change, il affiche une ligne comme `--- UPD --- [ ... ] --------> /actions/hello.js` et redémarre l'application.\n- Le watcher écrit un fichier `index.pid` contenant son identifiant de processus. Supprimer ce fichier arrête le watcher et l'application.\n- Le framework écrit `index.js.map`, une liste JSON des routes et des actions enregistrées.\n\nPasse un port en argument quand le script de démarrage n'en définit pas :\n\n```bash\n$ node index.js 8001\n```\n\n## Exécuter en mode release\n\n```bash\n$ node index.js --release\n```\n\nAvec le script de démarrage ci-dessus, `--release` passe `DEBUG` à `false`, mais le watcher continue de tourner et redémarre l'application quand un fichier change.\n\nEn production, décommente la ligne `options.watcher = false` dans le script de démarrage et lance l'application avec `node index.js`. L'application s'exécute alors en mode release dans le processus courant, sans le watcher, et les modifications des fichiers source n'ont aucun effet tant que tu ne la redémarres pas.\n\n## Étapes suivantes\n\n- [Ton premier formulaire](../first-form/) : affiche un formulaire, reçois ses données et réponds avec une nouvelle page.\n- [Structure de l'application](../application-structure/) décrit chaque répertoire.\n- [Routage](../routing/), [Contrôleur](../controller/) et [Actions](../actions/) couvrent le flux d'une requête.\n- [Vues](../views/) effectue le rendu de pages HTML depuis le répertoire `views`.\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:54.646Z"}
{"id":"JanG7m1pZ60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/installation/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Installazione e prima app","summary":"Installa il pacchetto total5, scrivi lo script di avvio, aggiungi una prima route e un'azione ed esegui l'app in modalità debug e release.","markdown":"---\ntitle: Installazione e prima app\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/installation/\nupdated: 2026-11-18T16:59:54.646Z\n---\n\n# Installazione e prima app\n\n> Installa il pacchetto total5, scrivi lo script di avvio, aggiungi una prima route e un'azione ed esegui l'app in modalità debug e release.\n\nQuesta guida installa il pacchetto `total5`, scrive lo script di avvio, aggiunge una prima route e una prima azione ed esegue l'applicazione in modalità debug e release.\n\n## Requisiti\n\nTotal.js 5 funziona su [Node.js](https://nodejs.org/). Installa la versione LTS attuale, che installa anche `npm`. Poi apri un terminale e controlla che entrambi i comandi rispondano con un numero di versione:\n\n```bash\n$ node --version\n$ npm --version\n```\n\n## Installare il pacchetto\n\nCrea una directory per l'applicazione e installa il pacchetto da npm:\n\n```bash\n$ mkdir myapp\n$ cd myapp\n$ npm init -y\n$ npm install total5@beta\n```\n\nIl pacchetto non ha dipendenze proprie, quindi questo installa solo il framework. Installa anche gli strumenti da riga di comando `total5` e `flow5` (vedi [Riga di comando](../command-line/)).\n\n## Lo script di avvio\n\nCrea `index.js` nella root dell'applicazione. Questo è lo script di avvio ufficiale di Total.js 5:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket');\n// options.unixsocket777 = true;\n// options.config = { name: 'Total.js' };\n// options.inspector = 9229;\n// options.watch = ['private'];\n// options.livereload = 'https://yourhostname';\n// options.watcher = false; // disables watcher\n// options.edit = 'wss://www.yourcodeinstance.com/?id=projectname'\n\noptions.release = process.argv.includes('--release');\n\n// Service mode:\noptions.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode');\n// options.servicemode = 'definitions,modules,config';\n\n// Cluster:\n// options.tz = 'utc';\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nAvvialo con `node index.js` in modalità debug, con `node index.js --release` in modalità release, oppure con `node index.js --service` per caricare l'applicazione senza il server HTTP.\n\n`Total.run()` (la stessa funzione di `F.run()`) avvia il watcher di debug: l'applicazione gira in un processo figlio che si riavvia quando cambia un file. `options.release` cambia solo `DEBUG` in `false`, quindi con `--release` il watcher continua a riavviare l'applicazione quando ci sono modifiche. Con `options.watcher = false` l'applicazione gira in modalità release nel processo corrente, senza il watcher.\n\nLe righe commentate sono le altre opzioni di avvio:\n\n| Opzione | Descrizione |\n|--------|-------------|\n| `ip` | Indirizzo IP su cui restare in ascolto. Predefinito `0.0.0.0` (`CONF.$ip`). |\n| `port` | Numero di porta. Quando non è impostato, la porta viene dalla chiave di configurazione `$port`. Quando questa è `auto` (il valore predefinito), la porta viene dalla variabile d'ambiente `PORT`, poi dal primo argomento della riga di comando composto da 3 a 5 cifre, e ripiega su `8000`. |\n| `unixsocket` | Resta in ascolto su un socket Unix invece che su IP e porta. |\n| `unixsocket777` | Dà al socket Unix i permessi 777. |\n| `config` | Un oggetto con chiavi di configurazione applicate prima del caricamento dell'app, per esempio `{ name: 'My app' }`. |\n| `inspector` | Con il watcher: avvia l'app con l'inspector di Node.js su questa porta (`--inspect=9229`). |\n| `watch` | Con il watcher: un array di directory aggiuntive osservate dal watcher. |\n| `livereload` | Con il watcher: `true` avvia un server WebSocket di live reload sulla porta `35729` e osserva anche `public` e `views`, un numero imposta la porta, e un nome host invia i file modificati al servizio di live reload di Total.js. |\n| `watcher` | `false` esegue l'applicazione in modalità release nel processo corrente, senza il watcher. |\n| `edit` | Collega l'applicazione al Total.js Code Editor. |\n| `release` | `true` esegue l'applicazione con `DEBUG = false`. |\n| `servicemode` | `true` carica l'applicazione senza il server HTTP. Una stringa separata da virgole (per esempio `'config,modules,definitions'`) carica solo quelle parti. |\n| `cluster` | Un numero di processi, oppure `'auto'` (vedi [Worker, thread e cluster](../workers-and-threads/)). |\n| `limit` | Con `cluster: 'auto'`: il numero massimo di processi. |\n| `tz` | Con `cluster`: il fuso orario dei processi (`process.env.TZ`), `'utc'` per impostazione predefinita. |\n\nOgni opzione è descritta nel [riferimento](../../reference/application-structure/).\n\nIl framework imposta come directory di lavoro la directory dello script di avvio. Con il watcher l'applicazione gira in un processo figlio, quindi la root dell'applicazione è la directory che contiene `index.js` anche se la avvii da un altro posto (`node /www/myapp/index.js`). Con `options.watcher = false` la root dell'applicazione è la directory da cui avvii lo script, quindi avvialo dalla directory dell'applicazione.\n\n## Struttura delle cartelle\n\nAll'avvio il framework carica questi file e directory dalla root dell'applicazione. Sono tutti facoltativi: crea solo quelli che usi.\n\n```text\nmyapp/\n├── index.js          start script\n├── config            configuration (key : value per line)\n├── .env              environment variables\n├── version           application version (first line)\n├── controllers/      routes: *.js files with exports.install\n├── actions/          NEWACTION() definitions\n├── schemas/          NEWSCHEMA() definitions\n├── models/           business logic\n├── definitions/      startup code: delegates, helpers, globals\n├── modules/          modules with exports.install\n├── extensions/       extensions of the framework\n├── middleware/       NEWMIDDLEWARE() definitions\n├── plugins/          plugins: plugins/<name>/index.js\n├── jsonschemas/      JSON schemas (*.json or *.txt)\n├── resources/        localization (*.resource)\n├── views/            HTML views\n├── public/           static files (CSS, JS, images)\n├── flowstreams/      FlowStream schemas\n├── databases/        NoSQL databases and file storages\n├── logs/             log files\n└── tmp/              temporary files\n```\n\nOgni file `.js` in `controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `extensions` e `middleware` viene caricato con require e, quando esporta una funzione `install()`, il framework la chiama. Vengono lette anche le sottodirectory. Un file o una directory il cui nome contiene `-bk` o `_bk` viene saltato. La descrizione completa di ogni directory è in [Struttura dell'applicazione](../application-structure/).\n\n## Prima route\n\nCrea `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/hello/ --> hello');\n\tROUTE('POST /api/greet/ --> greet');\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n```\n\n`ROUTE('GET /', index)` invia una risposta in testo semplice da una funzione. Le altre due route non hanno funzione: l'operatore `-->` esegue l'azione indicata e invia il suo risultato come JSON. Il routing è spiegato in [Routing](../routing/) e l'oggetto `$` in [Controller](../controller/).\n\n## Prima azione\n\nCrea `actions/hello.js`:\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nNEWACTION('greet', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.callback({ message: 'Hello ' + model.name });\n\t}\n});\n```\n\nL'azione `hello` risponde con `$.success()`, che invia `{\"success\":true,\"value\":\"Hello from an action\"}`. L'azione `greet` dichiara uno schema di input inline: `*name:String` indica un campo stringa obbligatorio. Il framework valida il body della richiesta prima che l'azione venga eseguita, e `model` sono i dati validati. Una richiesta senza `name` riceve una risposta di errore:\n\n```bash\n$ curl -X POST -H 'Content-Type: application/json' -d '{\"name\":\"Peter\"}' http://127.0.0.1:8000/api/greet/\n{\"message\":\"Hello Peter\"}\n\n$ curl -X POST -H 'Content-Type: application/json' -d '{}' http://127.0.0.1:8000/api/greet/\n[{\"name\":\"name\",\"error\":\"The field \\\"name\\\" is invalid\",\"path\":\"name\"}]\n```\n\nAzioni e schemi inline sono trattati in [Azioni](../actions/) e [JSON schema](../json-schemas/).\n\n## Configurazione\n\nCrea un file `config` con una coppia `key : value` per riga:\n\n```text\nname          : My first app\n```\n\nIl valore è disponibile come `CONF.name` e viene stampato all'avvio dell'app. Vedi [Configurazione](../configuration/).\n\n## Eseguire in modalità debug\n\n```bash\n$ node index.js\n```\n\nIl modulo di debug avvia un processo watcher (`Total.js watcher PID: ...`), che avvia l'applicazione in un processo figlio e stampa le informazioni di avvio:\n\n```text\n====================================================\nPID           : 75692\n...\nName          : My first app\nVersion       : 1.0.0\nMode          : debug\nCompiled      : 2 files (4ms)\n====================================================\n\nhttp://0.0.0.0:8000/\n```\n\nApri `http://127.0.0.1:8000/` nel browser: la pagina mostra `Hello world`. Premi `Ctrl+C` nel terminale per fermare l'applicazione.\n\nIn modalità debug:\n\n- `DEBUG` è `true`.\n- Il watcher controlla le directory dell'applicazione (`controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `plugins` e le altre) e i file `config` e `version` nella root. Quando un file cambia, stampa una riga come `--- UPD --- [ ... ] --------> /actions/hello.js` e riavvia l'applicazione.\n- Il watcher scrive un file `index.pid` con il suo ID di processo. Eliminare il file ferma il watcher e l'applicazione.\n- Il framework scrive `index.js.map`, un elenco JSON delle route e delle azioni registrate.\n\nPassa una porta come argomento quando lo script di avvio non ne imposta una:\n\n```bash\n$ node index.js 8001\n```\n\n## Eseguire in modalità release\n\n```bash\n$ node index.js --release\n```\n\nCon lo script di avvio qui sopra, `--release` imposta `DEBUG` a `false`, ma il watcher resta attivo e riavvia l'applicazione quando un file cambia.\n\nIn produzione, togli il commento dalla riga `options.watcher = false` nello script di avvio e avvia l'applicazione con `node index.js`. L'applicazione viene quindi eseguita in modalità release nel processo corrente, senza il watcher, e le modifiche ai file sorgente non hanno effetto finché non la riavvii.\n\n## Prossimi passi\n\n- [Il tuo primo modulo](../first-form/): mostra un modulo, ricevi i suoi dati e rispondi con una nuova pagina.\n- [Struttura dell'applicazione](../application-structure/) descrive ogni directory.\n- [Routing](../routing/), [Controller](../controller/) e [Azioni](../actions/) trattano il flusso della richiesta.\n- [View](../views/) esegue il rendering delle pagine HTML dalla directory `views`.\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:54.646Z"}
{"id":"JanG7m1pZ60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/installation/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Inštalácia a prvá aplikácia","summary":"Nainštaluj balík total5, napíš štartovací skript, pridaj prvú routu a akciu a spusti aplikáciu v režime debug a release.","markdown":"---\ntitle: \"Inštalácia a prvá aplikácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/installation/\nupdated: 2026-11-18T16:59:54.646Z\n---\n\n# Inštalácia a prvá aplikácia\n\n> Nainštaluj balík total5, napíš štartovací skript, pridaj prvú routu a akciu a spusti aplikáciu v režime debug a release.\n\nTento návod nainštaluje balík `total5`, napíše štartovací skript, pridá prvú routu a prvú akciu a spustí aplikáciu v režime debug a v režime release.\n\n## Požiadavky\n\nTotal.js 5 beží na [Node.js](https://nodejs.org/). Nainštaluj aktuálnu verziu LTS, ktorá nainštaluje aj `npm`. Potom otvor terminál a skontroluj, či oba príkazy odpovedia číslom verzie:\n\n```bash\n$ node --version\n$ npm --version\n```\n\n## Inštalácia balíka\n\nVytvor adresár pre aplikáciu a nainštaluj balík z npm:\n\n```bash\n$ mkdir myapp\n$ cd myapp\n$ npm init -y\n$ npm install total5@beta\n```\n\nBalík nemá žiadne vlastné závislosti, takže sa nainštaluje len framework. Nainštalujú sa aj nástroje príkazového riadku `total5` a `flow5` (pozri [Príkazový riadok](../command-line/)).\n\n## Štartovací skript\n\nVytvor `index.js` v koreni aplikácie. Toto je oficiálny štartovací skript Total.js 5:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.unixsocket = PATH.join(F.tmpdir, 'app_name.socket');\n// options.unixsocket777 = true;\n// options.config = { name: 'Total.js' };\n// options.inspector = 9229;\n// options.watch = ['private'];\n// options.livereload = 'https://yourhostname';\n// options.watcher = false; // disables watcher\n// options.edit = 'wss://www.yourcodeinstance.com/?id=projectname'\n\noptions.release = process.argv.includes('--release');\n\n// Service mode:\noptions.servicemode = process.argv.includes('--service') || process.argv.includes('--servicemode');\n// options.servicemode = 'definitions,modules,config';\n\n// Cluster:\n// options.tz = 'utc';\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nSpusti ho cez `node index.js` v režime debug, cez `node index.js --release` v režime release alebo cez `node index.js --service`, ak chceš načítať aplikáciu bez HTTP servera.\n\n`Total.run()` (tá istá funkcia ako `F.run()`) spustí debug watcher: aplikácia beží v podriadenom procese, ktorý sa reštartuje, keď sa zmení súbor. `options.release` len prepne `DEBUG` na `false`, takže s `--release` watcher aplikáciu pri zmenách stále reštartuje. S `options.watcher = false` beží aplikácia v režime release v aktuálnom procese, bez watchera.\n\nZakomentované riadky sú ostatné štartovacie voľby:\n\n| Voľba | Popis |\n|--------|-------------|\n| `ip` | IP adresa, na ktorej sa počúva. Predvolene `0.0.0.0` (`CONF.$ip`). |\n| `port` | Číslo portu. Keď nie je nastavený, port sa vezme z konfiguračného kľúča `$port`. Keď je ten `auto` (predvolená hodnota), port sa vezme z premennej prostredia `PORT`, potom z prvého argumentu príkazového riadku s 3 až 5 číslicami a nakoniec sa použije `8000`. |\n| `unixsocket` | Počúvať na Unix sockete namiesto IP a portu. |\n| `unixsocket777` | Dá Unix socketu oprávnenia 777. |\n| `config` | Objekt s konfiguračnými kľúčmi použitými pred načítaním aplikácie, napríklad `{ name: 'My app' }`. |\n| `inspector` | S watcherom: spustí aplikáciu s inšpektorom Node.js na tomto porte (`--inspect=9229`). |\n| `watch` | S watcherom: pole ďalších adresárov, ktoré watcher sleduje. |\n| `livereload` | S watcherom: `true` spustí WebSocket server live reloadu na porte `35729` a sleduje aj `public` a `views`, číslo nastaví port a názov hostiteľa posiela zmenené súbory službe live reload od Total.js. |\n| `watcher` | `false` spustí aplikáciu v režime release v aktuálnom procese, bez watchera. |\n| `edit` | Pripojí aplikáciu k Total.js Code Editoru. |\n| `release` | `true` spustí aplikáciu s `DEBUG = false`. |\n| `servicemode` | `true` načíta aplikáciu bez HTTP servera. Reťazec oddelený čiarkami (napríklad `'config,modules,definitions'`) načíta len tieto časti. |\n| `cluster` | Počet procesov alebo `'auto'` (pozri [Workery, vlákna a klaster](../workers-and-threads/)). |\n| `limit` | S `cluster: 'auto'`: najväčší počet procesov. |\n| `tz` | S `cluster`: časové pásmo procesov (`process.env.TZ`), predvolene `'utc'`. |\n\nKaždá voľba je opísaná v [referencii](../../reference/application-structure/).\n\nFramework prepne pracovný adresár na adresár štartovacieho skriptu. S watcherom beží aplikácia v podriadenom procese, takže koreňom aplikácie je adresár, ktorý obsahuje `index.js`, aj keď ju spustíš z iného miesta (`node /www/myapp/index.js`). S `options.watcher = false` je koreňom aplikácie adresár, z ktorého skript spúšťaš, takže ho spúšťaj z adresára aplikácie.\n\n## Štruktúra priečinkov\n\nFramework pri štarte načíta tieto súbory a adresáre z koreňa aplikácie. Všetky sú voliteľné: vytvor len tie, ktoré používaš.\n\n```text\nmyapp/\n├── index.js          start script\n├── config            configuration (key : value per line)\n├── .env              environment variables\n├── version           application version (first line)\n├── controllers/      routes: *.js files with exports.install\n├── actions/          NEWACTION() definitions\n├── schemas/          NEWSCHEMA() definitions\n├── models/           business logic\n├── definitions/      startup code: delegates, helpers, globals\n├── modules/          modules with exports.install\n├── extensions/       extensions of the framework\n├── middleware/       NEWMIDDLEWARE() definitions\n├── plugins/          plugins: plugins/<name>/index.js\n├── jsonschemas/      JSON schemas (*.json or *.txt)\n├── resources/        localization (*.resource)\n├── views/            HTML views\n├── public/           static files (CSS, JS, images)\n├── flowstreams/      FlowStream schemas\n├── databases/        NoSQL databases and file storages\n├── logs/             log files\n└── tmp/              temporary files\n```\n\nKaždý súbor `.js` v `controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `extensions` a `middleware` sa načíta pomocou require a keď exportuje funkciu `install()`, framework ju zavolá. Čítajú sa aj podadresáre. Súbor alebo adresár, ktorého názov obsahuje `-bk` alebo `_bk`, sa preskočí. Úplný popis každého adresára nájdeš v [Štruktúra aplikácie](../application-structure/).\n\n## Prvá routa\n\nVytvor `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/hello/ --> hello');\n\tROUTE('POST /api/greet/ --> greet');\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n```\n\n`ROUTE('GET /', index)` pošle z funkcie odpoveď s obyčajným textom. Ostatné dve routy nemajú funkciu: operátor `-->` spustí pomenovanú akciu a pošle jej výsledok ako JSON. Routing je vysvetlený v [Routing](../routing/) a objekt `$` v [Controller](../controller/).\n\n## Prvá akcia\n\nVytvor `actions/hello.js`:\n\n```js\nNEWACTION('hello', {\n\tname: 'Say hello',\n\taction: function($) {\n\t\t$.success('Hello from an action');\n\t}\n});\n\nNEWACTION('greet', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.callback({ message: 'Hello ' + model.name });\n\t}\n});\n```\n\nAkcia `hello` odpovie pomocou `$.success()`, ktorý pošle `{\"success\":true,\"value\":\"Hello from an action\"}`. Akcia `greet` deklaruje inline vstupnú schému: `*name:String` znamená povinné reťazcové pole. Framework pred spustením akcie overí telo požiadavky a `model` sú overené dáta. Požiadavka bez `name` dostane chybovú odpoveď:\n\n```bash\n$ curl -X POST -H 'Content-Type: application/json' -d '{\"name\":\"Peter\"}' http://127.0.0.1:8000/api/greet/\n{\"message\":\"Hello Peter\"}\n\n$ curl -X POST -H 'Content-Type: application/json' -d '{}' http://127.0.0.1:8000/api/greet/\n[{\"name\":\"name\",\"error\":\"The field \\\"name\\\" is invalid\",\"path\":\"name\"}]\n```\n\nAkcie a inline schémy sú opísané v [Akcie](../actions/) a [JSON schémy](../json-schemas/).\n\n## Konfigurácia\n\nVytvor súbor `config` s jednou dvojicou `key : value` na riadok:\n\n```text\nname          : My first app\n```\n\nHodnota je dostupná ako `CONF.name` a vypíše sa pri štarte aplikácie. Pozri [Konfigurácia](../configuration/).\n\n## Spustenie v režime debug\n\n```bash\n$ node index.js\n```\n\nModul debug spustí proces watchera (`Total.js watcher PID: ...`), ktorý spustí aplikáciu v podriadenom procese a vypíše štartovacie informácie:\n\n```text\n====================================================\nPID           : 75692\n...\nName          : My first app\nVersion       : 1.0.0\nMode          : debug\nCompiled      : 2 files (4ms)\n====================================================\n\nhttp://0.0.0.0:8000/\n```\n\nOtvor `http://127.0.0.1:8000/` v prehliadači: stránka zobrazí `Hello world`. Aplikáciu zastavíš stlačením `Ctrl+C` v termináli.\n\nV režime debug:\n\n- `DEBUG` je `true`.\n- Watcher kontroluje adresáre aplikácie (`controllers`, `actions`, `schemas`, `models`, `definitions`, `modules`, `plugins` a ďalšie) a súbory `config` a `version` v koreni. Keď sa súbor zmení, vypíše riadok ako `--- UPD --- [ ... ] --------> /actions/hello.js` a reštartuje aplikáciu.\n- Watcher zapíše súbor `index.pid` so svojím ID procesu. Odstránenie súboru zastaví watcher aj aplikáciu.\n- Framework zapíše `index.js.map`, zoznam zaregistrovaných rout a akcií vo formáte JSON.\n\nKeď štartovací skript port nenastavuje, odovzdaj ho ako argument:\n\n```bash\n$ node index.js 8001\n```\n\n## Spustenie v režime release\n\n```bash\n$ node index.js --release\n```\n\nS vyššie uvedeným štartovacím skriptom prepne `--release` `DEBUG` na `false`, ale watcher beží ďalej a pri zmene súboru aplikáciu reštartuje.\n\nV produkcii odkomentuj v štartovacom skripte riadok `options.watcher = false` a aplikáciu spusti príkazom `node index.js`. Aplikácia potom beží v release režime v aktuálnom procese, bez watchera, a zmeny zdrojových súborov sa neprejavia, kým ju znova nespustíš.\n\n## Ďalšie kroky\n\n- [Tvoj prvý formulár](../first-form/): zobraz formulár, prijmi jeho údaje a odpovedz novou stránkou.\n- [Štruktúra aplikácie](../application-structure/) opisuje každý adresár.\n- [Routing](../routing/), [Controller](../controller/) a [Akcie](../actions/) pokrývajú tok požiadavky.\n- [Views](../views/) renderuje HTML stránky z adresára `views`.\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:54.646Z"}
{"id":"Jan6lW1uB61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/first-form/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Your first form","summary":"Show a form, receive its data and answer with a new page.","markdown":"---\ntitle: Your first form\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/first-form/\nupdated: 2026-11-18T15:59:56.968Z\n---\n\n# Your first form\n\n> Show a form, receive its data and answer with a new page.\n\nThis guide builds a page with a form: the browser shows the form, sends the name you write, and the application answers with a new page. It continues the application of [Installation and first app](../installation/).\n\n## Create the layout\n\nEvery view is rendered into a layout, so create it first:\n\n```html\n<!-- views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t<title>@{title}</title>\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`@{title}` prints the title of the page and `@{body}` prints the view.\n\n## Create the form\n\nThis view shows the form, and a message when there is one:\n\n```html\n<!-- views/contact.html -->\n@{title('Contact')}\n\n<h1>Contact</h1>\n\n@{if model.error}\n<p>@{model.error}</p>\n@{fi}\n\n<form method=\"post\" action=\"/contact/\">\n\t<label>\n\t\tYour name\n\t\t<input type=\"text\" name=\"name\" value=\"@{model.name}\" />\n\t</label>\n\t<button>Send</button>\n</form>\n```\n\nThe `name` attribute of the input is the name of the field that the application receives.\n\n## Create the result page\n\nThis view shows the name that was sent:\n\n```html\n<!-- views/thanks.html -->\n@{title('Thank you')}\n\n<h1>Hello @{model.name}</h1>\n\n<p><a href=\"/contact/\">Send another name</a></p>\n```\n\n## Add the routes\n\nOne route shows the form and the other one receives it:\n\n```js\n// controllers/contact.js\nexports.install = function() {\n\tROUTE('GET /contact/', form);\n\tROUTE('POST /contact/', send);\n};\n\nfunction form($) {\n\t$.view('contact', { name: '', error: '' });\n}\n\nfunction send($) {\n\tvar name = ($.body.name || '').trim();\n\n\tif (!name) {\n\t\t$.view('contact', { name: '', error: 'Write your name.' });\n\t\treturn;\n\t}\n\n\t$.view('thanks', { name: name });\n}\n```\n\n`$.body` contains the fields of the form. `$.view(name, model)` renders a view, and the view reads those values from `model`.\n\n## Try it\n\nStart the application:\n\n```bash\n$ node index.js\n```\n\nOpen `http://127.0.0.1:8000/contact/` in the browser and try both cases:\n\n- Send the form with the field empty: the page shows `Write your name.`\n- Write a name and send it: the page shows `Hello` and the name.\n\n`@{model.name}` encodes the value, so HTML written in the field is shown as text and does not run. Press `Ctrl+C` in the terminal to stop the application.\n\n## Next steps\n\n- [Views](../views/): layouts and the commands of a view.\n- [Controller](../controller/): the data of a request and the responses.\n- [Actions](../actions/): validate the data of larger forms.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:59:56.968Z"}
{"id":"Jan6lW1uB61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/first-form/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Dein erstes Formular","summary":"Zeige ein Formular an, empfange seine Daten und antworte mit einer neuen Seite.","markdown":"---\ntitle: Dein erstes Formular\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/first-form/\nupdated: 2026-11-18T15:59:56.968Z\n---\n\n# Dein erstes Formular\n\n> Zeige ein Formular an, empfange seine Daten und antworte mit einer neuen Seite.\n\nDiese Anleitung erstellt eine Seite mit einem Formular: Der Browser zeigt das Formular an und sendet den eingegebenen Namen, und die Anwendung antwortet mit einer neuen Seite. Sie setzt die Anwendung aus [Installation und erste App](../installation/) fort.\n\n## Layout erstellen\n\nJede View wird in ein Layout gerendert, erstelle es also zuerst:\n\n```html\n<!-- views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t<title>@{title}</title>\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`@{title}` gibt den Titel der Seite aus und `@{body}` die View.\n\n## Formular erstellen\n\nDiese View zeigt das Formular und, falls vorhanden, eine Meldung:\n\n```html\n<!-- views/contact.html -->\n@{title('Contact')}\n\n<h1>Contact</h1>\n\n@{if model.error}\n<p>@{model.error}</p>\n@{fi}\n\n<form method=\"post\" action=\"/contact/\">\n\t<label>\n\t\tYour name\n\t\t<input type=\"text\" name=\"name\" value=\"@{model.name}\" />\n\t</label>\n\t<button>Send</button>\n</form>\n```\n\nDas Attribut `name` des Eingabefelds ist der Name, unter dem die Anwendung den Wert erhält.\n\n## Ergebnisseite erstellen\n\nDiese View zeigt den gesendeten Namen:\n\n```html\n<!-- views/thanks.html -->\n@{title('Thank you')}\n\n<h1>Hello @{model.name}</h1>\n\n<p><a href=\"/contact/\">Send another name</a></p>\n```\n\n## Routen hinzufügen\n\nEine Route zeigt das Formular an, die andere empfängt es:\n\n```js\n// controllers/contact.js\nexports.install = function() {\n\tROUTE('GET /contact/', form);\n\tROUTE('POST /contact/', send);\n};\n\nfunction form($) {\n\t$.view('contact', { name: '', error: '' });\n}\n\nfunction send($) {\n\tvar name = ($.body.name || '').trim();\n\n\tif (!name) {\n\t\t$.view('contact', { name: '', error: 'Write your name.' });\n\t\treturn;\n\t}\n\n\t$.view('thanks', { name: name });\n}\n```\n\n`$.body` enthält die Felder des Formulars. `$.view(name, model)` rendert eine View, und die View liest diese Werte aus `model`.\n\n## Ausprobieren\n\nStarte die Anwendung:\n\n```bash\n$ node index.js\n```\n\nÖffne `http://127.0.0.1:8000/contact/` im Browser und probiere beide Fälle aus:\n\n- Sende das Formular mit leerem Feld: Die Seite zeigt `Write your name.`\n- Gib einen Namen ein und sende ihn: Die Seite zeigt `Hello` und den Namen.\n\n`@{model.name}` kodiert den Wert, daher wird in das Feld eingegebenes HTML als Text angezeigt und nicht ausgeführt. Drücke `Ctrl+C` im Terminal, um die Anwendung zu beenden.\n\n## Nächste Schritte\n\n- [Views](../views/): Layouts und die Befehle einer View.\n- [Controller](../controller/): die Daten einer Anfrage und die Antworten.\n- [Aktionen](../actions/): Validiere die Daten größerer Formulare.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:59:56.968Z"}
{"id":"Jan6lW1uB61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/first-form/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Tu primer formulario","summary":"Muestra un formulario, recibe sus datos y responde con una página nueva.","markdown":"---\ntitle: Tu primer formulario\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/first-form/\nupdated: 2026-11-18T15:59:56.968Z\n---\n\n# Tu primer formulario\n\n> Muestra un formulario, recibe sus datos y responde con una página nueva.\n\nEsta guía crea una página con un formulario: el navegador muestra el formulario, envía el nombre que escribes y la aplicación responde con una página nueva. Continúa la aplicación de [Instalación y primera app](../installation/).\n\n## Crea el layout\n\nCada vista se renderiza dentro de un layout, así que créalo primero:\n\n```html\n<!-- views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t<title>@{title}</title>\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`@{title}` imprime el título de la página y `@{body}` imprime la vista.\n\n## Crea el formulario\n\nEsta vista muestra el formulario y, si lo hay, un mensaje:\n\n```html\n<!-- views/contact.html -->\n@{title('Contact')}\n\n<h1>Contact</h1>\n\n@{if model.error}\n<p>@{model.error}</p>\n@{fi}\n\n<form method=\"post\" action=\"/contact/\">\n\t<label>\n\t\tYour name\n\t\t<input type=\"text\" name=\"name\" value=\"@{model.name}\" />\n\t</label>\n\t<button>Send</button>\n</form>\n```\n\nEl atributo `name` del campo es el nombre con el que la aplicación recibe el dato.\n\n## Crea la página de resultado\n\nEsta vista muestra el nombre enviado:\n\n```html\n<!-- views/thanks.html -->\n@{title('Thank you')}\n\n<h1>Hello @{model.name}</h1>\n\n<p><a href=\"/contact/\">Send another name</a></p>\n```\n\n## Añade las rutas\n\nUna ruta muestra el formulario y la otra lo recibe:\n\n```js\n// controllers/contact.js\nexports.install = function() {\n\tROUTE('GET /contact/', form);\n\tROUTE('POST /contact/', send);\n};\n\nfunction form($) {\n\t$.view('contact', { name: '', error: '' });\n}\n\nfunction send($) {\n\tvar name = ($.body.name || '').trim();\n\n\tif (!name) {\n\t\t$.view('contact', { name: '', error: 'Write your name.' });\n\t\treturn;\n\t}\n\n\t$.view('thanks', { name: name });\n}\n```\n\n`$.body` contiene los campos del formulario. `$.view(name, model)` renderiza una vista, y la vista lee esos valores de `model`.\n\n## Pruébalo\n\nInicia la aplicación:\n\n```bash\n$ node index.js\n```\n\nAbre `http://127.0.0.1:8000/contact/` en el navegador y prueba los dos casos:\n\n- Envía el formulario con el campo vacío: la página muestra `Write your name.`\n- Escribe un nombre y envíalo: la página muestra `Hello` y el nombre.\n\n`@{model.name}` codifica el valor, así que el HTML escrito en el campo se muestra como texto y no se ejecuta. Pulsa `Ctrl+C` en la terminal para detener la aplicación.\n\n## Siguientes pasos\n\n- [Vistas](../views/): los layouts y los comandos de una vista.\n- [Controller](../controller/): los datos de una petición y las respuestas.\n- [Acciones](../actions/): valida los datos de formularios más grandes.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:59:56.968Z"}
{"id":"Jan6lW1uB61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/first-form/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Ton premier formulaire","summary":"Affiche un formulaire, reçois ses données et réponds avec une nouvelle page.","markdown":"---\ntitle: Ton premier formulaire\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/first-form/\nupdated: 2026-11-18T15:59:56.968Z\n---\n\n# Ton premier formulaire\n\n> Affiche un formulaire, reçois ses données et réponds avec une nouvelle page.\n\nCe guide crée une page avec un formulaire : le navigateur affiche le formulaire et envoie le nom que tu écris, puis l'application répond avec une nouvelle page. Il poursuit l'application de [Installation et première application](../installation/).\n\n## Crée le layout\n\nChaque vue est rendue dans un layout, alors crée-le d'abord :\n\n```html\n<!-- views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t<title>@{title}</title>\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`@{title}` affiche le titre de la page et `@{body}` affiche la vue.\n\n## Crée le formulaire\n\nCette vue affiche le formulaire et, s'il y en a un, un message :\n\n```html\n<!-- views/contact.html -->\n@{title('Contact')}\n\n<h1>Contact</h1>\n\n@{if model.error}\n<p>@{model.error}</p>\n@{fi}\n\n<form method=\"post\" action=\"/contact/\">\n\t<label>\n\t\tYour name\n\t\t<input type=\"text\" name=\"name\" value=\"@{model.name}\" />\n\t</label>\n\t<button>Send</button>\n</form>\n```\n\nL'attribut `name` du champ est le nom sous lequel l'application reçoit la valeur.\n\n## Crée la page de résultat\n\nCette vue affiche le nom envoyé :\n\n```html\n<!-- views/thanks.html -->\n@{title('Thank you')}\n\n<h1>Hello @{model.name}</h1>\n\n<p><a href=\"/contact/\">Send another name</a></p>\n```\n\n## Ajoute les routes\n\nUne route affiche le formulaire et l'autre le reçoit :\n\n```js\n// controllers/contact.js\nexports.install = function() {\n\tROUTE('GET /contact/', form);\n\tROUTE('POST /contact/', send);\n};\n\nfunction form($) {\n\t$.view('contact', { name: '', error: '' });\n}\n\nfunction send($) {\n\tvar name = ($.body.name || '').trim();\n\n\tif (!name) {\n\t\t$.view('contact', { name: '', error: 'Write your name.' });\n\t\treturn;\n\t}\n\n\t$.view('thanks', { name: name });\n}\n```\n\n`$.body` contient les champs du formulaire. `$.view(name, model)` effectue le rendu d'une vue, et la vue lit ces valeurs dans `model`.\n\n## Essaie\n\nDémarre l'application :\n\n```bash\n$ node index.js\n```\n\nOuvre `http://127.0.0.1:8000/contact/` dans le navigateur et essaie les deux cas :\n\n- Envoie le formulaire avec le champ vide : la page affiche `Write your name.`\n- Écris un nom et envoie-le : la page affiche `Hello` et le nom.\n\n`@{model.name}` encode la valeur : le HTML écrit dans le champ s'affiche donc comme du texte et ne s'exécute pas. Appuie sur `Ctrl+C` dans le terminal pour arrêter l'application.\n\n## Étapes suivantes\n\n- [Vues](../views/) : les layouts et les commandes d'une vue.\n- [Controller](../controller/) : les données d'une requête et les réponses.\n- [Actions](../actions/) : valide les données des formulaires plus importants.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:59:56.968Z"}
{"id":"Jan6lW1uB61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/first-form/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Il tuo primo modulo","summary":"Mostra un modulo, ricevi i suoi dati e rispondi con una nuova pagina.","markdown":"---\ntitle: Il tuo primo modulo\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/first-form/\nupdated: 2026-11-18T15:59:56.968Z\n---\n\n# Il tuo primo modulo\n\n> Mostra un modulo, ricevi i suoi dati e rispondi con una nuova pagina.\n\nQuesta guida crea una pagina con un modulo: il browser mostra il modulo e invia il nome che scrivi, poi l'applicazione risponde con una nuova pagina. Continua l'applicazione di [Installazione e prima app](../installation/).\n\n## Crea il layout\n\nOgni vista viene renderizzata in un layout, quindi crealo per primo:\n\n```html\n<!-- views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t<title>@{title}</title>\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`@{title}` stampa il titolo della pagina e `@{body}` stampa la vista.\n\n## Crea il modulo\n\nQuesta vista mostra il modulo e, se presente, un messaggio:\n\n```html\n<!-- views/contact.html -->\n@{title('Contact')}\n\n<h1>Contact</h1>\n\n@{if model.error}\n<p>@{model.error}</p>\n@{fi}\n\n<form method=\"post\" action=\"/contact/\">\n\t<label>\n\t\tYour name\n\t\t<input type=\"text\" name=\"name\" value=\"@{model.name}\" />\n\t</label>\n\t<button>Send</button>\n</form>\n```\n\nL'attributo `name` del campo è il nome con cui l'applicazione riceve il valore.\n\n## Crea la pagina del risultato\n\nQuesta vista mostra il nome inviato:\n\n```html\n<!-- views/thanks.html -->\n@{title('Thank you')}\n\n<h1>Hello @{model.name}</h1>\n\n<p><a href=\"/contact/\">Send another name</a></p>\n```\n\n## Aggiungi le route\n\nUna route mostra il modulo e l'altra lo riceve:\n\n```js\n// controllers/contact.js\nexports.install = function() {\n\tROUTE('GET /contact/', form);\n\tROUTE('POST /contact/', send);\n};\n\nfunction form($) {\n\t$.view('contact', { name: '', error: '' });\n}\n\nfunction send($) {\n\tvar name = ($.body.name || '').trim();\n\n\tif (!name) {\n\t\t$.view('contact', { name: '', error: 'Write your name.' });\n\t\treturn;\n\t}\n\n\t$.view('thanks', { name: name });\n}\n```\n\n`$.body` contiene i campi del modulo. `$.view(name, model)` renderizza una vista, e la vista legge quei valori da `model`.\n\n## Provalo\n\nAvvia l'applicazione:\n\n```bash\n$ node index.js\n```\n\nApri `http://127.0.0.1:8000/contact/` nel browser e prova entrambi i casi:\n\n- Invia il modulo con il campo vuoto: la pagina mostra `Write your name.`\n- Scrivi un nome e invialo: la pagina mostra `Hello` e il nome.\n\n`@{model.name}` codifica il valore, quindi l'HTML scritto nel campo viene mostrato come testo e non viene eseguito. Premi `Ctrl+C` nel terminale per fermare l'applicazione.\n\n## Passi successivi\n\n- [Viste](../views/): i layout e i comandi di una vista.\n- [Controller](../controller/): i dati di una richiesta e le risposte.\n- [Azioni](../actions/): valida i dati dei moduli più grandi.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:59:56.968Z"}
{"id":"Jan6lW1uB61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/first-form/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Tvoj prvý formulár","summary":"Zobraz formulár, prijmi jeho údaje a odpovedz novou stránkou.","markdown":"---\ntitle: \"Tvoj prvý formulár\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/first-form/\nupdated: 2026-11-18T15:59:56.968Z\n---\n\n# Tvoj prvý formulár\n\n> Zobraz formulár, prijmi jeho údaje a odpovedz novou stránkou.\n\nV tomto návode vytvoríš stránku s formulárom: prehliadač zobrazí formulár a odošle meno, ktoré napíšeš, a aplikácia odpovie novou stránkou. Nadväzuje na aplikáciu z návodu [Inštalácia a prvá aplikácia](../installation/).\n\n## Vytvor layout\n\nKaždý pohľad sa vykresľuje do layoutu, preto ho vytvor ako prvý:\n\n```html\n<!-- views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t<title>@{title}</title>\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`@{title}` vypíše názov stránky a `@{body}` vypíše pohľad.\n\n## Vytvor formulár\n\nTento pohľad zobrazí formulár a prípadnú správu:\n\n```html\n<!-- views/contact.html -->\n@{title('Contact')}\n\n<h1>Contact</h1>\n\n@{if model.error}\n<p>@{model.error}</p>\n@{fi}\n\n<form method=\"post\" action=\"/contact/\">\n\t<label>\n\t\tYour name\n\t\t<input type=\"text\" name=\"name\" value=\"@{model.name}\" />\n\t</label>\n\t<button>Send</button>\n</form>\n```\n\nAtribút `name` poľa je názov, pod ktorým aplikácia dostane hodnotu.\n\n## Vytvor stránku s výsledkom\n\nTento pohľad zobrazí odoslané meno:\n\n```html\n<!-- views/thanks.html -->\n@{title('Thank you')}\n\n<h1>Hello @{model.name}</h1>\n\n<p><a href=\"/contact/\">Send another name</a></p>\n```\n\n## Pridaj routy\n\nJedna routa zobrazí formulár a druhá ho prijme:\n\n```js\n// controllers/contact.js\nexports.install = function() {\n\tROUTE('GET /contact/', form);\n\tROUTE('POST /contact/', send);\n};\n\nfunction form($) {\n\t$.view('contact', { name: '', error: '' });\n}\n\nfunction send($) {\n\tvar name = ($.body.name || '').trim();\n\n\tif (!name) {\n\t\t$.view('contact', { name: '', error: 'Write your name.' });\n\t\treturn;\n\t}\n\n\t$.view('thanks', { name: name });\n}\n```\n\n`$.body` obsahuje polia formulára. `$.view(name, model)` vykreslí pohľad a pohľad číta tieto hodnoty z `model`.\n\n## Vyskúšaj to\n\nSpusti aplikáciu:\n\n```bash\n$ node index.js\n```\n\nOtvor `http://127.0.0.1:8000/contact/` v prehliadači a vyskúšaj oba prípady:\n\n- Odošli formulár s prázdnym poľom: stránka zobrazí `Write your name.`\n- Napíš meno a odošli ho: stránka zobrazí `Hello` a meno.\n\n`@{model.name}` hodnotu zakóduje, takže HTML napísané do poľa sa zobrazí ako text a nespustí sa. Aplikáciu zastavíš stlačením `Ctrl+C` v termináli.\n\n## Ďalšie kroky\n\n- [Views](../views/): layouty a príkazy pohľadu.\n- [Kontrolér](../controller/): údaje požiadavky a odpovede.\n- [Akcie](../actions/): over údaje väčších formulárov.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:59:56.968Z"}
{"id":"JanG8G22Z61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/migrating-from-total4/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Migrating from Total.js 4","summary":"Move a Total.js 4 application to Total.js 5, area by area, with the code before and after each change.","markdown":"---\ntitle: Migrating from Total.js 4\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/migrating-from-total4/\nupdated: 2026-11-18T16:59:59.647Z\n---\n\n# Migrating from Total.js 4\n\n> Move a Total.js 4 application to Total.js 5, area by area, with the code before and after each change.\n\nThis guide moves an application from Total.js 4 to Total.js 5. It lists what you have to change in each area, with the old code next to its replacement, and ends with a small application shown in both versions.\n\n## Recommended order of work\n\n1. Replace the `total4` package with `total5` and update the [start script](#start-script).\n2. Rename the [configuration keys](#configuration) and add types to numeric values.\n3. Turn [schemas into actions](#schemas-and-actions) and update the routes that call them.\n4. Replace `this` with `$` in [routes and controllers](#routes) and in [middleware](#middleware).\n5. Check [views](#views) and [mail views](#mail): folders, layouts and titles.\n6. Update [NoSQL](#nosql) queries, [RESTBuilder](#restbuilder) error handling, [WebSockets](#websockets) and [file storage](#file-storage).\n7. Replace [`SCHEDULE()`](#scheduling), [operations and tasks](#operations-and-tasks), and `MODULE()` and `MODEL()` [calls](#modules-models-and-definitions).\n8. Rewrite the [unit tests](#unit-tests) and run the application.\n\n## Start script\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `npm install total4` | `npm install total5@beta` |\n| `require('total4/debug')(options)` | `require('total5'); Total.run(options)` |\n| `require('total4/release')(options)` | `options.release = true; Total.run(options)` |\n\nBefore:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.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\nAfter:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\nBoth scripts start in debug mode, and in release mode with `node index.js --release`. See [Installation](../installation/).\n\n## Schemas and actions\n\n`schema.define()` and the `schema.setInsert()` family do not exist in Total.js 5. An unchanged schema stops the application at start with `TypeError: schema.define is not a function`. Move each operation into a `NEWACTION()` in the `actions/` folder and declare its fields in `input`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `schema.define('name', 'String(30)', true)` | `input: '*name:String(30)'` |\n| `schema.define('role', ['admin', 'user'])` | `input: 'role:{admin\\|user}'` |\n| `schema.setInsert(fn)`, `setQuery(fn)`, `setRead(fn)`... | `NEWACTION('Users/insert', { action: fn })` |\n| `ROUTE('POST /api/users/ *Users --> insert')` | `ROUTE('POST /api/users/ --> Users/insert')` |\n| `$.id` | `params: '*id:String'` and `$.params.id` |\n| `.callback($.callback)` | `.callback($)` |\n| `$.invalid('age', 'Message')` | `$.invalid('Message', 'age')` |\n| `CALL('Math --> double', data)` | `ACTION('Math/double', data)` |\n\nBefore:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(30)', 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 = 'A1';\n\t\t$.success(model);\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ *Users --> insert');\n};\n```\n\nAfter:\n\n```js\nNEWACTION('Users/insert', {\n\tinput: '*name:String(30), *email:Email, age:Number, role:{admin|user}',\n\taction: function($, model) {\n\t\tmodel.id = 'A1';\n\t\t$.success(model);\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ --> Users/insert');\n};\n```\n\n### Custom validators\n\nA validator function in `schema.define()` moves into the action.\n\nBefore:\n\n```js\nNEWSCHEMA('Signup', function(schema) {\n\n\tschema.define('name', 'String(30)', true);\n\tschema.define('age', Number, value => value >= 18, 'You must be an adult');\n\n\tschema.setInsert(function($, model) {\n\t\t$.success(model.age);\n\t});\n\n});\n```\n\nAfter:\n\n```js\nNEWACTION('Signup/insert', {\n\tinput: '*name:String(30), age:Number',\n\taction: function($, model) {\n\n\t\tif (model.age < 18) {\n\t\t\t$.invalid('You must be an adult', 'age');\n\t\t\treturn;\n\t\t}\n\n\t\t$.success(model.age);\n\t}\n});\n```\n\n### Schemas that already use `schema.action()`\n\nThese schemas keep working. Only the route changes: `*Tags --> list` becomes `--> Tags/list`.\n\n```js\nNEWSCHEMA('Tags', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of tags',\n\t\tquery: 'limit:Number',\n\t\taction: function($) {\n\t\t\t$.callback(['a', 'b', 'c'].slice(0, $.query.limit || 3));\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a tag',\n\t\tinput: '*name:String(20)',\n\t\taction: function($, model) {\n\t\t\t$.success(model.name);\n\t\t}\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('GET  /api/tags/ --> Tags/list');\n\tROUTE('POST /api/tags/ --> Tags/create');\n};\n```\n\n### Values and errors your clients will notice\n\n| Case | Total.js 4 | Total.js 5 |\n| --- | --- | --- |\n| Optional `Number` is missing | The field is `0` | The field is left out |\n| Optional enum is missing | The field is left out | The field is `''` |\n| Enum value is not in the list | Value dropped, request accepted | `400` with an error for the field |\n| Keys of a required-field error | `name`, `error`, `path`, `prefix` | `name`, `error`, `path` |\n| Keys of an error from `$.invalid()` with a field | `name`, `error` | `error`, `path` |\n\nA client that reads `name` from your own errors has to read `path` instead. See [Actions](../actions/) and [JSON schemas](../json-schemas/).\n\n## Routes\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function detail(id) { this.json({ id: id }); }` | `function detail($) { $.json({ id: $.params.id }); }` |\n| `ROUTE('/about/', fn)` | `ROUTE('GET /about/', fn)`: the method is required |\n| `{page:number}` converts the value | `{page}` is a string: `$.params.page.parseInt()` |\n| `ROUTE('POST /upload/', fn, ['upload'], 1024)` | `ROUTE('POST /upload/ @upload <1MB', fn)` |\n| `ROUTE('POST /import/', fn, 1024)` | `ROUTE('POST /import/ <1MB', fn)` |\n| `ROUTE('+GET /admin/ @admin', fn)` | `ROUTE('+GET /admin/', fn)` and `UNAUTHORIZED($, 'admin')` in the handler |\n| `ROUTE('API /api/ -users_list *Users --> list')` | `ROUTE('API /api/ users_list --> Users/list')` |\n| `ROUTE('API /api/ +users_save *Users --> save')` | `ROUTE('API /api/ users_save --> Users/save')` |\n\nA route without a size flag refuses a JSON body above 256 kB with `431`, so give routes that import large data their own limit. An unknown `API` endpoint answers `400` instead of `404`. See [Routing](../routing/).\n\nBefore:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail(id, order) {\n\tthis.json({ id: id, order: order, params: this.params });\n}\n```\n\nAfter:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail($) {\n\t$.json({ id: $.params.id, order: $.params.order, params: $.params });\n}\n```\n\n## Controllers\n\nHandlers receive the controller as `$`. `this` is no longer the controller in HTTP routes.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.status = 201` | `$.response.status = 201` |\n| `this.header('X-Version', '1')` | `$.response.headers['x-version'] = '1'` |\n| `this.nocache()` | `$.response.headers['cache-control'] = 'private, no-cache, no-store, max-age=0'` |\n| `this.content('<a>1</a>', 'text/xml')` | `$.xml('<a>1</a>')` |\n| `this.content('id;name', 'text/csv')` | `$.binary(Buffer.from('id;name'), 'text/csv')` |\n| `this.nocontent()` | `$.empty()` |\n| `this.throw404()`, `this.throw403()` | `$.fallback(404)`, `$.fallback(403)` |\n| `this.throw500('Problem')` | `$.fallback(500, 'Problem')` |\n| `this.file('docs/a.txt', 'report.txt')` | `$.file(PATH.public('docs/a.txt'), 'report.txt')` |\n| `this.success(true, 42)` | `$.success(42)` |\n| `this.success(false)` | `$.json({ success: false })` |\n| `this.invalid('email', 'Message')` | `var err = new ErrorBuilder(); err.push('Message', 'email'); $.invalid(err);` |\n| `file.isImage()` | `file.isImage` |\n| `this.mail(email, subject, view, model)` | `MAIL(email, subject, view, model)` |\n\nThese members only need `this` replaced with `$`: `params`, `query`, `body`, `files`, `headers`, `url`, `ip`, `ua`, `mobile`, `robot`, `xhr`, `referrer`, `user`, `language`, `cookie()`, `hostname()`, `json()`, `plain()`, `view()`, `filefs()` and `stream(type, stream)`.\n\nAn error route sets the status in the same way:\n\n```js\nexports.install = function() {\n\tROUTE('GET /missing/', missing);\n\tROUTE('GET /denied/', denied);\n\tROUTE('GET /broken/', broken);\n\tROUTE('#404', notfound);\n};\n\nfunction missing($) {\n\t$.fallback(404);\n}\n\nfunction denied($) {\n\t$.fallback(403);\n}\n\nfunction broken($) {\n\t$.fallback(500, 'Unexpected problem');\n}\n\nfunction notfound($) {\n\t$.response.status = 404;\n\t$.plain('My 404 page');\n}\n```\n\nSee [Controller](../controller/).\n\n## Views\n\nThe syntax of view files does not change: expressions, conditions, loops, sections, partial views and helpers from `DEF.helpers` work as before.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.view('detail')` in `controllers/users.js` finds `views/users/detail.html` | `$.view('users/detail')`: the name always starts in `views/` |\n| The layout can read `model` | Set `@{repository.name = model.name}` in the view and read `repository` in the layout |\n| `this.title('Products')` | `@{title('Products')}` in the view |\n| `this.repository.page = 'list'` | `@{repository.page = 'list'}` in the view |\n| `VIEW('mail/order', model)` | `F.view('mail/order', model)`, with `@{layout('')}` in the view |\n| The title of the home page gets ` - ` and `CONF.name` | The title of the home page stays as you wrote it |\n\nBefore:\n\n```html\n<title>@{model.name}</title>@{body}\n```\n\nAfter:\n\n```html\n<title>@{repository.name}</title>@{body}\n```\n\n```html\n@{repository.name = model.name}\n<h1>@{model.name}</h1>\n```\n\nSee [Views](../views/).\n\n## Middleware\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MIDDLEWARE('name', function($) { $.next(); })` | `NEWMIDDLEWARE('name', function($, next) { next(); })` |\n| `$.res.throw401()` | `$.invalid(401)` |\n| `$.res.setHeader('x-stamp', 'yes')` | `$.response.headers['x-stamp'] = 'yes'` |\n| `ROUTE('GET /private/', fn, ['#apikey'])` | `ROUTE('GET /private/ #apikey', fn)` |\n| `ROUTE('GET /open/ &stamp', fn)` | `ROUTE('GET /open/ #stamp', fn)` |\n| `USE('poweredby', ['web'])` | Third argument `'routes'`, inside `ON('ready')` |\n\nBefore:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('x-server', 'myapp');\n\t$.next();\n});\n\nUSE('poweredby', ['web']);\n```\n\nAfter:\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('poweredby', function($, next) {\n\t\t$.response.headers['x-server'] = 'myapp';\n\t\tnext();\n\t}, 'routes');\n});\n```\n\nSee [Middleware](../middleware/).\n\n## WebSockets\n\nA `SOCKET` route keeps its structure, and `this` still works inside its handler.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function room(name) {}` | `function room($) { var name = $.params.name; }` |\n| `ROUTE('SOCKET /feed/', fn, ['json'], 64)` | `ROUTE('SOCKET /feed/ <64kB', fn)` |\n| `ROUTE('SOCKET /terminal/', fn, ['text'])` | `ROUTE('SOCKET /terminal/ @text', fn)` |\n| `client.send(text)` on a text route | `client.send(text, true)` |\n| `client.close('finished', 4000)` | `client.close(4000, 'finished')` |\n| A refused `+SOCKET` client connects and is closed with `4001` | The handshake is refused and the client sees `1006` |\n\nSee [WebSockets](../websockets/).\n\n## NoSQL\n\nExisting `.nosql` files can be read as they are. `insert()`, `find()`, `read()`, `update()`, `remove()`, `where()`, `search()`, `fields()`, `skip()`, `take()`, `first()` and the `+field` update prefix do not change.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `find()` starts with the oldest document | `find()` starts with the newest document: add `sort()` when the order matters |\n| `find2()` | `find()` |\n| `one()` | `read()` |\n| `sort('age_desc')` | `sort('age', true)` |\n| `NOSQL('users').count()` | `DATA.count('nosql/users')` |\n| `NOSQL('users').list()` | `DATA.list('nosql/users')` |\n| `rule('doc.age > arg.min', { min: 45 })` | `query('doc.age > 45')` |\n| `update({ '-score': 3 })` | `update({ '+score': -3 })` |\n| `TABLE('users')` | `NOSQL('users')` |\n\n`TABLE()` does not exist in Total.js 5, so move the rows of `.table` files into a NoSQL database yourself.\n\nBefore:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run() {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.one().where('id', '2').fields('name').promise();\n\tvar count = await db.count().where('age', '>', 35).promise();\n\tvar list = await db.list().sort('age_desc').fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().rule('doc.age > arg.min', { min: 45 }).fields('name').promise();\n\n\tawait db.update({ '-score': 3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\tthis.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nAfter:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run($) {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.read().where('id', '2').fields('name').promise();\n\tvar count = await DATA.count('nosql/users').where('age', '>', 35).promise();\n\tvar list = await DATA.list('nosql/users').sort('age', true).fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().query('doc.age > 45').fields('name').promise();\n\n\tawait db.update({ '+score': -3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\t$.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nSee [NoSQL database](../nosql/).\n\n## RESTBuilder\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| A status of `400` or higher is an error only with `.strict()` | A status of `400` or higher is always an error |\n| `.callback($.callback)` in an operation | `.callback($)` in an action |\n\nCode that reads `output.status` after a failed request has to handle `err` first. See [HTTP requests](../http-requests/).\n\n## Configuration\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `default_root` | `$root` |\n| `default_timezone` | `$timezone` |\n| `default_cookies_samesite` | `$cookiesamesite` |\n| `default_cookies_secure` | `$cookiesecure` |\n| `default_xpoweredby` | `$xpoweredby` |\n| `allow_custom_titles` | `$customtitles` |\n| `allow_gzip` | `$httpcompress` |\n| `limit : 50` is a number | `limit (number) : 50`: without a type the value is a string |\n| `smtp (object) : { port: 465 }` | `smtp (json) : { \"port\": 465 }` |\n| `config-release` | Not loaded: keep the values in `config` |\n\nBefore:\n\n```text\nname                     : Shop\ndefault_root             : /app/\ndefault_timezone         : Europe/Bratislava\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\ndefault_xpoweredby       : MyServer\nallow_custom_titles      : true\nallow_gzip               : false\n```\n\nAfter:\n\n```text\nname            : Shop\n$root           : /app/\n$timezone       : Europe/Bratislava\n$cookiesamesite : Strict\n$cookiesecure   : true\n$xpoweredby     : MyServer\n$customtitles   : true\n$httpcompress   : false\n```\n\n`CORS()`, `name`, `(array)` values and `mail_smtp_options` written as a JavaScript object work as before. See [Configuration](../configuration/).\n\n## Authorization\n\nThe `AUTH()` delegate, the `+` and `-` route flags and `UNAUTHORIZED()` do not change. `SESSION()` does not exist in Total.js 5: use the built-in session of `AUTH()`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SESSION()` with `ondata` | `AUTH(opt)` with `opt.onread` |\n| `session.setcookie($, options, callback)` | `opt.authcookie($, UID(), userid, '1 hour')` |\n| `session.remove2(userid)` and clearing the cookie | `opt.logout($)` in an action |\n\nBefore:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\tnext(null, { id: meta.id, name: 'Peter' });\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 hour', key: 'session-key' }, 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\nMAIN.session = session;\n```\n\nAfter:\n\n```js\nvar opt = {};\n\nopt.secret = 'session-key';\nopt.cookie = 'sid';\nopt.expire = '1 hour';\n\nopt.onread = function(meta, next) {\n\tnext(null, { id: meta.userid, name: 'Peter' });\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\n```js\nNEWACTION('Account/logout', {\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.logout()` removes the session from memory and clears the cookie. A saved copy of the token is signed, so it is accepted again whenever `onread` returns a user. Check the session in your database inside `onread` when signing out has to revoke the token. See [Authorization](../authorization/).\n\n## Localization\n\nResource files and `@(Text)` in views stay the same, and the generated keys are identical.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `LOCALIZE(function(req, res) {})` | `LOCALIZE(function($) {})` |\n| `RESOURCE('sk', 'title')` | `F.resource('sk', 'title')` |\n| `TRANSLATOR('sk', '<b>@(Welcome)</b>')` | `TRANSLATE('sk', '<b>@(Welcome)</b>')` |\n| `TRANSLATE('sk', 'Welcome')` | `TRANSLATE('sk', '@(Welcome)')` |\n\nSee [Localization](../localization/).\n\n## Mail\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MAIL()` renders the view without a layout | `MAIL()` renders the view into `views/layout.html` |\n| `ON('mail', fn)` | `ON('$mail', fn)` |\n| `message.address_to` | `message.email_to` |\n\nStart every mail view with `@{layout('')}`. Without it the message is wrapped in your site layout, and when `views/layout.html` does not exist the message is not sent at all.\n\nBefore:\n\n```html\n<p>Hello @{model.name}</p>\n```\n\nAfter:\n\n```html\n@{layout('')}\n<p>Hello @{model.name}</p>\n```\n\nSee [Sending email](../mail/).\n\n## File storage\n\nThe arguments of `save()` change order: the custom data now comes before the callback.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `fs.save(id, name, data, callback, custom)` | `fs.save(id, name, data, custom, callback)` |\n\n`read()` and `$.filefs()` do not change. See [File storage](../file-storage/).\n\n## Scheduling\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SCHEDULE('* * * * *', fn)` | `CRON('* * * * *', fn)` |\n| `SCHEDULE('03:00', '1 day', fn)` | `CRON('0 3 * * *', fn)` |\n\nBefore:\n\n```js\nMAIN.runs = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nAfter:\n\n```js\nMAIN.runs = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nSee [Scheduling and events](../scheduling-and-events/).\n\n## Operations and tasks\n\n`NEWOPERATION()`, `OPERATION()`, `RUN()`, `NEWTASK()` and `TASK()` do not exist in Total.js 5. Each operation becomes an action, and the steps of a task become one action or several actions called in sequence.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `NEWOPERATION('order_price', fn)` | `NEWACTION('order_price', { input: '...', action: fn })` |\n| `OPERATION('order_price', value, callback)` | `ACTION('order_price', value).callback(callback)` |\n| `RUN('order_check, order_price', value, callback)` | `await ACTION(...).promise($)` for each step |\n| `NEWTASK('order', fn)` and `TASK('order/check', ...)` | `NEWACTION('order', { action: fn })` |\n\nBefore:\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order() {\n\tvar self = this;\n\tOPERATION('order_price', self.body, function(err, response) {\n\t\tself.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nfunction chain() {\n\tvar self = this;\n\tRUN('order_check, order_price', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.order_price);\n\t});\n}\n```\n\nAfter:\n\n```js\nNEWACTION('order_check', {\n\tinput: '*email:String, count:Number',\n\taction: function($, model) {\n\t\tmodel.email = model.email.toLowerCase();\n\t\t$.callback(model);\n\t}\n});\n\nNEWACTION('order_price', {\n\tinput: 'email:String, count:Number',\n\taction: function($, model) {\n\t\t$.callback({ email: model.email, price: model.count * 10 });\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order($) {\n\tACTION('order_price', $.body).callback(function(err, response) {\n\t\t$.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nasync function chain($) {\n\tvar model = await ACTION('order_check', $.body).promise($);\n\t$.json(await ACTION('order_price', model).promise($));\n}\n```\n\nSee [Actions](../actions/).\n\n## Modules, models and definitions\n\nFiles in `definitions/` and `modules/` load as before, and `MAIN`, `FUNC`, `PATH` and `ON('ready')` do not change.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MODULE('greeter').greet('Peter')` | `MODS.greeter.greet('Peter')` |\n| `MODEL('price').total(2, 5)` | `require(PATH.root('models/price.js')).total(2, 5)` |\n| `CACHE('products', value, '5 minutes')` | `CACHE.set('products', value, '5 minutes')` |\n| `CACHE('products')` | `CACHE.read('products')` |\n\nSee [Application structure](../application-structure/).\n\n## Unit tests\n\n`TESTER()` is replaced by the `Test` object of `total5/test`.\n\nBefore:\n\n```js\nrequire('total4');\n\nTESTER(function(group, start) {\n\n\tgroup('Strings', function(test) {\n\n\t\ttest('slug()', function(next) {\n\t\t\tnext('Hello World'.slug() === 'hello-world' ? undefined : 'Unexpected slug');\n\t\t});\n\n\t\ttest('capitalize()', function(next) {\n\t\t\tnext('total'.capitalize() === 'Total' ? undefined : 'Unexpected value');\n\t\t});\n\n\t});\n\n\tstart();\n});\n```\n\nAfter:\n\n```js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nSee [Unit tests](../unit-tests/).\n\n## Command line\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `total4 translate` | `total5 translate \"$PWD/translate.resource\"` |\n\nGive `total5 translate` the full path of the output file. See [Command line](../command-line/).\n\n## A complete application\n\nThis small notes application has a public list, protected writes, a home page, a notification mail, a live WebSocket channel and a job that runs every minute. Both versions answer the same requests in the same way, except for the home page title described in [Views](#views).\n\n### Total.js 4\n\n`index.js`\n\n```js\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\n`config`\n\n```text\nname              : Notes\napitoken          : secret\nmail_notify       : admin@example.com\nmail_from         : notes@example.com\nmail_smtp         : 127.0.0.1\nmail_smtp_options : { port: 19854 }\nmaxnotes          : 100\n```\n\n`definitions/auth.js`\n\n```js\nAUTH(function($) {\n\tif ($.headers['x-token'] === CONF.apitoken)\n\t\t$.success({ id: '1', name: 'Admin' });\n\telse\n\t\t$.invalid();\n});\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`schemas/notes.js`\n\n```js\nNEWSCHEMA('Notes', function(schema) {\n\n\tschema.define('title', 'String(50)', value => value && value !== 'spam', 'This title is not allowed');\n\tschema.define('body', 'String(500)');\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('notes').find().sort('dtcreated_desc').fields('id,title').take(CONF.maxnotes).callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('notes').read().id($.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t});\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t});\n\n\tschema.setRemove(function($) {\n\t\tNOSQL('notes').remove().id($.id).callback($.done());\n\t});\n\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        *Notes --> query');\n\tROUTE('GET     /api/notes/{id}/   *Notes --> read');\n\tROUTE('+POST   /api/notes/        *Notes --> insert');\n\tROUTE('+DELETE /api/notes/{id}/   *Notes --> remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats() {\n\tthis.json({ ticks: MAIN.ticks });\n}\n\nfunction live() {\n\tMAIN.live = this;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tvar self = this;\n\tself.title('Latest notes');\n\tNOSQL('notes').find().sort('dtcreated_desc').fields('title').callback(function(err, notes) {\n\t\tself.view('index', notes);\n\t});\n}\n```\n\n`views/layout.html`\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`views/index.html`\n\n```html\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n<p>New note: @{model.title}</p>\n```\n\n### Total.js 5\n\n`definitions/auth.js` and `views/layout.html` stay the same.\n\n`index.js`\n\n```js\nrequire('total5');\n\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\n`config`\n\n```text\nname                : Notes\napitoken            : secret\nmail_notify         : admin@example.com\nmail_from           : notes@example.com\nmail_smtp           : 127.0.0.1\nmail_smtp_options   : { port: 19854 }\nmaxnotes (number)   : 100\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`actions/notes.js`\n\n```js\nNEWACTION('Notes/query', {\n\taction: function($) {\n\t\tNOSQL('notes').find().sort('dtcreated', true).fields('id,title').take(CONF.maxnotes).callback($);\n\t}\n});\n\nNEWACTION('Notes/read', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').read().id($.params.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/insert', {\n\tinput: '*title:String(50), body:String(500)',\n\taction: function($, model) {\n\n\t\tif (model.title === 'spam') {\n\t\t\t$.invalid('This title is not allowed', 'title');\n\t\t\treturn;\n\t\t}\n\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/remove', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').remove().id($.params.id).callback($.done());\n\t}\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        --> Notes/query');\n\tROUTE('GET     /api/notes/{id}/   --> Notes/read');\n\tROUTE('+POST   /api/notes/        --> Notes/insert');\n\tROUTE('+DELETE /api/notes/{id}/   --> Notes/remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats($) {\n\t$.json({ ticks: MAIN.ticks });\n}\n\nfunction live($) {\n\tMAIN.live = $;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index($) {\n\tNOSQL('notes').find().sort('dtcreated', true).fields('title').callback(function(err, notes) {\n\t\t$.view('index', notes);\n\t});\n}\n```\n\n`views/index.html`\n\n```html\n@{title('Latest notes')}\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n@{layout('')}\n<p>New note: @{model.title}</p>\n```\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:59.647Z"}
{"id":"JanG8G22Z61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/migrating-from-total4/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Migration von Total.js 4","summary":"Bringe eine Total.js-4-Anwendung Bereich für Bereich auf Total.js 5, mit dem Code vor und nach jeder Änderung.","markdown":"---\ntitle: Migration von Total.js 4\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/migrating-from-total4/\nupdated: 2026-11-18T16:59:59.647Z\n---\n\n# Migration von Total.js 4\n\n> Bringe eine Total.js-4-Anwendung Bereich für Bereich auf Total.js 5, mit dem Code vor und nach jeder Änderung.\n\nDiese Anleitung bringt eine Anwendung von Total.js 4 auf Total.js 5. Für jeden Bereich steht hier, was du ändern musst, mit dem alten Code neben seinem Ersatz. Am Ende findest du eine kleine Anwendung in beiden Versionen.\n\n## Empfohlene Reihenfolge\n\n1. Ersetze das Paket `total4` durch `total5` und aktualisiere das [Startskript](#start-script).\n2. Benenne die [Konfigurationsschlüssel](#configuration) um und ergänze Typen für numerische Werte.\n3. Mache aus [Schemas Actions](#schemas-and-actions) und aktualisiere die Routen, die sie aufrufen.\n4. Ersetze `this` durch `$` in [Routen und Controllern](#routes) und in der [Middleware](#middleware).\n5. Prüfe [Views](#views) und [Mail-Views](#mail): Ordner, Layouts und Titel.\n6. Aktualisiere [NoSQL](#nosql)-Abfragen, die Fehlerbehandlung von [RESTBuilder](#restbuilder), [WebSockets](#websockets) und den [Dateispeicher](#file-storage).\n7. Ersetze [`SCHEDULE()`](#scheduling), [Operations und Tasks](#operations-and-tasks) sowie die [Aufrufe](#modules-models-and-definitions) von `MODULE()` und `MODEL()`.\n8. Schreibe die [Unit-Tests](#unit-tests) neu und starte die Anwendung.\n\n## Startskript\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `npm install total4` | `npm install total5@beta` |\n| `require('total4/debug')(options)` | `require('total5'); Total.run(options)` |\n| `require('total4/release')(options)` | `options.release = true; Total.run(options)` |\n\nVorher:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.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\nNachher:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\nBeide Skripte starten im Debug-Modus und mit `node index.js --release` im Release-Modus. Siehe [Installation](../installation/).\n\n## Schemas und Actions\n\n`schema.define()` und die Familie von `schema.setInsert()` gibt es in Total.js 5 nicht. Ein unverändertes Schema stoppt die Anwendung beim Start mit `TypeError: schema.define is not a function`. Verschiebe jede Operation in eine `NEWACTION()` im Ordner `actions/` und deklariere ihre Felder in `input`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `schema.define('name', 'String(30)', true)` | `input: '*name:String(30)'` |\n| `schema.define('role', ['admin', 'user'])` | `input: 'role:{admin\\|user}'` |\n| `schema.setInsert(fn)`, `setQuery(fn)`, `setRead(fn)`... | `NEWACTION('Users/insert', { action: fn })` |\n| `ROUTE('POST /api/users/ *Users --> insert')` | `ROUTE('POST /api/users/ --> Users/insert')` |\n| `$.id` | `params: '*id:String'` und `$.params.id` |\n| `.callback($.callback)` | `.callback($)` |\n| `$.invalid('age', 'Message')` | `$.invalid('Message', 'age')` |\n| `CALL('Math --> double', data)` | `ACTION('Math/double', data)` |\n\nVorher:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(30)', 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 = 'A1';\n\t\t$.success(model);\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ *Users --> insert');\n};\n```\n\nNachher:\n\n```js\nNEWACTION('Users/insert', {\n\tinput: '*name:String(30), *email:Email, age:Number, role:{admin|user}',\n\taction: function($, model) {\n\t\tmodel.id = 'A1';\n\t\t$.success(model);\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ --> Users/insert');\n};\n```\n\n### Eigene Validatoren\n\nEine Validierungsfunktion aus `schema.define()` wandert in die Action.\n\nVorher:\n\n```js\nNEWSCHEMA('Signup', function(schema) {\n\n\tschema.define('name', 'String(30)', true);\n\tschema.define('age', Number, value => value >= 18, 'You must be an adult');\n\n\tschema.setInsert(function($, model) {\n\t\t$.success(model.age);\n\t});\n\n});\n```\n\nNachher:\n\n```js\nNEWACTION('Signup/insert', {\n\tinput: '*name:String(30), age:Number',\n\taction: function($, model) {\n\n\t\tif (model.age < 18) {\n\t\t\t$.invalid('You must be an adult', 'age');\n\t\t\treturn;\n\t\t}\n\n\t\t$.success(model.age);\n\t}\n});\n```\n\n### Schemas, die bereits `schema.action()` verwenden\n\nDiese Schemas funktionieren weiter. Nur die Route ändert sich: Aus `*Tags --> list` wird `--> Tags/list`.\n\n```js\nNEWSCHEMA('Tags', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of tags',\n\t\tquery: 'limit:Number',\n\t\taction: function($) {\n\t\t\t$.callback(['a', 'b', 'c'].slice(0, $.query.limit || 3));\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a tag',\n\t\tinput: '*name:String(20)',\n\t\taction: function($, model) {\n\t\t\t$.success(model.name);\n\t\t}\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('GET  /api/tags/ --> Tags/list');\n\tROUTE('POST /api/tags/ --> Tags/create');\n};\n```\n\n### Werte und Fehler, die deine Clients bemerken\n\n| Fall | Total.js 4 | Total.js 5 |\n| --- | --- | --- |\n| Optionale `Number` fehlt | Das Feld ist `0` | Das Feld wird weggelassen |\n| Optionales Enum fehlt | Das Feld wird weggelassen | Das Feld ist `''` |\n| Enum-Wert steht nicht in der Liste | Wert wird verworfen, Anfrage wird akzeptiert | `400` mit einem Fehler für das Feld |\n| Schlüssel eines Pflichtfeld-Fehlers | `name`, `error`, `path`, `prefix` | `name`, `error`, `path` |\n| Schlüssel eines Fehlers aus `$.invalid()` mit Feld | `name`, `error` | `error`, `path` |\n\nEin Client, der `name` aus deinen eigenen Fehlern liest, muss stattdessen `path` lesen. Siehe [Actions](../actions/) und [JSON-Schemas](../json-schemas/).\n\n## Routen\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function detail(id) { this.json({ id: id }); }` | `function detail($) { $.json({ id: $.params.id }); }` |\n| `ROUTE('/about/', fn)` | `ROUTE('GET /about/', fn)`: Die Methode ist Pflicht |\n| `{page:number}` wandelt den Wert um | `{page}` ist ein String: `$.params.page.parseInt()` |\n| `ROUTE('POST /upload/', fn, ['upload'], 1024)` | `ROUTE('POST /upload/ @upload <1MB', fn)` |\n| `ROUTE('POST /import/', fn, 1024)` | `ROUTE('POST /import/ <1MB', fn)` |\n| `ROUTE('+GET /admin/ @admin', fn)` | `ROUTE('+GET /admin/', fn)` und `UNAUTHORIZED($, 'admin')` im Handler |\n| `ROUTE('API /api/ -users_list *Users --> list')` | `ROUTE('API /api/ users_list --> Users/list')` |\n| `ROUTE('API /api/ +users_save *Users --> save')` | `ROUTE('API /api/ users_save --> Users/save')` |\n\nEine Route ohne Größen-Flag lehnt einen JSON-Body über 256 kB mit `431` ab, gib Routen, die große Datenmengen importieren, also ein eigenes Limit. Ein unbekannter `API`-Endpunkt antwortet mit `400` statt mit `404`. Siehe [Routing](../routing/).\n\nVorher:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail(id, order) {\n\tthis.json({ id: id, order: order, params: this.params });\n}\n```\n\nNachher:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail($) {\n\t$.json({ id: $.params.id, order: $.params.order, params: $.params });\n}\n```\n\n## Controller\n\nHandler erhalten den Controller als `$`. In HTTP-Routen ist `this` nicht mehr der Controller.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.status = 201` | `$.response.status = 201` |\n| `this.header('X-Version', '1')` | `$.response.headers['x-version'] = '1'` |\n| `this.nocache()` | `$.response.headers['cache-control'] = 'private, no-cache, no-store, max-age=0'` |\n| `this.content('<a>1</a>', 'text/xml')` | `$.xml('<a>1</a>')` |\n| `this.content('id;name', 'text/csv')` | `$.binary(Buffer.from('id;name'), 'text/csv')` |\n| `this.nocontent()` | `$.empty()` |\n| `this.throw404()`, `this.throw403()` | `$.fallback(404)`, `$.fallback(403)` |\n| `this.throw500('Problem')` | `$.fallback(500, 'Problem')` |\n| `this.file('docs/a.txt', 'report.txt')` | `$.file(PATH.public('docs/a.txt'), 'report.txt')` |\n| `this.success(true, 42)` | `$.success(42)` |\n| `this.success(false)` | `$.json({ success: false })` |\n| `this.invalid('email', 'Message')` | `var err = new ErrorBuilder(); err.push('Message', 'email'); $.invalid(err);` |\n| `file.isImage()` | `file.isImage` |\n| `this.mail(email, subject, view, model)` | `MAIL(email, subject, view, model)` |\n\nBei diesen Membern musst du nur `this` durch `$` ersetzen: `params`, `query`, `body`, `files`, `headers`, `url`, `ip`, `ua`, `mobile`, `robot`, `xhr`, `referrer`, `user`, `language`, `cookie()`, `hostname()`, `json()`, `plain()`, `view()`, `filefs()` und `stream(type, stream)`.\n\nEine Fehler-Route setzt den Status auf die gleiche Weise:\n\n```js\nexports.install = function() {\n\tROUTE('GET /missing/', missing);\n\tROUTE('GET /denied/', denied);\n\tROUTE('GET /broken/', broken);\n\tROUTE('#404', notfound);\n};\n\nfunction missing($) {\n\t$.fallback(404);\n}\n\nfunction denied($) {\n\t$.fallback(403);\n}\n\nfunction broken($) {\n\t$.fallback(500, 'Unexpected problem');\n}\n\nfunction notfound($) {\n\t$.response.status = 404;\n\t$.plain('My 404 page');\n}\n```\n\nSiehe [Controller](../controller/).\n\n## Views\n\nDie Syntax der View-Dateien ändert sich nicht: Ausdrücke, Bedingungen, Schleifen, Sections, Partial Views und Helper aus `DEF.helpers` funktionieren wie bisher.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.view('detail')` in `controllers/users.js` findet `views/users/detail.html` | `$.view('users/detail')`: Der Name beginnt immer in `views/` |\n| Das Layout kann `model` lesen | Setze `@{repository.name = model.name}` in der View und lies `repository` im Layout |\n| `this.title('Products')` | `@{title('Products')}` in der View |\n| `this.repository.page = 'list'` | `@{repository.page = 'list'}` in der View |\n| `VIEW('mail/order', model)` | `F.view('mail/order', model)`, mit `@{layout('')}` in der View |\n| Der Titel der Startseite erhält ` - ` und `CONF.name` | Der Titel der Startseite bleibt so, wie du ihn geschrieben hast |\n\nVorher:\n\n```html\n<title>@{model.name}</title>@{body}\n```\n\nNachher:\n\n```html\n<title>@{repository.name}</title>@{body}\n```\n\n```html\n@{repository.name = model.name}\n<h1>@{model.name}</h1>\n```\n\nSiehe [Views](../views/).\n\n## Middleware\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MIDDLEWARE('name', function($) { $.next(); })` | `NEWMIDDLEWARE('name', function($, next) { next(); })` |\n| `$.res.throw401()` | `$.invalid(401)` |\n| `$.res.setHeader('x-stamp', 'yes')` | `$.response.headers['x-stamp'] = 'yes'` |\n| `ROUTE('GET /private/', fn, ['#apikey'])` | `ROUTE('GET /private/ #apikey', fn)` |\n| `ROUTE('GET /open/ &stamp', fn)` | `ROUTE('GET /open/ #stamp', fn)` |\n| `USE('poweredby', ['web'])` | Drittes Argument `'routes'`, innerhalb von `ON('ready')` |\n\nVorher:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('x-server', 'myapp');\n\t$.next();\n});\n\nUSE('poweredby', ['web']);\n```\n\nNachher:\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('poweredby', function($, next) {\n\t\t$.response.headers['x-server'] = 'myapp';\n\t\tnext();\n\t}, 'routes');\n});\n```\n\nSiehe [Middleware](../middleware/).\n\n## WebSockets\n\nEine `SOCKET`-Route behält ihre Struktur, und `this` funktioniert in ihrem Handler weiterhin.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function room(name) {}` | `function room($) { var name = $.params.name; }` |\n| `ROUTE('SOCKET /feed/', fn, ['json'], 64)` | `ROUTE('SOCKET /feed/ <64kB', fn)` |\n| `ROUTE('SOCKET /terminal/', fn, ['text'])` | `ROUTE('SOCKET /terminal/ @text', fn)` |\n| `client.send(text)` auf einer Text-Route | `client.send(text, true)` |\n| `client.close('finished', 4000)` | `client.close(4000, 'finished')` |\n| Ein abgewiesener `+SOCKET`-Client verbindet sich und wird mit `4001` geschlossen | Der Handshake wird abgelehnt und der Client sieht `1006` |\n\nSiehe [WebSockets](../websockets/).\n\n## NoSQL\n\nVorhandene `.nosql`-Dateien lassen sich unverändert lesen. `insert()`, `find()`, `read()`, `update()`, `remove()`, `where()`, `search()`, `fields()`, `skip()`, `take()`, `first()` und das Update-Präfix `+field` ändern sich nicht.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `find()` beginnt mit dem ältesten Dokument | `find()` beginnt mit dem neuesten Dokument: Ergänze `sort()`, wenn die Reihenfolge wichtig ist |\n| `find2()` | `find()` |\n| `one()` | `read()` |\n| `sort('age_desc')` | `sort('age', true)` |\n| `NOSQL('users').count()` | `DATA.count('nosql/users')` |\n| `NOSQL('users').list()` | `DATA.list('nosql/users')` |\n| `rule('doc.age > arg.min', { min: 45 })` | `query('doc.age > 45')` |\n| `update({ '-score': 3 })` | `update({ '+score': -3 })` |\n| `TABLE('users')` | `NOSQL('users')` |\n\n`TABLE()` gibt es in Total.js 5 nicht, verschiebe die Zeilen aus `.table`-Dateien also selbst in eine NoSQL-Datenbank.\n\nVorher:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run() {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.one().where('id', '2').fields('name').promise();\n\tvar count = await db.count().where('age', '>', 35).promise();\n\tvar list = await db.list().sort('age_desc').fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().rule('doc.age > arg.min', { min: 45 }).fields('name').promise();\n\n\tawait db.update({ '-score': 3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\tthis.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nNachher:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run($) {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.read().where('id', '2').fields('name').promise();\n\tvar count = await DATA.count('nosql/users').where('age', '>', 35).promise();\n\tvar list = await DATA.list('nosql/users').sort('age', true).fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().query('doc.age > 45').fields('name').promise();\n\n\tawait db.update({ '+score': -3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\t$.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nSiehe [NoSQL-Datenbank](../nosql/).\n\n## RESTBuilder\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| Ein Status ab `400` ist nur mit `.strict()` ein Fehler | Ein Status ab `400` ist immer ein Fehler |\n| `.callback($.callback)` in einer Operation | `.callback($)` in einer Action |\n\nCode, der nach einer fehlgeschlagenen Anfrage `output.status` liest, muss zuerst `err` behandeln. Siehe [HTTP-Anfragen](../http-requests/).\n\n## Konfiguration\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `default_root` | `$root` |\n| `default_timezone` | `$timezone` |\n| `default_cookies_samesite` | `$cookiesamesite` |\n| `default_cookies_secure` | `$cookiesecure` |\n| `default_xpoweredby` | `$xpoweredby` |\n| `allow_custom_titles` | `$customtitles` |\n| `allow_gzip` | `$httpcompress` |\n| `limit : 50` ist eine Zahl | `limit (number) : 50`: Ohne Typ ist der Wert ein String |\n| `smtp (object) : { port: 465 }` | `smtp (json) : { \"port\": 465 }` |\n| `config-release` | Wird nicht geladen: Behalte die Werte in `config` |\n\nVorher:\n\n```text\nname                     : Shop\ndefault_root             : /app/\ndefault_timezone         : Europe/Bratislava\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\ndefault_xpoweredby       : MyServer\nallow_custom_titles      : true\nallow_gzip               : false\n```\n\nNachher:\n\n```text\nname            : Shop\n$root           : /app/\n$timezone       : Europe/Bratislava\n$cookiesamesite : Strict\n$cookiesecure   : true\n$xpoweredby     : MyServer\n$customtitles   : true\n$httpcompress   : false\n```\n\n`CORS()`, `name`, `(array)`-Werte und `mail_smtp_options` als JavaScript-Objekt funktionieren wie bisher. Siehe [Konfiguration](../configuration/).\n\n## Autorisierung\n\nDas Delegate `AUTH()`, die Routen-Flags `+` und `-` sowie `UNAUTHORIZED()` ändern sich nicht. `SESSION()` gibt es in Total.js 5 nicht: Verwende die eingebaute Session von `AUTH()`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SESSION()` mit `ondata` | `AUTH(opt)` mit `opt.onread` |\n| `session.setcookie($, options, callback)` | `opt.authcookie($, UID(), userid, '1 hour')` |\n| `session.remove2(userid)` und das Löschen des Cookies | `opt.logout($)` in einer Action |\n\nVorher:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\tnext(null, { id: meta.id, name: 'Peter' });\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 hour', key: 'session-key' }, 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\nMAIN.session = session;\n```\n\nNachher:\n\n```js\nvar opt = {};\n\nopt.secret = 'session-key';\nopt.cookie = 'sid';\nopt.expire = '1 hour';\n\nopt.onread = function(meta, next) {\n\tnext(null, { id: meta.userid, name: 'Peter' });\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\n```js\nNEWACTION('Account/logout', {\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.logout()` entfernt die Session aus dem Speicher und löscht das Cookie. Eine gespeicherte Kopie des Tokens ist signiert und wird deshalb wieder akzeptiert, sobald `onread` einen Benutzer zurückgibt. Prüfe die Session innerhalb von `onread` in deiner Datenbank, wenn die Abmeldung das Token widerrufen muss. Siehe [Autorisierung](../authorization/).\n\n## Lokalisierung\n\nRessourcendateien und `@(Text)` in Views bleiben gleich, und die erzeugten Schlüssel sind identisch.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `LOCALIZE(function(req, res) {})` | `LOCALIZE(function($) {})` |\n| `RESOURCE('sk', 'title')` | `F.resource('sk', 'title')` |\n| `TRANSLATOR('sk', '<b>@(Welcome)</b>')` | `TRANSLATE('sk', '<b>@(Welcome)</b>')` |\n| `TRANSLATE('sk', 'Welcome')` | `TRANSLATE('sk', '@(Welcome)')` |\n\nSiehe [Lokalisierung](../localization/).\n\n## Mail\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MAIL()` rendert die View ohne Layout | `MAIL()` rendert die View in `views/layout.html` |\n| `ON('mail', fn)` | `ON('$mail', fn)` |\n| `message.address_to` | `message.email_to` |\n\nBeginne jede Mail-View mit `@{layout('')}`. Ohne diese Zeile wird die Nachricht in das Layout deiner Website eingebettet, und wenn `views/layout.html` nicht existiert, wird die Nachricht gar nicht versendet.\n\nVorher:\n\n```html\n<p>Hello @{model.name}</p>\n```\n\nNachher:\n\n```html\n@{layout('')}\n<p>Hello @{model.name}</p>\n```\n\nSiehe [E-Mails versenden](../mail/).\n\n## Dateispeicher\n\nDie Argumente von `save()` ändern ihre Reihenfolge: Die benutzerdefinierten Daten stehen jetzt vor dem Callback.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `fs.save(id, name, data, callback, custom)` | `fs.save(id, name, data, custom, callback)` |\n\n`read()` und `$.filefs()` ändern sich nicht. Siehe [Dateispeicher](../file-storage/).\n\n## Zeitplanung\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SCHEDULE('* * * * *', fn)` | `CRON('* * * * *', fn)` |\n| `SCHEDULE('03:00', '1 day', fn)` | `CRON('0 3 * * *', fn)` |\n\nVorher:\n\n```js\nMAIN.runs = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nNachher:\n\n```js\nMAIN.runs = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nSiehe [Zeitplanung und Ereignisse](../scheduling-and-events/).\n\n## Operations und Tasks\n\n`NEWOPERATION()`, `OPERATION()`, `RUN()`, `NEWTASK()` und `TASK()` gibt es in Total.js 5 nicht. Jede Operation wird zu einer Action, und die Schritte eines Tasks werden zu einer Action oder zu mehreren Actions, die du nacheinander aufrufst.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `NEWOPERATION('order_price', fn)` | `NEWACTION('order_price', { input: '...', action: fn })` |\n| `OPERATION('order_price', value, callback)` | `ACTION('order_price', value).callback(callback)` |\n| `RUN('order_check, order_price', value, callback)` | `await ACTION(...).promise($)` für jeden Schritt |\n| `NEWTASK('order', fn)` und `TASK('order/check', ...)` | `NEWACTION('order', { action: fn })` |\n\nVorher:\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order() {\n\tvar self = this;\n\tOPERATION('order_price', self.body, function(err, response) {\n\t\tself.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nfunction chain() {\n\tvar self = this;\n\tRUN('order_check, order_price', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.order_price);\n\t});\n}\n```\n\nNachher:\n\n```js\nNEWACTION('order_check', {\n\tinput: '*email:String, count:Number',\n\taction: function($, model) {\n\t\tmodel.email = model.email.toLowerCase();\n\t\t$.callback(model);\n\t}\n});\n\nNEWACTION('order_price', {\n\tinput: 'email:String, count:Number',\n\taction: function($, model) {\n\t\t$.callback({ email: model.email, price: model.count * 10 });\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order($) {\n\tACTION('order_price', $.body).callback(function(err, response) {\n\t\t$.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nasync function chain($) {\n\tvar model = await ACTION('order_check', $.body).promise($);\n\t$.json(await ACTION('order_price', model).promise($));\n}\n```\n\nSiehe [Actions](../actions/).\n\n## Module, Modelle und Definitionen\n\nDateien in `definitions/` und `modules/` werden wie bisher geladen, und `MAIN`, `FUNC`, `PATH` und `ON('ready')` ändern sich nicht.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MODULE('greeter').greet('Peter')` | `MODS.greeter.greet('Peter')` |\n| `MODEL('price').total(2, 5)` | `require(PATH.root('models/price.js')).total(2, 5)` |\n| `CACHE('products', value, '5 minutes')` | `CACHE.set('products', value, '5 minutes')` |\n| `CACHE('products')` | `CACHE.read('products')` |\n\nSiehe [Anwendungsstruktur](../application-structure/).\n\n## Unit-Tests\n\n`TESTER()` wird durch das Objekt `Test` aus `total5/test` ersetzt.\n\nVorher:\n\n```js\nrequire('total4');\n\nTESTER(function(group, start) {\n\n\tgroup('Strings', function(test) {\n\n\t\ttest('slug()', function(next) {\n\t\t\tnext('Hello World'.slug() === 'hello-world' ? undefined : 'Unexpected slug');\n\t\t});\n\n\t\ttest('capitalize()', function(next) {\n\t\t\tnext('total'.capitalize() === 'Total' ? undefined : 'Unexpected value');\n\t\t});\n\n\t});\n\n\tstart();\n});\n```\n\nNachher:\n\n```js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nSiehe [Unit-Tests](../unit-tests/).\n\n## Kommandozeile\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `total4 translate` | `total5 translate \"$PWD/translate.resource\"` |\n\nGib `total5 translate` den vollständigen Path der Ausgabedatei an. Siehe [Kommandozeile](../command-line/).\n\n## Eine vollständige Anwendung\n\nDiese kleine Notizen-Anwendung hat eine öffentliche Liste, geschützte Schreibzugriffe, eine Startseite, eine Benachrichtigungs-Mail, einen Live-WebSocket-Kanal und einen Job, der jede Minute läuft. Beide Versionen beantworten dieselben Anfragen auf dieselbe Weise, mit Ausnahme des Titels der Startseite, der unter [Views](#views) beschrieben ist.\n\n### Total.js 4\n\n`index.js`\n\n```js\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\n`config`\n\n```text\nname              : Notes\napitoken          : secret\nmail_notify       : admin@example.com\nmail_from         : notes@example.com\nmail_smtp         : 127.0.0.1\nmail_smtp_options : { port: 19854 }\nmaxnotes          : 100\n```\n\n`definitions/auth.js`\n\n```js\nAUTH(function($) {\n\tif ($.headers['x-token'] === CONF.apitoken)\n\t\t$.success({ id: '1', name: 'Admin' });\n\telse\n\t\t$.invalid();\n});\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`schemas/notes.js`\n\n```js\nNEWSCHEMA('Notes', function(schema) {\n\n\tschema.define('title', 'String(50)', value => value && value !== 'spam', 'This title is not allowed');\n\tschema.define('body', 'String(500)');\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('notes').find().sort('dtcreated_desc').fields('id,title').take(CONF.maxnotes).callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('notes').read().id($.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t});\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t});\n\n\tschema.setRemove(function($) {\n\t\tNOSQL('notes').remove().id($.id).callback($.done());\n\t});\n\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        *Notes --> query');\n\tROUTE('GET     /api/notes/{id}/   *Notes --> read');\n\tROUTE('+POST   /api/notes/        *Notes --> insert');\n\tROUTE('+DELETE /api/notes/{id}/   *Notes --> remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats() {\n\tthis.json({ ticks: MAIN.ticks });\n}\n\nfunction live() {\n\tMAIN.live = this;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tvar self = this;\n\tself.title('Latest notes');\n\tNOSQL('notes').find().sort('dtcreated_desc').fields('title').callback(function(err, notes) {\n\t\tself.view('index', notes);\n\t});\n}\n```\n\n`views/layout.html`\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`views/index.html`\n\n```html\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n<p>New note: @{model.title}</p>\n```\n\n### Total.js 5\n\n`definitions/auth.js` und `views/layout.html` bleiben gleich.\n\n`index.js`\n\n```js\nrequire('total5');\n\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\n`config`\n\n```text\nname                : Notes\napitoken            : secret\nmail_notify         : admin@example.com\nmail_from           : notes@example.com\nmail_smtp           : 127.0.0.1\nmail_smtp_options   : { port: 19854 }\nmaxnotes (number)   : 100\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`actions/notes.js`\n\n```js\nNEWACTION('Notes/query', {\n\taction: function($) {\n\t\tNOSQL('notes').find().sort('dtcreated', true).fields('id,title').take(CONF.maxnotes).callback($);\n\t}\n});\n\nNEWACTION('Notes/read', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').read().id($.params.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/insert', {\n\tinput: '*title:String(50), body:String(500)',\n\taction: function($, model) {\n\n\t\tif (model.title === 'spam') {\n\t\t\t$.invalid('This title is not allowed', 'title');\n\t\t\treturn;\n\t\t}\n\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/remove', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').remove().id($.params.id).callback($.done());\n\t}\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        --> Notes/query');\n\tROUTE('GET     /api/notes/{id}/   --> Notes/read');\n\tROUTE('+POST   /api/notes/        --> Notes/insert');\n\tROUTE('+DELETE /api/notes/{id}/   --> Notes/remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats($) {\n\t$.json({ ticks: MAIN.ticks });\n}\n\nfunction live($) {\n\tMAIN.live = $;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index($) {\n\tNOSQL('notes').find().sort('dtcreated', true).fields('title').callback(function(err, notes) {\n\t\t$.view('index', notes);\n\t});\n}\n```\n\n`views/index.html`\n\n```html\n@{title('Latest notes')}\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n@{layout('')}\n<p>New note: @{model.title}</p>\n```\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:59.647Z"}
{"id":"JanG8G22Z61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/migrating-from-total4/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Migrar desde Total.js 4","summary":"Lleva una aplicación de Total.js 4 a Total.js 5, área por área, con el código antes y después de cada cambio.","markdown":"---\ntitle: Migrar desde Total.js 4\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/migrating-from-total4/\nupdated: 2026-11-18T16:59:59.647Z\n---\n\n# Migrar desde Total.js 4\n\n> Lleva una aplicación de Total.js 4 a Total.js 5, área por área, con el código antes y después de cada cambio.\n\nEsta guía lleva una aplicación de Total.js 4 a Total.js 5. Enumera lo que tienes que cambiar en cada área, con el código antiguo junto a su sustituto, y termina con una pequeña aplicación mostrada en las dos versiones.\n\n## Orden de trabajo recomendado\n\n1. Sustituye el paquete `total4` por `total5` y actualiza el [script de inicio](#start-script).\n2. Renombra las [claves de configuración](#configuration) y añade tipos a los valores numéricos.\n3. Convierte los [esquemas en acciones](#schemas-and-actions) y actualiza las rutas que los llaman.\n4. Sustituye `this` por `$` en las [rutas y controladores](#routes) y en el [middleware](#middleware).\n5. Revisa las [vistas](#views) y las [vistas de correo](#mail): carpetas, layouts y títulos.\n6. Actualiza las consultas [NoSQL](#nosql), la gestión de errores de [RESTBuilder](#restbuilder), los [WebSockets](#websockets) y el [almacenamiento de archivos](#file-storage).\n7. Sustituye [`SCHEDULE()`](#scheduling), las [operaciones y tareas](#operations-and-tasks), y las [llamadas](#modules-models-and-definitions) a `MODULE()` y `MODEL()`.\n8. Reescribe las [pruebas unitarias](#unit-tests) y ejecuta la aplicación.\n\n## Script de inicio\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `npm install total4` | `npm install total5@beta` |\n| `require('total4/debug')(options)` | `require('total5'); Total.run(options)` |\n| `require('total4/release')(options)` | `options.release = true; Total.run(options)` |\n\nAntes:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.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\nDespués:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\nLos dos scripts arrancan en modo de depuración, y en modo release con `node index.js --release`. Consulta [Instalación](../installation/).\n\n## Esquemas y acciones\n\n`schema.define()` y la familia de `schema.setInsert()` no existen en Total.js 5. Un esquema sin cambios detiene la aplicación al arrancar con `TypeError: schema.define is not a function`. Mueve cada operación a un `NEWACTION()` en la carpeta `actions/` y declara sus campos en `input`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `schema.define('name', 'String(30)', true)` | `input: '*name:String(30)'` |\n| `schema.define('role', ['admin', 'user'])` | `input: 'role:{admin\\|user}'` |\n| `schema.setInsert(fn)`, `setQuery(fn)`, `setRead(fn)`... | `NEWACTION('Users/insert', { action: fn })` |\n| `ROUTE('POST /api/users/ *Users --> insert')` | `ROUTE('POST /api/users/ --> Users/insert')` |\n| `$.id` | `params: '*id:String'` y `$.params.id` |\n| `.callback($.callback)` | `.callback($)` |\n| `$.invalid('age', 'Message')` | `$.invalid('Message', 'age')` |\n| `CALL('Math --> double', data)` | `ACTION('Math/double', data)` |\n\nAntes:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(30)', 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 = 'A1';\n\t\t$.success(model);\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ *Users --> insert');\n};\n```\n\nDespués:\n\n```js\nNEWACTION('Users/insert', {\n\tinput: '*name:String(30), *email:Email, age:Number, role:{admin|user}',\n\taction: function($, model) {\n\t\tmodel.id = 'A1';\n\t\t$.success(model);\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ --> Users/insert');\n};\n```\n\n### Validadores personalizados\n\nUna función de validación de `schema.define()` pasa a la acción.\n\nAntes:\n\n```js\nNEWSCHEMA('Signup', function(schema) {\n\n\tschema.define('name', 'String(30)', true);\n\tschema.define('age', Number, value => value >= 18, 'You must be an adult');\n\n\tschema.setInsert(function($, model) {\n\t\t$.success(model.age);\n\t});\n\n});\n```\n\nDespués:\n\n```js\nNEWACTION('Signup/insert', {\n\tinput: '*name:String(30), age:Number',\n\taction: function($, model) {\n\n\t\tif (model.age < 18) {\n\t\t\t$.invalid('You must be an adult', 'age');\n\t\t\treturn;\n\t\t}\n\n\t\t$.success(model.age);\n\t}\n});\n```\n\n### Esquemas que ya usan `schema.action()`\n\nEstos esquemas siguen funcionando. Solo cambia la ruta: `*Tags --> list` pasa a ser `--> Tags/list`.\n\n```js\nNEWSCHEMA('Tags', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of tags',\n\t\tquery: 'limit:Number',\n\t\taction: function($) {\n\t\t\t$.callback(['a', 'b', 'c'].slice(0, $.query.limit || 3));\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a tag',\n\t\tinput: '*name:String(20)',\n\t\taction: function($, model) {\n\t\t\t$.success(model.name);\n\t\t}\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('GET  /api/tags/ --> Tags/list');\n\tROUTE('POST /api/tags/ --> Tags/create');\n};\n```\n\n### Valores y errores que notarán tus clientes\n\n| Caso | Total.js 4 | Total.js 5 |\n| --- | --- | --- |\n| Falta un `Number` opcional | El campo vale `0` | El campo se omite |\n| Falta un enum opcional | El campo se omite | El campo vale `''` |\n| El valor del enum no está en la lista | Se descarta el valor y se acepta la petición | `400` con un error para el campo |\n| Claves de un error de campo obligatorio | `name`, `error`, `path`, `prefix` | `name`, `error`, `path` |\n| Claves de un error de `$.invalid()` con un campo | `name`, `error` | `error`, `path` |\n\nUn cliente que lea `name` de tus propios errores tiene que leer `path` en su lugar. Consulta [Acciones](../actions/) y [Esquemas JSON](../json-schemas/).\n\n## Rutas\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function detail(id) { this.json({ id: id }); }` | `function detail($) { $.json({ id: $.params.id }); }` |\n| `ROUTE('/about/', fn)` | `ROUTE('GET /about/', fn)`: el método es obligatorio |\n| `{page:number}` convierte el valor | `{page}` es una cadena: `$.params.page.parseInt()` |\n| `ROUTE('POST /upload/', fn, ['upload'], 1024)` | `ROUTE('POST /upload/ @upload <1MB', fn)` |\n| `ROUTE('POST /import/', fn, 1024)` | `ROUTE('POST /import/ <1MB', fn)` |\n| `ROUTE('+GET /admin/ @admin', fn)` | `ROUTE('+GET /admin/', fn)` y `UNAUTHORIZED($, 'admin')` en el manejador |\n| `ROUTE('API /api/ -users_list *Users --> list')` | `ROUTE('API /api/ users_list --> Users/list')` |\n| `ROUTE('API /api/ +users_save *Users --> save')` | `ROUTE('API /api/ users_save --> Users/save')` |\n\nUna ruta sin flag de tamaño rechaza con `431` un cuerpo JSON de más de 256 kB, así que da un límite propio a las rutas que importan muchos datos. Un endpoint `API` desconocido responde `400` en lugar de `404`. Consulta [Enrutamiento](../routing/).\n\nAntes:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail(id, order) {\n\tthis.json({ id: id, order: order, params: this.params });\n}\n```\n\nDespués:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail($) {\n\t$.json({ id: $.params.id, order: $.params.order, params: $.params });\n}\n```\n\n## Controladores\n\nLos manejadores reciben el controlador como `$`. En las rutas HTTP, `this` ya no es el controlador.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.status = 201` | `$.response.status = 201` |\n| `this.header('X-Version', '1')` | `$.response.headers['x-version'] = '1'` |\n| `this.nocache()` | `$.response.headers['cache-control'] = 'private, no-cache, no-store, max-age=0'` |\n| `this.content('<a>1</a>', 'text/xml')` | `$.xml('<a>1</a>')` |\n| `this.content('id;name', 'text/csv')` | `$.binary(Buffer.from('id;name'), 'text/csv')` |\n| `this.nocontent()` | `$.empty()` |\n| `this.throw404()`, `this.throw403()` | `$.fallback(404)`, `$.fallback(403)` |\n| `this.throw500('Problem')` | `$.fallback(500, 'Problem')` |\n| `this.file('docs/a.txt', 'report.txt')` | `$.file(PATH.public('docs/a.txt'), 'report.txt')` |\n| `this.success(true, 42)` | `$.success(42)` |\n| `this.success(false)` | `$.json({ success: false })` |\n| `this.invalid('email', 'Message')` | `var err = new ErrorBuilder(); err.push('Message', 'email'); $.invalid(err);` |\n| `file.isImage()` | `file.isImage` |\n| `this.mail(email, subject, view, model)` | `MAIL(email, subject, view, model)` |\n\nEn estos miembros basta con sustituir `this` por `$`: `params`, `query`, `body`, `files`, `headers`, `url`, `ip`, `ua`, `mobile`, `robot`, `xhr`, `referrer`, `user`, `language`, `cookie()`, `hostname()`, `json()`, `plain()`, `view()`, `filefs()` y `stream(type, stream)`.\n\nUna ruta de error establece el estado de la misma manera:\n\n```js\nexports.install = function() {\n\tROUTE('GET /missing/', missing);\n\tROUTE('GET /denied/', denied);\n\tROUTE('GET /broken/', broken);\n\tROUTE('#404', notfound);\n};\n\nfunction missing($) {\n\t$.fallback(404);\n}\n\nfunction denied($) {\n\t$.fallback(403);\n}\n\nfunction broken($) {\n\t$.fallback(500, 'Unexpected problem');\n}\n\nfunction notfound($) {\n\t$.response.status = 404;\n\t$.plain('My 404 page');\n}\n```\n\nConsulta [Controlador](../controller/).\n\n## Vistas\n\nLa sintaxis de los archivos de vista no cambia: las expresiones, condiciones, bucles, secciones, vistas parciales y helpers de `DEF.helpers` funcionan como antes.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.view('detail')` en `controllers/users.js` encuentra `views/users/detail.html` | `$.view('users/detail')`: el nombre siempre parte de `views/` |\n| El layout puede leer `model` | Establece `@{repository.name = model.name}` en la vista y lee `repository` en el layout |\n| `this.title('Products')` | `@{title('Products')}` en la vista |\n| `this.repository.page = 'list'` | `@{repository.page = 'list'}` en la vista |\n| `VIEW('mail/order', model)` | `F.view('mail/order', model)`, con `@{layout('')}` en la vista |\n| Al título de la página de inicio se le añaden ` - ` y `CONF.name` | El título de la página de inicio se queda tal como lo escribiste |\n\nAntes:\n\n```html\n<title>@{model.name}</title>@{body}\n```\n\nDespués:\n\n```html\n<title>@{repository.name}</title>@{body}\n```\n\n```html\n@{repository.name = model.name}\n<h1>@{model.name}</h1>\n```\n\nConsulta [Vistas](../views/).\n\n## Middleware\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MIDDLEWARE('name', function($) { $.next(); })` | `NEWMIDDLEWARE('name', function($, next) { next(); })` |\n| `$.res.throw401()` | `$.invalid(401)` |\n| `$.res.setHeader('x-stamp', 'yes')` | `$.response.headers['x-stamp'] = 'yes'` |\n| `ROUTE('GET /private/', fn, ['#apikey'])` | `ROUTE('GET /private/ #apikey', fn)` |\n| `ROUTE('GET /open/ &stamp', fn)` | `ROUTE('GET /open/ #stamp', fn)` |\n| `USE('poweredby', ['web'])` | Tercer argumento `'routes'`, dentro de `ON('ready')` |\n\nAntes:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('x-server', 'myapp');\n\t$.next();\n});\n\nUSE('poweredby', ['web']);\n```\n\nDespués:\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('poweredby', function($, next) {\n\t\t$.response.headers['x-server'] = 'myapp';\n\t\tnext();\n\t}, 'routes');\n});\n```\n\nConsulta [Middleware](../middleware/).\n\n## WebSockets\n\nUna ruta `SOCKET` mantiene su estructura, y `this` sigue funcionando dentro de su manejador.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function room(name) {}` | `function room($) { var name = $.params.name; }` |\n| `ROUTE('SOCKET /feed/', fn, ['json'], 64)` | `ROUTE('SOCKET /feed/ <64kB', fn)` |\n| `ROUTE('SOCKET /terminal/', fn, ['text'])` | `ROUTE('SOCKET /terminal/ @text', fn)` |\n| `client.send(text)` en una ruta de texto | `client.send(text, true)` |\n| `client.close('finished', 4000)` | `client.close(4000, 'finished')` |\n| Un cliente `+SOCKET` rechazado se conecta y se cierra con `4001` | Se rechaza el handshake y el cliente ve `1006` |\n\nConsulta [WebSockets](../websockets/).\n\n## NoSQL\n\nLos archivos `.nosql` existentes se pueden leer tal cual. `insert()`, `find()`, `read()`, `update()`, `remove()`, `where()`, `search()`, `fields()`, `skip()`, `take()`, `first()` y el prefijo de actualización `+field` no cambian.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `find()` empieza por el documento más antiguo | `find()` empieza por el documento más reciente: añade `sort()` cuando importe el orden |\n| `find2()` | `find()` |\n| `one()` | `read()` |\n| `sort('age_desc')` | `sort('age', true)` |\n| `NOSQL('users').count()` | `DATA.count('nosql/users')` |\n| `NOSQL('users').list()` | `DATA.list('nosql/users')` |\n| `rule('doc.age > arg.min', { min: 45 })` | `query('doc.age > 45')` |\n| `update({ '-score': 3 })` | `update({ '+score': -3 })` |\n| `TABLE('users')` | `NOSQL('users')` |\n\n`TABLE()` no existe en Total.js 5, así que tendrás que mover tú mismo las filas de los archivos `.table` a una base de datos NoSQL.\n\nAntes:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run() {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.one().where('id', '2').fields('name').promise();\n\tvar count = await db.count().where('age', '>', 35).promise();\n\tvar list = await db.list().sort('age_desc').fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().rule('doc.age > arg.min', { min: 45 }).fields('name').promise();\n\n\tawait db.update({ '-score': 3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\tthis.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nDespués:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run($) {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.read().where('id', '2').fields('name').promise();\n\tvar count = await DATA.count('nosql/users').where('age', '>', 35).promise();\n\tvar list = await DATA.list('nosql/users').sort('age', true).fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().query('doc.age > 45').fields('name').promise();\n\n\tawait db.update({ '+score': -3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\t$.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nConsulta [Base de datos NoSQL](../nosql/).\n\n## RESTBuilder\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| Un estado de `400` o superior solo es un error con `.strict()` | Un estado de `400` o superior siempre es un error |\n| `.callback($.callback)` en una operación | `.callback($)` en una acción |\n\nEl código que lee `output.status` después de una petición fallida tiene que gestionar antes `err`. Consulta [Peticiones HTTP](../http-requests/).\n\n## Configuración\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `default_root` | `$root` |\n| `default_timezone` | `$timezone` |\n| `default_cookies_samesite` | `$cookiesamesite` |\n| `default_cookies_secure` | `$cookiesecure` |\n| `default_xpoweredby` | `$xpoweredby` |\n| `allow_custom_titles` | `$customtitles` |\n| `allow_gzip` | `$httpcompress` |\n| `limit : 50` es un número | `limit (number) : 50`: sin tipo, el valor es una cadena |\n| `smtp (object) : { port: 465 }` | `smtp (json) : { \"port\": 465 }` |\n| `config-release` | No se carga: guarda los valores en `config` |\n\nAntes:\n\n```text\nname                     : Shop\ndefault_root             : /app/\ndefault_timezone         : Europe/Bratislava\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\ndefault_xpoweredby       : MyServer\nallow_custom_titles      : true\nallow_gzip               : false\n```\n\nDespués:\n\n```text\nname            : Shop\n$root           : /app/\n$timezone       : Europe/Bratislava\n$cookiesamesite : Strict\n$cookiesecure   : true\n$xpoweredby     : MyServer\n$customtitles   : true\n$httpcompress   : false\n```\n\n`CORS()`, `name`, los valores `(array)` y `mail_smtp_options` escrito como objeto JavaScript funcionan como antes. Consulta [Configuración](../configuration/).\n\n## Autorización\n\nEl delegate `AUTH()`, los flags de ruta `+` y `-` y `UNAUTHORIZED()` no cambian. `SESSION()` no existe en Total.js 5: usa la sesión integrada de `AUTH()`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SESSION()` con `ondata` | `AUTH(opt)` con `opt.onread` |\n| `session.setcookie($, options, callback)` | `opt.authcookie($, UID(), userid, '1 hour')` |\n| `session.remove2(userid)` y borrar la cookie | `opt.logout($)` en una acción |\n\nAntes:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\tnext(null, { id: meta.id, name: 'Peter' });\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 hour', key: 'session-key' }, 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\nMAIN.session = session;\n```\n\nDespués:\n\n```js\nvar opt = {};\n\nopt.secret = 'session-key';\nopt.cookie = 'sid';\nopt.expire = '1 hour';\n\nopt.onread = function(meta, next) {\n\tnext(null, { id: meta.userid, name: 'Peter' });\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\n```js\nNEWACTION('Account/logout', {\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.logout()` elimina la sesión de la memoria y borra la cookie. Una copia guardada del token está firmada, así que se vuelve a aceptar siempre que `onread` devuelva un usuario. Comprueba la sesión en tu base de datos dentro de `onread` cuando cerrar la sesión tenga que revocar el token. Consulta [Autorización](../authorization/).\n\n## Localización\n\nLos archivos de recursos y `@(Text)` en las vistas siguen igual, y las claves generadas son idénticas.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `LOCALIZE(function(req, res) {})` | `LOCALIZE(function($) {})` |\n| `RESOURCE('sk', 'title')` | `F.resource('sk', 'title')` |\n| `TRANSLATOR('sk', '<b>@(Welcome)</b>')` | `TRANSLATE('sk', '<b>@(Welcome)</b>')` |\n| `TRANSLATE('sk', 'Welcome')` | `TRANSLATE('sk', '@(Welcome)')` |\n\nConsulta [Localización](../localization/).\n\n## Correo\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MAIL()` renderiza la vista sin layout | `MAIL()` renderiza la vista dentro de `views/layout.html` |\n| `ON('mail', fn)` | `ON('$mail', fn)` |\n| `message.address_to` | `message.email_to` |\n\nEmpieza cada vista de correo con `@{layout('')}`. Sin esto, el mensaje se envuelve en el layout de tu sitio y, si `views/layout.html` no existe, el mensaje no llega a enviarse.\n\nAntes:\n\n```html\n<p>Hello @{model.name}</p>\n```\n\nDespués:\n\n```html\n@{layout('')}\n<p>Hello @{model.name}</p>\n```\n\nConsulta [Envío de correo](../mail/).\n\n## Almacenamiento de archivos\n\nLos argumentos de `save()` cambian de orden: los datos personalizados ahora van antes del callback.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `fs.save(id, name, data, callback, custom)` | `fs.save(id, name, data, custom, callback)` |\n\n`read()` y `$.filefs()` no cambian. Consulta [Almacenamiento de archivos](../file-storage/).\n\n## Programación de tareas\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SCHEDULE('* * * * *', fn)` | `CRON('* * * * *', fn)` |\n| `SCHEDULE('03:00', '1 day', fn)` | `CRON('0 3 * * *', fn)` |\n\nAntes:\n\n```js\nMAIN.runs = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nDespués:\n\n```js\nMAIN.runs = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nConsulta [Programación de tareas y eventos](../scheduling-and-events/).\n\n## Operaciones y tareas\n\n`NEWOPERATION()`, `OPERATION()`, `RUN()`, `NEWTASK()` y `TASK()` no existen en Total.js 5. Cada operación se convierte en una acción, y los pasos de una tarea se convierten en una acción o en varias acciones llamadas en secuencia.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `NEWOPERATION('order_price', fn)` | `NEWACTION('order_price', { input: '...', action: fn })` |\n| `OPERATION('order_price', value, callback)` | `ACTION('order_price', value).callback(callback)` |\n| `RUN('order_check, order_price', value, callback)` | `await ACTION(...).promise($)` para cada paso |\n| `NEWTASK('order', fn)` y `TASK('order/check', ...)` | `NEWACTION('order', { action: fn })` |\n\nAntes:\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order() {\n\tvar self = this;\n\tOPERATION('order_price', self.body, function(err, response) {\n\t\tself.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nfunction chain() {\n\tvar self = this;\n\tRUN('order_check, order_price', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.order_price);\n\t});\n}\n```\n\nDespués:\n\n```js\nNEWACTION('order_check', {\n\tinput: '*email:String, count:Number',\n\taction: function($, model) {\n\t\tmodel.email = model.email.toLowerCase();\n\t\t$.callback(model);\n\t}\n});\n\nNEWACTION('order_price', {\n\tinput: 'email:String, count:Number',\n\taction: function($, model) {\n\t\t$.callback({ email: model.email, price: model.count * 10 });\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order($) {\n\tACTION('order_price', $.body).callback(function(err, response) {\n\t\t$.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nasync function chain($) {\n\tvar model = await ACTION('order_check', $.body).promise($);\n\t$.json(await ACTION('order_price', model).promise($));\n}\n```\n\nConsulta [Acciones](../actions/).\n\n## Módulos, modelos y definiciones\n\nLos archivos de `definitions/` y `modules/` se cargan como antes, y `MAIN`, `FUNC`, `PATH` y `ON('ready')` no cambian.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MODULE('greeter').greet('Peter')` | `MODS.greeter.greet('Peter')` |\n| `MODEL('price').total(2, 5)` | `require(PATH.root('models/price.js')).total(2, 5)` |\n| `CACHE('products', value, '5 minutes')` | `CACHE.set('products', value, '5 minutes')` |\n| `CACHE('products')` | `CACHE.read('products')` |\n\nConsulta [Estructura de la aplicación](../application-structure/).\n\n## Pruebas unitarias\n\n`TESTER()` se sustituye por el objeto `Test` de `total5/test`.\n\nAntes:\n\n```js\nrequire('total4');\n\nTESTER(function(group, start) {\n\n\tgroup('Strings', function(test) {\n\n\t\ttest('slug()', function(next) {\n\t\t\tnext('Hello World'.slug() === 'hello-world' ? undefined : 'Unexpected slug');\n\t\t});\n\n\t\ttest('capitalize()', function(next) {\n\t\t\tnext('total'.capitalize() === 'Total' ? undefined : 'Unexpected value');\n\t\t});\n\n\t});\n\n\tstart();\n});\n```\n\nDespués:\n\n```js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nConsulta [Pruebas unitarias](../unit-tests/).\n\n## Línea de comandos\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `total4 translate` | `total5 translate \"$PWD/translate.resource\"` |\n\nIndica a `total5 translate` el path completo del archivo de salida. Consulta [Línea de comandos](../command-line/).\n\n## Una aplicación completa\n\nEsta pequeña aplicación de notas tiene una lista pública, escrituras protegidas, una página de inicio, un correo de notificación, un canal WebSocket en directo y un trabajo que se ejecuta cada minuto. Las dos versiones responden a las mismas peticiones de la misma manera, salvo por el título de la página de inicio descrito en [Vistas](#views).\n\n### Total.js 4\n\n`index.js`\n\n```js\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\n`config`\n\n```text\nname              : Notes\napitoken          : secret\nmail_notify       : admin@example.com\nmail_from         : notes@example.com\nmail_smtp         : 127.0.0.1\nmail_smtp_options : { port: 19854 }\nmaxnotes          : 100\n```\n\n`definitions/auth.js`\n\n```js\nAUTH(function($) {\n\tif ($.headers['x-token'] === CONF.apitoken)\n\t\t$.success({ id: '1', name: 'Admin' });\n\telse\n\t\t$.invalid();\n});\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`schemas/notes.js`\n\n```js\nNEWSCHEMA('Notes', function(schema) {\n\n\tschema.define('title', 'String(50)', value => value && value !== 'spam', 'This title is not allowed');\n\tschema.define('body', 'String(500)');\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('notes').find().sort('dtcreated_desc').fields('id,title').take(CONF.maxnotes).callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('notes').read().id($.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t});\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t});\n\n\tschema.setRemove(function($) {\n\t\tNOSQL('notes').remove().id($.id).callback($.done());\n\t});\n\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        *Notes --> query');\n\tROUTE('GET     /api/notes/{id}/   *Notes --> read');\n\tROUTE('+POST   /api/notes/        *Notes --> insert');\n\tROUTE('+DELETE /api/notes/{id}/   *Notes --> remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats() {\n\tthis.json({ ticks: MAIN.ticks });\n}\n\nfunction live() {\n\tMAIN.live = this;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tvar self = this;\n\tself.title('Latest notes');\n\tNOSQL('notes').find().sort('dtcreated_desc').fields('title').callback(function(err, notes) {\n\t\tself.view('index', notes);\n\t});\n}\n```\n\n`views/layout.html`\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`views/index.html`\n\n```html\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n<p>New note: @{model.title}</p>\n```\n\n### Total.js 5\n\n`definitions/auth.js` y `views/layout.html` siguen igual.\n\n`index.js`\n\n```js\nrequire('total5');\n\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\n`config`\n\n```text\nname                : Notes\napitoken            : secret\nmail_notify         : admin@example.com\nmail_from           : notes@example.com\nmail_smtp           : 127.0.0.1\nmail_smtp_options   : { port: 19854 }\nmaxnotes (number)   : 100\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`actions/notes.js`\n\n```js\nNEWACTION('Notes/query', {\n\taction: function($) {\n\t\tNOSQL('notes').find().sort('dtcreated', true).fields('id,title').take(CONF.maxnotes).callback($);\n\t}\n});\n\nNEWACTION('Notes/read', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').read().id($.params.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/insert', {\n\tinput: '*title:String(50), body:String(500)',\n\taction: function($, model) {\n\n\t\tif (model.title === 'spam') {\n\t\t\t$.invalid('This title is not allowed', 'title');\n\t\t\treturn;\n\t\t}\n\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/remove', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').remove().id($.params.id).callback($.done());\n\t}\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        --> Notes/query');\n\tROUTE('GET     /api/notes/{id}/   --> Notes/read');\n\tROUTE('+POST   /api/notes/        --> Notes/insert');\n\tROUTE('+DELETE /api/notes/{id}/   --> Notes/remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats($) {\n\t$.json({ ticks: MAIN.ticks });\n}\n\nfunction live($) {\n\tMAIN.live = $;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index($) {\n\tNOSQL('notes').find().sort('dtcreated', true).fields('title').callback(function(err, notes) {\n\t\t$.view('index', notes);\n\t});\n}\n```\n\n`views/index.html`\n\n```html\n@{title('Latest notes')}\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n@{layout('')}\n<p>New note: @{model.title}</p>\n```\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:59.647Z"}
{"id":"JanG8G22Z61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/migrating-from-total4/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Migrer depuis Total.js 4","summary":"Fais passer une application Total.js 4 à Total.js 5, domaine par domaine, avec le code avant et après chaque changement.","markdown":"---\ntitle: Migrer depuis Total.js 4\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/migrating-from-total4/\nupdated: 2026-11-18T16:59:59.647Z\n---\n\n# Migrer depuis Total.js 4\n\n> Fais passer une application Total.js 4 à Total.js 5, domaine par domaine, avec le code avant et après chaque changement.\n\nCe guide fait passer une application de Total.js 4 à Total.js 5. Il indique ce que tu dois changer dans chaque domaine, avec l'ancien code à côté de son remplacement, et se termine par une petite application présentée dans les deux versions.\n\n## Ordre de travail recommandé\n\n1. Remplace le paquet `total4` par `total5` et mets à jour le [script de démarrage](#start-script).\n2. Renomme les [clés de configuration](#configuration) et ajoute un type aux valeurs numériques.\n3. Transforme les [schémas en actions](#schemas-and-actions) et mets à jour les routes qui les appellent.\n4. Remplace `this` par `$` dans les [routes et les contrôleurs](#routes) ainsi que dans les [middlewares](#middleware).\n5. Vérifie les [vues](#views) et les [vues d'e-mail](#mail) : dossiers, layouts et titres.\n6. Mets à jour les requêtes [NoSQL](#nosql), la gestion des erreurs de [RESTBuilder](#restbuilder), les [WebSockets](#websockets) et le [stockage de fichiers](#file-storage).\n7. Remplace [`SCHEDULE()`](#scheduling), les [opérations et les tâches](#operations-and-tasks), ainsi que les [appels](#modules-models-and-definitions) à `MODULE()` et `MODEL()`.\n8. Réécris les [tests unitaires](#unit-tests) et lance l'application.\n\n## Script de démarrage\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `npm install total4` | `npm install total5@beta` |\n| `require('total4/debug')(options)` | `require('total5'); Total.run(options)` |\n| `require('total4/release')(options)` | `options.release = true; Total.run(options)` |\n\nAvant :\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.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\nAprès :\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\nLes deux scripts démarrent en mode debug, et en mode release avec `node index.js --release`. Consulte [Installation](../installation/).\n\n## Schémas et actions\n\n`schema.define()` et la famille `schema.setInsert()` n'existent pas dans Total.js 5. Un schéma laissé tel quel arrête l'application au démarrage avec `TypeError: schema.define is not a function`. Déplace chaque opération dans un `NEWACTION()` du dossier `actions/` et déclare ses champs dans `input`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `schema.define('name', 'String(30)', true)` | `input: '*name:String(30)'` |\n| `schema.define('role', ['admin', 'user'])` | `input: 'role:{admin\\|user}'` |\n| `schema.setInsert(fn)`, `setQuery(fn)`, `setRead(fn)`... | `NEWACTION('Users/insert', { action: fn })` |\n| `ROUTE('POST /api/users/ *Users --> insert')` | `ROUTE('POST /api/users/ --> Users/insert')` |\n| `$.id` | `params: '*id:String'` et `$.params.id` |\n| `.callback($.callback)` | `.callback($)` |\n| `$.invalid('age', 'Message')` | `$.invalid('Message', 'age')` |\n| `CALL('Math --> double', data)` | `ACTION('Math/double', data)` |\n\nAvant :\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(30)', 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 = 'A1';\n\t\t$.success(model);\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ *Users --> insert');\n};\n```\n\nAprès :\n\n```js\nNEWACTION('Users/insert', {\n\tinput: '*name:String(30), *email:Email, age:Number, role:{admin|user}',\n\taction: function($, model) {\n\t\tmodel.id = 'A1';\n\t\t$.success(model);\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ --> Users/insert');\n};\n```\n\n### Validateurs personnalisés\n\nUne fonction de validation placée dans `schema.define()` passe dans l'action.\n\nAvant :\n\n```js\nNEWSCHEMA('Signup', function(schema) {\n\n\tschema.define('name', 'String(30)', true);\n\tschema.define('age', Number, value => value >= 18, 'You must be an adult');\n\n\tschema.setInsert(function($, model) {\n\t\t$.success(model.age);\n\t});\n\n});\n```\n\nAprès :\n\n```js\nNEWACTION('Signup/insert', {\n\tinput: '*name:String(30), age:Number',\n\taction: function($, model) {\n\n\t\tif (model.age < 18) {\n\t\t\t$.invalid('You must be an adult', 'age');\n\t\t\treturn;\n\t\t}\n\n\t\t$.success(model.age);\n\t}\n});\n```\n\n### Schémas qui utilisent déjà `schema.action()`\n\nCes schémas continuent de fonctionner. Seule la route change : `*Tags --> list` devient `--> Tags/list`.\n\n```js\nNEWSCHEMA('Tags', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of tags',\n\t\tquery: 'limit:Number',\n\t\taction: function($) {\n\t\t\t$.callback(['a', 'b', 'c'].slice(0, $.query.limit || 3));\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a tag',\n\t\tinput: '*name:String(20)',\n\t\taction: function($, model) {\n\t\t\t$.success(model.name);\n\t\t}\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('GET  /api/tags/ --> Tags/list');\n\tROUTE('POST /api/tags/ --> Tags/create');\n};\n```\n\n### Valeurs et erreurs que tes clients remarqueront\n\n| Cas | Total.js 4 | Total.js 5 |\n| --- | --- | --- |\n| Un `Number` optionnel est absent | Le champ vaut `0` | Le champ est omis |\n| Un enum optionnel est absent | Le champ est omis | Le champ vaut `''` |\n| La valeur de l'enum n'est pas dans la liste | Valeur ignorée, requête acceptée | `400` avec une erreur pour le champ |\n| Clés d'une erreur de champ obligatoire | `name`, `error`, `path`, `prefix` | `name`, `error`, `path` |\n| Clés d'une erreur de `$.invalid()` avec un champ | `name`, `error` | `error`, `path` |\n\nUn client qui lit `name` dans tes propres erreurs doit lire `path` à la place. Consulte [Actions](../actions/) et [Schémas JSON](../json-schemas/).\n\n## Routes\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function detail(id) { this.json({ id: id }); }` | `function detail($) { $.json({ id: $.params.id }); }` |\n| `ROUTE('/about/', fn)` | `ROUTE('GET /about/', fn)` : la méthode est obligatoire |\n| `{page:number}` convertit la valeur | `{page}` est une chaîne : `$.params.page.parseInt()` |\n| `ROUTE('POST /upload/', fn, ['upload'], 1024)` | `ROUTE('POST /upload/ @upload <1MB', fn)` |\n| `ROUTE('POST /import/', fn, 1024)` | `ROUTE('POST /import/ <1MB', fn)` |\n| `ROUTE('+GET /admin/ @admin', fn)` | `ROUTE('+GET /admin/', fn)` et `UNAUTHORIZED($, 'admin')` dans le gestionnaire |\n| `ROUTE('API /api/ -users_list *Users --> list')` | `ROUTE('API /api/ users_list --> Users/list')` |\n| `ROUTE('API /api/ +users_save *Users --> save')` | `ROUTE('API /api/ users_save --> Users/save')` |\n\nUne route sans flag de taille refuse un corps JSON de plus de 256 kB avec `431` : donne donc leur propre limite aux routes qui importent de gros volumes de données. Un endpoint `API` inconnu répond `400` au lieu de `404`. Consulte [Routage](../routing/).\n\nAvant :\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail(id, order) {\n\tthis.json({ id: id, order: order, params: this.params });\n}\n```\n\nAprès :\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail($) {\n\t$.json({ id: $.params.id, order: $.params.order, params: $.params });\n}\n```\n\n## Contrôleurs\n\nLes gestionnaires reçoivent le contrôleur dans `$`. `this` n'est plus le contrôleur dans les routes HTTP.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.status = 201` | `$.response.status = 201` |\n| `this.header('X-Version', '1')` | `$.response.headers['x-version'] = '1'` |\n| `this.nocache()` | `$.response.headers['cache-control'] = 'private, no-cache, no-store, max-age=0'` |\n| `this.content('<a>1</a>', 'text/xml')` | `$.xml('<a>1</a>')` |\n| `this.content('id;name', 'text/csv')` | `$.binary(Buffer.from('id;name'), 'text/csv')` |\n| `this.nocontent()` | `$.empty()` |\n| `this.throw404()`, `this.throw403()` | `$.fallback(404)`, `$.fallback(403)` |\n| `this.throw500('Problem')` | `$.fallback(500, 'Problem')` |\n| `this.file('docs/a.txt', 'report.txt')` | `$.file(PATH.public('docs/a.txt'), 'report.txt')` |\n| `this.success(true, 42)` | `$.success(42)` |\n| `this.success(false)` | `$.json({ success: false })` |\n| `this.invalid('email', 'Message')` | `var err = new ErrorBuilder(); err.push('Message', 'email'); $.invalid(err);` |\n| `file.isImage()` | `file.isImage` |\n| `this.mail(email, subject, view, model)` | `MAIL(email, subject, view, model)` |\n\nPour ces membres, il suffit de remplacer `this` par `$` : `params`, `query`, `body`, `files`, `headers`, `url`, `ip`, `ua`, `mobile`, `robot`, `xhr`, `referrer`, `user`, `language`, `cookie()`, `hostname()`, `json()`, `plain()`, `view()`, `filefs()` et `stream(type, stream)`.\n\nUne route d'erreur définit le statut de la même manière :\n\n```js\nexports.install = function() {\n\tROUTE('GET /missing/', missing);\n\tROUTE('GET /denied/', denied);\n\tROUTE('GET /broken/', broken);\n\tROUTE('#404', notfound);\n};\n\nfunction missing($) {\n\t$.fallback(404);\n}\n\nfunction denied($) {\n\t$.fallback(403);\n}\n\nfunction broken($) {\n\t$.fallback(500, 'Unexpected problem');\n}\n\nfunction notfound($) {\n\t$.response.status = 404;\n\t$.plain('My 404 page');\n}\n```\n\nConsulte [Contrôleur](../controller/).\n\n## Vues\n\nLa syntaxe des fichiers de vue ne change pas : les expressions, les conditions, les boucles, les sections, les vues partielles et les helpers de `DEF.helpers` fonctionnent comme avant.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.view('detail')` dans `controllers/users.js` trouve `views/users/detail.html` | `$.view('users/detail')` : le nom part toujours de `views/` |\n| Le layout peut lire `model` | Définis `@{repository.name = model.name}` dans la vue et lis `repository` dans le layout |\n| `this.title('Products')` | `@{title('Products')}` dans la vue |\n| `this.repository.page = 'list'` | `@{repository.page = 'list'}` dans la vue |\n| `VIEW('mail/order', model)` | `F.view('mail/order', model)`, avec `@{layout('')}` dans la vue |\n| Le titre de la page d'accueil reçoit ` - ` et `CONF.name` | Le titre de la page d'accueil reste tel que tu l'as écrit |\n\nAvant :\n\n```html\n<title>@{model.name}</title>@{body}\n```\n\nAprès :\n\n```html\n<title>@{repository.name}</title>@{body}\n```\n\n```html\n@{repository.name = model.name}\n<h1>@{model.name}</h1>\n```\n\nConsulte [Vues](../views/).\n\n## Middleware\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MIDDLEWARE('name', function($) { $.next(); })` | `NEWMIDDLEWARE('name', function($, next) { next(); })` |\n| `$.res.throw401()` | `$.invalid(401)` |\n| `$.res.setHeader('x-stamp', 'yes')` | `$.response.headers['x-stamp'] = 'yes'` |\n| `ROUTE('GET /private/', fn, ['#apikey'])` | `ROUTE('GET /private/ #apikey', fn)` |\n| `ROUTE('GET /open/ &stamp', fn)` | `ROUTE('GET /open/ #stamp', fn)` |\n| `USE('poweredby', ['web'])` | Troisième argument `'routes'`, dans `ON('ready')` |\n\nAvant :\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('x-server', 'myapp');\n\t$.next();\n});\n\nUSE('poweredby', ['web']);\n```\n\nAprès :\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('poweredby', function($, next) {\n\t\t$.response.headers['x-server'] = 'myapp';\n\t\tnext();\n\t}, 'routes');\n});\n```\n\nConsulte [Middleware](../middleware/).\n\n## WebSockets\n\nUne route `SOCKET` conserve sa structure, et `this` fonctionne toujours dans son gestionnaire.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function room(name) {}` | `function room($) { var name = $.params.name; }` |\n| `ROUTE('SOCKET /feed/', fn, ['json'], 64)` | `ROUTE('SOCKET /feed/ <64kB', fn)` |\n| `ROUTE('SOCKET /terminal/', fn, ['text'])` | `ROUTE('SOCKET /terminal/ @text', fn)` |\n| `client.send(text)` sur une route texte | `client.send(text, true)` |\n| `client.close('finished', 4000)` | `client.close(4000, 'finished')` |\n| Un client `+SOCKET` refusé se connecte, puis la connexion est fermée avec `4001` | Le handshake est refusé et le client voit `1006` |\n\nConsulte [WebSockets](../websockets/).\n\n## NoSQL\n\nLes fichiers `.nosql` existants peuvent être lus tels quels. `insert()`, `find()`, `read()`, `update()`, `remove()`, `where()`, `search()`, `fields()`, `skip()`, `take()`, `first()` et le préfixe de mise à jour `+field` ne changent pas.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `find()` commence par le document le plus ancien | `find()` commence par le document le plus récent : ajoute `sort()` quand l'ordre compte |\n| `find2()` | `find()` |\n| `one()` | `read()` |\n| `sort('age_desc')` | `sort('age', true)` |\n| `NOSQL('users').count()` | `DATA.count('nosql/users')` |\n| `NOSQL('users').list()` | `DATA.list('nosql/users')` |\n| `rule('doc.age > arg.min', { min: 45 })` | `query('doc.age > 45')` |\n| `update({ '-score': 3 })` | `update({ '+score': -3 })` |\n| `TABLE('users')` | `NOSQL('users')` |\n\n`TABLE()` n'existe pas dans Total.js 5 : déplace donc toi-même les lignes des fichiers `.table` vers une base de données NoSQL.\n\nAvant :\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run() {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.one().where('id', '2').fields('name').promise();\n\tvar count = await db.count().where('age', '>', 35).promise();\n\tvar list = await db.list().sort('age_desc').fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().rule('doc.age > arg.min', { min: 45 }).fields('name').promise();\n\n\tawait db.update({ '-score': 3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\tthis.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nAprès :\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run($) {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.read().where('id', '2').fields('name').promise();\n\tvar count = await DATA.count('nosql/users').where('age', '>', 35).promise();\n\tvar list = await DATA.list('nosql/users').sort('age', true).fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().query('doc.age > 45').fields('name').promise();\n\n\tawait db.update({ '+score': -3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\t$.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nConsulte [Base de données NoSQL](../nosql/).\n\n## RESTBuilder\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| Un statut de `400` ou plus n'est une erreur qu'avec `.strict()` | Un statut de `400` ou plus est toujours une erreur |\n| `.callback($.callback)` dans une opération | `.callback($)` dans une action |\n\nLe code qui lit `output.status` après une requête en échec doit d'abord traiter `err`. Consulte [Requêtes HTTP](../http-requests/).\n\n## Configuration\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `default_root` | `$root` |\n| `default_timezone` | `$timezone` |\n| `default_cookies_samesite` | `$cookiesamesite` |\n| `default_cookies_secure` | `$cookiesecure` |\n| `default_xpoweredby` | `$xpoweredby` |\n| `allow_custom_titles` | `$customtitles` |\n| `allow_gzip` | `$httpcompress` |\n| `limit : 50` est un nombre | `limit (number) : 50` : sans type, la valeur est une chaîne |\n| `smtp (object) : { port: 465 }` | `smtp (json) : { \"port\": 465 }` |\n| `config-release` | Non chargé : garde les valeurs dans `config` |\n\nAvant :\n\n```text\nname                     : Shop\ndefault_root             : /app/\ndefault_timezone         : Europe/Bratislava\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\ndefault_xpoweredby       : MyServer\nallow_custom_titles      : true\nallow_gzip               : false\n```\n\nAprès :\n\n```text\nname            : Shop\n$root           : /app/\n$timezone       : Europe/Bratislava\n$cookiesamesite : Strict\n$cookiesecure   : true\n$xpoweredby     : MyServer\n$customtitles   : true\n$httpcompress   : false\n```\n\n`CORS()`, `name`, les valeurs `(array)` et `mail_smtp_options` écrit sous forme d'objet JavaScript fonctionnent comme avant. Consulte [Configuration](../configuration/).\n\n## Autorisation\n\nLe delegate `AUTH()`, les flags de route `+` et `-` et `UNAUTHORIZED()` ne changent pas. `SESSION()` n'existe pas dans Total.js 5 : utilise la session intégrée de `AUTH()`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SESSION()` avec `ondata` | `AUTH(opt)` avec `opt.onread` |\n| `session.setcookie($, options, callback)` | `opt.authcookie($, UID(), userid, '1 hour')` |\n| `session.remove2(userid)` et suppression du cookie | `opt.logout($)` dans une action |\n\nAvant :\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\tnext(null, { id: meta.id, name: 'Peter' });\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 hour', key: 'session-key' }, 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\nMAIN.session = session;\n```\n\nAprès :\n\n```js\nvar opt = {};\n\nopt.secret = 'session-key';\nopt.cookie = 'sid';\nopt.expire = '1 hour';\n\nopt.onread = function(meta, next) {\n\tnext(null, { id: meta.userid, name: 'Peter' });\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\n```js\nNEWACTION('Account/logout', {\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.logout()` retire la session de la mémoire et supprime le cookie. Une copie enregistrée du jeton est signée : elle est donc de nouveau acceptée dès que `onread` renvoie un utilisateur. Vérifie la session dans ta base de données à l'intérieur de `onread` lorsque la déconnexion doit révoquer le jeton. Consulte [Autorisation](../authorization/).\n\n## Localisation\n\nLes fichiers de ressources et `@(Text)` dans les vues restent identiques, et les clés générées sont les mêmes.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `LOCALIZE(function(req, res) {})` | `LOCALIZE(function($) {})` |\n| `RESOURCE('sk', 'title')` | `F.resource('sk', 'title')` |\n| `TRANSLATOR('sk', '<b>@(Welcome)</b>')` | `TRANSLATE('sk', '<b>@(Welcome)</b>')` |\n| `TRANSLATE('sk', 'Welcome')` | `TRANSLATE('sk', '@(Welcome)')` |\n\nConsulte [Localisation](../localization/).\n\n## E-mails\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MAIL()` rend la vue sans layout | `MAIL()` rend la vue dans `views/layout.html` |\n| `ON('mail', fn)` | `ON('$mail', fn)` |\n| `message.address_to` | `message.email_to` |\n\nCommence chaque vue d'e-mail par `@{layout('')}`. Sans cela, le message est enveloppé dans le layout de ton site, et si `views/layout.html` n'existe pas, le message n'est pas envoyé du tout.\n\nAvant :\n\n```html\n<p>Hello @{model.name}</p>\n```\n\nAprès :\n\n```html\n@{layout('')}\n<p>Hello @{model.name}</p>\n```\n\nConsulte [Envoi d'e-mails](../mail/).\n\n## Stockage de fichiers\n\nL'ordre des arguments de `save()` change : les données personnalisées passent désormais avant le callback.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `fs.save(id, name, data, callback, custom)` | `fs.save(id, name, data, custom, callback)` |\n\n`read()` et `$.filefs()` ne changent pas. Consulte [Stockage de fichiers](../file-storage/).\n\n## Planification\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SCHEDULE('* * * * *', fn)` | `CRON('* * * * *', fn)` |\n| `SCHEDULE('03:00', '1 day', fn)` | `CRON('0 3 * * *', fn)` |\n\nAvant :\n\n```js\nMAIN.runs = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nAprès :\n\n```js\nMAIN.runs = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nConsulte [Planification et événements](../scheduling-and-events/).\n\n## Opérations et tâches\n\n`NEWOPERATION()`, `OPERATION()`, `RUN()`, `NEWTASK()` et `TASK()` n'existent pas dans Total.js 5. Chaque opération devient une action, et les étapes d'une tâche deviennent une action ou plusieurs actions appelées à la suite.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `NEWOPERATION('order_price', fn)` | `NEWACTION('order_price', { input: '...', action: fn })` |\n| `OPERATION('order_price', value, callback)` | `ACTION('order_price', value).callback(callback)` |\n| `RUN('order_check, order_price', value, callback)` | `await ACTION(...).promise($)` pour chaque étape |\n| `NEWTASK('order', fn)` et `TASK('order/check', ...)` | `NEWACTION('order', { action: fn })` |\n\nAvant :\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order() {\n\tvar self = this;\n\tOPERATION('order_price', self.body, function(err, response) {\n\t\tself.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nfunction chain() {\n\tvar self = this;\n\tRUN('order_check, order_price', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.order_price);\n\t});\n}\n```\n\nAprès :\n\n```js\nNEWACTION('order_check', {\n\tinput: '*email:String, count:Number',\n\taction: function($, model) {\n\t\tmodel.email = model.email.toLowerCase();\n\t\t$.callback(model);\n\t}\n});\n\nNEWACTION('order_price', {\n\tinput: 'email:String, count:Number',\n\taction: function($, model) {\n\t\t$.callback({ email: model.email, price: model.count * 10 });\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order($) {\n\tACTION('order_price', $.body).callback(function(err, response) {\n\t\t$.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nasync function chain($) {\n\tvar model = await ACTION('order_check', $.body).promise($);\n\t$.json(await ACTION('order_price', model).promise($));\n}\n```\n\nConsulte [Actions](../actions/).\n\n## Modules, modèles de données et définitions\n\nLes fichiers de `definitions/` et de `modules/` se chargent comme avant, et `MAIN`, `FUNC`, `PATH` et `ON('ready')` ne changent pas.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MODULE('greeter').greet('Peter')` | `MODS.greeter.greet('Peter')` |\n| `MODEL('price').total(2, 5)` | `require(PATH.root('models/price.js')).total(2, 5)` |\n| `CACHE('products', value, '5 minutes')` | `CACHE.set('products', value, '5 minutes')` |\n| `CACHE('products')` | `CACHE.read('products')` |\n\nConsulte [Structure de l'application](../application-structure/).\n\n## Tests unitaires\n\n`TESTER()` est remplacé par l'objet `Test` de `total5/test`.\n\nAvant :\n\n```js\nrequire('total4');\n\nTESTER(function(group, start) {\n\n\tgroup('Strings', function(test) {\n\n\t\ttest('slug()', function(next) {\n\t\t\tnext('Hello World'.slug() === 'hello-world' ? undefined : 'Unexpected slug');\n\t\t});\n\n\t\ttest('capitalize()', function(next) {\n\t\t\tnext('total'.capitalize() === 'Total' ? undefined : 'Unexpected value');\n\t\t});\n\n\t});\n\n\tstart();\n});\n```\n\nAprès :\n\n```js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nConsulte [Tests unitaires](../unit-tests/).\n\n## Ligne de commande\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `total4 translate` | `total5 translate \"$PWD/translate.resource\"` |\n\nIndique à `total5 translate` le path complet du fichier de sortie. Consulte [Ligne de commande](../command-line/).\n\n## Une application complète\n\nCette petite application de notes propose une liste publique, des écritures protégées, une page d'accueil, un e-mail de notification, un canal WebSocket en direct et une tâche qui s'exécute chaque minute. Les deux versions répondent de la même manière aux mêmes requêtes, à l'exception du titre de la page d'accueil décrit dans [Vues](#views).\n\n### Total.js 4\n\n`index.js`\n\n```js\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\n`config`\n\n```text\nname              : Notes\napitoken          : secret\nmail_notify       : admin@example.com\nmail_from         : notes@example.com\nmail_smtp         : 127.0.0.1\nmail_smtp_options : { port: 19854 }\nmaxnotes          : 100\n```\n\n`definitions/auth.js`\n\n```js\nAUTH(function($) {\n\tif ($.headers['x-token'] === CONF.apitoken)\n\t\t$.success({ id: '1', name: 'Admin' });\n\telse\n\t\t$.invalid();\n});\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`schemas/notes.js`\n\n```js\nNEWSCHEMA('Notes', function(schema) {\n\n\tschema.define('title', 'String(50)', value => value && value !== 'spam', 'This title is not allowed');\n\tschema.define('body', 'String(500)');\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('notes').find().sort('dtcreated_desc').fields('id,title').take(CONF.maxnotes).callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('notes').read().id($.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t});\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t});\n\n\tschema.setRemove(function($) {\n\t\tNOSQL('notes').remove().id($.id).callback($.done());\n\t});\n\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        *Notes --> query');\n\tROUTE('GET     /api/notes/{id}/   *Notes --> read');\n\tROUTE('+POST   /api/notes/        *Notes --> insert');\n\tROUTE('+DELETE /api/notes/{id}/   *Notes --> remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats() {\n\tthis.json({ ticks: MAIN.ticks });\n}\n\nfunction live() {\n\tMAIN.live = this;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tvar self = this;\n\tself.title('Latest notes');\n\tNOSQL('notes').find().sort('dtcreated_desc').fields('title').callback(function(err, notes) {\n\t\tself.view('index', notes);\n\t});\n}\n```\n\n`views/layout.html`\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`views/index.html`\n\n```html\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n<p>New note: @{model.title}</p>\n```\n\n### Total.js 5\n\n`definitions/auth.js` et `views/layout.html` restent identiques.\n\n`index.js`\n\n```js\nrequire('total5');\n\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\n`config`\n\n```text\nname                : Notes\napitoken            : secret\nmail_notify         : admin@example.com\nmail_from           : notes@example.com\nmail_smtp           : 127.0.0.1\nmail_smtp_options   : { port: 19854 }\nmaxnotes (number)   : 100\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`actions/notes.js`\n\n```js\nNEWACTION('Notes/query', {\n\taction: function($) {\n\t\tNOSQL('notes').find().sort('dtcreated', true).fields('id,title').take(CONF.maxnotes).callback($);\n\t}\n});\n\nNEWACTION('Notes/read', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').read().id($.params.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/insert', {\n\tinput: '*title:String(50), body:String(500)',\n\taction: function($, model) {\n\n\t\tif (model.title === 'spam') {\n\t\t\t$.invalid('This title is not allowed', 'title');\n\t\t\treturn;\n\t\t}\n\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/remove', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').remove().id($.params.id).callback($.done());\n\t}\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        --> Notes/query');\n\tROUTE('GET     /api/notes/{id}/   --> Notes/read');\n\tROUTE('+POST   /api/notes/        --> Notes/insert');\n\tROUTE('+DELETE /api/notes/{id}/   --> Notes/remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats($) {\n\t$.json({ ticks: MAIN.ticks });\n}\n\nfunction live($) {\n\tMAIN.live = $;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index($) {\n\tNOSQL('notes').find().sort('dtcreated', true).fields('title').callback(function(err, notes) {\n\t\t$.view('index', notes);\n\t});\n}\n```\n\n`views/index.html`\n\n```html\n@{title('Latest notes')}\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n@{layout('')}\n<p>New note: @{model.title}</p>\n```\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:59.647Z"}
{"id":"JanG8G22Z61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/migrating-from-total4/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Migrazione da Total.js 4","summary":"Porta un'applicazione Total.js 4 a Total.js 5, area per area, con il codice prima e dopo ogni modifica.","markdown":"---\ntitle: Migrazione da Total.js 4\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/migrating-from-total4/\nupdated: 2026-11-18T16:59:59.647Z\n---\n\n# Migrazione da Total.js 4\n\n> Porta un'applicazione Total.js 4 a Total.js 5, area per area, con il codice prima e dopo ogni modifica.\n\nQuesta guida porta un'applicazione da Total.js 4 a Total.js 5. Elenca cosa devi cambiare in ogni area, con il vecchio codice accanto al suo sostituto, e si chiude con una piccola applicazione mostrata in entrambe le versioni.\n\n## Ordine di lavoro consigliato\n\n1. Sostituisci il pacchetto `total4` con `total5` e aggiorna lo [script di avvio](#start-script).\n2. Rinomina le [chiavi di configurazione](#configuration) e aggiungi i tipi ai valori numerici.\n3. Trasforma gli [schemi in azioni](#schemas-and-actions) e aggiorna le route che li richiamano.\n4. Sostituisci `this` con `$` nelle [route e nei controller](#routes) e nel [middleware](#middleware).\n5. Controlla le [viste](#views) e le [viste delle email](#mail): cartelle, layout e titoli.\n6. Aggiorna le query [NoSQL](#nosql), la gestione degli errori di [RESTBuilder](#restbuilder), i [WebSocket](#websockets) e l'[archiviazione dei file](#file-storage).\n7. Sostituisci [`SCHEDULE()`](#scheduling), le [operazioni e i task](#operations-and-tasks) e le [chiamate](#modules-models-and-definitions) a `MODULE()` e `MODEL()`.\n8. Riscrivi i [test unitari](#unit-tests) e avvia l'applicazione.\n\n## Script di avvio\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `npm install total4` | `npm install total5@beta` |\n| `require('total4/debug')(options)` | `require('total5'); Total.run(options)` |\n| `require('total4/release')(options)` | `options.release = true; Total.run(options)` |\n\nPrima:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.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\nDopo:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\nEntrambi gli script si avviano in modalità debug e, con `node index.js --release`, in modalità release. Vedi [Installazione](../installation/).\n\n## Schemi e azioni\n\n`schema.define()` e la famiglia di `schema.setInsert()` non esistono in Total.js 5. Uno schema non modificato blocca l'applicazione all'avvio con `TypeError: schema.define is not a function`. Sposta ogni operazione in un `NEWACTION()` nella cartella `actions/` e dichiara i suoi campi in `input`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `schema.define('name', 'String(30)', true)` | `input: '*name:String(30)'` |\n| `schema.define('role', ['admin', 'user'])` | `input: 'role:{admin\\|user}'` |\n| `schema.setInsert(fn)`, `setQuery(fn)`, `setRead(fn)`... | `NEWACTION('Users/insert', { action: fn })` |\n| `ROUTE('POST /api/users/ *Users --> insert')` | `ROUTE('POST /api/users/ --> Users/insert')` |\n| `$.id` | `params: '*id:String'` e `$.params.id` |\n| `.callback($.callback)` | `.callback($)` |\n| `$.invalid('age', 'Message')` | `$.invalid('Message', 'age')` |\n| `CALL('Math --> double', data)` | `ACTION('Math/double', data)` |\n\nPrima:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(30)', 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 = 'A1';\n\t\t$.success(model);\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ *Users --> insert');\n};\n```\n\nDopo:\n\n```js\nNEWACTION('Users/insert', {\n\tinput: '*name:String(30), *email:Email, age:Number, role:{admin|user}',\n\taction: function($, model) {\n\t\tmodel.id = 'A1';\n\t\t$.success(model);\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ --> Users/insert');\n};\n```\n\n### Validatori personalizzati\n\nUna funzione di validazione in `schema.define()` si sposta nell'azione.\n\nPrima:\n\n```js\nNEWSCHEMA('Signup', function(schema) {\n\n\tschema.define('name', 'String(30)', true);\n\tschema.define('age', Number, value => value >= 18, 'You must be an adult');\n\n\tschema.setInsert(function($, model) {\n\t\t$.success(model.age);\n\t});\n\n});\n```\n\nDopo:\n\n```js\nNEWACTION('Signup/insert', {\n\tinput: '*name:String(30), age:Number',\n\taction: function($, model) {\n\n\t\tif (model.age < 18) {\n\t\t\t$.invalid('You must be an adult', 'age');\n\t\t\treturn;\n\t\t}\n\n\t\t$.success(model.age);\n\t}\n});\n```\n\n### Schemi che usano già `schema.action()`\n\nQuesti schemi continuano a funzionare. Cambia solo la route: `*Tags --> list` diventa `--> Tags/list`.\n\n```js\nNEWSCHEMA('Tags', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of tags',\n\t\tquery: 'limit:Number',\n\t\taction: function($) {\n\t\t\t$.callback(['a', 'b', 'c'].slice(0, $.query.limit || 3));\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a tag',\n\t\tinput: '*name:String(20)',\n\t\taction: function($, model) {\n\t\t\t$.success(model.name);\n\t\t}\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('GET  /api/tags/ --> Tags/list');\n\tROUTE('POST /api/tags/ --> Tags/create');\n};\n```\n\n### Valori ed errori che i tuoi client noteranno\n\n| Caso | Total.js 4 | Total.js 5 |\n| --- | --- | --- |\n| `Number` opzionale assente | Il campo è `0` | Il campo viene omesso |\n| Enum opzionale assente | Il campo viene omesso | Il campo è `''` |\n| Valore enum non presente nell'elenco | Valore scartato, richiesta accettata | `400` con un errore per il campo |\n| Chiavi di un errore di campo obbligatorio | `name`, `error`, `path`, `prefix` | `name`, `error`, `path` |\n| Chiavi di un errore di `$.invalid()` con un campo | `name`, `error` | `error`, `path` |\n\nUn client che legge `name` dai tuoi errori deve leggere invece `path`. Vedi [Azioni](../actions/) e [Schemi JSON](../json-schemas/).\n\n## Route\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function detail(id) { this.json({ id: id }); }` | `function detail($) { $.json({ id: $.params.id }); }` |\n| `ROUTE('/about/', fn)` | `ROUTE('GET /about/', fn)`: il metodo è obbligatorio |\n| `{page:number}` converte il valore | `{page}` è una stringa: `$.params.page.parseInt()` |\n| `ROUTE('POST /upload/', fn, ['upload'], 1024)` | `ROUTE('POST /upload/ @upload <1MB', fn)` |\n| `ROUTE('POST /import/', fn, 1024)` | `ROUTE('POST /import/ <1MB', fn)` |\n| `ROUTE('+GET /admin/ @admin', fn)` | `ROUTE('+GET /admin/', fn)` e `UNAUTHORIZED($, 'admin')` nel gestore |\n| `ROUTE('API /api/ -users_list *Users --> list')` | `ROUTE('API /api/ users_list --> Users/list')` |\n| `ROUTE('API /api/ +users_save *Users --> save')` | `ROUTE('API /api/ users_save --> Users/save')` |\n\nUna route senza flag di dimensione rifiuta con `431` un corpo JSON superiore a 256 kB, quindi assegna un limite proprio alle route che importano grandi quantità di dati. Un endpoint `API` sconosciuto risponde `400` invece di `404`. Vedi [Routing](../routing/).\n\nPrima:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail(id, order) {\n\tthis.json({ id: id, order: order, params: this.params });\n}\n```\n\nDopo:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail($) {\n\t$.json({ id: $.params.id, order: $.params.order, params: $.params });\n}\n```\n\n## Controller\n\nI gestori ricevono il controller come `$`. Nelle route HTTP `this` non è più il controller.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.status = 201` | `$.response.status = 201` |\n| `this.header('X-Version', '1')` | `$.response.headers['x-version'] = '1'` |\n| `this.nocache()` | `$.response.headers['cache-control'] = 'private, no-cache, no-store, max-age=0'` |\n| `this.content('<a>1</a>', 'text/xml')` | `$.xml('<a>1</a>')` |\n| `this.content('id;name', 'text/csv')` | `$.binary(Buffer.from('id;name'), 'text/csv')` |\n| `this.nocontent()` | `$.empty()` |\n| `this.throw404()`, `this.throw403()` | `$.fallback(404)`, `$.fallback(403)` |\n| `this.throw500('Problem')` | `$.fallback(500, 'Problem')` |\n| `this.file('docs/a.txt', 'report.txt')` | `$.file(PATH.public('docs/a.txt'), 'report.txt')` |\n| `this.success(true, 42)` | `$.success(42)` |\n| `this.success(false)` | `$.json({ success: false })` |\n| `this.invalid('email', 'Message')` | `var err = new ErrorBuilder(); err.push('Message', 'email'); $.invalid(err);` |\n| `file.isImage()` | `file.isImage` |\n| `this.mail(email, subject, view, model)` | `MAIL(email, subject, view, model)` |\n\nPer questi membri basta sostituire `this` con `$`: `params`, `query`, `body`, `files`, `headers`, `url`, `ip`, `ua`, `mobile`, `robot`, `xhr`, `referrer`, `user`, `language`, `cookie()`, `hostname()`, `json()`, `plain()`, `view()`, `filefs()` e `stream(type, stream)`.\n\nUna route di errore imposta lo stato allo stesso modo:\n\n```js\nexports.install = function() {\n\tROUTE('GET /missing/', missing);\n\tROUTE('GET /denied/', denied);\n\tROUTE('GET /broken/', broken);\n\tROUTE('#404', notfound);\n};\n\nfunction missing($) {\n\t$.fallback(404);\n}\n\nfunction denied($) {\n\t$.fallback(403);\n}\n\nfunction broken($) {\n\t$.fallback(500, 'Unexpected problem');\n}\n\nfunction notfound($) {\n\t$.response.status = 404;\n\t$.plain('My 404 page');\n}\n```\n\nVedi [Controller](../controller/).\n\n## Viste\n\nLa sintassi dei file di vista non cambia: espressioni, condizioni, cicli, sezioni, viste parziali e helper di `DEF.helpers` funzionano come prima.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.view('detail')` in `controllers/users.js` trova `views/users/detail.html` | `$.view('users/detail')`: il nome parte sempre da `views/` |\n| Il layout può leggere `model` | Imposta `@{repository.name = model.name}` nella vista e leggi `repository` nel layout |\n| `this.title('Products')` | `@{title('Products')}` nella vista |\n| `this.repository.page = 'list'` | `@{repository.page = 'list'}` nella vista |\n| `VIEW('mail/order', model)` | `F.view('mail/order', model)`, con `@{layout('')}` nella vista |\n| Al titolo della home page vengono aggiunti ` - ` e `CONF.name` | Il titolo della home page resta come l'hai scritto |\n\nPrima:\n\n```html\n<title>@{model.name}</title>@{body}\n```\n\nDopo:\n\n```html\n<title>@{repository.name}</title>@{body}\n```\n\n```html\n@{repository.name = model.name}\n<h1>@{model.name}</h1>\n```\n\nVedi [Viste](../views/).\n\n## Middleware\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MIDDLEWARE('name', function($) { $.next(); })` | `NEWMIDDLEWARE('name', function($, next) { next(); })` |\n| `$.res.throw401()` | `$.invalid(401)` |\n| `$.res.setHeader('x-stamp', 'yes')` | `$.response.headers['x-stamp'] = 'yes'` |\n| `ROUTE('GET /private/', fn, ['#apikey'])` | `ROUTE('GET /private/ #apikey', fn)` |\n| `ROUTE('GET /open/ &stamp', fn)` | `ROUTE('GET /open/ #stamp', fn)` |\n| `USE('poweredby', ['web'])` | Terzo argomento `'routes'`, dentro `ON('ready')` |\n\nPrima:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('x-server', 'myapp');\n\t$.next();\n});\n\nUSE('poweredby', ['web']);\n```\n\nDopo:\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('poweredby', function($, next) {\n\t\t$.response.headers['x-server'] = 'myapp';\n\t\tnext();\n\t}, 'routes');\n});\n```\n\nVedi [Middleware](../middleware/).\n\n## WebSocket\n\nUna route `SOCKET` mantiene la sua struttura e `this` continua a funzionare nel suo gestore.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function room(name) {}` | `function room($) { var name = $.params.name; }` |\n| `ROUTE('SOCKET /feed/', fn, ['json'], 64)` | `ROUTE('SOCKET /feed/ <64kB', fn)` |\n| `ROUTE('SOCKET /terminal/', fn, ['text'])` | `ROUTE('SOCKET /terminal/ @text', fn)` |\n| `client.send(text)` su una route di testo | `client.send(text, true)` |\n| `client.close('finished', 4000)` | `client.close(4000, 'finished')` |\n| Un client `+SOCKET` rifiutato si connette e viene chiuso con `4001` | L'handshake viene rifiutato e il client riceve `1006` |\n\nVedi [WebSocket](../websockets/).\n\n## NoSQL\n\nI file `.nosql` esistenti si possono leggere così come sono. `insert()`, `find()`, `read()`, `update()`, `remove()`, `where()`, `search()`, `fields()`, `skip()`, `take()`, `first()` e il prefisso di aggiornamento `+field` non cambiano.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `find()` parte dal documento più vecchio | `find()` parte dal documento più recente: aggiungi `sort()` quando l'ordine è importante |\n| `find2()` | `find()` |\n| `one()` | `read()` |\n| `sort('age_desc')` | `sort('age', true)` |\n| `NOSQL('users').count()` | `DATA.count('nosql/users')` |\n| `NOSQL('users').list()` | `DATA.list('nosql/users')` |\n| `rule('doc.age > arg.min', { min: 45 })` | `query('doc.age > 45')` |\n| `update({ '-score': 3 })` | `update({ '+score': -3 })` |\n| `TABLE('users')` | `NOSQL('users')` |\n\n`TABLE()` non esiste in Total.js 5, quindi devi spostare tu stesso le righe dei file `.table` in un database NoSQL.\n\nPrima:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run() {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.one().where('id', '2').fields('name').promise();\n\tvar count = await db.count().where('age', '>', 35).promise();\n\tvar list = await db.list().sort('age_desc').fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().rule('doc.age > arg.min', { min: 45 }).fields('name').promise();\n\n\tawait db.update({ '-score': 3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\tthis.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nDopo:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run($) {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.read().where('id', '2').fields('name').promise();\n\tvar count = await DATA.count('nosql/users').where('age', '>', 35).promise();\n\tvar list = await DATA.list('nosql/users').sort('age', true).fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().query('doc.age > 45').fields('name').promise();\n\n\tawait db.update({ '+score': -3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\t$.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nVedi [Database NoSQL](../nosql/).\n\n## RESTBuilder\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| Uno stato `400` o superiore è un errore solo con `.strict()` | Uno stato `400` o superiore è sempre un errore |\n| `.callback($.callback)` in un'operazione | `.callback($)` in un'azione |\n\nIl codice che legge `output.status` dopo una richiesta non riuscita deve prima gestire `err`. Vedi [Richieste HTTP](../http-requests/).\n\n## Configurazione\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `default_root` | `$root` |\n| `default_timezone` | `$timezone` |\n| `default_cookies_samesite` | `$cookiesamesite` |\n| `default_cookies_secure` | `$cookiesecure` |\n| `default_xpoweredby` | `$xpoweredby` |\n| `allow_custom_titles` | `$customtitles` |\n| `allow_gzip` | `$httpcompress` |\n| `limit : 50` è un numero | `limit (number) : 50`: senza tipo il valore è una stringa |\n| `smtp (object) : { port: 465 }` | `smtp (json) : { \"port\": 465 }` |\n| `config-release` | Non viene caricato: tieni i valori in `config` |\n\nPrima:\n\n```text\nname                     : Shop\ndefault_root             : /app/\ndefault_timezone         : Europe/Bratislava\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\ndefault_xpoweredby       : MyServer\nallow_custom_titles      : true\nallow_gzip               : false\n```\n\nDopo:\n\n```text\nname            : Shop\n$root           : /app/\n$timezone       : Europe/Bratislava\n$cookiesamesite : Strict\n$cookiesecure   : true\n$xpoweredby     : MyServer\n$customtitles   : true\n$httpcompress   : false\n```\n\n`CORS()`, `name`, i valori `(array)` e `mail_smtp_options` scritto come oggetto JavaScript funzionano come prima. Vedi [Configurazione](../configuration/).\n\n## Autorizzazione\n\nIl delegate `AUTH()`, i flag di route `+` e `-` e `UNAUTHORIZED()` non cambiano. `SESSION()` non esiste in Total.js 5: usa la sessione integrata di `AUTH()`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SESSION()` con `ondata` | `AUTH(opt)` con `opt.onread` |\n| `session.setcookie($, options, callback)` | `opt.authcookie($, UID(), userid, '1 hour')` |\n| `session.remove2(userid)` e cancellazione del cookie | `opt.logout($)` in un'azione |\n\nPrima:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\tnext(null, { id: meta.id, name: 'Peter' });\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 hour', key: 'session-key' }, 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\nMAIN.session = session;\n```\n\nDopo:\n\n```js\nvar opt = {};\n\nopt.secret = 'session-key';\nopt.cookie = 'sid';\nopt.expire = '1 hour';\n\nopt.onread = function(meta, next) {\n\tnext(null, { id: meta.userid, name: 'Peter' });\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\n```js\nNEWACTION('Account/logout', {\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.logout()` rimuove la sessione dalla memoria e cancella il cookie. Una copia salvata del token è firmata, quindi viene accettata di nuovo ogni volta che `onread` restituisce un utente. Se il logout deve revocare il token, controlla la sessione nel tuo database dentro `onread`. Vedi [Autorizzazione](../authorization/).\n\n## Localizzazione\n\nI file di risorse e `@(Text)` nelle viste restano invariati e le chiavi generate sono identiche.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `LOCALIZE(function(req, res) {})` | `LOCALIZE(function($) {})` |\n| `RESOURCE('sk', 'title')` | `F.resource('sk', 'title')` |\n| `TRANSLATOR('sk', '<b>@(Welcome)</b>')` | `TRANSLATE('sk', '<b>@(Welcome)</b>')` |\n| `TRANSLATE('sk', 'Welcome')` | `TRANSLATE('sk', '@(Welcome)')` |\n\nVedi [Localizzazione](../localization/).\n\n## Email\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MAIL()` esegue il rendering della vista senza layout | `MAIL()` esegue il rendering della vista dentro `views/layout.html` |\n| `ON('mail', fn)` | `ON('$mail', fn)` |\n| `message.address_to` | `message.email_to` |\n\nInizia ogni vista email con `@{layout('')}`. Senza, il messaggio viene inserito nel layout del tuo sito e, se `views/layout.html` non esiste, il messaggio non viene inviato affatto.\n\nPrima:\n\n```html\n<p>Hello @{model.name}</p>\n```\n\nDopo:\n\n```html\n@{layout('')}\n<p>Hello @{model.name}</p>\n```\n\nVedi [Invio di email](../mail/).\n\n## Archiviazione dei file\n\nGli argomenti di `save()` cambiano ordine: i dati personalizzati ora vengono prima della callback.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `fs.save(id, name, data, callback, custom)` | `fs.save(id, name, data, custom, callback)` |\n\n`read()` e `$.filefs()` non cambiano. Vedi [Archiviazione dei file](../file-storage/).\n\n## Pianificazione\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SCHEDULE('* * * * *', fn)` | `CRON('* * * * *', fn)` |\n| `SCHEDULE('03:00', '1 day', fn)` | `CRON('0 3 * * *', fn)` |\n\nPrima:\n\n```js\nMAIN.runs = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nDopo:\n\n```js\nMAIN.runs = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nVedi [Pianificazione ed eventi](../scheduling-and-events/).\n\n## Operazioni e task\n\n`NEWOPERATION()`, `OPERATION()`, `RUN()`, `NEWTASK()` e `TASK()` non esistono in Total.js 5. Ogni operazione diventa un'azione e i passaggi di un task diventano un'azione o più azioni richiamate in sequenza.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `NEWOPERATION('order_price', fn)` | `NEWACTION('order_price', { input: '...', action: fn })` |\n| `OPERATION('order_price', value, callback)` | `ACTION('order_price', value).callback(callback)` |\n| `RUN('order_check, order_price', value, callback)` | `await ACTION(...).promise($)` per ogni passaggio |\n| `NEWTASK('order', fn)` e `TASK('order/check', ...)` | `NEWACTION('order', { action: fn })` |\n\nPrima:\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order() {\n\tvar self = this;\n\tOPERATION('order_price', self.body, function(err, response) {\n\t\tself.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nfunction chain() {\n\tvar self = this;\n\tRUN('order_check, order_price', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.order_price);\n\t});\n}\n```\n\nDopo:\n\n```js\nNEWACTION('order_check', {\n\tinput: '*email:String, count:Number',\n\taction: function($, model) {\n\t\tmodel.email = model.email.toLowerCase();\n\t\t$.callback(model);\n\t}\n});\n\nNEWACTION('order_price', {\n\tinput: 'email:String, count:Number',\n\taction: function($, model) {\n\t\t$.callback({ email: model.email, price: model.count * 10 });\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order($) {\n\tACTION('order_price', $.body).callback(function(err, response) {\n\t\t$.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nasync function chain($) {\n\tvar model = await ACTION('order_check', $.body).promise($);\n\t$.json(await ACTION('order_price', model).promise($));\n}\n```\n\nVedi [Azioni](../actions/).\n\n## Moduli, modelli e definizioni\n\nI file in `definitions/` e `modules/` si caricano come prima, e `MAIN`, `FUNC`, `PATH` e `ON('ready')` non cambiano.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MODULE('greeter').greet('Peter')` | `MODS.greeter.greet('Peter')` |\n| `MODEL('price').total(2, 5)` | `require(PATH.root('models/price.js')).total(2, 5)` |\n| `CACHE('products', value, '5 minutes')` | `CACHE.set('products', value, '5 minutes')` |\n| `CACHE('products')` | `CACHE.read('products')` |\n\nVedi [Struttura dell'applicazione](../application-structure/).\n\n## Test unitari\n\n`TESTER()` viene sostituito dall'oggetto `Test` di `total5/test`.\n\nPrima:\n\n```js\nrequire('total4');\n\nTESTER(function(group, start) {\n\n\tgroup('Strings', function(test) {\n\n\t\ttest('slug()', function(next) {\n\t\t\tnext('Hello World'.slug() === 'hello-world' ? undefined : 'Unexpected slug');\n\t\t});\n\n\t\ttest('capitalize()', function(next) {\n\t\t\tnext('total'.capitalize() === 'Total' ? undefined : 'Unexpected value');\n\t\t});\n\n\t});\n\n\tstart();\n});\n```\n\nDopo:\n\n```js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nVedi [Test unitari](../unit-tests/).\n\n## Riga di comando\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `total4 translate` | `total5 translate \"$PWD/translate.resource\"` |\n\nPassa a `total5 translate` il path completo del file di output. Vedi [Riga di comando](../command-line/).\n\n## Un'applicazione completa\n\nQuesta piccola applicazione di note ha un elenco pubblico, scritture protette, una home page, un'email di notifica, un canale WebSocket in tempo reale e un job eseguito ogni minuto. Entrambe le versioni rispondono alle stesse richieste allo stesso modo, tranne che per il titolo della home page descritto in [Viste](#views).\n\n### Total.js 4\n\n`index.js`\n\n```js\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\n`config`\n\n```text\nname              : Notes\napitoken          : secret\nmail_notify       : admin@example.com\nmail_from         : notes@example.com\nmail_smtp         : 127.0.0.1\nmail_smtp_options : { port: 19854 }\nmaxnotes          : 100\n```\n\n`definitions/auth.js`\n\n```js\nAUTH(function($) {\n\tif ($.headers['x-token'] === CONF.apitoken)\n\t\t$.success({ id: '1', name: 'Admin' });\n\telse\n\t\t$.invalid();\n});\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`schemas/notes.js`\n\n```js\nNEWSCHEMA('Notes', function(schema) {\n\n\tschema.define('title', 'String(50)', value => value && value !== 'spam', 'This title is not allowed');\n\tschema.define('body', 'String(500)');\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('notes').find().sort('dtcreated_desc').fields('id,title').take(CONF.maxnotes).callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('notes').read().id($.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t});\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t});\n\n\tschema.setRemove(function($) {\n\t\tNOSQL('notes').remove().id($.id).callback($.done());\n\t});\n\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        *Notes --> query');\n\tROUTE('GET     /api/notes/{id}/   *Notes --> read');\n\tROUTE('+POST   /api/notes/        *Notes --> insert');\n\tROUTE('+DELETE /api/notes/{id}/   *Notes --> remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats() {\n\tthis.json({ ticks: MAIN.ticks });\n}\n\nfunction live() {\n\tMAIN.live = this;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tvar self = this;\n\tself.title('Latest notes');\n\tNOSQL('notes').find().sort('dtcreated_desc').fields('title').callback(function(err, notes) {\n\t\tself.view('index', notes);\n\t});\n}\n```\n\n`views/layout.html`\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`views/index.html`\n\n```html\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n<p>New note: @{model.title}</p>\n```\n\n### Total.js 5\n\n`definitions/auth.js` e `views/layout.html` restano invariati.\n\n`index.js`\n\n```js\nrequire('total5');\n\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\n`config`\n\n```text\nname                : Notes\napitoken            : secret\nmail_notify         : admin@example.com\nmail_from           : notes@example.com\nmail_smtp           : 127.0.0.1\nmail_smtp_options   : { port: 19854 }\nmaxnotes (number)   : 100\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`actions/notes.js`\n\n```js\nNEWACTION('Notes/query', {\n\taction: function($) {\n\t\tNOSQL('notes').find().sort('dtcreated', true).fields('id,title').take(CONF.maxnotes).callback($);\n\t}\n});\n\nNEWACTION('Notes/read', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').read().id($.params.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/insert', {\n\tinput: '*title:String(50), body:String(500)',\n\taction: function($, model) {\n\n\t\tif (model.title === 'spam') {\n\t\t\t$.invalid('This title is not allowed', 'title');\n\t\t\treturn;\n\t\t}\n\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/remove', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').remove().id($.params.id).callback($.done());\n\t}\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        --> Notes/query');\n\tROUTE('GET     /api/notes/{id}/   --> Notes/read');\n\tROUTE('+POST   /api/notes/        --> Notes/insert');\n\tROUTE('+DELETE /api/notes/{id}/   --> Notes/remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats($) {\n\t$.json({ ticks: MAIN.ticks });\n}\n\nfunction live($) {\n\tMAIN.live = $;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index($) {\n\tNOSQL('notes').find().sort('dtcreated', true).fields('title').callback(function(err, notes) {\n\t\t$.view('index', notes);\n\t});\n}\n```\n\n`views/index.html`\n\n```html\n@{title('Latest notes')}\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n@{layout('')}\n<p>New note: @{model.title}</p>\n```\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:59.647Z"}
{"id":"JanG8G22Z61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/migrating-from-total4/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Migrácia z Total.js 4","summary":"Presuň aplikáciu z Total.js 4 na Total.js 5 oblasť po oblasti, s kódom pred každou zmenou a po nej.","markdown":"---\ntitle: \"Migrácia z Total.js 4\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/migrating-from-total4/\nupdated: 2026-11-18T16:59:59.647Z\n---\n\n# Migrácia z Total.js 4\n\n> Presuň aplikáciu z Total.js 4 na Total.js 5 oblasť po oblasti, s kódom pred každou zmenou a po nej.\n\nTento sprievodca ti ukáže, ako presunúť aplikáciu z Total.js 4 na Total.js 5. Pri každej oblasti uvádza, čo musíš zmeniť, so starým kódom vedľa jeho náhrady a na záver ukazuje malú aplikáciu v oboch verziách.\n\n## Odporúčané poradie práce\n\n1. Nahraď balík `total4` balíkom `total5` a aktualizuj [spúšťací skript](#start-script).\n2. Premenuj [konfiguračné kľúče](#configuration) a číselným hodnotám pridaj typy.\n3. Zmeň [schémy na akcie](#schemas-and-actions) a aktualizuj routy, ktoré ich volajú.\n4. Nahraď `this` za `$` v [routách a kontroléroch](#routes) a v [middlewari](#middleware).\n5. Skontroluj [pohľady](#views) a [mailové pohľady](#mail): priečinky, layouty a titulky.\n6. Aktualizuj dotazy [NoSQL](#nosql), spracovanie chýb v [RESTBuilderi](#restbuilder), [WebSockety](#websockets) a [úložisko súborov](#file-storage).\n7. Nahraď [`SCHEDULE()`](#scheduling), [operácie a úlohy](#operations-and-tasks) a [volania](#modules-models-and-definitions) `MODULE()` a `MODEL()`.\n8. Prepíš [jednotkové testy](#unit-tests) a spusti aplikáciu.\n\n## Spúšťací skript\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `npm install total4` | `npm install total5@beta` |\n| `require('total4/debug')(options)` | `require('total5'); Total.run(options)` |\n| `require('total4/release')(options)` | `options.release = true; Total.run(options)` |\n\nPred zmenou:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.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\nPo zmene:\n\n```js\nrequire('total5');\n\nconst options = {};\n\n// options.ip = '127.0.0.1';\noptions.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\nOba skripty sa spúšťajú v režime debug a príkazom `node index.js --release` v režime release. Pozri [Inštalácia](../installation/).\n\n## Schémy a akcie\n\n`schema.define()` ani rodina funkcií `schema.setInsert()` v Total.js 5 neexistujú. Neupravená schéma zastaví aplikáciu pri štarte chybou `TypeError: schema.define is not a function`. Každú operáciu presuň do `NEWACTION()` v priečinku `actions/` a jej polia deklaruj v `input`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `schema.define('name', 'String(30)', true)` | `input: '*name:String(30)'` |\n| `schema.define('role', ['admin', 'user'])` | `input: 'role:{admin\\|user}'` |\n| `schema.setInsert(fn)`, `setQuery(fn)`, `setRead(fn)`... | `NEWACTION('Users/insert', { action: fn })` |\n| `ROUTE('POST /api/users/ *Users --> insert')` | `ROUTE('POST /api/users/ --> Users/insert')` |\n| `$.id` | `params: '*id:String'` a `$.params.id` |\n| `.callback($.callback)` | `.callback($)` |\n| `$.invalid('age', 'Message')` | `$.invalid('Message', 'age')` |\n| `CALL('Math --> double', data)` | `ACTION('Math/double', data)` |\n\nPred zmenou:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(30)', 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 = 'A1';\n\t\t$.success(model);\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ *Users --> insert');\n};\n```\n\nPo zmene:\n\n```js\nNEWACTION('Users/insert', {\n\tinput: '*name:String(30), *email:Email, age:Number, role:{admin|user}',\n\taction: function($, model) {\n\t\tmodel.id = 'A1';\n\t\t$.success(model);\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/users/ --> Users/insert');\n};\n```\n\n### Vlastné validátory\n\nFunkcia validátora zo `schema.define()` sa presúva do akcie.\n\nPred zmenou:\n\n```js\nNEWSCHEMA('Signup', function(schema) {\n\n\tschema.define('name', 'String(30)', true);\n\tschema.define('age', Number, value => value >= 18, 'You must be an adult');\n\n\tschema.setInsert(function($, model) {\n\t\t$.success(model.age);\n\t});\n\n});\n```\n\nPo zmene:\n\n```js\nNEWACTION('Signup/insert', {\n\tinput: '*name:String(30), age:Number',\n\taction: function($, model) {\n\n\t\tif (model.age < 18) {\n\t\t\t$.invalid('You must be an adult', 'age');\n\t\t\treturn;\n\t\t}\n\n\t\t$.success(model.age);\n\t}\n});\n```\n\n### Schémy, ktoré už používajú `schema.action()`\n\nTieto schémy fungujú ďalej. Mení sa len routa: z `*Tags --> list` bude `--> Tags/list`.\n\n```js\nNEWSCHEMA('Tags', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of tags',\n\t\tquery: 'limit:Number',\n\t\taction: function($) {\n\t\t\t$.callback(['a', 'b', 'c'].slice(0, $.query.limit || 3));\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a tag',\n\t\tinput: '*name:String(20)',\n\t\taction: function($, model) {\n\t\t\t$.success(model.name);\n\t\t}\n\t});\n\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('GET  /api/tags/ --> Tags/list');\n\tROUTE('POST /api/tags/ --> Tags/create');\n};\n```\n\n### Hodnoty a chyby, ktoré si všimnú tvoji klienti\n\n| Prípad | Total.js 4 | Total.js 5 |\n| --- | --- | --- |\n| Chýba voliteľné `Number` | Pole má hodnotu `0` | Pole sa vynechá |\n| Chýba voliteľný enum | Pole sa vynechá | Pole má hodnotu `''` |\n| Hodnota enumu nie je v zozname | Hodnota sa zahodí, požiadavka sa prijme | `400` s chybou pri danom poli |\n| Kľúče chyby povinného poľa | `name`, `error`, `path`, `prefix` | `name`, `error`, `path` |\n| Kľúče chyby z `$.invalid()` s poľom | `name`, `error` | `error`, `path` |\n\nKlient, ktorý z tvojich vlastných chýb číta `name`, musí namiesto toho čítať `path`. Pozri [Akcie](../actions/) a [JSON schémy](../json-schemas/).\n\n## Routy\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function detail(id) { this.json({ id: id }); }` | `function detail($) { $.json({ id: $.params.id }); }` |\n| `ROUTE('/about/', fn)` | `ROUTE('GET /about/', fn)`: metóda je povinná |\n| `{page:number}` skonvertuje hodnotu | `{page}` je reťazec: `$.params.page.parseInt()` |\n| `ROUTE('POST /upload/', fn, ['upload'], 1024)` | `ROUTE('POST /upload/ @upload <1MB', fn)` |\n| `ROUTE('POST /import/', fn, 1024)` | `ROUTE('POST /import/ <1MB', fn)` |\n| `ROUTE('+GET /admin/ @admin', fn)` | `ROUTE('+GET /admin/', fn)` a `UNAUTHORIZED($, 'admin')` v obslužnej funkcii |\n| `ROUTE('API /api/ -users_list *Users --> list')` | `ROUTE('API /api/ users_list --> Users/list')` |\n| `ROUTE('API /api/ +users_save *Users --> save')` | `ROUTE('API /api/ users_save --> Users/save')` |\n\nRouta bez flagu veľkosti odmietne telo JSON väčšie ako 256 kB kódom `431`, preto routám, ktoré importujú veľké dáta, nastav vlastný limit. Neznámy endpoint `API` odpovie `400` namiesto `404`. Pozri [Smerovanie](../routing/).\n\nPred zmenou:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail(id, order) {\n\tthis.json({ id: id, order: order, params: this.params });\n}\n```\n\nPo zmene:\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', detail);\n};\n\nfunction detail($) {\n\t$.json({ id: $.params.id, order: $.params.order, params: $.params });\n}\n```\n\n## Kontroléry\n\nObslužné funkcie dostávajú kontrolér ako `$`. V HTTP routách už `this` nie je kontrolér.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.status = 201` | `$.response.status = 201` |\n| `this.header('X-Version', '1')` | `$.response.headers['x-version'] = '1'` |\n| `this.nocache()` | `$.response.headers['cache-control'] = 'private, no-cache, no-store, max-age=0'` |\n| `this.content('<a>1</a>', 'text/xml')` | `$.xml('<a>1</a>')` |\n| `this.content('id;name', 'text/csv')` | `$.binary(Buffer.from('id;name'), 'text/csv')` |\n| `this.nocontent()` | `$.empty()` |\n| `this.throw404()`, `this.throw403()` | `$.fallback(404)`, `$.fallback(403)` |\n| `this.throw500('Problem')` | `$.fallback(500, 'Problem')` |\n| `this.file('docs/a.txt', 'report.txt')` | `$.file(PATH.public('docs/a.txt'), 'report.txt')` |\n| `this.success(true, 42)` | `$.success(42)` |\n| `this.success(false)` | `$.json({ success: false })` |\n| `this.invalid('email', 'Message')` | `var err = new ErrorBuilder(); err.push('Message', 'email'); $.invalid(err);` |\n| `file.isImage()` | `file.isImage` |\n| `this.mail(email, subject, view, model)` | `MAIL(email, subject, view, model)` |\n\nPri týchto členoch stačí nahradiť `this` za `$`: `params`, `query`, `body`, `files`, `headers`, `url`, `ip`, `ua`, `mobile`, `robot`, `xhr`, `referrer`, `user`, `language`, `cookie()`, `hostname()`, `json()`, `plain()`, `view()`, `filefs()` a `stream(type, stream)`.\n\nChybová routa nastavuje stav rovnakým spôsobom:\n\n```js\nexports.install = function() {\n\tROUTE('GET /missing/', missing);\n\tROUTE('GET /denied/', denied);\n\tROUTE('GET /broken/', broken);\n\tROUTE('#404', notfound);\n};\n\nfunction missing($) {\n\t$.fallback(404);\n}\n\nfunction denied($) {\n\t$.fallback(403);\n}\n\nfunction broken($) {\n\t$.fallback(500, 'Unexpected problem');\n}\n\nfunction notfound($) {\n\t$.response.status = 404;\n\t$.plain('My 404 page');\n}\n```\n\nPozri [Kontrolér](../controller/).\n\n## Pohľady\n\nSyntax súborov pohľadov sa nemení: výrazy, podmienky, cykly, sekcie, čiastkové pohľady a helpery z `DEF.helpers` fungujú ako predtým.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `this.view('detail')` v `controllers/users.js` nájde `views/users/detail.html` | `$.view('users/detail')`: názov sa vždy začína v `views/` |\n| Layout môže čítať `model` | V pohľade nastav `@{repository.name = model.name}` a v layoute čítaj `repository` |\n| `this.title('Products')` | `@{title('Products')}` v pohľade |\n| `this.repository.page = 'list'` | `@{repository.page = 'list'}` v pohľade |\n| `VIEW('mail/order', model)` | `F.view('mail/order', model)`, s `@{layout('')}` v pohľade |\n| K titulku domovskej stránky sa pridá ` - ` a `CONF.name` | Titulok domovskej stránky zostane tak, ako ho napíšeš |\n\nPred zmenou:\n\n```html\n<title>@{model.name}</title>@{body}\n```\n\nPo zmene:\n\n```html\n<title>@{repository.name}</title>@{body}\n```\n\n```html\n@{repository.name = model.name}\n<h1>@{model.name}</h1>\n```\n\nPozri [Pohľady](../views/).\n\n## Middleware\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MIDDLEWARE('name', function($) { $.next(); })` | `NEWMIDDLEWARE('name', function($, next) { next(); })` |\n| `$.res.throw401()` | `$.invalid(401)` |\n| `$.res.setHeader('x-stamp', 'yes')` | `$.response.headers['x-stamp'] = 'yes'` |\n| `ROUTE('GET /private/', fn, ['#apikey'])` | `ROUTE('GET /private/ #apikey', fn)` |\n| `ROUTE('GET /open/ &stamp', fn)` | `ROUTE('GET /open/ #stamp', fn)` |\n| `USE('poweredby', ['web'])` | Tretí argument `'routes'`, vnútri `ON('ready')` |\n\nPred zmenou:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('x-server', 'myapp');\n\t$.next();\n});\n\nUSE('poweredby', ['web']);\n```\n\nPo zmene:\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('poweredby', function($, next) {\n\t\t$.response.headers['x-server'] = 'myapp';\n\t\tnext();\n\t}, 'routes');\n});\n```\n\nPozri [Middleware](../middleware/).\n\n## WebSockety\n\nRouta `SOCKET` si zachováva svoju štruktúru a `this` v jej obslužnej funkcii stále funguje.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `function room(name) {}` | `function room($) { var name = $.params.name; }` |\n| `ROUTE('SOCKET /feed/', fn, ['json'], 64)` | `ROUTE('SOCKET /feed/ <64kB', fn)` |\n| `ROUTE('SOCKET /terminal/', fn, ['text'])` | `ROUTE('SOCKET /terminal/ @text', fn)` |\n| `client.send(text)` na textovej route | `client.send(text, true)` |\n| `client.close('finished', 4000)` | `client.close(4000, 'finished')` |\n| Odmietnutý klient `+SOCKET` sa pripojí a spojenie sa zatvorí s kódom `4001` | Handshake sa odmietne a klient dostane `1006` |\n\nPozri [WebSockety](../websockets/).\n\n## NoSQL\n\nExistujúce súbory `.nosql` môžeš čítať bez úprav. `insert()`, `find()`, `read()`, `update()`, `remove()`, `where()`, `search()`, `fields()`, `skip()`, `take()`, `first()` a prefix aktualizácie `+field` sa nemenia.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `find()` začína najstarším dokumentom | `find()` začína najnovším dokumentom: ak záleží na poradí, pridaj `sort()` |\n| `find2()` | `find()` |\n| `one()` | `read()` |\n| `sort('age_desc')` | `sort('age', true)` |\n| `NOSQL('users').count()` | `DATA.count('nosql/users')` |\n| `NOSQL('users').list()` | `DATA.list('nosql/users')` |\n| `rule('doc.age > arg.min', { min: 45 })` | `query('doc.age > 45')` |\n| `update({ '-score': 3 })` | `update({ '+score': -3 })` |\n| `TABLE('users')` | `NOSQL('users')` |\n\n`TABLE()` v Total.js 5 neexistuje, takže riadky zo súborov `.table` si do databázy NoSQL musíš presunúť vlastnými silami.\n\nPred zmenou:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run() {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.one().where('id', '2').fields('name').promise();\n\tvar count = await db.count().where('age', '>', 35).promise();\n\tvar list = await db.list().sort('age_desc').fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().rule('doc.age > arg.min', { min: 45 }).fields('name').promise();\n\n\tawait db.update({ '-score': 3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\tthis.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nPo zmene:\n\n```js\nexports.install = function() {\n\tROUTE('GET /run/', run);\n};\n\nasync function run($) {\n\tvar db = NOSQL('users');\n\tawait db.insert({ id: '1', name: 'Ann', age: 30, score: 10 }).promise();\n\tawait db.insert({ id: '2', name: 'Bob', age: 40, score: 10 }).promise();\n\tawait db.insert({ id: '3', name: 'Cid', age: 50, score: 10 }).promise();\n\n\tvar one = await db.read().where('id', '2').fields('name').promise();\n\tvar count = await DATA.count('nosql/users').where('age', '>', 35).promise();\n\tvar list = await DATA.list('nosql/users').sort('age', true).fields('name').paginate(1, 2).promise();\n\tvar rule = await db.find().query('doc.age > 45').fields('name').promise();\n\n\tawait db.update({ '+score': -3 }).where('id', '1').promise();\n\tvar score = await db.read().id('1').fields('score').promise();\n\n\t$.json({ one: one, count: count.count, items: list.items, pages: list.pages, total: list.count, rule: rule, score: score });\n}\n```\n\nPozri [Databáza NoSQL](../nosql/).\n\n## RESTBuilder\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| Stav `400` alebo vyšší je chybou len s `.strict()` | Stav `400` alebo vyšší je vždy chybou |\n| `.callback($.callback)` v operácii | `.callback($)` v akcii |\n\nKód, ktorý po neúspešnej požiadavke číta `output.status`, musí najprv spracovať `err`. Pozri [HTTP požiadavky](../http-requests/).\n\n## Konfigurácia\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `default_root` | `$root` |\n| `default_timezone` | `$timezone` |\n| `default_cookies_samesite` | `$cookiesamesite` |\n| `default_cookies_secure` | `$cookiesecure` |\n| `default_xpoweredby` | `$xpoweredby` |\n| `allow_custom_titles` | `$customtitles` |\n| `allow_gzip` | `$httpcompress` |\n| `limit : 50` je číslo | `limit (number) : 50`: bez typu je hodnota reťazec |\n| `smtp (object) : { port: 465 }` | `smtp (json) : { \"port\": 465 }` |\n| `config-release` | Nenačíta sa: hodnoty maj v `config` |\n\nPred zmenou:\n\n```text\nname                     : Shop\ndefault_root             : /app/\ndefault_timezone         : Europe/Bratislava\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\ndefault_xpoweredby       : MyServer\nallow_custom_titles      : true\nallow_gzip               : false\n```\n\nPo zmene:\n\n```text\nname            : Shop\n$root           : /app/\n$timezone       : Europe/Bratislava\n$cookiesamesite : Strict\n$cookiesecure   : true\n$xpoweredby     : MyServer\n$customtitles   : true\n$httpcompress   : false\n```\n\n`CORS()`, `name`, hodnoty `(array)` a `mail_smtp_options` zapísané ako objekt JavaScriptu fungujú ako predtým. Pozri [Konfigurácia](../configuration/).\n\n## Autorizácia\n\nDelegate `AUTH()`, flagy rout `+` a `-` a `UNAUTHORIZED()` sa nemenia. `SESSION()` v Total.js 5 neexistuje: použi vstavanú session z `AUTH()`.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SESSION()` s `ondata` | `AUTH(opt)` s `opt.onread` |\n| `session.setcookie($, options, callback)` | `opt.authcookie($, UID(), userid, '1 hour')` |\n| `session.remove2(userid)` a vymazanie cookie | `opt.logout($)` v akcii |\n\nPred zmenou:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\tnext(null, { id: meta.id, name: 'Peter' });\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 hour', key: 'session-key' }, 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\nMAIN.session = session;\n```\n\nPo zmene:\n\n```js\nvar opt = {};\n\nopt.secret = 'session-key';\nopt.cookie = 'sid';\nopt.expire = '1 hour';\n\nopt.onread = function(meta, next) {\n\tnext(null, { id: meta.userid, name: 'Peter' });\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\n```js\nNEWACTION('Account/logout', {\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.logout()` odstráni session z pamäte a vymaže cookie. Uložená kópia tokenu je podpísaná, takže sa znova prijme vždy, keď `onread` vráti používateľa. Ak má odhlásenie token zneplatniť, over session vo svojej databáze vnútri `onread`. Pozri [Autorizácia](../authorization/).\n\n## Lokalizácia\n\nSúbory zdrojov a `@(Text)` v pohľadoch zostávajú rovnaké a vygenerované kľúče sú identické.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `LOCALIZE(function(req, res) {})` | `LOCALIZE(function($) {})` |\n| `RESOURCE('sk', 'title')` | `F.resource('sk', 'title')` |\n| `TRANSLATOR('sk', '<b>@(Welcome)</b>')` | `TRANSLATE('sk', '<b>@(Welcome)</b>')` |\n| `TRANSLATE('sk', 'Welcome')` | `TRANSLATE('sk', '@(Welcome)')` |\n\nPozri [Lokalizácia](../localization/).\n\n## E-mail\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MAIL()` vykreslí pohľad bez layoutu | `MAIL()` vykreslí pohľad do `views/layout.html` |\n| `ON('mail', fn)` | `ON('$mail', fn)` |\n| `message.address_to` | `message.email_to` |\n\nKaždý mailový pohľad začni s `@{layout('')}`. Bez neho sa správa zabalí do layoutu tvojho webu a ak `views/layout.html` neexistuje, správa sa vôbec neodošle.\n\nPred zmenou:\n\n```html\n<p>Hello @{model.name}</p>\n```\n\nPo zmene:\n\n```html\n@{layout('')}\n<p>Hello @{model.name}</p>\n```\n\nPozri [Odosielanie e-mailov](../mail/).\n\n## Úložisko súborov\n\nArgumenty funkcie `save()` menia poradie: vlastné dáta sú teraz pred callbackom.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `fs.save(id, name, data, callback, custom)` | `fs.save(id, name, data, custom, callback)` |\n\n`read()` a `$.filefs()` sa nemenia. Pozri [Úložisko súborov](../file-storage/).\n\n## Plánovanie\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `SCHEDULE('* * * * *', fn)` | `CRON('* * * * *', fn)` |\n| `SCHEDULE('03:00', '1 day', fn)` | `CRON('0 3 * * *', fn)` |\n\nPred zmenou:\n\n```js\nMAIN.runs = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nPo zmene:\n\n```js\nMAIN.runs = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.runs++;\n});\n```\n\nPozri [Plánovanie a udalosti](../scheduling-and-events/).\n\n## Operácie a úlohy\n\n`NEWOPERATION()`, `OPERATION()`, `RUN()`, `NEWTASK()` ani `TASK()` v Total.js 5 neexistujú. Z každej operácie sa stane akcia a z krokov úlohy jedna akcia alebo niekoľko akcií volaných postupne.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `NEWOPERATION('order_price', fn)` | `NEWACTION('order_price', { input: '...', action: fn })` |\n| `OPERATION('order_price', value, callback)` | `ACTION('order_price', value).callback(callback)` |\n| `RUN('order_check, order_price', value, callback)` | `await ACTION(...).promise($)` pre každý krok |\n| `NEWTASK('order', fn)` a `TASK('order/check', ...)` | `NEWACTION('order', { action: fn })` |\n\nPred zmenou:\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order() {\n\tvar self = this;\n\tOPERATION('order_price', self.body, function(err, response) {\n\t\tself.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nfunction chain() {\n\tvar self = this;\n\tRUN('order_check, order_price', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.order_price);\n\t});\n}\n```\n\nPo zmene:\n\n```js\nNEWACTION('order_check', {\n\tinput: '*email:String, count:Number',\n\taction: function($, model) {\n\t\tmodel.email = model.email.toLowerCase();\n\t\t$.callback(model);\n\t}\n});\n\nNEWACTION('order_price', {\n\tinput: 'email:String, count:Number',\n\taction: function($, model) {\n\t\t$.callback({ email: model.email, price: model.count * 10 });\n\t}\n});\n```\n\n```js\nexports.install = function() {\n\tROUTE('POST /order/', order);\n\tROUTE('POST /chain/', chain);\n};\n\nfunction order($) {\n\tACTION('order_price', $.body).callback(function(err, response) {\n\t\t$.json({ err: err ? err.toString() : null, response: response });\n\t});\n}\n\nasync function chain($) {\n\tvar model = await ACTION('order_check', $.body).promise($);\n\t$.json(await ACTION('order_price', model).promise($));\n}\n```\n\nPozri [Akcie](../actions/).\n\n## Moduly, modely a definície\n\nSúbory v `definitions/` a `modules/` sa načítavajú ako predtým a `MAIN`, `FUNC`, `PATH` a `ON('ready')` sa nemenia.\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `MODULE('greeter').greet('Peter')` | `MODS.greeter.greet('Peter')` |\n| `MODEL('price').total(2, 5)` | `require(PATH.root('models/price.js')).total(2, 5)` |\n| `CACHE('products', value, '5 minutes')` | `CACHE.set('products', value, '5 minutes')` |\n| `CACHE('products')` | `CACHE.read('products')` |\n\nPozri [Štruktúra aplikácie](../application-structure/).\n\n## Jednotkové testy\n\n`TESTER()` nahrádza objekt `Test` z `total5/test`.\n\nPred zmenou:\n\n```js\nrequire('total4');\n\nTESTER(function(group, start) {\n\n\tgroup('Strings', function(test) {\n\n\t\ttest('slug()', function(next) {\n\t\t\tnext('Hello World'.slug() === 'hello-world' ? undefined : 'Unexpected slug');\n\t\t});\n\n\t\ttest('capitalize()', function(next) {\n\t\t\tnext('total'.capitalize() === 'Total' ? undefined : 'Unexpected value');\n\t\t});\n\n\t});\n\n\tstart();\n});\n```\n\nPo zmene:\n\n```js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nPozri [Jednotkové testy](../unit-tests/).\n\n## Príkazový riadok\n\n| Total.js 4 | Total.js 5 |\n| --- | --- |\n| `total4 translate` | `total5 translate \"$PWD/translate.resource\"` |\n\nPríkazu `total5 translate` zadaj úplný path výstupného súboru. Pozri [Príkazový riadok](../command-line/).\n\n## Kompletná aplikácia\n\nTáto malá aplikácia na poznámky má verejný zoznam, chránený zápis, domovskú stránku, notifikačný e-mail, živý kanál WebSocket a úlohu, ktorá sa spúšťa každú minútu. Obe verzie odpovedajú na rovnaké požiadavky rovnako, s výnimkou titulku domovskej stránky opísaného v časti [Pohľady](#views).\n\n### Total.js 4\n\n`index.js`\n\n```js\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\n`config`\n\n```text\nname              : Notes\napitoken          : secret\nmail_notify       : admin@example.com\nmail_from         : notes@example.com\nmail_smtp         : 127.0.0.1\nmail_smtp_options : { port: 19854 }\nmaxnotes          : 100\n```\n\n`definitions/auth.js`\n\n```js\nAUTH(function($) {\n\tif ($.headers['x-token'] === CONF.apitoken)\n\t\t$.success({ id: '1', name: 'Admin' });\n\telse\n\t\t$.invalid();\n});\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nSCHEDULE('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`schemas/notes.js`\n\n```js\nNEWSCHEMA('Notes', function(schema) {\n\n\tschema.define('title', 'String(50)', value => value && value !== 'spam', 'This title is not allowed');\n\tschema.define('body', 'String(500)');\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('notes').find().sort('dtcreated_desc').fields('id,title').take(CONF.maxnotes).callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('notes').read().id($.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t});\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t});\n\n\tschema.setRemove(function($) {\n\t\tNOSQL('notes').remove().id($.id).callback($.done());\n\t});\n\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        *Notes --> query');\n\tROUTE('GET     /api/notes/{id}/   *Notes --> read');\n\tROUTE('+POST   /api/notes/        *Notes --> insert');\n\tROUTE('+DELETE /api/notes/{id}/   *Notes --> remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats() {\n\tthis.json({ ticks: MAIN.ticks });\n}\n\nfunction live() {\n\tMAIN.live = this;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tvar self = this;\n\tself.title('Latest notes');\n\tNOSQL('notes').find().sort('dtcreated_desc').fields('title').callback(function(err, notes) {\n\t\tself.view('index', notes);\n\t});\n}\n```\n\n`views/layout.html`\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n`views/index.html`\n\n```html\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n<p>New note: @{model.title}</p>\n```\n\n### Total.js 5\n\n`definitions/auth.js` a `views/layout.html` zostávajú rovnaké.\n\n`index.js`\n\n```js\nrequire('total5');\n\nconst options = {};\n\noptions.port = parseInt(process.argv[2]);\noptions.release = process.argv.includes('--release');\n\nTotal.run(options);\n```\n\n`config`\n\n```text\nname                : Notes\napitoken            : secret\nmail_notify         : admin@example.com\nmail_from           : notes@example.com\nmail_smtp           : 127.0.0.1\nmail_smtp_options   : { port: 19854 }\nmaxnotes (number)   : 100\n```\n\n`definitions/jobs.js`\n\n```js\nMAIN.ticks = 0;\n\nCRON('* * * * *', function() {\n\tMAIN.ticks++;\n});\n```\n\n`actions/notes.js`\n\n```js\nNEWACTION('Notes/query', {\n\taction: function($) {\n\t\tNOSQL('notes').find().sort('dtcreated', true).fields('id,title').take(CONF.maxnotes).callback($);\n\t}\n});\n\nNEWACTION('Notes/read', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').read().id($.params.id).fields('id,title,body').callback(function(err, note) {\n\t\t\tif (note)\n\t\t\t\t$.callback(note);\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/insert', {\n\tinput: '*title:String(50), body:String(500)',\n\taction: function($, model) {\n\n\t\tif (model.title === 'spam') {\n\t\t\t$.invalid('This title is not allowed', 'title');\n\t\t\treturn;\n\t\t}\n\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = new Date();\n\t\tNOSQL('notes').insert(model).callback(function() {\n\t\t\tMAIL(CONF.mail_notify, 'New note', 'mail/note', model);\n\t\t\tMAIN.live && MAIN.live.send({ type: 'note', title: model.title });\n\t\t\t$.success(model.id);\n\t\t});\n\t}\n});\n\nNEWACTION('Notes/remove', {\n\tparams: '*id:String',\n\taction: function($) {\n\t\tNOSQL('notes').remove().id($.params.id).callback($.done());\n\t}\n});\n```\n\n`controllers/api.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET     /api/notes/        --> Notes/query');\n\tROUTE('GET     /api/notes/{id}/   --> Notes/read');\n\tROUTE('+POST   /api/notes/        --> Notes/insert');\n\tROUTE('+DELETE /api/notes/{id}/   --> Notes/remove');\n\tROUTE('GET     /api/stats/',      stats);\n\tROUTE('SOCKET  /live/',           live);\n};\n\nfunction stats($) {\n\t$.json({ ticks: MAIN.ticks });\n}\n\nfunction live($) {\n\tMAIN.live = $;\n}\n```\n\n`controllers/default.js`\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index($) {\n\tNOSQL('notes').find().sort('dtcreated', true).fields('title').callback(function(err, notes) {\n\t\t$.view('index', notes);\n\t});\n}\n```\n\n`views/index.html`\n\n```html\n@{title('Latest notes')}\n<h1>@{config.name}</h1>\n<ul>\n@{foreach note in model}\n\t<li>@{note.title}</li>\n@{end}\n</ul>\n```\n\n`views/mail/note.html`\n\n```html\n@{layout('')}\n<p>New note: @{model.title}</p>\n```\n","entries":[],"license":"MIT","updated":"2026-11-18T16:59:59.647Z"}
{"id":"JaedEODGT61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/routing/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Routing","summary":"Declare routes with ROUTE(): methods, dynamic paths, authorization, actions, API endpoints, flags, file routes, CORS and proxies.","markdown":"---\ntitle: Routing\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/routing/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Routing\n\n> Declare routes with ROUTE(): methods, dynamic paths, authorization, actions, API endpoints, flags, file routes, CORS and proxies.\n\nRoutes connect URLs to code. You declare them with the global `ROUTE()` in the `install` function of a file in `/controllers/` (or of a plugin or a module). Each route is a single string: the HTTP method, the path and optional flags, followed by the action.\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /products/{id}/', detail);\n\tROUTE('POST /contact/', contact);\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n\nfunction detail($) {\n\t$.json({ id: $.params.id });\n}\n\nfunction contact($) {\n\t// $.body contains the parsed JSON or form data\n\t$.success();\n}\n```\n\nThe action receives the controller `$`. Its properties and methods (`$.params`, `$.body`, `$.query`, `$.json()`, `$.view()`...) are described in [Controller](../../guides/controller/).\n\n## Methods and paths\n\nThe first word is the method: `GET`, `POST`, `PUT`, `PATCH`, `DELETE` or any other method name. The path is compared in lower case and the trailing slash does not matter. When `CONF.$root` is set (for example `/admin/`), it is prepended to every path.\n\nThe action can be:\n\n- a function, called with the controller;\n- a string, the name of a view that is rendered;\n- missing, then a view named after the first segment of the path is rendered (`index` for `/`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');      // views/index.html\n\tROUTE('GET /about/');         // views/about.html\n\tROUTE('GET /pricing/', 'cms/pricing');\n};\n```\n\n## Dynamic parameters and wildcards\n\nA segment in curly braces is a parameter. Its value is in `$.params` as a string, with the case of the request URL. A route with parameters matches only URLs with the same number of segments.\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', function($) {\n\t\t$.json({ user: $.params.id, order: $.params.order });\n\t});\n\tROUTE('GET /docs/*', function($) {\n\t\t// /docs/, /docs/a/, /docs/a/b/c/ ...\n\t\t$.plain($.url);\n\t});\n};\n```\n\nA `*` at the end makes a wildcard route: it matches the path and everything below it. Fixed routes are checked first, then routes with parameters, then wildcards.\n\n## Authorization: `+` and `-`\n\nPrefix the method with `+` for routes that need a signed-in user, or with `-` for routes only for visitors who are not signed in. The [AUTH()](../../guides/authorization/) delegate decides who is signed in; when the user does not fit any route of the URL, the answer is `401`. Without `AUTH()` the prefixes are not checked and every route serves everybody. A route without a prefix serves everybody.\n\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', 'account');\n\tROUTE('-GET /account/', 'login');\n\tROUTE('+POST /account/password/', password);\n};\n```\n\nYou can declare the same URL twice, once with `+` and once with `-`, as above.\n\n## Actions with `-->`\n\nInstead of a function, a route can call [actions](../../guides/actions/) declared with `NEWACTION()`. Write their names after `-->`. The request body is the payload and the result is sent back as the response (an error is sent with `$.invalid()`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/ --> Products/list');\n\tROUTE('+POST /api/products/ --> Products/insert');\n\tROUTE('+PUT /api/products/{id}/ --> Products/update');\n\tROUTE('+POST /api/orders/ --> Orders/insert Orders/read (response)');\n};\n```\n\nWith several actions, `(response)` marks the action whose result is the response.\n\n## API routes with `?`\n\n`API` routes put many operations behind one URL. A `?` in the path is replaced with `CONF.$api` (default `/api/`). The client sends `POST` with a JSON body `{ \"schema\": \"name/param?query\", \"data\": {...} }`; the framework finds the endpoint `name`, fills `$.params` from the path parts, `$.query` from the part after `?`, and uses `data` as the body.\n\n```js\nexports.install = function() {\n\tROUTE('API ? products_list --> Products/list');\n\tROUTE('API ? products_read/{id} --> Products/read');\n\tROUTE('+API ? products_save --> Products/save');\n\tROUTE('+API ? products_remove/{id} --> Products/remove');\n};\n```\n\n```js\n// client\nAJAX('POST /api/', { schema: 'products_read/123', data: null }, console.log);\n```\n\n`+API` and `-API` set the authorization of each endpoint separately. A missing parameter is answered with an error for `params.<name>`, and an unknown endpoint or a body without `schema` with `400`.\n\n## Flags\n\nFlags follow the path. `@flag` limits when the route matches, `#name` runs a middleware, `<value` sets a body size limit or a timeout.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', upload);\n\tROUTE('POST /api/import/ @json <2m', importdata);\n\tROUTE('GET /dashboard/ @xhr #nocache', dashboard);\n};\n```\n\n| Flag | The route matches only when |\n| --- | --- |\n| `@json` | The body is JSON |\n| `@xml` | The body is XML |\n| `@upload` | The body is `multipart/form-data` |\n| `@xhr` | The request has `X-Requested-With: XMLHttpRequest` |\n| `@mobile` | The client is a mobile device |\n| `@robot` | The client is a crawler |\n| `@referrer` (or `@referer`) | The `Referer` header contains the host of the request |\n| `@debug` | The application runs in debug mode |\n| `@release` | The application runs in release mode |\n\nWhen two routes have the same method and path, the one with fewer flags is checked first. Size limits and timeouts:\n\n| Flag | Meaning |\n| --- | --- |\n| `<500b` | Body size limit in bytes |\n| `<512kB` | Body size limit in kilobytes (1 kB = 1024 bytes) |\n| `<10MB` | Body size limit in megabytes |\n| `<2GB` | Body size limit in gigabytes |\n| `<30s` | Timeout in seconds |\n| `<5m` | Timeout in minutes |\n| `<1h` | Timeout in hours |\n\nWithout a size flag, the limit is `CONF.$httpmaxsize` (256 kB); a larger body is answered with `431`. Without a timeout flag, the request has `CONF.$httptimeout` (5 seconds) and then ends with `503`. The timeout is checked every 5 seconds. The third argument of `ROUTE()` also sets the limit, in bytes: `ROUTE('POST /import/', fn, 1024 * 1024 * 50)`.\n\n## Middleware\n\n`#name` runs the middleware registered with `MIDDLEWARE(name, fn)` before the action, in the order written. See [Middleware](../../guides/middleware/).\n\n```js\nMIDDLEWARE('nocache', function($, next) {\n\t$.response.headers['cache-control'] = 'no-store';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /report/ #nocache', report);\n};\n```\n\n## File routes\n\nThe `FILE` method handles requests for static files (URLs with an extension) with your own code.\n\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', robots);          // one file\n\tROUTE('FILE /docs/*.md|txt', docs);          // extensions inside /docs/\n\tROUTE('FILE /downloads/*', downloads);       // every file inside /downloads/\n\tROUTE('FILE *.webp', webp);                  // every .webp file\n};\n\nfunction robots($) {\n\t$.plain('User-agent: *');\n}\n\nfunction downloads($) {\n\t$.file(PATH.databases('files' + $.url.substring(10)), true);\n}\n```\n\n## WebSocket routes\n\n`SOCKET` (or `WEBSOCKET`) declares a WebSocket endpoint with the same path syntax, `+`/`-` and size flags. See [WebSockets](../../guides/websockets/).\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/ <1MB', chat);\n};\n```\n\n## Error routes\n\nA route named `#` plus a status code replaces the default error page for that code.\n\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n## Removing a route\n\n`ROUTE()` returns the route object. Call `remove()` on it to unregister the route while the application runs; the routing table is sorted again at once. It works for every kind of route: an HTTP route, one API endpoint (the shared `POST` route of the API disappears with its last endpoint), a `FILE` route and a `SOCKET` route (its open connections are closed).\n\n```js\nvar route = ROUTE('GET /promo/', function($) {\n\t$.plain('Promo is running');\n});\n\nvar endpoint = ROUTE('API ? promo_read --> Promo/read');\n\n// later\nroute.remove();\nendpoint.remove();\n```\n\n## CORS\n\nRequests with an `Origin` header from another host are checked against `CONF.$cors`. Set it with `CORS()` or in `/config`.\n\n```js\nCORS();                                         // any origin\nCORS('https://app.example.com,https://admin.example.com');\nCORS('+https://partner.example.com');           // add one more\nCORS('*example.com');                           // any origin that contains example.com\n```\n\nAn allowed request gets `Access-Control-Allow-*` headers and a preflight `OPTIONS` request is answered at once. A refused origin gets `400` with `Invalid origin (CORS)`.\n\n## Proxies\n\n`PROXY(path, target)` forwards every request whose path starts with `path` to another server, before the routes are searched. The target is an `http://` or `https://` URL, a Unix socket path, or a function that receives the controller.\n\n```js\nPROXY('/cdn/', 'https://cdn.example.com').copy('extend').timeout(10000);\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nThe forwarded request gets `X-Forwarded-For`, `X-Forwarded-URL` and `X-Forwarded-Host`. When the target fails, the client gets `503`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"JaedEODGT61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/routing/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Routing","summary":"Routen mit ROUTE() deklarieren: Methoden, dynamische Pfade, Autorisierung, Aktionen, API-Endpunkte, Flags, Datei-Routen, CORS und Proxys.","markdown":"---\ntitle: Routing\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/routing/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Routing\n\n> Routen mit ROUTE() deklarieren: Methoden, dynamische Pfade, Autorisierung, Aktionen, API-Endpunkte, Flags, Datei-Routen, CORS und Proxys.\n\nRouten verbinden URLs mit Code. Du deklarierst sie mit dem globalen `ROUTE()` in der Funktion `install` einer Datei in `/controllers/` (oder eines Plugins oder Moduls). Jede Route ist ein einzelner String: die HTTP-Methode, der Pfad und optionale Flags, gefolgt von der Aktion.\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /products/{id}/', detail);\n\tROUTE('POST /contact/', contact);\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n\nfunction detail($) {\n\t$.json({ id: $.params.id });\n}\n\nfunction contact($) {\n\t// $.body contains the parsed JSON or form data\n\t$.success();\n}\n```\n\nDie Aktion erhält den Controller `$`. Seine Eigenschaften und Methoden (`$.params`, `$.body`, `$.query`, `$.json()`, `$.view()`...) werden in [Controller](../../guides/controller/) beschrieben.\n\n## Methoden und Pfade\n\nDas erste Wort ist die Methode: `GET`, `POST`, `PUT`, `PATCH`, `DELETE` oder jeder andere Methodenname. Der Pfad wird kleingeschrieben verglichen, und der abschließende Schrägstrich spielt keine Rolle. Ist `CONF.$root` gesetzt (zum Beispiel `/admin/`), wird es jedem Pfad vorangestellt.\n\nDie Aktion kann sein:\n\n- eine Funktion, die mit dem Controller aufgerufen wird;\n- ein String, der Name einer View, die gerendert wird;\n- weggelassen, dann wird eine View gerendert, die nach dem ersten Segment des Pfads benannt ist (`index` für `/`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');      // views/index.html\n\tROUTE('GET /about/');         // views/about.html\n\tROUTE('GET /pricing/', 'cms/pricing');\n};\n```\n\n## Dynamische Parameter und Platzhalter\n\nEin Segment in geschweiften Klammern ist ein Parameter. Sein Wert steht in `$.params` als String, mit der Schreibweise der Anfrage-URL. Eine Route mit Parametern passt nur zu URLs mit derselben Anzahl von Segmenten.\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', function($) {\n\t\t$.json({ user: $.params.id, order: $.params.order });\n\t});\n\tROUTE('GET /docs/*', function($) {\n\t\t// /docs/, /docs/a/, /docs/a/b/c/ ...\n\t\t$.plain($.url);\n\t});\n};\n```\n\nEin `*` am Ende macht eine Platzhalter-Route: Sie passt zum Pfad und zu allem darunter. Feste Routen werden zuerst geprüft, dann Routen mit Parametern, dann Platzhalter.\n\n## Autorisierung: `+` und `-`\n\nStelle der Methode `+` voran für Routen, die einen angemeldeten Benutzer brauchen, oder `-` für Routen nur für Besucher, die nicht angemeldet sind. Der Delegate [AUTH()](../../guides/authorization/) entscheidet, wer angemeldet ist; passt der Benutzer zu keiner Route der URL, lautet die Antwort `401`. Ohne `AUTH()` werden die Präfixe nicht geprüft, und jede Route bedient alle. Eine Route ohne Präfix bedient alle.\n\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', 'account');\n\tROUTE('-GET /account/', 'login');\n\tROUTE('+POST /account/password/', password);\n};\n```\n\nDu kannst dieselbe URL zweimal deklarieren, einmal mit `+` und einmal mit `-`, wie oben.\n\n## Aktionen mit `-->`\n\nStatt einer Funktion kann eine Route mit `NEWACTION()` deklarierte [Aktionen](../../guides/actions/) aufrufen. Schreibe ihre Namen nach `-->`. Der Body der Anfrage sind die Nutzdaten, und das Ergebnis wird als Antwort zurückgesendet (ein Fehler wird mit `$.invalid()` gesendet).\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/ --> Products/list');\n\tROUTE('+POST /api/products/ --> Products/insert');\n\tROUTE('+PUT /api/products/{id}/ --> Products/update');\n\tROUTE('+POST /api/orders/ --> Orders/insert Orders/read (response)');\n};\n```\n\nBei mehreren Aktionen markiert `(response)` die Aktion, deren Ergebnis die Antwort ist.\n\n## API-Routen mit `?`\n\n`API`-Routen stellen viele Operationen hinter eine URL. Ein `?` im Pfad wird durch `CONF.$api` ersetzt (Standard `/api/`). Der Client sendet `POST` mit einem JSON-Body `{ \"schema\": \"name/param?query\", \"data\": {...} }`; das Framework findet den Endpunkt `name`, füllt `$.params` aus den Pfadteilen, `$.query` aus dem Teil nach `?` und verwendet `data` als Body.\n\n```js\nexports.install = function() {\n\tROUTE('API ? products_list --> Products/list');\n\tROUTE('API ? products_read/{id} --> Products/read');\n\tROUTE('+API ? products_save --> Products/save');\n\tROUTE('+API ? products_remove/{id} --> Products/remove');\n};\n```\n\n```js\n// client\nAJAX('POST /api/', { schema: 'products_read/123', data: null }, console.log);\n```\n\n`+API` und `-API` setzen die Autorisierung jedes Endpunkts separat. Ein fehlender Parameter wird mit einem Fehler für `params.<name>` beantwortet, und ein unbekannter Endpunkt oder ein Body ohne `schema` mit `400`.\n\n## Flags\n\nFlags folgen dem Pfad. `@flag` schränkt ein, wann die Route passt, `#name` führt eine Middleware aus, `<value` setzt ein Größenlimit für den Body oder ein Timeout.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', upload);\n\tROUTE('POST /api/import/ @json <2m', importdata);\n\tROUTE('GET /dashboard/ @xhr #nocache', dashboard);\n};\n```\n\n| Flag | Die Route passt nur, wenn |\n| --- | --- |\n| `@json` | Der Body JSON ist |\n| `@xml` | Der Body XML ist |\n| `@upload` | Der Body `multipart/form-data` ist |\n| `@xhr` | Die Anfrage `X-Requested-With: XMLHttpRequest` hat |\n| `@mobile` | Der Client ein Mobilgerät ist |\n| `@robot` | Der Client ein Crawler ist |\n| `@referrer` (oder `@referer`) | Der Header `Referer` den Host der Anfrage enthält |\n| `@debug` | Die Anwendung im Debug-Modus läuft |\n| `@release` | Die Anwendung im Release-Modus läuft |\n\nHaben zwei Routen dieselbe Methode und denselben Pfad, wird die mit weniger Flags zuerst geprüft. Größenlimits und Timeouts:\n\n| Flag | Bedeutung |\n| --- | --- |\n| `<500b` | Größenlimit des Bodys in Bytes |\n| `<512kB` | Größenlimit des Bodys in Kilobytes (1 kB = 1024 Bytes) |\n| `<10MB` | Größenlimit des Bodys in Megabytes |\n| `<2GB` | Größenlimit des Bodys in Gigabytes |\n| `<30s` | Timeout in Sekunden |\n| `<5m` | Timeout in Minuten |\n| `<1h` | Timeout in Stunden |\n\nOhne Größen-Flag ist das Limit `CONF.$httpmaxsize` (256 kB); ein größerer Body wird mit `431` beantwortet. Ohne Timeout-Flag hat die Anfrage `CONF.$httptimeout` (5 Sekunden) und endet dann mit `503`. Das Timeout wird alle 5 Sekunden geprüft. Das dritte Argument von `ROUTE()` setzt ebenfalls das Limit, in Bytes: `ROUTE('POST /import/', fn, 1024 * 1024 * 50)`.\n\n## Middleware\n\n`#name` führt die mit `MIDDLEWARE(name, fn)` registrierte Middleware vor der Aktion aus, in der angegebenen Reihenfolge. Siehe [Middleware](../../guides/middleware/).\n\n```js\nMIDDLEWARE('nocache', function($, next) {\n\t$.response.headers['cache-control'] = 'no-store';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /report/ #nocache', report);\n};\n```\n\n## Datei-Routen\n\nDie Methode `FILE` behandelt Anfragen nach statischen Dateien (URLs mit einer Endung) mit deinem eigenen Code.\n\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', robots);          // one file\n\tROUTE('FILE /docs/*.md|txt', docs);          // extensions inside /docs/\n\tROUTE('FILE /downloads/*', downloads);       // every file inside /downloads/\n\tROUTE('FILE *.webp', webp);                  // every .webp file\n};\n\nfunction robots($) {\n\t$.plain('User-agent: *');\n}\n\nfunction downloads($) {\n\t$.file(PATH.databases('files' + $.url.substring(10)), true);\n}\n```\n\n## WebSocket-Routen\n\n`SOCKET` (oder `WEBSOCKET`) deklariert einen WebSocket-Endpunkt mit derselben Pfadsyntax, `+`/`-` und Größen-Flags. Siehe [WebSockets](../../guides/websockets/).\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/ <1MB', chat);\n};\n```\n\n## Fehler-Routen\n\nEine Route mit dem Namen `#` plus einem Statuscode ersetzt die Standard-Fehlerseite für diesen Code.\n\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n## Eine Route entfernen\n\n`ROUTE()` gibt das Routen-Objekt zurück. Rufe darauf `remove()` auf, um die Route während der Laufzeit der Anwendung abzumelden; die Routing-Tabelle wird sofort neu sortiert. Es funktioniert für jede Art von Route: eine HTTP-Route, einen API-Endpunkt (die gemeinsame `POST`-Route der API verschwindet mit ihrem letzten Endpunkt), eine `FILE`-Route und eine `SOCKET`-Route (ihre offenen Verbindungen werden geschlossen).\n\n```js\nvar route = ROUTE('GET /promo/', function($) {\n\t$.plain('Promo is running');\n});\n\nvar endpoint = ROUTE('API ? promo_read --> Promo/read');\n\n// later\nroute.remove();\nendpoint.remove();\n```\n\n## CORS\n\nAnfragen mit einem Header `Origin` von einem anderen Host werden gegen `CONF.$cors` geprüft. Setze es mit `CORS()` oder in `/config`.\n\n```js\nCORS();                                         // any origin\nCORS('https://app.example.com,https://admin.example.com');\nCORS('+https://partner.example.com');           // add one more\nCORS('*example.com');                           // any origin that contains example.com\n```\n\nEine erlaubte Anfrage erhält `Access-Control-Allow-*`-Header, und eine Preflight-Anfrage `OPTIONS` wird sofort beantwortet. Ein abgewiesener Origin erhält `400` mit `Invalid origin (CORS)`.\n\n## Proxys\n\n`PROXY(path, target)` leitet jede Anfrage, deren Pfad mit `path` beginnt, an einen anderen Server weiter, bevor die Routen durchsucht werden. Das Ziel ist eine `http://`- oder `https://`-URL, ein Unix-Socket-Pfad oder eine Funktion, die den Controller erhält.\n\n```js\nPROXY('/cdn/', 'https://cdn.example.com').copy('extend').timeout(10000);\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nDie weitergeleitete Anfrage erhält `X-Forwarded-For`, `X-Forwarded-URL` und `X-Forwarded-Host`. Schlägt das Ziel fehl, erhält der Client `503`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"JaedEODGT61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/routing/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Enrutamiento","summary":"Declara rutas con ROUTE(): métodos, rutas dinámicas, autorización, acciones, endpoints API, flags, rutas de archivos, CORS y proxies.","markdown":"---\ntitle: Enrutamiento\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/routing/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Enrutamiento\n\n> Declara rutas con ROUTE(): métodos, rutas dinámicas, autorización, acciones, endpoints API, flags, rutas de archivos, CORS y proxies.\n\nLas rutas conectan URLs con código. Las declaras con el global `ROUTE()` en la función `install` de un archivo de `/controllers/` (o de un plugin o un módulo). Cada ruta es un único string: el método HTTP, la ruta y flags opcionales, seguidos de la acción.\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /products/{id}/', detail);\n\tROUTE('POST /contact/', contact);\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n\nfunction detail($) {\n\t$.json({ id: $.params.id });\n}\n\nfunction contact($) {\n\t// $.body contains the parsed JSON or form data\n\t$.success();\n}\n```\n\nLa acción recibe el controlador `$`. Sus propiedades y métodos (`$.params`, `$.body`, `$.query`, `$.json()`, `$.view()`...) se describen en [Controlador](../../guides/controller/).\n\n## Métodos y rutas\n\nLa primera palabra es el método: `GET`, `POST`, `PUT`, `PATCH`, `DELETE` o cualquier otro nombre de método. La ruta se compara en minúsculas y la barra final no importa. Cuando se establece `CONF.$root` (por ejemplo `/admin/`), se antepone a cada ruta.\n\nLa acción puede ser:\n\n- una función, llamada con el controlador;\n- un string, el nombre de una vista que se renderiza;\n- nada, y entonces se renderiza una vista con el nombre del primer segmento de la ruta (`index` para `/`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');      // views/index.html\n\tROUTE('GET /about/');         // views/about.html\n\tROUTE('GET /pricing/', 'cms/pricing');\n};\n```\n\n## Parámetros dinámicos y comodines\n\nUn segmento entre llaves es un parámetro. Su valor está en `$.params` como string, con las mayúsculas y minúsculas de la URL de la petición. Una ruta con parámetros solo coincide con URLs con el mismo número de segmentos.\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', function($) {\n\t\t$.json({ user: $.params.id, order: $.params.order });\n\t});\n\tROUTE('GET /docs/*', function($) {\n\t\t// /docs/, /docs/a/, /docs/a/b/c/ ...\n\t\t$.plain($.url);\n\t});\n};\n```\n\nUn `*` al final crea una ruta comodín: coincide con la ruta y con todo lo que hay debajo. Primero se comprueban las rutas fijas, luego las rutas con parámetros y luego los comodines.\n\n## Autorización: `+` y `-`\n\nAntepón `+` al método para las rutas que necesitan un usuario con sesión iniciada, o `-` para las rutas solo para visitantes sin sesión iniciada. El delegado [AUTH()](../../guides/authorization/) decide quién tiene sesión iniciada; cuando el usuario no encaja en ninguna ruta de la URL, la respuesta es `401`. Sin `AUTH()` los prefijos no se comprueban y todas las rutas atienden a todo el mundo. Una ruta sin prefijo atiende a todo el mundo.\n\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', 'account');\n\tROUTE('-GET /account/', 'login');\n\tROUTE('+POST /account/password/', password);\n};\n```\n\nPuedes declarar la misma URL dos veces, una con `+` y otra con `-`, como arriba.\n\n## Acciones con `-->`\n\nEn lugar de una función, una ruta puede llamar a [acciones](../../guides/actions/) declaradas con `NEWACTION()`. Escribe sus nombres después de `-->`. El cuerpo de la petición es la carga útil y el resultado se devuelve como respuesta (un error se envía con `$.invalid()`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/ --> Products/list');\n\tROUTE('+POST /api/products/ --> Products/insert');\n\tROUTE('+PUT /api/products/{id}/ --> Products/update');\n\tROUTE('+POST /api/orders/ --> Orders/insert Orders/read (response)');\n};\n```\n\nCon varias acciones, `(response)` marca la acción cuyo resultado es la respuesta.\n\n## Rutas API con `?`\n\nLas rutas `API` ponen muchas operaciones detrás de una URL. Un `?` en la ruta se sustituye por `CONF.$api` (por defecto `/api/`). El cliente envía `POST` con un cuerpo JSON `{ \"schema\": \"name/param?query\", \"data\": {...} }`; el framework encuentra el endpoint `name`, rellena `$.params` con las partes de la ruta, `$.query` con la parte después de `?`, y usa `data` como cuerpo.\n\n```js\nexports.install = function() {\n\tROUTE('API ? products_list --> Products/list');\n\tROUTE('API ? products_read/{id} --> Products/read');\n\tROUTE('+API ? products_save --> Products/save');\n\tROUTE('+API ? products_remove/{id} --> Products/remove');\n};\n```\n\n```js\n// client\nAJAX('POST /api/', { schema: 'products_read/123', data: null }, console.log);\n```\n\n`+API` y `-API` establecen la autorización de cada endpoint por separado. A un parámetro que falta se responde con un error para `params.<name>`, y a un endpoint desconocido o a un cuerpo sin `schema`, con `400`.\n\n## Flags\n\nLos flags siguen a la ruta. `@flag` limita cuándo coincide la ruta, `#name` ejecuta un middleware, `<value` establece un límite de tamaño del cuerpo o un tiempo de espera.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', upload);\n\tROUTE('POST /api/import/ @json <2m', importdata);\n\tROUTE('GET /dashboard/ @xhr #nocache', dashboard);\n};\n```\n\n| Flag | La ruta solo coincide cuando |\n| --- | --- |\n| `@json` | El cuerpo es JSON |\n| `@xml` | El cuerpo es XML |\n| `@upload` | El cuerpo es `multipart/form-data` |\n| `@xhr` | La petición tiene `X-Requested-With: XMLHttpRequest` |\n| `@mobile` | El cliente es un dispositivo móvil |\n| `@robot` | El cliente es un crawler |\n| `@referrer` (o `@referer`) | La cabecera `Referer` contiene el host de la petición |\n| `@debug` | La aplicación se ejecuta en modo debug |\n| `@release` | La aplicación se ejecuta en modo release |\n\nCuando dos rutas tienen el mismo método y la misma ruta, se comprueba primero la que tiene menos flags. Límites de tamaño y tiempos de espera:\n\n| Flag | Significado |\n| --- | --- |\n| `<500b` | Límite de tamaño del cuerpo en bytes |\n| `<512kB` | Límite de tamaño del cuerpo en kilobytes (1 kB = 1024 bytes) |\n| `<10MB` | Límite de tamaño del cuerpo en megabytes |\n| `<2GB` | Límite de tamaño del cuerpo en gigabytes |\n| `<30s` | Tiempo de espera en segundos |\n| `<5m` | Tiempo de espera en minutos |\n| `<1h` | Tiempo de espera en horas |\n\nSin un flag de tamaño, el límite es `CONF.$httpmaxsize` (256 kB); a un cuerpo mayor se responde con `431`. Sin un flag de tiempo de espera, la petición tiene `CONF.$httptimeout` (5 segundos) y luego termina con `503`. El tiempo de espera se comprueba cada 5 segundos. El tercer argumento de `ROUTE()` también establece el límite, en bytes: `ROUTE('POST /import/', fn, 1024 * 1024 * 50)`.\n\n## Middleware\n\n`#name` ejecuta el middleware registrado con `MIDDLEWARE(name, fn)` antes de la acción, en el orden escrito. Consulta [Middleware](../../guides/middleware/).\n\n```js\nMIDDLEWARE('nocache', function($, next) {\n\t$.response.headers['cache-control'] = 'no-store';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /report/ #nocache', report);\n};\n```\n\n## Rutas de archivos\n\nEl método `FILE` gestiona con tu propio código las peticiones de archivos estáticos (URLs con una extensión).\n\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', robots);          // one file\n\tROUTE('FILE /docs/*.md|txt', docs);          // extensions inside /docs/\n\tROUTE('FILE /downloads/*', downloads);       // every file inside /downloads/\n\tROUTE('FILE *.webp', webp);                  // every .webp file\n};\n\nfunction robots($) {\n\t$.plain('User-agent: *');\n}\n\nfunction downloads($) {\n\t$.file(PATH.databases('files' + $.url.substring(10)), true);\n}\n```\n\n## Rutas WebSocket\n\n`SOCKET` (o `WEBSOCKET`) declara un endpoint WebSocket con la misma sintaxis de ruta, `+`/`-` y flags de tamaño. Consulta [WebSockets](../../guides/websockets/).\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/ <1MB', chat);\n};\n```\n\n## Rutas de error\n\nUna ruta llamada `#` más un código de estado sustituye la página de error por defecto para ese código.\n\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n## Eliminar una ruta\n\n`ROUTE()` devuelve el objeto de la ruta. Llama a `remove()` sobre él para dar de baja la ruta mientras la aplicación se ejecuta; la tabla de enrutamiento se vuelve a ordenar de inmediato. Funciona para cualquier tipo de ruta: una ruta HTTP, un endpoint API (la ruta `POST` compartida de la API desaparece con su último endpoint), una ruta `FILE` y una ruta `SOCKET` (se cierran sus conexiones abiertas).\n\n```js\nvar route = ROUTE('GET /promo/', function($) {\n\t$.plain('Promo is running');\n});\n\nvar endpoint = ROUTE('API ? promo_read --> Promo/read');\n\n// later\nroute.remove();\nendpoint.remove();\n```\n\n## CORS\n\nLas peticiones con una cabecera `Origin` de otro host se comprueban contra `CONF.$cors`. Establécelo con `CORS()` o en `/config`.\n\n```js\nCORS();                                         // any origin\nCORS('https://app.example.com,https://admin.example.com');\nCORS('+https://partner.example.com');           // add one more\nCORS('*example.com');                           // any origin that contains example.com\n```\n\nUna petición permitida recibe cabeceras `Access-Control-Allow-*` y a una petición preflight `OPTIONS` se responde de inmediato. Un origen rechazado recibe `400` con `Invalid origin (CORS)`.\n\n## Proxies\n\n`PROXY(path, target)` reenvía a otro servidor cada petición cuya ruta empieza por `path`, antes de buscar en las rutas. El destino es una URL `http://` o `https://`, una ruta de socket Unix o una función que recibe el controlador.\n\n```js\nPROXY('/cdn/', 'https://cdn.example.com').copy('extend').timeout(10000);\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nLa petición reenviada recibe `X-Forwarded-For`, `X-Forwarded-URL` y `X-Forwarded-Host`. Cuando el destino falla, el cliente recibe `503`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"JaedEODGT61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/routing/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Routage","summary":"Déclare des routes avec ROUTE() : méthodes, chemins dynamiques, autorisation, actions, endpoints d'API, flags, routes de fichiers, CORS et proxys.","markdown":"---\ntitle: Routage\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/routing/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Routage\n\n> Déclare des routes avec ROUTE() : méthodes, chemins dynamiques, autorisation, actions, endpoints d'API, flags, routes de fichiers, CORS et proxys.\n\nLes routes relient des URL à du code. Tu les déclares avec la fonction globale `ROUTE()` dans la fonction `install` d'un fichier de `/controllers/` (ou d'un plugin ou d'un module). Chaque route est une seule chaîne : la méthode HTTP, le chemin et des flags facultatifs, suivis de l'action.\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /products/{id}/', detail);\n\tROUTE('POST /contact/', contact);\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n\nfunction detail($) {\n\t$.json({ id: $.params.id });\n}\n\nfunction contact($) {\n\t// $.body contains the parsed JSON or form data\n\t$.success();\n}\n```\n\nL'action reçoit le contrôleur `$`. Ses propriétés et méthodes (`$.params`, `$.body`, `$.query`, `$.json()`, `$.view()`...) sont décrites dans [Contrôleur](../../guides/controller/).\n\n## Méthodes et chemins\n\nLe premier mot est la méthode : `GET`, `POST`, `PUT`, `PATCH`, `DELETE` ou tout autre nom de méthode. Le chemin est comparé en minuscules et la barre oblique finale n'a pas d'importance. Lorsque `CONF.$root` est défini (par exemple `/admin/`), il est ajouté au début de chaque chemin.\n\nL'action peut être :\n\n- une fonction, appelée avec le contrôleur ;\n- une chaîne, le nom d'une vue dont le rendu est effectué ;\n- absente : une vue nommée d'après le premier segment du chemin est alors rendue (`index` pour `/`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');      // views/index.html\n\tROUTE('GET /about/');         // views/about.html\n\tROUTE('GET /pricing/', 'cms/pricing');\n};\n```\n\n## Paramètres dynamiques et jokers\n\nUn segment entre accolades est un paramètre. Sa valeur se trouve dans `$.params` sous forme de chaîne, avec la casse de l'URL de la requête. Une route avec des paramètres ne correspond qu'aux URL ayant le même nombre de segments.\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', function($) {\n\t\t$.json({ user: $.params.id, order: $.params.order });\n\t});\n\tROUTE('GET /docs/*', function($) {\n\t\t// /docs/, /docs/a/, /docs/a/b/c/ ...\n\t\t$.plain($.url);\n\t});\n};\n```\n\nUn `*` à la fin crée une route joker : elle correspond au chemin et à tout ce qui se trouve en dessous. Les routes fixes sont vérifiées en premier, puis les routes avec paramètres, puis les jokers.\n\n## Autorisation : `+` et `-`\n\nPréfixe la méthode avec `+` pour les routes qui nécessitent un utilisateur connecté, ou avec `-` pour les routes réservées aux visiteurs non connectés. Le délégué [AUTH()](../../guides/authorization/) décide qui est connecté ; lorsque l'utilisateur ne correspond à aucune route de l'URL, la réponse est `401`. Sans `AUTH()`, les préfixes ne sont pas vérifiés et chaque route sert tout le monde. Une route sans préfixe sert tout le monde.\n\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', 'account');\n\tROUTE('-GET /account/', 'login');\n\tROUTE('+POST /account/password/', password);\n};\n```\n\nTu peux déclarer deux fois la même URL, une fois avec `+` et une fois avec `-`, comme ci-dessus.\n\n## Actions avec `-->`\n\nAu lieu d'une fonction, une route peut appeler des [actions](../../guides/actions/) déclarées avec `NEWACTION()`. Écris leurs noms après `-->`. Le corps de la requête est la charge utile et le résultat est renvoyé comme réponse (une erreur est envoyée avec `$.invalid()`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/ --> Products/list');\n\tROUTE('+POST /api/products/ --> Products/insert');\n\tROUTE('+PUT /api/products/{id}/ --> Products/update');\n\tROUTE('+POST /api/orders/ --> Orders/insert Orders/read (response)');\n};\n```\n\nAvec plusieurs actions, `(response)` marque l'action dont le résultat constitue la réponse.\n\n## Routes d'API avec `?`\n\nLes routes `API` placent de nombreuses opérations derrière une seule URL. Un `?` dans le chemin est remplacé par `CONF.$api` (par défaut `/api/`). Le client envoie un `POST` avec un corps JSON `{ \"schema\": \"name/param?query\", \"data\": {...} }` ; le framework trouve l'endpoint `name`, remplit `$.params` à partir des parties du chemin, `$.query` à partir de la partie après `?`, et utilise `data` comme corps.\n\n```js\nexports.install = function() {\n\tROUTE('API ? products_list --> Products/list');\n\tROUTE('API ? products_read/{id} --> Products/read');\n\tROUTE('+API ? products_save --> Products/save');\n\tROUTE('+API ? products_remove/{id} --> Products/remove');\n};\n```\n\n```js\n// client\nAJAX('POST /api/', { schema: 'products_read/123', data: null }, console.log);\n```\n\n`+API` et `-API` définissent l'autorisation de chaque endpoint séparément. Un paramètre manquant reçoit en réponse une erreur pour `params.<name>`, et un endpoint inconnu ou un corps sans `schema` reçoit `400`.\n\n## Flags\n\nLes flags suivent le chemin. `@flag` limite les cas où la route correspond, `#name` exécute un middleware, `<value` définit une limite de taille du corps ou un délai d'expiration.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', upload);\n\tROUTE('POST /api/import/ @json <2m', importdata);\n\tROUTE('GET /dashboard/ @xhr #nocache', dashboard);\n};\n```\n\n| Flag | La route ne correspond que lorsque |\n| --- | --- |\n| `@json` | Le corps est du JSON |\n| `@xml` | Le corps est du XML |\n| `@upload` | Le corps est `multipart/form-data` |\n| `@xhr` | La requête a `X-Requested-With: XMLHttpRequest` |\n| `@mobile` | Le client est un appareil mobile |\n| `@robot` | Le client est un robot d'indexation |\n| `@referrer` (ou `@referer`) | L'en-tête `Referer` contient l'hôte de la requête |\n| `@debug` | L'application s'exécute en mode debug |\n| `@release` | L'application s'exécute en mode release |\n\nLorsque deux routes ont la même méthode et le même chemin, celle qui a le moins de flags est vérifiée en premier. Limites de taille et délais d'expiration :\n\n| Flag | Signification |\n| --- | --- |\n| `<500b` | Limite de taille du corps en octets |\n| `<512kB` | Limite de taille du corps en kilooctets (1 ko = 1024 octets) |\n| `<10MB` | Limite de taille du corps en mégaoctets |\n| `<2GB` | Limite de taille du corps en gigaoctets |\n| `<30s` | Délai d'expiration en secondes |\n| `<5m` | Délai d'expiration en minutes |\n| `<1h` | Délai d'expiration en heures |\n\nSans flag de taille, la limite est `CONF.$httpmaxsize` (256 ko) ; un corps plus grand reçoit en réponse `431`. Sans flag de délai, la requête dispose de `CONF.$httptimeout` (5 secondes) puis se termine avec `503`. Le délai est vérifié toutes les 5 secondes. Le troisième argument de `ROUTE()` définit aussi la limite, en octets : `ROUTE('POST /import/', fn, 1024 * 1024 * 50)`.\n\n## Middleware\n\n`#name` exécute le middleware enregistré avec `MIDDLEWARE(name, fn)` avant l'action, dans l'ordre d'écriture. Voir [Middleware](../../guides/middleware/).\n\n```js\nMIDDLEWARE('nocache', function($, next) {\n\t$.response.headers['cache-control'] = 'no-store';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /report/ #nocache', report);\n};\n```\n\n## Routes de fichiers\n\nLa méthode `FILE` traite avec ton propre code les requêtes de fichiers statiques (URL avec une extension).\n\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', robots);          // one file\n\tROUTE('FILE /docs/*.md|txt', docs);          // extensions inside /docs/\n\tROUTE('FILE /downloads/*', downloads);       // every file inside /downloads/\n\tROUTE('FILE *.webp', webp);                  // every .webp file\n};\n\nfunction robots($) {\n\t$.plain('User-agent: *');\n}\n\nfunction downloads($) {\n\t$.file(PATH.databases('files' + $.url.substring(10)), true);\n}\n```\n\n## Routes WebSocket\n\n`SOCKET` (ou `WEBSOCKET`) déclare un endpoint WebSocket avec la même syntaxe de chemin, `+`/`-` et les flags de taille. Voir [WebSockets](../../guides/websockets/).\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/ <1MB', chat);\n};\n```\n\n## Routes d'erreur\n\nUne route nommée `#` suivi d'un code de statut remplace la page d'erreur par défaut pour ce code.\n\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n## Supprimer une route\n\n`ROUTE()` renvoie l'objet route. Appelle `remove()` sur celui-ci pour désenregistrer la route pendant l'exécution de l'application ; la table de routage est immédiatement triée à nouveau. Cela fonctionne pour tous les types de routes : une route HTTP, un endpoint d'API (la route `POST` partagée de l'API disparaît avec son dernier endpoint), une route `FILE` et une route `SOCKET` (ses connexions ouvertes sont fermées).\n\n```js\nvar route = ROUTE('GET /promo/', function($) {\n\t$.plain('Promo is running');\n});\n\nvar endpoint = ROUTE('API ? promo_read --> Promo/read');\n\n// later\nroute.remove();\nendpoint.remove();\n```\n\n## CORS\n\nLes requêtes ayant un en-tête `Origin` provenant d'un autre hôte sont vérifiées par rapport à `CONF.$cors`. Définis-le avec `CORS()` ou dans `/config`.\n\n```js\nCORS();                                         // any origin\nCORS('https://app.example.com,https://admin.example.com');\nCORS('+https://partner.example.com');           // add one more\nCORS('*example.com');                           // any origin that contains example.com\n```\n\nUne requête autorisée reçoit des en-têtes `Access-Control-Allow-*` et une requête preflight `OPTIONS` reçoit immédiatement une réponse. Une origine refusée reçoit `400` avec `Invalid origin (CORS)`.\n\n## Proxys\n\n`PROXY(path, target)` transmet chaque requête dont le chemin commence par `path` à un autre serveur, avant la recherche des routes. La cible est une URL `http://` ou `https://`, un chemin de socket Unix, ou une fonction qui reçoit le contrôleur.\n\n```js\nPROXY('/cdn/', 'https://cdn.example.com').copy('extend').timeout(10000);\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nLa requête transmise reçoit `X-Forwarded-For`, `X-Forwarded-URL` et `X-Forwarded-Host`. Lorsque la cible échoue, le client reçoit `503`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"JaedEODGT61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/routing/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Routing","summary":"Dichiara le route con ROUTE(): metodi, percorsi dinamici, autorizzazione, azioni, endpoint API, flag, route per file, CORS e proxy.","markdown":"---\ntitle: Routing\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/routing/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Routing\n\n> Dichiara le route con ROUTE(): metodi, percorsi dinamici, autorizzazione, azioni, endpoint API, flag, route per file, CORS e proxy.\n\nLe route collegano gli URL al codice. Le dichiari con la funzione globale `ROUTE()` nella funzione `install` di un file in `/controllers/` (o di un plugin o di un modulo). Ogni route è un'unica stringa: il metodo HTTP, il percorso e flag facoltativi, seguiti dall'azione.\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /products/{id}/', detail);\n\tROUTE('POST /contact/', contact);\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n\nfunction detail($) {\n\t$.json({ id: $.params.id });\n}\n\nfunction contact($) {\n\t// $.body contains the parsed JSON or form data\n\t$.success();\n}\n```\n\nL'azione riceve il controller `$`. Le sue proprietà e i suoi metodi (`$.params`, `$.body`, `$.query`, `$.json()`, `$.view()`...) sono descritti in [Controller](../../guides/controller/).\n\n## Metodi e percorsi\n\nLa prima parola è il metodo: `GET`, `POST`, `PUT`, `PATCH`, `DELETE` o qualsiasi altro nome di metodo. Il percorso viene confrontato in minuscolo e la barra finale non conta. Quando `CONF.$root` è impostato (per esempio `/admin/`), viene anteposto a ogni percorso.\n\nL'azione può essere:\n\n- una funzione, chiamata con il controller;\n- una stringa, il nome di una vista che viene renderizzata;\n- assente: in tal caso viene renderizzata una vista con il nome del primo segmento del percorso (`index` per `/`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');      // views/index.html\n\tROUTE('GET /about/');         // views/about.html\n\tROUTE('GET /pricing/', 'cms/pricing');\n};\n```\n\n## Parametri dinamici e caratteri jolly\n\nUn segmento tra parentesi graffe è un parametro. Il suo valore è in `$.params` come stringa, con le maiuscole/minuscole dell'URL della richiesta. Una route con parametri corrisponde solo agli URL con lo stesso numero di segmenti.\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', function($) {\n\t\t$.json({ user: $.params.id, order: $.params.order });\n\t});\n\tROUTE('GET /docs/*', function($) {\n\t\t// /docs/, /docs/a/, /docs/a/b/c/ ...\n\t\t$.plain($.url);\n\t});\n};\n```\n\nUn `*` alla fine crea una route jolly: corrisponde al percorso e a tutto ciò che sta sotto di esso. Vengono controllate prima le route fisse, poi le route con parametri, poi quelle jolly.\n\n## Autorizzazione: `+` e `-`\n\nAnteponi `+` al metodo per le route che richiedono un utente autenticato, o `-` per le route riservate ai visitatori non autenticati. Il delegate [AUTH()](../../guides/authorization/) decide chi è autenticato; quando l'utente non corrisponde a nessuna route dell'URL, la risposta è `401`. Senza `AUTH()` i prefissi non vengono controllati e ogni route serve tutti. Una route senza prefisso serve tutti.\n\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', 'account');\n\tROUTE('-GET /account/', 'login');\n\tROUTE('+POST /account/password/', password);\n};\n```\n\nPuoi dichiarare lo stesso URL due volte, una con `+` e una con `-`, come sopra.\n\n## Azioni con `-->`\n\nInvece di una funzione, una route può chiamare [azioni](../../guides/actions/) dichiarate con `NEWACTION()`. Scrivi i loro nomi dopo `-->`. Il body della richiesta è il payload e il risultato viene rimandato come risposta (un errore viene inviato con `$.invalid()`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/ --> Products/list');\n\tROUTE('+POST /api/products/ --> Products/insert');\n\tROUTE('+PUT /api/products/{id}/ --> Products/update');\n\tROUTE('+POST /api/orders/ --> Orders/insert Orders/read (response)');\n};\n```\n\nCon più azioni, `(response)` indica l'azione il cui risultato è la risposta.\n\n## Route API con `?`\n\nLe route `API` mettono molte operazioni dietro un unico URL. Un `?` nel percorso viene sostituito con `CONF.$api` (predefinito `/api/`). Il client invia `POST` con un body JSON `{ \"schema\": \"name/param?query\", \"data\": {...} }`; il framework trova l'endpoint `name`, riempie `$.params` dalle parti del percorso, `$.query` dalla parte dopo `?`, e usa `data` come body.\n\n```js\nexports.install = function() {\n\tROUTE('API ? products_list --> Products/list');\n\tROUTE('API ? products_read/{id} --> Products/read');\n\tROUTE('+API ? products_save --> Products/save');\n\tROUTE('+API ? products_remove/{id} --> Products/remove');\n};\n```\n\n```js\n// client\nAJAX('POST /api/', { schema: 'products_read/123', data: null }, console.log);\n```\n\n`+API` e `-API` impostano l'autorizzazione di ogni endpoint separatamente. A un parametro mancante si risponde con un errore per `params.<name>`, e a un endpoint sconosciuto o a un body senza `schema` con `400`.\n\n## Flag\n\nI flag seguono il percorso. `@flag` limita quando la route corrisponde, `#name` esegue un middleware, `<value` imposta un limite di dimensione del body o un timeout.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', upload);\n\tROUTE('POST /api/import/ @json <2m', importdata);\n\tROUTE('GET /dashboard/ @xhr #nocache', dashboard);\n};\n```\n\n| Flag | La route corrisponde solo quando |\n| --- | --- |\n| `@json` | Il body è JSON |\n| `@xml` | Il body è XML |\n| `@upload` | Il body è `multipart/form-data` |\n| `@xhr` | La richiesta ha `X-Requested-With: XMLHttpRequest` |\n| `@mobile` | Il client è un dispositivo mobile |\n| `@robot` | Il client è un crawler |\n| `@referrer` (o `@referer`) | L'header `Referer` contiene l'host della richiesta |\n| `@debug` | L'applicazione gira in modalità debug |\n| `@release` | L'applicazione gira in modalità release |\n\nQuando due route hanno lo stesso metodo e lo stesso percorso, viene controllata per prima quella con meno flag. Limiti di dimensione e timeout:\n\n| Flag | Significato |\n| --- | --- |\n| `<500b` | Limite di dimensione del body in byte |\n| `<512kB` | Limite di dimensione del body in kilobyte (1 kB = 1024 byte) |\n| `<10MB` | Limite di dimensione del body in megabyte |\n| `<2GB` | Limite di dimensione del body in gigabyte |\n| `<30s` | Timeout in secondi |\n| `<5m` | Timeout in minuti |\n| `<1h` | Timeout in ore |\n\nSenza un flag di dimensione, il limite è `CONF.$httpmaxsize` (256 kB); a un body più grande si risponde con `431`. Senza un flag di timeout, la richiesta ha `CONF.$httptimeout` (5 secondi) e poi termina con `503`. Il timeout viene controllato ogni 5 secondi. Anche il terzo argomento di `ROUTE()` imposta il limite, in byte: `ROUTE('POST /import/', fn, 1024 * 1024 * 50)`.\n\n## Middleware\n\n`#name` esegue il middleware registrato con `MIDDLEWARE(name, fn)` prima dell'azione, nell'ordine in cui è scritto. Vedi [Middleware](../../guides/middleware/).\n\n```js\nMIDDLEWARE('nocache', function($, next) {\n\t$.response.headers['cache-control'] = 'no-store';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /report/ #nocache', report);\n};\n```\n\n## Route per file\n\nIl metodo `FILE` gestisce con il tuo codice le richieste di file statici (URL con un'estensione).\n\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', robots);          // one file\n\tROUTE('FILE /docs/*.md|txt', docs);          // extensions inside /docs/\n\tROUTE('FILE /downloads/*', downloads);       // every file inside /downloads/\n\tROUTE('FILE *.webp', webp);                  // every .webp file\n};\n\nfunction robots($) {\n\t$.plain('User-agent: *');\n}\n\nfunction downloads($) {\n\t$.file(PATH.databases('files' + $.url.substring(10)), true);\n}\n```\n\n## Route WebSocket\n\n`SOCKET` (o `WEBSOCKET`) dichiara un endpoint WebSocket con la stessa sintassi del percorso, `+`/`-` e i flag di dimensione. Vedi [WebSocket](../../guides/websockets/).\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/ <1MB', chat);\n};\n```\n\n## Route di errore\n\nUna route chiamata `#` più un codice di stato sostituisce la pagina di errore predefinita per quel codice.\n\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n## Rimuovere una route\n\n`ROUTE()` restituisce l'oggetto route. Chiama `remove()` su di esso per annullare la registrazione della route mentre l'applicazione gira; la tabella di routing viene subito riordinata. Funziona per ogni tipo di route: una route HTTP, un endpoint API (la route `POST` condivisa dell'API scompare con il suo ultimo endpoint), una route `FILE` e una route `SOCKET` (le sue connessioni aperte vengono chiuse).\n\n```js\nvar route = ROUTE('GET /promo/', function($) {\n\t$.plain('Promo is running');\n});\n\nvar endpoint = ROUTE('API ? promo_read --> Promo/read');\n\n// later\nroute.remove();\nendpoint.remove();\n```\n\n## CORS\n\nLe richieste con un header `Origin` di un altro host vengono confrontate con `CONF.$cors`. Impostalo con `CORS()` o in `/config`.\n\n```js\nCORS();                                         // any origin\nCORS('https://app.example.com,https://admin.example.com');\nCORS('+https://partner.example.com');           // add one more\nCORS('*example.com');                           // any origin that contains example.com\n```\n\nUna richiesta consentita riceve gli header `Access-Control-Allow-*` e a una richiesta preflight `OPTIONS` si risponde subito. Un'origine rifiutata riceve `400` con `Invalid origin (CORS)`.\n\n## Proxy\n\n`PROXY(path, target)` inoltra a un altro server ogni richiesta il cui percorso inizia con `path`, prima che vengano cercate le route. La destinazione è un URL `http://` o `https://`, il percorso di un socket Unix, oppure una funzione che riceve il controller.\n\n```js\nPROXY('/cdn/', 'https://cdn.example.com').copy('extend').timeout(10000);\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nLa richiesta inoltrata riceve `X-Forwarded-For`, `X-Forwarded-URL` e `X-Forwarded-Host`. Quando la destinazione fallisce, il client riceve `503`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"JaedEODGT61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/routing/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Smerovanie","summary":"Deklarovanie trás cez ROUTE(): metódy, dynamické cesty, autorizácia, akcie, API endpointy, flagy, súborové trasy, CORS a proxy.","markdown":"---\ntitle: Smerovanie\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/routing/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Smerovanie\n\n> Deklarovanie trás cez ROUTE(): metódy, dynamické cesty, autorizácia, akcie, API endpointy, flagy, súborové trasy, CORS a proxy.\n\nTrasy spájajú URL s kódom. Deklaruješ ich globálnym `ROUTE()` vo funkcii `install` súboru v `/controllers/` (alebo pluginu či modulu). Každá trasa je jeden reťazec: HTTP metóda, cesta a voliteľné flagy, za ktorými nasleduje akcia.\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /products/{id}/', detail);\n\tROUTE('POST /contact/', contact);\n};\n\nfunction index($) {\n\t$.plain('Hello world');\n}\n\nfunction detail($) {\n\t$.json({ id: $.params.id });\n}\n\nfunction contact($) {\n\t// $.body contains the parsed JSON or form data\n\t$.success();\n}\n```\n\nAkcia dostane kontrolér `$`. Jeho vlastnosti a metódy (`$.params`, `$.body`, `$.query`, `$.json()`, `$.view()`...) sú opísané v [Kontrolér](../../guides/controller/).\n\n## Metódy a cesty\n\nPrvé slovo je metóda: `GET`, `POST`, `PUT`, `PATCH`, `DELETE` alebo akýkoľvek iný názov metódy. Cesta sa porovnáva malými písmenami a na lomke na konci nezáleží. Keď je nastavené `CONF.$root` (napríklad `/admin/`), pridá sa pred každú cestu.\n\nAkcia môže byť:\n\n- funkcia volaná s kontrolérom;\n- reťazec, názov pohľadu, ktorý sa vykreslí;\n- chýbajúca, potom sa vykreslí pohľad pomenovaný podľa prvého segmentu cesty (`index` pre `/`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');      // views/index.html\n\tROUTE('GET /about/');         // views/about.html\n\tROUTE('GET /pricing/', 'cms/pricing');\n};\n```\n\n## Dynamické parametre a wildcardy\n\nSegment v zložených zátvorkách je parameter. Jeho hodnota je v `$.params` ako reťazec s veľkosťou písmen z URL požiadavky. Trasa s parametrami zodpovedá iba URL s rovnakým počtom segmentov.\n\n```js\nexports.install = function() {\n\tROUTE('GET /users/{id}/orders/{order}/', function($) {\n\t\t$.json({ user: $.params.id, order: $.params.order });\n\t});\n\tROUTE('GET /docs/*', function($) {\n\t\t// /docs/, /docs/a/, /docs/a/b/c/ ...\n\t\t$.plain($.url);\n\t});\n};\n```\n\n`*` na konci vytvorí wildcard trasu: zodpovedá ceste a všetkému pod ňou. Najprv sa kontrolujú pevné trasy, potom trasy s parametrami, potom wildcardy.\n\n## Autorizácia: `+` a `-`\n\nPridaj pred metódu `+` pre trasy, ktoré potrebujú prihláseného používateľa, alebo `-` pre trasy iba pre návštevníkov, ktorí nie sú prihlásení. Delegát [AUTH()](../../guides/authorization/) rozhoduje, kto je prihlásený; keď používateľ nezodpovedá žiadnej trase URL, odpoveď je `401`. Bez `AUTH()` sa prefixy nekontrolujú a každá trasa obsluhuje každého. Trasa bez prefixu obsluhuje každého.\n\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', 'account');\n\tROUTE('-GET /account/', 'login');\n\tROUTE('+POST /account/password/', password);\n};\n```\n\nTú istú URL môžeš deklarovať dvakrát, raz s `+` a raz s `-`, ako vyššie.\n\n## Akcie cez `-->`\n\nNamiesto funkcie môže trasa volať [akcie](../../guides/actions/) deklarované cez `NEWACTION()`. Ich názvy napíš za `-->`. Telo požiadavky je payload a výsledok sa pošle späť ako odpoveď (chyba sa pošle cez `$.invalid()`).\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/ --> Products/list');\n\tROUTE('+POST /api/products/ --> Products/insert');\n\tROUTE('+PUT /api/products/{id}/ --> Products/update');\n\tROUTE('+POST /api/orders/ --> Orders/insert Orders/read (response)');\n};\n```\n\nPri viacerých akciách `(response)` označuje akciu, ktorej výsledok je odpoveďou.\n\n## API trasy s `?`\n\nTrasy `API` dávajú veľa operácií za jednu URL. `?` v ceste sa nahradí `CONF.$api` (predvolene `/api/`). Klient pošle `POST` s JSON telom `{ \"schema\": \"name/param?query\", \"data\": {...} }`; framework nájde endpoint `name`, naplní `$.params` z častí cesty, `$.query` z časti za `?` a `data` použije ako telo.\n\n```js\nexports.install = function() {\n\tROUTE('API ? products_list --> Products/list');\n\tROUTE('API ? products_read/{id} --> Products/read');\n\tROUTE('+API ? products_save --> Products/save');\n\tROUTE('+API ? products_remove/{id} --> Products/remove');\n};\n```\n\n```js\n// client\nAJAX('POST /api/', { schema: 'products_read/123', data: null }, console.log);\n```\n\n`+API` a `-API` nastavujú autorizáciu každého endpointu zvlášť. Na chýbajúci parameter sa odpovie chybou pre `params.<name>` a na neznámy endpoint alebo telo bez `schema` s `400`.\n\n## Flagy\n\nFlagy nasledujú za cestou. `@flag` obmedzuje, kedy trasa zodpovedá, `#name` spustí middleware, `<value` nastaví limit veľkosti tela alebo časový limit.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', upload);\n\tROUTE('POST /api/import/ @json <2m', importdata);\n\tROUTE('GET /dashboard/ @xhr #nocache', dashboard);\n};\n```\n\n| Flag | Trasa zodpovedá iba vtedy, keď |\n| --- | --- |\n| `@json` | Telo je JSON |\n| `@xml` | Telo je XML |\n| `@upload` | Telo je `multipart/form-data` |\n| `@xhr` | Požiadavka má `X-Requested-With: XMLHttpRequest` |\n| `@mobile` | Klient je mobilné zariadenie |\n| `@robot` | Klient je crawler |\n| `@referrer` (alebo `@referer`) | Hlavička `Referer` obsahuje host požiadavky |\n| `@debug` | Aplikácia beží v režime debug |\n| `@release` | Aplikácia beží v režime release |\n\nKeď majú dve trasy rovnakú metódu a cestu, najprv sa kontroluje tá s menším počtom flagov. Limity veľkosti a časové limity:\n\n| Flag | Význam |\n| --- | --- |\n| `<500b` | Limit veľkosti tela v bajtoch |\n| `<512kB` | Limit veľkosti tela v kilobajtoch (1 kB = 1024 bajtov) |\n| `<10MB` | Limit veľkosti tela v megabajtoch |\n| `<2GB` | Limit veľkosti tela v gigabajtoch |\n| `<30s` | Časový limit v sekundách |\n| `<5m` | Časový limit v minútach |\n| `<1h` | Časový limit v hodinách |\n\nBez flagu veľkosti je limit `CONF.$httpmaxsize` (256 kB); na väčšie telo sa odpovie s `431`. Bez flagu časového limitu má požiadavka `CONF.$httptimeout` (5 sekúnd) a potom skončí s `503`. Časový limit sa kontroluje každých 5 sekúnd. Limit nastavuje aj tretí argument `ROUTE()`, v bajtoch: `ROUTE('POST /import/', fn, 1024 * 1024 * 50)`.\n\n## Middleware\n\n`#name` spustí middleware registrovaný cez `MIDDLEWARE(name, fn)` pred akciou, v zapísanom poradí. Pozri [Middleware](../../guides/middleware/).\n\n```js\nMIDDLEWARE('nocache', function($, next) {\n\t$.response.headers['cache-control'] = 'no-store';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /report/ #nocache', report);\n};\n```\n\n## Súborové trasy\n\nMetóda `FILE` obsluhuje požiadavky na statické súbory (URL s príponou) tvojím vlastným kódom.\n\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', robots);          // one file\n\tROUTE('FILE /docs/*.md|txt', docs);          // extensions inside /docs/\n\tROUTE('FILE /downloads/*', downloads);       // every file inside /downloads/\n\tROUTE('FILE *.webp', webp);                  // every .webp file\n};\n\nfunction robots($) {\n\t$.plain('User-agent: *');\n}\n\nfunction downloads($) {\n\t$.file(PATH.databases('files' + $.url.substring(10)), true);\n}\n```\n\n## WebSocket trasy\n\n`SOCKET` (alebo `WEBSOCKET`) deklaruje WebSocket endpoint s rovnakou syntaxou cesty, `+`/`-` a flagmi veľkosti. Pozri [WebSockety](../../guides/websockets/).\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/ <1MB', chat);\n};\n```\n\n## Chybové trasy\n\nTrasa s názvom `#` a stavovým kódom nahradí predvolenú chybovú stránku pre tento kód.\n\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n## Odstránenie trasy\n\n`ROUTE()` vracia objekt trasy. Zavolaj na ňom `remove()`, aby si trasu odregistroval počas behu aplikácie; tabuľka smerovania sa okamžite znova zoradí. Funguje to pre každý druh trasy: HTTP trasu, jeden API endpoint (zdieľaná trasa `POST` API zmizne s jej posledným endpointom), trasu `FILE` a trasu `SOCKET` (jej otvorené spojenia sa zatvoria).\n\n```js\nvar route = ROUTE('GET /promo/', function($) {\n\t$.plain('Promo is running');\n});\n\nvar endpoint = ROUTE('API ? promo_read --> Promo/read');\n\n// later\nroute.remove();\nendpoint.remove();\n```\n\n## CORS\n\nPožiadavky s hlavičkou `Origin` z iného hostu sa kontrolujú voči `CONF.$cors`. Nastav ho cez `CORS()` alebo v `/config`.\n\n```js\nCORS();                                         // any origin\nCORS('https://app.example.com,https://admin.example.com');\nCORS('+https://partner.example.com');           // add one more\nCORS('*example.com');                           // any origin that contains example.com\n```\n\nPovolená požiadavka dostane hlavičky `Access-Control-Allow-*` a na preflight požiadavku `OPTIONS` sa odpovie okamžite. Odmietnutý origin dostane `400` s `Invalid origin (CORS)`.\n\n## Proxy\n\n`PROXY(path, target)` prepošle každú požiadavku, ktorej cesta začína `path`, na iný server, ešte pred hľadaním trás. Cieľ je URL `http://` alebo `https://`, cesta k Unix socketu alebo funkcia, ktorá dostane kontrolér.\n\n```js\nPROXY('/cdn/', 'https://cdn.example.com').copy('extend').timeout(10000);\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nPreposlaná požiadavka dostane `X-Forwarded-For`, `X-Forwarded-URL` a `X-Forwarded-Host`. Keď cieľ zlyhá, klient dostane `503`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"JafwUzCTx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/controller/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Controller","summary":"The `$` object of a route action: request data, uploaded files, responses, errors, headers and cookies.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/controller/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Controller\n\n> The `$` object of a route action: request data, uploaded files, responses, errors, headers and cookies.\n\nIn Total.js 5 the action of a route receives one argument, the **controller**, written as `$` by convention. The controller holds everything about the HTTP request and has the methods that send the response. A new controller is created for each request.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail($) {\n\t$.json({ id: $.params.id, ip: $.ip });\n}\n```\n\nThe routes themselves are described in [Routing](../routing/). 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| `$.method` | The HTTP method in upper case (`GET`, `POST`...) |\n| `$.url` | The path of the URL, with a trailing slash and without the query string |\n| `$.split` | The segments of the path as an array (`/a/b/` gives `['a', 'b']`) |\n| `$.params` | The dynamic parts of the URL (`{id}`) as strings |\n| `$.query` | The query string as an object (`?page=2` gives `{ page: '2' }`) |\n| `$.body` | The parsed body: JSON, a URL-encoded form or the fields of a multipart form |\n| `$.files` | Uploaded files of a `multipart/form-data` request |\n| `$.payload` | The raw body as a `Buffer` (not for multipart requests) |\n| `$.headers` | The request headers, with lower-case names |\n| `$.ip` | The IP address of the client (the first `X-Forwarded-For` address behind a proxy) |\n| `$.ua` | A short name of the system and the browser, parsed from `User-Agent` |\n| `$.mobile`, `$.robot` | `true` for mobile devices, or for crawlers |\n| `$.xhr` | `true` when the request has `X-Requested-With: XMLHttpRequest` |\n| `$.user` | The user returned by your authorization delegate, or `undefined` |\n| `$.language` | The language returned by your localization delegate, or an empty string |\n| `$.protocol`, `$.host`, `$.address` | `http` or `https`, the `Host` header and the full URL |\n| `$.req`, `$.res` | The Node.js request and response objects |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar model = $.body;\n\tvar page = $.query.page;\n\tvar agent = $.headers['user-agent'];\n\t$.success();\n}\n```\n\nValues of `$.params`, `$.query` and URL-encoded forms are strings: convert numbers and dates yourself, or use an action with a schema (see [Actions](../actions/) and [JSON schemas](../json-schemas/)). The body is read only for `POST`, `PUT`, `PATCH` and `DELETE` requests. A body bigger than the size limit of the route is refused with `431`.\n\n## Uploaded files\n\nThe fields of a `multipart/form-data` request are in `$.body` and the files in `$.files`. Each file has `name` (the field), `filename`, `type`, `size`, `extension`, `width` and `height` for images, and methods to `move()`, `read()`, `copy()` or save the file into a file storage with `fs()`. Uploaded files are temporary: they are removed when the response ends, unless you moved them.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ <5MB', upload);\n};\n\nfunction upload($) {\n\tvar file = $.files[0];\n\n\tif (!file || !file.isImage) {\n\t\t$.invalid('@(Upload an image)');\n\t\treturn;\n\t}\n\n\tfile.move(PATH.public('photos/' + UID() + '.' + file.extension), function(err) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success();\n\t});\n}\n```\n\nThe flag `<5MB` raises the size limit of the body for this route (the default is the configuration key `$httpmaxsize`, 256 kB). See [Routing](../routing/).\n\n## Sending a response\n\nEach method below ends the request. Call only one of them per request.\n\n| Method | Response |\n| --- | --- |\n| `$.json(value)` | JSON |\n| `$.success([value])` | `{ success: true, value: value }` as JSON |\n| `$.invalid(error)` | An error as JSON, with status 400 or the status of the error |\n| `$.jsonstring(text)` | A string that is already JSON |\n| `$.html(text)`, `$.plain(text)`, `$.xml(text)` | Text with the right content type |\n| `$.view(name, [model])` | A rendered view |\n| `$.file(path, [download])` | A file from the disk |\n| `$.stream(type, stream, [download])` | A readable stream |\n| `$.binary(buffer, type, [download])` | A `Buffer` |\n| `$.content(value, [type])` | A string or a `Buffer` with your content type |\n| `$.redirect(url, [permanent])` | A redirect with 302, or 301 |\n| `$.empty()` | Status 204 without a body |\n| `$.fallback(code, [error])` | An error page (or JSON for XHR requests) |\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', list);\n\tROUTE('GET /download/', download);\n\tROUTE('GET /old/', function($) {\n\t\t$.redirect('/new/', true);\n\t});\n};\n\nfunction list($) {\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.json(response);\n\t});\n}\n\nfunction download($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n}\n```\n\n`$.json(value, [beautify], [replacer])` serializes `value` with `JSON.stringify()`, sets `content-type: application/json` and headers that disable caching (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). Pass `true` as `beautify` to indent the output with tabs, and a `replacer` function (or an array of keys) to filter the values, exactly as the second argument of `JSON.stringify()`.\n\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n`$.callback()` without arguments returns a function `(err, value)` that answers with `$.invalid(err)` or `$.json(value)`, which is handy for callbacks of the database: `NOSQL('products').find().callback($.callback())`. `$.done([value])` does the same and wraps the value with `{ success: true, value: ... }`.\n\n## Errors\n\n`$.invalid()` accepts a string, an `Error`, an `ErrorBuilder` or an HTTP status code. The response is a JSON array of errors. Text written as `@(text)` is translated with the resources of the request language.\n\n```js\nfunction update($) {\n\tif (!$.body.name) {\n\t\t$.invalid('Name is required');\n\t\treturn;\n\t}\n\tif (!$.user) {\n\t\t$.invalid(401);\n\t\treturn;\n\t}\n\t$.success($.body.name);\n}\n```\n\n`$.invalidsafe(message, error)` sends `message` like `$.invalid()` and writes `error` to the error log, so the client does not see the details of the error. `$.throw(error)` only writes an error to the log; you still send a response.\n\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n`$.fallback(code)` sends the built-in error page with the given status. When you define a route like `ROUTE('#404', fn)`, that action handles the request instead; the status is `200` unless the action sets `$.response.status`. For XHR requests the error is sent as JSON.\n\n## Status and headers\n\nThe response that will be sent is in `$.response`. Change `$.response.status` and `$.response.headers` before you call a response method:\n\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\nFor HTTP caching, `$.httpcache(date)` sets `Last-Modified`, `Expires` and `Cache-Control`, and `$.notmodified(date)` answers with `304` when the browser already has the same version.\n\n## Cookies\n\n`$.cookie(name)` reads a cookie and `$.cookie(name, value, expires, [options])` sets one. `expires` is a `Date` or a string such as `'7 days'`. The options are `domain`, `path` (default `/`), `secure`, `httponly` and `samesite` (`'Lax'`, `'Strict'`, `'None'`). The defaults for `secure` and `samesite` come from the configuration keys `$cookiesecure` and `$cookiesamesite`.\n\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true });\n\t$.success();\n}\n\nfunction profile($) {\n\tvar session = $.cookie('session');\n\t$.json({ session: session });\n}\n```\n\nTo remove a cookie, set it with an empty value and a date in the past.\n\n## Views\n\n`$.view(name, [model])` renders a file from the `/views/` directory and sends it as HTML. `$.layout(name)` chooses the layout for the next view. See [Views](../views/).\n\n```js\nfunction homepage($) {\n\t$.layout('layout');\n\t$.view('index', { title: 'Home' });\n}\n```\n\n## Other helpers\n\n- `$.action(name, model)` runs an action with this controller (see [Actions](../actions/)).\n- `$.authorize([callback])` runs your authorization delegate manually and fills `$.user`.\n- `$.proxy(url)` forwards the request to another server and sends its answer.\n- `$.hostname([path])` returns `protocol://host` with an optional path.\n- `$.href([key], [value])` returns the query string of the request with one parameter changed, for paging and sorting links; `$.href({ page: 1, sort: 'price' })` returns the URL with several parameters changed.\n- `$.touch([url])` clears the cached state of a static file after you change it (see [Static files](../static-files/)).\n- `$.csrf()` creates a CSRF token.\n- `$.custom()` tells the framework that you write to `$.res` yourself.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUzCTx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/controller/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Controller","summary":"Das Objekt `$` einer Routen-Aktion: Anfragedaten, hochgeladene Dateien, Antworten, Fehler, Header und Cookies.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/controller/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Controller\n\n> Das Objekt `$` einer Routen-Aktion: Anfragedaten, hochgeladene Dateien, Antworten, Fehler, Header und Cookies.\n\nIn Total.js 5 erhält die Aktion einer Route ein Argument, den **Controller**, der nach Konvention als `$` geschrieben wird. Der Controller enthält alles über die HTTP-Anfrage und hat die Methoden, die die Antwort senden. 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($) {\n\t$.json({ id: $.params.id, ip: $.ip });\n}\n```\n\nDie Routen selbst werden in [Routing](../routing/) beschrieben. Die vollständige Liste der Eigenschaften und Methoden steht in der Referenz [Controller](../../reference/controller/).\n\n## Anfragedaten\n\n| Eigenschaft | Was sie enthält |\n| --- | --- |\n| `$.method` | Die HTTP-Methode in Großbuchstaben (`GET`, `POST`...) |\n| `$.url` | Der Pfad der URL, mit abschließendem Schrägstrich und ohne Query String |\n| `$.split` | Die Segmente des Pfads als Array (`/a/b/` ergibt `['a', 'b']`) |\n| `$.params` | Die dynamischen Teile der URL (`{id}`) als Strings |\n| `$.query` | Der Query String als Objekt (`?page=2` ergibt `{ page: '2' }`) |\n| `$.body` | Der geparste Body: JSON, ein URL-codiertes Formular oder die Felder eines Multipart-Formulars |\n| `$.files` | Hochgeladene Dateien einer `multipart/form-data`-Anfrage |\n| `$.payload` | Der rohe Body als `Buffer` (nicht bei Multipart-Anfragen) |\n| `$.headers` | Die Header der Anfrage, mit kleingeschriebenen Namen |\n| `$.ip` | Die IP-Adresse des Clients (hinter einem Proxy die erste Adresse aus `X-Forwarded-For`) |\n| `$.ua` | Ein kurzer Name des Systems und des Browsers, aus `User-Agent` geparst |\n| `$.mobile`, `$.robot` | `true` für Mobilgeräte bzw. für Crawler |\n| `$.xhr` | `true`, wenn die Anfrage `X-Requested-With: XMLHttpRequest` hat |\n| `$.user` | Der von deinem Autorisierungs-Delegate zurückgegebene Benutzer oder `undefined` |\n| `$.language` | Die von deinem Lokalisierungs-Delegate zurückgegebene Sprache oder ein leerer String |\n| `$.protocol`, `$.host`, `$.address` | `http` oder `https`, der Header `Host` und die vollständige URL |\n| `$.req`, `$.res` | Die Node.js-Objekte für Anfrage und Antwort |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar model = $.body;\n\tvar page = $.query.page;\n\tvar agent = $.headers['user-agent'];\n\t$.success();\n}\n```\n\nWerte von `$.params`, `$.query` und URL-codierten Formularen sind Strings: Wandle Zahlen und Datumswerte selbst um oder verwende eine Aktion mit einem Schema (siehe [Aktionen](../actions/) und [JSON-Schemas](../json-schemas/)). Der Body wird nur bei `POST`-, `PUT`-, `PATCH`- und `DELETE`-Anfragen gelesen. Ein Body, der größer als das Größenlimit der Route ist, wird mit `431` abgewiesen.\n\n## Hochgeladene Dateien\n\nDie Felder einer `multipart/form-data`-Anfrage stehen in `$.body` und die Dateien in `$.files`. Jede Datei hat `name` (das Feld), `filename`, `type`, `size`, `extension`, `width` und `height` bei Bildern sowie Methoden, um die Datei zu verschieben (`move()`), zu lesen (`read()`), zu kopieren (`copy()`) oder mit `fs()` in einem Dateispeicher zu speichern. Hochgeladene Dateien sind temporär: Sie werden entfernt, wenn die Antwort endet, sofern du sie nicht verschoben hast.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ <5MB', upload);\n};\n\nfunction upload($) {\n\tvar file = $.files[0];\n\n\tif (!file || !file.isImage) {\n\t\t$.invalid('@(Upload an image)');\n\t\treturn;\n\t}\n\n\tfile.move(PATH.public('photos/' + UID() + '.' + file.extension), function(err) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success();\n\t});\n}\n```\n\nDas Flag `<5MB` erhöht das Größenlimit des Bodys für diese Route (der Standard ist der Konfigurationsschlüssel `$httpmaxsize`, 256 kB). Siehe [Routing](../routing/).\n\n## Eine Antwort senden\n\nJede der folgenden Methoden beendet die Anfrage. Rufe pro Anfrage nur eine davon auf.\n\n| Methode | Antwort |\n| --- | --- |\n| `$.json(value)` | JSON |\n| `$.success([value])` | `{ success: true, value: value }` als JSON |\n| `$.invalid(error)` | Ein Fehler als JSON, mit Status 400 oder dem Status des Fehlers |\n| `$.jsonstring(text)` | Ein String, der bereits JSON ist |\n| `$.html(text)`, `$.plain(text)`, `$.xml(text)` | Text mit dem passenden Content-Type |\n| `$.view(name, [model])` | Eine gerenderte View |\n| `$.file(path, [download])` | Eine Datei von der Festplatte |\n| `$.stream(type, stream, [download])` | Ein lesbarer Stream |\n| `$.binary(buffer, type, [download])` | Ein `Buffer` |\n| `$.content(value, [type])` | Ein String oder ein `Buffer` mit deinem Content-Type |\n| `$.redirect(url, [permanent])` | Eine Weiterleitung mit 302 oder 301 |\n| `$.empty()` | Status 204 ohne Body |\n| `$.fallback(code, [error])` | Eine Fehlerseite (oder JSON bei XHR-Anfragen) |\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', list);\n\tROUTE('GET /download/', download);\n\tROUTE('GET /old/', function($) {\n\t\t$.redirect('/new/', true);\n\t});\n};\n\nfunction list($) {\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.json(response);\n\t});\n}\n\nfunction download($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n}\n```\n\n`$.json(value, [beautify], [replacer])` serialisiert `value` mit `JSON.stringify()`, setzt `content-type: application/json` und Header, die das Caching abschalten (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). Übergib `true` als `beautify`, um die Ausgabe mit Tabs einzurücken, und eine `replacer`-Funktion (oder ein Array von Schlüsseln), um die Werte zu filtern, genau wie das zweite Argument von `JSON.stringify()`.\n\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n`$.callback()` ohne Argumente gibt eine Funktion `(err, value)` zurück, die mit `$.invalid(err)` oder `$.json(value)` antwortet, was für Callbacks der Datenbank praktisch ist: `NOSQL('products').find().callback($.callback())`. `$.done([value])` tut dasselbe und verpackt den Wert in `{ success: true, value: ... }`.\n\n## Fehler\n\n`$.invalid()` akzeptiert einen String, einen `Error`, einen `ErrorBuilder` oder einen HTTP-Statuscode. Die Antwort ist ein JSON-Array von Fehlern. Als `@(text)` geschriebener Text wird mit den Ressourcen der Sprache der Anfrage übersetzt.\n\n```js\nfunction update($) {\n\tif (!$.body.name) {\n\t\t$.invalid('Name is required');\n\t\treturn;\n\t}\n\tif (!$.user) {\n\t\t$.invalid(401);\n\t\treturn;\n\t}\n\t$.success($.body.name);\n}\n```\n\n`$.invalidsafe(message, error)` sendet `message` wie `$.invalid()` und schreibt `error` ins Fehlerlog, sodass der Client die Details des Fehlers nicht sieht. `$.throw(error)` schreibt nur einen Fehler ins Log; eine Antwort sendest du trotzdem selbst.\n\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n`$.fallback(code)` sendet die eingebaute Fehlerseite mit dem angegebenen Status. Definierst du eine Route wie `ROUTE('#404', fn)`, behandelt stattdessen diese Aktion die Anfrage; der Status ist `200`, außer die Aktion setzt `$.response.status`. Bei XHR-Anfragen wird der Fehler als JSON gesendet.\n\n## Status und Header\n\nDie Antwort, die gesendet wird, steht in `$.response`. Ändere `$.response.status` und `$.response.headers`, bevor du eine Antwortmethode aufrufst:\n\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\nFür HTTP-Caching setzt `$.httpcache(date)` `Last-Modified`, `Expires` und `Cache-Control`, und `$.notmodified(date)` antwortet mit `304`, wenn der Browser bereits dieselbe Version hat.\n\n## Cookies\n\n`$.cookie(name)` liest ein Cookie, und `$.cookie(name, value, expires, [options])` setzt eines. `expires` ist ein `Date` oder ein String wie `'7 days'`. Die Optionen sind `domain`, `path` (Standard `/`), `secure`, `httponly` und `samesite` (`'Lax'`, `'Strict'`, `'None'`). Die Standardwerte für `secure` und `samesite` kommen aus den Konfigurationsschlüsseln `$cookiesecure` und `$cookiesamesite`.\n\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true });\n\t$.success();\n}\n\nfunction profile($) {\n\tvar session = $.cookie('session');\n\t$.json({ session: session });\n}\n```\n\nUm ein Cookie zu entfernen, setze es mit einem leeren Wert und einem Datum in der Vergangenheit.\n\n## Views\n\n`$.view(name, [model])` rendert eine Datei aus dem Verzeichnis `/views/` und sendet sie als HTML. `$.layout(name)` wählt das Layout für die nächste View. Siehe [Views](../views/).\n\n```js\nfunction homepage($) {\n\t$.layout('layout');\n\t$.view('index', { title: 'Home' });\n}\n```\n\n## Weitere Helfer\n\n- `$.action(name, model)` führt eine Aktion mit diesem Controller aus (siehe [Aktionen](../actions/)).\n- `$.authorize([callback])` führt deinen Autorisierungs-Delegate manuell aus und füllt `$.user`.\n- `$.proxy(url)` leitet die Anfrage an einen anderen Server weiter und sendet dessen Antwort.\n- `$.hostname([path])` gibt `protocol://host` mit einem optionalen Pfad zurück.\n- `$.href([key], [value])` gibt den Query String der Anfrage mit einem geänderten Parameter zurück, für Links zum Blättern und Sortieren; `$.href({ page: 1, sort: 'price' })` gibt die URL mit mehreren geänderten Parametern zurück.\n- `$.touch([url])` löscht den gecachten Zustand einer statischen Datei, nachdem du sie geändert hast (siehe [Statische Dateien](../static-files/)).\n- `$.csrf()` erstellt ein CSRF-Token.\n- `$.custom()` teilt dem Framework mit, dass du selbst in `$.res` schreibst.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUzCTx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/controller/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Controller","summary":"El objeto `$` de la acción de una ruta: datos de la petición, archivos subidos, respuestas, errores, cabeceras y cookies.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/controller/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Controller\n\n> El objeto `$` de la acción de una ruta: datos de la petición, archivos subidos, respuestas, errores, cabeceras y cookies.\n\nEn Total.js 5 la acción de una ruta recibe un argumento, el **controlador**, escrito como `$` por convención. El controlador contiene todo lo relativo a la petición HTTP y tiene los métodos que envían la respuesta. Se crea un nuevo controlador para cada petición.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail($) {\n\t$.json({ id: $.params.id, ip: $.ip });\n}\n```\n\nLas rutas en sí se describen en [Enrutamiento](../routing/). La lista completa de propiedades y métodos está en la referencia de [Controlador](../../reference/controller/).\n\n## Datos de la petición\n\n| Propiedad | Qué contiene |\n| --- | --- |\n| `$.method` | El método HTTP en mayúsculas (`GET`, `POST`...) |\n| `$.url` | La ruta de la URL, con barra final y sin la query string |\n| `$.split` | Los segmentos de la ruta como array (`/a/b/` da `['a', 'b']`) |\n| `$.params` | Las partes dinámicas de la URL (`{id}`) como strings |\n| `$.query` | La query string como objeto (`?page=2` da `{ page: '2' }`) |\n| `$.body` | El cuerpo parseado: JSON, un formulario URL-encoded o los campos de un formulario multipart |\n| `$.files` | Los archivos subidos de una petición `multipart/form-data` |\n| `$.payload` | El cuerpo en bruto como `Buffer` (no para peticiones multipart) |\n| `$.headers` | Las cabeceras de la petición, con nombres en minúsculas |\n| `$.ip` | La dirección IP del cliente (la primera dirección de `X-Forwarded-For` detrás de un proxy) |\n| `$.ua` | Un nombre corto del sistema y del navegador, parseado de `User-Agent` |\n| `$.mobile`, `$.robot` | `true` para dispositivos móviles, o para crawlers |\n| `$.xhr` | `true` cuando la petición tiene `X-Requested-With: XMLHttpRequest` |\n| `$.user` | El usuario devuelto por tu delegado de autorización, o `undefined` |\n| `$.language` | El idioma devuelto por tu delegado de localización, o un string vacío |\n| `$.protocol`, `$.host`, `$.address` | `http` o `https`, la cabecera `Host` y la URL completa |\n| `$.req`, `$.res` | Los objetos de petición y respuesta de Node.js |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar model = $.body;\n\tvar page = $.query.page;\n\tvar agent = $.headers['user-agent'];\n\t$.success();\n}\n```\n\nLos valores de `$.params`, `$.query` y de los formularios URL-encoded son strings: convierte tú mismo los números y las fechas, o usa una acción con un esquema (consulta [Acciones](../actions/) y [Esquemas JSON](../json-schemas/)). El cuerpo solo se lee en las peticiones `POST`, `PUT`, `PATCH` y `DELETE`. Un cuerpo mayor que el límite de tamaño de la ruta se rechaza con `431`.\n\n## Archivos subidos\n\nLos campos de una petición `multipart/form-data` están en `$.body` y los archivos en `$.files`. Cada archivo tiene `name` (el campo), `filename`, `type`, `size`, `extension`, `width` y `height` para imágenes, y métodos para `move()`, `read()`, `copy()` o guardar el archivo en un almacenamiento de archivos con `fs()`. Los archivos subidos son temporales: se eliminan cuando termina la respuesta, salvo que los hayas movido.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ <5MB', upload);\n};\n\nfunction upload($) {\n\tvar file = $.files[0];\n\n\tif (!file || !file.isImage) {\n\t\t$.invalid('@(Upload an image)');\n\t\treturn;\n\t}\n\n\tfile.move(PATH.public('photos/' + UID() + '.' + file.extension), function(err) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success();\n\t});\n}\n```\n\nEl flag `<5MB` aumenta el límite de tamaño del cuerpo para esta ruta (el valor por defecto es la clave de configuración `$httpmaxsize`, 256 kB). Consulta [Enrutamiento](../routing/).\n\n## Enviar una respuesta\n\nCada método de abajo termina la petición. Llama solo a uno de ellos por petición.\n\n| Método | Respuesta |\n| --- | --- |\n| `$.json(value)` | JSON |\n| `$.success([value])` | `{ success: true, value: value }` como JSON |\n| `$.invalid(error)` | Un error como JSON, con el estado 400 o el estado del error |\n| `$.jsonstring(text)` | Un string que ya es JSON |\n| `$.html(text)`, `$.plain(text)`, `$.xml(text)` | Texto con el content type adecuado |\n| `$.view(name, [model])` | Una vista renderizada |\n| `$.file(path, [download])` | Un archivo del disco |\n| `$.stream(type, stream, [download])` | Un stream legible |\n| `$.binary(buffer, type, [download])` | Un `Buffer` |\n| `$.content(value, [type])` | Un string o un `Buffer` con tu content type |\n| `$.redirect(url, [permanent])` | Una redirección con 302, o 301 |\n| `$.empty()` | Estado 204 sin cuerpo |\n| `$.fallback(code, [error])` | Una página de error (o JSON para peticiones XHR) |\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', list);\n\tROUTE('GET /download/', download);\n\tROUTE('GET /old/', function($) {\n\t\t$.redirect('/new/', true);\n\t});\n};\n\nfunction list($) {\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.json(response);\n\t});\n}\n\nfunction download($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n}\n```\n\n`$.json(value, [beautify], [replacer])` serializa `value` con `JSON.stringify()`, establece `content-type: application/json` y cabeceras que desactivan la caché (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). Pasa `true` como `beautify` para indentar la salida con tabuladores, y una función `replacer` (o un array de claves) para filtrar los valores, exactamente como el segundo argumento de `JSON.stringify()`.\n\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n`$.callback()` sin argumentos devuelve una función `(err, value)` que responde con `$.invalid(err)` o `$.json(value)`, lo que es práctico para los callbacks de la base de datos: `NOSQL('products').find().callback($.callback())`. `$.done([value])` hace lo mismo y envuelve el valor con `{ success: true, value: ... }`.\n\n## Errores\n\n`$.invalid()` acepta un string, un `Error`, un `ErrorBuilder` o un código de estado HTTP. La respuesta es un array JSON de errores. El texto escrito como `@(text)` se traduce con los recursos del idioma de la petición.\n\n```js\nfunction update($) {\n\tif (!$.body.name) {\n\t\t$.invalid('Name is required');\n\t\treturn;\n\t}\n\tif (!$.user) {\n\t\t$.invalid(401);\n\t\treturn;\n\t}\n\t$.success($.body.name);\n}\n```\n\n`$.invalidsafe(message, error)` envía `message` como `$.invalid()` y escribe `error` en el log de errores, así el cliente no ve los detalles del error. `$.throw(error)` solo escribe un error en el log; tú sigues enviando una respuesta.\n\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n`$.fallback(code)` envía la página de error integrada con el estado dado. Cuando defines una ruta como `ROUTE('#404', fn)`, esa acción gestiona la petición en su lugar; el estado es `200` salvo que la acción establezca `$.response.status`. Para peticiones XHR el error se envía como JSON.\n\n## Estado y cabeceras\n\nLa respuesta que se enviará está en `$.response`. Cambia `$.response.status` y `$.response.headers` antes de llamar a un método de respuesta:\n\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\nPara la caché HTTP, `$.httpcache(date)` establece `Last-Modified`, `Expires` y `Cache-Control`, y `$.notmodified(date)` responde con `304` cuando el navegador ya tiene la misma versión.\n\n## Cookies\n\n`$.cookie(name)` lee una cookie y `$.cookie(name, value, expires, [options])` establece una. `expires` es un `Date` o un string como `'7 days'`. Las opciones son `domain`, `path` (por defecto `/`), `secure`, `httponly` y `samesite` (`'Lax'`, `'Strict'`, `'None'`). Los valores por defecto de `secure` y `samesite` vienen de las claves de configuración `$cookiesecure` y `$cookiesamesite`.\n\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true });\n\t$.success();\n}\n\nfunction profile($) {\n\tvar session = $.cookie('session');\n\t$.json({ session: session });\n}\n```\n\nPara eliminar una cookie, establécela con un valor vacío y una fecha pasada.\n\n## Vistas\n\n`$.view(name, [model])` renderiza un archivo del directorio `/views/` y lo envía como HTML. `$.layout(name)` elige la plantilla (layout) para la siguiente vista. Consulta [Vistas](../views/).\n\n```js\nfunction homepage($) {\n\t$.layout('layout');\n\t$.view('index', { title: 'Home' });\n}\n```\n\n## Otros helpers\n\n- `$.action(name, model)` ejecuta una acción con este controlador (consulta [Acciones](../actions/)).\n- `$.authorize([callback])` ejecuta manualmente tu delegado de autorización y rellena `$.user`.\n- `$.proxy(url)` reenvía la petición a otro servidor y envía su respuesta.\n- `$.hostname([path])` devuelve `protocol://host` con una ruta opcional.\n- `$.href([key], [value])` devuelve el query string de la petición con un parámetro cambiado, para enlaces de paginación y ordenación; `$.href({ page: 1, sort: 'price' })` devuelve la URL con varios parámetros cambiados.\n- `$.touch([url])` borra el estado en caché de un archivo estático después de cambiarlo (consulta [Archivos estáticos](../static-files/)).\n- `$.csrf()` crea un token CSRF.\n- `$.custom()` indica al framework que escribes tú mismo en `$.res`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUzCTx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/controller/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Controller","summary":"L'objet `$` d'une action de route : données de la requête, fichiers envoyés, réponses, erreurs, en-têtes et cookies.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/controller/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Controller\n\n> L'objet `$` d'une action de route : données de la requête, fichiers envoyés, réponses, erreurs, en-têtes et cookies.\n\nDans Total.js 5, l'action d'une route reçoit un argument, le **contrôleur**, écrit `$` par convention. Le contrôleur contient tout ce qui concerne la requête HTTP et possède les méthodes qui envoient la réponse. 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($) {\n\t$.json({ id: $.params.id, ip: $.ip });\n}\n```\n\nLes routes elles-mêmes sont décrites dans [Routage](../routing/). La liste complète des propriétés et des méthodes se trouve dans la référence [Contrôleur](../../reference/controller/).\n\n## Données de la requête\n\n| Propriété | Ce qu'elle contient |\n| --- | --- |\n| `$.method` | La méthode HTTP en majuscules (`GET`, `POST`...) |\n| `$.url` | Le chemin de l'URL, avec une barre oblique finale et sans la query string |\n| `$.split` | Les segments du chemin sous forme de tableau (`/a/b/` donne `['a', 'b']`) |\n| `$.params` | Les parties dynamiques de l'URL (`{id}`) sous forme de chaînes |\n| `$.query` | La query string sous forme d'objet (`?page=2` donne `{ page: '2' }`) |\n| `$.body` | Le corps analysé : JSON, un formulaire URL-encoded ou les champs d'un formulaire multipart |\n| `$.files` | Les fichiers envoyés d'une requête `multipart/form-data` |\n| `$.payload` | Le corps brut sous forme de `Buffer` (pas pour les requêtes multipart) |\n| `$.headers` | Les en-têtes de la requête, avec des noms en minuscules |\n| `$.ip` | L'adresse IP du client (la première adresse `X-Forwarded-For` derrière un proxy) |\n| `$.ua` | Un nom court du système et du navigateur, extrait de `User-Agent` |\n| `$.mobile`, `$.robot` | `true` pour les appareils mobiles, ou pour les robots d'indexation |\n| `$.xhr` | `true` lorsque la requête a `X-Requested-With: XMLHttpRequest` |\n| `$.user` | L'utilisateur renvoyé par ton délégué d'autorisation, ou `undefined` |\n| `$.language` | La langue renvoyée par ton délégué de localisation, ou une chaîne vide |\n| `$.protocol`, `$.host`, `$.address` | `http` ou `https`, l'en-tête `Host` et l'URL complète |\n| `$.req`, `$.res` | Les objets requête et réponse de Node.js |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar model = $.body;\n\tvar page = $.query.page;\n\tvar agent = $.headers['user-agent'];\n\t$.success();\n}\n```\n\nLes valeurs de `$.params`, de `$.query` et des formulaires URL-encoded sont des chaînes : convertis toi-même les nombres et les dates, ou utilise une action avec un schéma (voir [Actions](../actions/) et [Schémas JSON](../json-schemas/)). Le corps n'est lu que pour les requêtes `POST`, `PUT`, `PATCH` et `DELETE`. Un corps plus grand que la limite de taille de la route est refusé avec `431`.\n\n## Fichiers envoyés\n\nLes champs d'une requête `multipart/form-data` sont dans `$.body` et les fichiers dans `$.files`. Chaque fichier a `name` (le champ), `filename`, `type`, `size`, `extension`, `width` et `height` pour les images, ainsi que des méthodes pour `move()`, `read()`, `copy()` ou enregistrer le fichier dans un stockage de fichiers avec `fs()`. Les fichiers envoyés sont temporaires : ils sont supprimés à la fin de la réponse, sauf si tu les as déplacés.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ <5MB', upload);\n};\n\nfunction upload($) {\n\tvar file = $.files[0];\n\n\tif (!file || !file.isImage) {\n\t\t$.invalid('@(Upload an image)');\n\t\treturn;\n\t}\n\n\tfile.move(PATH.public('photos/' + UID() + '.' + file.extension), function(err) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success();\n\t});\n}\n```\n\nLe flag `<5MB` augmente la limite de taille du corps pour cette route (la valeur par défaut est la clé de configuration `$httpmaxsize`, 256 ko). Voir [Routage](../routing/).\n\n## Envoyer une réponse\n\nChaque méthode ci-dessous termine la requête. N'en appelle qu'une seule par requête.\n\n| Méthode | Réponse |\n| --- | --- |\n| `$.json(value)` | JSON |\n| `$.success([value])` | `{ success: true, value: value }` en JSON |\n| `$.invalid(error)` | Une erreur en JSON, avec le statut 400 ou le statut de l'erreur |\n| `$.jsonstring(text)` | Une chaîne qui est déjà du JSON |\n| `$.html(text)`, `$.plain(text)`, `$.xml(text)` | Du texte avec le bon type de contenu |\n| `$.view(name, [model])` | Une vue rendue |\n| `$.file(path, [download])` | Un fichier du disque |\n| `$.stream(type, stream, [download])` | Un stream lisible |\n| `$.binary(buffer, type, [download])` | Un `Buffer` |\n| `$.content(value, [type])` | Une chaîne ou un `Buffer` avec ton type de contenu |\n| `$.redirect(url, [permanent])` | Une redirection avec 302, ou 301 |\n| `$.empty()` | Statut 204 sans corps |\n| `$.fallback(code, [error])` | Une page d'erreur (ou du JSON pour les requêtes XHR) |\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', list);\n\tROUTE('GET /download/', download);\n\tROUTE('GET /old/', function($) {\n\t\t$.redirect('/new/', true);\n\t});\n};\n\nfunction list($) {\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.json(response);\n\t});\n}\n\nfunction download($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n}\n```\n\n`$.json(value, [beautify], [replacer])` sérialise `value` avec `JSON.stringify()`, définit `content-type: application/json` et des en-têtes qui désactivent le cache (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). Passe `true` comme `beautify` pour indenter la sortie avec des tabulations, et une fonction `replacer` (ou un tableau de clés) pour filtrer les valeurs, exactement comme le second argument de `JSON.stringify()`.\n\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n`$.callback()` sans argument renvoie une fonction `(err, value)` qui répond avec `$.invalid(err)` ou `$.json(value)`, ce qui est pratique pour les callbacks de la base de données : `NOSQL('products').find().callback($.callback())`. `$.done([value])` fait de même et enveloppe la valeur avec `{ success: true, value: ... }`.\n\n## Erreurs\n\n`$.invalid()` accepte une chaîne, une `Error`, un `ErrorBuilder` ou un code de statut HTTP. La réponse est un tableau JSON d'erreurs. Un texte écrit sous la forme `@(text)` est traduit avec les ressources de la langue de la requête.\n\n```js\nfunction update($) {\n\tif (!$.body.name) {\n\t\t$.invalid('Name is required');\n\t\treturn;\n\t}\n\tif (!$.user) {\n\t\t$.invalid(401);\n\t\treturn;\n\t}\n\t$.success($.body.name);\n}\n```\n\n`$.invalidsafe(message, error)` envoie `message` comme `$.invalid()` et écrit `error` dans le log des erreurs, de sorte que le client ne voit pas les détails de l'erreur. `$.throw(error)` écrit seulement une erreur dans le log ; tu envoies quand même une réponse.\n\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n`$.fallback(code)` envoie la page d'erreur intégrée avec le statut indiqué. Lorsque tu définis une route comme `ROUTE('#404', fn)`, c'est cette action qui traite la requête à la place ; le statut est `200` sauf si l'action définit `$.response.status`. Pour les requêtes XHR, l'erreur est envoyée en JSON.\n\n## Statut et en-têtes\n\nLa réponse qui sera envoyée se trouve dans `$.response`. Modifie `$.response.status` et `$.response.headers` avant d'appeler une méthode de réponse :\n\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\nPour le cache HTTP, `$.httpcache(date)` définit `Last-Modified`, `Expires` et `Cache-Control`, et `$.notmodified(date)` répond avec `304` lorsque le navigateur possède déjà la même version.\n\n## Cookies\n\n`$.cookie(name)` lit un cookie et `$.cookie(name, value, expires, [options])` en définit un. `expires` est une `Date` ou une chaîne comme `'7 days'`. Les options sont `domain`, `path` (par défaut `/`), `secure`, `httponly` et `samesite` (`'Lax'`, `'Strict'`, `'None'`). Les valeurs par défaut de `secure` et `samesite` proviennent des clés de configuration `$cookiesecure` et `$cookiesamesite`.\n\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true });\n\t$.success();\n}\n\nfunction profile($) {\n\tvar session = $.cookie('session');\n\t$.json({ session: session });\n}\n```\n\nPour supprimer un cookie, définis-le avec une valeur vide et une date passée.\n\n## Vues\n\n`$.view(name, [model])` effectue le rendu d'un fichier du répertoire `/views/` et l'envoie en HTML. `$.layout(name)` choisit le layout de la vue suivante. Voir [Vues](../views/).\n\n```js\nfunction homepage($) {\n\t$.layout('layout');\n\t$.view('index', { title: 'Home' });\n}\n```\n\n## Autres helpers\n\n- `$.action(name, model)` exécute une action avec ce contrôleur (voir [Actions](../actions/)).\n- `$.authorize([callback])` exécute manuellement ton délégué d'autorisation et remplit `$.user`.\n- `$.proxy(url)` transmet la requête à un autre serveur et envoie sa réponse.\n- `$.hostname([path])` renvoie `protocol://host` avec un chemin facultatif.\n- `$.href([key], [value])` renvoie la query string de la requête avec un paramètre modifié, pour les liens de pagination et de tri ; `$.href({ page: 1, sort: 'price' })` renvoie l'URL avec plusieurs paramètres modifiés.\n- `$.touch([url])` efface l'état mis en cache d'un fichier statique après que tu l'as modifié (voir [Fichiers statiques](../static-files/)).\n- `$.csrf()` crée un token CSRF.\n- `$.custom()` indique au framework que tu écris toi-même dans `$.res`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUzCTx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/controller/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Controller","summary":"L'oggetto `$` dell'azione di una route: dati della richiesta, file caricati, risposte, errori, header e cookie.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/controller/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Controller\n\n> L'oggetto `$` dell'azione di una route: dati della richiesta, file caricati, risposte, errori, header e cookie.\n\nIn Total.js 5 l'azione di una route riceve un solo argomento, il **controller**, scritto come `$` per convenzione. Il controller contiene tutto ciò che riguarda la richiesta HTTP e ha i metodi che inviano la risposta. Per ogni richiesta viene creato un nuovo controller.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail($) {\n\t$.json({ id: $.params.id, ip: $.ip });\n}\n```\n\nLe route stesse sono descritte in [Routing](../routing/). 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| `$.method` | Il metodo HTTP in maiuscolo (`GET`, `POST`...) |\n| `$.url` | Il percorso dell'URL, con la barra finale e senza la query string |\n| `$.split` | I segmenti del percorso come array (`/a/b/` dà `['a', 'b']`) |\n| `$.params` | Le parti dinamiche dell'URL (`{id}`) come stringhe |\n| `$.query` | La query string come oggetto (`?page=2` dà `{ page: '2' }`) |\n| `$.body` | Il body interpretato: JSON, un form URL-encoded o i campi di un form multipart |\n| `$.files` | I file caricati di una richiesta `multipart/form-data` |\n| `$.payload` | Il body grezzo come `Buffer` (non per le richieste multipart) |\n| `$.headers` | Gli header della richiesta, con i nomi in minuscolo |\n| `$.ip` | L'indirizzo IP del client (il primo indirizzo di `X-Forwarded-For` dietro un proxy) |\n| `$.ua` | Un nome breve del sistema e del browser, ricavato da `User-Agent` |\n| `$.mobile`, `$.robot` | `true` per i dispositivi mobili, o per i crawler |\n| `$.xhr` | `true` quando la richiesta ha `X-Requested-With: XMLHttpRequest` |\n| `$.user` | L'utente restituito dal tuo delegate di autorizzazione, oppure `undefined` |\n| `$.language` | La lingua restituita dal tuo delegate di localizzazione, oppure una stringa vuota |\n| `$.protocol`, `$.host`, `$.address` | `http` o `https`, l'header `Host` e l'URL completo |\n| `$.req`, `$.res` | Gli oggetti richiesta e risposta di Node.js |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar model = $.body;\n\tvar page = $.query.page;\n\tvar agent = $.headers['user-agent'];\n\t$.success();\n}\n```\n\nI valori di `$.params`, `$.query` e dei form URL-encoded sono stringhe: converti tu numeri e date, oppure usa un'azione con uno schema (vedi [Azioni](../actions/) e [Schemi JSON](../json-schemas/)). Il body viene letto solo per le richieste `POST`, `PUT`, `PATCH` e `DELETE`. Un body più grande del limite di dimensione della route viene rifiutato con `431`.\n\n## File caricati\n\nI campi di una richiesta `multipart/form-data` sono in `$.body` e i file in `$.files`. Ogni file ha `name` (il campo), `filename`, `type`, `size`, `extension`, `width` e `height` per le immagini, e i metodi per spostare il file con `move()`, leggerlo con `read()`, copiarlo con `copy()` o salvarlo in un file storage con `fs()`. I file caricati sono temporanei: vengono rimossi quando la risposta termina, a meno che tu non li abbia spostati.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ <5MB', upload);\n};\n\nfunction upload($) {\n\tvar file = $.files[0];\n\n\tif (!file || !file.isImage) {\n\t\t$.invalid('@(Upload an image)');\n\t\treturn;\n\t}\n\n\tfile.move(PATH.public('photos/' + UID() + '.' + file.extension), function(err) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success();\n\t});\n}\n```\n\nIl flag `<5MB` alza il limite di dimensione del body per questa route (il predefinito è la chiave di configurazione `$httpmaxsize`, 256 kB). Vedi [Routing](../routing/).\n\n## Inviare una risposta\n\nOgnuno dei metodi seguenti termina la richiesta. Chiamane solo uno per richiesta.\n\n| Metodo | Risposta |\n| --- | --- |\n| `$.json(value)` | JSON |\n| `$.success([value])` | `{ success: true, value: value }` come JSON |\n| `$.invalid(error)` | Un errore come JSON, con stato 400 o lo stato dell'errore |\n| `$.jsonstring(text)` | Una stringa che è già JSON |\n| `$.html(text)`, `$.plain(text)`, `$.xml(text)` | Testo con il content type corretto |\n| `$.view(name, [model])` | Una vista renderizzata |\n| `$.file(path, [download])` | Un file dal disco |\n| `$.stream(type, stream, [download])` | Uno stream leggibile |\n| `$.binary(buffer, type, [download])` | Un `Buffer` |\n| `$.content(value, [type])` | Una stringa o un `Buffer` con il tuo content type |\n| `$.redirect(url, [permanent])` | Un redirect con 302, o 301 |\n| `$.empty()` | Stato 204 senza body |\n| `$.fallback(code, [error])` | Una pagina di errore (o JSON per le richieste XHR) |\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', list);\n\tROUTE('GET /download/', download);\n\tROUTE('GET /old/', function($) {\n\t\t$.redirect('/new/', true);\n\t});\n};\n\nfunction list($) {\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.json(response);\n\t});\n}\n\nfunction download($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n}\n```\n\n`$.json(value, [beautify], [replacer])` serializza `value` con `JSON.stringify()`, imposta `content-type: application/json` e header che disattivano la cache (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). Passa `true` come `beautify` per indentare l'output con tabulazioni, e una funzione `replacer` (o un array di chiavi) per filtrare i valori, esattamente come il secondo argomento di `JSON.stringify()`.\n\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n`$.callback()` senza argomenti restituisce una funzione `(err, value)` che risponde con `$.invalid(err)` o `$.json(value)`, comoda per le callback del database: `NOSQL('products').find().callback($.callback())`. `$.done([value])` fa lo stesso e racchiude il valore in `{ success: true, value: ... }`.\n\n## Errori\n\n`$.invalid()` accetta una stringa, un `Error`, un `ErrorBuilder` o un codice di stato HTTP. La risposta è un array JSON di errori. Il testo scritto come `@(text)` viene tradotto con le risorse della lingua della richiesta.\n\n```js\nfunction update($) {\n\tif (!$.body.name) {\n\t\t$.invalid('Name is required');\n\t\treturn;\n\t}\n\tif (!$.user) {\n\t\t$.invalid(401);\n\t\treturn;\n\t}\n\t$.success($.body.name);\n}\n```\n\n`$.invalidsafe(message, error)` invia `message` come `$.invalid()` e scrive `error` nel log degli errori, così il client non vede i dettagli dell'errore. `$.throw(error)` scrive soltanto un errore nel log; la risposta la invii comunque tu.\n\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n`$.fallback(code)` invia la pagina di errore integrata con lo stato indicato. Quando definisci una route come `ROUTE('#404', fn)`, è quell'azione a gestire la richiesta; lo stato è `200` a meno che l'azione non imposti `$.response.status`. Per le richieste XHR l'errore viene inviato come JSON.\n\n## Stato e header\n\nLa risposta che verrà inviata è in `$.response`. Modifica `$.response.status` e `$.response.headers` prima di chiamare un metodo di risposta:\n\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\nPer la cache HTTP, `$.httpcache(date)` imposta `Last-Modified`, `Expires` e `Cache-Control`, e `$.notmodified(date)` risponde con `304` quando il browser ha già la stessa versione.\n\n## Cookie\n\n`$.cookie(name)` legge un cookie e `$.cookie(name, value, expires, [options])` ne imposta uno. `expires` è una `Date` o una stringa come `'7 days'`. Le opzioni sono `domain`, `path` (predefinito `/`), `secure`, `httponly` e `samesite` (`'Lax'`, `'Strict'`, `'None'`). I valori predefiniti di `secure` e `samesite` provengono dalle chiavi di configurazione `$cookiesecure` e `$cookiesamesite`.\n\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true });\n\t$.success();\n}\n\nfunction profile($) {\n\tvar session = $.cookie('session');\n\t$.json({ session: session });\n}\n```\n\nPer rimuovere un cookie, impostalo con un valore vuoto e una data nel passato.\n\n## Viste\n\n`$.view(name, [model])` renderizza un file della directory `/views/` e lo invia come HTML. `$.layout(name)` sceglie il layout per la vista successiva. Vedi [Viste](../views/).\n\n```js\nfunction homepage($) {\n\t$.layout('layout');\n\t$.view('index', { title: 'Home' });\n}\n```\n\n## Altri helper\n\n- `$.action(name, model)` esegue un'azione con questo controller (vedi [Azioni](../actions/)).\n- `$.authorize([callback])` esegue manualmente il tuo delegate di autorizzazione e riempie `$.user`.\n- `$.proxy(url)` inoltra la richiesta a un altro server e invia la sua risposta.\n- `$.hostname([path])` restituisce `protocol://host` con un percorso facoltativo.\n- `$.href([key], [value])` restituisce la query string della richiesta con un parametro modificato, per i link di paginazione e di ordinamento; `$.href({ page: 1, sort: 'price' })` restituisce l'URL con più parametri modificati.\n- `$.touch([url])` cancella lo stato in cache di un file statico dopo che lo hai modificato (vedi [File statici](../static-files/)).\n- `$.csrf()` crea un token CSRF.\n- `$.custom()` indica al framework che scrivi tu stesso su `$.res`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUzCTx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/controller/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Kontrolér","summary":"Objekt `$` akcie trasy: údaje požiadavky, nahrané súbory, odpovede, chyby, hlavičky a cookies.","markdown":"---\ntitle: \"Kontrolér\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/controller/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Kontrolér\n\n> Objekt `$` akcie trasy: údaje požiadavky, nahrané súbory, odpovede, chyby, hlavičky a cookies.\n\nV Total.js 5 dostane akcia trasy jeden argument, **kontrolér**, podľa konvencie zapisovaný ako `$`. Kontrolér obsahuje všetko o HTTP požiadavke a má metódy, ktoré posielajú odpoveď. 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($) {\n\t$.json({ id: $.params.id, ip: $.ip });\n}\n```\n\nSamotné trasy sú opísané v [Smerovaní](../routing/). Úplný zoznam vlastností a metód je v referencii [Kontrolér](../../reference/controller/).\n\n## Dáta požiadavky\n\n| Vlastnosť | Čo obsahuje |\n| --- | --- |\n| `$.method` | HTTP metóda veľkými písmenami (`GET`, `POST`...) |\n| `$.url` | Cesta URL s lomkou na konci a bez query stringu |\n| `$.split` | Segmenty cesty ako pole (`/a/b/` dá `['a', 'b']`) |\n| `$.params` | Dynamické časti URL (`{id}`) ako reťazce |\n| `$.query` | Query string ako objekt (`?page=2` dá `{ page: '2' }`) |\n| `$.body` | Spracované telo: JSON, URL-encoded formulár alebo polia multipart formulára |\n| `$.files` | Nahrané súbory požiadavky `multipart/form-data` |\n| `$.payload` | Surové telo ako `Buffer` (nie pre multipart požiadavky) |\n| `$.headers` | Hlavičky požiadavky s názvami malými písmenami |\n| `$.ip` | IP adresa klienta (prvá adresa z `X-Forwarded-For` za proxy) |\n| `$.ua` | Krátky názov systému a prehliadača spracovaný z `User-Agent` |\n| `$.mobile`, `$.robot` | `true` pre mobilné zariadenia alebo pre crawlery |\n| `$.xhr` | `true`, keď má požiadavka `X-Requested-With: XMLHttpRequest` |\n| `$.user` | Používateľ vrátený tvojím autorizačným delegátom alebo `undefined` |\n| `$.language` | Jazyk vrátený tvojím lokalizačným delegátom alebo prázdny reťazec |\n| `$.protocol`, `$.host`, `$.address` | `http` alebo `https`, hlavička `Host` a úplná URL |\n| `$.req`, `$.res` | Objekty požiadavky a odpovede z Node.js |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar model = $.body;\n\tvar page = $.query.page;\n\tvar agent = $.headers['user-agent'];\n\t$.success();\n}\n```\n\nHodnoty `$.params`, `$.query` a URL-encoded formulárov sú reťazce: čísla a dátumy si skonvertuj sám alebo použi akciu so schémou (pozri [Akcie](../actions/) a [JSON schémy](../json-schemas/)). Telo sa číta iba pre požiadavky `POST`, `PUT`, `PATCH` a `DELETE`. Telo väčšie ako limit veľkosti trasy sa odmietne s `431`.\n\n## Nahrané súbory\n\nPolia požiadavky `multipart/form-data` sú v `$.body` a súbory v `$.files`. Každý súbor má `name` (pole), `filename`, `type`, `size`, `extension`, `width` a `height` pre obrázky a metódy `move()`, `read()`, `copy()` alebo uloženie súboru do file storage cez `fs()`. Nahrané súbory sú dočasné: odstránia sa, keď odpoveď skončí, pokiaľ si ich nepresunul.\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ <5MB', upload);\n};\n\nfunction upload($) {\n\tvar file = $.files[0];\n\n\tif (!file || !file.isImage) {\n\t\t$.invalid('@(Upload an image)');\n\t\treturn;\n\t}\n\n\tfile.move(PATH.public('photos/' + UID() + '.' + file.extension), function(err) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success();\n\t});\n}\n```\n\nFlag `<5MB` zvýši limit veľkosti tela pre túto trasu (predvolený je konfiguračný kľúč `$httpmaxsize`, 256 kB). Pozri [Smerovanie](../routing/).\n\n## Odoslanie odpovede\n\nKaždá metóda nižšie ukončí požiadavku. Na jednu požiadavku zavolaj iba jednu z nich.\n\n| Metóda | Odpoveď |\n| --- | --- |\n| `$.json(value)` | JSON |\n| `$.success([value])` | `{ success: true, value: value }` ako JSON |\n| `$.invalid(error)` | Chyba ako JSON so stavom 400 alebo so stavom chyby |\n| `$.jsonstring(text)` | Reťazec, ktorý už je JSON |\n| `$.html(text)`, `$.plain(text)`, `$.xml(text)` | Text so správnym typom obsahu |\n| `$.view(name, [model])` | Vykreslený pohľad |\n| `$.file(path, [download])` | Súbor z disku |\n| `$.stream(type, stream, [download])` | Čitateľný stream |\n| `$.binary(buffer, type, [download])` | `Buffer` |\n| `$.content(value, [type])` | Reťazec alebo `Buffer` s tvojím typom obsahu |\n| `$.redirect(url, [permanent])` | Presmerovanie s 302 alebo 301 |\n| `$.empty()` | Stav 204 bez tela |\n| `$.fallback(code, [error])` | Chybová stránka (alebo JSON pre XHR požiadavky) |\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', list);\n\tROUTE('GET /download/', download);\n\tROUTE('GET /old/', function($) {\n\t\t$.redirect('/new/', true);\n\t});\n};\n\nfunction list($) {\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.json(response);\n\t});\n}\n\nfunction download($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n}\n```\n\n`$.json(value, [beautify], [replacer])` serializuje `value` cez `JSON.stringify()`, nastaví `content-type: application/json` a hlavičky, ktoré vypínajú cache (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). Odovzdaj `true` ako `beautify`, aby sa výstup odsadil tabulátormi, a funkciu `replacer` (alebo pole kľúčov) na filtrovanie hodnôt, presne ako druhý argument `JSON.stringify()`.\n\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n`$.callback()` bez argumentov vráti funkciu `(err, value)`, ktorá odpovie cez `$.invalid(err)` alebo `$.json(value)`, čo sa hodí pre callbacky databázy: `NOSQL('products').find().callback($.callback())`. `$.done([value])` robí to isté a obalí hodnotu do `{ success: true, value: ... }`.\n\n## Chyby\n\n`$.invalid()` prijíma reťazec, `Error`, `ErrorBuilder` alebo HTTP stavový kód. Odpoveďou je JSON pole chýb. Text zapísaný ako `@(text)` sa preloží zdrojmi jazyka požiadavky.\n\n```js\nfunction update($) {\n\tif (!$.body.name) {\n\t\t$.invalid('Name is required');\n\t\treturn;\n\t}\n\tif (!$.user) {\n\t\t$.invalid(401);\n\t\treturn;\n\t}\n\t$.success($.body.name);\n}\n```\n\n`$.invalidsafe(message, error)` pošle `message` ako `$.invalid()` a zapíše `error` do chybového logu, takže klient nevidí podrobnosti chyby. `$.throw(error)` iba zapíše chybu do logu; odpoveď musíš poslať aj tak.\n\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n`$.fallback(code)` pošle vstavanú chybovú stránku s daným stavom. Keď definuješ trasu ako `ROUTE('#404', fn)`, požiadavku namiesto toho obslúži táto akcia; stav je `200`, pokiaľ akcia nenastaví `$.response.status`. Pre XHR požiadavky sa chyba pošle ako JSON.\n\n## Stav a hlavičky\n\nOdpoveď, ktorá sa odošle, je v `$.response`. Zmeň `$.response.status` a `$.response.headers` predtým, ako zavoláš metódu odpovede:\n\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\nPre HTTP cache `$.httpcache(date)` nastaví `Last-Modified`, `Expires` a `Cache-Control` a `$.notmodified(date)` odpovie s `304`, keď prehliadač už má rovnakú verziu.\n\n## Cookies\n\n`$.cookie(name)` prečíta cookie a `$.cookie(name, value, expires, [options])` ju nastaví. `expires` je `Date` alebo reťazec ako `'7 days'`. Voľby sú `domain`, `path` (predvolene `/`), `secure`, `httponly` a `samesite` (`'Lax'`, `'Strict'`, `'None'`). Predvolené hodnoty pre `secure` a `samesite` pochádzajú z konfiguračných kľúčov `$cookiesecure` a `$cookiesamesite`.\n\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true });\n\t$.success();\n}\n\nfunction profile($) {\n\tvar session = $.cookie('session');\n\t$.json({ session: session });\n}\n```\n\nAk chceš cookie odstrániť, nastav ju s prázdnou hodnotou a dátumom v minulosti.\n\n## Pohľady\n\n`$.view(name, [model])` vykreslí súbor z adresára `/views/` a pošle ho ako HTML. `$.layout(name)` vyberie layout pre ďalší pohľad. Pozri [Pohľady](../views/).\n\n```js\nfunction homepage($) {\n\t$.layout('layout');\n\t$.view('index', { title: 'Home' });\n}\n```\n\n## Ďalšie pomocné funkcie\n\n- `$.action(name, model)` spustí akciu s týmto kontrolérom (pozri [Akcie](../actions/)).\n- `$.authorize([callback])` ručne spustí tvoj autorizačný delegát a naplní `$.user`.\n- `$.proxy(url)` prepošle požiadavku na iný server a pošle jeho odpoveď.\n- `$.hostname([path])` vráti `protocol://host` s voliteľnou cestou.\n- `$.href([key], [value])` vráti query string požiadavky s jedným zmeneným parametrom, pre odkazy na stránkovanie a triedenie; `$.href({ page: 1, sort: 'price' })` vráti URL s viacerými zmenenými parametrami.\n- `$.touch([url])` vymaže uložený stav statického súboru po tom, ako ho zmeníš (pozri [Statické súbory](../static-files/)).\n- `$.csrf()` vytvorí CSRF token.\n- `$.custom()` povie frameworku, že do `$.res` zapisuješ sám.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUVAMx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/actions/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Actions","summary":"Declare business logic with NEWACTION(), validate its input, expose it as a route and run it from code with ACTION().","markdown":"---\ntitle: Actions\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/actions/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Actions\n\n> Declare business logic with NEWACTION(), validate its input, expose it as a route and run it from code with ACTION().\n\nAn **action** is a named piece of business logic. It declares what it accepts (body, URL params, query string), who may run it and what it returns, and it can be exposed as a route or called from your code. Actions are the main way to write the logic of a Total.js 5 application.\n\n```js\n// actions/products.js\nNEWACTION('products_create', {\n\tname: 'Create a product',\n\tinput: '*name:String, price:Number, description:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = NOW;\n\t\tDATA.insert('products', model).callback($.done(model.id));\n\t}\n});\n```\n\nPut files with actions in the `/actions/` folder (or in a plugin). The framework loads them at start, so `NEWACTION()` runs once and registers the action under its name. Declaring an action with an existing name replaces the old one.\n\n## Declaring an action\n\n`NEWACTION(name, options)` takes the name and an object of options. You can also pass only the object with an `id` (or `name`) property. The `action` function is required and receives the options object `$` and the validated model.\n\n| Option | What it does |\n| --- | --- |\n| `action` | `function($, model)`, the logic |\n| `input` | Schema of the payload (the body); the validated result is `$.model` |\n| `output` | Schema of the response; the value of `$.callback()` is cleaned by it |\n| `params` | Schema of the dynamic URL parameters (`$.params`) |\n| `query` | Schema of the query string (`$.query`) |\n| `user` | `true` requires a signed-in user, `false` requires an anonymous request |\n| `sa` / `su` | Requires a user with the `sa` or `su` flag |\n| `permissions` | Required permissions, `'products_create,admin'` or an array |\n| `route` | A route that runs the action, e.g. `'+POST /api/products/'` |\n| `middleware` | Names of middleware to run before the action, `'auth, ratelimit'` |\n| `partial` | Validates the input partially (only the fields that are sent) |\n| `extend` | Puts the response into the payload under this key and returns the payload |\n| `audit` | `true` or a template; writes an audit record after success |\n| `config` | Any object; available as `$.config` |\n| `timeout` | Milliseconds; the action fails with `Timeout.` when it does not respond in time |\n| `cache` | `true` or `{ query, params, input, user, language, key, expire }`; keeps the response in the cache |\n| `oninput` | `function($)`, called right before `action` |\n| `onoutput` | `function(err, response, $)`, called after the action responds |\n| `summary` | A description of the action; the MCP server uses it as the description of the tool |\n| `mcp` | `true` makes the action a tool of the [MCP server](../../guides/mcp-server/) |\n\nA schema is an inline definition (`'*name:String, email:Email'`, a `*` marks a required field) or the name of a registered JSON schema with `@` (`'@product'`). The syntax and the types are described in [JSON schemas](../../guides/json-schemas/). When validation fails, the action does not run and the caller receives the errors; errors of `query` and `params` are prefixed with `query.` and `params.`.\n\n## The `$` object\n\nThe first argument of `action` is an options object, usually named `$`. It carries the data of the call and the methods that finish it.\n\n```js\nNEWACTION('orders_read', {\n\tparams: '*id:UID',\n\tquery: 'fields:String',\n\tuser: true,\n\taction: function($) {\n\t\tvar id = $.params.id;\n\t\tvar user = $.user;\n\t\tDATA.read('orders').id(id).where('userid', user.id).error(404).callback($);\n\t}\n});\n```\n\n| Property | What it contains |\n| --- | --- |\n| `$.model` | The validated payload (aliases `$.payload` and `$.value`) |\n| `$.input` | Another alias of `$.model` |\n| `$.params` | The validated URL parameters |\n| `$.query` | The validated query string |\n| `$.user` | The user of the request, or the user passed to `ACTION().user()` |\n| `$.config` | The `config` option of the action |\n| `$.id` | The name of the running action |\n| `$.controller` | The controller of the HTTP request, or `undefined` |\n| `$.error` | The `ErrorBuilder` of the call |\n| `$.xhr` | `true` for an XHR request, `null` without a controller |\n| `$.meta` | The definition object of the action |\n| `$.env` | The value passed to `ACTION().env()`, or `undefined` |\n| `$.ip`, `$.headers`, `$.url`, `$.files`, `$.language`, `$.ua` | Shortcuts to the controller, empty without one |\n\nAn action ends with exactly one of these calls:\n\n- `$.success([value])` responds with `{ success: true, value: value }`.\n- `$.callback(value)` responds with the value as it is. You can pass `$` itself as a callback of a database query, for example `DATA.find('products').callback($)`.\n- `$.done([value])` returns a `function(err, response)` callback: an error becomes `$.invalid()`, otherwise it calls `$.success(value)`, or `$.success(response)` when `value` is `true`.\n- `$.invalid(error, [path], [index])` fails the call. A number above 399 is an HTTP status (`$.invalid(404)`); a string is an error message.\n\n`$.redirect(url)` redirects the HTTP request instead of responding. `$.output('html')` changes how a route responds (the default is JSON).\n\n`$.invalidsafe(message, error)` ends the action like `$.invalid(message)`, but it also writes `error` to the error log. The caller gets only the message, so the details of the error (paths, SQL, addresses) stay on the server. `$.throw(error)` only writes an error to the log and does not end the action. In an `async` action an exception that you do not catch ends the call with `500: Internal Server Error` and goes to the error log.\n\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n`$.touch([url])` clears the cached state of a static file after you change it (see [Static files](../../guides/static-files/)), the same as `TOUCH()`.\n\n## Routes\n\nThe `route` option creates a route for the action. The route string is the same as in [Routing](../../guides/routing/): a `+` before the method requires a signed-in user, a `-` an anonymous one.\n\n```js\nNEWACTION('products_list', {\n\tquery: 'search:String, page:Number',\n\troute: 'GET /api/products/',\n\taction: function($) {\n\t\tvar builder = DATA.list('products');\n\t\t$.query.search && builder.search('name', $.query.search);\n\t\tbuilder.paginate($.query.page, 20);\n\t\tbuilder.callback($);\n\t}\n});\n```\n\nA route can also call actions declared elsewhere with `-->`. The actions run one after another with the same `$`, and the route returns the response of the action marked `(response)`, or an object with the responses of all actions by name when none is marked.\n\n```js\nexports.install = function() {\n\tROUTE('+POST /api/orders/ --> orders_create orders_notify (response) orders_stats');\n\tROUTE('+API ?  +orders_create --> orders_create');\n};\n```\n\nA `+` before an action name says that it uses the payload, a `-` that it does not; without a prefix the `input` option decides. `API` routes join many actions under one endpoint (`?` is the `$api` endpoint, `/api/` by default); see [Routing](../../guides/routing/).\n\n`route: true` is a shortcut for an `API ?` endpoint named after the action. It becomes `+API ?` when the action has the `user` or `permissions` option.\n\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\troute: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n```\n\n## Running actions from code\n\n`ACTION(name, [payload], [controller])` (alias `EXEC`) runs one action, or several separated by spaces or commas. It returns a caller; the call starts on the next tick, so you chain its settings first.\n\n```js\nACTION('products_create', { name: 'Keyboard', price: 49 }).user(user).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.toString());\n\telse\n\t\tconsole.log(response);\n});\n```\n\n| Method | What it does |\n| --- | --- |\n| `.callback(fn)` | `function(err, response)`, or an existing `$` that receives the result |\n| `.promise([$])` | Returns a Promise; with `$`, an error goes to `$.invalid()` |\n| `.user(user)` | Sets `$.user` (it also accepts a `$` and takes its user) |\n| `.query(obj)` / `.params(obj)` | Sets the query string and the URL parameters |\n| `.ctrl(controller)` | Runs the action with a controller |\n| `.autorespond()` | Sends the response (or the error) to the controller |\n| `.status(fn)` | Receives the values the action sends with `$.status()` |\n| `.progress(fn)` | Receives the values the action sends with `$.progress()` |\n| `.config(obj)` | Adds keys to `$.config` for this call only |\n| `.env(value)` | Sets `$.env`, a value that tells the action where it is called from |\n\nInside an action, `$.action(name, [payload])` runs another action with the same controller (or the same user, query and params when there is none). In a route handler, `$.action(name, [model])` (where `$` is the controller) does the same with the controller.\n\n```js\nNEWACTION('orders_checkout', {\n\tinput: '*productid:UID, *count:Number',\n\tuser: true,\n\taction: async function($, model) {\n\t\tvar order = await $.action('orders_create', model).promise($);\n\t\tvar payment = await $.action('payments_create', { orderid: order.value }).promise($);\n\t\t$.success(payment);\n\t}\n});\n```\n\nAfter every successful action, the framework emits the event `@<name>` with `($, response)`:\n\n```js\nON('@products_create', function($, response) {\n\tconsole.log($.user.name, 'created', response.value);\n});\n```\n\nThe hooks `oninput($)` and `onoutput(err, response, $)` run before the action and after its successful response, so you can prepare data or log results without touching the logic:\n\n```js\nNEWACTION('notes_save', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.input.body = $.input.body.trim();\n\t},\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, 'done', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(model.body.length);\n\t}\n});\n```\n\n## Caching the response\n\nThe `cache` option keeps the first successful response in the cache. The next calls get a copy of it at once, without running the middleware and the action. List the values that change the response, so each combination gets its own entry: `query`, `params` and `input` take `true` (all fields of the schema) or a list of fields, `user: true` keeps one entry per user and `language: true` one per language. Entries expire after `expire` (5 minutes by default).\n\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').page($.query.page, 20).callback($);\n\t}\n});\n\nNEWACTION('Products|save', {\n\tinput: '*id:UID,*name:String',\n\taction: function($, model) {\n\t\tDATA.update('products', model).id(model.id).callback(function() {\n\t\t\tCACHE.reset('action|products|'); // the next list is read again\n\t\t\t$.success();\n\t\t});\n\t}\n});\n```\n\nErrors are not cached. Without `user`, every user gets the same cached response, so do not cache answers that depend on the user without it.\n\n## Schemas\n\n`NEWSCHEMA(name, callback)` groups actions under a common prefix. The callback receives an object whose `action(name, options)` creates the action `<schema>/<name>`.\n\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.action('list', {\n\t\troute: 'GET /api/products/',\n\t\taction: function($) {\n\t\t\tDATA.find('products').callback($);\n\t\t}\n\t});\n});\n\n// The action name is 'Products/list'\n```\n\n## Transformations\n\nA transformation is a named chain of functions that change a value. `NEWTRANSFORM(name, fn, [id])` adds one function to the chain; `TRANSFORM(name, value, [callback])` runs the chain. Every function receives `$` and the value, changes `$.value` and calls `$.next()`.\n\n```js\nNEWTRANSFORM('product', function($, value) {\n\tvalue.name = value.name.trim();\n\t$.next();\n}, 'name');\n\nNEWTRANSFORM('product', function($, value) {\n\t$.value = { id: value.id, name: value.name, price: value.price };\n\t$.next();\n});\n\nTRANSFORM('product', { id: 1, name: ' Mouse ', price: 9, stock: 3 }, function(err, response) {\n\tconsole.log(response); // { id: 1, name: 'Mouse', price: 9 }\n});\n```\n\nA function can also stop the chain with `$.invalid(error)`; the callback then receives the errors. When you pass an action's `$` as the third argument of the Promise form, the errors go to `$.invalid()` of that action:\n\n```js\nNEWACTION('products_read', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await DATA.read('products').id($.params.id).promise($);\n\t\t$.callback(await TRANSFORM('product', item, $));\n\t}\n});\n```\n\nWithout a callback, `TRANSFORM()` returns a Promise, which rejects with the errors of `$.invalid()` when you do not pass a `$`. In an action, `$.transform(name, value, [callback])` runs it with the controller of the action (and the user of that controller). Put transformations in the `/transforms/` folder.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUVAMx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/actions/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Aktionen","summary":"Geschäftslogik mit NEWACTION() deklarieren, ihre Eingabe validieren, sie als Route bereitstellen und mit ACTION() aus Code ausführen.","markdown":"---\ntitle: Aktionen\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/actions/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Aktionen\n\n> Geschäftslogik mit NEWACTION() deklarieren, ihre Eingabe validieren, sie als Route bereitstellen und mit ACTION() aus Code ausführen.\n\nEine **Aktion** ist ein benanntes Stück Geschäftslogik. Sie deklariert, was sie akzeptiert (Body, URL-Parameter, Query String), wer sie ausführen darf und was sie zurückgibt, und sie kann als Route bereitgestellt oder aus deinem Code aufgerufen werden. Aktionen sind der wichtigste Weg, die Logik einer Total.js-5-Anwendung zu schreiben.\n\n```js\n// actions/products.js\nNEWACTION('products_create', {\n\tname: 'Create a product',\n\tinput: '*name:String, price:Number, description:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = NOW;\n\t\tDATA.insert('products', model).callback($.done(model.id));\n\t}\n});\n```\n\nLege Dateien mit Aktionen in den Ordner `/actions/` (oder in ein Plugin). Das Framework lädt sie beim Start, daher läuft `NEWACTION()` einmal und registriert die Aktion unter ihrem Namen. Wird eine Aktion mit einem bestehenden Namen deklariert, ersetzt sie die alte.\n\n## Eine Aktion deklarieren\n\n`NEWACTION(name, options)` nimmt den Namen und ein Objekt mit Optionen. Du kannst auch nur das Objekt mit einer Eigenschaft `id` (oder `name`) übergeben. Die Funktion `action` ist erforderlich und erhält das Optionsobjekt `$` und das validierte Modell.\n\n| Option | Was sie bewirkt |\n| --- | --- |\n| `action` | `function($, model)`, die Logik |\n| `input` | Schema des Payloads (des Bodys); das validierte Ergebnis ist `$.model` |\n| `output` | Schema der Antwort; der Wert von `$.callback()` wird damit bereinigt |\n| `params` | Schema der dynamischen URL-Parameter (`$.params`) |\n| `query` | Schema des Query Strings (`$.query`) |\n| `user` | `true` erfordert einen angemeldeten Benutzer, `false` eine anonyme Anfrage |\n| `sa` / `su` | Erfordert einen Benutzer mit dem Flag `sa` oder `su` |\n| `permissions` | Erforderliche Berechtigungen, `'products_create,admin'` oder ein Array |\n| `route` | Eine Route, die die Aktion ausführt, z. B. `'+POST /api/products/'` |\n| `middleware` | Namen der Middleware, die vor der Aktion läuft, `'auth, ratelimit'` |\n| `partial` | Validiert die Eingabe teilweise (nur die gesendeten Felder) |\n| `extend` | Legt die Antwort unter diesem Schlüssel in den Payload und gibt den Payload zurück |\n| `audit` | `true` oder ein Template; schreibt nach Erfolg einen Audit-Eintrag |\n| `config` | Ein beliebiges Objekt; verfügbar als `$.config` |\n| `timeout` | Millisekunden; die Aktion schlägt mit `Timeout.` fehl, wenn sie nicht rechtzeitig antwortet |\n| `cache` | `true` oder `{ query, params, input, user, language, key, expire }`; behält die Antwort im Cache |\n| `oninput` | `function($)`, wird direkt vor `action` aufgerufen |\n| `onoutput` | `function(err, response, $)`, wird aufgerufen, nachdem die Aktion geantwortet hat |\n| `summary` | Eine Beschreibung der Aktion; der MCP-Server verwendet sie als Beschreibung des Tools |\n| `mcp` | `true` macht die Aktion zu einem Tool des [MCP-Servers](../../guides/mcp-server/) |\n\nEin Schema ist eine eingebettete Definition (`'*name:String, email:Email'`, ein `*` markiert ein Pflichtfeld) oder der Name eines registrierten JSON-Schemas mit `@` (`'@product'`). Die Syntax und die Typen sind in [JSON-Schemas](../../guides/json-schemas/) beschrieben. Schlägt die Validierung fehl, läuft die Aktion nicht und der Aufrufer erhält die Fehler; Fehlern von `query` und `params` wird `query.` bzw. `params.` vorangestellt.\n\n## Das Objekt `$`\n\nDas erste Argument von `action` ist ein Optionsobjekt, meist `$` genannt. Es trägt die Daten des Aufrufs und die Methoden, die ihn beenden.\n\n```js\nNEWACTION('orders_read', {\n\tparams: '*id:UID',\n\tquery: 'fields:String',\n\tuser: true,\n\taction: function($) {\n\t\tvar id = $.params.id;\n\t\tvar user = $.user;\n\t\tDATA.read('orders').id(id).where('userid', user.id).error(404).callback($);\n\t}\n});\n```\n\n| Eigenschaft | Was sie enthält |\n| --- | --- |\n| `$.model` | Der validierte Payload (Aliase `$.payload` und `$.value`) |\n| `$.input` | Ein weiterer Alias von `$.model` |\n| `$.params` | Die validierten URL-Parameter |\n| `$.query` | Der validierte Query String |\n| `$.user` | Der Benutzer der Anfrage oder der an `ACTION().user()` übergebene Benutzer |\n| `$.config` | Die Option `config` der Aktion |\n| `$.id` | Der Name der laufenden Aktion |\n| `$.controller` | Der Controller der HTTP-Anfrage oder `undefined` |\n| `$.error` | Der `ErrorBuilder` des Aufrufs |\n| `$.xhr` | `true` bei einer XHR-Anfrage, `null` ohne Controller |\n| `$.meta` | Das Definitionsobjekt der Aktion |\n| `$.env` | Der an `ACTION().env()` übergebene Wert oder `undefined` |\n| `$.ip`, `$.headers`, `$.url`, `$.files`, `$.language`, `$.ua` | Abkürzungen zum Controller, leer ohne Controller |\n\nEine Aktion endet mit genau einem dieser Aufrufe:\n\n- `$.success([value])` antwortet mit `{ success: true, value: value }`.\n- `$.callback(value)` antwortet mit dem Wert, wie er ist. Du kannst `$` selbst als Callback einer Datenbankabfrage übergeben, zum Beispiel `DATA.find('products').callback($)`.\n- `$.done([value])` gibt einen Callback `function(err, response)` zurück: Ein Fehler wird zu `$.invalid()`, andernfalls ruft er `$.success(value)` auf, oder `$.success(response)`, wenn `value` `true` ist.\n- `$.invalid(error, [path], [index])` lässt den Aufruf fehlschlagen. Eine Zahl über 399 ist ein HTTP-Status (`$.invalid(404)`); ein String ist eine Fehlermeldung.\n\n`$.redirect(url)` leitet die HTTP-Anfrage um, statt zu antworten. `$.output('html')` ändert, wie eine Route antwortet (Standard ist JSON).\n\n`$.invalidsafe(message, error)` beendet die Aktion wie `$.invalid(message)`, schreibt aber zusätzlich `error` ins Fehlerlog. Der Aufrufer erhält nur die Meldung, sodass die Details des Fehlers (Pfade, SQL, Adressen) auf dem Server bleiben. `$.throw(error)` schreibt nur einen Fehler ins Log und beendet die Aktion nicht. In einer `async`-Aktion beendet eine Exception, die du nicht abfängst, den Aufruf mit `500: Internal Server Error` und landet im Fehlerlog.\n\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n`$.touch([url])` löscht den gecachten Zustand einer statischen Datei, nachdem du sie geändert hast (siehe [Statische Dateien](../../guides/static-files/)), genau wie `TOUCH()`.\n\n## Routen\n\nDie Option `route` erstellt eine Route für die Aktion. Der Routen-String ist derselbe wie in [Routing](../../guides/routing/): Ein `+` vor der Methode erfordert einen angemeldeten Benutzer, ein `-` einen anonymen.\n\n```js\nNEWACTION('products_list', {\n\tquery: 'search:String, page:Number',\n\troute: 'GET /api/products/',\n\taction: function($) {\n\t\tvar builder = DATA.list('products');\n\t\t$.query.search && builder.search('name', $.query.search);\n\t\tbuilder.paginate($.query.page, 20);\n\t\tbuilder.callback($);\n\t}\n});\n```\n\nEine Route kann mit `-->` auch Aktionen aufrufen, die anderswo deklariert sind. Die Aktionen laufen nacheinander mit demselben `$`, und die Route gibt die Antwort der mit `(response)` markierten Aktion zurück oder, wenn keine markiert ist, ein Objekt mit den Antworten aller Aktionen nach Name.\n\n```js\nexports.install = function() {\n\tROUTE('+POST /api/orders/ --> orders_create orders_notify (response) orders_stats');\n\tROUTE('+API ?  +orders_create --> orders_create');\n};\n```\n\nEin `+` vor einem Aktionsnamen bedeutet, dass sie den Payload verwendet, ein `-`, dass sie es nicht tut; ohne Präfix entscheidet die Option `input`. `API`-Routen fassen viele Aktionen unter einem Endpunkt zusammen (`?` ist der Endpunkt `$api`, standardmäßig `/api/`); siehe [Routing](../../guides/routing/).\n\n`route: true` ist eine Abkürzung für einen nach der Aktion benannten `API ?`-Endpunkt. Er wird zu `+API ?`, wenn die Aktion die Option `user` oder `permissions` hat.\n\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\troute: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n```\n\n## Aktionen aus dem Code ausführen\n\n`ACTION(name, [payload], [controller])` (Alias `EXEC`) führt eine Aktion aus oder mehrere, durch Leerzeichen oder Kommas getrennt. Es gibt einen Aufrufer zurück; der Aufruf startet im nächsten Tick, daher verkettest du zuerst seine Einstellungen.\n\n```js\nACTION('products_create', { name: 'Keyboard', price: 49 }).user(user).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.toString());\n\telse\n\t\tconsole.log(response);\n});\n```\n\n| Methode | Was sie bewirkt |\n| --- | --- |\n| `.callback(fn)` | `function(err, response)` oder ein bestehendes `$`, das das Ergebnis erhält |\n| `.promise([$])` | Gibt ein Promise zurück; mit `$` geht ein Fehler an `$.invalid()` |\n| `.user(user)` | Setzt `$.user` (akzeptiert auch ein `$` und übernimmt dessen Benutzer) |\n| `.query(obj)` / `.params(obj)` | Setzt den Query String und die URL-Parameter |\n| `.ctrl(controller)` | Führt die Aktion mit einem Controller aus |\n| `.autorespond()` | Sendet die Antwort (oder den Fehler) an den Controller |\n| `.status(fn)` | Erhält die Werte, die die Aktion mit `$.status()` sendet |\n| `.progress(fn)` | Erhält die Werte, die die Aktion mit `$.progress()` sendet |\n| `.config(obj)` | Fügt `$.config` nur für diesen Aufruf Schlüssel hinzu |\n| `.env(value)` | Setzt `$.env`, einen Wert, der der Aktion sagt, von wo sie aufgerufen wird |\n\nInnerhalb einer Aktion führt `$.action(name, [payload])` eine andere Aktion mit demselben Controller aus (oder mit demselben Benutzer, Query und Params, wenn es keinen gibt). In einem Routen-Handler macht `$.action(name, [model])` (wobei `$` der Controller ist) dasselbe mit dem Controller.\n\n```js\nNEWACTION('orders_checkout', {\n\tinput: '*productid:UID, *count:Number',\n\tuser: true,\n\taction: async function($, model) {\n\t\tvar order = await $.action('orders_create', model).promise($);\n\t\tvar payment = await $.action('payments_create', { orderid: order.value }).promise($);\n\t\t$.success(payment);\n\t}\n});\n```\n\nNach jeder erfolgreichen Aktion sendet das Framework das Event `@<name>` mit `($, response)`:\n\n```js\nON('@products_create', function($, response) {\n\tconsole.log($.user.name, 'created', response.value);\n});\n```\n\nDie Hooks `oninput($)` und `onoutput(err, response, $)` laufen vor der Aktion und nach ihrer erfolgreichen Antwort, sodass du Daten vorbereiten oder Ergebnisse loggen kannst, ohne die Logik anzufassen:\n\n```js\nNEWACTION('notes_save', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.input.body = $.input.body.trim();\n\t},\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, 'done', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(model.body.length);\n\t}\n});\n```\n\n## Die Antwort cachen\n\nDie Option `cache` behält die erste erfolgreiche Antwort im Cache. Die nächsten Aufrufe erhalten sofort eine Kopie davon, ohne dass die Middleware und die Aktion laufen. Gib die Werte an, die die Antwort verändern, damit jede Kombination ihren eigenen Eintrag bekommt: `query`, `params` und `input` nehmen `true` (alle Felder des Schemas) oder eine Liste von Feldern, `user: true` behält einen Eintrag pro Benutzer und `language: true` einen pro Sprache. Einträge laufen nach `expire` ab (standardmäßig nach 5 Minuten).\n\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').page($.query.page, 20).callback($);\n\t}\n});\n\nNEWACTION('Products|save', {\n\tinput: '*id:UID,*name:String',\n\taction: function($, model) {\n\t\tDATA.update('products', model).id(model.id).callback(function() {\n\t\t\tCACHE.reset('action|products|'); // the next list is read again\n\t\t\t$.success();\n\t\t});\n\t}\n});\n```\n\nFehler werden nicht gecacht. Ohne `user` bekommt jeder Benutzer dieselbe gecachte Antwort, also cache Antworten, die vom Benutzer abhängen, nicht ohne diese Option.\n\n## Schemas\n\n`NEWSCHEMA(name, callback)` gruppiert Aktionen unter einem gemeinsamen Präfix. Der Callback erhält ein Objekt, dessen `action(name, options)` die Aktion `<schema>/<name>` erstellt.\n\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.action('list', {\n\t\troute: 'GET /api/products/',\n\t\taction: function($) {\n\t\t\tDATA.find('products').callback($);\n\t\t}\n\t});\n});\n\n// The action name is 'Products/list'\n```\n\n## Transformationen\n\nEine Transformation ist eine benannte Kette von Funktionen, die einen Wert ändern. `NEWTRANSFORM(name, fn, [id])` fügt der Kette eine Funktion hinzu; `TRANSFORM(name, value, [callback])` führt die Kette aus. Jede Funktion erhält `$` und den Wert, ändert `$.value` und ruft `$.next()` auf.\n\n```js\nNEWTRANSFORM('product', function($, value) {\n\tvalue.name = value.name.trim();\n\t$.next();\n}, 'name');\n\nNEWTRANSFORM('product', function($, value) {\n\t$.value = { id: value.id, name: value.name, price: value.price };\n\t$.next();\n});\n\nTRANSFORM('product', { id: 1, name: ' Mouse ', price: 9, stock: 3 }, function(err, response) {\n\tconsole.log(response); // { id: 1, name: 'Mouse', price: 9 }\n});\n```\n\nEine Funktion kann die Kette auch mit `$.invalid(error)` stoppen; der Callback erhält dann die Fehler. Wenn du in der Promise-Form das `$` einer Aktion als drittes Argument übergibst, gehen die Fehler an `$.invalid()` dieser Aktion:\n\n```js\nNEWACTION('products_read', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await DATA.read('products').id($.params.id).promise($);\n\t\t$.callback(await TRANSFORM('product', item, $));\n\t}\n});\n```\n\nOhne Callback gibt `TRANSFORM()` ein Promise zurück, das mit den Fehlern von `$.invalid()` abgelehnt wird, wenn du kein `$` übergibst. In einer Aktion führt `$.transform(name, value, [callback])` sie mit dem Controller der Aktion (und dem Benutzer dieses Controllers) aus. Lege Transformationen in den Ordner `/transforms/`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUVAMx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/actions/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Acciones","summary":"Declara la lógica de negocio con NEWACTION(), valida su entrada, exponla como ruta y ejecútala desde código con ACTION().","markdown":"---\ntitle: Acciones\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/actions/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Acciones\n\n> Declara la lógica de negocio con NEWACTION(), valida su entrada, exponla como ruta y ejecútala desde código con ACTION().\n\nUna **acción** es una pieza de lógica de negocio con nombre. Declara lo que acepta (cuerpo, parámetros de la URL, query string), quién puede ejecutarla y qué devuelve, y puede exponerse como una ruta o llamarse desde tu código. Las acciones son la forma principal de escribir la lógica de una aplicación Total.js 5.\n\n```js\n// actions/products.js\nNEWACTION('products_create', {\n\tname: 'Create a product',\n\tinput: '*name:String, price:Number, description:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = NOW;\n\t\tDATA.insert('products', model).callback($.done(model.id));\n\t}\n});\n```\n\nPon los archivos con acciones en la carpeta `/actions/` (o en un plugin). El framework los carga al arrancar, así que `NEWACTION()` se ejecuta una vez y registra la acción bajo su nombre. Declarar una acción con un nombre existente reemplaza la anterior.\n\n## Declarar una acción\n\n`NEWACTION(name, options)` recibe el nombre y un objeto de opciones. También puedes pasar solo el objeto con una propiedad `id` (o `name`). La función `action` es obligatoria y recibe el objeto de opciones `$` y el modelo validado.\n\n| Opción | Qué hace |\n| --- | --- |\n| `action` | `function($, model)`, la lógica |\n| `input` | Esquema de la carga útil (el cuerpo); el resultado validado es `$.model` |\n| `output` | Esquema de la respuesta; el valor de `$.callback()` se limpia con él |\n| `params` | Esquema de los parámetros dinámicos de la URL (`$.params`) |\n| `query` | Esquema del query string (`$.query`) |\n| `user` | `true` exige un usuario con sesión iniciada, `false` exige una petición anónima |\n| `sa` / `su` | Exige un usuario con el flag `sa` o `su` |\n| `permissions` | Permisos requeridos, `'products_create,admin'` o un array |\n| `route` | Una ruta que ejecuta la acción, p. ej. `'+POST /api/products/'` |\n| `middleware` | Nombres de middleware que se ejecutan antes de la acción, `'auth, ratelimit'` |\n| `partial` | Valida la entrada parcialmente (solo los campos que se envían) |\n| `extend` | Pone la respuesta en la carga útil bajo esta clave y devuelve la carga útil |\n| `audit` | `true` o una plantilla; escribe un registro de auditoría tras el éxito |\n| `config` | Cualquier objeto; disponible como `$.config` |\n| `timeout` | Milisegundos; la acción falla con `Timeout.` cuando no responde a tiempo |\n| `cache` | `true` o `{ query, params, input, user, language, key, expire }`; guarda la respuesta en la caché |\n| `oninput` | `function($)`, se llama justo antes de `action` |\n| `onoutput` | `function(err, response, $)`, se llama después de que la acción responde |\n| `summary` | Una descripción de la acción; el servidor MCP la usa como descripción de la herramienta |\n| `mcp` | `true` convierte la acción en una herramienta del [servidor MCP](../../guides/mcp-server/) |\n\nUn esquema es una definición en línea (`'*name:String, email:Email'`, un `*` marca un campo obligatorio) o el nombre de un esquema JSON registrado con `@` (`'@product'`). La sintaxis y los tipos se describen en [Esquemas JSON](../../guides/json-schemas/). Cuando la validación falla, la acción no se ejecuta y quien llama recibe los errores; los errores de `query` y `params` llevan el prefijo `query.` y `params.`.\n\n## El objeto `$`\n\nEl primer argumento de `action` es un objeto de opciones, normalmente llamado `$`. Lleva los datos de la llamada y los métodos que la terminan.\n\n```js\nNEWACTION('orders_read', {\n\tparams: '*id:UID',\n\tquery: 'fields:String',\n\tuser: true,\n\taction: function($) {\n\t\tvar id = $.params.id;\n\t\tvar user = $.user;\n\t\tDATA.read('orders').id(id).where('userid', user.id).error(404).callback($);\n\t}\n});\n```\n\n| Propiedad | Qué contiene |\n| --- | --- |\n| `$.model` | La carga útil validada (alias `$.payload` y `$.value`) |\n| `$.input` | Otro alias de `$.model` |\n| `$.params` | Los parámetros de la URL validados |\n| `$.query` | El query string validado |\n| `$.user` | El usuario de la petición, o el usuario pasado a `ACTION().user()` |\n| `$.config` | La opción `config` de la acción |\n| `$.id` | El nombre de la acción en ejecución |\n| `$.controller` | El controlador de la petición HTTP, o `undefined` |\n| `$.error` | El `ErrorBuilder` de la llamada |\n| `$.xhr` | `true` para una petición XHR, `null` sin controlador |\n| `$.meta` | El objeto de definición de la acción |\n| `$.env` | El valor pasado a `ACTION().env()`, o `undefined` |\n| `$.ip`, `$.headers`, `$.url`, `$.files`, `$.language`, `$.ua` | Atajos al controlador, vacíos si no lo hay |\n\nUna acción termina exactamente con una de estas llamadas:\n\n- `$.success([value])` responde con `{ success: true, value: value }`.\n- `$.callback(value)` responde con el valor tal cual. Puedes pasar el propio `$` como callback de una consulta a la base de datos, por ejemplo `DATA.find('products').callback($)`.\n- `$.done([value])` devuelve un callback `function(err, response)`: un error se convierte en `$.invalid()`; si no, llama a `$.success(value)`, o a `$.success(response)` cuando `value` es `true`.\n- `$.invalid(error, [path], [index])` hace fallar la llamada. Un número mayor que 399 es un código de estado HTTP (`$.invalid(404)`); un string es un mensaje de error.\n\n`$.redirect(url)` redirige la petición HTTP en lugar de responder. `$.output('html')` cambia cómo responde una ruta (por defecto es JSON).\n\n`$.invalidsafe(message, error)` termina la acción como `$.invalid(message)`, pero además escribe `error` en el log de errores. Quien llama solo recibe el mensaje, así los detalles del error (rutas, SQL, direcciones) se quedan en el servidor. `$.throw(error)` solo escribe un error en el log y no termina la acción. En una acción `async`, una excepción que no capturas termina la llamada con `500: Internal Server Error` y va al log de errores.\n\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n`$.touch([url])` borra el estado en caché de un archivo estático después de cambiarlo (consulta [Archivos estáticos](../../guides/static-files/)), igual que `TOUCH()`.\n\n## Rutas\n\nLa opción `route` crea una ruta para la acción. El string de la ruta es el mismo que en [Enrutamiento](../../guides/routing/): un `+` antes del método exige un usuario con sesión iniciada, un `-` uno anónimo.\n\n```js\nNEWACTION('products_list', {\n\tquery: 'search:String, page:Number',\n\troute: 'GET /api/products/',\n\taction: function($) {\n\t\tvar builder = DATA.list('products');\n\t\t$.query.search && builder.search('name', $.query.search);\n\t\tbuilder.paginate($.query.page, 20);\n\t\tbuilder.callback($);\n\t}\n});\n```\n\nUna ruta también puede llamar a acciones declaradas en otro lugar con `-->`. Las acciones se ejecutan una tras otra con el mismo `$`, y la ruta devuelve la respuesta de la acción marcada con `(response)`, o un objeto con las respuestas de todas las acciones por nombre cuando no hay ninguna marcada.\n\n```js\nexports.install = function() {\n\tROUTE('+POST /api/orders/ --> orders_create orders_notify (response) orders_stats');\n\tROUTE('+API ?  +orders_create --> orders_create');\n};\n```\n\nUn `+` antes del nombre de una acción indica que usa la carga útil, un `-` que no; sin prefijo decide la opción `input`. Las rutas `API` agrupan muchas acciones bajo un endpoint (`?` es el endpoint `$api`, `/api/` por defecto); consulta [Enrutamiento](../../guides/routing/).\n\n`route: true` es un atajo para un endpoint `API ?` con el nombre de la acción. Pasa a ser `+API ?` cuando la acción tiene la opción `user` o `permissions`.\n\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\troute: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n```\n\n## Ejecutar acciones desde el código\n\n`ACTION(name, [payload], [controller])` (alias `EXEC`) ejecuta una acción, o varias separadas por espacios o comas. Devuelve un llamador; la llamada empieza en el siguiente tick, así que primero encadenas sus ajustes.\n\n```js\nACTION('products_create', { name: 'Keyboard', price: 49 }).user(user).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.toString());\n\telse\n\t\tconsole.log(response);\n});\n```\n\n| Método | Qué hace |\n| --- | --- |\n| `.callback(fn)` | `function(err, response)`, o un `$` existente que recibe el resultado |\n| `.promise([$])` | Devuelve una Promise; con `$`, un error va a `$.invalid()` |\n| `.user(user)` | Establece `$.user` (también acepta un `$` y toma su usuario) |\n| `.query(obj)` / `.params(obj)` | Establece el query string y los parámetros de la URL |\n| `.ctrl(controller)` | Ejecuta la acción con un controlador |\n| `.autorespond()` | Envía la respuesta (o el error) al controlador |\n| `.status(fn)` | Recibe los valores que la acción envía con `$.status()` |\n| `.progress(fn)` | Recibe los valores que la acción envía con `$.progress()` |\n| `.config(obj)` | Añade claves a `$.config` solo para esta llamada |\n| `.env(value)` | Establece `$.env`, un valor que indica a la acción desde dónde se la llama |\n\nDentro de una acción, `$.action(name, [payload])` ejecuta otra acción con el mismo controlador (o con el mismo usuario, query y params cuando no lo hay). En un handler de ruta, `$.action(name, [model])` (donde `$` es el controlador) hace lo mismo con el controlador.\n\n```js\nNEWACTION('orders_checkout', {\n\tinput: '*productid:UID, *count:Number',\n\tuser: true,\n\taction: async function($, model) {\n\t\tvar order = await $.action('orders_create', model).promise($);\n\t\tvar payment = await $.action('payments_create', { orderid: order.value }).promise($);\n\t\t$.success(payment);\n\t}\n});\n```\n\nDespués de cada acción correcta, el framework emite el evento `@<name>` con `($, response)`:\n\n```js\nON('@products_create', function($, response) {\n\tconsole.log($.user.name, 'created', response.value);\n});\n```\n\nLos hooks `oninput($)` y `onoutput(err, response, $)` se ejecutan antes de la acción y después de su respuesta correcta, así que puedes preparar datos o registrar resultados sin tocar la lógica:\n\n```js\nNEWACTION('notes_save', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.input.body = $.input.body.trim();\n\t},\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, 'done', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(model.body.length);\n\t}\n});\n```\n\n## Guardar la respuesta en caché\n\nLa opción `cache` guarda en la caché la primera respuesta correcta. Las siguientes llamadas reciben al instante una copia de ella, sin ejecutar el middleware ni la acción. Indica los valores que cambian la respuesta, para que cada combinación tenga su propia entrada: `query`, `params` e `input` aceptan `true` (todos los campos del esquema) o una lista de campos, `user: true` guarda una entrada por usuario y `language: true` una por idioma. Las entradas caducan tras `expire` (5 minutos por defecto).\n\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').page($.query.page, 20).callback($);\n\t}\n});\n\nNEWACTION('Products|save', {\n\tinput: '*id:UID,*name:String',\n\taction: function($, model) {\n\t\tDATA.update('products', model).id(model.id).callback(function() {\n\t\t\tCACHE.reset('action|products|'); // the next list is read again\n\t\t\t$.success();\n\t\t});\n\t}\n});\n```\n\nLos errores no se guardan en caché. Sin `user`, todos los usuarios reciben la misma respuesta de la caché, así que no guardes sin él respuestas que dependen del usuario.\n\n## Esquemas\n\n`NEWSCHEMA(name, callback)` agrupa acciones bajo un prefijo común. El callback recibe un objeto cuyo `action(name, options)` crea la acción `<schema>/<name>`.\n\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.action('list', {\n\t\troute: 'GET /api/products/',\n\t\taction: function($) {\n\t\t\tDATA.find('products').callback($);\n\t\t}\n\t});\n});\n\n// The action name is 'Products/list'\n```\n\n## Transformaciones\n\nUna transformación es una cadena de funciones con nombre que modifican un valor. `NEWTRANSFORM(name, fn, [id])` añade una función a la cadena; `TRANSFORM(name, value, [callback])` ejecuta la cadena. Cada función recibe `$` y el valor, modifica `$.value` y llama a `$.next()`.\n\n```js\nNEWTRANSFORM('product', function($, value) {\n\tvalue.name = value.name.trim();\n\t$.next();\n}, 'name');\n\nNEWTRANSFORM('product', function($, value) {\n\t$.value = { id: value.id, name: value.name, price: value.price };\n\t$.next();\n});\n\nTRANSFORM('product', { id: 1, name: ' Mouse ', price: 9, stock: 3 }, function(err, response) {\n\tconsole.log(response); // { id: 1, name: 'Mouse', price: 9 }\n});\n```\n\nUna función también puede detener la cadena con `$.invalid(error)`; el callback recibe entonces los errores. Cuando pasas el `$` de una acción como tercer argumento de la forma con Promise, los errores van a `$.invalid()` de esa acción:\n\n```js\nNEWACTION('products_read', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await DATA.read('products').id($.params.id).promise($);\n\t\t$.callback(await TRANSFORM('product', item, $));\n\t}\n});\n```\n\nSin callback, `TRANSFORM()` devuelve una Promise, que se rechaza con los errores de `$.invalid()` cuando no pasas un `$`. En una acción, `$.transform(name, value, [callback])` la ejecuta con el controlador de la acción (y el usuario de ese controlador). Pon las transformaciones en la carpeta `/transforms/`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUVAMx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/actions/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Actions","summary":"Déclare la logique métier avec NEWACTION(), valide ses entrées, expose-la comme route et exécute-la depuis le code avec ACTION().","markdown":"---\ntitle: Actions\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/actions/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Actions\n\n> Déclare la logique métier avec NEWACTION(), valide ses entrées, expose-la comme route et exécute-la depuis le code avec ACTION().\n\nUne **action** est un morceau nommé de logique métier. Elle déclare ce qu'elle accepte (corps, paramètres d'URL, query string), qui peut l'exécuter et ce qu'elle renvoie, et elle peut être exposée comme route ou appelée depuis ton code. Les actions sont la principale manière d'écrire la logique d'une application Total.js 5.\n\n```js\n// actions/products.js\nNEWACTION('products_create', {\n\tname: 'Create a product',\n\tinput: '*name:String, price:Number, description:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = NOW;\n\t\tDATA.insert('products', model).callback($.done(model.id));\n\t}\n});\n```\n\nPlace les fichiers contenant des actions dans le dossier `/actions/` (ou dans un plugin). Le framework les charge au démarrage : `NEWACTION()` s'exécute donc une fois et enregistre l'action sous son nom. Déclarer une action avec un nom existant remplace l'ancienne.\n\n## Déclarer une action\n\n`NEWACTION(name, options)` prend le nom et un objet d'options. Tu peux aussi ne passer que l'objet avec une propriété `id` (ou `name`). La fonction `action` est obligatoire et reçoit l'objet d'options `$` et le modèle validé.\n\n| Option | Ce qu'elle fait |\n| --- | --- |\n| `action` | `function($, model)`, la logique |\n| `input` | Schéma des données envoyées (le corps) ; le résultat validé est `$.model` |\n| `output` | Schéma de la réponse ; la valeur de `$.callback()` est nettoyée par celui-ci |\n| `params` | Schéma des paramètres dynamiques de l'URL (`$.params`) |\n| `query` | Schéma de la query string (`$.query`) |\n| `user` | `true` exige un utilisateur connecté, `false` exige une requête anonyme |\n| `sa` / `su` | Exige un utilisateur avec le flag `sa` ou `su` |\n| `permissions` | Permissions requises, `'products_create,admin'` ou un tableau |\n| `route` | Une route qui exécute l'action, par ex. `'+POST /api/products/'` |\n| `middleware` | Noms des middlewares à exécuter avant l'action, `'auth, ratelimit'` |\n| `partial` | Valide l'entrée partiellement (seulement les champs envoyés) |\n| `extend` | Place la réponse dans les données envoyées sous cette clé et renvoie ces données |\n| `audit` | `true` ou un template ; écrit un enregistrement d'audit après un succès |\n| `config` | N'importe quel objet ; disponible sous `$.config` |\n| `timeout` | Millisecondes ; l'action échoue avec `Timeout.` si elle ne répond pas à temps |\n| `cache` | `true` ou `{ query, params, input, user, language, key, expire }` ; garde la réponse en cache |\n| `oninput` | `function($)`, appelée juste avant `action` |\n| `onoutput` | `function(err, response, $)`, appelée après la réponse de l'action |\n| `summary` | Une description de l'action ; le serveur MCP l'utilise comme description de l'outil |\n| `mcp` | `true` fait de l'action un outil du [serveur MCP](../../guides/mcp-server/) |\n\nUn schéma est une définition inline (`'*name:String, email:Email'`, un `*` marque un champ obligatoire) ou le nom d'un schéma JSON enregistré avec `@` (`'@product'`). La syntaxe et les types sont décrits dans [Schémas JSON](../../guides/json-schemas/). Quand la validation échoue, l'action ne s'exécute pas et l'appelant reçoit les erreurs ; les erreurs de `query` et `params` sont préfixées par `query.` et `params.`.\n\n## L'objet `$`\n\nLe premier argument de `action` est un objet d'options, généralement nommé `$`. Il porte les données de l'appel et les méthodes qui le terminent.\n\n```js\nNEWACTION('orders_read', {\n\tparams: '*id:UID',\n\tquery: 'fields:String',\n\tuser: true,\n\taction: function($) {\n\t\tvar id = $.params.id;\n\t\tvar user = $.user;\n\t\tDATA.read('orders').id(id).where('userid', user.id).error(404).callback($);\n\t}\n});\n```\n\n| Propriété | Ce qu'elle contient |\n| --- | --- |\n| `$.model` | Les données envoyées validées (alias `$.payload` et `$.value`) |\n| `$.input` | Un autre alias de `$.model` |\n| `$.params` | Les paramètres d'URL validés |\n| `$.query` | La query string validée |\n| `$.user` | L'utilisateur de la requête, ou l'utilisateur passé à `ACTION().user()` |\n| `$.config` | L'option `config` de l'action |\n| `$.id` | Le nom de l'action en cours d'exécution |\n| `$.controller` | Le contrôleur de la requête HTTP, ou `undefined` |\n| `$.error` | L'`ErrorBuilder` de l'appel |\n| `$.xhr` | `true` pour une requête XHR, `null` sans contrôleur |\n| `$.meta` | L'objet de définition de l'action |\n| `$.env` | La valeur passée à `ACTION().env()`, ou `undefined` |\n| `$.ip`, `$.headers`, `$.url`, `$.files`, `$.language`, `$.ua` | Raccourcis vers le contrôleur, vides sans contrôleur |\n\nUne action se termine par exactement un de ces appels :\n\n- `$.success([value])` répond avec `{ success: true, value: value }`.\n- `$.callback(value)` répond avec la valeur telle quelle. Tu peux passer `$` lui-même comme callback d'une requête de base de données, par exemple `DATA.find('products').callback($)`.\n- `$.done([value])` renvoie un callback `function(err, response)` : une erreur devient `$.invalid()`, sinon il appelle `$.success(value)`, ou `$.success(response)` lorsque `value` vaut `true`.\n- `$.invalid(error, [path], [index])` fait échouer l'appel. Un nombre supérieur à 399 est un statut HTTP (`$.invalid(404)`) ; une chaîne est un message d'erreur.\n\n`$.redirect(url)` redirige la requête HTTP au lieu de répondre. `$.output('html')` change la manière dont une route répond (JSON par défaut).\n\n`$.invalidsafe(message, error)` termine l'action comme `$.invalid(message)`, mais écrit aussi `error` dans le log des erreurs. L'appelant ne reçoit que le message, donc les détails de l'erreur (chemins, SQL, adresses) restent sur le serveur. `$.throw(error)` écrit seulement une erreur dans le log et ne termine pas l'action. Dans une action `async`, une exception que tu n'attrapes pas termine l'appel avec `500: Internal Server Error` et va dans le log des erreurs.\n\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n`$.touch([url])` efface l'état mis en cache d'un fichier statique après que tu l'as modifié (voir [Fichiers statiques](../../guides/static-files/)), comme `TOUCH()`.\n\n## Routes\n\nL'option `route` crée une route pour l'action. La chaîne de route est la même que dans [Routage](../../guides/routing/) : un `+` devant la méthode exige un utilisateur connecté, un `-` un utilisateur anonyme.\n\n```js\nNEWACTION('products_list', {\n\tquery: 'search:String, page:Number',\n\troute: 'GET /api/products/',\n\taction: function($) {\n\t\tvar builder = DATA.list('products');\n\t\t$.query.search && builder.search('name', $.query.search);\n\t\tbuilder.paginate($.query.page, 20);\n\t\tbuilder.callback($);\n\t}\n});\n```\n\nUne route peut aussi appeler des actions déclarées ailleurs avec `-->`. Les actions s'exécutent l'une après l'autre avec le même `$`, et la route renvoie la réponse de l'action marquée `(response)`, ou un objet avec les réponses de toutes les actions par nom si aucune n'est marquée.\n\n```js\nexports.install = function() {\n\tROUTE('+POST /api/orders/ --> orders_create orders_notify (response) orders_stats');\n\tROUTE('+API ?  +orders_create --> orders_create');\n};\n```\n\nUn `+` devant un nom d'action indique qu'elle utilise les données envoyées, un `-` qu'elle ne les utilise pas ; sans préfixe, c'est l'option `input` qui décide. Les routes `API` regroupent de nombreuses actions sous un seul endpoint (`?` est l'endpoint `$api`, `/api/` par défaut) ; voir [Routage](../../guides/routing/).\n\n`route: true` est un raccourci pour un endpoint `API ?` nommé d'après l'action. Il devient `+API ?` lorsque l'action a l'option `user` ou `permissions`.\n\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\troute: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n```\n\n## Exécuter des actions depuis le code\n\n`ACTION(name, [payload], [controller])` (alias `EXEC`) exécute une action, ou plusieurs séparées par des espaces ou des virgules. Elle renvoie un appelant ; l'appel démarre au tick suivant, tu chaînes donc d'abord ses réglages.\n\n```js\nACTION('products_create', { name: 'Keyboard', price: 49 }).user(user).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.toString());\n\telse\n\t\tconsole.log(response);\n});\n```\n\n| Méthode | Ce qu'elle fait |\n| --- | --- |\n| `.callback(fn)` | `function(err, response)`, ou un `$` existant qui reçoit le résultat |\n| `.promise([$])` | Renvoie une Promise ; avec `$`, une erreur va à `$.invalid()` |\n| `.user(user)` | Définit `$.user` (accepte aussi un `$` et prend son utilisateur) |\n| `.query(obj)` / `.params(obj)` | Définit la query string et les paramètres d'URL |\n| `.ctrl(controller)` | Exécute l'action avec un contrôleur |\n| `.autorespond()` | Envoie la réponse (ou l'erreur) au contrôleur |\n| `.status(fn)` | Reçoit les valeurs que l'action envoie avec `$.status()` |\n| `.progress(fn)` | Reçoit les valeurs que l'action envoie avec `$.progress()` |\n| `.config(obj)` | Ajoute des clés à `$.config` pour cet appel uniquement |\n| `.env(value)` | Définit `$.env`, une valeur qui indique à l'action d'où elle est appelée |\n\nÀ l'intérieur d'une action, `$.action(name, [payload])` exécute une autre action avec le même contrôleur (ou le même utilisateur, la même query et les mêmes params s'il n'y en a pas). Dans un handler de route, `$.action(name, [model])` (où `$` est le contrôleur) fait de même avec le contrôleur.\n\n```js\nNEWACTION('orders_checkout', {\n\tinput: '*productid:UID, *count:Number',\n\tuser: true,\n\taction: async function($, model) {\n\t\tvar order = await $.action('orders_create', model).promise($);\n\t\tvar payment = await $.action('payments_create', { orderid: order.value }).promise($);\n\t\t$.success(payment);\n\t}\n});\n```\n\nAprès chaque action réussie, le framework émet l'événement `@<name>` avec `($, response)` :\n\n```js\nON('@products_create', function($, response) {\n\tconsole.log($.user.name, 'created', response.value);\n});\n```\n\nLes hooks `oninput($)` et `onoutput(err, response, $)` s'exécutent avant l'action et après sa réponse réussie : tu peux ainsi préparer des données ou journaliser les résultats sans toucher à la logique :\n\n```js\nNEWACTION('notes_save', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.input.body = $.input.body.trim();\n\t},\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, 'done', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(model.body.length);\n\t}\n});\n```\n\n## Mettre la réponse en cache\n\nL'option `cache` garde en cache la première réponse réussie. Les appels suivants en reçoivent tout de suite une copie, sans exécuter le middleware ni l'action. Liste les valeurs qui changent la réponse, pour que chaque combinaison ait sa propre entrée : `query`, `params` et `input` acceptent `true` (tous les champs du schéma) ou une liste de champs, `user: true` garde une entrée par utilisateur et `language: true` une par langue. Les entrées expirent après `expire` (5 minutes par défaut).\n\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').page($.query.page, 20).callback($);\n\t}\n});\n\nNEWACTION('Products|save', {\n\tinput: '*id:UID,*name:String',\n\taction: function($, model) {\n\t\tDATA.update('products', model).id(model.id).callback(function() {\n\t\t\tCACHE.reset('action|products|'); // the next list is read again\n\t\t\t$.success();\n\t\t});\n\t}\n});\n```\n\nLes erreurs ne sont pas mises en cache. Sans `user`, tous les utilisateurs reçoivent la même réponse en cache, donc ne mets pas en cache sans lui des réponses qui dépendent de l'utilisateur.\n\n## Schémas\n\n`NEWSCHEMA(name, callback)` regroupe des actions sous un préfixe commun. Le callback reçoit un objet dont `action(name, options)` crée l'action `<schema>/<name>`.\n\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.action('list', {\n\t\troute: 'GET /api/products/',\n\t\taction: function($) {\n\t\t\tDATA.find('products').callback($);\n\t\t}\n\t});\n});\n\n// The action name is 'Products/list'\n```\n\n## Transformations\n\nUne transformation est une chaîne nommée de fonctions qui modifient une valeur. `NEWTRANSFORM(name, fn, [id])` ajoute une fonction à la chaîne ; `TRANSFORM(name, value, [callback])` exécute la chaîne. Chaque fonction reçoit `$` et la valeur, modifie `$.value` et appelle `$.next()`.\n\n```js\nNEWTRANSFORM('product', function($, value) {\n\tvalue.name = value.name.trim();\n\t$.next();\n}, 'name');\n\nNEWTRANSFORM('product', function($, value) {\n\t$.value = { id: value.id, name: value.name, price: value.price };\n\t$.next();\n});\n\nTRANSFORM('product', { id: 1, name: ' Mouse ', price: 9, stock: 3 }, function(err, response) {\n\tconsole.log(response); // { id: 1, name: 'Mouse', price: 9 }\n});\n```\n\nUne fonction peut aussi arrêter la chaîne avec `$.invalid(error)` ; le callback reçoit alors les erreurs. Quand tu passes le `$` d'une action comme troisième argument de la forme Promise, les erreurs vont à `$.invalid()` de cette action :\n\n```js\nNEWACTION('products_read', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await DATA.read('products').id($.params.id).promise($);\n\t\t$.callback(await TRANSFORM('product', item, $));\n\t}\n});\n```\n\nSans callback, `TRANSFORM()` renvoie une Promise, qui est rejetée avec les erreurs de `$.invalid()` quand tu ne passes pas de `$`. Dans une action, `$.transform(name, value, [callback])` l'exécute avec le contrôleur de l'action (et l'utilisateur de ce contrôleur). Place les transformations dans le dossier `/transforms/`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUVAMx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/actions/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Azioni","summary":"Dichiara la logica di business con NEWACTION(), valida il suo input, esponila come route ed eseguila dal codice con ACTION().","markdown":"---\ntitle: Azioni\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/actions/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Azioni\n\n> Dichiara la logica di business con NEWACTION(), valida il suo input, esponila come route ed eseguila dal codice con ACTION().\n\nUn'**azione** è una porzione di logica di business con un nome. Dichiara cosa accetta (body, parametri URL, query string), chi può eseguirla e cosa restituisce, e può essere esposta come route o chiamata dal tuo codice. Le azioni sono il modo principale per scrivere la logica di un'applicazione Total.js 5.\n\n```js\n// actions/products.js\nNEWACTION('products_create', {\n\tname: 'Create a product',\n\tinput: '*name:String, price:Number, description:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = NOW;\n\t\tDATA.insert('products', model).callback($.done(model.id));\n\t}\n});\n```\n\nMetti i file con le azioni nella cartella `/actions/` (o in un plugin). Il framework li carica all'avvio, quindi `NEWACTION()` viene eseguito una volta e registra l'azione con il suo nome. Dichiarare un'azione con un nome già esistente sostituisce quella vecchia.\n\n## Dichiarare un'azione\n\n`NEWACTION(name, options)` accetta il nome e un oggetto di opzioni. Puoi anche passare solo l'oggetto con una proprietà `id` (o `name`). La funzione `action` è obbligatoria e riceve l'oggetto options `$` e il modello validato.\n\n| Opzione | Cosa fa |\n| --- | --- |\n| `action` | `function($, model)`, la logica |\n| `input` | Schema del payload (il body); il risultato validato è `$.model` |\n| `output` | Schema della risposta; il valore di `$.callback()` viene ripulito da esso |\n| `params` | Schema dei parametri URL dinamici (`$.params`) |\n| `query` | Schema della query string (`$.query`) |\n| `user` | `true` richiede un utente autenticato, `false` richiede una richiesta anonima |\n| `sa` / `su` | Richiede un utente con il flag `sa` o `su` |\n| `permissions` | Permessi richiesti, `'products_create,admin'` o un array |\n| `route` | Una route che esegue l'azione, es. `'+POST /api/products/'` |\n| `middleware` | Nomi dei middleware da eseguire prima dell'azione, `'auth, ratelimit'` |\n| `partial` | Valida l'input parzialmente (solo i campi inviati) |\n| `extend` | Inserisce la risposta nel payload sotto questa chiave e restituisce il payload |\n| `audit` | `true` o un template; scrive un record di audit dopo il successo |\n| `config` | Qualsiasi oggetto; disponibile come `$.config` |\n| `timeout` | Millisecondi; l'azione fallisce con `Timeout.` quando non risponde in tempo |\n| `cache` | `true` o `{ query, params, input, user, language, key, expire }`; mantiene la risposta in cache |\n| `oninput` | `function($)`, chiamata subito prima di `action` |\n| `onoutput` | `function(err, response, $)`, chiamata dopo che l'azione ha risposto |\n| `summary` | Una descrizione dell'azione; il server MCP la usa come descrizione del tool |\n| `mcp` | `true` rende l'azione un tool del [server MCP](../../guides/mcp-server/) |\n\nUno schema è una definizione inline (`'*name:String, email:Email'`, un `*` indica un campo obbligatorio) o il nome di uno schema JSON registrato con `@` (`'@product'`). La sintassi e i tipi sono descritti in [Schemi JSON](../../guides/json-schemas/). Quando la validazione fallisce, l'azione non viene eseguita e il chiamante riceve gli errori; gli errori di `query` e `params` hanno il prefisso `query.` e `params.`.\n\n## L'oggetto `$`\n\nIl primo argomento di `action` è un oggetto options, di solito chiamato `$`. Contiene i dati della chiamata e i metodi che la concludono.\n\n```js\nNEWACTION('orders_read', {\n\tparams: '*id:UID',\n\tquery: 'fields:String',\n\tuser: true,\n\taction: function($) {\n\t\tvar id = $.params.id;\n\t\tvar user = $.user;\n\t\tDATA.read('orders').id(id).where('userid', user.id).error(404).callback($);\n\t}\n});\n```\n\n| Proprietà | Cosa contiene |\n| --- | --- |\n| `$.model` | Il payload validato (alias `$.payload` e `$.value`) |\n| `$.input` | Un altro alias di `$.model` |\n| `$.params` | I parametri URL validati |\n| `$.query` | La query string validata |\n| `$.user` | L'utente della richiesta, o l'utente passato a `ACTION().user()` |\n| `$.config` | L'opzione `config` dell'azione |\n| `$.id` | Il nome dell'azione in esecuzione |\n| `$.controller` | Il controller della richiesta HTTP, oppure `undefined` |\n| `$.error` | L'`ErrorBuilder` della chiamata |\n| `$.xhr` | `true` per una richiesta XHR, `null` senza controller |\n| `$.meta` | L'oggetto di definizione dell'azione |\n| `$.env` | Il valore passato a `ACTION().env()`, oppure `undefined` |\n| `$.ip`, `$.headers`, `$.url`, `$.files`, `$.language`, `$.ua` | Scorciatoie verso il controller, vuote se non c'è |\n\nUn'azione termina con esattamente una di queste chiamate:\n\n- `$.success([value])` risponde con `{ success: true, value: value }`.\n- `$.callback(value)` risponde con il valore così com'è. Puoi passare `$` stesso come callback di una query al database, per esempio `DATA.find('products').callback($)`.\n- `$.done([value])` restituisce una callback `function(err, response)`: un errore diventa `$.invalid()`, altrimenti chiama `$.success(value)`, oppure `$.success(response)` quando `value` è `true`.\n- `$.invalid(error, [path], [index])` fa fallire la chiamata. Un numero sopra 399 è uno stato HTTP (`$.invalid(404)`); una stringa è un messaggio di errore.\n\n`$.redirect(url)` reindirizza la richiesta HTTP invece di rispondere. `$.output('html')` cambia il modo in cui risponde una route (il predefinito è JSON).\n\n`$.invalidsafe(message, error)` termina l'azione come `$.invalid(message)`, ma scrive anche `error` nel log degli errori. Il chiamante riceve solo il messaggio, così i dettagli dell'errore (percorsi, SQL, indirizzi) restano sul server. `$.throw(error)` scrive soltanto un errore nel log e non termina l'azione. In un'azione `async`, un'eccezione che non catturi termina la chiamata con `500: Internal Server Error` e finisce nel log degli errori.\n\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n`$.touch([url])` cancella lo stato in cache di un file statico dopo che lo hai modificato (vedi [File statici](../../guides/static-files/)), come `TOUCH()`.\n\n## Route\n\nL'opzione `route` crea una route per l'azione. La stringa della route è la stessa di [Routing](../../guides/routing/): un `+` prima del metodo richiede un utente autenticato, un `-` uno anonimo.\n\n```js\nNEWACTION('products_list', {\n\tquery: 'search:String, page:Number',\n\troute: 'GET /api/products/',\n\taction: function($) {\n\t\tvar builder = DATA.list('products');\n\t\t$.query.search && builder.search('name', $.query.search);\n\t\tbuilder.paginate($.query.page, 20);\n\t\tbuilder.callback($);\n\t}\n});\n```\n\nUna route può anche chiamare azioni dichiarate altrove con `-->`. Le azioni vengono eseguite una dopo l'altra con lo stesso `$`, e la route restituisce la risposta dell'azione contrassegnata con `(response)`, oppure un oggetto con le risposte di tutte le azioni per nome quando nessuna è contrassegnata.\n\n```js\nexports.install = function() {\n\tROUTE('+POST /api/orders/ --> orders_create orders_notify (response) orders_stats');\n\tROUTE('+API ?  +orders_create --> orders_create');\n};\n```\n\nUn `+` prima del nome di un'azione indica che usa il payload, un `-` che non lo usa; senza prefisso decide l'opzione `input`. Le route `API` riuniscono molte azioni sotto un unico endpoint (`?` è l'endpoint `$api`, `/api/` per impostazione predefinita); vedi [Routing](../../guides/routing/).\n\n`route: true` è una scorciatoia per un endpoint `API ?` con il nome dell'azione. Diventa `+API ?` quando l'azione ha l'opzione `user` o `permissions`.\n\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\troute: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n```\n\n## Eseguire azioni dal codice\n\n`ACTION(name, [payload], [controller])` (alias `EXEC`) esegue un'azione, oppure più azioni separate da spazi o virgole. Restituisce un caller; la chiamata parte al tick successivo, quindi prima concateni le sue impostazioni.\n\n```js\nACTION('products_create', { name: 'Keyboard', price: 49 }).user(user).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.toString());\n\telse\n\t\tconsole.log(response);\n});\n```\n\n| Metodo | Cosa fa |\n| --- | --- |\n| `.callback(fn)` | `function(err, response)`, oppure un `$` esistente che riceve il risultato |\n| `.promise([$])` | Restituisce una Promise; con `$`, un errore va a `$.invalid()` |\n| `.user(user)` | Imposta `$.user` (accetta anche un `$` e ne prende l'utente) |\n| `.query(obj)` / `.params(obj)` | Imposta la query string e i parametri URL |\n| `.ctrl(controller)` | Esegue l'azione con un controller |\n| `.autorespond()` | Invia la risposta (o l'errore) al controller |\n| `.status(fn)` | Riceve i valori che l'azione invia con `$.status()` |\n| `.progress(fn)` | Riceve i valori che l'azione invia con `$.progress()` |\n| `.config(obj)` | Aggiunge chiavi a `$.config` solo per questa chiamata |\n| `.env(value)` | Imposta `$.env`, un valore che dice all'azione da dove viene chiamata |\n\nAll'interno di un'azione, `$.action(name, [payload])` esegue un'altra azione con lo stesso controller (o con lo stesso utente, query e params quando non c'è). In un handler di route, `$.action(name, [model])` (dove `$` è il controller) fa lo stesso con il controller.\n\n```js\nNEWACTION('orders_checkout', {\n\tinput: '*productid:UID, *count:Number',\n\tuser: true,\n\taction: async function($, model) {\n\t\tvar order = await $.action('orders_create', model).promise($);\n\t\tvar payment = await $.action('payments_create', { orderid: order.value }).promise($);\n\t\t$.success(payment);\n\t}\n});\n```\n\nDopo ogni azione riuscita, il framework emette l'evento `@<name>` con `($, response)`:\n\n```js\nON('@products_create', function($, response) {\n\tconsole.log($.user.name, 'created', response.value);\n});\n```\n\nGli hook `oninput($)` e `onoutput(err, response, $)` vengono eseguiti prima dell'azione e dopo la sua risposta riuscita, così puoi preparare dati o registrare risultati senza toccare la logica:\n\n```js\nNEWACTION('notes_save', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.input.body = $.input.body.trim();\n\t},\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, 'done', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(model.body.length);\n\t}\n});\n```\n\n## Cache della risposta\n\nL'opzione `cache` mantiene in cache la prima risposta riuscita. Le chiamate successive ne ricevono subito una copia, senza eseguire il middleware e l'azione. Elenca i valori che cambiano la risposta, così ogni combinazione ottiene una propria voce: `query`, `params` e `input` accettano `true` (tutti i campi dello schema) o un elenco di campi, `user: true` mantiene una voce per utente e `language: true` una per lingua. Le voci scadono dopo `expire` (5 minuti per impostazione predefinita).\n\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').page($.query.page, 20).callback($);\n\t}\n});\n\nNEWACTION('Products|save', {\n\tinput: '*id:UID,*name:String',\n\taction: function($, model) {\n\t\tDATA.update('products', model).id(model.id).callback(function() {\n\t\t\tCACHE.reset('action|products|'); // the next list is read again\n\t\t\t$.success();\n\t\t});\n\t}\n});\n```\n\nGli errori non vengono messi in cache. Senza `user`, ogni utente riceve la stessa risposta in cache, quindi senza di esso non mettere in cache risposte che dipendono dall'utente.\n\n## Schemi\n\n`NEWSCHEMA(name, callback)` raggruppa le azioni sotto un prefisso comune. La callback riceve un oggetto il cui `action(name, options)` crea l'azione `<schema>/<name>`.\n\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.action('list', {\n\t\troute: 'GET /api/products/',\n\t\taction: function($) {\n\t\t\tDATA.find('products').callback($);\n\t\t}\n\t});\n});\n\n// The action name is 'Products/list'\n```\n\n## Trasformazioni\n\nUna trasformazione è una catena di funzioni con un nome che modificano un valore. `NEWTRANSFORM(name, fn, [id])` aggiunge una funzione alla catena; `TRANSFORM(name, value, [callback])` esegue la catena. Ogni funzione riceve `$` e il valore, modifica `$.value` e chiama `$.next()`.\n\n```js\nNEWTRANSFORM('product', function($, value) {\n\tvalue.name = value.name.trim();\n\t$.next();\n}, 'name');\n\nNEWTRANSFORM('product', function($, value) {\n\t$.value = { id: value.id, name: value.name, price: value.price };\n\t$.next();\n});\n\nTRANSFORM('product', { id: 1, name: ' Mouse ', price: 9, stock: 3 }, function(err, response) {\n\tconsole.log(response); // { id: 1, name: 'Mouse', price: 9 }\n});\n```\n\nUna funzione può anche interrompere la catena con `$.invalid(error)`; la callback riceve allora gli errori. Quando passi il `$` di un'azione come terzo argomento della forma Promise, gli errori vanno a `$.invalid()` di quell'azione:\n\n```js\nNEWACTION('products_read', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await DATA.read('products').id($.params.id).promise($);\n\t\t$.callback(await TRANSFORM('product', item, $));\n\t}\n});\n```\n\nSenza callback, `TRANSFORM()` restituisce una Promise, che viene rifiutata con gli errori di `$.invalid()` quando non passi un `$`. In un'azione, `$.transform(name, value, [callback])` la esegue con il controller dell'azione (e l'utente di quel controller). Metti le trasformazioni nella cartella `/transforms/`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwUVAMx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/actions/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Akcie","summary":"Deklaruj biznis logiku pomocou NEWACTION(), over jej vstup, sprístupni ju ako trasu a spúšťaj ju z kódu pomocou ACTION().","markdown":"---\ntitle: Akcie\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/actions/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Akcie\n\n> Deklaruj biznis logiku pomocou NEWACTION(), over jej vstup, sprístupni ju ako trasu a spúšťaj ju z kódu pomocou ACTION().\n\n**Akcia** je pomenovaný kus biznis logiky. Deklaruje, čo prijíma (telo, URL parametre, query string), kto ju smie spustiť a čo vracia, a dá sa sprístupniť ako routa alebo volať z tvojho kódu. Akcie sú hlavný spôsob, ako písať logiku aplikácie Total.js 5.\n\n```js\n// actions/products.js\nNEWACTION('products_create', {\n\tname: 'Create a product',\n\tinput: '*name:String, price:Number, description:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tmodel.dtcreated = NOW;\n\t\tDATA.insert('products', model).callback($.done(model.id));\n\t}\n});\n```\n\nSúbory s akciami daj do priečinka `/actions/` (alebo do pluginu). Framework ich načíta pri štarte, takže `NEWACTION()` sa spustí raz a zaregistruje akciu pod jej názvom. Deklarovanie akcie s existujúcim názvom nahradí starú.\n\n## Deklarovanie akcie\n\n`NEWACTION(name, options)` prijíma názov a objekt možností. Môžeš odovzdať aj iba objekt s vlastnosťou `id` (alebo `name`). Funkcia `action` je povinná a dostane objekt možností `$` a validovaný model.\n\n| Možnosť | Čo robí |\n| --- | --- |\n| `action` | `function($, model)`, logika |\n| `input` | Schéma payloadu (tela); validovaný výsledok je `$.model` |\n| `output` | Schéma odpovede; hodnota z `$.callback()` sa ňou vyčistí |\n| `params` | Schéma dynamických URL parametrov (`$.params`) |\n| `query` | Schéma query stringu (`$.query`) |\n| `user` | `true` vyžaduje prihláseného používateľa, `false` anonymnú požiadavku |\n| `sa` / `su` | Vyžaduje používateľa s flagom `sa` alebo `su` |\n| `permissions` | Požadované oprávnenia, `'products_create,admin'` alebo pole |\n| `route` | Routa, ktorá spustí akciu, napr. `'+POST /api/products/'` |\n| `middleware` | Názvy middleware, ktoré sa spustia pred akciou, `'auth, ratelimit'` |\n| `partial` | Validuje vstup čiastočne (iba odoslané polia) |\n| `extend` | Vloží odpoveď do payloadu pod týmto kľúčom a vráti payload |\n| `audit` | `true` alebo šablóna; po úspechu zapíše audit záznam |\n| `config` | Ľubovoľný objekt; dostupný ako `$.config` |\n| `timeout` | Milisekundy; akcia zlyhá s `Timeout.`, keď neodpovie včas |\n| `cache` | `true` alebo `{ query, params, input, user, language, key, expire }`; uchová odpoveď v cache |\n| `oninput` | `function($)`, volá sa tesne pred `action` |\n| `onoutput` | `function(err, response, $)`, volá sa po odpovedi akcie |\n| `summary` | Popis akcie; MCP server ho používa ako popis nástroja |\n| `mcp` | `true` urobí z akcie nástroj [MCP servera](../../guides/mcp-server/) |\n\nSchéma je inline definícia (`'*name:String, email:Email'`, `*` označuje povinné pole) alebo názov zaregistrovanej JSON schémy s `@` (`'@product'`). Syntax a typy sú opísané v [JSON schémy](../../guides/json-schemas/). Keď validácia zlyhá, akcia sa nespustí a volajúci dostane chyby; chyby `query` a `params` majú prefix `query.` a `params.`.\n\n## Objekt `$`\n\nPrvý argument `action` je objekt možností, zvyčajne nazvaný `$`. Nesie dáta volania a metódy, ktoré ho ukončia.\n\n```js\nNEWACTION('orders_read', {\n\tparams: '*id:UID',\n\tquery: 'fields:String',\n\tuser: true,\n\taction: function($) {\n\t\tvar id = $.params.id;\n\t\tvar user = $.user;\n\t\tDATA.read('orders').id(id).where('userid', user.id).error(404).callback($);\n\t}\n});\n```\n\n| Vlastnosť | Čo obsahuje |\n| --- | --- |\n| `$.model` | Validovaný payload (aliasy `$.payload` a `$.value`) |\n| `$.input` | Ďalší alias `$.model` |\n| `$.params` | Validované URL parametre |\n| `$.query` | Validovaný query string |\n| `$.user` | Používateľ požiadavky alebo používateľ odovzdaný do `ACTION().user()` |\n| `$.config` | Možnosť `config` akcie |\n| `$.id` | Názov bežiacej akcie |\n| `$.controller` | Controller HTTP požiadavky alebo `undefined` |\n| `$.error` | `ErrorBuilder` volania |\n| `$.xhr` | `true` pre XHR požiadavku, `null` bez controllera |\n| `$.meta` | Definičný objekt akcie |\n| `$.env` | Hodnota odovzdaná do `ACTION().env()` alebo `undefined` |\n| `$.ip`, `$.headers`, `$.url`, `$.files`, `$.language`, `$.ua` | Skratky na controller, bez neho prázdne |\n\nAkcia končí práve jedným z týchto volaní:\n\n- `$.success([value])` odpovie s `{ success: true, value: value }`.\n- `$.callback(value)` odpovie hodnotou tak, ako je. Samotný `$` môžeš odovzdať ako callback databázového dotazu, napríklad `DATA.find('products').callback($)`.\n- `$.done([value])` vráti callback `function(err, response)`: chyba sa stane `$.invalid()`, inak zavolá `$.success(value)`, alebo `$.success(response)`, keď je `value` `true`.\n- `$.invalid(error, [path], [index])` volanie zlyhá. Číslo nad 399 je HTTP status (`$.invalid(404)`); reťazec je chybová správa.\n\n`$.redirect(url)` presmeruje HTTP požiadavku namiesto odpovede. `$.output('html')` zmení, ako routa odpovedá (predvolene JSON).\n\n`$.invalidsafe(message, error)` ukončí akciu ako `$.invalid(message)`, ale zároveň zapíše `error` do chybového logu. Volajúci dostane iba správu, takže podrobnosti chyby (cesty, SQL, adresy) zostanú na serveri. `$.throw(error)` iba zapíše chybu do logu a akciu neukončí. V `async` akcii výnimka, ktorú nezachytíš, ukončí volanie s `500: Internal Server Error` a zapíše sa do chybového logu.\n\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n`$.touch([url])` vymaže uložený stav statického súboru po tom, ako ho zmeníš (pozri [Statické súbory](../../guides/static-files/)), rovnako ako `TOUCH()`.\n\n## Routy\n\nMožnosť `route` vytvorí pre akciu routu. Reťazec routy je rovnaký ako v [Routing](../../guides/routing/): `+` pred metódou vyžaduje prihláseného používateľa, `-` anonymného.\n\n```js\nNEWACTION('products_list', {\n\tquery: 'search:String, page:Number',\n\troute: 'GET /api/products/',\n\taction: function($) {\n\t\tvar builder = DATA.list('products');\n\t\t$.query.search && builder.search('name', $.query.search);\n\t\tbuilder.paginate($.query.page, 20);\n\t\tbuilder.callback($);\n\t}\n});\n```\n\nRouta môže tiež volať akcie deklarované inde cez `-->`. Akcie sa spúšťajú jedna po druhej s rovnakým `$` a routa vráti odpoveď akcie označenej `(response)`, alebo objekt s odpoveďami všetkých akcií podľa názvu, keď nie je označená žiadna.\n\n```js\nexports.install = function() {\n\tROUTE('+POST /api/orders/ --> orders_create orders_notify (response) orders_stats');\n\tROUTE('+API ?  +orders_create --> orders_create');\n};\n```\n\n`+` pred názvom akcie hovorí, že používa payload, `-`, že nie; bez prefixu rozhoduje možnosť `input`. Routy `API` spájajú veľa akcií pod jeden endpoint (`?` je endpoint `$api`, predvolene `/api/`); pozri [Routing](../../guides/routing/).\n\n`route: true` je skratka pre endpoint `API ?` pomenovaný podľa akcie. Stane sa z neho `+API ?`, keď má akcia možnosť `user` alebo `permissions`.\n\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\troute: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n```\n\n## Spúšťanie akcií z kódu\n\n`ACTION(name, [payload], [controller])` (alias `EXEC`) spustí jednu akciu alebo viac akcií oddelených medzerami alebo čiarkami. Vráti volajúci objekt; volanie začne v ďalšom ticku, takže najprv zreťazíš jeho nastavenia.\n\n```js\nACTION('products_create', { name: 'Keyboard', price: 49 }).user(user).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.toString());\n\telse\n\t\tconsole.log(response);\n});\n```\n\n| Metóda | Čo robí |\n| --- | --- |\n| `.callback(fn)` | `function(err, response)` alebo existujúci `$`, ktorý dostane výsledok |\n| `.promise([$])` | Vráti Promise; s `$` ide chyba do `$.invalid()` |\n| `.user(user)` | Nastaví `$.user` (prijíma aj `$` a vezme jeho používateľa) |\n| `.query(obj)` / `.params(obj)` | Nastaví query string a URL parametre |\n| `.ctrl(controller)` | Spustí akciu s controllerom |\n| `.autorespond()` | Pošle odpoveď (alebo chybu) controlleru |\n| `.status(fn)` | Dostáva hodnoty, ktoré akcia posiela cez `$.status()` |\n| `.progress(fn)` | Dostáva hodnoty, ktoré akcia posiela cez `$.progress()` |\n| `.config(obj)` | Pridá kľúče do `$.config` iba pre toto volanie |\n| `.env(value)` | Nastaví `$.env`, hodnotu, ktorá akcii povie, odkiaľ sa volá |\n\nVnútri akcie `$.action(name, [payload])` spustí inú akciu s rovnakým controllerom (alebo s rovnakým používateľom, query a params, keď controller nie je). V handleri routy `$.action(name, [model])` (kde `$` je controller) robí to isté s controllerom.\n\n```js\nNEWACTION('orders_checkout', {\n\tinput: '*productid:UID, *count:Number',\n\tuser: true,\n\taction: async function($, model) {\n\t\tvar order = await $.action('orders_create', model).promise($);\n\t\tvar payment = await $.action('payments_create', { orderid: order.value }).promise($);\n\t\t$.success(payment);\n\t}\n});\n```\n\nPo každej úspešnej akcii framework vyšle udalosť `@<name>` s `($, response)`:\n\n```js\nON('@products_create', function($, response) {\n\tconsole.log($.user.name, 'created', response.value);\n});\n```\n\nHooky `oninput($)` a `onoutput(err, response, $)` sa spúšťajú pred akciou a po jej úspešnej odpovedi, takže môžeš pripraviť dáta alebo logovať výsledky bez zásahu do logiky:\n\n```js\nNEWACTION('notes_save', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.input.body = $.input.body.trim();\n\t},\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, 'done', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(model.body.length);\n\t}\n});\n```\n\n## Cachovanie odpovede\n\nMožnosť `cache` uchová prvú úspešnú odpoveď v cache. Ďalšie volania dostanú hneď jej kópiu, bez spustenia middleware a akcie. Vymenuj hodnoty, ktoré menia odpoveď, aby každá kombinácia dostala vlastný záznam: `query`, `params` a `input` berú `true` (všetky polia schémy) alebo zoznam polí, `user: true` uchováva jeden záznam na používateľa a `language: true` jeden na jazyk. Záznamy vypršia po `expire` (predvolene 5 minút).\n\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').page($.query.page, 20).callback($);\n\t}\n});\n\nNEWACTION('Products|save', {\n\tinput: '*id:UID,*name:String',\n\taction: function($, model) {\n\t\tDATA.update('products', model).id(model.id).callback(function() {\n\t\t\tCACHE.reset('action|products|'); // the next list is read again\n\t\t\t$.success();\n\t\t});\n\t}\n});\n```\n\nChyby sa necachujú. Bez `user` dostane každý používateľ rovnakú odpoveď z cache, takže odpovede, ktoré závisia od používateľa, bez neho necachuj.\n\n## Schémy\n\n`NEWSCHEMA(name, callback)` zoskupí akcie pod spoločný prefix. Callback dostane objekt, ktorého `action(name, options)` vytvorí akciu `<schema>/<name>`.\n\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.action('list', {\n\t\troute: 'GET /api/products/',\n\t\taction: function($) {\n\t\t\tDATA.find('products').callback($);\n\t\t}\n\t});\n});\n\n// The action name is 'Products/list'\n```\n\n## Transformácie\n\nTransformácia je pomenovaná reťaz funkcií, ktoré menia hodnotu. `NEWTRANSFORM(name, fn, [id])` pridá do reťaze jednu funkciu; `TRANSFORM(name, value, [callback])` reťaz spustí. Každá funkcia dostane `$` a hodnotu, zmení `$.value` a zavolá `$.next()`.\n\n```js\nNEWTRANSFORM('product', function($, value) {\n\tvalue.name = value.name.trim();\n\t$.next();\n}, 'name');\n\nNEWTRANSFORM('product', function($, value) {\n\t$.value = { id: value.id, name: value.name, price: value.price };\n\t$.next();\n});\n\nTRANSFORM('product', { id: 1, name: ' Mouse ', price: 9, stock: 3 }, function(err, response) {\n\tconsole.log(response); // { id: 1, name: 'Mouse', price: 9 }\n});\n```\n\nFunkcia môže reťaz aj zastaviť cez `$.invalid(error)`; callback potom dostane chyby. Keď v podobe s Promise odovzdáš ako tretí argument `$` akcie, chyby idú do `$.invalid()` tejto akcie:\n\n```js\nNEWACTION('products_read', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await DATA.read('products').id($.params.id).promise($);\n\t\t$.callback(await TRANSFORM('product', item, $));\n\t}\n});\n```\n\nBez callbacku `TRANSFORM()` vráti Promise, ktorý sa zamietne s chybami z `$.invalid()`, keď neodovzdáš `$`. V akcii `$.transform(name, value, [callback])` ju spustí s controllerom akcie (a používateľom tohto controllera). Transformácie daj do priečinka `/transforms/`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwVPESx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Schemas and validation","summary":"Inline schemas, JSON schemas and ErrorBuilder: how Total.js 5 validates and converts data.","markdown":"---\ntitle: Schemas and validation\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/json-schemas/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Schemas and validation\n\n> Inline schemas, JSON schemas and ErrorBuilder: how Total.js 5 validates and converts data.\n\nTotal.js 5 validates data with **schemas**. A schema describes the fields of an object, converts every value to its type and collects the errors. The same schema object works in actions, in your own code and in the files of the `jsonschemas/` folder.\n\nYou can write a schema in two ways:\n\n- an **inline schema**, a short string such as `'*name:String,email:Email,age:Number'`;\n- a **JSON schema**, a plain object with `type`, `properties`, `required` and other keywords.\n\nAn inline schema is turned into a JSON schema object, so both ways end in the same format and the same validator.\n\n## Inline schemas\n\nAn inline schema is a list of fields separated by commas or new lines. Each field is `name:Type`. Spaces around names and types are ignored and the type names are not case-sensitive (`Email`, `email` and `EMAIL` are the same). A field without a type is a `String`, and an unknown type is a `String` too.\n\n```js\nvar schema = '*name:String,*email:Email,age:Number,newsletter:Boolean'.toJSONSchema();\n\nvar result = schema.transform({ name: '  Peter ', email: 'PETER@EXAMPLE.COM', age: '33' });\n// result.error === null\n// result.response === { name: 'Peter', email: 'peter@example.com', age: 33, newsletter: false }\n```\n\n`transform()` returns an object with two keys: `response` (the clean object) and `error` (an [ErrorBuilder](#errors-and-errorbuilder) with the errors, or `null`). Only the fields of the schema are copied to the response; other keys of the input are dropped.\n\n### Modifiers\n\n| Syntax | Meaning |\n| --- | --- |\n| `*name:String` | The field is required (`!name:String` is the same) |\n| `name:String(50)` | The text can have at most 50 characters |\n| `tags:[String]` | An array of values of the type |\n| `type:{draft\\|published}` | The value must be one of the listed values |\n| `address:{street:String,city:String}` | A nested object with its own fields |\n| `address:@Address` | A nested object validated by the registered schema `Address` |\n| `name:String // Enter your name` | A custom error message for the field |\n\nA required field fails when its value is empty: an empty string, a missing number, a missing boolean or a date that can't be parsed. `0` is a valid required number and `false` is a valid required boolean.\n\n### Types\n\n| Type | What it does with the value |\n| --- | --- |\n| `String`, `Text` | Converted to a string and trimmed |\n| `String2` | Like `String`, but an empty value becomes `null` |\n| `Number`, `Number2`, `Int`, `Integer`, `Float`, `Decimal` | Parsed as a number (`'1,5'` gives `1.5`); a value that is not a number is left out |\n| `SmallInt` | A number from -32767 to 32767 |\n| `TinyInt` | A number from 0 to 255 |\n| `Boolean`, `Bool` | `true` or `false`; strings like `'true'`, `'1'` or `'on'` are parsed |\n| `Date` | A `Date` object, or `null` |\n| `Email` | Spaces removed, lower case, must be a valid email |\n| `Email2` | Like `Email`, and the tag is removed: `name+tag@domain.com` gives `name@domain.com` |\n| `Phone` | Spaces removed, must be a valid phone number |\n| `URL` | Must be a valid URL |\n| `Zip` | Must be a valid ZIP code |\n| `UID`, `GUID` | Must be a valid Total.js UID or a GUID; empty becomes `null` |\n| `Name` | Formatted as a person name (`'peter sirka'` gives `'Peter Sirka'`) |\n| `Lower`, `Lowercase`, `Upper`, `Uppercase` | Converted to lower or upper case |\n| `Capitalize`, `Capitalize2` | First letter of every word, or only of the first word, in upper case |\n| `Color` | A hex color: `#RGB`, `#RRGGBB` or `#RRGGBBAA` |\n| `Icon` | An icon class such as `ti ti-home` or `fa fa-check` |\n| `Base64` | Must be a Base64 string; empty becomes `null` |\n| `JSON` | A string that looks like JSON (see `String.isJSON()`); it is kept as text and empty becomes `null` |\n| `IP` | An IPv4 or IPv6 address; trimmed, empty becomes `null` |\n| `DataURI` | Must be a Base64 data URI; parsed into `{ type, buffer }` |\n| `DataURI2` | Must be a Base64 data URI; kept as the original text |\n| `SafeString` | Rejected when it contains XSS or SQL injection patterns |\n| `Search` | Converted to a search string with `String.toSearch()` |\n\nStrings, booleans and dates are always present in the response: a missing string is `''`, a missing boolean is `false` and a missing date is `null`. A missing number is left out.\n\n```js\nvar schema = 'color:Color,icon:Icon,photo:DataURI,avatar:DataURI2'.toJSONSchema();\nvar result = schema.transform({ color: '#FF0000', icon: 'ti ti-user', photo: 'data:image/png;base64,iVBORw0KGgo=', avatar: 'data:image/png;base64,iVBORw0KGgo=' });\n// result.response.photo === { type: 'image/png', buffer: <Buffer> }\n// result.response.avatar === 'data:image/png;base64,iVBORw0KGgo='\n```\n\n### Enums, arrays and nested objects\n\n```js\nvar schema = `*title:String(100)\n\tstatus:{draft|published|archived}\n\ttags:[String]\n\tratings:[Number]\n\tauthor:{name:String,email:Email}\n\titems:[{name:String,price:Number}]`.toJSONSchema();\n```\n\nAn enum accepts `|` or `;` between the values. An array field accepts only an array; every item is converted to the type. `[{...}]` is an array of nested objects. A nested object can contain further nested objects and arrays, at any depth:\n\n```js\nvar schema = 'order:{number:String,lines:[{sku:String,qty:Number}],shipping:{address:{street:String,city:String}}}'.toJSONSchema();\n```\n\nThe errors of a nested field have a path such as `author.email`, `items[1].price` or `order.shipping.address.city`.\n\n### Registered schemas\n\n`NEWSCHEMA(name, schema)` registers an inline schema under a name. Other schemas and actions use it with `@name`.\n\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\n\nNEWSCHEMA('@Customer', `*name:String(50)\n\t*email:Email\n\taddress:@Address\n\tbranches:[@Address]`);\n```\n\nAll registered schemas are in the `F.jsonschemas` object. `'...'.toJSONSchema(name)` registers the schema under `name` too.\n\n## Schemas in actions\n\nThe `input`, `output`, `query` and `params` options of an action take an inline schema or the name of a registered schema with `@`. The input is validated before the action runs; when it fails, the action does not run and the client receives the errors. See [Actions](../../guides/actions/).\n\n```js\nNEWACTION('Customers/create', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t// model is the validated object\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Customers/list', {\n\tquery: 'page:Number,limit:Number,search:Search',\n\taction: function($) {\n\t\t// $.query.page is a number\n\t\t$.callback([]);\n\t}\n});\n```\n\nErrors from `query` have names that start with `query.` and errors from `params` start with `params.`. An action with `partial: true` validates only the fields that exist in the input, so it fits updates of a few fields.\n\n## JSON schemas\n\nA JSON schema is an object. Register it with `F.newjsonschema()`, or put it in the `jsonschemas/` folder.\n\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tsku: { type: 'string', subtype: 'uid' },\n\t\tprice: { type: 'number', minimum: 1 },\n\t\tstock: { type: 'number', subtype: 'smallint' },\n\t\ttags: { type: 'array', items: { type: 'string' }, uniqueItems: true },\n\t\tsupplier: { type: 'object', $ref: '#/definitions/Supplier' }\n\t},\n\trequired: ['name', 'price'],\n\tdefinitions: {\n\t\tSupplier: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { name: { type: 'string' }, email: { type: 'string', subtype: 'email' } },\n\t\t\trequired: ['name']\n\t\t}\n\t}\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nSupported types: `object`, `array`, `string`, `number` (or `integer`), `boolean` (or `bool`) and `date`. Supported keywords: `properties`, `required`, `minLength`, `maxLength`, `enum`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `items`, `minItems`, `uniqueItems`, `$ref`, `definitions`, and two Total.js keywords: `subtype` (a type from the inline table, such as `email`, `uid`, `ip` or `json`, plus `ipaddress`, the same as `ip`) and `nullable` (an empty string becomes `null`).\n\n### The jsonschemas folder\n\nWhen the application starts, every `.json` file in `jsonschemas/` is parsed and registered with the file name as its name. The folder is loaded before the folders with code, so `jsonschemas/Address.json` can be used as `@Address` in any action.\n\n## Errors and ErrorBuilder\n\n`ErrorBuilder` collects errors. Validation fills it, and you can use it on your own.\n\n```js\nvar err = new ErrorBuilder();\nerr.push('The order is closed');\nerr.push2('email');\t  // a field error\nerr.output();\n// [{ error: 'The order is closed' }, { name: 'email', error: 'The field \"email\" is invalid' }]\n```\n\nThe message of a field error is found in this order: the `//` message of the schema, a resource with the field name (see [Localization](../../guides/localization/)), and the text `The field \"name\" is invalid`. A pushed number from 400 up sets the HTTP status (`err.push(404)`); otherwise the status is 400. When an action or a controller answers with an ErrorBuilder, the client receives the JSON array of `output()` with that status.\n\n## AI tools\n\nTwo methods of an inline schema describe it for AI models: the fields become the parameters, the `//` messages become their descriptions and the required fields stay required. See [AI models](../../guides/ai-models/).\n\n`schema.toAITool(name)` returns a tool definition in the common function format:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar tool = schema.toAITool('weather');\n// { type: 'function', function: { name: 'weather', parameters: { type: 'object', properties: {...}, required: ['city'] } } }\n```\n\n`schema.toAIObject(name, [description])` returns a standard JSON Schema object with a name, for example for a structured answer of a model. Dates get `format: 'date-time'`, emails `format: 'email'`, enums their values, and fields that can be `null` the type `['string', 'null']`:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// { name: 'forecast', description: 'The weather forecast for a city', type: 'object', additionalProperties: false,\n//   properties: { city: { type: 'string', description: 'The name of the city' }, days: {...} }, required: ['city'] }\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwVPESx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Schemas und Validierung","summary":"Inline-Schemas, JSON-Schemas und ErrorBuilder: wie Total.js 5 Daten validiert und konvertiert.","markdown":"---\ntitle: Schemas und Validierung\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/json-schemas/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Schemas und Validierung\n\n> Inline-Schemas, JSON-Schemas und ErrorBuilder: wie Total.js 5 Daten validiert und konvertiert.\n\nTotal.js 5 validiert Daten mit **Schemas**. Ein Schema beschreibt die Felder eines Objekts, wandelt jeden Wert in seinen Typ um und sammelt die Fehler. Dasselbe Schema-Objekt funktioniert in Aktionen, in deinem eigenen Code und in den Dateien des Ordners `jsonschemas/`.\n\nDu kannst ein Schema auf zwei Arten schreiben:\n\n- ein **Inline-Schema**, ein kurzer String wie `'*name:String,email:Email,age:Number'`;\n- ein **JSON-Schema**, ein einfaches Objekt mit `type`, `properties`, `required` und anderen Schlüsselwörtern.\n\nEin Inline-Schema wird in ein JSON-Schema-Objekt umgewandelt, daher enden beide Wege im selben Format und beim selben Validator.\n\n## Inline-Schemas\n\nEin Inline-Schema ist eine Liste von Feldern, getrennt durch Kommas oder Zeilenumbrüche. Jedes Feld ist `name:Type`. Leerzeichen um Namen und Typen werden ignoriert, und die Typnamen unterscheiden nicht zwischen Groß- und Kleinschreibung (`Email`, `email` und `EMAIL` sind dasselbe). Ein Feld ohne Typ ist ein `String`, und ein unbekannter Typ ist ebenfalls ein `String`.\n\n```js\nvar schema = '*name:String,*email:Email,age:Number,newsletter:Boolean'.toJSONSchema();\n\nvar result = schema.transform({ name: '  Peter ', email: 'PETER@EXAMPLE.COM', age: '33' });\n// result.error === null\n// result.response === { name: 'Peter', email: 'peter@example.com', age: 33, newsletter: false }\n```\n\n`transform()` gibt ein Objekt mit zwei Schlüsseln zurück: `response` (das bereinigte Objekt) und `error` (ein [ErrorBuilder](#errors-and-errorbuilder) mit den Fehlern oder `null`). Nur die Felder des Schemas werden in die Antwort kopiert; andere Schlüssel der Eingabe werden verworfen.\n\n### Modifikatoren\n\n| Syntax | Bedeutung |\n| --- | --- |\n| `*name:String` | Das Feld ist ein Pflichtfeld (`!name:String` ist dasselbe) |\n| `name:String(50)` | Der Text darf höchstens 50 Zeichen haben |\n| `tags:[String]` | Ein Array von Werten des Typs |\n| `type:{draft\\|published}` | Der Wert muss einer der aufgeführten Werte sein |\n| `address:{street:String,city:String}` | Ein verschachteltes Objekt mit eigenen Feldern |\n| `address:@Address` | Ein verschachteltes Objekt, das mit dem registrierten Schema `Address` validiert wird |\n| `name:String // Enter your name` | Eine eigene Fehlermeldung für das Feld |\n\nEin Pflichtfeld schlägt fehl, wenn sein Wert leer ist: ein leerer String, eine fehlende Zahl, ein fehlender Boolean oder ein Datum, das nicht geparst werden kann. `0` ist eine gültige Pflichtzahl und `false` ein gültiger Pflicht-Boolean.\n\n### Typen\n\n| Typ | Was er mit dem Wert macht |\n| --- | --- |\n| `String`, `Text` | In einen String umgewandelt und getrimmt |\n| `String2` | Wie `String`, aber ein leerer Wert wird zu `null` |\n| `Number`, `Number2`, `Int`, `Integer`, `Float`, `Decimal` | Als Zahl geparst (`'1,5'` ergibt `1.5`); ein Wert, der keine Zahl ist, wird weggelassen |\n| `SmallInt` | Eine Zahl von -32767 bis 32767 |\n| `TinyInt` | Eine Zahl von 0 bis 255 |\n| `Boolean`, `Bool` | `true` oder `false`; Strings wie `'true'`, `'1'` oder `'on'` werden geparst |\n| `Date` | Ein `Date`-Objekt oder `null` |\n| `Email` | Leerzeichen entfernt, kleingeschrieben, muss eine gültige E-Mail sein |\n| `Email2` | Wie `Email`, und der Tag wird entfernt: `name+tag@domain.com` ergibt `name@domain.com` |\n| `Phone` | Leerzeichen entfernt, muss eine gültige Telefonnummer sein |\n| `URL` | Muss eine gültige URL sein |\n| `Zip` | Muss eine gültige Postleitzahl sein |\n| `UID`, `GUID` | Muss eine gültige Total.js-UID oder eine GUID sein; leer wird zu `null` |\n| `Name` | Als Personenname formatiert (`'peter sirka'` ergibt `'Peter Sirka'`) |\n| `Lower`, `Lowercase`, `Upper`, `Uppercase` | In Klein- bzw. Großbuchstaben umgewandelt |\n| `Capitalize`, `Capitalize2` | Erster Buchstabe jedes Wortes oder nur des ersten Wortes großgeschrieben |\n| `Color` | Eine Hex-Farbe: `#RGB`, `#RRGGBB` oder `#RRGGBBAA` |\n| `Icon` | Eine Icon-Klasse wie `ti ti-home` oder `fa fa-check` |\n| `Base64` | Muss ein Base64-String sein; leer wird zu `null` |\n| `JSON` | Ein String, der wie JSON aussieht (siehe `String.isJSON()`); er bleibt Text, und ein leerer Wert wird zu `null` |\n| `IP` | Eine IPv4- oder IPv6-Adresse; getrimmt, ein leerer Wert wird zu `null` |\n| `DataURI` | Muss eine Base64-Data-URI sein; geparst zu `{ type, buffer }` |\n| `DataURI2` | Muss eine Base64-Data-URI sein; bleibt als Originaltext erhalten |\n| `SafeString` | Abgelehnt, wenn er XSS- oder SQL-Injection-Muster enthält |\n| `Search` | Mit `String.toSearch()` in einen Such-String umgewandelt |\n\nStrings, Booleans und Datumswerte sind in der Antwort immer vorhanden: Ein fehlender String ist `''`, ein fehlender Boolean ist `false` und ein fehlendes Datum ist `null`. Eine fehlende Zahl wird weggelassen.\n\n```js\nvar schema = 'color:Color,icon:Icon,photo:DataURI,avatar:DataURI2'.toJSONSchema();\nvar result = schema.transform({ color: '#FF0000', icon: 'ti ti-user', photo: 'data:image/png;base64,iVBORw0KGgo=', avatar: 'data:image/png;base64,iVBORw0KGgo=' });\n// result.response.photo === { type: 'image/png', buffer: <Buffer> }\n// result.response.avatar === 'data:image/png;base64,iVBORw0KGgo='\n```\n\n### Enums, Arrays und verschachtelte Objekte\n\n```js\nvar schema = `*title:String(100)\n\tstatus:{draft|published|archived}\n\ttags:[String]\n\tratings:[Number]\n\tauthor:{name:String,email:Email}\n\titems:[{name:String,price:Number}]`.toJSONSchema();\n```\n\nEin Enum akzeptiert `|` oder `;` zwischen den Werten. Ein Array-Feld akzeptiert nur ein Array; jedes Element wird in den Typ umgewandelt. `[{...}]` ist ein Array verschachtelter Objekte. Ein verschachteltes Objekt kann weitere verschachtelte Objekte und Arrays enthalten, in beliebiger Tiefe:\n\n```js\nvar schema = 'order:{number:String,lines:[{sku:String,qty:Number}],shipping:{address:{street:String,city:String}}}'.toJSONSchema();\n```\n\nDie Fehler eines verschachtelten Feldes haben einen Pfad wie `author.email`, `items[1].price` oder `order.shipping.address.city`.\n\n### Registrierte Schemas\n\n`NEWSCHEMA(name, schema)` registriert ein Inline-Schema unter einem Namen. Andere Schemas und Aktionen verwenden es mit `@name`.\n\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\n\nNEWSCHEMA('@Customer', `*name:String(50)\n\t*email:Email\n\taddress:@Address\n\tbranches:[@Address]`);\n```\n\nAlle registrierten Schemas stehen im Objekt `F.jsonschemas`. `'...'.toJSONSchema(name)` registriert das Schema ebenfalls unter `name`.\n\n## Schemas in Aktionen\n\nDie Optionen `input`, `output`, `query` und `params` einer Aktion nehmen ein Inline-Schema oder den Namen eines registrierten Schemas mit `@`. Die Eingabe wird validiert, bevor die Aktion läuft; schlägt sie fehl, läuft die Aktion nicht, und der Client erhält die Fehler. Siehe [Aktionen](../../guides/actions/).\n\n```js\nNEWACTION('Customers/create', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t// model is the validated object\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Customers/list', {\n\tquery: 'page:Number,limit:Number,search:Search',\n\taction: function($) {\n\t\t// $.query.page is a number\n\t\t$.callback([]);\n\t}\n});\n```\n\nFehler aus `query` haben Namen, die mit `query.` beginnen, und Fehler aus `params` beginnen mit `params.`. Eine Aktion mit `partial: true` validiert nur die Felder, die in der Eingabe vorhanden sind, und eignet sich daher für Aktualisierungen weniger Felder.\n\n## JSON-Schemas\n\nEin JSON-Schema ist ein Objekt. Registriere es mit `F.newjsonschema()` oder lege es in den Ordner `jsonschemas/`.\n\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tsku: { type: 'string', subtype: 'uid' },\n\t\tprice: { type: 'number', minimum: 1 },\n\t\tstock: { type: 'number', subtype: 'smallint' },\n\t\ttags: { type: 'array', items: { type: 'string' }, uniqueItems: true },\n\t\tsupplier: { type: 'object', $ref: '#/definitions/Supplier' }\n\t},\n\trequired: ['name', 'price'],\n\tdefinitions: {\n\t\tSupplier: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { name: { type: 'string' }, email: { type: 'string', subtype: 'email' } },\n\t\t\trequired: ['name']\n\t\t}\n\t}\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nUnterstützte Typen: `object`, `array`, `string`, `number` (oder `integer`), `boolean` (oder `bool`) und `date`. Unterstützte Schlüsselwörter: `properties`, `required`, `minLength`, `maxLength`, `enum`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `items`, `minItems`, `uniqueItems`, `$ref`, `definitions` und zwei Total.js-Schlüsselwörter: `subtype` (ein Typ aus der Inline-Tabelle, etwa `email`, `uid`, `ip` oder `json`, dazu `ipaddress`, das dasselbe wie `ip` ist) und `nullable` (ein leerer String wird zu `null`).\n\n### Der Ordner jsonschemas\n\nBeim Start der Anwendung wird jede `.json`-Datei in `jsonschemas/` geparst und mit dem Dateinamen als Namen registriert. Der Ordner wird vor den Ordnern mit Code geladen, daher kann `jsonschemas/Address.json` in jeder Aktion als `@Address` verwendet werden.\n\n## Fehler und ErrorBuilder\n\n`ErrorBuilder` sammelt Fehler. Die Validierung füllt ihn, und du kannst ihn auch selbst verwenden.\n\n```js\nvar err = new ErrorBuilder();\nerr.push('The order is closed');\nerr.push2('email');\t  // a field error\nerr.output();\n// [{ error: 'The order is closed' }, { name: 'email', error: 'The field \"email\" is invalid' }]\n```\n\nDie Meldung eines Feldfehlers wird in dieser Reihenfolge gesucht: die `//`-Meldung des Schemas, eine Ressource mit dem Feldnamen (siehe [Lokalisierung](../../guides/localization/)) und der Text `The field \"name\" is invalid`. Eine hinzugefügte Zahl ab 400 setzt den HTTP-Status (`err.push(404)`); andernfalls ist der Status 400. Antwortet eine Aktion oder ein Controller mit einem ErrorBuilder, erhält der Client das JSON-Array von `output()` mit diesem Status.\n\n## KI-Tools\n\nZwei Methoden eines Inline-Schemas beschreiben es für KI-Modelle: Die Felder werden zu den Parametern, die `//`-Meldungen zu deren Beschreibungen, und die erforderlichen Felder bleiben erforderlich. Siehe [KI-Modelle](../../guides/ai-models/).\n\n`schema.toAITool(name)` gibt eine Tool-Definition im üblichen Funktionsformat zurück:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar tool = schema.toAITool('weather');\n// { type: 'function', function: { name: 'weather', parameters: { type: 'object', properties: {...}, required: ['city'] } } }\n```\n\n`schema.toAIObject(name, [description])` gibt ein Standard-JSON-Schema-Objekt mit einem Namen zurück, zum Beispiel für eine strukturierte Antwort eines Modells. Datumswerte erhalten `format: 'date-time'`, E-Mails `format: 'email'`, Enums ihre Werte, und Felder, die `null` sein können, den Typ `['string', 'null']`:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// { name: 'forecast', description: 'The weather forecast for a city', type: 'object', additionalProperties: false,\n//   properties: { city: { type: 'string', description: 'The name of the city' }, days: {...} }, required: ['city'] }\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwVPESx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Esquemas y validación","summary":"Esquemas inline, esquemas JSON y ErrorBuilder: cómo Total.js 5 valida y convierte los datos.","markdown":"---\ntitle: \"Esquemas y validación\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/json-schemas/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Esquemas y validación\n\n> Esquemas inline, esquemas JSON y ErrorBuilder: cómo Total.js 5 valida y convierte los datos.\n\nTotal.js 5 valida los datos con **esquemas**. Un esquema describe los campos de un objeto, convierte cada valor a su tipo y recoge los errores. El mismo objeto de esquema funciona en acciones, en tu propio código y en los archivos de la carpeta `jsonschemas/`.\n\nPuedes escribir un esquema de dos formas:\n\n- un **esquema en línea**, un string corto como `'*name:String,email:Email,age:Number'`;\n- un **esquema JSON**, un objeto plano con `type`, `properties`, `required` y otras palabras clave.\n\nUn esquema en línea se convierte en un objeto de esquema JSON, así ambas formas terminan en el mismo formato y el mismo validador.\n\n## Esquemas en línea\n\nUn esquema en línea es una lista de campos separados por comas o saltos de línea. Cada campo es `name:Type`. Los espacios alrededor de los nombres y los tipos se ignoran y los nombres de tipo no distinguen mayúsculas de minúsculas (`Email`, `email` y `EMAIL` son lo mismo). Un campo sin tipo es un `String`, y un tipo desconocido también es un `String`.\n\n```js\nvar schema = '*name:String,*email:Email,age:Number,newsletter:Boolean'.toJSONSchema();\n\nvar result = schema.transform({ name: '  Peter ', email: 'PETER@EXAMPLE.COM', age: '33' });\n// result.error === null\n// result.response === { name: 'Peter', email: 'peter@example.com', age: 33, newsletter: false }\n```\n\n`transform()` devuelve un objeto con dos claves: `response` (el objeto limpio) y `error` (un [ErrorBuilder](#errors-and-errorbuilder) con los errores, o `null`). Solo los campos del esquema se copian en la respuesta; las demás claves de la entrada se descartan.\n\n### Modificadores\n\n| Sintaxis | Significado |\n| --- | --- |\n| `*name:String` | El campo es obligatorio (`!name:String` es lo mismo) |\n| `name:String(50)` | El texto puede tener como máximo 50 caracteres |\n| `tags:[String]` | Un array de valores del tipo |\n| `type:{draft\\|published}` | El valor debe ser uno de los valores listados |\n| `address:{street:String,city:String}` | Un objeto anidado con sus propios campos |\n| `address:@Address` | Un objeto anidado validado por el esquema registrado `Address` |\n| `name:String // Enter your name` | Un mensaje de error personalizado para el campo |\n\nUn campo obligatorio falla cuando su valor está vacío: un string vacío, un número que falta, un booleano que falta o una fecha que no se puede parsear. `0` es un número obligatorio válido y `false` es un booleano obligatorio válido.\n\n### Tipos\n\n| Tipo | Qué hace con el valor |\n| --- | --- |\n| `String`, `Text` | Se convierte a string y se recorta |\n| `String2` | Como `String`, pero un valor vacío se convierte en `null` |\n| `Number`, `Number2`, `Int`, `Integer`, `Float`, `Decimal` | Se parsea como número (`'1,5'` da `1.5`); un valor que no es un número se omite |\n| `SmallInt` | Un número de -32767 a 32767 |\n| `TinyInt` | Un número de 0 a 255 |\n| `Boolean`, `Bool` | `true` o `false`; se parsean strings como `'true'`, `'1'` u `'on'` |\n| `Date` | Un objeto `Date`, o `null` |\n| `Email` | Sin espacios, en minúsculas, debe ser un e-mail válido |\n| `Email2` | Como `Email`, y se quita la etiqueta: `name+tag@domain.com` da `name@domain.com` |\n| `Phone` | Sin espacios, debe ser un número de teléfono válido |\n| `URL` | Debe ser una URL válida |\n| `Zip` | Debe ser un código postal válido |\n| `UID`, `GUID` | Debe ser un UID de Total.js o un GUID válido; vacío se convierte en `null` |\n| `Name` | Se formatea como nombre de persona (`'peter sirka'` da `'Peter Sirka'`) |\n| `Lower`, `Lowercase`, `Upper`, `Uppercase` | Se convierte a minúsculas o mayúsculas |\n| `Capitalize`, `Capitalize2` | Primera letra de cada palabra, o solo de la primera palabra, en mayúscula |\n| `Color` | Un color hexadecimal: `#RGB`, `#RRGGBB` o `#RRGGBBAA` |\n| `Icon` | Una clase de icono como `ti ti-home` o `fa fa-check` |\n| `Base64` | Debe ser un string Base64; vacío se convierte en `null` |\n| `JSON` | Un string con aspecto de JSON (consulta `String.isJSON()`); se mantiene como texto y vacío se convierte en `null` |\n| `IP` | Una dirección IPv4 o IPv6; se recorta, vacío se convierte en `null` |\n| `DataURI` | Debe ser un data URI Base64; se parsea en `{ type, buffer }` |\n| `DataURI2` | Debe ser un data URI Base64; se mantiene como el texto original |\n| `SafeString` | Se rechaza cuando contiene patrones de XSS o de inyección SQL |\n| `Search` | Se convierte en un string de búsqueda con `String.toSearch()` |\n\nLos strings, booleanos y fechas siempre están presentes en la respuesta: un string que falta es `''`, un booleano que falta es `false` y una fecha que falta es `null`. Un número que falta se omite.\n\n```js\nvar schema = 'color:Color,icon:Icon,photo:DataURI,avatar:DataURI2'.toJSONSchema();\nvar result = schema.transform({ color: '#FF0000', icon: 'ti ti-user', photo: 'data:image/png;base64,iVBORw0KGgo=', avatar: 'data:image/png;base64,iVBORw0KGgo=' });\n// result.response.photo === { type: 'image/png', buffer: <Buffer> }\n// result.response.avatar === 'data:image/png;base64,iVBORw0KGgo='\n```\n\n### Enums, arrays y objetos anidados\n\n```js\nvar schema = `*title:String(100)\n\tstatus:{draft|published|archived}\n\ttags:[String]\n\tratings:[Number]\n\tauthor:{name:String,email:Email}\n\titems:[{name:String,price:Number}]`.toJSONSchema();\n```\n\nUn enum acepta `|` o `;` entre los valores. Un campo array acepta solo un array; cada elemento se convierte al tipo. `[{...}]` es un array de objetos anidados. Un objeto anidado puede contener más objetos anidados y arrays, a cualquier profundidad:\n\n```js\nvar schema = 'order:{number:String,lines:[{sku:String,qty:Number}],shipping:{address:{street:String,city:String}}}'.toJSONSchema();\n```\n\nLos errores de un campo anidado tienen una ruta como `author.email`, `items[1].price` u `order.shipping.address.city`.\n\n### Esquemas registrados\n\n`NEWSCHEMA(name, schema)` registra un esquema en línea bajo un nombre. Otros esquemas y acciones lo usan con `@name`.\n\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\n\nNEWSCHEMA('@Customer', `*name:String(50)\n\t*email:Email\n\taddress:@Address\n\tbranches:[@Address]`);\n```\n\nTodos los esquemas registrados están en el objeto `F.jsonschemas`. `'...'.toJSONSchema(name)` también registra el esquema bajo `name`.\n\n## Esquemas en acciones\n\nLas opciones `input`, `output`, `query` y `params` de una acción reciben un esquema en línea o el nombre de un esquema registrado con `@`. La entrada se valida antes de que se ejecute la acción; cuando falla, la acción no se ejecuta y el cliente recibe los errores. Consulta [Acciones](../../guides/actions/).\n\n```js\nNEWACTION('Customers/create', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t// model is the validated object\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Customers/list', {\n\tquery: 'page:Number,limit:Number,search:Search',\n\taction: function($) {\n\t\t// $.query.page is a number\n\t\t$.callback([]);\n\t}\n});\n```\n\nLos errores de `query` tienen nombres que empiezan por `query.` y los errores de `params` empiezan por `params.`. Una acción con `partial: true` valida solo los campos que existen en la entrada, así que sirve para actualizar unos pocos campos.\n\n## Esquemas JSON\n\nUn esquema JSON es un objeto. Regístralo con `F.newjsonschema()`, o ponlo en la carpeta `jsonschemas/`.\n\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tsku: { type: 'string', subtype: 'uid' },\n\t\tprice: { type: 'number', minimum: 1 },\n\t\tstock: { type: 'number', subtype: 'smallint' },\n\t\ttags: { type: 'array', items: { type: 'string' }, uniqueItems: true },\n\t\tsupplier: { type: 'object', $ref: '#/definitions/Supplier' }\n\t},\n\trequired: ['name', 'price'],\n\tdefinitions: {\n\t\tSupplier: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { name: { type: 'string' }, email: { type: 'string', subtype: 'email' } },\n\t\t\trequired: ['name']\n\t\t}\n\t}\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nTipos admitidos: `object`, `array`, `string`, `number` (o `integer`), `boolean` (o `bool`) y `date`. Palabras clave admitidas: `properties`, `required`, `minLength`, `maxLength`, `enum`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `items`, `minItems`, `uniqueItems`, `$ref`, `definitions`, y dos palabras clave de Total.js: `subtype` (un tipo de la tabla de esquemas en línea, como `email`, `uid`, `ip` o `json`, además de `ipaddress`, igual que `ip`) y `nullable` (un string vacío se convierte en `null`).\n\n### La carpeta jsonschemas\n\nAl iniciar la aplicación, cada archivo `.json` de `jsonschemas/` se parsea y se registra con el nombre del archivo como nombre. La carpeta se carga antes que las carpetas con código, así que `jsonschemas/Address.json` se puede usar como `@Address` en cualquier acción.\n\n## Errores y ErrorBuilder\n\n`ErrorBuilder` recoge errores. La validación lo rellena, y puedes usarlo por tu cuenta.\n\n```js\nvar err = new ErrorBuilder();\nerr.push('The order is closed');\nerr.push2('email');\t  // a field error\nerr.output();\n// [{ error: 'The order is closed' }, { name: 'email', error: 'The field \"email\" is invalid' }]\n```\n\nEl mensaje de un error de campo se busca en este orden: el mensaje `//` del esquema, un recurso con el nombre del campo (consulta [Localización](../../guides/localization/)) y el texto `The field \"name\" is invalid`. Un número añadido a partir de 400 establece el estado HTTP (`err.push(404)`); en otro caso el estado es 400. Cuando una acción o un controlador responde con un ErrorBuilder, el cliente recibe el array JSON de `output()` con ese estado.\n\n## Herramientas de IA\n\nDos métodos de un esquema en línea lo describen para modelos de IA: los campos se convierten en los parámetros, los mensajes `//` en sus descripciones y los campos obligatorios siguen siendo obligatorios. Consulta [Modelos de IA](../../guides/ai-models/).\n\n`schema.toAITool(name)` devuelve una definición de herramienta en el formato de función habitual:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar tool = schema.toAITool('weather');\n// { type: 'function', function: { name: 'weather', parameters: { type: 'object', properties: {...}, required: ['city'] } } }\n```\n\n`schema.toAIObject(name, [description])` devuelve un objeto JSON Schema estándar con un nombre, por ejemplo para una respuesta estructurada de un modelo. Las fechas reciben `format: 'date-time'`, los e-mails `format: 'email'`, los enums sus valores, y los campos que pueden ser `null` el tipo `['string', 'null']`:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// { name: 'forecast', description: 'The weather forecast for a city', type: 'object', additionalProperties: false,\n//   properties: { city: { type: 'string', description: 'The name of the city' }, days: {...} }, required: ['city'] }\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwVPESx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Schémas et validation","summary":"Schémas inline, schémas JSON et ErrorBuilder : comment Total.js 5 valide et convertit les données.","markdown":"---\ntitle: \"Schémas et validation\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/json-schemas/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Schémas et validation\n\n> Schémas inline, schémas JSON et ErrorBuilder : comment Total.js 5 valide et convertit les données.\n\nTotal.js 5 valide les données avec des **schémas**. Un schéma décrit les champs d'un objet, convertit chaque valeur dans son type et collecte les erreurs. Le même objet schéma fonctionne dans les actions, dans ton propre code et dans les fichiers du dossier `jsonschemas/`.\n\nTu peux écrire un schéma de deux façons :\n\n- un **schéma en ligne**, une courte chaîne comme `'*name:String,email:Email,age:Number'` ;\n- un **schéma JSON**, un objet simple avec `type`, `properties`, `required` et d'autres mots-clés.\n\nUn schéma en ligne est transformé en objet schéma JSON : les deux façons aboutissent donc au même format et au même validateur.\n\n## Schémas en ligne\n\nUn schéma en ligne est une liste de champs séparés par des virgules ou des sauts de ligne. Chaque champ s'écrit `name:Type`. Les espaces autour des noms et des types sont ignorés et les noms de types ne sont pas sensibles à la casse (`Email`, `email` et `EMAIL` sont identiques). Un champ sans type est un `String`, et un type inconnu est aussi un `String`.\n\n```js\nvar schema = '*name:String,*email:Email,age:Number,newsletter:Boolean'.toJSONSchema();\n\nvar result = schema.transform({ name: '  Peter ', email: 'PETER@EXAMPLE.COM', age: '33' });\n// result.error === null\n// result.response === { name: 'Peter', email: 'peter@example.com', age: 33, newsletter: false }\n```\n\n`transform()` renvoie un objet avec deux clés : `response` (l'objet nettoyé) et `error` (un [ErrorBuilder](#errors-and-errorbuilder) avec les erreurs, ou `null`). Seuls les champs du schéma sont copiés dans la réponse ; les autres clés de l'entrée sont supprimées.\n\n### Modificateurs\n\n| Syntaxe | Signification |\n| --- | --- |\n| `*name:String` | Le champ est obligatoire (`!name:String` est identique) |\n| `name:String(50)` | Le texte peut contenir au maximum 50 caractères |\n| `tags:[String]` | Un tableau de valeurs du type |\n| `type:{draft\\|published}` | La valeur doit être l'une des valeurs listées |\n| `address:{street:String,city:String}` | Un objet imbriqué avec ses propres champs |\n| `address:@Address` | Un objet imbriqué validé par le schéma enregistré `Address` |\n| `name:String // Enter your name` | Un message d'erreur personnalisé pour le champ |\n\nUn champ obligatoire échoue lorsque sa valeur est vide : une chaîne vide, un nombre manquant, un booléen manquant ou une date qui ne peut pas être analysée. `0` est un nombre obligatoire valide et `false` est un booléen obligatoire valide.\n\n### Types\n\n| Type | Ce qu'il fait de la valeur |\n| --- | --- |\n| `String`, `Text` | Convertie en chaîne et débarrassée des espaces aux extrémités |\n| `String2` | Comme `String`, mais une valeur vide devient `null` |\n| `Number`, `Number2`, `Int`, `Integer`, `Float`, `Decimal` | Analysée comme un nombre (`'1,5'` donne `1.5`) ; une valeur qui n'est pas un nombre est omise |\n| `SmallInt` | Un nombre de -32767 à 32767 |\n| `TinyInt` | Un nombre de 0 à 255 |\n| `Boolean`, `Bool` | `true` ou `false` ; les chaînes comme `'true'`, `'1'` ou `'on'` sont analysées |\n| `Date` | Un objet `Date`, ou `null` |\n| `Email` | Espaces supprimés, en minuscules, doit être un e-mail valide |\n| `Email2` | Comme `Email`, et le tag est retiré : `name+tag@domain.com` donne `name@domain.com` |\n| `Phone` | Espaces supprimés, doit être un numéro de téléphone valide |\n| `URL` | Doit être une URL valide |\n| `Zip` | Doit être un code postal valide |\n| `UID`, `GUID` | Doit être un UID Total.js ou un GUID valide ; une valeur vide devient `null` |\n| `Name` | Formatée comme un nom de personne (`'peter sirka'` donne `'Peter Sirka'`) |\n| `Lower`, `Lowercase`, `Upper`, `Uppercase` | Convertie en minuscules ou en majuscules |\n| `Capitalize`, `Capitalize2` | Première lettre de chaque mot, ou seulement du premier mot, en majuscule |\n| `Color` | Une couleur hexadécimale : `#RGB`, `#RRGGBB` ou `#RRGGBBAA` |\n| `Icon` | Une classe d'icône comme `ti ti-home` ou `fa fa-check` |\n| `Base64` | Doit être une chaîne Base64 ; une valeur vide devient `null` |\n| `JSON` | Une chaîne qui ressemble à du JSON (voir `String.isJSON()`) ; elle est conservée sous forme de texte et une valeur vide devient `null` |\n| `IP` | Une adresse IPv4 ou IPv6 ; débarrassée des espaces aux extrémités, une valeur vide devient `null` |\n| `DataURI` | Doit être une data URI Base64 ; analysée en `{ type, buffer }` |\n| `DataURI2` | Doit être une data URI Base64 ; conservée sous forme du texte d'origine |\n| `SafeString` | Rejetée lorsqu'elle contient des motifs de XSS ou d'injection SQL |\n| `Search` | Convertie en chaîne de recherche avec `String.toSearch()` |\n\nLes chaînes, les booléens et les dates sont toujours présents dans la réponse : une chaîne manquante vaut `''`, un booléen manquant vaut `false` et une date manquante vaut `null`. Un nombre manquant est omis.\n\n```js\nvar schema = 'color:Color,icon:Icon,photo:DataURI,avatar:DataURI2'.toJSONSchema();\nvar result = schema.transform({ color: '#FF0000', icon: 'ti ti-user', photo: 'data:image/png;base64,iVBORw0KGgo=', avatar: 'data:image/png;base64,iVBORw0KGgo=' });\n// result.response.photo === { type: 'image/png', buffer: <Buffer> }\n// result.response.avatar === 'data:image/png;base64,iVBORw0KGgo='\n```\n\n### Enums, tableaux et objets imbriqués\n\n```js\nvar schema = `*title:String(100)\n\tstatus:{draft|published|archived}\n\ttags:[String]\n\tratings:[Number]\n\tauthor:{name:String,email:Email}\n\titems:[{name:String,price:Number}]`.toJSONSchema();\n```\n\nUn enum accepte `|` ou `;` entre les valeurs. Un champ tableau n'accepte qu'un tableau ; chaque élément est converti dans le type. `[{...}]` est un tableau d'objets imbriqués. Un objet imbriqué peut contenir d'autres objets et tableaux imbriqués, à n'importe quelle profondeur :\n\n```js\nvar schema = 'order:{number:String,lines:[{sku:String,qty:Number}],shipping:{address:{street:String,city:String}}}'.toJSONSchema();\n```\n\nLes erreurs d'un champ imbriqué ont un chemin comme `author.email`, `items[1].price` ou `order.shipping.address.city`.\n\n### Schémas enregistrés\n\n`NEWSCHEMA(name, schema)` enregistre un schéma en ligne sous un nom. Les autres schémas et les actions l'utilisent avec `@name`.\n\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\n\nNEWSCHEMA('@Customer', `*name:String(50)\n\t*email:Email\n\taddress:@Address\n\tbranches:[@Address]`);\n```\n\nTous les schémas enregistrés se trouvent dans l'objet `F.jsonschemas`. `'...'.toJSONSchema(name)` enregistre aussi le schéma sous `name`.\n\n## Schémas dans les actions\n\nLes options `input`, `output`, `query` et `params` d'une action acceptent un schéma en ligne ou le nom d'un schéma enregistré avec `@`. L'entrée est validée avant l'exécution de l'action ; en cas d'échec, l'action ne s'exécute pas et le client reçoit les erreurs. Voir [Actions](../../guides/actions/).\n\n```js\nNEWACTION('Customers/create', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t// model is the validated object\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Customers/list', {\n\tquery: 'page:Number,limit:Number,search:Search',\n\taction: function($) {\n\t\t// $.query.page is a number\n\t\t$.callback([]);\n\t}\n});\n```\n\nLes erreurs de `query` ont des noms qui commencent par `query.` et les erreurs de `params` commencent par `params.`. Une action avec `partial: true` ne valide que les champs présents dans l'entrée : elle convient donc aux mises à jour de quelques champs.\n\n## Schémas JSON\n\nUn schéma JSON est un objet. Enregistre-le avec `F.newjsonschema()`, ou place-le dans le dossier `jsonschemas/`.\n\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tsku: { type: 'string', subtype: 'uid' },\n\t\tprice: { type: 'number', minimum: 1 },\n\t\tstock: { type: 'number', subtype: 'smallint' },\n\t\ttags: { type: 'array', items: { type: 'string' }, uniqueItems: true },\n\t\tsupplier: { type: 'object', $ref: '#/definitions/Supplier' }\n\t},\n\trequired: ['name', 'price'],\n\tdefinitions: {\n\t\tSupplier: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { name: { type: 'string' }, email: { type: 'string', subtype: 'email' } },\n\t\t\trequired: ['name']\n\t\t}\n\t}\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nTypes pris en charge : `object`, `array`, `string`, `number` (ou `integer`), `boolean` (ou `bool`) et `date`. Mots-clés pris en charge : `properties`, `required`, `minLength`, `maxLength`, `enum`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `items`, `minItems`, `uniqueItems`, `$ref`, `definitions`, et deux mots-clés Total.js : `subtype` (un type du tableau des schémas en ligne, comme `email`, `uid`, `ip` ou `json`, ainsi que `ipaddress`, identique à `ip`) et `nullable` (une chaîne vide devient `null`).\n\n### Le dossier jsonschemas\n\nAu démarrage de l'application, chaque fichier `.json` de `jsonschemas/` est analysé et enregistré avec le nom du fichier comme nom. Le dossier est chargé avant les dossiers contenant du code : `jsonschemas/Address.json` peut donc être utilisé sous la forme `@Address` dans n'importe quelle action.\n\n## Erreurs et ErrorBuilder\n\n`ErrorBuilder` collecte les erreurs. La validation le remplit, et tu peux l'utiliser toi-même.\n\n```js\nvar err = new ErrorBuilder();\nerr.push('The order is closed');\nerr.push2('email');\t  // a field error\nerr.output();\n// [{ error: 'The order is closed' }, { name: 'email', error: 'The field \"email\" is invalid' }]\n```\n\nLe message d'une erreur de champ est recherché dans cet ordre : le message `//` du schéma, une ressource portant le nom du champ (voir [Localisation](../../guides/localization/)), et le texte `The field \"name\" is invalid`. Un nombre ajouté à partir de 400 définit le statut HTTP (`err.push(404)`) ; sinon le statut est 400. Lorsqu'une action ou un contrôleur répond avec un ErrorBuilder, le client reçoit le tableau JSON de `output()` avec ce statut.\n\n## Outils d'IA\n\nDeux méthodes d'un schéma en ligne le décrivent pour les modèles d'IA : les champs deviennent les paramètres, les messages `//` deviennent leurs descriptions et les champs obligatoires restent obligatoires. Voir [Modèles d'IA](../../guides/ai-models/).\n\n`schema.toAITool(name)` renvoie une définition d'outil dans le format de fonction courant :\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar tool = schema.toAITool('weather');\n// { type: 'function', function: { name: 'weather', parameters: { type: 'object', properties: {...}, required: ['city'] } } }\n```\n\n`schema.toAIObject(name, [description])` renvoie un objet JSON Schema standard avec un nom, par exemple pour une réponse structurée d'un modèle. Les dates reçoivent `format: 'date-time'`, les e-mails `format: 'email'`, les enums leurs valeurs, et les champs qui peuvent valoir `null` le type `['string', 'null']` :\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// { name: 'forecast', description: 'The weather forecast for a city', type: 'object', additionalProperties: false,\n//   properties: { city: { type: 'string', description: 'The name of the city' }, days: {...} }, required: ['city'] }\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwVPESx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Schemi e validazione","summary":"Schemi inline, schemi JSON ed ErrorBuilder: come Total.js 5 valida e converte i dati.","markdown":"---\ntitle: Schemi e validazione\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/json-schemas/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Schemi e validazione\n\n> Schemi inline, schemi JSON ed ErrorBuilder: come Total.js 5 valida e converte i dati.\n\nTotal.js 5 valida i dati con gli **schemi**. Uno schema descrive i campi di un oggetto, converte ogni valore nel suo tipo e raccoglie gli errori. Lo stesso oggetto schema funziona nelle azioni, nel tuo codice e nei file della cartella `jsonschemas/`.\n\nPuoi scrivere uno schema in due modi:\n\n- uno **schema inline**, una breve stringa come `'*name:String,email:Email,age:Number'`;\n- uno **schema JSON**, un semplice oggetto con `type`, `properties`, `required` e altre parole chiave.\n\nUno schema inline viene trasformato in un oggetto schema JSON, quindi entrambi i modi arrivano allo stesso formato e allo stesso validatore.\n\n## Schemi inline\n\nUno schema inline è un elenco di campi separati da virgole o a capo. Ogni campo è `name:Type`. Gli spazi attorno a nomi e tipi vengono ignorati e i nomi dei tipi non distinguono maiuscole e minuscole (`Email`, `email` ed `EMAIL` sono uguali). Un campo senza tipo è uno `String`, e anche un tipo sconosciuto è uno `String`.\n\n```js\nvar schema = '*name:String,*email:Email,age:Number,newsletter:Boolean'.toJSONSchema();\n\nvar result = schema.transform({ name: '  Peter ', email: 'PETER@EXAMPLE.COM', age: '33' });\n// result.error === null\n// result.response === { name: 'Peter', email: 'peter@example.com', age: 33, newsletter: false }\n```\n\n`transform()` restituisce un oggetto con due chiavi: `response` (l'oggetto ripulito) ed `error` (un [ErrorBuilder](#errors-and-errorbuilder) con gli errori, oppure `null`). Nella risposta vengono copiati solo i campi dello schema; le altre chiavi dell'input vengono scartate.\n\n### Modificatori\n\n| Sintassi | Significato |\n| --- | --- |\n| `*name:String` | Il campo è obbligatorio (`!name:String` è equivalente) |\n| `name:String(50)` | Il testo può avere al massimo 50 caratteri |\n| `tags:[String]` | Un array di valori del tipo |\n| `type:{draft\\|published}` | Il valore deve essere uno dei valori elencati |\n| `address:{street:String,city:String}` | Un oggetto annidato con i propri campi |\n| `address:@Address` | Un oggetto annidato validato dallo schema registrato `Address` |\n| `name:String // Enter your name` | Un messaggio di errore personalizzato per il campo |\n\nUn campo obbligatorio fallisce quando il suo valore è vuoto: una stringa vuota, un numero mancante, un booleano mancante o una data che non può essere interpretata. `0` è un numero obbligatorio valido e `false` è un booleano obbligatorio valido.\n\n### Tipi\n\n| Tipo | Cosa fa con il valore |\n| --- | --- |\n| `String`, `Text` | Convertito in stringa e ripulito dagli spazi |\n| `String2` | Come `String`, ma un valore vuoto diventa `null` |\n| `Number`, `Number2`, `Int`, `Integer`, `Float`, `Decimal` | Interpretato come numero (`'1,5'` dà `1.5`); un valore che non è un numero viene omesso |\n| `SmallInt` | Un numero da -32767 a 32767 |\n| `TinyInt` | Un numero da 0 a 255 |\n| `Boolean`, `Bool` | `true` o `false`; stringhe come `'true'`, `'1'` o `'on'` vengono interpretate |\n| `Date` | Un oggetto `Date`, oppure `null` |\n| `Email` | Spazi rimossi, minuscolo, deve essere un'e-mail valida |\n| `Email2` | Come `Email`, e il tag viene rimosso: `name+tag@domain.com` diventa `name@domain.com` |\n| `Phone` | Spazi rimossi, deve essere un numero di telefono valido |\n| `URL` | Deve essere un URL valido |\n| `Zip` | Deve essere un codice postale valido |\n| `UID`, `GUID` | Deve essere un UID Total.js o un GUID valido; vuoto diventa `null` |\n| `Name` | Formattato come nome di persona (`'peter sirka'` dà `'Peter Sirka'`) |\n| `Lower`, `Lowercase`, `Upper`, `Uppercase` | Convertito in minuscolo o maiuscolo |\n| `Capitalize`, `Capitalize2` | Prima lettera di ogni parola, o solo della prima parola, in maiuscolo |\n| `Color` | Un colore esadecimale: `#RGB`, `#RRGGBB` o `#RRGGBBAA` |\n| `Icon` | Una classe di icona come `ti ti-home` o `fa fa-check` |\n| `Base64` | Deve essere una stringa Base64; vuoto diventa `null` |\n| `JSON` | Una stringa che sembra JSON (vedi `String.isJSON()`); viene mantenuta come testo e vuoto diventa `null` |\n| `IP` | Un indirizzo IPv4 o IPv6; ripulito dagli spazi, vuoto diventa `null` |\n| `DataURI` | Deve essere un data URI Base64; interpretato in `{ type, buffer }` |\n| `DataURI2` | Deve essere un data URI Base64; mantenuto come testo originale |\n| `SafeString` | Rifiutato quando contiene pattern di XSS o SQL injection |\n| `Search` | Convertito in una stringa di ricerca con `String.toSearch()` |\n\nStringhe, booleani e date sono sempre presenti nella risposta: una stringa mancante è `''`, un booleano mancante è `false` e una data mancante è `null`. Un numero mancante viene omesso.\n\n```js\nvar schema = 'color:Color,icon:Icon,photo:DataURI,avatar:DataURI2'.toJSONSchema();\nvar result = schema.transform({ color: '#FF0000', icon: 'ti ti-user', photo: 'data:image/png;base64,iVBORw0KGgo=', avatar: 'data:image/png;base64,iVBORw0KGgo=' });\n// result.response.photo === { type: 'image/png', buffer: <Buffer> }\n// result.response.avatar === 'data:image/png;base64,iVBORw0KGgo='\n```\n\n### Enum, array e oggetti annidati\n\n```js\nvar schema = `*title:String(100)\n\tstatus:{draft|published|archived}\n\ttags:[String]\n\tratings:[Number]\n\tauthor:{name:String,email:Email}\n\titems:[{name:String,price:Number}]`.toJSONSchema();\n```\n\nUn enum accetta `|` o `;` tra i valori. Un campo array accetta solo un array; ogni elemento viene convertito nel tipo. `[{...}]` è un array di oggetti annidati. Un oggetto annidato può contenere ulteriori oggetti annidati e array, a qualsiasi profondità:\n\n```js\nvar schema = 'order:{number:String,lines:[{sku:String,qty:Number}],shipping:{address:{street:String,city:String}}}'.toJSONSchema();\n```\n\nGli errori di un campo annidato hanno un percorso come `author.email`, `items[1].price` o `order.shipping.address.city`.\n\n### Schemi registrati\n\n`NEWSCHEMA(name, schema)` registra uno schema inline con un nome. Altri schemi e azioni lo usano con `@name`.\n\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\n\nNEWSCHEMA('@Customer', `*name:String(50)\n\t*email:Email\n\taddress:@Address\n\tbranches:[@Address]`);\n```\n\nTutti gli schemi registrati sono nell'oggetto `F.jsonschemas`. Anche `'...'.toJSONSchema(name)` registra lo schema con il nome `name`.\n\n## Schemi nelle azioni\n\nLe opzioni `input`, `output`, `query` e `params` di un'azione accettano uno schema inline o il nome di uno schema registrato con `@`. L'input viene validato prima che l'azione venga eseguita; quando fallisce, l'azione non viene eseguita e il client riceve gli errori. Vedi [Azioni](../../guides/actions/).\n\n```js\nNEWACTION('Customers/create', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t// model is the validated object\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Customers/list', {\n\tquery: 'page:Number,limit:Number,search:Search',\n\taction: function($) {\n\t\t// $.query.page is a number\n\t\t$.callback([]);\n\t}\n});\n```\n\nGli errori di `query` hanno nomi che iniziano con `query.` e gli errori di `params` iniziano con `params.`. Un'azione con `partial: true` valida solo i campi presenti nell'input, quindi è adatta agli aggiornamenti di pochi campi.\n\n## Schemi JSON\n\nUno schema JSON è un oggetto. Registralo con `F.newjsonschema()`, oppure mettilo nella cartella `jsonschemas/`.\n\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tsku: { type: 'string', subtype: 'uid' },\n\t\tprice: { type: 'number', minimum: 1 },\n\t\tstock: { type: 'number', subtype: 'smallint' },\n\t\ttags: { type: 'array', items: { type: 'string' }, uniqueItems: true },\n\t\tsupplier: { type: 'object', $ref: '#/definitions/Supplier' }\n\t},\n\trequired: ['name', 'price'],\n\tdefinitions: {\n\t\tSupplier: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { name: { type: 'string' }, email: { type: 'string', subtype: 'email' } },\n\t\t\trequired: ['name']\n\t\t}\n\t}\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nTipi supportati: `object`, `array`, `string`, `number` (o `integer`), `boolean` (o `bool`) e `date`. Parole chiave supportate: `properties`, `required`, `minLength`, `maxLength`, `enum`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `items`, `minItems`, `uniqueItems`, `$ref`, `definitions`, e due parole chiave di Total.js: `subtype` (un tipo della tabella inline, come `email`, `uid`, `ip` o `json`, più `ipaddress`, uguale a `ip`) e `nullable` (una stringa vuota diventa `null`).\n\n### La cartella jsonschemas\n\nAll'avvio dell'applicazione, ogni file `.json` in `jsonschemas/` viene interpretato e registrato con il nome del file come nome. La cartella viene caricata prima delle cartelle con il codice, quindi `jsonschemas/Address.json` può essere usato come `@Address` in qualsiasi azione.\n\n## Errori ed ErrorBuilder\n\n`ErrorBuilder` raccoglie gli errori. La validazione lo riempie, e puoi usarlo anche per conto tuo.\n\n```js\nvar err = new ErrorBuilder();\nerr.push('The order is closed');\nerr.push2('email');\t  // a field error\nerr.output();\n// [{ error: 'The order is closed' }, { name: 'email', error: 'The field \"email\" is invalid' }]\n```\n\nIl messaggio di un errore di campo viene cercato in quest'ordine: il messaggio `//` dello schema, una risorsa con il nome del campo (vedi [Localizzazione](../../guides/localization/)) e il testo `The field \"name\" is invalid`. Un numero aggiunto da 400 in su imposta lo stato HTTP (`err.push(404)`); altrimenti lo stato è 400. Quando un'azione o un controller risponde con un ErrorBuilder, il client riceve l'array JSON di `output()` con quello stato.\n\n## Tool AI\n\nDue metodi di uno schema inline lo descrivono per i modelli AI: i campi diventano i parametri, i messaggi `//` diventano le loro descrizioni e i campi obbligatori restano obbligatori. Vedi [Modelli AI](../../guides/ai-models/).\n\n`schema.toAITool(name)` restituisce la definizione di un tool nel formato di funzione comune:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar tool = schema.toAITool('weather');\n// { type: 'function', function: { name: 'weather', parameters: { type: 'object', properties: {...}, required: ['city'] } } }\n```\n\n`schema.toAIObject(name, [description])` restituisce un oggetto JSON Schema standard con un nome, per esempio per una risposta strutturata di un modello. Le date ricevono `format: 'date-time'`, le e-mail `format: 'email'`, gli enum i loro valori e i campi che possono essere `null` il tipo `['string', 'null']`:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// { name: 'forecast', description: 'The weather forecast for a city', type: 'object', additionalProperties: false,\n//   properties: { city: { type: 'string', description: 'The name of the city' }, days: {...} }, required: ['city'] }\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwVPESx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Schémy a validácia","summary":"Inline schémy, JSON schémy a ErrorBuilder: ako Total.js 5 validuje a konvertuje dáta.","markdown":"---\ntitle: \"Schémy a validácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/json-schemas/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Schémy a validácia\n\n> Inline schémy, JSON schémy a ErrorBuilder: ako Total.js 5 validuje a konvertuje dáta.\n\nTotal.js 5 validuje dáta cez **schémy**. Schéma opisuje polia objektu, konvertuje každú hodnotu na jej typ a zbiera chyby. Ten istý objekt schémy funguje v akciách, v tvojom vlastnom kóde aj v súboroch priečinka `jsonschemas/`.\n\nSchému môžeš napísať dvoma spôsobmi:\n\n- **inline schéma**, krátky reťazec ako `'*name:String,email:Email,age:Number'`;\n- **JSON schéma**, obyčajný objekt s `type`, `properties`, `required` a ďalšími kľúčovými slovami.\n\nInline schéma sa premení na objekt JSON schémy, takže oba spôsoby skončia v rovnakom formáte a s rovnakým validátorom.\n\n## Inline schémy\n\nInline schéma je zoznam polí oddelených čiarkami alebo novými riadkami. Každé pole je `name:Type`. Medzery okolo názvov a typov sa ignorujú a názvy typov nerozlišujú veľkosť písmen (`Email`, `email` a `EMAIL` sú to isté). Pole bez typu je `String` a neznámy typ je tiež `String`.\n\n```js\nvar schema = '*name:String,*email:Email,age:Number,newsletter:Boolean'.toJSONSchema();\n\nvar result = schema.transform({ name: '  Peter ', email: 'PETER@EXAMPLE.COM', age: '33' });\n// result.error === null\n// result.response === { name: 'Peter', email: 'peter@example.com', age: 33, newsletter: false }\n```\n\n`transform()` vráti objekt s dvoma kľúčmi: `response` (čistý objekt) a `error` ([ErrorBuilder](#errors-and-errorbuilder) s chybami alebo `null`). Do odpovede sa skopírujú iba polia schémy; ostatné kľúče vstupu sa zahodia.\n\n### Modifikátory\n\n| Syntax | Význam |\n| --- | --- |\n| `*name:String` | Pole je povinné (`!name:String` je to isté) |\n| `name:String(50)` | Text môže mať najviac 50 znakov |\n| `tags:[String]` | Pole hodnôt daného typu |\n| `type:{draft\\|published}` | Hodnota musí byť jedna z uvedených hodnôt |\n| `address:{street:String,city:String}` | Vnorený objekt s vlastnými poliami |\n| `address:@Address` | Vnorený objekt validovaný zaregistrovanou schémou `Address` |\n| `name:String // Enter your name` | Vlastná chybová správa pre pole |\n\nPovinné pole zlyhá, keď je jeho hodnota prázdna: prázdny reťazec, chýbajúce číslo, chýbajúci boolean alebo dátum, ktorý sa nedá spracovať. `0` je platné povinné číslo a `false` je platný povinný boolean.\n\n### Typy\n\n| Typ | Čo robí s hodnotou |\n| --- | --- |\n| `String`, `Text` | Konvertuje na reťazec a oreže |\n| `String2` | Ako `String`, ale prázdna hodnota sa zmení na `null` |\n| `Number`, `Number2`, `Int`, `Integer`, `Float`, `Decimal` | Spracuje ako číslo (`'1,5'` dá `1.5`); hodnota, ktorá nie je číslo, sa vynechá |\n| `SmallInt` | Číslo od -32767 do 32767 |\n| `TinyInt` | Číslo od 0 do 255 |\n| `Boolean`, `Bool` | `true` alebo `false`; reťazce ako `'true'`, `'1'` alebo `'on'` sa spracujú |\n| `Date` | Objekt `Date` alebo `null` |\n| `Email` | Medzery odstránené, malé písmená, musí byť platný e-mail |\n| `Email2` | Ako `Email` a navyše sa odstráni tag: z `name+tag@domain.com` vznikne `name@domain.com` |\n| `Phone` | Medzery odstránené, musí byť platné telefónne číslo |\n| `URL` | Musí byť platná URL |\n| `Zip` | Musí byť platné PSČ |\n| `UID`, `GUID` | Musí byť platné Total.js UID alebo GUID; prázdne sa zmení na `null` |\n| `Name` | Naformátuje ako meno osoby (`'peter sirka'` dá `'Peter Sirka'`) |\n| `Lower`, `Lowercase`, `Upper`, `Uppercase` | Konvertuje na malé alebo veľké písmená |\n| `Capitalize`, `Capitalize2` | Prvé písmeno každého slova, alebo iba prvého slova, veľké |\n| `Color` | Hex farba: `#RGB`, `#RRGGBB` alebo `#RRGGBBAA` |\n| `Icon` | Trieda ikony ako `ti ti-home` alebo `fa fa-check` |\n| `Base64` | Musí byť Base64 reťazec; prázdne sa zmení na `null` |\n| `JSON` | Reťazec, ktorý vyzerá ako JSON (pozri `String.isJSON()`); ponechá sa ako text a prázdne sa zmení na `null` |\n| `IP` | IPv4 alebo IPv6 adresa; oreže sa, prázdna sa zmení na `null` |\n| `DataURI` | Musí byť Base64 data URI; spracuje sa na `{ type, buffer }` |\n| `DataURI2` | Musí byť Base64 data URI; ponechá sa ako pôvodný text |\n| `SafeString` | Odmietne sa, keď obsahuje vzory XSS alebo SQL injection |\n| `Search` | Konvertuje na vyhľadávací reťazec cez `String.toSearch()` |\n\nReťazce, booleany a dátumy sú v odpovedi vždy: chýbajúci reťazec je `''`, chýbajúci boolean je `false` a chýbajúci dátum je `null`. Chýbajúce číslo sa vynechá.\n\n```js\nvar schema = 'color:Color,icon:Icon,photo:DataURI,avatar:DataURI2'.toJSONSchema();\nvar result = schema.transform({ color: '#FF0000', icon: 'ti ti-user', photo: 'data:image/png;base64,iVBORw0KGgo=', avatar: 'data:image/png;base64,iVBORw0KGgo=' });\n// result.response.photo === { type: 'image/png', buffer: <Buffer> }\n// result.response.avatar === 'data:image/png;base64,iVBORw0KGgo='\n```\n\n### Enumy, polia a vnorené objekty\n\n```js\nvar schema = `*title:String(100)\n\tstatus:{draft|published|archived}\n\ttags:[String]\n\tratings:[Number]\n\tauthor:{name:String,email:Email}\n\titems:[{name:String,price:Number}]`.toJSONSchema();\n```\n\nEnum prijíma medzi hodnotami `|` alebo `;`. Pole typu array prijíma iba pole; každá položka sa konvertuje na daný typ. `[{...}]` je pole vnorených objektov. Vnorený objekt môže obsahovať ďalšie vnorené objekty a polia v ľubovoľnej hĺbke:\n\n```js\nvar schema = 'order:{number:String,lines:[{sku:String,qty:Number}],shipping:{address:{street:String,city:String}}}'.toJSONSchema();\n```\n\nChyby vnoreného poľa majú cestu ako `author.email`, `items[1].price` alebo `order.shipping.address.city`.\n\n### Zaregistrované schémy\n\n`NEWSCHEMA(name, schema)` zaregistruje inline schému pod názvom. Ostatné schémy a akcie ju používajú cez `@name`.\n\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\n\nNEWSCHEMA('@Customer', `*name:String(50)\n\t*email:Email\n\taddress:@Address\n\tbranches:[@Address]`);\n```\n\nVšetky zaregistrované schémy sú v objekte `F.jsonschemas`. `'...'.toJSONSchema(name)` zaregistruje schému tiež pod `name`.\n\n## Schémy v akciách\n\nVoľby `input`, `output`, `query` a `params` akcie prijímajú inline schému alebo názov zaregistrovanej schémy s `@`. Vstup sa validuje pred spustením akcie; keď zlyhá, akcia sa nespustí a klient dostane chyby. Pozri [Akcie](../../guides/actions/).\n\n```js\nNEWACTION('Customers/create', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t// model is the validated object\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Customers/list', {\n\tquery: 'page:Number,limit:Number,search:Search',\n\taction: function($) {\n\t\t// $.query.page is a number\n\t\t$.callback([]);\n\t}\n});\n```\n\nChyby z `query` majú názvy, ktoré začínajú `query.`, a chyby z `params` začínajú `params.`. Akcia s `partial: true` validuje iba polia, ktoré vo vstupe existujú, takže sa hodí na aktualizácie niekoľkých polí.\n\n## JSON schémy\n\nJSON schéma je objekt. Zaregistruj ju cez `F.newjsonschema()` alebo ju daj do priečinka `jsonschemas/`.\n\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tsku: { type: 'string', subtype: 'uid' },\n\t\tprice: { type: 'number', minimum: 1 },\n\t\tstock: { type: 'number', subtype: 'smallint' },\n\t\ttags: { type: 'array', items: { type: 'string' }, uniqueItems: true },\n\t\tsupplier: { type: 'object', $ref: '#/definitions/Supplier' }\n\t},\n\trequired: ['name', 'price'],\n\tdefinitions: {\n\t\tSupplier: {\n\t\t\ttype: 'object',\n\t\t\tproperties: { name: { type: 'string' }, email: { type: 'string', subtype: 'email' } },\n\t\t\trequired: ['name']\n\t\t}\n\t}\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nPodporované typy: `object`, `array`, `string`, `number` (alebo `integer`), `boolean` (alebo `bool`) a `date`. Podporované kľúčové slová: `properties`, `required`, `minLength`, `maxLength`, `enum`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `items`, `minItems`, `uniqueItems`, `$ref`, `definitions` a dve kľúčové slová Total.js: `subtype` (typ z inline tabuľky, napríklad `email`, `uid`, `ip` alebo `json`, plus `ipaddress`, to isté ako `ip`) a `nullable` (prázdny reťazec sa zmení na `null`).\n\n### Priečinok jsonschemas\n\nPri štarte aplikácie sa každý súbor `.json` v `jsonschemas/` spracuje a zaregistruje s názvom súboru ako názvom. Priečinok sa načíta pred priečinkami s kódom, takže `jsonschemas/Address.json` sa dá použiť ako `@Address` v ľubovoľnej akcii.\n\n## Chyby a ErrorBuilder\n\n`ErrorBuilder` zbiera chyby. Plní ho validácia a môžeš ho použiť aj sám.\n\n```js\nvar err = new ErrorBuilder();\nerr.push('The order is closed');\nerr.push2('email');\t  // a field error\nerr.output();\n// [{ error: 'The order is closed' }, { name: 'email', error: 'The field \"email\" is invalid' }]\n```\n\nSpráva chyby poľa sa hľadá v tomto poradí: správa `//` zo schémy, zdroj s názvom poľa (pozri [Lokalizácia](../../guides/localization/)) a text `The field \"name\" is invalid`. Vložené číslo od 400 vyššie nastaví HTTP stav (`err.push(404)`); inak je stav 400. Keď akcia alebo kontrolér odpovie cez ErrorBuilder, klient dostane JSON pole z `output()` s týmto stavom.\n\n## AI nástroje\n\nDve metódy inline schémy ju opíšu pre AI modely: polia sa stanú parametrami, správy `//` ich popismi a povinné polia zostanú povinné. Pozri [AI modely](../../guides/ai-models/).\n\n`schema.toAITool(name)` vráti definíciu nástroja v bežnom formáte funkcie:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar tool = schema.toAITool('weather');\n// { type: 'function', function: { name: 'weather', parameters: { type: 'object', properties: {...}, required: ['city'] } } }\n```\n\n`schema.toAIObject(name, [description])` vráti štandardný objekt JSON Schema s názvom, napríklad pre štruktúrovanú odpoveď modelu. Dátumy dostanú `format: 'date-time'`, e-maily `format: 'email'`, enumy svoje hodnoty a polia, ktoré môžu byť `null`, typ `['string', 'null']`:\n\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// { name: 'forecast', description: 'The weather forecast for a city', type: 'object', additionalProperties: false,\n//   properties: { city: { type: 'string', description: 'The name of the city' }, days: {...} }, required: ['city'] }\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"Jafwtz4nx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/views/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Views","summary":"HTML views with @{} commands: rendering, layouts, conditions, loops, sections, meta tags, imports, helpers and templates.","markdown":"---\ntitle: Views\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/views/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Views\n\n> HTML views with @{} commands: rendering, layouts, conditions, loops, sections, meta tags, imports, helpers and templates.\n\nA view is an HTML file in the `/views/` folder with commands between `@{` and `}`. The framework compiles each view into a JavaScript function and runs it with your model. In debug mode a view is compiled again on every render, so you see changes at once; in release mode the compiled function is cached by name and language.\n\n```html\n<!-- /views/index.html -->\n@{title('Products')}\n\n<h1>@{model.name}</h1>\n<ul>\n@{foreach item in model.items}\n\t<li>@{item.name} - @{item.price}</li>\n@{end}\n</ul>\n```\n\n## Rendering a view\n\nIn a route, call `$.view(name, [model])`. The name is the path of the file in `/views/` without `.html`; a name that starts with `#` reads the file from the `/plugins/` folder. The view is rendered into `/views/layout.html`, so create that file first or start the view with `@{layout('')}` (see [Layouts](#layouts)).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /contact/');              // renders /views/contact.html\n\tROUTE('GET /products/', 'products'); // renders /views/products.html\n};\n\nfunction index($) {\n\t$.view('index', { name: 'Shop', items: [{ name: 'Pen', price: 5 }] });\n}\n```\n\nA route without an action renders the view named by the first part of its URL (`index` for `/`), and a route whose action is a string renders the view of that name. The [Routing](../../guides/routing/) guide has the details.\n\n`$.view()` without arguments returns a new view object that you render yourself, and `F.view(name, [model], [prepare])` renders a view outside of a request and returns the HTML string. `F.view()` is what you use for e-mails, files or caches.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n});\n```\n\n## Layouts\n\nEvery view is rendered into a layout. The default layout is `/views/layout.html`; the layout prints the HTML of the view with `@{body}`. If the file does not exist, the request fails with an `ENOENT` error and the client receives a `503` response.\n\n```html\n<!-- /views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nChange the layout in the view with `@{layout('name')}` or in the route with `$.layout('name')`. An empty name (`@{layout('')}`) renders the view without a layout. The view runs first and the layout after it, so the layout can read the title, the sections and the `repository` values that the view set. The layout does not receive the model: pass the values it needs through `repository`.\n\n## Output and escaping\n\n`@{expression}` prints the value of any JavaScript expression, HTML-encoded. `@{!expression}` prints it without encoding. `null` and `undefined` print as an empty string. A route without an action renders its view without a model: `model` is then `undefined`, so `@{model.name}` throws an error and the client receives a `503` response. Pass a model with `$.view(name, model)`, even an empty object.\n\n```html\n<p>@{model.name}</p>             <!-- &lt;b&gt;Peter&lt;/b&gt; -->\n<div>@{!model.html}</div>        <!-- the raw HTML -->\n<span>@{model.items.length}</span>\n@{repository.count = 5}          <!-- an assignment prints nothing -->\n```\n\nThese variables are available in every view:\n\n| Variable | What it contains |\n| --- | --- |\n| `model` | The model passed to the view |\n| `repository` | An object shared by the view, its partial views and the layout |\n| `config` | The configuration (`CONF`) |\n| `controller` | The controller of the request (`undefined` in `F.view()`) |\n| `query`, `body`, `files` | The query string, the parsed body and the uploaded files of the request |\n| `user`, `session` | The user and the session of the request |\n| `language` | The language of the view: of the request, or `view.language` set for `F.view()` (an empty string by default) |\n| `url` | The path of the request, without the query string (`undefined` in `F.view()`) |\n| `helpers` | The custom helpers (`DEF.helpers`) |\n\nGlobal objects such as `MAIN`, `REPO`, `FUNC`, `CONF` and `MODS` work as well. `@{'%name'}` prints a configuration value that is read once, when the view is compiled.\n\n`@{hostname()}` prints the absolute URL of the current page and `@{hostname('/path/')}` the absolute URL of another path, for example for canonical links and share images:\n\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n## Conditions and loops\n\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n```\n\n`@{endif}` is the same as `@{fi}`. Inside `@{foreach}`, `@{index}` is the zero-based position, and `@{continue}` and `@{break}` work as in JavaScript. A loop over an object (not an array) gives items with `key` and `value`.\n\n## Partial views and sections\n\n`@{view('name', [model])}` renders another view in place, with its own model and without a layout. A section collects HTML in the view and prints it elsewhere, usually in the layout:\n\n```html\n<!-- in the view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- in the layout -->\n@{section('scripts')}\n```\n\n## Title, meta tags and imports\n\n`@{title('Text')}`, `@{description('Text')}` and `@{keywords('a, b')}` store the values in `repository`; `@{title2('Text')}` appends text to the title, and `@{meta(title, description, keywords, image)}` sets them all at once. The values are stored as they are and HTML-encoded once, when they are printed. The layout prints them with `@{import('meta')}` (or `@{meta}`): a `<title>` tag, the description and keywords meta tags and the `og:image` tags. The title gets ` - ` and `CONF.name` appended, except on the home page and when `CONF.$customtitles` is `true`.\n\n`@{import()}` creates the tags for your static files. A `.css` name is looked up in `/css/` and other names in `/js/`; a path that starts with `/` is used as it is. Several names joined with `+` are merged into one minified file, which the framework serves itself. An `@` before a name appends `?ts=` with the start time of the application, so browsers load the new file after each restart.\n\n```html\n@{import('meta', 'favicon.ico', 'default.css', '@app.js')}\n@{import('reset.css + layout.css + forms.css')}\n@{import('/vendor/editor.js')}\n```\n\n## Helpers\n\nA helper is a function you can call from every view. Register it in `DEF.helpers`; inside it `this` is the view, so `this.model` and `this.repository` are available. Call it by its name, with `@{helpers.name()}`, or with `@{helper('name', ...)}`. A helper returns the HTML it prints, without encoding.\n\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n```\n\n```html\n<span>@{price(model.price)}</span>\n```\n\n## Localization\n\nText in `@(...)` is translated into the language of the view when the view is compiled, so every language has its own compiled copy. The language comes from the request; set `view.language` for `F.view()`. The [Localization](../../guides/localization/) guide explains the resource files.\n\n```html\n<h1>@(Welcome to our shop)</h1>\n```\n\n## Compression\n\nWhen a view is compiled, HTML comments are removed, the CSS of `<style>` tags and the JavaScript of `<script>` tags are minified, and runs of spaces inside the text are collapsed; line breaks and indentation between tags are kept. `@{nocompress html}` (or `js`, `css`, `all`) in the view turns off one of these steps. Commands work inside `<style>` too, also several in one block: `<style>.a{color:@{model.color}}.b{background:@{model.background}}</style>`.\n\n## Templates\n\n`TEMPLATE(body, [model], [$])` renders a template with the Tangular engine and returns a promise with the HTML. Templates are not views: they use `{{ }}` commands and the model is `value`. The body is the template itself, a URL, a path of a file in `/templates/` (`.html` is added when missing), a path that starts with `#` for a file in `/plugins/` (`.html` is added when missing), or `~` and an absolute path.\n\n```js\nvar html = await TEMPLATE('invoice', { number: 'F001', items: items });\n```\n\n```html\n<!-- /templates/invoice.html -->\n<h1>Invoice {{ value.number }}</h1>\n{{ foreach item in value.items }}\n\t<p>{{ item.name }}: {{ item.price | format(2) }}</p>\n{{ end }}\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"Jafwtz4nx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/views/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Views","summary":"HTML-Views mit @{}-Befehlen: Rendern, Layouts, Bedingungen, Schleifen, Abschnitte, Meta-Tags, Importe, Helper und Templates.","markdown":"---\ntitle: Views\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/views/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Views\n\n> HTML-Views mit @{}-Befehlen: Rendern, Layouts, Bedingungen, Schleifen, Abschnitte, Meta-Tags, Importe, Helper und Templates.\n\nEine View ist eine HTML-Datei im Ordner `/views/` mit Befehlen zwischen `@{` und `}`. Das Framework kompiliert jede View in eine JavaScript-Funktion und führt sie mit deinem Modell aus. Im Debug-Modus wird eine View bei jedem Rendern neu kompiliert, sodass du Änderungen sofort siehst; im Release-Modus wird die kompilierte Funktion nach Name und Sprache gecacht.\n\n```html\n<!-- /views/index.html -->\n@{title('Products')}\n\n<h1>@{model.name}</h1>\n<ul>\n@{foreach item in model.items}\n\t<li>@{item.name} - @{item.price}</li>\n@{end}\n</ul>\n```\n\n## Eine View rendern\n\nRufe in einer Route `$.view(name, [model])` auf. Der Name ist der Pfad der Datei in `/views/` ohne `.html`; ein Name, der mit `#` beginnt, liest die Datei aus dem Ordner `/plugins/`. Die View wird in `/views/layout.html` gerendert, lege diese Datei also zuerst an oder beginne die View mit `@{layout('')}` (siehe [Layouts](#layouts)).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /contact/');              // renders /views/contact.html\n\tROUTE('GET /products/', 'products'); // renders /views/products.html\n};\n\nfunction index($) {\n\t$.view('index', { name: 'Shop', items: [{ name: 'Pen', price: 5 }] });\n}\n```\n\nEine Route ohne Aktion rendert die View, die nach dem ersten Teil ihrer URL benannt ist (`index` für `/`), und eine Route, deren Aktion ein String ist, rendert die View mit diesem Namen. Der Leitfaden [Routing](../../guides/routing/) enthält die Details.\n\n`$.view()` ohne Argumente gibt ein neues View-Objekt zurück, das du selbst renderst, und `F.view(name, [model], [prepare])` rendert eine View außerhalb einer Anfrage und gibt den HTML-String zurück. `F.view()` verwendest du für E-Mails, Dateien oder Caches.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n});\n```\n\n## Layouts\n\nJede View wird in ein Layout gerendert. Das Standard-Layout ist `/views/layout.html`; das Layout gibt das HTML der View mit `@{body}` aus. Existiert die Datei nicht, schlägt die Anfrage mit einem `ENOENT`-Fehler fehl und der Client erhält die Antwort `503`.\n\n```html\n<!-- /views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nÄndere das Layout in der View mit `@{layout('name')}` oder in der Route mit `$.layout('name')`. Ein leerer Name (`@{layout('')}`) rendert die View ohne Layout. Zuerst läuft die View und danach das Layout, daher kann das Layout den Titel, die Sektionen und die `repository`-Werte lesen, die die View gesetzt hat. Das Layout erhält das Modell nicht: Übergib die Werte, die es braucht, über `repository`.\n\n## Ausgabe und Escaping\n\n`@{expression}` gibt den Wert eines beliebigen JavaScript-Ausdrucks HTML-kodiert aus. `@{!expression}` gibt ihn ohne Kodierung aus. `null` und `undefined` werden als leerer String ausgegeben. Eine Route ohne Aktion rendert ihre View ohne Modell: `model` ist dann `undefined`, daher wirft `@{model.name}` einen Fehler und der Client erhält die Antwort `503`. Übergib mit `$.view(name, model)` ein Modell, auch wenn es nur ein leeres Objekt ist.\n\n```html\n<p>@{model.name}</p>             <!-- &lt;b&gt;Peter&lt;/b&gt; -->\n<div>@{!model.html}</div>        <!-- the raw HTML -->\n<span>@{model.items.length}</span>\n@{repository.count = 5}          <!-- an assignment prints nothing -->\n```\n\nDiese Variablen sind in jeder View verfügbar:\n\n| Variable | Was sie enthält |\n| --- | --- |\n| `model` | Das an die View übergebene Modell |\n| `repository` | Ein Objekt, das die View, ihre Teil-Views und das Layout teilen |\n| `config` | Die Konfiguration (`CONF`) |\n| `controller` | Der Controller der Anfrage (`undefined` in `F.view()`) |\n| `query`, `body`, `files` | Der Query String, der geparste Body und die hochgeladenen Dateien der Anfrage |\n| `user`, `session` | Der Benutzer und die Session der Anfrage |\n| `language` | Die Sprache der View: die der Anfrage oder `view.language`, gesetzt für `F.view()` (standardmäßig ein leerer String) |\n| `url` | Der Pfad der Anfrage, ohne Query String (`undefined` in `F.view()`) |\n| `helpers` | Die eigenen Helfer (`DEF.helpers`) |\n\nGlobale Objekte wie `MAIN`, `REPO`, `FUNC`, `CONF` und `MODS` funktionieren ebenfalls. `@{'%name'}` gibt einen Konfigurationswert aus, der einmal gelesen wird, wenn die View kompiliert wird.\n\n`@{hostname()}` gibt die absolute URL der aktuellen Seite aus und `@{hostname('/path/')}` die absolute URL eines anderen Pfads, zum Beispiel für kanonische Links und Bilder zum Teilen:\n\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n## Bedingungen und Schleifen\n\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n```\n\n`@{endif}` ist dasselbe wie `@{fi}`. Innerhalb von `@{foreach}` ist `@{index}` die nullbasierte Position, und `@{continue}` und `@{break}` funktionieren wie in JavaScript. Eine Schleife über ein Objekt (kein Array) liefert Elemente mit `key` und `value`.\n\n## Teil-Views und Sektionen\n\n`@{view('name', [model])}` rendert an Ort und Stelle eine andere View, mit eigenem Modell und ohne Layout. Eine Sektion sammelt HTML in der View und gibt es an anderer Stelle aus, meist im Layout:\n\n```html\n<!-- in the view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- in the layout -->\n@{section('scripts')}\n```\n\n## Titel, Meta-Tags und Importe\n\n`@{title('Text')}`, `@{description('Text')}` und `@{keywords('a, b')}` speichern die Werte in `repository`; `@{title2('Text')}` hängt Text an den Titel an, und `@{meta(title, description, keywords, image)}` setzt alle auf einmal. Die Werte werden so gespeichert, wie sie sind, und einmal HTML-kodiert, wenn sie ausgegeben werden. Das Layout gibt sie mit `@{import('meta')}` (oder `@{meta}`) aus: ein `<title>`-Tag, die Meta-Tags für Beschreibung und Schlüsselwörter und die `og:image`-Tags. An den Titel werden ` - ` und `CONF.name` angehängt, außer auf der Startseite und wenn `CONF.$customtitles` `true` ist.\n\n`@{import()}` erzeugt die Tags für deine statischen Dateien. Ein `.css`-Name wird in `/css/` gesucht und andere Namen in `/js/`; ein Pfad, der mit `/` beginnt, wird unverändert verwendet. Mehrere mit `+` verbundene Namen werden zu einer minifizierten Datei zusammengeführt, die das Framework selbst ausliefert. Ein `@` vor einem Namen hängt `?ts=` mit der Startzeit der Anwendung an, sodass Browser nach jedem Neustart die neue Datei laden.\n\n```html\n@{import('meta', 'favicon.ico', 'default.css', '@app.js')}\n@{import('reset.css + layout.css + forms.css')}\n@{import('/vendor/editor.js')}\n```\n\n## Helfer\n\nEin Helfer ist eine Funktion, die du aus jeder View aufrufen kannst. Registriere ihn in `DEF.helpers`; darin ist `this` die View, daher sind `this.model` und `this.repository` verfügbar. Rufe ihn über seinen Namen auf, mit `@{helpers.name()}` oder mit `@{helper('name', ...)}`. Ein Helfer gibt das HTML zurück, das er ausgibt, ohne Kodierung.\n\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n```\n\n```html\n<span>@{price(model.price)}</span>\n```\n\n## Lokalisierung\n\nText in `@(...)` wird beim Kompilieren der View in die Sprache der View übersetzt, daher hat jede Sprache ihre eigene kompilierte Kopie. Die Sprache stammt aus der Anfrage; setze `view.language` für `F.view()`. Der Leitfaden [Lokalisierung](../../guides/localization/) erklärt die Ressourcendateien.\n\n```html\n<h1>@(Welcome to our shop)</h1>\n```\n\n## Kompression\n\nBeim Kompilieren einer View werden HTML-Kommentare entfernt, das CSS von `<style>`-Tags und das JavaScript von `<script>`-Tags minifiziert und Folgen von Leerzeichen im Text werden zusammengefasst; Zeilenumbrüche und Einrückungen zwischen Tags bleiben erhalten. `@{nocompress html}` (oder `js`, `css`, `all`) in der View schaltet einen dieser Schritte ab. Befehle funktionieren auch innerhalb von `<style>`, auch mehrere in einem Block: `<style>.a{color:@{model.color}}.b{background:@{model.background}}</style>`.\n\n## Templates\n\n`TEMPLATE(body, [model], [$])` rendert ein Template mit der Engine Tangular und gibt ein Promise mit dem HTML zurück. Templates sind keine Views: Sie verwenden `{{ }}`-Befehle, und das Modell ist `value`. Der Body ist das Template selbst, eine URL, ein Pfad einer Datei in `/templates/` (`.html` wird ergänzt, wenn es fehlt), ein Pfad, der mit `#` beginnt, für eine Datei in `/plugins/` (`.html` wird ergänzt, wenn es fehlt), oder `~` und ein absoluter Pfad.\n\n```js\nvar html = await TEMPLATE('invoice', { number: 'F001', items: items });\n```\n\n```html\n<!-- /templates/invoice.html -->\n<h1>Invoice {{ value.number }}</h1>\n{{ foreach item in value.items }}\n\t<p>{{ item.name }}: {{ item.price | format(2) }}</p>\n{{ end }}\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"Jafwtz4nx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/views/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Vistas","summary":"Vistas HTML con comandos @{}: renderizado, plantillas (layouts), condiciones, bucles, secciones, meta tags, importaciones, helpers y templates.","markdown":"---\ntitle: Vistas\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/views/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Vistas\n\n> Vistas HTML con comandos @{}: renderizado, plantillas (layouts), condiciones, bucles, secciones, meta tags, importaciones, helpers y templates.\n\nUna vista es un archivo HTML en la carpeta `/views/` con comandos entre `@{` y `}`. El framework compila cada vista en una función JavaScript y la ejecuta con tu modelo. En modo debug una vista se vuelve a compilar en cada renderizado, así que ves los cambios al instante; en modo release la función compilada se guarda en caché por nombre e idioma.\n\n```html\n<!-- /views/index.html -->\n@{title('Products')}\n\n<h1>@{model.name}</h1>\n<ul>\n@{foreach item in model.items}\n\t<li>@{item.name} - @{item.price}</li>\n@{end}\n</ul>\n```\n\n## Renderizar una vista\n\nEn una ruta, llama a `$.view(name, [model])`. El nombre es la ruta del archivo en `/views/` sin `.html`; un nombre que empieza por `#` lee el archivo de la carpeta `/plugins/`. La vista se renderiza dentro de `/views/layout.html`, así que crea antes ese archivo o empieza la vista con `@{layout('')}` (consulta [Plantillas (layouts)](#layouts)).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /contact/');              // renders /views/contact.html\n\tROUTE('GET /products/', 'products'); // renders /views/products.html\n};\n\nfunction index($) {\n\t$.view('index', { name: 'Shop', items: [{ name: 'Pen', price: 5 }] });\n}\n```\n\nUna ruta sin acción renderiza la vista con el nombre de la primera parte de su URL (`index` para `/`), y una ruta cuya acción es un string renderiza la vista con ese nombre. La guía [Enrutamiento](../../guides/routing/) tiene los detalles.\n\n`$.view()` sin argumentos devuelve un nuevo objeto vista que renderizas tú mismo, y `F.view(name, [model], [prepare])` renderiza una vista fuera de una petición y devuelve el string HTML. `F.view()` es lo que usas para e-mails, archivos o cachés.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n});\n```\n\n## Plantillas (layouts)\n\nCada vista se renderiza dentro de una plantilla (layout). La plantilla por defecto es `/views/layout.html`; la plantilla imprime el HTML de la vista con `@{body}`. Si el archivo no existe, la petición falla con un error `ENOENT` y el cliente recibe una respuesta `503`.\n\n```html\n<!-- /views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nCambia la plantilla en la vista con `@{layout('name')}` o en la ruta con `$.layout('name')`. Un nombre vacío (`@{layout('')}`) renderiza la vista sin plantilla. La vista se ejecuta primero y la plantilla después, así que la plantilla puede leer el título, las secciones y los valores de `repository` que estableció la vista. La plantilla no recibe el modelo: pasa los valores que necesite a través de `repository`.\n\n## Salida y escape\n\n`@{expression}` imprime el valor de cualquier expresión JavaScript, codificado para HTML. `@{!expression}` lo imprime sin codificar. `null` y `undefined` se imprimen como un string vacío. Una ruta sin acción renderiza su vista sin modelo: `model` es entonces `undefined`, así que `@{model.name}` lanza un error y el cliente recibe una respuesta `503`. Pasa un modelo con `$.view(name, model)`, aunque sea un objeto vacío.\n\n```html\n<p>@{model.name}</p>             <!-- &lt;b&gt;Peter&lt;/b&gt; -->\n<div>@{!model.html}</div>        <!-- the raw HTML -->\n<span>@{model.items.length}</span>\n@{repository.count = 5}          <!-- an assignment prints nothing -->\n```\n\nEstas variables están disponibles en todas las vistas:\n\n| Variable | Qué contiene |\n| --- | --- |\n| `model` | El modelo pasado a la vista |\n| `repository` | Un objeto compartido por la vista, sus vistas parciales y la plantilla |\n| `config` | La configuración (`CONF`) |\n| `controller` | El controlador de la petición (`undefined` en `F.view()`) |\n| `query`, `body`, `files` | El query string, el cuerpo parseado y los archivos subidos de la petición |\n| `user`, `session` | El usuario y la sesión de la petición |\n| `language` | El idioma de la vista: el de la petición, o `view.language` establecido para `F.view()` (un string vacío por defecto) |\n| `url` | La ruta de la petición, sin el query string (`undefined` en `F.view()`) |\n| `helpers` | Los helpers personalizados (`DEF.helpers`) |\n\nLos objetos globales como `MAIN`, `REPO`, `FUNC`, `CONF` y `MODS` también funcionan. `@{'%name'}` imprime un valor de configuración que se lee una sola vez, cuando se compila la vista.\n\n`@{hostname()}` imprime la URL absoluta de la página actual y `@{hostname('/path/')}` la URL absoluta de otra ruta, por ejemplo para enlaces canónicos e imágenes para compartir:\n\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n## Condiciones y bucles\n\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n```\n\n`@{endif}` es lo mismo que `@{fi}`. Dentro de `@{foreach}`, `@{index}` es la posición empezando en cero, y `@{continue}` y `@{break}` funcionan como en JavaScript. Un bucle sobre un objeto (no un array) da elementos con `key` y `value`.\n\n## Vistas parciales y secciones\n\n`@{view('name', [model])}` renderiza otra vista en ese lugar, con su propio modelo y sin plantilla. Una sección recoge HTML en la vista y lo imprime en otro lugar, normalmente en la plantilla:\n\n```html\n<!-- in the view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- in the layout -->\n@{section('scripts')}\n```\n\n## Título, meta tags e importaciones\n\n`@{title('Text')}`, `@{description('Text')}` y `@{keywords('a, b')}` guardan los valores en `repository`; `@{title2('Text')}` añade texto al título, y `@{meta(title, description, keywords, image)}` los establece todos a la vez. Los valores se guardan tal cual y se codifican en HTML una sola vez, cuando se imprimen. La plantilla los imprime con `@{import('meta')}` (o `@{meta}`): una etiqueta `<title>`, los meta tags de descripción y palabras clave y las etiquetas `og:image`. Al título se le añade ` - ` y `CONF.name`, excepto en la página de inicio y cuando `CONF.$customtitles` es `true`.\n\n`@{import()}` crea las etiquetas para tus archivos estáticos. Un nombre `.css` se busca en `/css/` y los demás nombres en `/js/`; una ruta que empieza por `/` se usa tal cual. Varios nombres unidos con `+` se combinan en un único archivo minificado, que sirve el propio framework. Una `@` antes de un nombre añade `?ts=` con la hora de inicio de la aplicación, para que los navegadores carguen el archivo nuevo después de cada reinicio.\n\n```html\n@{import('meta', 'favicon.ico', 'default.css', '@app.js')}\n@{import('reset.css + layout.css + forms.css')}\n@{import('/vendor/editor.js')}\n```\n\n## Helpers\n\nUn helper es una función que puedes llamar desde todas las vistas. Regístralo en `DEF.helpers`; dentro de él `this` es la vista, así que `this.model` y `this.repository` están disponibles. Llámalo por su nombre, con `@{helpers.name()}`, o con `@{helper('name', ...)}`. Un helper devuelve el HTML que imprime, sin codificar.\n\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n```\n\n```html\n<span>@{price(model.price)}</span>\n```\n\n## Localización\n\nEl texto en `@(...)` se traduce al idioma de la vista cuando se compila la vista, así que cada idioma tiene su propia copia compilada. El idioma viene de la petición; establece `view.language` para `F.view()`. La guía [Localización](../../guides/localization/) explica los archivos de recursos.\n\n```html\n<h1>@(Welcome to our shop)</h1>\n```\n\n## Compresión\n\nCuando se compila una vista, se eliminan los comentarios HTML, se minifican el CSS de las etiquetas `<style>` y el JavaScript de las etiquetas `<script>`, y se colapsan las secuencias de espacios dentro del texto; se conservan los saltos de línea y la sangría entre etiquetas. `@{nocompress html}` (o `js`, `css`, `all`) en la vista desactiva uno de estos pasos. Los comandos también funcionan dentro de `<style>`, incluso varios en un bloque: `<style>.a{color:@{model.color}}.b{background:@{model.background}}</style>`.\n\n## Plantillas Tangular\n\n`TEMPLATE(body, [model], [$])` renderiza una plantilla con el motor Tangular y devuelve una promesa con el HTML. Las plantillas no son vistas: usan comandos `{{ }}` y el modelo es `value`. El cuerpo es la propia plantilla, una URL, una ruta de un archivo en `/templates/` (se añade `.html` si falta), una ruta que empieza por `#` para un archivo en `/plugins/` (se añade `.html` si falta), o `~` y una ruta absoluta.\n\n```js\nvar html = await TEMPLATE('invoice', { number: 'F001', items: items });\n```\n\n```html\n<!-- /templates/invoice.html -->\n<h1>Invoice {{ value.number }}</h1>\n{{ foreach item in value.items }}\n\t<p>{{ item.name }}: {{ item.price | format(2) }}</p>\n{{ end }}\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"Jafwtz4nx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/views/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Vues","summary":"Vues HTML avec des commandes @{} : rendu, layouts, conditions, boucles, sections, balises meta, imports, helpers et templates.","markdown":"---\ntitle: Vues\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/views/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Vues\n\n> Vues HTML avec des commandes @{} : rendu, layouts, conditions, boucles, sections, balises meta, imports, helpers et templates.\n\nUne vue est un fichier HTML du dossier `/views/` avec des commandes entre `@{` et `}`. Le framework compile chaque vue en une fonction JavaScript et l'exécute avec ton modèle. En mode debug, une vue est recompilée à chaque rendu, tu vois donc les modifications immédiatement ; en mode release, la fonction compilée est mise en cache par nom et par langue.\n\n```html\n<!-- /views/index.html -->\n@{title('Products')}\n\n<h1>@{model.name}</h1>\n<ul>\n@{foreach item in model.items}\n\t<li>@{item.name} - @{item.price}</li>\n@{end}\n</ul>\n```\n\n## Afficher une vue\n\nDans une route, appelle `$.view(name, [model])`. Le nom est le chemin du fichier dans `/views/` sans `.html` ; un nom qui commence par `#` lit le fichier depuis le dossier `/plugins/`. La vue est rendue dans `/views/layout.html` : crée d'abord ce fichier ou commence la vue par `@{layout('')}` (voir [Layouts](#layouts)).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /contact/');              // renders /views/contact.html\n\tROUTE('GET /products/', 'products'); // renders /views/products.html\n};\n\nfunction index($) {\n\t$.view('index', { name: 'Shop', items: [{ name: 'Pen', price: 5 }] });\n}\n```\n\nUne route sans action affiche la vue nommée d'après la première partie de son URL (`index` pour `/`), et une route dont l'action est une chaîne affiche la vue de ce nom. Le guide [Routage](../../guides/routing/) donne les détails.\n\n`$.view()` sans arguments renvoie un nouvel objet vue que tu affiches toi-même, et `F.view(name, [model], [prepare])` affiche une vue en dehors d'une requête et renvoie la chaîne HTML. `F.view()` est ce que tu utilises pour les e-mails, les fichiers ou les caches.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n});\n```\n\n## Layouts\n\nChaque vue est affichée dans un layout. Le layout par défaut est `/views/layout.html` ; le layout affiche le HTML de la vue avec `@{body}`. Si le fichier n'existe pas, la requête échoue avec une erreur `ENOENT` et le client reçoit une réponse `503`.\n\n```html\n<!-- /views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nChange le layout dans la vue avec `@{layout('name')}` ou dans la route avec `$.layout('name')`. Un nom vide (`@{layout('')}`) affiche la vue sans layout. La vue s'exécute d'abord et le layout ensuite : le layout peut donc lire le titre, les sections et les valeurs de `repository` définis par la vue. Le layout ne reçoit pas le modèle : transmets les valeurs dont il a besoin via `repository`.\n\n## Sortie et échappement\n\n`@{expression}` affiche la valeur de n'importe quelle expression JavaScript, encodée en HTML. `@{!expression}` l'affiche sans encodage. `null` et `undefined` s'affichent comme une chaîne vide. Une route sans action rend sa vue sans modèle de données : `model` vaut alors `undefined`, donc `@{model.name}` lève une erreur et le client reçoit une réponse `503`. Passe un modèle de données avec `$.view(name, model)`, même un objet vide.\n\n```html\n<p>@{model.name}</p>             <!-- &lt;b&gt;Peter&lt;/b&gt; -->\n<div>@{!model.html}</div>        <!-- the raw HTML -->\n<span>@{model.items.length}</span>\n@{repository.count = 5}          <!-- an assignment prints nothing -->\n```\n\nCes variables sont disponibles dans chaque vue :\n\n| Variable | Ce qu'elle contient |\n| --- | --- |\n| `model` | Le modèle passé à la vue |\n| `repository` | Un objet partagé par la vue, ses vues partielles et le layout |\n| `config` | La configuration (`CONF`) |\n| `controller` | Le contrôleur de la requête (`undefined` dans `F.view()`) |\n| `query`, `body`, `files` | La query string, le corps analysé et les fichiers envoyés de la requête |\n| `user`, `session` | L'utilisateur et la session de la requête |\n| `language` | La langue de la vue : celle de la requête, ou `view.language` défini pour `F.view()` (une chaîne vide par défaut) |\n| `url` | Le chemin de la requête, sans la query string (`undefined` dans `F.view()`) |\n| `helpers` | Les helpers personnalisés (`DEF.helpers`) |\n\nLes objets globaux comme `MAIN`, `REPO`, `FUNC`, `CONF` et `MODS` fonctionnent aussi. `@{'%name'}` affiche une valeur de configuration lue une seule fois, à la compilation de la vue.\n\n`@{hostname()}` affiche l'URL absolue de la page actuelle et `@{hostname('/path/')}` l'URL absolue d'un autre chemin, par exemple pour les liens canoniques et les images de partage :\n\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n## Conditions et boucles\n\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n```\n\n`@{endif}` équivaut à `@{fi}`. Dans `@{foreach}`, `@{index}` est la position à partir de zéro, et `@{continue}` et `@{break}` fonctionnent comme en JavaScript. Une boucle sur un objet (et non un tableau) donne des éléments avec `key` et `value`.\n\n## Vues partielles et sections\n\n`@{view('name', [model])}` affiche une autre vue à cet endroit, avec son propre modèle et sans layout. Une section collecte du HTML dans la vue et l'affiche ailleurs, généralement dans le layout :\n\n```html\n<!-- in the view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- in the layout -->\n@{section('scripts')}\n```\n\n## Titre, balises meta et imports\n\n`@{title('Text')}`, `@{description('Text')}` et `@{keywords('a, b')}` stockent les valeurs dans `repository` ; `@{title2('Text')}` ajoute du texte au titre, et `@{meta(title, description, keywords, image)}` les définit toutes à la fois. Les valeurs sont stockées telles quelles et encodées en HTML une seule fois, au moment de leur affichage. Le layout les affiche avec `@{import('meta')}` (ou `@{meta}`) : une balise `<title>`, les balises meta description et keywords et les balises `og:image`. Le titre reçoit ` - ` et `CONF.name` en suffixe, sauf sur la page d'accueil et lorsque `CONF.$customtitles` vaut `true`.\n\n`@{import()}` crée les balises pour tes fichiers statiques. Un nom `.css` est recherché dans `/css/` et les autres noms dans `/js/` ; un chemin qui commence par `/` est utilisé tel quel. Plusieurs noms joints avec `+` sont fusionnés en un seul fichier minifié, que le framework sert lui-même. Un `@` devant un nom ajoute `?ts=` avec l'heure de démarrage de l'application, afin que les navigateurs chargent le nouveau fichier après chaque redémarrage.\n\n```html\n@{import('meta', 'favicon.ico', 'default.css', '@app.js')}\n@{import('reset.css + layout.css + forms.css')}\n@{import('/vendor/editor.js')}\n```\n\n## Helpers\n\nUn helper est une fonction que tu peux appeler depuis chaque vue. Enregistre-le dans `DEF.helpers` ; à l'intérieur, `this` est la vue, donc `this.model` et `this.repository` sont disponibles. Appelle-le par son nom, avec `@{helpers.name()}`, ou avec `@{helper('name', ...)}`. Un helper renvoie le HTML qu'il affiche, sans encodage.\n\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n```\n\n```html\n<span>@{price(model.price)}</span>\n```\n\n## Localisation\n\nLe texte entre `@(...)` est traduit dans la langue de la vue à la compilation de la vue : chaque langue a donc sa propre copie compilée. La langue vient de la requête ; définis `view.language` pour `F.view()`. Le guide [Localisation](../../guides/localization/) explique les fichiers de ressources.\n\n```html\n<h1>@(Welcome to our shop)</h1>\n```\n\n## Compression\n\nÀ la compilation d'une vue, les commentaires HTML sont retirés, le CSS des balises `<style>` et le JavaScript des balises `<script>` sont minifiés, et les suites d'espaces dans le texte sont réduites ; les retours à la ligne et l'indentation entre les balises sont conservés. `@{nocompress html}` (ou `js`, `css`, `all`) dans la vue désactive l'une de ces étapes. Les commandes fonctionnent aussi dans `<style>`, même plusieurs dans un seul bloc : `<style>.a{color:@{model.color}}.b{background:@{model.background}}</style>`.\n\n## Templates\n\n`TEMPLATE(body, [model], [$])` affiche un template avec le moteur Tangular et renvoie une promesse avec le HTML. Les templates ne sont pas des vues : ils utilisent des commandes `{{ }}` et le modèle est `value`. Le body est le template lui-même, une URL, le chemin d'un fichier dans `/templates/` (`.html` est ajouté s'il manque), un chemin qui commence par `#` pour un fichier dans `/plugins/` (`.html` est ajouté s'il manque), ou `~` suivi d'un chemin absolu.\n\n```js\nvar html = await TEMPLATE('invoice', { number: 'F001', items: items });\n```\n\n```html\n<!-- /templates/invoice.html -->\n<h1>Invoice {{ value.number }}</h1>\n{{ foreach item in value.items }}\n\t<p>{{ item.name }}: {{ item.price | format(2) }}</p>\n{{ end }}\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"Jafwtz4nx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/views/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Viste","summary":"Viste HTML con comandi @{}: rendering, layout, condizioni, cicli, sezioni, meta tag, import, helper e template.","markdown":"---\ntitle: Viste\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/views/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Viste\n\n> Viste HTML con comandi @{}: rendering, layout, condizioni, cicli, sezioni, meta tag, import, helper e template.\n\nUna vista è un file HTML nella cartella `/views/` con comandi tra `@{` e `}`. Il framework compila ogni vista in una funzione JavaScript e la esegue con il tuo modello. In modalità debug una vista viene ricompilata a ogni rendering, così vedi subito le modifiche; in modalità release la funzione compilata viene messa in cache per nome e lingua.\n\n```html\n<!-- /views/index.html -->\n@{title('Products')}\n\n<h1>@{model.name}</h1>\n<ul>\n@{foreach item in model.items}\n\t<li>@{item.name} - @{item.price}</li>\n@{end}\n</ul>\n```\n\n## Renderizzare una vista\n\nIn una route, chiama `$.view(name, [model])`. Il nome è il percorso del file in `/views/` senza `.html`; un nome che inizia con `#` legge il file dalla cartella `/plugins/`. La vista viene renderizzata in `/views/layout.html`, quindi crea prima quel file oppure inizia la vista con `@{layout('')}` (vedi [Layout](#layouts)).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /contact/');              // renders /views/contact.html\n\tROUTE('GET /products/', 'products'); // renders /views/products.html\n};\n\nfunction index($) {\n\t$.view('index', { name: 'Shop', items: [{ name: 'Pen', price: 5 }] });\n}\n```\n\nUna route senza azione renderizza la vista indicata dalla prima parte del suo URL (`index` per `/`), e una route la cui azione è una stringa renderizza la vista con quel nome. La guida [Routing](../../guides/routing/) contiene i dettagli.\n\n`$.view()` senza argomenti restituisce un nuovo oggetto vista che renderizzi tu, e `F.view(name, [model], [prepare])` renderizza una vista al di fuori di una richiesta e restituisce la stringa HTML. `F.view()` è ciò che usi per e-mail, file o cache.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n});\n```\n\n## Layout\n\nOgni vista viene renderizzata all'interno di un layout. Il layout predefinito è `/views/layout.html`; il layout stampa l'HTML della vista con `@{body}`. Se il file non esiste, la richiesta fallisce con un errore `ENOENT` e il client riceve una risposta `503`.\n\n```html\n<!-- /views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nCambia il layout nella vista con `@{layout('name')}` o nella route con `$.layout('name')`. Un nome vuoto (`@{layout('')}`) renderizza la vista senza layout. La vista viene eseguita per prima e il layout dopo, quindi il layout può leggere il titolo, le sezioni e i valori di `repository` impostati dalla vista. Il layout non riceve il modello: passa i valori di cui ha bisogno tramite `repository`.\n\n## Output ed escaping\n\n`@{expression}` stampa il valore di qualsiasi espressione JavaScript, codificato in HTML. `@{!expression}` lo stampa senza codifica. `null` e `undefined` vengono stampati come stringa vuota. Una route senza azione renderizza la sua vista senza modello: `model` è quindi `undefined`, perciò `@{model.name}` genera un errore e il client riceve una risposta `503`. Passa un modello con `$.view(name, model)`, anche un oggetto vuoto.\n\n```html\n<p>@{model.name}</p>             <!-- &lt;b&gt;Peter&lt;/b&gt; -->\n<div>@{!model.html}</div>        <!-- the raw HTML -->\n<span>@{model.items.length}</span>\n@{repository.count = 5}          <!-- an assignment prints nothing -->\n```\n\nQueste variabili sono disponibili in ogni vista:\n\n| Variabile | Cosa contiene |\n| --- | --- |\n| `model` | Il modello passato alla vista |\n| `repository` | Un oggetto condiviso dalla vista, dalle sue viste parziali e dal layout |\n| `config` | La configurazione (`CONF`) |\n| `controller` | Il controller della richiesta (`undefined` in `F.view()`) |\n| `query`, `body`, `files` | La query string, il body analizzato e i file caricati della richiesta |\n| `user`, `session` | L'utente e la sessione della richiesta |\n| `language` | La lingua della vista: quella della richiesta, o `view.language` impostato per `F.view()` (una stringa vuota per impostazione predefinita) |\n| `url` | Il percorso della richiesta, senza la query string (`undefined` in `F.view()`) |\n| `helpers` | Gli helper personalizzati (`DEF.helpers`) |\n\nFunzionano anche gli oggetti globali come `MAIN`, `REPO`, `FUNC`, `CONF` e `MODS`. `@{'%name'}` stampa un valore di configurazione che viene letto una sola volta, quando la vista viene compilata.\n\n`@{hostname()}` stampa l'URL assoluto della pagina corrente e `@{hostname('/path/')}` l'URL assoluto di un altro percorso, per esempio per i link canonici e le immagini di condivisione:\n\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n## Condizioni e cicli\n\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n```\n\n`@{endif}` equivale a `@{fi}`. Dentro `@{foreach}`, `@{index}` è la posizione a partire da zero, e `@{continue}` e `@{break}` funzionano come in JavaScript. Un ciclo su un oggetto (non un array) fornisce elementi con `key` e `value`.\n\n## Viste parziali e sezioni\n\n`@{view('name', [model])}` renderizza un'altra vista sul posto, con il proprio modello e senza layout. Una sezione raccoglie HTML nella vista e lo stampa altrove, di solito nel layout:\n\n```html\n<!-- in the view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- in the layout -->\n@{section('scripts')}\n```\n\n## Titolo, meta tag e import\n\n`@{title('Text')}`, `@{description('Text')}` e `@{keywords('a, b')}` salvano i valori in `repository`; `@{title2('Text')}` aggiunge testo al titolo, e `@{meta(title, description, keywords, image)}` li imposta tutti insieme. I valori vengono salvati così come sono e codificati in HTML una sola volta, quando vengono stampati. Il layout li stampa con `@{import('meta')}` (o `@{meta}`): un tag `<title>`, i meta tag description e keywords e i tag `og:image`. Al titolo vengono aggiunti ` - ` e `CONF.name`, tranne nella home page e quando `CONF.$customtitles` è `true`.\n\n`@{import()}` crea i tag per i tuoi file statici. Un nome `.css` viene cercato in `/css/` e gli altri nomi in `/js/`; un percorso che inizia con `/` viene usato così com'è. Più nomi uniti con `+` vengono uniti in un unico file minificato, che il framework serve da solo. Una `@` davanti a un nome aggiunge `?ts=` con l'orario di avvio dell'applicazione, così i browser caricano il nuovo file dopo ogni riavvio.\n\n```html\n@{import('meta', 'favicon.ico', 'default.css', '@app.js')}\n@{import('reset.css + layout.css + forms.css')}\n@{import('/vendor/editor.js')}\n```\n\n## Helper\n\nUn helper è una funzione che puoi chiamare da ogni vista. Registralo in `DEF.helpers`; al suo interno `this` è la vista, quindi `this.model` e `this.repository` sono disponibili. Chiamalo con il suo nome, con `@{helpers.name()}`, oppure con `@{helper('name', ...)}`. Un helper restituisce l'HTML che stampa, senza codifica.\n\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n```\n\n```html\n<span>@{price(model.price)}</span>\n```\n\n## Localizzazione\n\nIl testo in `@(...)` viene tradotto nella lingua della vista quando la vista viene compilata, quindi ogni lingua ha la propria copia compilata. La lingua proviene dalla richiesta; imposta `view.language` per `F.view()`. La guida [Localizzazione](../../guides/localization/) spiega i file di risorse.\n\n```html\n<h1>@(Welcome to our shop)</h1>\n```\n\n## Compressione\n\nQuando una vista viene compilata, i commenti HTML vengono rimossi, il CSS dei tag `<style>` e il JavaScript dei tag `<script>` vengono minificati, e le sequenze di spazi all'interno del testo vengono ridotte; le interruzioni di riga e l'indentazione tra i tag vengono mantenute. `@{nocompress html}` (o `js`, `css`, `all`) nella vista disattiva uno di questi passaggi. I comandi funzionano anche dentro `<style>`, anche più di uno nello stesso blocco: `<style>.a{color:@{model.color}}.b{background:@{model.background}}</style>`.\n\n## Template\n\n`TEMPLATE(body, [model], [$])` renderizza un template con il motore Tangular e restituisce una promise con l'HTML. I template non sono viste: usano comandi `{{ }}` e il modello è `value`. Il body è il template stesso, un URL, un percorso di un file in `/templates/` (`.html` viene aggiunto se manca), un percorso che inizia con `#` per un file in `/plugins/` (`.html` viene aggiunto se manca), oppure `~` e un percorso assoluto.\n\n```js\nvar html = await TEMPLATE('invoice', { number: 'F001', items: items });\n```\n\n```html\n<!-- /templates/invoice.html -->\n<h1>Invoice {{ value.number }}</h1>\n{{ foreach item in value.items }}\n\t<p>{{ item.name }}: {{ item.price | format(2) }}</p>\n{{ end }}\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"Jafwtz4nx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/views/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Views","summary":"HTML pohľady s príkazmi @{}: vykresľovanie, layouty, podmienky, cykly, sekcie, meta tagy, importy, helpery a šablóny.","markdown":"---\ntitle: Views\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/views/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Views\n\n> HTML pohľady s príkazmi @{}: vykresľovanie, layouty, podmienky, cykly, sekcie, meta tagy, importy, helpery a šablóny.\n\nView je HTML súbor v priečinku `/views/` s príkazmi medzi `@{` a `}`. Framework skompiluje každé view do JavaScript funkcie a spustí ju s tvojím modelom. V debug režime sa view kompiluje znova pri každom vykreslení, takže zmeny vidíš hneď; v release režime sa skompilovaná funkcia cachuje podľa názvu a jazyka.\n\n```html\n<!-- /views/index.html -->\n@{title('Products')}\n\n<h1>@{model.name}</h1>\n<ul>\n@{foreach item in model.items}\n\t<li>@{item.name} - @{item.price}</li>\n@{end}\n</ul>\n```\n\n## Vykreslenie view\n\nV route zavolaj `$.view(name, [model])`. Názov je cesta k súboru v `/views/` bez `.html`; názov, ktorý začína `#`, číta súbor z priečinka `/plugins/`. Pohľad sa vykresľuje do `/views/layout.html`, preto najprv vytvor tento súbor alebo začni pohľad príkazom `@{layout('')}` (pozri [Layouty](#layouts)).\n\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /contact/');              // renders /views/contact.html\n\tROUTE('GET /products/', 'products'); // renders /views/products.html\n};\n\nfunction index($) {\n\t$.view('index', { name: 'Shop', items: [{ name: 'Pen', price: 5 }] });\n}\n```\n\nRouta bez akcie vykreslí view pomenované podľa prvej časti svojej URL (`index` pre `/`) a routa, ktorej akcia je reťazec, vykreslí view s týmto názvom. Podrobnosti nájdeš v návode [Routing](../../guides/routing/).\n\n`$.view()` bez argumentov vráti nový objekt view, ktorý vykreslíš sám, a `F.view(name, [model], [prepare])` vykreslí view mimo požiadavky a vráti HTML reťazec. `F.view()` používaš pre e-maily, súbory alebo cache.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n});\n```\n\n## Layouty\n\nKaždé view sa vykresľuje do layoutu. Predvolený layout je `/views/layout.html`; layout vypíše HTML view cez `@{body}`. Ak súbor neexistuje, požiadavka zlyhá s chybou `ENOENT` a klient dostane odpoveď `503`.\n\n```html\n<!-- /views/layout.html -->\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nLayout zmeníš vo view cez `@{layout('name')}` alebo v route cez `$.layout('name')`. Prázdny názov (`@{layout('')}`) vykreslí view bez layoutu. Najprv sa spustí view a po ňom layout, takže layout môže čítať titulok, sekcie a hodnoty `repository`, ktoré view nastavilo. Layout nedostane model: hodnoty, ktoré potrebuje, odovzdaj cez `repository`.\n\n## Výstup a escapovanie\n\n`@{expression}` vypíše hodnotu ľubovoľného JavaScript výrazu, HTML-zakódovanú. `@{!expression}` ju vypíše bez kódovania. `null` a `undefined` sa vypíšu ako prázdny reťazec. Routa bez akcie vykreslí svoj pohľad bez modelu: `model` je vtedy `undefined`, takže `@{model.name}` vyhodí chybu a klient dostane odpoveď `503`. Odovzdaj model cez `$.view(name, model)`, aj keby to bol prázdny objekt.\n\n```html\n<p>@{model.name}</p>             <!-- &lt;b&gt;Peter&lt;/b&gt; -->\n<div>@{!model.html}</div>        <!-- the raw HTML -->\n<span>@{model.items.length}</span>\n@{repository.count = 5}          <!-- an assignment prints nothing -->\n```\n\nTieto premenné sú dostupné v každom view:\n\n| Premenná | Čo obsahuje |\n| --- | --- |\n| `model` | Model odovzdaný do view |\n| `repository` | Objekt zdieľaný view, jeho čiastkovými view a layoutom |\n| `config` | Konfigurácia (`CONF`) |\n| `controller` | Controller požiadavky (`undefined` v `F.view()`) |\n| `query`, `body`, `files` | Query string, sparsované telo a nahrané súbory požiadavky |\n| `user`, `session` | Používateľ a session požiadavky |\n| `language` | Jazyk view: požiadavky alebo `view.language` nastavený pre `F.view()` (predvolene prázdny reťazec) |\n| `url` | Cesta požiadavky bez query stringu (`undefined` v `F.view()`) |\n| `helpers` | Vlastné pomocné funkcie (`DEF.helpers`) |\n\nFungujú aj globálne objekty ako `MAIN`, `REPO`, `FUNC`, `CONF` a `MODS`. `@{'%name'}` vypíše konfiguračnú hodnotu, ktorá sa prečíta raz, pri kompilácii view.\n\n`@{hostname()}` vypíše absolútnu URL aktuálnej stránky a `@{hostname('/path/')}` absolútnu URL inej cesty, napríklad pre kanonické odkazy a obrázky na zdieľanie:\n\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n## Podmienky a cykly\n\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n```\n\n`@{endif}` je to isté ako `@{fi}`. Vnútri `@{foreach}` je `@{index}` pozícia počítaná od nuly a `@{continue}` a `@{break}` fungujú ako v JavaScripte. Cyklus nad objektom (nie poľom) dáva položky s `key` a `value`.\n\n## Čiastkové view a sekcie\n\n`@{view('name', [model])}` vykreslí na danom mieste iné view, s vlastným modelom a bez layoutu. Sekcia zbiera HTML vo view a vypíše ho inde, zvyčajne v layoute:\n\n```html\n<!-- in the view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- in the layout -->\n@{section('scripts')}\n```\n\n## Titulok, meta tagy a importy\n\n`@{title('Text')}`, `@{description('Text')}` a `@{keywords('a, b')}` uložia hodnoty do `repository`; `@{title2('Text')}` pripojí text k titulku a `@{meta(title, description, keywords, image)}` ich nastaví všetky naraz. Hodnoty sa uložia tak, ako sú, a HTML-kódujú sa raz, pri vypísaní. Layout ich vypíše cez `@{import('meta')}` (alebo `@{meta}`): tag `<title>`, meta tagy description a keywords a tagy `og:image`. K titulku sa pripojí ` - ` a `CONF.name`, okrem domovskej stránky a prípadu, keď je `CONF.$customtitles` `true`.\n\n`@{import()}` vytvorí tagy pre tvoje statické súbory. Názov `.css` sa hľadá v `/css/` a ostatné názvy v `/js/`; cesta, ktorá začína `/`, sa použije tak, ako je. Viac názvov spojených cez `+` sa zlúči do jedného minifikovaného súboru, ktorý framework obsluhuje sám. `@` pred názvom pripojí `?ts=` s časom spustenia aplikácie, takže prehliadače po každom reštarte načítajú nový súbor.\n\n```html\n@{import('meta', 'favicon.ico', 'default.css', '@app.js')}\n@{import('reset.css + layout.css + forms.css')}\n@{import('/vendor/editor.js')}\n```\n\n## Pomocné funkcie\n\nPomocná funkcia (helper) je funkcia, ktorú môžeš volať z každého view. Zaregistruj ju v `DEF.helpers`; vnútri nej je `this` view, takže máš k dispozícii `this.model` a `this.repository`. Volaj ju jej názvom, cez `@{helpers.name()}` alebo cez `@{helper('name', ...)}`. Pomocná funkcia vráti HTML, ktoré vypíše, bez kódovania.\n\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n```\n\n```html\n<span>@{price(model.price)}</span>\n```\n\n## Lokalizácia\n\nText v `@(...)` sa pri kompilácii view preloží do jazyka view, takže každý jazyk má vlastnú skompilovanú kópiu. Jazyk pochádza z požiadavky; pre `F.view()` nastav `view.language`. Návod [Lokalizácia](../../guides/localization/) vysvetľuje súbory zdrojov.\n\n```html\n<h1>@(Welcome to our shop)</h1>\n```\n\n## Kompresia\n\nPri kompilácii view sa odstránia HTML komentáre, CSS tagov `<style>` a JavaScript tagov `<script>` sa minifikujú a viacnásobné medzery v texte sa zlúčia; zalomenia riadkov a odsadenie medzi tagmi sa zachovajú. `@{nocompress html}` (alebo `js`, `css`, `all`) vo view vypne jeden z týchto krokov. Príkazy fungujú aj vnútri `<style>`, aj viacero v jednom bloku: `<style>.a{color:@{model.color}}.b{background:@{model.background}}</style>`.\n\n## Šablóny\n\n`TEMPLATE(body, [model], [$])` vykreslí šablónu enginom Tangular a vráti promise s HTML. Šablóny nie sú view: používajú príkazy `{{ }}` a model je `value`. Telo je samotná šablóna, URL, cesta k súboru v `/templates/` (`.html` sa doplní, keď chýba), cesta začínajúca `#` pre súbor v `/plugins/` (`.html` sa doplní, keď chýba) alebo `~` a absolútna cesta.\n\n```js\nvar html = await TEMPLATE('invoice', { number: 'F001', items: items });\n```\n\n```html\n<!-- /templates/invoice.html -->\n<h1>Invoice {{ value.number }}</h1>\n{{ foreach item in value.items }}\n\t<p>{{ item.name }}: {{ item.price | format(2) }}</p>\n{{ end }}\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JancE21cE61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/production/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Running in production","summary":"Run a Total.js application on a server: no watcher, the right address, automatic restarts, nginx, clean stops and logs.","markdown":"---\ntitle: Running in production\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/production/\nupdated: 2026-11-18T19:21:30.967Z\n---\n\n# Running in production\n\n> Run a Total.js application on a server: no watcher, the right address, automatic restarts, nginx, clean stops and logs.\n\nThis guide takes an application from `node index.js` on your computer to a server: it starts without the watcher, listens on the right address, restarts when the process ends, runs behind nginx, and stops and logs in a predictable way. It uses the start script from [Installation](../installation/).\n\n## Start without the watcher\n\nIn the start script, uncomment this line:\n\n```js\noptions.watcher = false;\n```\n\nThen start the application from its directory:\n\n```bash\n$ node index.js\n```\n\nThe application now runs in that single process. No watcher starts and no `index.pid` file is written. `DEBUG` is `false` and the start information prints `Mode : release`. A change to a source file has no effect until the next start.\n\nThe working directory is the application root, so a start from another directory does not find the routes of the application.\n\nThe `--release` argument alone is not enough for production. It sets `DEBUG` to `false`, but the watcher keeps running in a separate process and restarts the application when a file changes.\n\n## Choose the address and the port\n\nBy default the application listens on all network interfaces. Set the address and the port in the start script:\n\n```js\noptions.ip = '127.0.0.1';\noptions.port = 8000;\n```\n\nOr set them in the `config` file:\n\n```text\n$ip   : 127.0.0.1\n$port : 8000\n```\n\nThe port comes from the first of these that is set:\n\n| Order | Source | Example |\n| --- | --- | --- |\n| 1 | The start option | `options.port = 8000;` |\n| 2 | The configuration key | `$port : 8000` |\n| 3 | A number in the command line | `node index.js 8001` |\n| 4 | The default | `8000` |\n\nThe address follows the same rule: `options.ip` wins over `$ip`. When the port is already in use, the application prints a message and exits with code `1`.\n\nWith the address `127.0.0.1`, only programs on the same machine can connect. Use it when a reverse proxy runs on the same machine and connects to `http://127.0.0.1:8000`. A proxy in another container cannot reach that address and answers `502`. In that case keep the default address and do not publish the port of the application, as in the setup below.\n\n## Keep the application running\n\nAn uncaught exception or an unhandled promise rejection does not stop the application. The framework logs the error and keeps serving requests. To react to these errors, create `definitions/errors.js`:\n\n```js\nON('error', function(obj) {\n\tconsole.log('Application error:', obj.error);\n});\n```\n\nWhen the process does end, nothing starts it again, so something outside the application has to do it. With Docker, that is the restart policy of the container. Create a `Dockerfile` in the application root, next to `package.json` and `package-lock.json`:\n\n```dockerfile\nFROM node:24-alpine\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm ci --omit=dev\nCOPY . .\nRUN chown -R node:node /app\nUSER node\nCMD [\"node\", \"index.js\"]\n```\n\nCreate `.dockerignore`:\n\n```text\nnode_modules\ntmp\nlogs\n```\n\nCreate `compose.yaml`. The `nginx` service and its `nginx.conf` file are described in the next section:\n\n```yaml\nservices:\n  app:\n    build: .\n    restart: unless-stopped\n\n  nginx:\n    image: nginx:1.29-alpine\n    restart: unless-stopped\n    ports:\n      - \"80:80\"\n    volumes:\n      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro\n    depends_on:\n      - app\n```\n\nBuild and start both services:\n\n```bash\n$ docker compose up -d --build\n```\n\nWith `restart: unless-stopped`, Docker starts the container again each time the process exits, whether the exit code is `0` or `1`. An application that you stop with `docker compose stop` stays stopped. To see how many times the container has been restarted:\n\n```bash\n$ docker inspect -f '{{.RestartCount}}' $(docker compose ps -a -q app)\n```\n\nDuring a start the port opens shortly before the routes are loaded, so requests in that moment get a `404` response. A health check should therefore expect `200` from a route of your application.\n\n## Put nginx in front\n\nCreate `nginx.conf` next to `compose.yaml`:\n\n```nginx\nmap $http_upgrade $connection_upgrade {\n\tdefault upgrade;\n\t''      close;\n}\n\nserver {\n\tlisten 80;\n\n\tlocation / {\n\t\tproxy_pass http://app:8000;\n\t\tproxy_http_version 1.1;\n\t\tproxy_set_header Host $host;\n\t\tproxy_set_header X-Forwarded-For $remote_addr;\n\t\tproxy_set_header X-Forwarded-Proto $scheme;\n\t\tproxy_set_header Upgrade $http_upgrade;\n\t\tproxy_set_header Connection $connection_upgrade;\n\t}\n}\n```\n\n`proxy_pass` uses the service name `app` and the default port `8000`. Only nginx publishes a port, so clients cannot connect to the application directly.\n\nThe `map` block and the `Upgrade` and `Connection` headers pass WebSocket connections through the proxy, on the same address as the HTTP requests. No other setting is needed for idle connections: the framework pings its WebSocket clients, and this keeps a connection without messages open through nginx.\n\nWhile the application is down, nginx answers `502`. When the application is back, nginx reaches it again without a restart of nginx.\n\n## What the application sees behind the proxy\n\nThe `proxy_set_header` lines decide what the application reads from a request:\n\n| Value | Source | Result |\n| --- | --- | --- |\n| `$.ip` | First address in `X-Forwarded-For` | The address of the client |\n| `client.ip` (WebSocket) | First address in `X-Forwarded-For` | The address of the client |\n| `$.protocol` | `X-Forwarded-Proto` | `https` when the header is `https`, otherwise `http` |\n| `$.host` | `Host` | The host name the client asked for |\n| `$.hostname('/x')` | `X-Forwarded-Proto` and `Host` | `https://www.example.com/x` |\n| `$.address` | `X-Forwarded-Proto`, `Host` and the URL | `https://www.example.com/info/` |\n\nThe framework trusts `X-Forwarded-For` on every request and reads its first address. Two rules follow from this:\n\n- Send `X-Forwarded-For $remote_addr`, as in the configuration above, so nginx replaces whatever the client sent. With `$proxy_add_x_forwarded_for`, nginx appends to the value from the client, and a client can choose the address that `$.ip` returns.\n- Do not let clients connect to the application directly, because they can then send the header themselves.\n\n## Stop the application cleanly\n\nThe signals `SIGTERM` and `SIGINT` stop the application. `docker stop` and `docker compose stop` send `SIGTERM`, and the container ends in less than three seconds.\n\nAfter the signal:\n\n1. The `exit` event runs.\n2. The application refuses new connections.\n3. About 300 ms later the process exits with code `1`.\n\nThe exit code is `1` after a clean stop too, so do not read it as a crash.\n\nThe application does not wait for running requests. A request that ends within those 300 ms gets its response. A longer request gets no response, and WebSocket clients are disconnected.\n\nUse the `exit` event for short work, for example in `definitions/exit.js`:\n\n```js\nconst Fs = require('node:fs');\n\nON('exit', function() {\n\tFs.appendFileSync(PATH.root('stopped.log'), new Date().toISOString() + '\\n');\n});\n```\n\nKeep this work synchronous or shorter than 300 ms, because the process ends after that time. The signal `SIGKILL` ends the process at once and the `exit` event does not run.\n\n## Logs\n\nThe application writes no log file by default. All output goes to the standard streams of the process:\n\n| Output | Stream |\n| --- | --- |\n| `console.log()` | stdout |\n| The start information | stdout |\n| Errors logged by the framework (`ERROR ======= ...`) | stdout |\n| `console.warn()` and `console.error()` | stderr |\n\nDocker collects both streams:\n\n```bash\n$ docker compose logs app\n```\n\nTo write to a file instead, add this key to the `config` file:\n\n```text\n$logger : true\n```\n\n`console.log()`, `console.warn()`, `console.error()` and the errors logged by the framework then go to `logs/debug.log`, and new lines are added to the file after each restart. The start information stays on stdout. To hide it, set `$imprint : false`.\n","entries":[],"license":"MIT","updated":"2026-11-18T19:21:30.967Z"}
{"id":"JancE21cE61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/production/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Betrieb in der Produktion","summary":"Betreibe eine Total.js-Anwendung auf einem Server: kein Watcher, die richtige Adresse, automatische Neustarts, nginx, sauberes Beenden und Logs.","markdown":"---\ntitle: Betrieb in der Produktion\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/production/\nupdated: 2026-11-18T19:21:30.967Z\n---\n\n# Betrieb in der Produktion\n\n> Betreibe eine Total.js-Anwendung auf einem Server: kein Watcher, die richtige Adresse, automatische Neustarts, nginx, sauberes Beenden und Logs.\n\nDiese Anleitung bringt eine Anwendung von `node index.js` auf deinem Computer auf einen Server: Dort startet sie ohne den Watcher, lauscht auf der richtigen Adresse, startet neu, wenn der Prozess endet, läuft hinter nginx und verhält sich beim Beenden und Protokollieren vorhersehbar. Grundlage ist das Startskript aus [Installation](../installation/).\n\n## Ohne den Watcher starten\n\nEntferne im Startskript den Kommentar vor dieser Zeile:\n\n```js\noptions.watcher = false;\n```\n\nStarte die Anwendung dann aus ihrem Verzeichnis:\n\n```bash\n$ node index.js\n```\n\nDie Anwendung läuft jetzt in diesem einen Prozess. Es startet kein Watcher und es wird keine `index.pid`-Datei geschrieben. `DEBUG` ist `false` und die Startinformationen zeigen `Mode : release`. Eine Änderung an einer Quelldatei wirkt sich erst beim nächsten Start aus.\n\nDas Arbeitsverzeichnis ist das Stammverzeichnis der Anwendung. Startest du sie aus einem anderen Verzeichnis, werden ihre Routen daher nicht gefunden.\n\nDas Argument `--release` allein reicht für die Produktion nicht aus. Es setzt `DEBUG` zwar auf `false`, aber der Watcher läuft in einem separaten Prozess weiter und startet die Anwendung neu, wenn sich eine Datei ändert.\n\n## Adresse und Port wählen\n\nStandardmäßig lauscht die Anwendung auf allen Netzwerkschnittstellen. Lege Adresse und Port im Startskript fest:\n\n```js\noptions.ip = '127.0.0.1';\noptions.port = 8000;\n```\n\nOder lege sie in der Datei `config` fest:\n\n```text\n$ip   : 127.0.0.1\n$port : 8000\n```\n\nDer Port stammt aus der ersten dieser Quellen, die gesetzt ist:\n\n| Reihenfolge | Quelle | Beispiel |\n| --- | --- | --- |\n| 1 | Die Startoption | `options.port = 8000;` |\n| 2 | Der Konfigurationsschlüssel | `$port : 8000` |\n| 3 | Eine Zahl in der Befehlszeile | `node index.js 8001` |\n| 4 | Der Standardwert | `8000` |\n\nFür die Adresse gilt dieselbe Regel: `options.ip` hat Vorrang vor `$ip`. Ist der Port bereits belegt, gibt die Anwendung eine Meldung aus und beendet sich mit dem Code `1`.\n\nMit der Adresse `127.0.0.1` können sich nur Programme auf demselben Rechner verbinden. Verwende sie, wenn ein Reverse Proxy auf demselben Rechner läuft und sich mit `http://127.0.0.1:8000` verbindet. Ein Proxy in einem anderen Container erreicht diese Adresse nicht und antwortet mit `502`. Behalte in diesem Fall die Standardadresse bei und veröffentliche den Port der Anwendung nicht, wie im Setup weiter unten.\n\n## Die Anwendung am Laufen halten\n\nEine nicht abgefangene Exception oder eine nicht behandelte Promise-Ablehnung stoppt die Anwendung nicht. Das Framework protokolliert den Fehler und bearbeitet weiter Anfragen. Um auf diese Fehler zu reagieren, erstelle `definitions/errors.js`:\n\n```js\nON('error', function(obj) {\n\tconsole.log('Application error:', obj.error);\n});\n```\n\nEndet der Prozess doch, startet ihn nichts von selbst neu. Das muss also etwas außerhalb der Anwendung übernehmen. Bei Docker ist das die Restart-Policy des Containers. Erstelle im Stammverzeichnis der Anwendung neben `package.json` und `package-lock.json` ein `Dockerfile`:\n\n```dockerfile\nFROM node:24-alpine\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm ci --omit=dev\nCOPY . .\nRUN chown -R node:node /app\nUSER node\nCMD [\"node\", \"index.js\"]\n```\n\nErstelle `.dockerignore`:\n\n```text\nnode_modules\ntmp\nlogs\n```\n\nErstelle `compose.yaml`. Der Dienst `nginx` und seine Datei `nginx.conf` werden im nächsten Abschnitt beschrieben:\n\n```yaml\nservices:\n  app:\n    build: .\n    restart: unless-stopped\n\n  nginx:\n    image: nginx:1.29-alpine\n    restart: unless-stopped\n    ports:\n      - \"80:80\"\n    volumes:\n      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro\n    depends_on:\n      - app\n```\n\nBaue und starte beide Dienste:\n\n```bash\n$ docker compose up -d --build\n```\n\nMit `restart: unless-stopped` startet Docker den Container jedes Mal neu, wenn der Prozess endet, egal ob der Exit-Code `0` oder `1` ist. Eine Anwendung, die du mit `docker compose stop` stoppst, bleibt gestoppt. So siehst du, wie oft der Container neu gestartet wurde:\n\n```bash\n$ docker inspect -f '{{.RestartCount}}' $(docker compose ps -a -q app)\n```\n\nBeim Start öffnet sich der Port kurz bevor die Routen geladen sind, daher erhalten Anfragen in diesem Moment eine `404`-Antwort. Ein Health-Check sollte deshalb `200` von einer Route deiner Anwendung erwarten.\n\n## nginx davorschalten\n\nErstelle `nginx.conf` neben `compose.yaml`:\n\n```nginx\nmap $http_upgrade $connection_upgrade {\n\tdefault upgrade;\n\t''      close;\n}\n\nserver {\n\tlisten 80;\n\n\tlocation / {\n\t\tproxy_pass http://app:8000;\n\t\tproxy_http_version 1.1;\n\t\tproxy_set_header Host $host;\n\t\tproxy_set_header X-Forwarded-For $remote_addr;\n\t\tproxy_set_header X-Forwarded-Proto $scheme;\n\t\tproxy_set_header Upgrade $http_upgrade;\n\t\tproxy_set_header Connection $connection_upgrade;\n\t}\n}\n```\n\n`proxy_pass` verwendet den Dienstnamen `app` und den Standardport `8000`. Nur nginx veröffentlicht einen Port, daher können sich Clients nicht direkt mit der Anwendung verbinden.\n\nDer `map`-Block und die Header `Upgrade` und `Connection` leiten WebSocket-Verbindungen durch den Proxy, und zwar auf derselben Adresse wie die HTTP-Anfragen. Für inaktive Verbindungen ist keine weitere Einstellung nötig: Das Framework pingt seine WebSocket-Clients an, und das hält eine Verbindung ohne Nachrichten durch nginx hindurch offen.\n\nSolange die Anwendung nicht läuft, antwortet nginx mit `502`. Sobald die Anwendung wieder da ist, erreicht nginx sie erneut, ohne dass nginx neu gestartet werden muss.\n\n## Was die Anwendung hinter dem Proxy sieht\n\nDie `proxy_set_header`-Zeilen bestimmen, was die Anwendung aus einer Anfrage liest:\n\n| Wert | Quelle | Ergebnis |\n| --- | --- | --- |\n| `$.ip` | Erste Adresse in `X-Forwarded-For` | Die Adresse des Clients |\n| `client.ip` (WebSocket) | Erste Adresse in `X-Forwarded-For` | Die Adresse des Clients |\n| `$.protocol` | `X-Forwarded-Proto` | `https`, wenn der Header `https` ist, sonst `http` |\n| `$.host` | `Host` | Der vom Client angefragte Hostname |\n| `$.hostname('/x')` | `X-Forwarded-Proto` und `Host` | `https://www.example.com/x` |\n| `$.address` | `X-Forwarded-Proto`, `Host` und die URL | `https://www.example.com/info/` |\n\nDas Framework vertraut `X-Forwarded-For` bei jeder Anfrage und liest die erste Adresse daraus. Daraus ergeben sich zwei Regeln:\n\n- Sende `X-Forwarded-For $remote_addr` wie in der Konfiguration oben, damit nginx alles ersetzt, was der Client gesendet hat. Mit `$proxy_add_x_forwarded_for` hängt nginx an den Wert des Clients an, und ein Client kann die Adresse wählen, die `$.ip` zurückgibt.\n- Lass nicht zu, dass sich Clients direkt mit der Anwendung verbinden, denn dann können sie den Header selbst senden.\n\n## Die Anwendung sauber beenden\n\nDie Signale `SIGTERM` und `SIGINT` beenden die Anwendung. `docker stop` und `docker compose stop` senden `SIGTERM`, und der Container endet in weniger als drei Sekunden.\n\nNach dem Signal passiert Folgendes:\n\n1. Das Event `exit` wird ausgeführt.\n2. Die Anwendung lehnt neue Verbindungen ab.\n3. Etwa 300 ms später endet der Prozess mit dem Code `1`.\n\nDer Exit-Code ist auch nach einem sauberen Beenden `1`, werte ihn also nicht als Absturz.\n\nDie Anwendung wartet nicht auf laufende Anfragen. Eine Anfrage, die innerhalb dieser 300 ms fertig wird, erhält ihre Antwort. Eine längere Anfrage erhält keine Antwort, und WebSocket-Clients werden getrennt.\n\nNutze das Event `exit` für kurze Aufgaben, zum Beispiel in `definitions/exit.js`:\n\n```js\nconst Fs = require('node:fs');\n\nON('exit', function() {\n\tFs.appendFileSync(PATH.root('stopped.log'), new Date().toISOString() + '\\n');\n});\n```\n\nHalte diese Arbeit synchron oder kürzer als 300 ms, denn nach dieser Zeit endet der Prozess. Das Signal `SIGKILL` beendet den Prozess sofort, und das Event `exit` wird nicht ausgeführt.\n\n## Logs\n\nStandardmäßig schreibt die Anwendung keine Logdatei. Alle Ausgaben gehen an die Standardstreams des Prozesses:\n\n| Ausgabe | Stream |\n| --- | --- |\n| `console.log()` | stdout |\n| Die Startinformationen | stdout |\n| Vom Framework protokollierte Fehler (`ERROR ======= ...`) | stdout |\n| `console.warn()` und `console.error()` | stderr |\n\nDocker sammelt beide Streams:\n\n```bash\n$ docker compose logs app\n```\n\nUm stattdessen in eine Datei zu schreiben, füge der Datei `config` diesen Schlüssel hinzu:\n\n```text\n$logger : true\n```\n\n`console.log()`, `console.warn()`, `console.error()` und die vom Framework protokollierten Fehler landen dann in `logs/debug.log`, und nach jedem Neustart werden neue Zeilen an die Datei angehängt. Die Startinformationen bleiben auf stdout. Um sie auszublenden, setze `$imprint : false`.\n","entries":[],"license":"MIT","updated":"2026-11-18T19:21:30.967Z"}
{"id":"JancE21cE61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/production/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Ejecución en producción","summary":"Ejecuta una aplicación Total.js en un servidor: sin watcher, en la dirección correcta, con reinicios automáticos, nginx, paradas limpias y logs.","markdown":"---\ntitle: \"Ejecución en producción\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/production/\nupdated: 2026-11-18T19:21:30.967Z\n---\n\n# Ejecución en producción\n\n> Ejecuta una aplicación Total.js en un servidor: sin watcher, en la dirección correcta, con reinicios automáticos, nginx, paradas limpias y logs.\n\nEsta guía lleva una aplicación desde `node index.js` en tu ordenador hasta un servidor: arranca sin el watcher, escucha en la dirección correcta, se reinicia cuando el proceso termina, se ejecuta detrás de nginx y se detiene y registra sus logs de forma predecible. Usa el script de inicio de [Instalación](../installation/).\n\n## Arranca sin el watcher\n\nEn el script de inicio, descomenta esta línea:\n\n```js\noptions.watcher = false;\n```\n\nDespués, inicia la aplicación desde su directorio:\n\n```bash\n$ node index.js\n```\n\nAhora la aplicación se ejecuta en ese único proceso. No arranca ningún watcher y no se escribe ningún archivo `index.pid`. `DEBUG` es `false` y la información de inicio muestra `Mode : release`. Un cambio en un archivo de código fuente no tiene efecto hasta el siguiente arranque.\n\nEl directorio de trabajo es la raíz de la aplicación, así que si la inicias desde otro directorio no encuentra sus rutas.\n\nEl argumento `--release` por sí solo no basta para producción. Pone `DEBUG` a `false`, pero el watcher sigue ejecutándose en un proceso aparte y reinicia la aplicación cuando cambia un archivo.\n\n## Elige la dirección y el puerto\n\nDe forma predeterminada, la aplicación escucha en todas las interfaces de red. Define la dirección y el puerto en el script de inicio:\n\n```js\noptions.ip = '127.0.0.1';\noptions.port = 8000;\n```\n\nO defínelos en el archivo `config`:\n\n```text\n$ip   : 127.0.0.1\n$port : 8000\n```\n\nEl puerto se toma de la primera de estas fuentes que esté definida:\n\n| Orden | Origen | Ejemplo |\n| --- | --- | --- |\n| 1 | La opción de inicio | `options.port = 8000;` |\n| 2 | La clave de configuración | `$port : 8000` |\n| 3 | Un número en la línea de comandos | `node index.js 8001` |\n| 4 | El valor predeterminado | `8000` |\n\nLa dirección sigue la misma regla: `options.ip` tiene prioridad sobre `$ip`. Si el puerto ya está en uso, la aplicación muestra un mensaje y termina con el código `1`.\n\nCon la dirección `127.0.0.1`, solo pueden conectarse los programas de la misma máquina. Úsala cuando un proxy inverso se ejecute en la misma máquina y se conecte a `http://127.0.0.1:8000`. Un proxy en otro contenedor no puede llegar a esa dirección y responde `502`. En ese caso, deja la dirección predeterminada y no publiques el puerto de la aplicación, como en la configuración que aparece más adelante.\n\n## Mantén la aplicación en marcha\n\nUna excepción no capturada o un rechazo de promesa no gestionado no detienen la aplicación. El framework registra el error y sigue atendiendo peticiones. Para reaccionar a estos errores, crea `definitions/errors.js`:\n\n```js\nON('error', function(obj) {\n\tconsole.log('Application error:', obj.error);\n});\n```\n\nCuando el proceso sí termina, nada vuelve a iniciarlo, así que de eso debe encargarse algo externo a la aplicación. Con Docker, es la política de reinicio del contenedor. Crea un `Dockerfile` en la raíz de la aplicación, junto a `package.json` y `package-lock.json`:\n\n```dockerfile\nFROM node:24-alpine\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm ci --omit=dev\nCOPY . .\nRUN chown -R node:node /app\nUSER node\nCMD [\"node\", \"index.js\"]\n```\n\nCrea `.dockerignore`:\n\n```text\nnode_modules\ntmp\nlogs\n```\n\nCrea `compose.yaml`. El servicio `nginx` y su archivo `nginx.conf` se describen en la siguiente sección:\n\n```yaml\nservices:\n  app:\n    build: .\n    restart: unless-stopped\n\n  nginx:\n    image: nginx:1.29-alpine\n    restart: unless-stopped\n    ports:\n      - \"80:80\"\n    volumes:\n      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro\n    depends_on:\n      - app\n```\n\nConstruye e inicia los dos servicios:\n\n```bash\n$ docker compose up -d --build\n```\n\nCon `restart: unless-stopped`, Docker vuelve a iniciar el contenedor cada vez que el proceso termina, tanto si el código de salida es `0` como si es `1`. Una aplicación que detienes con `docker compose stop` permanece detenida. Para ver cuántas veces se ha reiniciado el contenedor:\n\n```bash\n$ docker inspect -f '{{.RestartCount}}' $(docker compose ps -a -q app)\n```\n\nDurante el arranque, el puerto se abre poco antes de que se carguen las rutas, así que las peticiones que llegan en ese momento reciben una respuesta `404`. Por eso, una comprobación de estado debe esperar un `200` de una ruta de tu aplicación.\n\n## Pon nginx delante\n\nCrea `nginx.conf` junto a `compose.yaml`:\n\n```nginx\nmap $http_upgrade $connection_upgrade {\n\tdefault upgrade;\n\t''      close;\n}\n\nserver {\n\tlisten 80;\n\n\tlocation / {\n\t\tproxy_pass http://app:8000;\n\t\tproxy_http_version 1.1;\n\t\tproxy_set_header Host $host;\n\t\tproxy_set_header X-Forwarded-For $remote_addr;\n\t\tproxy_set_header X-Forwarded-Proto $scheme;\n\t\tproxy_set_header Upgrade $http_upgrade;\n\t\tproxy_set_header Connection $connection_upgrade;\n\t}\n}\n```\n\n`proxy_pass` usa el nombre de servicio `app` y el puerto predeterminado `8000`. Solo nginx publica un puerto, así que los clientes no pueden conectarse directamente a la aplicación.\n\nEl bloque `map` y las cabeceras `Upgrade` y `Connection` hacen pasar las conexiones WebSocket por el proxy, en la misma dirección que las peticiones HTTP. Las conexiones inactivas no necesitan ningún otro ajuste: el framework envía pings a sus clientes WebSocket, y eso mantiene abierta a través de nginx una conexión sin mensajes.\n\nMientras la aplicación está caída, nginx responde `502`. Cuando la aplicación vuelve, nginx llega de nuevo a ella sin necesidad de reiniciar nginx.\n\n## Qué ve la aplicación detrás del proxy\n\nLas líneas `proxy_set_header` deciden lo que la aplicación lee de una petición:\n\n| Valor | Origen | Resultado |\n| --- | --- | --- |\n| `$.ip` | Primera dirección de `X-Forwarded-For` | La dirección del cliente |\n| `client.ip` (WebSocket) | Primera dirección de `X-Forwarded-For` | La dirección del cliente |\n| `$.protocol` | `X-Forwarded-Proto` | `https` cuando la cabecera es `https`; en caso contrario, `http` |\n| `$.host` | `Host` | El nombre de host que pidió el cliente |\n| `$.hostname('/x')` | `X-Forwarded-Proto` y `Host` | `https://www.example.com/x` |\n| `$.address` | `X-Forwarded-Proto`, `Host` y la URL | `https://www.example.com/info/` |\n\nEl framework confía en `X-Forwarded-For` en cada petición y lee su primera dirección. De esto se derivan dos reglas:\n\n- Envía `X-Forwarded-For $remote_addr`, como en la configuración anterior, para que nginx sustituya lo que haya enviado el cliente. Con `$proxy_add_x_forwarded_for`, nginx añade la dirección al valor que envía el cliente, y un cliente puede elegir la dirección que devuelve `$.ip`.\n- No permitas que los clientes se conecten directamente a la aplicación, porque entonces pueden enviar ellos mismos la cabecera.\n\n## Detén la aplicación de forma limpia\n\nLas señales `SIGTERM` y `SIGINT` detienen la aplicación. `docker stop` y `docker compose stop` envían `SIGTERM`, y el contenedor termina en menos de tres segundos.\n\nTras la señal:\n\n1. Se ejecuta el evento `exit`.\n2. La aplicación rechaza las conexiones nuevas.\n3. Unos 300 ms después, el proceso termina con el código `1`.\n\nEl código de salida también es `1` tras una parada limpia, así que no lo interpretes como un fallo.\n\nLa aplicación no espera a las peticiones en curso. Una petición que termina dentro de esos 300 ms recibe su respuesta. Una petición más larga no recibe respuesta, y los clientes WebSocket se desconectan.\n\nUsa el evento `exit` para tareas breves, por ejemplo en `definitions/exit.js`:\n\n```js\nconst Fs = require('node:fs');\n\nON('exit', function() {\n\tFs.appendFileSync(PATH.root('stopped.log'), new Date().toISOString() + '\\n');\n});\n```\n\nHaz que este trabajo sea síncrono o dure menos de 300 ms, porque el proceso termina pasado ese tiempo. La señal `SIGKILL` termina el proceso de inmediato y el evento `exit` no se ejecuta.\n\n## Logs\n\nDe forma predeterminada, la aplicación no escribe ningún archivo de log. Toda la salida va a los flujos estándar del proceso:\n\n| Salida | Flujo |\n| --- | --- |\n| `console.log()` | stdout |\n| La información de inicio | stdout |\n| Errores registrados por el framework (`ERROR ======= ...`) | stdout |\n| `console.warn()` y `console.error()` | stderr |\n\nDocker recoge los dos flujos:\n\n```bash\n$ docker compose logs app\n```\n\nPara escribir en un archivo, añade esta clave al archivo `config`:\n\n```text\n$logger : true\n```\n\n`console.log()`, `console.warn()`, `console.error()` y los errores registrados por el framework pasan entonces a `logs/debug.log`, y las líneas nuevas se añaden al archivo después de cada reinicio. La información de inicio se queda en stdout. Para ocultarla, define `$imprint : false`.\n","entries":[],"license":"MIT","updated":"2026-11-18T19:21:30.967Z"}
{"id":"JancE21cE61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/production/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Exécuter en production","summary":"Exécute une application Total.js sur un serveur : sans observateur, sur la bonne adresse, avec des redémarrages automatiques, nginx, des arrêts propres et des journaux.","markdown":"---\ntitle: \"Exécuter en production\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/production/\nupdated: 2026-11-18T19:21:30.967Z\n---\n\n# Exécuter en production\n\n> Exécute une application Total.js sur un serveur : sans observateur, sur la bonne adresse, avec des redémarrages automatiques, nginx, des arrêts propres et des journaux.\n\nCe guide fait passer une application de `node index.js` sur ton ordinateur à un serveur : elle démarre sans l'observateur, écoute sur la bonne adresse, redémarre quand le processus se termine, tourne derrière nginx, et s'arrête et journalise de façon prévisible. Il utilise le script de démarrage présenté dans [Installation](../installation/).\n\n## Démarrer sans l'observateur\n\nDans le script de démarrage, décommente cette ligne :\n\n```js\noptions.watcher = false;\n```\n\nDémarre ensuite l'application depuis son répertoire :\n\n```bash\n$ node index.js\n```\n\nL'application tourne désormais dans ce seul processus. Aucun observateur ne démarre et aucun fichier `index.pid` n'est écrit. `DEBUG` vaut `false` et les informations de démarrage affichent `Mode : release`. La modification d'un fichier source n'a aucun effet avant le prochain démarrage.\n\nLe répertoire de travail est la racine de l'application : si tu la démarres depuis un autre répertoire, elle ne trouve donc pas ses routes.\n\nL'argument `--release` seul ne suffit pas pour la production. Il met `DEBUG` à `false`, mais l'observateur continue de tourner dans un processus séparé et redémarre l'application quand un fichier change.\n\n## Choisir l'adresse et le port\n\nPar défaut, l'application écoute sur toutes les interfaces réseau. Définis l'adresse et le port dans le script de démarrage :\n\n```js\noptions.ip = '127.0.0.1';\noptions.port = 8000;\n```\n\nOu définis-les dans le fichier `config` :\n\n```text\n$ip   : 127.0.0.1\n$port : 8000\n```\n\nLe port provient de la première de ces sources qui est définie :\n\n| Ordre | Source | Exemple |\n| --- | --- | --- |\n| 1 | L'option de démarrage | `options.port = 8000;` |\n| 2 | La clé de configuration | `$port : 8000` |\n| 3 | Un nombre dans la ligne de commande | `node index.js 8001` |\n| 4 | La valeur par défaut | `8000` |\n\nL'adresse suit la même règle : `options.ip` l'emporte sur `$ip`. Quand le port est déjà utilisé, l'application affiche un message et se termine avec le code `1`.\n\nAvec l'adresse `127.0.0.1`, seuls les programmes de la même machine peuvent se connecter. Utilise-la quand un proxy inverse tourne sur la même machine et se connecte à `http://127.0.0.1:8000`. Un proxy situé dans un autre conteneur ne peut pas joindre cette adresse et répond `502`. Dans ce cas, garde l'adresse par défaut et ne publie pas le port de l'application, comme dans la configuration ci-dessous.\n\n## Maintenir l'application en marche\n\nUne exception non interceptée ou un rejet de promesse non géré n'arrête pas l'application. Le framework journalise l'erreur et continue de servir les requêtes. Pour réagir à ces erreurs, crée `definitions/errors.js` :\n\n```js\nON('error', function(obj) {\n\tconsole.log('Application error:', obj.error);\n});\n```\n\nQuand le processus se termine réellement, rien ne le relance : un élément extérieur à l'application doit donc s'en charger. Avec Docker, c'est la politique de redémarrage du conteneur. Crée un `Dockerfile` à la racine de l'application, à côté de `package.json` et de `package-lock.json` :\n\n```dockerfile\nFROM node:24-alpine\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm ci --omit=dev\nCOPY . .\nRUN chown -R node:node /app\nUSER node\nCMD [\"node\", \"index.js\"]\n```\n\nCrée `.dockerignore` :\n\n```text\nnode_modules\ntmp\nlogs\n```\n\nCrée `compose.yaml`. Le service `nginx` et son fichier `nginx.conf` sont décrits dans la section suivante :\n\n```yaml\nservices:\n  app:\n    build: .\n    restart: unless-stopped\n\n  nginx:\n    image: nginx:1.29-alpine\n    restart: unless-stopped\n    ports:\n      - \"80:80\"\n    volumes:\n      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro\n    depends_on:\n      - app\n```\n\nConstruis et démarre les deux services :\n\n```bash\n$ docker compose up -d --build\n```\n\nAvec `restart: unless-stopped`, Docker redémarre le conteneur chaque fois que le processus se termine, que le code de sortie soit `0` ou `1`. Une application que tu arrêtes avec `docker compose stop` reste arrêtée. Pour voir combien de fois le conteneur a redémarré :\n\n```bash\n$ docker inspect -f '{{.RestartCount}}' $(docker compose ps -a -q app)\n```\n\nPendant un démarrage, le port s'ouvre peu avant le chargement des routes : les requêtes reçues à ce moment-là obtiennent donc une réponse `404`. Un contrôle de santé doit par conséquent attendre un `200` d'une route de ton application.\n\n## Placer nginx en frontal\n\nCrée `nginx.conf` à côté de `compose.yaml` :\n\n```nginx\nmap $http_upgrade $connection_upgrade {\n\tdefault upgrade;\n\t''      close;\n}\n\nserver {\n\tlisten 80;\n\n\tlocation / {\n\t\tproxy_pass http://app:8000;\n\t\tproxy_http_version 1.1;\n\t\tproxy_set_header Host $host;\n\t\tproxy_set_header X-Forwarded-For $remote_addr;\n\t\tproxy_set_header X-Forwarded-Proto $scheme;\n\t\tproxy_set_header Upgrade $http_upgrade;\n\t\tproxy_set_header Connection $connection_upgrade;\n\t}\n}\n```\n\n`proxy_pass` utilise le nom de service `app` et le port par défaut `8000`. Seul nginx publie un port : les clients ne peuvent donc pas se connecter directement à l'application.\n\nLe bloc `map` et les en-têtes `Upgrade` et `Connection` font passer les connexions WebSocket par le proxy, sur la même adresse que les requêtes HTTP. Aucun autre réglage n'est nécessaire pour les connexions inactives : le framework envoie des pings à ses clients WebSocket, ce qui maintient ouverte à travers nginx une connexion sans messages.\n\nTant que l'application est arrêtée, nginx répond `502`. Quand elle revient, nginx la joint de nouveau sans avoir besoin de redémarrer.\n\n## Ce que l'application voit derrière le proxy\n\nLes lignes `proxy_set_header` déterminent ce que l'application lit dans une requête :\n\n| Valeur | Source | Résultat |\n| --- | --- | --- |\n| `$.ip` | Première adresse de `X-Forwarded-For` | L'adresse du client |\n| `client.ip` (WebSocket) | Première adresse de `X-Forwarded-For` | L'adresse du client |\n| `$.protocol` | `X-Forwarded-Proto` | `https` quand l'en-tête vaut `https`, sinon `http` |\n| `$.host` | `Host` | Le nom d'hôte demandé par le client |\n| `$.hostname('/x')` | `X-Forwarded-Proto` et `Host` | `https://www.example.com/x` |\n| `$.address` | `X-Forwarded-Proto`, `Host` et l'URL | `https://www.example.com/info/` |\n\nLe framework fait confiance à `X-Forwarded-For` sur chaque requête et lit sa première adresse. Il en découle deux règles :\n\n- Envoie `X-Forwarded-For $remote_addr`, comme dans la configuration ci-dessus, pour que nginx remplace ce que le client a envoyé. Avec `$proxy_add_x_forwarded_for`, nginx complète la valeur fournie par le client, et un client peut alors choisir l'adresse que renvoie `$.ip`.\n- Ne laisse pas les clients se connecter directement à l'application, car ils pourraient alors envoyer eux-mêmes cet en-tête.\n\n## Arrêter l'application proprement\n\nLes signaux `SIGTERM` et `SIGINT` arrêtent l'application. `docker stop` et `docker compose stop` envoient `SIGTERM`, et le conteneur s'arrête en moins de trois secondes.\n\nAprès le signal :\n\n1. L'événement `exit` s'exécute.\n2. L'application refuse les nouvelles connexions.\n3. Environ 300 ms plus tard, le processus se termine avec le code `1`.\n\nLe code de sortie est `1` même après un arrêt propre : ne l'interprète donc pas comme un plantage.\n\nL'application n'attend pas les requêtes en cours. Une requête qui se termine dans ces 300 ms obtient sa réponse. Une requête plus longue n'obtient aucune réponse, et les clients WebSocket sont déconnectés.\n\nUtilise l'événement `exit` pour des tâches courtes, par exemple dans `definitions/exit.js` :\n\n```js\nconst Fs = require('node:fs');\n\nON('exit', function() {\n\tFs.appendFileSync(PATH.root('stopped.log'), new Date().toISOString() + '\\n');\n});\n```\n\nGarde ces tâches synchrones ou d'une durée inférieure à 300 ms, car le processus se termine après ce délai. Le signal `SIGKILL` met fin au processus immédiatement et l'événement `exit` ne s'exécute pas.\n\n## Journaux\n\nPar défaut, l'application n'écrit aucun fichier journal. Toute la sortie va vers les flux standard du processus :\n\n| Sortie | Flux |\n| --- | --- |\n| `console.log()` | stdout |\n| Les informations de démarrage | stdout |\n| Les erreurs journalisées par le framework (`ERROR ======= ...`) | stdout |\n| `console.warn()` et `console.error()` | stderr |\n\nDocker collecte les deux flux :\n\n```bash\n$ docker compose logs app\n```\n\nPour écrire plutôt dans un fichier, ajoute cette clé au fichier `config` :\n\n```text\n$logger : true\n```\n\n`console.log()`, `console.warn()`, `console.error()` et les erreurs journalisées par le framework vont alors dans `logs/debug.log`, et les nouvelles lignes s'ajoutent au fichier après chaque redémarrage. Les informations de démarrage restent sur stdout. Pour les masquer, définis `$imprint : false`.\n","entries":[],"license":"MIT","updated":"2026-11-18T19:21:30.967Z"}
{"id":"JancE21cE61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/production/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Esecuzione in produzione","summary":"Esegui un'applicazione Total.js su un server: senza osservatore, sull'indirizzo giusto, con riavvii automatici, nginx, arresti puliti e log.","markdown":"---\ntitle: Esecuzione in produzione\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/production/\nupdated: 2026-11-18T19:21:30.967Z\n---\n\n# Esecuzione in produzione\n\n> Esegui un'applicazione Total.js su un server: senza osservatore, sull'indirizzo giusto, con riavvii automatici, nginx, arresti puliti e log.\n\nQuesta guida porta un'applicazione da `node index.js` sul tuo computer a un server: si avvia senza l'osservatore, resta in ascolto sull'indirizzo giusto, riparte quando il processo termina, funziona dietro nginx e si arresta e scrive i log in modo prevedibile. Usa lo script di avvio descritto in [Installazione](../installation/).\n\n## Avviare senza l'osservatore\n\nNello script di avvio, togli il commento da questa riga:\n\n```js\noptions.watcher = false;\n```\n\nPoi avvia l'applicazione dalla sua directory:\n\n```bash\n$ node index.js\n```\n\nOra l'applicazione viene eseguita in quell'unico processo. Non parte nessun osservatore e non viene scritto nessun file `index.pid`. `DEBUG` vale `false` e le informazioni di avvio mostrano `Mode : release`. Una modifica a un file sorgente non ha effetto fino all'avvio successivo.\n\nLa directory di lavoro è la radice dell'applicazione, quindi con un avvio da un'altra directory le route dell'applicazione non vengono trovate.\n\nIl solo argomento `--release` non basta per la produzione. Imposta `DEBUG` su `false`, ma l'osservatore continua a funzionare in un processo separato e riavvia l'applicazione quando un file cambia.\n\n## Scegliere l'indirizzo e la porta\n\nPer impostazione predefinita l'applicazione resta in ascolto su tutte le interfacce di rete. Imposta l'indirizzo e la porta nello script di avvio:\n\n```js\noptions.ip = '127.0.0.1';\noptions.port = 8000;\n```\n\nOppure impostali nel file `config`:\n\n```text\n$ip   : 127.0.0.1\n$port : 8000\n```\n\nLa porta viene dalla prima di queste origini che risulta impostata:\n\n| Ordine | Origine | Esempio |\n| --- | --- | --- |\n| 1 | L'opzione di avvio | `options.port = 8000;` |\n| 2 | La chiave di configurazione | `$port : 8000` |\n| 3 | Un numero nella riga di comando | `node index.js 8001` |\n| 4 | Il valore predefinito | `8000` |\n\nL'indirizzo segue la stessa regola: `options.ip` ha la precedenza su `$ip`. Quando la porta è già in uso, l'applicazione stampa un messaggio ed esce con codice `1`.\n\nCon l'indirizzo `127.0.0.1` possono connettersi solo i programmi sulla stessa macchina. Usalo quando un reverse proxy gira sulla stessa macchina e si connette a `http://127.0.0.1:8000`. Un proxy in un altro container non può raggiungere quell'indirizzo e risponde `502`. In quel caso mantieni l'indirizzo predefinito e non pubblicare la porta dell'applicazione, come nella configurazione qui sotto.\n\n## Mantenere l'applicazione in esecuzione\n\nUn'eccezione non catturata o un rifiuto di promise non gestito non fermano l'applicazione. Il framework registra l'errore nel log e continua a servire le richieste. Per reagire a questi errori, crea `definitions/errors.js`:\n\n```js\nON('error', function(obj) {\n\tconsole.log('Application error:', obj.error);\n});\n```\n\nQuando il processo termina davvero, nessuno lo riavvia, quindi deve occuparsene qualcosa di esterno all'applicazione. Con Docker, è la politica di riavvio del container. Crea un `Dockerfile` nella radice dell'applicazione, accanto a `package.json` e `package-lock.json`:\n\n```dockerfile\nFROM node:24-alpine\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm ci --omit=dev\nCOPY . .\nRUN chown -R node:node /app\nUSER node\nCMD [\"node\", \"index.js\"]\n```\n\nCrea `.dockerignore`:\n\n```text\nnode_modules\ntmp\nlogs\n```\n\nCrea `compose.yaml`. Il servizio `nginx` e il suo file `nginx.conf` sono descritti nella prossima sezione:\n\n```yaml\nservices:\n  app:\n    build: .\n    restart: unless-stopped\n\n  nginx:\n    image: nginx:1.29-alpine\n    restart: unless-stopped\n    ports:\n      - \"80:80\"\n    volumes:\n      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro\n    depends_on:\n      - app\n```\n\nCompila e avvia entrambi i servizi:\n\n```bash\n$ docker compose up -d --build\n```\n\nCon `restart: unless-stopped`, Docker riavvia il container ogni volta che il processo esce, sia con codice di uscita `0` sia con `1`. Un'applicazione che fermi con `docker compose stop` resta ferma. Per vedere quante volte il container è stato riavviato:\n\n```bash\n$ docker inspect -f '{{.RestartCount}}' $(docker compose ps -a -q app)\n```\n\nDurante l'avvio la porta si apre poco prima che le route vengano caricate, quindi le richieste che arrivano in quel momento ricevono una risposta `404`. Un controllo di integrità deve quindi aspettarsi `200` da una route della tua applicazione.\n\n## Mettere nginx davanti\n\nCrea `nginx.conf` accanto a `compose.yaml`:\n\n```nginx\nmap $http_upgrade $connection_upgrade {\n\tdefault upgrade;\n\t''      close;\n}\n\nserver {\n\tlisten 80;\n\n\tlocation / {\n\t\tproxy_pass http://app:8000;\n\t\tproxy_http_version 1.1;\n\t\tproxy_set_header Host $host;\n\t\tproxy_set_header X-Forwarded-For $remote_addr;\n\t\tproxy_set_header X-Forwarded-Proto $scheme;\n\t\tproxy_set_header Upgrade $http_upgrade;\n\t\tproxy_set_header Connection $connection_upgrade;\n\t}\n}\n```\n\n`proxy_pass` usa il nome del servizio `app` e la porta predefinita `8000`. Solo nginx pubblica una porta, quindi i client non possono connettersi direttamente all'applicazione.\n\nIl blocco `map` e gli header `Upgrade` e `Connection` fanno passare le connessioni WebSocket attraverso il proxy, sullo stesso indirizzo delle richieste HTTP. Per le connessioni inattive non serve nessun'altra impostazione: il framework invia ping ai suoi client WebSocket, e questo mantiene aperta attraverso nginx una connessione senza messaggi.\n\nFinché l'applicazione è inattiva, nginx risponde `502`. Quando l'applicazione torna disponibile, nginx la raggiunge di nuovo senza bisogno di riavviare nginx.\n\n## Cosa vede l'applicazione dietro il proxy\n\nLe righe `proxy_set_header` decidono cosa legge l'applicazione da una richiesta:\n\n| Valore | Origine | Risultato |\n| --- | --- | --- |\n| `$.ip` | Primo indirizzo in `X-Forwarded-For` | L'indirizzo del client |\n| `client.ip` (WebSocket) | Primo indirizzo in `X-Forwarded-For` | L'indirizzo del client |\n| `$.protocol` | `X-Forwarded-Proto` | `https` quando l'header è `https`, altrimenti `http` |\n| `$.host` | `Host` | Il nome host richiesto dal client |\n| `$.hostname('/x')` | `X-Forwarded-Proto` e `Host` | `https://www.example.com/x` |\n| `$.address` | `X-Forwarded-Proto`, `Host` e l'URL | `https://www.example.com/info/` |\n\nIl framework si fida di `X-Forwarded-For` a ogni richiesta e ne legge il primo indirizzo. Da qui derivano due regole:\n\n- Invia `X-Forwarded-For $remote_addr`, come nella configurazione qui sopra, così nginx sostituisce qualunque valore inviato dal client. Con `$proxy_add_x_forwarded_for`, nginx aggiunge in coda al valore del client, e un client può scegliere l'indirizzo restituito da `$.ip`.\n- Non permettere ai client di connettersi direttamente all'applicazione, perché in quel caso possono inviare l'header da soli.\n\n## Arrestare l'applicazione in modo pulito\n\nI segnali `SIGTERM` e `SIGINT` arrestano l'applicazione. `docker stop` e `docker compose stop` inviano `SIGTERM`, e il container termina in meno di tre secondi.\n\nDopo il segnale:\n\n1. Viene eseguito l'evento `exit`.\n2. L'applicazione rifiuta le nuove connessioni.\n3. Circa 300 ms dopo il processo esce con codice `1`.\n\nIl codice di uscita è `1` anche dopo un arresto pulito, quindi non interpretarlo come un crash.\n\nL'applicazione non aspetta le richieste in corso. Una richiesta che termina entro quei 300 ms riceve la sua risposta. Una richiesta più lunga non riceve nessuna risposta, e i client WebSocket vengono disconnessi.\n\nUsa l'evento `exit` per lavori brevi, ad esempio in `definitions/exit.js`:\n\n```js\nconst Fs = require('node:fs');\n\nON('exit', function() {\n\tFs.appendFileSync(PATH.root('stopped.log'), new Date().toISOString() + '\\n');\n});\n```\n\nFai in modo che questo lavoro sia sincrono o duri meno di 300 ms, perché il processo termina dopo quel tempo. Il segnale `SIGKILL` termina subito il processo e l'evento `exit` non viene eseguito.\n\n## Log\n\nPer impostazione predefinita l'applicazione non scrive nessun file di log. Tutto l'output va sui flussi standard del processo:\n\n| Output | Flusso |\n| --- | --- |\n| `console.log()` | stdout |\n| Le informazioni di avvio | stdout |\n| Gli errori registrati dal framework (`ERROR ======= ...`) | stdout |\n| `console.warn()` e `console.error()` | stderr |\n\nDocker raccoglie entrambi i flussi:\n\n```bash\n$ docker compose logs app\n```\n\nPer scrivere invece su un file, aggiungi questa chiave al file `config`:\n\n```text\n$logger : true\n```\n\n`console.log()`, `console.warn()`, `console.error()` e gli errori registrati dal framework finiscono allora in `logs/debug.log`, e dopo ogni riavvio le nuove righe vengono aggiunte al file. Le informazioni di avvio restano su stdout. Per nasconderle, imposta `$imprint : false`.\n","entries":[],"license":"MIT","updated":"2026-11-18T19:21:30.967Z"}
{"id":"JancE21cE61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/production/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Beh v produkcii","summary":"Spusti aplikáciu Total.js na serveri: bez sledovača, na správnej adrese, s automatickými reštartmi, za nginx, s čistým zastavením a logmi.","markdown":"---\ntitle: Beh v produkcii\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/production/\nupdated: 2026-11-18T19:21:30.967Z\n---\n\n# Beh v produkcii\n\n> Spusti aplikáciu Total.js na serveri: bez sledovača, na správnej adrese, s automatickými reštartmi, za nginx, s čistým zastavením a logmi.\n\nTáto príručka ťa prevedie cestou aplikácie od `node index.js` na tvojom počítači až na server: spustí sa bez sledovača, počúva na správnej adrese, po ukončení procesu sa reštartuje, beží za nginx a zastavuje sa aj loguje predvídateľným spôsobom. Používa štartovací skript z časti [Inštalácia](../installation/).\n\n## Spusti aplikáciu bez sledovača\n\nV štartovacom skripte odkomentuj tento riadok:\n\n```js\noptions.watcher = false;\n```\n\nPotom spusti aplikáciu z jej adresára:\n\n```bash\n$ node index.js\n```\n\nAplikácia teraz beží v tomto jedinom procese. Nespustí sa žiadny sledovač a nezapíše sa súbor `index.pid`. `DEBUG` má hodnotu `false` a v štartovacích informáciách sa vypíše `Mode : release`. Zmena zdrojového súboru sa neprejaví až do ďalšieho spustenia.\n\nPracovným adresárom je koreňový adresár aplikácie, takže pri spustení z iného adresára sa routy aplikácie nenájdu.\n\nSamotný argument `--release` na produkciu nestačí. Nastaví `DEBUG` na `false`, ale sledovač ďalej beží v samostatnom procese a pri zmene súboru aplikáciu reštartuje.\n\n## Zvoľ adresu a port\n\nAplikácia predvolene počúva na všetkých sieťových rozhraniach. Adresu a port nastav v štartovacom skripte:\n\n```js\noptions.ip = '127.0.0.1';\noptions.port = 8000;\n```\n\nAlebo ich nastav v súbore `config`:\n\n```text\n$ip   : 127.0.0.1\n$port : 8000\n```\n\nPort sa vezme z prvého zdroja v tomto poradí, ktorý je nastavený:\n\n| Poradie | Zdroj | Príklad |\n| --- | --- | --- |\n| 1 | Možnosť pri štarte | `options.port = 8000;` |\n| 2 | Konfiguračný kľúč | `$port : 8000` |\n| 3 | Číslo v príkazovom riadku | `node index.js 8001` |\n| 4 | Predvolená hodnota | `8000` |\n\nPre adresu platí rovnaké pravidlo: `options.ip` má prednosť pred `$ip`. Keď je port už obsadený, aplikácia vypíše správu a skončí s kódom `1`.\n\nNa adresu `127.0.0.1` sa môžu pripojiť iba programy na tom istom počítači. Použi ju, keď na tom istom počítači beží reverzné proxy, ktoré sa pripája na `http://127.0.0.1:8000`. Proxy v inom kontajneri sa na túto adresu nedostane a odpovie `502`. V takom prípade ponechaj predvolenú adresu a port aplikácie nepublikuj, ako v konfigurácii nižšie.\n\n## Udržuj aplikáciu v behu\n\nNezachytená výnimka ani neošetrené odmietnutie promisu aplikáciu nezastavia. Framework chybu zaznamená a ďalej obsluhuje požiadavky. Ak chceš na tieto chyby reagovať, vytvor `definitions/errors.js`:\n\n```js\nON('error', function(obj) {\n\tconsole.log('Application error:', obj.error);\n});\n```\n\nKeď sa proces predsa len ukončí, nič ho znova nespustí, takže sa o to musí postarať niečo mimo aplikácie. V Dockeri je to politika reštartu kontajnera. V koreňovom adresári aplikácie vytvor `Dockerfile`, vedľa `package.json` a `package-lock.json`:\n\n```dockerfile\nFROM node:24-alpine\nWORKDIR /app\nCOPY package.json package-lock.json ./\nRUN npm ci --omit=dev\nCOPY . .\nRUN chown -R node:node /app\nUSER node\nCMD [\"node\", \"index.js\"]\n```\n\nVytvor `.dockerignore`:\n\n```text\nnode_modules\ntmp\nlogs\n```\n\nVytvor `compose.yaml`. Služba `nginx` a jej súbor `nginx.conf` sú opísané v ďalšej časti:\n\n```yaml\nservices:\n  app:\n    build: .\n    restart: unless-stopped\n\n  nginx:\n    image: nginx:1.29-alpine\n    restart: unless-stopped\n    ports:\n      - \"80:80\"\n    volumes:\n      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro\n    depends_on:\n      - app\n```\n\nZostav a spusti obe služby:\n\n```bash\n$ docker compose up -d --build\n```\n\nS `restart: unless-stopped` Docker kontajner znova spustí pri každom ukončení procesu, či je kód ukončenia `0` alebo `1`. Aplikácia, ktorú zastavíš príkazom `docker compose stop`, zostane zastavená. Počet reštartov kontajnera zistíš takto:\n\n```bash\n$ docker inspect -f '{{.RestartCount}}' $(docker compose ps -a -q app)\n```\n\nPri štarte sa port otvorí krátko pred načítaním rout, takže požiadavky v tej chvíli dostanú odpoveď `404`. Kontrola stavu by preto mala očakávať `200` od niektorej routy tvojej aplikácie.\n\n## Postav nginx pred aplikáciu\n\nVedľa `compose.yaml` vytvor `nginx.conf`:\n\n```nginx\nmap $http_upgrade $connection_upgrade {\n\tdefault upgrade;\n\t''      close;\n}\n\nserver {\n\tlisten 80;\n\n\tlocation / {\n\t\tproxy_pass http://app:8000;\n\t\tproxy_http_version 1.1;\n\t\tproxy_set_header Host $host;\n\t\tproxy_set_header X-Forwarded-For $remote_addr;\n\t\tproxy_set_header X-Forwarded-Proto $scheme;\n\t\tproxy_set_header Upgrade $http_upgrade;\n\t\tproxy_set_header Connection $connection_upgrade;\n\t}\n}\n```\n\n`proxy_pass` používa názov služby `app` a predvolený port `8000`. Port publikuje iba nginx, takže klienti sa k aplikácii nemôžu pripojiť priamo.\n\nBlok `map` a hlavičky `Upgrade` a `Connection` prepúšťajú WebSocket pripojenia cez proxy, na tej istej adrese ako HTTP požiadavky. Pre nečinné pripojenia netreba nič ďalšie nastavovať: framework posiela svojim WebSocket klientom ping, a vďaka tomu zostáva pripojenie bez správ cez nginx otvorené.\n\nKým je aplikácia nedostupná, nginx odpovedá `502`. Keď aplikácia znova beží, nginx sa k nej opäť dostane bez reštartu nginx.\n\n## Čo aplikácia vidí za proxy\n\nRiadky `proxy_set_header` určujú, čo aplikácia z požiadavky prečíta:\n\n| Hodnota | Zdroj | Výsledok |\n| --- | --- | --- |\n| `$.ip` | Prvá adresa v `X-Forwarded-For` | Adresa klienta |\n| `client.ip` (WebSocket) | Prvá adresa v `X-Forwarded-For` | Adresa klienta |\n| `$.protocol` | `X-Forwarded-Proto` | `https`, keď má hlavička hodnotu `https`, inak `http` |\n| `$.host` | `Host` | Názov hostiteľa, ktorý klient požadoval |\n| `$.hostname('/x')` | `X-Forwarded-Proto` a `Host` | `https://www.example.com/x` |\n| `$.address` | `X-Forwarded-Proto`, `Host` a URL | `https://www.example.com/info/` |\n\nFramework dôveruje hlavičke `X-Forwarded-For` pri každej požiadavke a číta z nej prvú adresu. Vyplývajú z toho dve pravidlá:\n\n- Posielaj `X-Forwarded-For $remote_addr` ako v konfigurácii vyššie, aby nginx nahradil všetko, čo poslal klient. S `$proxy_add_x_forwarded_for` nginx pridáva adresu k hodnote od klienta a klient si tak môže zvoliť adresu, ktorú vráti `$.ip`.\n- Nedovoľ klientom pripájať sa k aplikácii priamo, pretože by potom mohli túto hlavičku poslať sami.\n\n## Zastav aplikáciu čisto\n\nSignály `SIGTERM` a `SIGINT` aplikáciu zastavia. `docker stop` a `docker compose stop` posielajú `SIGTERM` a kontajner sa ukončí za menej ako tri sekundy.\n\nPo signáli:\n\n1. Spustí sa udalosť `exit`.\n2. Aplikácia odmieta nové pripojenia.\n3. Približne o 300 ms neskôr sa proces ukončí s kódom `1`.\n\nKód ukončenia je `1` aj po čistom zastavení, takže ho neber ako pád aplikácie.\n\nAplikácia nečaká na prebiehajúce požiadavky. Požiadavka, ktorá sa dokončí v priebehu týchto 300 ms, dostane odpoveď. Dlhšia požiadavka odpoveď nedostane a WebSocket klienti sa odpoja.\n\nUdalosť `exit` používaj na krátku prácu, napríklad v `definitions/exit.js`:\n\n```js\nconst Fs = require('node:fs');\n\nON('exit', function() {\n\tFs.appendFileSync(PATH.root('stopped.log'), new Date().toISOString() + '\\n');\n});\n```\n\nTáto práca musí byť synchrónna alebo kratšia ako 300 ms, pretože proces sa po tomto čase ukončí. Signál `SIGKILL` ukončí proces okamžite a udalosť `exit` sa nespustí.\n\n## Logy\n\nAplikácia predvolene nezapisuje žiadny logovací súbor. Celý výstup ide do štandardných prúdov procesu:\n\n| Výstup | Prúd |\n| --- | --- |\n| `console.log()` | stdout |\n| Štartovacie informácie | stdout |\n| Chyby zaznamenané frameworkom (`ERROR ======= ...`) | stdout |\n| `console.warn()` a `console.error()` | stderr |\n\nDocker zbiera oba prúdy:\n\n```bash\n$ docker compose logs app\n```\n\nAk chceš namiesto toho zapisovať do súboru, pridaj do súboru `config` tento kľúč:\n\n```text\n$logger : true\n```\n\n`console.log()`, `console.warn()`, `console.error()` a chyby zaznamenané frameworkom potom idú do `logs/debug.log` a po každom reštarte sa do súboru pridávajú nové riadky. Štartovacie informácie zostávajú na stdout. Ak ich chceš skryť, nastav `$imprint : false`.\n","entries":[],"license":"MIT","updated":"2026-11-18T19:21:30.967Z"}
{"id":"JacV4g4ZP60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/configuration/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Configuration","summary":"The config file and its types, .env, CONF, LOADCONFIG() and DEBUG.","markdown":"---\ntitle: Configuration\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/configuration/\nupdated: 2026-11-16T15:32:37.496Z\n---\n\n# Configuration\n\n> The config file and its types, .env, CONF, LOADCONFIG() and DEBUG.\n\nThe configuration of a Total.js 5 application lives in a plain text file named `config` in the root directory of the application. The framework reads it when it starts and copies every key into the global object `CONF` (the same object as `F.config`). Your code and the framework read the values from there.\n\n```\nname             : My application\n$api             : /api/\n$httpmaxsize     : 1024\n$cors            : https://app.example.com\nmail_from        : info@example.com\nsmtp (json)      : {\"server\":\"smtp.example.com\",\"port\":465,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n```js\n// anywhere in the code\nconsole.log(CONF.name);       // My application\nconsole.log(F.config.$api);   // /api/\n```\n\nKeys that start with `$` are settings of the framework. Other keys (`name`, `mail_from`, your own keys) are free to use. Most `$` keys have a default value, so the file only needs the keys you change. The reference of [Configuration](../../reference/configuration/) lists them all.\n\n## The format of the file\n\nEach line is `key : value`. The framework splits the line at the first colon and skips one character after it, so always put a space after the colon. Spaces before the colon and around the value are removed, which lets you align the values in columns. Values may contain more colons (URLs, times).\n\n- Empty lines and lines that start with `#` or `//` are ignored.\n- `true` and `false` become booleans, and a value of one digit (`0` to `9`) becomes a number. Every other value without a type is a string.\n- A value that starts with `base64 ` or `hex ` is decoded to a string first.\n\nA type in parentheses after the key converts the value:\n\n| Type | Result |\n| --- | --- |\n| `(number)`, `(float)`, `(double)`, `(currency)` | A number |\n| `(boolean)`, `(bool)` | `true` when the value contains `true`, `on`, `1` or `enabled` |\n| `(array)` | An array of strings, split by commas and trimmed |\n| `(json)`, `(object)` | The parsed JSON |\n| `(eval)` | The result of a JavaScript expression |\n| `(date)`, `(time)`, `(datetime)` | A `Date` |\n| `(env)`, `(environment)` | The value of the environment variable with that name |\n| `(config)` | The value of another key that is already in `CONF` |\n| `(random)` | A new random identifier of the given length (default 10) on every start |\n| `(generate)`, `(hash)` | A random string of the given length (default 10), created once and kept |\n\n```\n$httptimeout (number)  : 10\nallowed (array)        : admin, editor\nlimits (json)          : {\"files\":10,\"size\":5}\nstarted (date)         : 2025-01-01\ndb (env)               : DATABASE_URL\nappname (config)       : name\ntoken (generate)       : 32\nlogo                   : base64 aGVsbG8=\n```\n\n`(generate)` and `(hash)` values are stored in `databases/config.json` the first time and read from there on every later start, so a generated secret does not change after a restart. Delete the key from that file to create a new one.\n\n`(config)` reads `CONF` before the file is applied: it sees the defaults and the values loaded earlier, not the keys of the same file.\n\nUse `(number)` for every numeric value of your own keys.\n\n## Environment variables and `.env`\n\nBefore the `config` file, the framework reads the file `.env` in the root directory, if it exists. Each line is `KEY=value`, with no spaces around `=`. Lines that start with `#` or `//` are ignored, quotes around the value are removed and `\\n` becomes a new line. A key is copied into `process.env` only when the variable is not already set, so the real environment always wins.\n\n```\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/app\nAPI_KEY=\"abc123\"\n```\n\nThe `config` file reads them with the `(env)` type:\n\n```\ndatabase (env)   : DATABASE_URL\napikey (env)     : API_KEY\n```\n\nThe framework itself reads a few variables: `PORT` (see the port below), and it sets `TZ` from `$timezone` and `NODE_TLS_REJECT_UNAUTHORIZED` from `$insecure`.\n\n## Loading order\n\nWhen the application starts, the framework loads, in this order:\n\n1. The `config` object from the options of `F.http()` (for example `F.http({ config: { name: 'Shop' } })`).\n2. The file `.env`.\n3. The file `config`. Its values win over the options.\n4. The file `version`: its first line, as a number, becomes `CONF.version`.\n5. The `config` file of each plugin, before the other files of the plugins.\n\nOnly after that does it load modules, actions, controllers and the other files, so the configuration is ready when your code runs. `F.load()` with a list of types (for example `LOAD('config,modules')`) loads only those parts; `env` and `config` are types too.\n\nIn debug mode the watcher restarts the application when the `config` file of the application or of a plugin changes.\n\n## Plugin configuration\n\nA plugin can bring its own `config` file: `plugins/<name>/config`, next to the `index.js` of the plugin. It has the same format and is loaded with `LOADCONFIG()` after the `config` of the application, so its keys are added to the same global `CONF` and overwrite keys with the same name. Prefix the keys with the name of the plugin to avoid conflicts.\n\n```\n# plugins/invoices/config\ninvoices_currency   : EUR\ninvoices_due (number) : 14\n```\n\n```js\n// plugins/invoices/index.js\nexports.install = function() {\n\tvar days = CONF.invoices_due;\n};\n```\n\nSee [Plugins and components](../plugins-and-components/) for the rest of the plugin structure.\n\n## Common keys\n\n| Key | Default | Meaning |\n| --- | --- | --- |\n| `name` | `Total.js` | The name of the application: page titles, e-mails, the start screen |\n| `version` | `1.0.0` | The version; also read from the `version` file |\n| `author` | `''` | Printed on the start screen |\n| `secret` | | The key for `ENCRYPT()`/`DECRYPT()` and signed values; set your own |\n| `secret_csrf` | `''` | Enables CSRF tokens; see [Authorization](../authorization/) |\n| `secret_encryption` | `''` | The key for encrypted WebSocket messages |\n| `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc`, `mail_bcc` | | Defaults for `MAIL()`; see [Mail](../mail/) |\n| `smtp` (or `mail`) | | The SMTP options as JSON; `mail_smtp` and `mail_smtp_options` set the server and the options separately |\n| `$root` | `''` | A prefix for all routes and static files, e.g. `/app/` |\n| `$api` | `/api/` | The URL that replaces `?` in API routes |\n| `$port`, `$ip` | `auto`, `0.0.0.0` | Where the HTTP server listens |\n| `$timezone` | `utc` | The time zone of the process (`TZ`) |\n| `$httpmaxsize` | `256` | The maximum size of a request body in kB |\n| `$httptimeout` | `5` | The request timeout in seconds |\n| `$cors` | `''` | Allowed origins for cross-origin requests |\n\n`$port` stays `auto` when you leave it out: the server then uses the `port` option of `F.http()`, the `PORT` variable, a number in the command line arguments, or 8000, in this order.\n\n## Changing the configuration at runtime\n\n`LOADCONFIG(value)` applies new values while the application runs. It accepts the text of a config file, an object, or an array of `{ id, type, value }` items. In an object or an array, the values `false`, `0` and `''` are stored as `undefined`; use the text form for them. Keys with a special meaning (`$root`, `$api`, `$timezone`, `$httpfiles`, `$cryptoiv`, `smtp`…) are processed the same way as in the file, and the framework then emits the `$reconfigure` event.\n\n```js\n// from a database, for example\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n\nLOADCONFIG('$httptimeout (number) : 15\\n$minifyhtml : false');\n\nON('$reconfigure', function() {\n\tconsole.log('New name:', CONF.name);\n});\n```\n\nYou can also assign `CONF.key = value` directly. That changes only the value: the derived settings (the CORS list, the time zone, TMS, the logger) are refreshed only by `LOADCONFIG()`.\n\n## `DEBUG`\n\nThe global `DEBUG` is `true` in debug mode and `false` in release mode. The framework uses it for caching, minification and the source map, and you can use it too:\n\n```js\nif (DEBUG)\n\tconsole.log('Running in debug mode');\n```\n\n`DEBUG` starts as `process.env.NODE_ENV !== 'production'`: it is `false` when `NODE_ENV` is `production` and `true` otherwise. `Total.run()` sets it before the application loads: `false` with `options.release = true` (the official start script sets it with `--release`) or with `options.watcher = false`, and `true` otherwise. So the variable decides the mode only when the application calls `F.http()` or `F.load()` without `Total.run()`. It is not a config key.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JacV4g4ZP60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/configuration/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Konfiguration","summary":"Die Datei config und ihre Typen, .env, CONF, LOADCONFIG() und DEBUG.","markdown":"---\ntitle: Konfiguration\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/configuration/\nupdated: 2026-11-16T15:32:37.496Z\n---\n\n# Konfiguration\n\n> Die Datei config und ihre Typen, .env, CONF, LOADCONFIG() und DEBUG.\n\nDie Konfiguration einer Total.js 5 Anwendung liegt in einer einfachen Textdatei namens `config` im Stammverzeichnis der Anwendung. Das Framework liest sie beim Start und kopiert jeden Schlüssel in das globale Objekt `CONF` (dasselbe Objekt wie `F.config`). Dein Code und das Framework lesen die Werte von dort.\n\n```\nname             : My application\n$api             : /api/\n$httpmaxsize     : 1024\n$cors            : https://app.example.com\nmail_from        : info@example.com\nsmtp (json)      : {\"server\":\"smtp.example.com\",\"port\":465,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n```js\n// anywhere in the code\nconsole.log(CONF.name);       // My application\nconsole.log(F.config.$api);   // /api/\n```\n\nSchlüssel, die mit `$` beginnen, sind Einstellungen des Frameworks. Andere Schlüssel (`name`, `mail_from`, deine eigenen Schlüssel) stehen frei zur Verfügung. Die meisten `$`-Schlüssel haben einen Standardwert, daher braucht die Datei nur die Schlüssel, die du änderst. Die Referenz [Konfiguration](../../reference/configuration/) listet sie alle auf.\n\n## Das Format der Datei\n\nJede Zeile ist `key : value`. Das Framework teilt die Zeile am ersten Doppelpunkt und überspringt ein Zeichen danach, setze also immer ein Leerzeichen nach dem Doppelpunkt. Leerzeichen vor dem Doppelpunkt und um den Wert werden entfernt, sodass du die Werte in Spalten ausrichten kannst. Werte dürfen weitere Doppelpunkte enthalten (URLs, Uhrzeiten).\n\n- Leere Zeilen und Zeilen, die mit `#` oder `//` beginnen, werden ignoriert.\n- `true` und `false` werden zu Booleans, und ein Wert aus einer Ziffer (`0` bis `9`) wird zu einer Zahl. Jeder andere Wert ohne Typ ist ein String.\n- Ein Wert, der mit `base64 ` oder `hex ` beginnt, wird zuerst in einen String decodiert.\n\nEin Typ in Klammern nach dem Schlüssel wandelt den Wert um:\n\n| Typ | Ergebnis |\n| --- | --- |\n| `(number)`, `(float)`, `(double)`, `(currency)` | Eine Zahl |\n| `(boolean)`, `(bool)` | `true`, wenn der Wert `true`, `on`, `1` oder `enabled` enthält |\n| `(array)` | Ein Array von Strings, an Kommas geteilt und getrimmt |\n| `(json)`, `(object)` | Das geparste JSON |\n| `(eval)` | Das Ergebnis eines JavaScript-Ausdrucks |\n| `(date)`, `(time)`, `(datetime)` | Ein `Date` |\n| `(env)`, `(environment)` | Der Wert der Umgebungsvariable mit diesem Namen |\n| `(config)` | Der Wert eines anderen Schlüssels, der bereits in `CONF` steht |\n| `(random)` | Bei jedem Start ein neuer zufälliger Bezeichner der angegebenen Länge (Standard 10) |\n| `(generate)`, `(hash)` | Ein zufälliger String der angegebenen Länge (Standard 10), einmal erstellt und beibehalten |\n\n```\n$httptimeout (number)  : 10\nallowed (array)        : admin, editor\nlimits (json)          : {\"files\":10,\"size\":5}\nstarted (date)         : 2025-01-01\ndb (env)               : DATABASE_URL\nappname (config)       : name\ntoken (generate)       : 32\nlogo                   : base64 aGVsbG8=\n```\n\nWerte von `(generate)` und `(hash)` werden beim ersten Mal in `databases/config.json` gespeichert und bei jedem späteren Start von dort gelesen, sodass sich ein generiertes Secret nach einem Neustart nicht ändert. Lösche den Schlüssel aus dieser Datei, um ein neues zu erstellen.\n\n`(config)` liest `CONF`, bevor die Datei angewendet wird: Es sieht die Standardwerte und die zuvor geladenen Werte, nicht die Schlüssel derselben Datei.\n\nVerwende `(number)` für jeden numerischen Wert deiner eigenen Schlüssel.\n\n## Umgebungsvariablen und `.env`\n\nVor der Datei `config` liest das Framework die Datei `.env` im Stammverzeichnis, falls sie existiert. Jede Zeile ist `KEY=value`, ohne Leerzeichen um `=`. Zeilen, die mit `#` oder `//` beginnen, werden ignoriert, Anführungszeichen um den Wert werden entfernt und `\\n` wird zu einem Zeilenumbruch. Ein Schlüssel wird nur dann in `process.env` kopiert, wenn die Variable noch nicht gesetzt ist, sodass die echte Umgebung immer gewinnt.\n\n```\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/app\nAPI_KEY=\"abc123\"\n```\n\nDie Datei `config` liest sie mit dem Typ `(env)`:\n\n```\ndatabase (env)   : DATABASE_URL\napikey (env)     : API_KEY\n```\n\nDas Framework selbst liest einige Variablen: `PORT` (siehe den Port unten), und es setzt `TZ` aus `$timezone` und `NODE_TLS_REJECT_UNAUTHORIZED` aus `$insecure`.\n\n## Ladereihenfolge\n\nBeim Start der Anwendung lädt das Framework in dieser Reihenfolge:\n\n1. Das `config`-Objekt aus den Optionen von `F.http()` (zum Beispiel `F.http({ config: { name: 'Shop' } })`).\n2. Die Datei `.env`.\n3. Die Datei `config`. Ihre Werte haben Vorrang vor den Optionen.\n4. Die Datei `version`: Ihre erste Zeile wird als Zahl zu `CONF.version`.\n5. Die Datei `config` jedes Plugins, vor den anderen Dateien der Plugins.\n\nErst danach lädt es Module, Aktionen, Controller und die anderen Dateien, sodass die Konfiguration bereit ist, wenn dein Code läuft. `F.load()` mit einer Liste von Typen (zum Beispiel `LOAD('config,modules')`) lädt nur diese Teile; `env` und `config` sind ebenfalls Typen.\n\nIm Debug-Modus startet der Watcher die Anwendung neu, wenn sich die Datei `config` der Anwendung oder eines Plugins ändert.\n\n## Konfiguration von Plugins\n\nEin Plugin kann eine eigene Datei `config` mitbringen: `plugins/<name>/config`, neben der `index.js` des Plugins. Sie hat dasselbe Format und wird nach der `config` der Anwendung mit `LOADCONFIG()` geladen, sodass ihre Schlüssel demselben globalen `CONF` hinzugefügt werden und Schlüssel mit demselben Namen überschreiben. Stelle den Schlüsseln den Namen des Plugins voran, um Konflikte zu vermeiden.\n\n```\n# plugins/invoices/config\ninvoices_currency   : EUR\ninvoices_due (number) : 14\n```\n\n```js\n// plugins/invoices/index.js\nexports.install = function() {\n\tvar days = CONF.invoices_due;\n};\n```\n\nSiehe [Plugins und Komponenten](../plugins-and-components/) für den restlichen Aufbau eines Plugins.\n\n## Häufige Schlüssel\n\n| Schlüssel | Standard | Bedeutung |\n| --- | --- | --- |\n| `name` | `Total.js` | Der Name der Anwendung: Seitentitel, E-Mails, der Startbildschirm |\n| `version` | `1.0.0` | Die Version; wird auch aus der Datei `version` gelesen |\n| `author` | `''` | Wird auf dem Startbildschirm ausgegeben |\n| `secret` | | Der Schlüssel für `ENCRYPT()`/`DECRYPT()` und signierte Werte; setze deinen eigenen |\n| `secret_csrf` | `''` | Aktiviert CSRF-Tokens; siehe [Autorisierung](../authorization/) |\n| `secret_encryption` | `''` | Der Schlüssel für verschlüsselte WebSocket-Nachrichten |\n| `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc`, `mail_bcc` | | Standardwerte für `MAIL()`; siehe [Mail](../mail/) |\n| `smtp` (oder `mail`) | | Die SMTP-Optionen als JSON; `mail_smtp` und `mail_smtp_options` setzen Server und Optionen getrennt |\n| `$root` | `''` | Ein Präfix für alle Routen und statischen Dateien, z. B. `/app/` |\n| `$api` | `/api/` | Die URL, die `?` in API-Routen ersetzt |\n| `$port`, `$ip` | `auto`, `0.0.0.0` | Wo der HTTP-Server lauscht |\n| `$timezone` | `utc` | Die Zeitzone des Prozesses (`TZ`) |\n| `$httpmaxsize` | `256` | Die maximale Größe eines Anfrage-Bodys in kB |\n| `$httptimeout` | `5` | Das Timeout der Anfrage in Sekunden |\n| `$cors` | `''` | Erlaubte Origins für Cross-Origin-Anfragen |\n\n`$port` bleibt `auto`, wenn du es weglässt: Der Server verwendet dann die Option `port` von `F.http()`, die Variable `PORT`, eine Zahl in den Kommandozeilenargumenten oder 8000, in dieser Reihenfolge.\n\n## Die Konfiguration zur Laufzeit ändern\n\n`LOADCONFIG(value)` wendet neue Werte an, während die Anwendung läuft. Es akzeptiert den Text einer Konfigurationsdatei, ein Objekt oder ein Array von `{ id, type, value }`-Einträgen. In einem Objekt oder einem Array werden die Werte `false`, `0` und `''` als `undefined` gespeichert; verwende für sie die Textform. Schlüssel mit besonderer Bedeutung (`$root`, `$api`, `$timezone`, `$httpfiles`, `$cryptoiv`, `smtp`…) werden genauso verarbeitet wie in der Datei, und das Framework löst danach das Event `$reconfigure` aus.\n\n```js\n// from a database, for example\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n\nLOADCONFIG('$httptimeout (number) : 15\\n$minifyhtml : false');\n\nON('$reconfigure', function() {\n\tconsole.log('New name:', CONF.name);\n});\n```\n\nDu kannst auch direkt `CONF.key = value` zuweisen. Das ändert nur den Wert: Die abgeleiteten Einstellungen (die CORS-Liste, die Zeitzone, TMS, der Logger) werden nur von `LOADCONFIG()` aktualisiert.\n\n## `DEBUG`\n\nDas globale `DEBUG` ist im Debug-Modus `true` und im Release-Modus `false`. Das Framework verwendet es für Caching, Minifizierung und die Source Map, und du kannst es ebenfalls verwenden:\n\n```js\nif (DEBUG)\n\tconsole.log('Running in debug mode');\n```\n\n`DEBUG` beginnt als `process.env.NODE_ENV !== 'production'`: Es ist `false`, wenn `NODE_ENV` gleich `production` ist, und sonst `true`. `Total.run()` setzt es, bevor die Anwendung lädt: auf `false` mit `options.release = true` (das offizielle Startskript setzt es mit `--release`) oder mit `options.watcher = false`, sonst auf `true`. Die Variable entscheidet also nur dann über den Modus, wenn die Anwendung `F.http()` oder `F.load()` ohne `Total.run()` aufruft. Es ist kein Konfigurationsschlüssel.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JacV4g4ZP60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/configuration/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Configuración","summary":"El archivo config y sus tipos, .env, CONF, LOADCONFIG() y DEBUG.","markdown":"---\ntitle: \"Configuración\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/configuration/\nupdated: 2026-11-16T15:32:37.496Z\n---\n\n# Configuración\n\n> El archivo config y sus tipos, .env, CONF, LOADCONFIG() y DEBUG.\n\nLa configuración de una aplicación Total.js 5 está en un archivo de texto plano llamado `config` en el directorio raíz de la aplicación. El framework lo lee al iniciarse y copia cada clave en el objeto global `CONF` (el mismo objeto que `F.config`). Tu código y el framework leen los valores de ahí.\n\n```\nname             : My application\n$api             : /api/\n$httpmaxsize     : 1024\n$cors            : https://app.example.com\nmail_from        : info@example.com\nsmtp (json)      : {\"server\":\"smtp.example.com\",\"port\":465,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n```js\n// anywhere in the code\nconsole.log(CONF.name);       // My application\nconsole.log(F.config.$api);   // /api/\n```\n\nLas claves que empiezan por `$` son ajustes del framework. Las demás claves (`name`, `mail_from`, tus propias claves) son de uso libre. La mayoría de las claves `$` tienen un valor por defecto, así que el archivo solo necesita las claves que cambias. La referencia de [Configuración](../../reference/configuration/) las lista todas.\n\n## El formato del archivo\n\nCada línea es `key : value`. El framework divide la línea en los primeros dos puntos y omite un carácter después de ellos, así que pon siempre un espacio después de los dos puntos. Se eliminan los espacios antes de los dos puntos y alrededor del valor, lo que te permite alinear los valores en columnas. Los valores pueden contener más dos puntos (URLs, horas).\n\n- Las líneas vacías y las que empiezan por `#` o `//` se ignoran.\n- `true` y `false` se convierten en booleanos, y un valor de una cifra (`0` a `9`) se convierte en número. Cualquier otro valor sin tipo es un string.\n- Un valor que empieza por `base64 ` o `hex ` se decodifica primero a string.\n\nUn tipo entre paréntesis después de la clave convierte el valor:\n\n| Tipo | Resultado |\n| --- | --- |\n| `(number)`, `(float)`, `(double)`, `(currency)` | Un número |\n| `(boolean)`, `(bool)` | `true` cuando el valor contiene `true`, `on`, `1` o `enabled` |\n| `(array)` | Un array de strings, divididos por comas y recortados |\n| `(json)`, `(object)` | El JSON parseado |\n| `(eval)` | El resultado de una expresión JavaScript |\n| `(date)`, `(time)`, `(datetime)` | Un `Date` |\n| `(env)`, `(environment)` | El valor de la variable de entorno con ese nombre |\n| `(config)` | El valor de otra clave que ya está en `CONF` |\n| `(random)` | Un nuevo identificador aleatorio de la longitud dada (por defecto 10) en cada inicio |\n| `(generate)`, `(hash)` | Un string aleatorio de la longitud dada (por defecto 10), creado una vez y conservado |\n\n```\n$httptimeout (number)  : 10\nallowed (array)        : admin, editor\nlimits (json)          : {\"files\":10,\"size\":5}\nstarted (date)         : 2025-01-01\ndb (env)               : DATABASE_URL\nappname (config)       : name\ntoken (generate)       : 32\nlogo                   : base64 aGVsbG8=\n```\n\nLos valores `(generate)` y `(hash)` se guardan en `databases/config.json` la primera vez y se leen de ahí en cada inicio posterior, así un secreto generado no cambia tras un reinicio. Borra la clave de ese archivo para crear uno nuevo.\n\n`(config)` lee `CONF` antes de aplicar el archivo: ve los valores por defecto y los valores cargados antes, no las claves del mismo archivo.\n\nUsa `(number)` para cada valor numérico de tus propias claves.\n\n## Variables de entorno y `.env`\n\nAntes del archivo `config`, el framework lee el archivo `.env` del directorio raíz, si existe. Cada línea es `KEY=value`, sin espacios alrededor de `=`. Las líneas que empiezan por `#` o `//` se ignoran, se eliminan las comillas alrededor del valor y `\\n` se convierte en un salto de línea. Una clave se copia en `process.env` solo cuando la variable no está ya establecida, así siempre gana el entorno real.\n\n```\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/app\nAPI_KEY=\"abc123\"\n```\n\nEl archivo `config` las lee con el tipo `(env)`:\n\n```\ndatabase (env)   : DATABASE_URL\napikey (env)     : API_KEY\n```\n\nEl propio framework lee algunas variables: `PORT` (consulta el puerto más abajo), y establece `TZ` a partir de `$timezone` y `NODE_TLS_REJECT_UNAUTHORIZED` a partir de `$insecure`.\n\n## Orden de carga\n\nAl iniciar la aplicación, el framework carga, en este orden:\n\n1. El objeto `config` de las opciones de `F.http()` (por ejemplo `F.http({ config: { name: 'Shop' } })`).\n2. El archivo `.env`.\n3. El archivo `config`. Sus valores prevalecen sobre las opciones.\n4. El archivo `version`: su primera línea, como número, pasa a ser `CONF.version`.\n5. El archivo `config` de cada plugin, antes que los demás archivos de los plugins.\n\nSolo después carga los módulos, las acciones, los controladores y los demás archivos, así la configuración está lista cuando se ejecuta tu código. `F.load()` con una lista de tipos (por ejemplo `LOAD('config,modules')`) carga solo esas partes; `env` y `config` también son tipos.\n\nEn modo debug el watcher reinicia la aplicación cuando cambia el archivo `config` de la aplicación o de un plugin.\n\n## Configuración de plugins\n\nUn plugin puede traer su propio archivo `config`: `plugins/<name>/config`, junto al `index.js` del plugin. Tiene el mismo formato y se carga con `LOADCONFIG()` después del `config` de la aplicación, así sus claves se añaden al mismo `CONF` global y sobrescriben las claves con el mismo nombre. Antepón a las claves el nombre del plugin para evitar conflictos.\n\n```\n# plugins/invoices/config\ninvoices_currency   : EUR\ninvoices_due (number) : 14\n```\n\n```js\n// plugins/invoices/index.js\nexports.install = function() {\n\tvar days = CONF.invoices_due;\n};\n```\n\nConsulta [Plugins y componentes](../plugins-and-components/) para el resto de la estructura del plugin.\n\n## Claves habituales\n\n| Clave | Por defecto | Significado |\n| --- | --- | --- |\n| `name` | `Total.js` | El nombre de la aplicación: títulos de página, e-mails, la pantalla de inicio |\n| `version` | `1.0.0` | La versión; también se lee del archivo `version` |\n| `author` | `''` | Se imprime en la pantalla de inicio |\n| `secret` | | La clave para `ENCRYPT()`/`DECRYPT()` y los valores firmados; establece la tuya |\n| `secret_csrf` | `''` | Activa los tokens CSRF; consulta [Autorización](../authorization/) |\n| `secret_encryption` | `''` | La clave para los mensajes WebSocket cifrados |\n| `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc`, `mail_bcc` | | Valores por defecto para `MAIL()`; consulta [Correo](../mail/) |\n| `smtp` (o `mail`) | | Las opciones SMTP como JSON; `mail_smtp` y `mail_smtp_options` establecen el servidor y las opciones por separado |\n| `$root` | `''` | Un prefijo para todas las rutas y archivos estáticos, p. ej. `/app/` |\n| `$api` | `/api/` | La URL que sustituye `?` en las rutas API |\n| `$port`, `$ip` | `auto`, `0.0.0.0` | Dónde escucha el servidor HTTP |\n| `$timezone` | `utc` | La zona horaria del proceso (`TZ`) |\n| `$httpmaxsize` | `256` | El tamaño máximo del cuerpo de una petición en kB |\n| `$httptimeout` | `5` | El tiempo de espera de la petición en segundos |\n| `$cors` | `''` | Orígenes permitidos para peticiones de origen cruzado |\n\n`$port` se queda en `auto` cuando lo omites: el servidor usa entonces la opción `port` de `F.http()`, la variable `PORT`, un número en los argumentos de la línea de comandos, o 8000, en este orden.\n\n## Cambiar la configuración en tiempo de ejecución\n\n`LOADCONFIG(value)` aplica nuevos valores mientras la aplicación se ejecuta. Acepta el texto de un archivo config, un objeto o un array de elementos `{ id, type, value }`. En un objeto o un array, los valores `false`, `0` y `''` se guardan como `undefined`; usa la forma de texto para ellos. Las claves con un significado especial (`$root`, `$api`, `$timezone`, `$httpfiles`, `$cryptoiv`, `smtp`…) se procesan igual que en el archivo, y luego el framework emite el evento `$reconfigure`.\n\n```js\n// from a database, for example\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n\nLOADCONFIG('$httptimeout (number) : 15\\n$minifyhtml : false');\n\nON('$reconfigure', function() {\n\tconsole.log('New name:', CONF.name);\n});\n```\n\nTambién puedes asignar `CONF.key = value` directamente. Eso cambia solo el valor: los ajustes derivados (la lista CORS, la zona horaria, TMS, el logger) solo los actualiza `LOADCONFIG()`.\n\n## `DEBUG`\n\nEl global `DEBUG` es `true` en modo debug y `false` en modo release. El framework lo usa para la caché, la minificación y el mapa de código fuente, y tú también puedes usarlo:\n\n```js\nif (DEBUG)\n\tconsole.log('Running in debug mode');\n```\n\n`DEBUG` empieza como `process.env.NODE_ENV !== 'production'`: es `false` cuando `NODE_ENV` es `production` y `true` en otro caso. `Total.run()` la establece antes de cargar la aplicación: `false` con `options.release = true` (el script de arranque oficial la activa con `--release`) o con `options.watcher = false`, y `true` en otro caso. Así que la variable decide el modo solo cuando la aplicación llama a `F.http()` o `F.load()` sin `Total.run()`. No es una clave de configuración.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JacV4g4ZP60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/configuration/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Configuration","summary":"Le fichier config et ses types, .env, CONF, LOADCONFIG() et DEBUG.","markdown":"---\ntitle: Configuration\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/configuration/\nupdated: 2026-11-16T15:32:37.496Z\n---\n\n# Configuration\n\n> Le fichier config et ses types, .env, CONF, LOADCONFIG() et DEBUG.\n\nLa configuration d'une application Total.js 5 se trouve dans un fichier texte simple nommé `config` dans le répertoire racine de l'application. Le framework le lit au démarrage et copie chaque clé dans l'objet global `CONF` (le même objet que `F.config`). Ton code et le framework y lisent les valeurs.\n\n```\nname             : My application\n$api             : /api/\n$httpmaxsize     : 1024\n$cors            : https://app.example.com\nmail_from        : info@example.com\nsmtp (json)      : {\"server\":\"smtp.example.com\",\"port\":465,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n```js\n// anywhere in the code\nconsole.log(CONF.name);       // My application\nconsole.log(F.config.$api);   // /api/\n```\n\nLes clés qui commencent par `$` sont des paramètres du framework. Les autres clés (`name`, `mail_from`, tes propres clés) sont libres d'utilisation. La plupart des clés `$` ont une valeur par défaut : le fichier ne doit donc contenir que les clés que tu modifies. La référence [Configuration](../../reference/configuration/) les liste toutes.\n\n## Le format du fichier\n\nChaque ligne s'écrit `key : value`. Le framework coupe la ligne au premier deux-points et ignore un caractère après celui-ci : mets donc toujours une espace après le deux-points. Les espaces avant le deux-points et autour de la valeur sont supprimées, ce qui te permet d'aligner les valeurs en colonnes. Les valeurs peuvent contenir d'autres deux-points (URL, heures).\n\n- Les lignes vides et les lignes qui commencent par `#` ou `//` sont ignorées.\n- `true` et `false` deviennent des booléens, et une valeur d'un seul chiffre (`0` à `9`) devient un nombre. Toute autre valeur sans type est une chaîne.\n- Une valeur qui commence par `base64 ` ou `hex ` est d'abord décodée en chaîne.\n\nUn type entre parenthèses après la clé convertit la valeur :\n\n| Type | Résultat |\n| --- | --- |\n| `(number)`, `(float)`, `(double)`, `(currency)` | Un nombre |\n| `(boolean)`, `(bool)` | `true` lorsque la valeur contient `true`, `on`, `1` ou `enabled` |\n| `(array)` | Un tableau de chaînes, découpé par les virgules et débarrassé des espaces |\n| `(json)`, `(object)` | Le JSON analysé |\n| `(eval)` | Le résultat d'une expression JavaScript |\n| `(date)`, `(time)`, `(datetime)` | Une `Date` |\n| `(env)`, `(environment)` | La valeur de la variable d'environnement portant ce nom |\n| `(config)` | La valeur d'une autre clé déjà présente dans `CONF` |\n| `(random)` | Un nouvel identifiant aléatoire de la longueur indiquée (par défaut 10) à chaque démarrage |\n| `(generate)`, `(hash)` | Une chaîne aléatoire de la longueur indiquée (par défaut 10), créée une fois et conservée |\n\n```\n$httptimeout (number)  : 10\nallowed (array)        : admin, editor\nlimits (json)          : {\"files\":10,\"size\":5}\nstarted (date)         : 2025-01-01\ndb (env)               : DATABASE_URL\nappname (config)       : name\ntoken (generate)       : 32\nlogo                   : base64 aGVsbG8=\n```\n\nLes valeurs `(generate)` et `(hash)` sont stockées dans `databases/config.json` la première fois, puis relues depuis ce fichier à chaque démarrage ultérieur : un secret généré ne change donc pas après un redémarrage. Supprime la clé de ce fichier pour en créer un nouveau.\n\n`(config)` lit `CONF` avant l'application du fichier : il voit les valeurs par défaut et les valeurs chargées auparavant, pas les clés du même fichier.\n\nUtilise `(number)` pour chaque valeur numérique de tes propres clés.\n\n## Variables d'environnement et `.env`\n\nAvant le fichier `config`, le framework lit le fichier `.env` du répertoire racine, s'il existe. Chaque ligne s'écrit `KEY=value`, sans espaces autour de `=`. Les lignes qui commencent par `#` ou `//` sont ignorées, les guillemets autour de la valeur sont supprimés et `\\n` devient un saut de ligne. Une clé n'est copiée dans `process.env` que si la variable n'est pas déjà définie : c'est donc toujours l'environnement réel qui l'emporte.\n\n```\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/app\nAPI_KEY=\"abc123\"\n```\n\nLe fichier `config` les lit avec le type `(env)` :\n\n```\ndatabase (env)   : DATABASE_URL\napikey (env)     : API_KEY\n```\n\nLe framework lui-même lit quelques variables : `PORT` (voir le port ci-dessous), et il définit `TZ` à partir de `$timezone` et `NODE_TLS_REJECT_UNAUTHORIZED` à partir de `$insecure`.\n\n## Ordre de chargement\n\nAu démarrage de l'application, le framework charge, dans cet ordre :\n\n1. L'objet `config` des options de `F.http()` (par exemple `F.http({ config: { name: 'Shop' } })`).\n2. Le fichier `.env`.\n3. Le fichier `config`. Ses valeurs l'emportent sur les options.\n4. Le fichier `version` : sa première ligne, sous forme de nombre, devient `CONF.version`.\n5. Le fichier `config` de chaque plugin, avant les autres fichiers des plugins.\n\nCe n'est qu'ensuite qu'il charge les modules, les actions, les contrôleurs et les autres fichiers : la configuration est donc prête lorsque ton code s'exécute. `F.load()` avec une liste de types (par exemple `LOAD('config,modules')`) ne charge que ces parties ; `env` et `config` sont aussi des types.\n\nEn mode debug, le watcher redémarre l'application lorsque le fichier `config` de l'application ou d'un plugin change.\n\n## Configuration des plugins\n\nUn plugin peut apporter son propre fichier `config` : `plugins/<name>/config`, à côté du `index.js` du plugin. Il a le même format et est chargé avec `LOADCONFIG()` après le `config` de l'application : ses clés sont donc ajoutées au même `CONF` global et écrasent les clés du même nom. Préfixe les clés avec le nom du plugin pour éviter les conflits.\n\n```\n# plugins/invoices/config\ninvoices_currency   : EUR\ninvoices_due (number) : 14\n```\n\n```js\n// plugins/invoices/index.js\nexports.install = function() {\n\tvar days = CONF.invoices_due;\n};\n```\n\nVoir [Plugins et composants](../plugins-and-components/) pour le reste de la structure d'un plugin.\n\n## Clés courantes\n\n| Clé | Défaut | Signification |\n| --- | --- | --- |\n| `name` | `Total.js` | Le nom de l'application : titres de pages, e-mails, écran de démarrage |\n| `version` | `1.0.0` | La version ; également lue depuis le fichier `version` |\n| `author` | `''` | Affiché sur l'écran de démarrage |\n| `secret` | | La clé pour `ENCRYPT()`/`DECRYPT()` et les valeurs signées ; définis la tienne |\n| `secret_csrf` | `''` | Active les tokens CSRF ; voir [Autorisation](../authorization/) |\n| `secret_encryption` | `''` | La clé pour les messages WebSocket chiffrés |\n| `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc`, `mail_bcc` | | Valeurs par défaut pour `MAIL()` ; voir [E-mail](../mail/) |\n| `smtp` (ou `mail`) | | Les options SMTP en JSON ; `mail_smtp` et `mail_smtp_options` définissent séparément le serveur et les options |\n| `$root` | `''` | Un préfixe pour toutes les routes et tous les fichiers statiques, par ex. `/app/` |\n| `$api` | `/api/` | L'URL qui remplace `?` dans les routes d'API |\n| `$port`, `$ip` | `auto`, `0.0.0.0` | Où le serveur HTTP écoute |\n| `$timezone` | `utc` | Le fuseau horaire du processus (`TZ`) |\n| `$httpmaxsize` | `256` | La taille maximale du corps d'une requête en ko |\n| `$httptimeout` | `5` | Le délai d'expiration d'une requête en secondes |\n| `$cors` | `''` | Origines autorisées pour les requêtes cross-origin |\n\n`$port` reste `auto` si tu l'omets : le serveur utilise alors l'option `port` de `F.http()`, la variable `PORT`, un nombre dans les arguments de la ligne de commande, ou 8000, dans cet ordre.\n\n## Modifier la configuration à l'exécution\n\n`LOADCONFIG(value)` applique de nouvelles valeurs pendant l'exécution de l'application. Elle accepte le texte d'un fichier config, un objet, ou un tableau d'éléments `{ id, type, value }`. Dans un objet ou un tableau, les valeurs `false`, `0` et `''` sont stockées comme `undefined` ; utilise la forme texte pour elles. Les clés ayant une signification particulière (`$root`, `$api`, `$timezone`, `$httpfiles`, `$cryptoiv`, `smtp`…) sont traitées de la même façon que dans le fichier, puis le framework émet l'événement `$reconfigure`.\n\n```js\n// from a database, for example\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n\nLOADCONFIG('$httptimeout (number) : 15\\n$minifyhtml : false');\n\nON('$reconfigure', function() {\n\tconsole.log('New name:', CONF.name);\n});\n```\n\nTu peux aussi assigner directement `CONF.key = value`. Cela ne change que la valeur : les paramètres dérivés (la liste CORS, le fuseau horaire, TMS, le logger) ne sont actualisés que par `LOADCONFIG()`.\n\n## `DEBUG`\n\nLa variable globale `DEBUG` vaut `true` en mode debug et `false` en mode release. Le framework l'utilise pour le cache, la minification et la source map, et tu peux l'utiliser aussi :\n\n```js\nif (DEBUG)\n\tconsole.log('Running in debug mode');\n```\n\n`DEBUG` vaut au départ `process.env.NODE_ENV !== 'production'` : elle vaut `false` lorsque `NODE_ENV` est `production` et `true` sinon. `Total.run()` la définit avant le chargement de l'application : `false` avec `options.release = true` (le script de démarrage officiel l'active avec `--release`) ou avec `options.watcher = false`, et `true` sinon. La variable ne décide donc du mode que lorsque l'application appelle `F.http()` ou `F.load()` sans `Total.run()`. Ce n'est pas une clé de configuration.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JacV4g4ZP60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/configuration/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Configurazione","summary":"Il file config e i suoi tipi, .env, CONF, LOADCONFIG() e DEBUG.","markdown":"---\ntitle: Configurazione\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/configuration/\nupdated: 2026-11-16T15:32:37.496Z\n---\n\n# Configurazione\n\n> Il file config e i suoi tipi, .env, CONF, LOADCONFIG() e DEBUG.\n\nLa configurazione di un'applicazione Total.js 5 si trova in un semplice file di testo chiamato `config` nella directory radice dell'applicazione. Il framework lo legge all'avvio e copia ogni chiave nell'oggetto globale `CONF` (lo stesso oggetto di `F.config`). Il tuo codice e il framework leggono i valori da lì.\n\n```\nname             : My application\n$api             : /api/\n$httpmaxsize     : 1024\n$cors            : https://app.example.com\nmail_from        : info@example.com\nsmtp (json)      : {\"server\":\"smtp.example.com\",\"port\":465,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n```js\n// anywhere in the code\nconsole.log(CONF.name);       // My application\nconsole.log(F.config.$api);   // /api/\n```\n\nLe chiavi che iniziano con `$` sono impostazioni del framework. Le altre chiavi (`name`, `mail_from`, le tue chiavi) sono liberamente utilizzabili. La maggior parte delle chiavi `$` ha un valore predefinito, quindi nel file servono solo le chiavi che cambi. Il riferimento di [Configurazione](../../reference/configuration/) le elenca tutte.\n\n## Il formato del file\n\nOgni riga è `key : value`. Il framework divide la riga al primo due punti e salta un carattere dopo di esso, quindi metti sempre uno spazio dopo i due punti. Gli spazi prima dei due punti e attorno al valore vengono rimossi, il che ti permette di allineare i valori in colonne. I valori possono contenere altri due punti (URL, orari).\n\n- Le righe vuote e le righe che iniziano con `#` o `//` vengono ignorate.\n- `true` e `false` diventano booleani, e un valore di una sola cifra (da `0` a `9`) diventa un numero. Ogni altro valore senza tipo è una stringa.\n- Un valore che inizia con `base64 ` o `hex ` viene prima decodificato in una stringa.\n\nUn tipo tra parentesi dopo la chiave converte il valore:\n\n| Tipo | Risultato |\n| --- | --- |\n| `(number)`, `(float)`, `(double)`, `(currency)` | Un numero |\n| `(boolean)`, `(bool)` | `true` quando il valore contiene `true`, `on`, `1` o `enabled` |\n| `(array)` | Un array di stringhe, diviso per virgole e ripulito dagli spazi |\n| `(json)`, `(object)` | Il JSON interpretato |\n| `(eval)` | Il risultato di un'espressione JavaScript |\n| `(date)`, `(time)`, `(datetime)` | Una `Date` |\n| `(env)`, `(environment)` | Il valore della variabile d'ambiente con quel nome |\n| `(config)` | Il valore di un'altra chiave già presente in `CONF` |\n| `(random)` | Un nuovo identificatore casuale della lunghezza indicata (predefinita 10) a ogni avvio |\n| `(generate)`, `(hash)` | Una stringa casuale della lunghezza indicata (predefinita 10), creata una volta e conservata |\n\n```\n$httptimeout (number)  : 10\nallowed (array)        : admin, editor\nlimits (json)          : {\"files\":10,\"size\":5}\nstarted (date)         : 2025-01-01\ndb (env)               : DATABASE_URL\nappname (config)       : name\ntoken (generate)       : 32\nlogo                   : base64 aGVsbG8=\n```\n\nI valori `(generate)` e `(hash)` vengono salvati in `databases/config.json` la prima volta e letti da lì a ogni avvio successivo, quindi un secret generato non cambia dopo un riavvio. Elimina la chiave da quel file per crearne uno nuovo.\n\n`(config)` legge `CONF` prima che il file venga applicato: vede i valori predefiniti e quelli caricati in precedenza, non le chiavi dello stesso file.\n\nUsa `(number)` per ogni valore numerico delle tue chiavi.\n\n## Variabili d'ambiente e `.env`\n\nPrima del file `config`, il framework legge il file `.env` nella directory radice, se esiste. Ogni riga è `KEY=value`, senza spazi attorno a `=`. Le righe che iniziano con `#` o `//` vengono ignorate, le virgolette attorno al valore vengono rimosse e `\\n` diventa un a capo. Una chiave viene copiata in `process.env` solo quando la variabile non è già impostata, quindi l'ambiente reale ha sempre la precedenza.\n\n```\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/app\nAPI_KEY=\"abc123\"\n```\n\nIl file `config` le legge con il tipo `(env)`:\n\n```\ndatabase (env)   : DATABASE_URL\napikey (env)     : API_KEY\n```\n\nIl framework stesso legge alcune variabili: `PORT` (vedi la porta più avanti), e imposta `TZ` da `$timezone` e `NODE_TLS_REJECT_UNAUTHORIZED` da `$insecure`.\n\n## Ordine di caricamento\n\nAll'avvio dell'applicazione, il framework carica, in quest'ordine:\n\n1. L'oggetto `config` dalle opzioni di `F.http()` (per esempio `F.http({ config: { name: 'Shop' } })`).\n2. Il file `.env`.\n3. Il file `config`. I suoi valori hanno la precedenza sulle opzioni.\n4. Il file `version`: la sua prima riga, come numero, diventa `CONF.version`.\n5. Il file `config` di ogni plugin, prima degli altri file dei plugin.\n\nSolo dopo carica moduli, azioni, controller e gli altri file, quindi la configurazione è pronta quando il tuo codice viene eseguito. `F.load()` con un elenco di tipi (per esempio `LOAD('config,modules')`) carica solo quelle parti; anche `env` e `config` sono tipi.\n\nIn modalità debug il watcher riavvia l'applicazione quando cambia il file `config` dell'applicazione o di un plugin.\n\n## Configurazione dei plugin\n\nUn plugin può avere il proprio file `config`: `plugins/<name>/config`, accanto all'`index.js` del plugin. Ha lo stesso formato e viene caricato con `LOADCONFIG()` dopo il `config` dell'applicazione, quindi le sue chiavi vengono aggiunte allo stesso `CONF` globale e sovrascrivono le chiavi con lo stesso nome. Usa il nome del plugin come prefisso delle chiavi per evitare conflitti.\n\n```\n# plugins/invoices/config\ninvoices_currency   : EUR\ninvoices_due (number) : 14\n```\n\n```js\n// plugins/invoices/index.js\nexports.install = function() {\n\tvar days = CONF.invoices_due;\n};\n```\n\nVedi [Plugin e componenti](../plugins-and-components/) per il resto della struttura dei plugin.\n\n## Chiavi comuni\n\n| Chiave | Predefinito | Significato |\n| --- | --- | --- |\n| `name` | `Total.js` | Il nome dell'applicazione: titoli delle pagine, e-mail, schermata di avvio |\n| `version` | `1.0.0` | La versione; letta anche dal file `version` |\n| `author` | `''` | Stampato nella schermata di avvio |\n| `secret` | | La chiave per `ENCRYPT()`/`DECRYPT()` e i valori firmati; imposta la tua |\n| `secret_csrf` | `''` | Attiva i token CSRF; vedi [Autorizzazione](../authorization/) |\n| `secret_encryption` | `''` | La chiave per i messaggi WebSocket cifrati |\n| `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc`, `mail_bcc` | | Valori predefiniti per `MAIL()`; vedi [Posta](../mail/) |\n| `smtp` (o `mail`) | | Le opzioni SMTP in JSON; `mail_smtp` e `mail_smtp_options` impostano il server e le opzioni separatamente |\n| `$root` | `''` | Un prefisso per tutte le route e i file statici, ad es. `/app/` |\n| `$api` | `/api/` | L'URL che sostituisce `?` nelle route API |\n| `$port`, `$ip` | `auto`, `0.0.0.0` | Dove resta in ascolto il server HTTP |\n| `$timezone` | `utc` | Il fuso orario del processo (`TZ`) |\n| `$httpmaxsize` | `256` | La dimensione massima del body di una richiesta in kB |\n| `$httptimeout` | `5` | Il timeout della richiesta in secondi |\n| `$cors` | `''` | Origini consentite per le richieste cross-origin |\n\n`$port` resta `auto` quando lo ometti: il server usa allora l'opzione `port` di `F.http()`, la variabile `PORT`, un numero negli argomenti della riga di comando, oppure 8000, in quest'ordine.\n\n## Modificare la configurazione a runtime\n\n`LOADCONFIG(value)` applica nuovi valori mentre l'applicazione gira. Accetta il testo di un file config, un oggetto o un array di elementi `{ id, type, value }`. In un oggetto o in un array, i valori `false`, `0` e `''` vengono salvati come `undefined`; per questi usa la forma testuale. Le chiavi con un significato speciale (`$root`, `$api`, `$timezone`, `$httpfiles`, `$cryptoiv`, `smtp`…) vengono elaborate come nel file, e il framework emette poi l'evento `$reconfigure`.\n\n```js\n// from a database, for example\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n\nLOADCONFIG('$httptimeout (number) : 15\\n$minifyhtml : false');\n\nON('$reconfigure', function() {\n\tconsole.log('New name:', CONF.name);\n});\n```\n\nPuoi anche assegnare direttamente `CONF.key = value`. Questo cambia solo il valore: le impostazioni derivate (l'elenco CORS, il fuso orario, TMS, il logger) vengono aggiornate solo da `LOADCONFIG()`.\n\n## `DEBUG`\n\nLa variabile globale `DEBUG` è `true` in modalità debug e `false` in modalità release. Il framework la usa per la cache, la minificazione e la source map, e puoi usarla anche tu:\n\n```js\nif (DEBUG)\n\tconsole.log('Running in debug mode');\n```\n\n`DEBUG` parte come `process.env.NODE_ENV !== 'production'`: è `false` quando `NODE_ENV` è `production` e `true` altrimenti. `Total.run()` la imposta prima che l'applicazione si carichi: `false` con `options.release = true` (lo script di avvio ufficiale la attiva con `--release`) o con `options.watcher = false`, e `true` altrimenti. Quindi la variabile decide la modalità solo quando l'applicazione chiama `F.http()` o `F.load()` senza `Total.run()`. Non è una chiave di configurazione.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JacV4g4ZP60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/configuration/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Konfigurácia","summary":"Súbor config a jeho typy, .env, CONF, LOADCONFIG() a DEBUG.","markdown":"---\ntitle: \"Konfigurácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/configuration/\nupdated: 2026-11-16T15:32:37.496Z\n---\n\n# Konfigurácia\n\n> Súbor config a jeho typy, .env, CONF, LOADCONFIG() a DEBUG.\n\nKonfigurácia aplikácie v Total.js 5 je v obyčajnom textovom súbore s názvom `config` v koreňovom adresári aplikácie. Framework ho prečíta pri štarte a každý kľúč skopíruje do globálneho objektu `CONF` (rovnaký objekt ako `F.config`). Tvoj kód aj framework čítajú hodnoty odtiaľ.\n\n```\nname             : My application\n$api             : /api/\n$httpmaxsize     : 1024\n$cors            : https://app.example.com\nmail_from        : info@example.com\nsmtp (json)      : {\"server\":\"smtp.example.com\",\"port\":465,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n```js\n// anywhere in the code\nconsole.log(CONF.name);       // My application\nconsole.log(F.config.$api);   // /api/\n```\n\nKľúče, ktoré začínajú `$`, sú nastavenia frameworku. Ostatné kľúče (`name`, `mail_from`, tvoje vlastné kľúče) môžeš používať voľne. Väčšina kľúčov `$` má predvolenú hodnotu, takže súbor potrebuje iba kľúče, ktoré meníš. Referencia [Konfigurácia](../../reference/configuration/) ich uvádza všetky.\n\n## Formát súboru\n\nKaždý riadok je `key : value`. Framework rozdelí riadok na prvej dvojbodke a preskočí jeden znak za ňou, preto za dvojbodku vždy daj medzeru. Medzery pred dvojbodkou a okolo hodnoty sa odstránia, takže hodnoty môžeš zarovnať do stĺpcov. Hodnoty môžu obsahovať ďalšie dvojbodky (URL, časy).\n\n- Prázdne riadky a riadky, ktoré začínajú `#` alebo `//`, sa ignorujú.\n- `true` a `false` sa stanú booleanmi a hodnota s jednou číslicou (`0` až `9`) sa stane číslom. Každá iná hodnota bez typu je reťazec.\n- Hodnota, ktorá začína `base64 ` alebo `hex `, sa najprv dekóduje na reťazec.\n\nTyp v zátvorkách za kľúčom konvertuje hodnotu:\n\n| Typ | Výsledok |\n| --- | --- |\n| `(number)`, `(float)`, `(double)`, `(currency)` | Číslo |\n| `(boolean)`, `(bool)` | `true`, keď hodnota obsahuje `true`, `on`, `1` alebo `enabled` |\n| `(array)` | Pole reťazcov rozdelené čiarkami a orezané |\n| `(json)`, `(object)` | Spracovaný JSON |\n| `(eval)` | Výsledok JavaScriptového výrazu |\n| `(date)`, `(time)`, `(datetime)` | `Date` |\n| `(env)`, `(environment)` | Hodnota premennej prostredia s týmto názvom |\n| `(config)` | Hodnota iného kľúča, ktorý už je v `CONF` |\n| `(random)` | Nový náhodný identifikátor zadanej dĺžky (predvolene 10) pri každom štarte |\n| `(generate)`, `(hash)` | Náhodný reťazec zadanej dĺžky (predvolene 10), vytvorený raz a uchovaný |\n\n```\n$httptimeout (number)  : 10\nallowed (array)        : admin, editor\nlimits (json)          : {\"files\":10,\"size\":5}\nstarted (date)         : 2025-01-01\ndb (env)               : DATABASE_URL\nappname (config)       : name\ntoken (generate)       : 32\nlogo                   : base64 aGVsbG8=\n```\n\nHodnoty `(generate)` a `(hash)` sa pri prvom štarte uložia do `databases/config.json` a pri každom ďalšom štarte sa čítajú odtiaľ, takže vygenerovaný secret sa po reštarte nezmení. Ak chceš vytvoriť nový, zmaž kľúč z tohto súboru.\n\n`(config)` číta `CONF` pred použitím súboru: vidí predvolené hodnoty a hodnoty načítané skôr, nie kľúče toho istého súboru.\n\nPre každú číselnú hodnotu vlastných kľúčov používaj `(number)`.\n\n## Premenné prostredia a `.env`\n\nPred súborom `config` framework prečíta súbor `.env` v koreňovom adresári, ak existuje. Každý riadok je `KEY=value` bez medzier okolo `=`. Riadky, ktoré začínajú `#` alebo `//`, sa ignorujú, úvodzovky okolo hodnoty sa odstránia a `\\n` sa zmení na nový riadok. Kľúč sa skopíruje do `process.env` iba vtedy, keď premenná ešte nie je nastavená, takže skutočné prostredie vždy vyhráva.\n\n```\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/app\nAPI_KEY=\"abc123\"\n```\n\nSúbor `config` ich číta cez typ `(env)`:\n\n```\ndatabase (env)   : DATABASE_URL\napikey (env)     : API_KEY\n```\n\nSamotný framework číta niekoľko premenných: `PORT` (pozri port nižšie) a nastavuje `TZ` z `$timezone` a `NODE_TLS_REJECT_UNAUTHORIZED` z `$insecure`.\n\n## Poradie načítania\n\nPri štarte aplikácie framework načíta v tomto poradí:\n\n1. Objekt `config` z volieb `F.http()` (napríklad `F.http({ config: { name: 'Shop' } })`).\n2. Súbor `.env`.\n3. Súbor `config`. Jeho hodnoty majú prednosť pred voľbami.\n4. Súbor `version`: jeho prvý riadok sa ako číslo stane `CONF.version`.\n5. Súbor `config` každého pluginu, pred ostatnými súbormi pluginov.\n\nAž potom načíta moduly, akcie, kontroléry a ostatné súbory, takže konfigurácia je pripravená, keď beží tvoj kód. `F.load()` so zoznamom typov (napríklad `LOAD('config,modules')`) načíta iba tieto časti; `env` a `config` sú tiež typy.\n\nV režime debug watcher reštartuje aplikáciu, keď sa zmení súbor `config` aplikácie alebo pluginu.\n\n## Konfigurácia pluginu\n\nPlugin si môže priniesť vlastný súbor `config`: `plugins/<name>/config`, vedľa `index.js` pluginu. Má rovnaký formát a načíta sa cez `LOADCONFIG()` po `config` aplikácie, takže jeho kľúče sa pridajú do toho istého globálneho `CONF` a prepíšu kľúče s rovnakým názvom. Aby si sa vyhol konfliktom, daj kľúčom predponu s názvom pluginu.\n\n```\n# plugins/invoices/config\ninvoices_currency   : EUR\ninvoices_due (number) : 14\n```\n\n```js\n// plugins/invoices/index.js\nexports.install = function() {\n\tvar days = CONF.invoices_due;\n};\n```\n\nZvyšok štruktúry pluginu nájdeš v [Pluginy a komponenty](../plugins-and-components/).\n\n## Bežné kľúče\n\n| Kľúč | Predvolene | Význam |\n| --- | --- | --- |\n| `name` | `Total.js` | Názov aplikácie: titulky stránok, e-maily, štartovacia obrazovka |\n| `version` | `1.0.0` | Verzia; číta sa aj zo súboru `version` |\n| `author` | `''` | Vypíše sa na štartovacej obrazovke |\n| `secret` | | Kľúč pre `ENCRYPT()`/`DECRYPT()` a podpísané hodnoty; nastav si vlastný |\n| `secret_csrf` | `''` | Zapne CSRF tokeny; pozri [Autorizácia](../authorization/) |\n| `secret_encryption` | `''` | Kľúč pre šifrované WebSocket správy |\n| `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc`, `mail_bcc` | | Predvolené hodnoty pre `MAIL()`; pozri [Pošta](../mail/) |\n| `smtp` (alebo `mail`) | | SMTP voľby ako JSON; `mail_smtp` a `mail_smtp_options` nastavujú server a voľby zvlášť |\n| `$root` | `''` | Predpona pre všetky trasy a statické súbory, napr. `/app/` |\n| `$api` | `/api/` | URL, ktorá nahrádza `?` v API trasách |\n| `$port`, `$ip` | `auto`, `0.0.0.0` | Kde HTTP server počúva |\n| `$timezone` | `utc` | Časová zóna procesu (`TZ`) |\n| `$httpmaxsize` | `256` | Maximálna veľkosť tela požiadavky v kB |\n| `$httptimeout` | `5` | Časový limit požiadavky v sekundách |\n| `$cors` | `''` | Povolené originy pre cross-origin požiadavky |\n\n`$port` zostane `auto`, keď ho vynecháš: server potom použije voľbu `port` z `F.http()`, premennú `PORT`, číslo v argumentoch príkazového riadka alebo 8000, v tomto poradí.\n\n## Zmena konfigurácie za behu\n\n`LOADCONFIG(value)` použije nové hodnoty počas behu aplikácie. Prijíma text konfiguračného súboru, objekt alebo pole položiek `{ id, type, value }`. V objekte alebo poli sa hodnoty `false`, `0` a `''` uložia ako `undefined`; pre ne použi textovú formu. Kľúče so špeciálnym významom (`$root`, `$api`, `$timezone`, `$httpfiles`, `$cryptoiv`, `smtp`…) sa spracujú rovnako ako v súbore a framework potom vyvolá udalosť `$reconfigure`.\n\n```js\n// from a database, for example\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n\nLOADCONFIG('$httptimeout (number) : 15\\n$minifyhtml : false');\n\nON('$reconfigure', function() {\n\tconsole.log('New name:', CONF.name);\n});\n```\n\nMôžeš tiež priamo priradiť `CONF.key = value`. Tým sa zmení iba hodnota: odvodené nastavenia (zoznam CORS, časová zóna, TMS, logger) obnoví iba `LOADCONFIG()`.\n\n## `DEBUG`\n\nGlobálne `DEBUG` je `true` v režime debug a `false` v režime release. Framework ho používa pre cache, minifikáciu a source mapu a môžeš ho používať aj ty:\n\n```js\nif (DEBUG)\n\tconsole.log('Running in debug mode');\n```\n\n`DEBUG` začína ako `process.env.NODE_ENV !== 'production'`: je `false`, keď je `NODE_ENV` rovné `production`, a inak `true`. `Total.run()` ho nastaví pred načítaním aplikácie: na `false` s `options.release = true` (oficiálny štartovací skript ho zapne cez `--release`) alebo s `options.watcher = false`, inak na `true`. Premenná teda rozhoduje o režime len vtedy, keď aplikácia volá `F.http()` alebo `F.load()` bez `Total.run()`. Nie je to konfiguračný kľúč.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JacVDy45I60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/authorization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Authorization","summary":"Decide who the user of a request is with AUTH(), protect routes and actions, and use built-in sessions.","markdown":"---\ntitle: Authorization\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/authorization/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Authorization\n\n> Decide who the user of a request is with AUTH(), protect routes and actions, and use built-in sessions.\n\nTotal.js does not decide who a user is. You register one **authorization delegate** with `AUTH()`, the framework calls it for every request that matches a route, and the object you accept becomes the user of the request: `$.user` in a route action and in an action. Routes then use the `+` and `-` flags to say who may call them.\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token === 'secret-token')\n\t\t$.success({ id: '1', name: 'Peter', sa: true });\n\telse\n\t\t$.invalid();\n});\n```\n\n## The delegate\n\nThe delegate gets `$`, an options object built for the current request. It has `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.cookie(name)` and `$.controller`. For WebSocket connections `$.iswebsocket` is `true`. End the delegate with exactly one of these calls:\n\n| Call | Result |\n| --- | --- |\n| `$.success(user)` | The request is authorized and `user` becomes `$.user` |\n| `$.invalid()` | The request is not authorized and the user is `undefined` |\n\nThe delegate can be asynchronous: call `$.success()` or `$.invalid()` when your database answers. The request body is already parsed when the delegate runs, so `$.body` is available.\n\nWithout an `AUTH()` delegate no user is ever assigned and the `+` and `-` flags of routes are not checked.\n\n## Route flags `+` and `-`\n\nPut the flag in front of the HTTP method:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /admin/', dashboard);\n\tROUTE('-GET  /login/', 'login');\n\tROUTE('-POST /api/login/    --> Account/login');\n\tROUTE('+GET  /api/logout/   --> Account/logout');\n\tROUTE('GET   /', 'index');\n};\n```\n\n| Flag | Who may call the route |\n| --- | --- |\n| `+` | Only an authorized request (the delegate called `$.success()`) |\n| `-` | Only an unauthorized request (the delegate called `$.invalid()`) |\n| none | Everybody |\n\nThe framework first finds the route by its URL, then runs the delegate. When the result does not fit the flag of the route, it looks for another route with the same URL whose flag fits. So you can define `+GET /` and `-GET /` side by side, one for logged users and one for visitors. When no route fits, an HTTP request gets `401` and a WebSocket connection is refused during the handshake, so a browser client receives the close code `1006`.\n\nFor API routes the flag belongs to the whole `API` line and is checked for every endpoint: `ROUTE('+API /api/ products_save --> Products/save')`.\n\n## The user in controllers and actions\n\n```js\nfunction dashboard($) {\n\t$.json({ id: $.user.id, name: $.user.name });\n}\n\nNEWACTION({\n\tid: 'Account/profile',\n\taction: function($) {\n\t\t$.success({ id: $.user.id, name: $.user.name });\n\t}\n});\n```\n\nWhen a route is public (no flag) you can still read the user: `$.user` is filled whenever the delegate accepted the request. `controller.authorize()` runs the delegate on demand and returns a `Promise` with the user.\n\n## Roles and permissions\n\nTotal.js reads two conventions of the user object:\n\n- `user.sa` or `user.su` (super admin) passes every check.\n- `user.permissions` or `user.roles` hold what the user may do, as an array (`['products', 'orders']`) or as an object (`{ products: true }`).\n\n`UNAUTHORIZED($, ...permissions)` returns `false` when the user has at least one of the permissions. Otherwise it responds with `401` through `$.invalid(401)` and returns `true`:\n\n```js\nNEWACTION({\n\tid: 'Products/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tif (UNAUTHORIZED($, 'products', 'admin'))\n\t\t\treturn;\n\t\t$.success();\n\t}\n});\n```\n\nActions can declare the same checks: `user: true` (only authorized), `user: false` (only unauthorized), `sa: true` (only super admins) and `permissions: 'products,admin'` (any of them).\n\n## Built-in sessions\n\nPass an object instead of a function and `AUTH()` installs a cookie session system. The framework fills the object with methods, so keep a reference to it:\n\n```js\n// definitions/auth.js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.ddos = 10;\nopt.options = { httponly: true, security: 'lax' };\n\nopt.onread = function(meta, next) {\n\t// meta: { sessionid, userid, ip, ua }\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\nThe cookie holds a signed token with the session ID and the user ID. On a request the framework verifies the token, looks for the session in memory and calls `onread()` only when the session is not there yet. The loaded data is kept for `expire` since the last read from the database; expired sessions are removed every `cleaner` minutes (default `5`).\n\nSign in and sign out from actions:\n\n```js\nNEWACTION({\n\tid: 'Account/login',\n\tinput: '*email:Email,*password:String',\n\taction: function($, model) {\n\n\t\tif (BLOCKED($, 10)) {\n\t\t\t$.invalid(401);\n\t\t\treturn;\n\t\t}\n\n\t\tDATA.read('tbl_user').where('email', model.email).where('password', model.password.sha256(CONF.secret)).callback(function(err, user) {\n\t\t\tif (user) {\n\t\t\t\tBLOCKED($, null);\n\t\t\t\tMAIN.session.authcookie($, UID(), user.id, '1 month');\n\t\t\t\t$.success();\n\t\t\t} else\n\t\t\t\t$.invalid(401);\n\t\t});\n\t}\n});\n\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.update(userid, fn)` changes the cached data of all sessions of a user and `opt.refresh(userid)` drops them, so the next request reads the user again.\n\n## Brute-force protection\n\n`BLOCKED($, limit, expire)` counts calls per IP address. It returns `true` when the address was counted more than `limit` times (default `5`). The counter is removed after `expire` (default `'15 minutes'`), or at once with `BLOCKED($, null)`. Call it before you check a password and reset it after a success, as in the login above.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JacVDy45I60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/authorization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Autorisierung","summary":"Mit AUTH() bestimmen, wer der Benutzer einer Anfrage ist, Routen und Aktionen schützen und eingebaute Sessions verwenden.","markdown":"---\ntitle: Autorisierung\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/authorization/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Autorisierung\n\n> Mit AUTH() bestimmen, wer der Benutzer einer Anfrage ist, Routen und Aktionen schützen und eingebaute Sessions verwenden.\n\nTotal.js entscheidet nicht, wer ein Benutzer ist. Du registrierst mit `AUTH()` einen **Autorisierungs-Delegate**, das Framework ruft ihn für jede Anfrage auf, die zu einer Route passt, und das Objekt, das du akzeptierst, wird zum Benutzer der Anfrage: `$.user` in einer Routen-Aktion und in einer Aktion. Routen verwenden dann die Flags `+` und `-`, um festzulegen, wer sie aufrufen darf.\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token === 'secret-token')\n\t\t$.success({ id: '1', name: 'Peter', sa: true });\n\telse\n\t\t$.invalid();\n});\n```\n\n## Der Delegate\n\nDer Delegate erhält `$`, ein für die aktuelle Anfrage erstelltes Optionsobjekt. Es hat `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.cookie(name)` und `$.controller`. Bei WebSocket-Verbindungen ist `$.iswebsocket` `true`. Beende den Delegate mit genau einem dieser Aufrufe:\n\n| Aufruf | Ergebnis |\n| --- | --- |\n| `$.success(user)` | Die Anfrage ist autorisiert, und `user` wird zu `$.user` |\n| `$.invalid()` | Die Anfrage ist nicht autorisiert, und der Benutzer ist `undefined` |\n\nDer Delegate kann asynchron sein: Rufe `$.success()` oder `$.invalid()` auf, wenn deine Datenbank antwortet. Der Body der Anfrage ist bereits geparst, wenn der Delegate läuft, daher ist `$.body` verfügbar.\n\nOhne einen `AUTH()`-Delegate wird nie ein Benutzer zugewiesen, und die Flags `+` und `-` der Routen werden nicht geprüft.\n\n## Routen-Flags `+` und `-`\n\nSetze das Flag vor die HTTP-Methode:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /admin/', dashboard);\n\tROUTE('-GET  /login/', 'login');\n\tROUTE('-POST /api/login/    --> Account/login');\n\tROUTE('+GET  /api/logout/   --> Account/logout');\n\tROUTE('GET   /', 'index');\n};\n```\n\n| Flag | Wer die Route aufrufen darf |\n| --- | --- |\n| `+` | Nur eine autorisierte Anfrage (der Delegate hat `$.success()` aufgerufen) |\n| `-` | Nur eine nicht autorisierte Anfrage (der Delegate hat `$.invalid()` aufgerufen) |\n| keines | Alle |\n\nDas Framework findet zuerst die Route anhand ihrer URL und führt dann den Delegate aus. Passt das Ergebnis nicht zum Flag der Route, sucht es eine andere Route mit derselben URL, deren Flag passt. So kannst du `+GET /` und `-GET /` nebeneinander definieren, eine für angemeldete Benutzer und eine für Besucher. Passt keine Route, erhält eine HTTP-Anfrage `401`, und eine WebSocket-Verbindung wird beim Handshake abgelehnt, sodass ein Browser-Client den Schließcode `1006` erhält.\n\nBei API-Routen gehört das Flag zur ganzen `API`-Zeile und wird für jeden Endpunkt geprüft: `ROUTE('+API /api/ products_save --> Products/save')`.\n\n## Der Benutzer in Controllern und Aktionen\n\n```js\nfunction dashboard($) {\n\t$.json({ id: $.user.id, name: $.user.name });\n}\n\nNEWACTION({\n\tid: 'Account/profile',\n\taction: function($) {\n\t\t$.success({ id: $.user.id, name: $.user.name });\n\t}\n});\n```\n\nIst eine Route öffentlich (ohne Flag), kannst du den Benutzer trotzdem lesen: `$.user` ist immer dann gefüllt, wenn der Delegate die Anfrage akzeptiert hat. `controller.authorize()` führt den Delegate bei Bedarf aus und gibt eine `Promise` mit dem Benutzer zurück.\n\n## Rollen und Berechtigungen\n\nTotal.js liest zwei Konventionen des Benutzerobjekts:\n\n- `user.sa` oder `user.su` (Super-Admin) besteht jede Prüfung.\n- `user.permissions` oder `user.roles` enthalten, was der Benutzer tun darf, als Array (`['products', 'orders']`) oder als Objekt (`{ products: true }`).\n\n`UNAUTHORIZED($, ...permissions)` gibt `false` zurück, wenn der Benutzer mindestens eine der Berechtigungen hat. Andernfalls antwortet es mit `401` über `$.invalid(401)` und gibt `true` zurück:\n\n```js\nNEWACTION({\n\tid: 'Products/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tif (UNAUTHORIZED($, 'products', 'admin'))\n\t\t\treturn;\n\t\t$.success();\n\t}\n});\n```\n\nAktionen können dieselben Prüfungen deklarieren: `user: true` (nur autorisiert), `user: false` (nur nicht autorisiert), `sa: true` (nur Super-Admins) und `permissions: 'products,admin'` (eine davon).\n\n## Eingebaute Sessions\n\nÜbergib ein Objekt statt einer Funktion, und `AUTH()` installiert ein Cookie-Session-System. Das Framework füllt das Objekt mit Methoden, behalte also eine Referenz darauf:\n\n```js\n// definitions/auth.js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.ddos = 10;\nopt.options = { httponly: true, security: 'lax' };\n\nopt.onread = function(meta, next) {\n\t// meta: { sessionid, userid, ip, ua }\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\nDas Cookie enthält ein signiertes Token mit der Session-ID und der Benutzer-ID. Bei einer Anfrage prüft das Framework das Token, sucht die Session im Speicher und ruft `onread()` nur auf, wenn die Session noch nicht dort ist. Die geladenen Daten werden für `expire` seit dem letzten Lesen aus der Datenbank behalten; abgelaufene Sessions werden alle `cleaner` Minuten entfernt (Standard `5`).\n\nAn- und Abmelden aus Aktionen:\n\n```js\nNEWACTION({\n\tid: 'Account/login',\n\tinput: '*email:Email,*password:String',\n\taction: function($, model) {\n\n\t\tif (BLOCKED($, 10)) {\n\t\t\t$.invalid(401);\n\t\t\treturn;\n\t\t}\n\n\t\tDATA.read('tbl_user').where('email', model.email).where('password', model.password.sha256(CONF.secret)).callback(function(err, user) {\n\t\t\tif (user) {\n\t\t\t\tBLOCKED($, null);\n\t\t\t\tMAIN.session.authcookie($, UID(), user.id, '1 month');\n\t\t\t\t$.success();\n\t\t\t} else\n\t\t\t\t$.invalid(401);\n\t\t});\n\t}\n});\n\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.update(userid, fn)` ändert die zwischengespeicherten Daten aller Sessions eines Benutzers, und `opt.refresh(userid)` verwirft sie, sodass die nächste Anfrage den Benutzer erneut liest.\n\n## Schutz vor Brute-Force-Angriffen\n\n`BLOCKED($, limit, expire)` zählt Aufrufe pro IP-Adresse. Es gibt `true` zurück, wenn die Adresse mehr als `limit` Mal gezählt wurde (Standard `5`). Der Zähler wird nach `expire` entfernt (Standard `'15 minutes'`) oder sofort mit `BLOCKED($, null)`. Rufe es auf, bevor du ein Passwort prüfst, und setze es nach einem Erfolg zurück, wie bei der Anmeldung oben.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JacVDy45I60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/authorization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Autorización","summary":"Decide quién es el usuario de una petición con AUTH(), protege rutas y acciones, y usa las sesiones integradas.","markdown":"---\ntitle: \"Autorización\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/authorization/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Autorización\n\n> Decide quién es el usuario de una petición con AUTH(), protege rutas y acciones, y usa las sesiones integradas.\n\nTotal.js no decide quién es un usuario. Registras un **delegado de autorización** con `AUTH()`, el framework lo llama en cada petición que coincide con una ruta, y el objeto que aceptas se convierte en el usuario de la petición: `$.user` en una acción de ruta y en una acción. Después, las rutas usan los flags `+` y `-` para indicar quién puede llamarlas.\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token === 'secret-token')\n\t\t$.success({ id: '1', name: 'Peter', sa: true });\n\telse\n\t\t$.invalid();\n});\n```\n\n## El delegado\n\nEl delegado recibe `$`, un objeto de opciones construido para la petición actual. Tiene `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.cookie(name)` y `$.controller`. En las conexiones WebSocket, `$.iswebsocket` es `true`. Termina el delegado exactamente con una de estas llamadas:\n\n| Llamada | Resultado |\n| --- | --- |\n| `$.success(user)` | La petición está autorizada y `user` se convierte en `$.user` |\n| `$.invalid()` | La petición no está autorizada y el usuario es `undefined` |\n\nEl delegado puede ser asíncrono: llama a `$.success()` o a `$.invalid()` cuando responda tu base de datos. El cuerpo de la petición ya está analizado cuando se ejecuta el delegado, así que `$.body` está disponible.\n\nSin un delegado `AUTH()` nunca se asigna un usuario y los flags `+` y `-` de las rutas no se comprueban.\n\n## Los flags de ruta `+` y `-`\n\nPon el flag delante del método HTTP:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /admin/', dashboard);\n\tROUTE('-GET  /login/', 'login');\n\tROUTE('-POST /api/login/    --> Account/login');\n\tROUTE('+GET  /api/logout/   --> Account/logout');\n\tROUTE('GET   /', 'index');\n};\n```\n\n| Flag | Quién puede llamar a la ruta |\n| --- | --- |\n| `+` | Solo una petición autorizada (el delegado llamó a `$.success()`) |\n| `-` | Solo una petición no autorizada (el delegado llamó a `$.invalid()`) |\n| ninguno | Todo el mundo |\n\nEl framework primero busca la ruta por su URL y luego ejecuta el delegado. Cuando el resultado no encaja con el flag de la ruta, busca otra ruta con la misma URL cuyo flag sí encaje. Así puedes definir `+GET /` y `-GET /` una al lado de otra, una para los usuarios con sesión iniciada y otra para los visitantes. Cuando no encaja ninguna ruta, una petición HTTP recibe `401` y una conexión WebSocket se rechaza durante el handshake, así que el cliente del navegador recibe el código de cierre `1006`.\n\nEn las rutas API, el flag pertenece a toda la línea `API` y se comprueba para cada endpoint: `ROUTE('+API /api/ products_save --> Products/save')`.\n\n## El usuario en los controladores y las acciones\n\n```js\nfunction dashboard($) {\n\t$.json({ id: $.user.id, name: $.user.name });\n}\n\nNEWACTION({\n\tid: 'Account/profile',\n\taction: function($) {\n\t\t$.success({ id: $.user.id, name: $.user.name });\n\t}\n});\n```\n\nCuando una ruta es pública (sin flag) igualmente puedes leer el usuario: `$.user` se rellena siempre que el delegado aceptó la petición. `controller.authorize()` ejecuta el delegado bajo demanda y devuelve una `Promise` con el usuario.\n\n## Roles y permisos\n\nTotal.js lee dos convenciones del objeto de usuario:\n\n- `user.sa` o `user.su` (superadministrador) supera todas las comprobaciones.\n- `user.permissions` o `user.roles` contienen lo que el usuario puede hacer, como array (`['products', 'orders']`) o como objeto (`{ products: true }`).\n\n`UNAUTHORIZED($, ...permissions)` devuelve `false` cuando el usuario tiene al menos uno de los permisos. Si no, responde con `401` mediante `$.invalid(401)` y devuelve `true`:\n\n```js\nNEWACTION({\n\tid: 'Products/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tif (UNAUTHORIZED($, 'products', 'admin'))\n\t\t\treturn;\n\t\t$.success();\n\t}\n});\n```\n\nLas acciones pueden declarar las mismas comprobaciones: `user: true` (solo autorizados), `user: false` (solo no autorizados), `sa: true` (solo superadministradores) y `permissions: 'products,admin'` (cualquiera de ellos).\n\n## Sesiones integradas\n\nPasa un objeto en lugar de una función y `AUTH()` instala un sistema de sesiones con cookies. El framework rellena el objeto con métodos, así que conserva una referencia a él:\n\n```js\n// definitions/auth.js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.ddos = 10;\nopt.options = { httponly: true, security: 'lax' };\n\nopt.onread = function(meta, next) {\n\t// meta: { sessionid, userid, ip, ua }\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\nLa cookie contiene un token firmado con el ID de la sesión y el ID del usuario. En cada petición, el framework verifica el token, busca la sesión en memoria y llama a `onread()` solo cuando la sesión todavía no está allí. Los datos cargados se conservan durante `expire` desde la última lectura de la base de datos; las sesiones expiradas se eliminan cada `cleaner` minutos (por defecto `5`).\n\nInicia y cierra sesión desde las acciones:\n\n```js\nNEWACTION({\n\tid: 'Account/login',\n\tinput: '*email:Email,*password:String',\n\taction: function($, model) {\n\n\t\tif (BLOCKED($, 10)) {\n\t\t\t$.invalid(401);\n\t\t\treturn;\n\t\t}\n\n\t\tDATA.read('tbl_user').where('email', model.email).where('password', model.password.sha256(CONF.secret)).callback(function(err, user) {\n\t\t\tif (user) {\n\t\t\t\tBLOCKED($, null);\n\t\t\t\tMAIN.session.authcookie($, UID(), user.id, '1 month');\n\t\t\t\t$.success();\n\t\t\t} else\n\t\t\t\t$.invalid(401);\n\t\t});\n\t}\n});\n\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.update(userid, fn)` cambia los datos en caché de todas las sesiones de un usuario y `opt.refresh(userid)` las descarta, así que la siguiente petición vuelve a leer el usuario.\n\n## Protección contra fuerza bruta\n\n`BLOCKED($, limit, expire)` cuenta las llamadas por dirección IP. Devuelve `true` cuando la dirección se ha contado más de `limit` veces (por defecto `5`). El contador se elimina después de `expire` (por defecto `'15 minutes'`), o de inmediato con `BLOCKED($, null)`. Llámala antes de comprobar una contraseña y reiníciala después de un éxito, como en el inicio de sesión anterior.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JacVDy45I60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/authorization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Autorisation","summary":"Détermine qui est l'utilisateur d'une requête avec AUTH(), protège les routes et les actions, et utilise les sessions intégrées.","markdown":"---\ntitle: Autorisation\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/authorization/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Autorisation\n\n> Détermine qui est l'utilisateur d'une requête avec AUTH(), protège les routes et les actions, et utilise les sessions intégrées.\n\nTotal.js ne décide pas qui est un utilisateur. Tu enregistres un **délégué d'autorisation** avec `AUTH()`, le framework l'appelle pour chaque requête qui correspond à une route, et l'objet que tu acceptes devient l'utilisateur de la requête : `$.user` dans une action de route et dans une action. Les routes utilisent ensuite les flags `+` et `-` pour indiquer qui peut les appeler.\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token === 'secret-token')\n\t\t$.success({ id: '1', name: 'Peter', sa: true });\n\telse\n\t\t$.invalid();\n});\n```\n\n## Le délégué\n\nLe délégué reçoit `$`, un objet d'options construit pour la requête courante. Il dispose de `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.cookie(name)` et `$.controller`. Pour les connexions WebSocket, `$.iswebsocket` vaut `true`. Termine le délégué par exactement un de ces appels :\n\n| Appel | Résultat |\n| --- | --- |\n| `$.success(user)` | La requête est autorisée et `user` devient `$.user` |\n| `$.invalid()` | La requête n'est pas autorisée et l'utilisateur vaut `undefined` |\n\nLe délégué peut être asynchrone : appelle `$.success()` ou `$.invalid()` quand ta base de données répond. Le corps de la requête est déjà analysé quand le délégué s'exécute : `$.body` est donc disponible.\n\nSans délégué `AUTH()`, aucun utilisateur n'est jamais affecté et les flags `+` et `-` des routes ne sont pas vérifiés.\n\n## Les flags de route `+` et `-`\n\nPlace le flag devant la méthode HTTP :\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /admin/', dashboard);\n\tROUTE('-GET  /login/', 'login');\n\tROUTE('-POST /api/login/    --> Account/login');\n\tROUTE('+GET  /api/logout/   --> Account/logout');\n\tROUTE('GET   /', 'index');\n};\n```\n\n| Flag | Qui peut appeler la route |\n| --- | --- |\n| `+` | Uniquement une requête autorisée (le délégué a appelé `$.success()`) |\n| `-` | Uniquement une requête non autorisée (le délégué a appelé `$.invalid()`) |\n| aucun | Tout le monde |\n\nLe framework trouve d'abord la route par son URL, puis exécute le délégué. Quand le résultat ne correspond pas au flag de la route, il cherche une autre route avec la même URL dont le flag correspond. Tu peux ainsi définir `+GET /` et `-GET /` côte à côte, l'une pour les utilisateurs connectés et l'autre pour les visiteurs. Quand aucune route ne correspond, une requête HTTP reçoit `401` et une connexion WebSocket est refusée pendant le handshake, et le client du navigateur reçoit donc le code de fermeture `1006`.\n\nPour les routes API, le flag s'applique à toute la ligne `API` et est vérifié pour chaque point de terminaison : `ROUTE('+API /api/ products_save --> Products/save')`.\n\n## L'utilisateur dans les contrôleurs et les actions\n\n```js\nfunction dashboard($) {\n\t$.json({ id: $.user.id, name: $.user.name });\n}\n\nNEWACTION({\n\tid: 'Account/profile',\n\taction: function($) {\n\t\t$.success({ id: $.user.id, name: $.user.name });\n\t}\n});\n```\n\nQuand une route est publique (sans flag), tu peux quand même lire l'utilisateur : `$.user` est renseigné dès que le délégué a accepté la requête. `controller.authorize()` exécute le délégué à la demande et renvoie une `Promise` avec l'utilisateur.\n\n## Rôles et permissions\n\nTotal.js lit deux conventions de l'objet utilisateur :\n\n- `user.sa` ou `user.su` (super administrateur) passe toutes les vérifications.\n- `user.permissions` ou `user.roles` contiennent ce que l'utilisateur peut faire, sous forme de tableau (`['products', 'orders']`) ou d'objet (`{ products: true }`).\n\n`UNAUTHORIZED($, ...permissions)` renvoie `false` quand l'utilisateur possède au moins une des permissions. Sinon, elle répond avec `401` via `$.invalid(401)` et renvoie `true` :\n\n```js\nNEWACTION({\n\tid: 'Products/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tif (UNAUTHORIZED($, 'products', 'admin'))\n\t\t\treturn;\n\t\t$.success();\n\t}\n});\n```\n\nLes actions peuvent déclarer les mêmes vérifications : `user: true` (uniquement autorisé), `user: false` (uniquement non autorisé), `sa: true` (uniquement les super administrateurs) et `permissions: 'products,admin'` (l'une d'elles).\n\n## Sessions intégrées\n\nPasse un objet au lieu d'une fonction et `AUTH()` installe un système de sessions par cookie. Le framework remplit l'objet de méthodes : conserve donc une référence à celui-ci :\n\n```js\n// definitions/auth.js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.ddos = 10;\nopt.options = { httponly: true, security: 'lax' };\n\nopt.onread = function(meta, next) {\n\t// meta: { sessionid, userid, ip, ua }\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\nLe cookie contient un jeton signé avec l'ID de session et l'ID de l'utilisateur. À chaque requête, le framework vérifie le jeton, cherche la session en mémoire et n'appelle `onread()` que lorsque la session n'y est pas encore. Les données chargées sont conservées pendant `expire` depuis la dernière lecture en base de données ; les sessions expirées sont supprimées toutes les `cleaner` minutes (`5` par défaut).\n\nConnexion et déconnexion depuis des actions :\n\n```js\nNEWACTION({\n\tid: 'Account/login',\n\tinput: '*email:Email,*password:String',\n\taction: function($, model) {\n\n\t\tif (BLOCKED($, 10)) {\n\t\t\t$.invalid(401);\n\t\t\treturn;\n\t\t}\n\n\t\tDATA.read('tbl_user').where('email', model.email).where('password', model.password.sha256(CONF.secret)).callback(function(err, user) {\n\t\t\tif (user) {\n\t\t\t\tBLOCKED($, null);\n\t\t\t\tMAIN.session.authcookie($, UID(), user.id, '1 month');\n\t\t\t\t$.success();\n\t\t\t} else\n\t\t\t\t$.invalid(401);\n\t\t});\n\t}\n});\n\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.update(userid, fn)` modifie les données en cache de toutes les sessions d'un utilisateur et `opt.refresh(userid)` les supprime, de sorte que la requête suivante relit l'utilisateur.\n\n## Protection contre la force brute\n\n`BLOCKED($, limit, expire)` compte les appels par adresse IP. Elle renvoie `true` quand l'adresse a été comptée plus de `limit` fois (`5` par défaut). Le compteur est supprimé après `expire` (`'15 minutes'` par défaut), ou immédiatement avec `BLOCKED($, null)`. Appelle-la avant de vérifier un mot de passe et réinitialise-la après un succès, comme dans la connexion ci-dessus.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JacVDy45I60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/authorization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Autorizzazione","summary":"Decidi chi è l'utente di una richiesta con AUTH(), proteggi route e azioni e usa le sessioni integrate.","markdown":"---\ntitle: Autorizzazione\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/authorization/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Autorizzazione\n\n> Decidi chi è l'utente di una richiesta con AUTH(), proteggi route e azioni e usa le sessioni integrate.\n\nTotal.js non decide chi è un utente. Registri un **delegate di autorizzazione** con `AUTH()`, il framework lo chiama per ogni richiesta che corrisponde a una route, e l'oggetto che accetti diventa l'utente della richiesta: `$.user` in un'azione di route e in un'azione. Le route usano poi i flag `+` e `-` per indicare chi può chiamarle.\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token === 'secret-token')\n\t\t$.success({ id: '1', name: 'Peter', sa: true });\n\telse\n\t\t$.invalid();\n});\n```\n\n## Il delegate\n\nIl delegate riceve `$`, un oggetto di opzioni costruito per la richiesta corrente. Ha `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.cookie(name)` e `$.controller`. Per le connessioni WebSocket `$.iswebsocket` è `true`. Termina il delegate con esattamente una di queste chiamate:\n\n| Chiamata | Risultato |\n| --- | --- |\n| `$.success(user)` | La richiesta è autorizzata e `user` diventa `$.user` |\n| `$.invalid()` | La richiesta non è autorizzata e l'utente è `undefined` |\n\nIl delegate può essere asincrono: chiama `$.success()` o `$.invalid()` quando il tuo database risponde. Il body della richiesta è già analizzato quando il delegate viene eseguito, quindi `$.body` è disponibile.\n\nSenza un delegate `AUTH()` nessun utente viene mai assegnato e i flag `+` e `-` delle route non vengono verificati.\n\n## Flag di route `+` e `-`\n\nMetti il flag davanti al metodo HTTP:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /admin/', dashboard);\n\tROUTE('-GET  /login/', 'login');\n\tROUTE('-POST /api/login/    --> Account/login');\n\tROUTE('+GET  /api/logout/   --> Account/logout');\n\tROUTE('GET   /', 'index');\n};\n```\n\n| Flag | Chi può chiamare la route |\n| --- | --- |\n| `+` | Solo una richiesta autorizzata (il delegate ha chiamato `$.success()`) |\n| `-` | Solo una richiesta non autorizzata (il delegate ha chiamato `$.invalid()`) |\n| nessuno | Tutti |\n\nIl framework prima trova la route in base al suo URL, poi esegue il delegate. Quando il risultato non corrisponde al flag della route, cerca un'altra route con lo stesso URL il cui flag corrisponda. Così puoi definire `+GET /` e `-GET /` uno accanto all'altro, uno per gli utenti autenticati e uno per i visitatori. Quando nessuna route corrisponde, una richiesta HTTP riceve `401` e una connessione WebSocket viene rifiutata durante l'handshake, quindi il client del browser riceve il codice di chiusura `1006`.\n\nPer le route API il flag appartiene all'intera riga `API` e viene verificato per ogni endpoint: `ROUTE('+API /api/ products_save --> Products/save')`.\n\n## L'utente nei controller e nelle azioni\n\n```js\nfunction dashboard($) {\n\t$.json({ id: $.user.id, name: $.user.name });\n}\n\nNEWACTION({\n\tid: 'Account/profile',\n\taction: function($) {\n\t\t$.success({ id: $.user.id, name: $.user.name });\n\t}\n});\n```\n\nQuando una route è pubblica (senza flag) puoi comunque leggere l'utente: `$.user` viene impostato ogni volta che il delegate ha accettato la richiesta. `controller.authorize()` esegue il delegate su richiesta e restituisce una `Promise` con l'utente.\n\n## Ruoli e permessi\n\nTotal.js legge due convenzioni dell'oggetto utente:\n\n- `user.sa` o `user.su` (super admin) supera ogni verifica.\n- `user.permissions` o `user.roles` contengono ciò che l'utente può fare, come array (`['products', 'orders']`) o come oggetto (`{ products: true }`).\n\n`UNAUTHORIZED($, ...permissions)` restituisce `false` quando l'utente ha almeno uno dei permessi. Altrimenti risponde con `401` tramite `$.invalid(401)` e restituisce `true`:\n\n```js\nNEWACTION({\n\tid: 'Products/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tif (UNAUTHORIZED($, 'products', 'admin'))\n\t\t\treturn;\n\t\t$.success();\n\t}\n});\n```\n\nLe azioni possono dichiarare le stesse verifiche: `user: true` (solo autorizzati), `user: false` (solo non autorizzati), `sa: true` (solo super admin) e `permissions: 'products,admin'` (uno qualsiasi di essi).\n\n## Sessioni integrate\n\nPassa un oggetto invece di una funzione e `AUTH()` installa un sistema di sessioni basato su cookie. Il framework riempie l'oggetto con dei metodi, quindi conservane un riferimento:\n\n```js\n// definitions/auth.js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.ddos = 10;\nopt.options = { httponly: true, security: 'lax' };\n\nopt.onread = function(meta, next) {\n\t// meta: { sessionid, userid, ip, ua }\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\nIl cookie contiene un token firmato con l'ID della sessione e l'ID dell'utente. A ogni richiesta il framework verifica il token, cerca la sessione in memoria e chiama `onread()` solo quando la sessione non è ancora presente. I dati caricati vengono conservati per `expire` dall'ultima lettura dal database; le sessioni scadute vengono rimosse ogni `cleaner` minuti (predefinito `5`).\n\nAccesso e disconnessione dalle azioni:\n\n```js\nNEWACTION({\n\tid: 'Account/login',\n\tinput: '*email:Email,*password:String',\n\taction: function($, model) {\n\n\t\tif (BLOCKED($, 10)) {\n\t\t\t$.invalid(401);\n\t\t\treturn;\n\t\t}\n\n\t\tDATA.read('tbl_user').where('email', model.email).where('password', model.password.sha256(CONF.secret)).callback(function(err, user) {\n\t\t\tif (user) {\n\t\t\t\tBLOCKED($, null);\n\t\t\t\tMAIN.session.authcookie($, UID(), user.id, '1 month');\n\t\t\t\t$.success();\n\t\t\t} else\n\t\t\t\t$.invalid(401);\n\t\t});\n\t}\n});\n\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.update(userid, fn)` modifica i dati in cache di tutte le sessioni di un utente e `opt.refresh(userid)` le scarta, così la richiesta successiva rilegge l'utente.\n\n## Protezione dal brute force\n\n`BLOCKED($, limit, expire)` conta le chiamate per indirizzo IP. Restituisce `true` quando l'indirizzo è stato contato più di `limit` volte (predefinito `5`). Il contatore viene rimosso dopo `expire` (predefinito `'15 minutes'`), o subito con `BLOCKED($, null)`. Chiamala prima di verificare una password e azzerala dopo un successo, come nel login qui sopra.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JacVDy45I60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/authorization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Autorizácia","summary":"Urči pomocou AUTH(), kto je používateľom požiadavky, chráň routy a akcie a používaj vstavané session.","markdown":"---\ntitle: \"Autorizácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/authorization/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Autorizácia\n\n> Urči pomocou AUTH(), kto je používateľom požiadavky, chráň routy a akcie a používaj vstavané session.\n\nTotal.js nerozhoduje, kto je používateľ. Zaregistruješ jeden **autorizačný delegát** pomocou `AUTH()`, framework ho zavolá pre každú požiadavku, ktorá zodpovedá route, a objekt, ktorý prijmeš, sa stane používateľom požiadavky: `$.user` v akcii routy aj v akcii. Routy potom pomocou flagov `+` a `-` určujú, kto ich môže volať.\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token === 'secret-token')\n\t\t$.success({ id: '1', name: 'Peter', sa: true });\n\telse\n\t\t$.invalid();\n});\n```\n\n## Delegát\n\nDelegát dostane `$`, objekt volieb vytvorený pre aktuálnu požiadavku. Má `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.cookie(name)` a `$.controller`. Pre WebSocket spojenia je `$.iswebsocket` `true`. Delegát ukonči presne jedným z týchto volaní:\n\n| Volanie | Výsledok |\n| --- | --- |\n| `$.success(user)` | Požiadavka je autorizovaná a `user` sa stane `$.user` |\n| `$.invalid()` | Požiadavka nie je autorizovaná a používateľ je `undefined` |\n\nDelegát môže byť asynchrónny: zavolaj `$.success()` alebo `$.invalid()`, keď tvoja databáza odpovie. Telo požiadavky je v čase behu delegáta už sparsované, takže `$.body` je dostupné.\n\nBez delegáta `AUTH()` sa nikdy nepriradí žiadny používateľ a flagy rout `+` a `-` sa nekontrolujú.\n\n## Flagy rout `+` a `-`\n\nFlag daj pred HTTP metódu:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /admin/', dashboard);\n\tROUTE('-GET  /login/', 'login');\n\tROUTE('-POST /api/login/    --> Account/login');\n\tROUTE('+GET  /api/logout/   --> Account/logout');\n\tROUTE('GET   /', 'index');\n};\n```\n\n| Flag | Kto môže volať routu |\n| --- | --- |\n| `+` | Len autorizovaná požiadavka (delegát zavolal `$.success()`) |\n| `-` | Len neautorizovaná požiadavka (delegát zavolal `$.invalid()`) |\n| žiadny | Všetci |\n\nFramework najprv nájde routu podľa jej URL, potom spustí delegát. Keď výsledok nezodpovedá flagu routy, hľadá inú routu s rovnakou URL, ktorej flag zodpovedá. Preto môžeš vedľa seba definovať `+GET /` a `-GET /`, jednu pre prihlásených používateľov a jednu pre návštevníkov. Keď nezodpovedá žiadna routa, HTTP požiadavka dostane `401` a WebSocket spojenie sa odmietne počas handshaku, takže klient v prehliadači dostane kód zatvorenia `1006`.\n\nPri API routách patrí flag celému riadku `API` a kontroluje sa pre každý endpoint: `ROUTE('+API /api/ products_save --> Products/save')`.\n\n## Používateľ v controlleroch a akciách\n\n```js\nfunction dashboard($) {\n\t$.json({ id: $.user.id, name: $.user.name });\n}\n\nNEWACTION({\n\tid: 'Account/profile',\n\taction: function($) {\n\t\t$.success({ id: $.user.id, name: $.user.name });\n\t}\n});\n```\n\nKeď je routa verejná (bez flagu), používateľa môžeš stále čítať: `$.user` sa vyplní vždy, keď delegát požiadavku prijal. `controller.authorize()` spustí delegát na požiadanie a vráti `Promise` s používateľom.\n\n## Roly a oprávnenia\n\nTotal.js číta dve konvencie objektu používateľa:\n\n- `user.sa` alebo `user.su` (super admin) prejde každou kontrolou.\n- `user.permissions` alebo `user.roles` obsahujú, čo používateľ smie robiť, ako pole (`['products', 'orders']`) alebo ako objekt (`{ products: true }`).\n\n`UNAUTHORIZED($, ...permissions)` vráti `false`, keď má používateľ aspoň jedno z oprávnení. Inak odpovie `401` cez `$.invalid(401)` a vráti `true`:\n\n```js\nNEWACTION({\n\tid: 'Products/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tif (UNAUTHORIZED($, 'products', 'admin'))\n\t\t\treturn;\n\t\t$.success();\n\t}\n});\n```\n\nAkcie môžu deklarovať rovnaké kontroly: `user: true` (len autorizovaní), `user: false` (len neautorizovaní), `sa: true` (len super admini) a `permissions: 'products,admin'` (ktorékoľvek z nich).\n\n## Vstavané session\n\nOdovzdaj objekt namiesto funkcie a `AUTH()` nainštaluje systém session založený na cookies. Framework objekt vyplní metódami, preto si naň uchovaj referenciu:\n\n```js\n// definitions/auth.js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.ddos = 10;\nopt.options = { httponly: true, security: 'lax' };\n\nopt.onread = function(meta, next) {\n\t// meta: { sessionid, userid, ip, ua }\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n\nAUTH(opt);\nMAIN.session = opt;\n```\n\nCookie obsahuje podpísaný token s ID session a ID používateľa. Pri požiadavke framework overí token, vyhľadá session v pamäti a zavolá `onread()` len vtedy, keď tam session ešte nie je. Načítané dáta sa uchovávajú počas `expire` od posledného čítania z databázy; expirované session sa odstraňujú každých `cleaner` minút (predvolene `5`).\n\nPrihlásenie a odhlásenie z akcií:\n\n```js\nNEWACTION({\n\tid: 'Account/login',\n\tinput: '*email:Email,*password:String',\n\taction: function($, model) {\n\n\t\tif (BLOCKED($, 10)) {\n\t\t\t$.invalid(401);\n\t\t\treturn;\n\t\t}\n\n\t\tDATA.read('tbl_user').where('email', model.email).where('password', model.password.sha256(CONF.secret)).callback(function(err, user) {\n\t\t\tif (user) {\n\t\t\t\tBLOCKED($, null);\n\t\t\t\tMAIN.session.authcookie($, UID(), user.id, '1 month');\n\t\t\t\t$.success();\n\t\t\t} else\n\t\t\t\t$.invalid(401);\n\t\t});\n\t}\n});\n\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n`opt.update(userid, fn)` zmení dáta v cache všetkých session používateľa a `opt.refresh(userid)` ich zahodí, takže ďalšia požiadavka načíta používateľa znova.\n\n## Ochrana proti brute-force\n\n`BLOCKED($, limit, expire)` počíta volania podľa IP adresy. Vráti `true`, keď bola adresa započítaná viac ako `limit`-krát (predvolene `5`). Počítadlo sa odstráni po `expire` (predvolene `'15 minutes'`), alebo okamžite pomocou `BLOCKED($, null)`. Zavolaj ho pred kontrolou hesla a po úspechu ho vynuluj, ako pri prihlásení vyššie.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JafJNb1uD61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/encryption/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Encryption","summary":"Encrypt values with ENCRYPT() and DECRYPT(), bind them to the client of a request with ENCRYPTREQ() and DECRYPTREQ(), and choose the cipher.","markdown":"---\ntitle: Encryption\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/encryption/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Encryption\n\n> Encrypt values with ENCRYPT() and DECRYPT(), bind them to the client of a request with ENCRYPTREQ() and DECRYPTREQ(), and choose the cipher.\n\n`ENCRYPT(value, key)` turns any JSON-serializable value into a string and `DECRYPT(string, key)` turns it back, or returns `null` for an invalid string. The secret `CONF.secret` is part of the key.\n\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\nvar data = DECRYPT(token, 'reset');\n```\n\n`ENCRYPTREQ($, value, key)` and `DECRYPTREQ($, value, key)` bind the value to the browser of the request (a hash of `User-Agent`, and the IP address with `strict`), so a token copied to another client does not decrypt:\n\n```js\nvar token = ENCRYPTREQ($, { id: user.id }, 'download');\n// later, in another request of the same browser\nvar data = DECRYPTREQ($, token, 'download');\n```\n\nTo use a Node.js cipher instead of the built-in algorithm, set `$crypto` in the configuration (for example `aes-256-cbc`). The key then must have the byte length the cipher needs.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJNb1uD61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/encryption/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Verschlüsselung","summary":"Verschlüssele Werte mit ENCRYPT() und DECRYPT(), binde sie mit ENCRYPTREQ() und DECRYPTREQ() an den Client einer Anfrage und wähle die Chiffre.","markdown":"---\ntitle: \"Verschlüsselung\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/encryption/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Verschlüsselung\n\n> Verschlüssele Werte mit ENCRYPT() und DECRYPT(), binde sie mit ENCRYPTREQ() und DECRYPTREQ() an den Client einer Anfrage und wähle die Chiffre.\n\n`ENCRYPT(value, key)` macht aus jedem JSON-serialisierbaren Wert einen String, und `DECRYPT(string, key)` wandelt ihn zurück oder gibt bei einem ungültigen String `null` zurück. Das Geheimnis `CONF.secret` ist Teil des Schlüssels.\n\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\nvar data = DECRYPT(token, 'reset');\n```\n\n`ENCRYPTREQ($, value, key)` und `DECRYPTREQ($, value, key)` binden den Wert an den Browser der Anfrage (ein Hash von `User-Agent` und mit `strict` der IP-Adresse), sodass ein auf einen anderen Client kopiertes Token nicht entschlüsselt wird:\n\n```js\nvar token = ENCRYPTREQ($, { id: user.id }, 'download');\n// later, in another request of the same browser\nvar data = DECRYPTREQ($, token, 'download');\n```\n\nUm statt des eingebauten Algorithmus eine Node.js-Chiffre zu verwenden, setze `$crypto` in der Konfiguration (zum Beispiel `aes-256-cbc`). Der Schlüssel muss dann die Bytelänge haben, die die Chiffre braucht.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJNb1uD61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/encryption/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Cifrado","summary":"Cifra valores con ENCRYPT() y DECRYPT(), átalos al cliente de una petición con ENCRYPTREQ() y DECRYPTREQ(), y elige el cifrador.","markdown":"---\ntitle: Cifrado\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/encryption/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Cifrado\n\n> Cifra valores con ENCRYPT() y DECRYPT(), átalos al cliente de una petición con ENCRYPTREQ() y DECRYPTREQ(), y elige el cifrador.\n\n`ENCRYPT(value, key)` convierte cualquier valor serializable a JSON en una cadena y `DECRYPT(string, key)` lo devuelve a su forma original, o devuelve `null` para una cadena no válida. El secreto `CONF.secret` forma parte de la clave.\n\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\nvar data = DECRYPT(token, 'reset');\n```\n\n`ENCRYPTREQ($, value, key)` y `DECRYPTREQ($, value, key)` vinculan el valor al navegador de la petición (un hash de `User-Agent`, y la dirección IP con `strict`), así que un token copiado a otro cliente no se descifra:\n\n```js\nvar token = ENCRYPTREQ($, { id: user.id }, 'download');\n// later, in another request of the same browser\nvar data = DECRYPTREQ($, token, 'download');\n```\n\nPara usar un cifrado de Node.js en lugar del algoritmo integrado, establece `$crypto` en la configuración (por ejemplo `aes-256-cbc`). La clave debe tener entonces la longitud en bytes que necesita el cifrado.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJNb1uD61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/encryption/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Chiffrement","summary":"Chiffre des valeurs avec ENCRYPT() et DECRYPT(), lie-les au client d'une requête avec ENCRYPTREQ() et DECRYPTREQ(), et choisis l'algorithme de chiffrement.","markdown":"---\ntitle: Chiffrement\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/encryption/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Chiffrement\n\n> Chiffre des valeurs avec ENCRYPT() et DECRYPT(), lie-les au client d'une requête avec ENCRYPTREQ() et DECRYPTREQ(), et choisis l'algorithme de chiffrement.\n\n`ENCRYPT(value, key)` transforme toute valeur sérialisable en JSON en chaîne et `DECRYPT(string, key)` la reconvertit, ou renvoie `null` pour une chaîne invalide. Le secret `CONF.secret` fait partie de la clé.\n\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\nvar data = DECRYPT(token, 'reset');\n```\n\n`ENCRYPTREQ($, value, key)` et `DECRYPTREQ($, value, key)` lient la valeur au navigateur de la requête (un hachage du `User-Agent`, et l'adresse IP avec `strict`), de sorte qu'un jeton copié vers un autre client ne se déchiffre pas :\n\n```js\nvar token = ENCRYPTREQ($, { id: user.id }, 'download');\n// later, in another request of the same browser\nvar data = DECRYPTREQ($, token, 'download');\n```\n\nPour utiliser un algorithme de chiffrement de Node.js au lieu de l'algorithme intégré, définis `$crypto` dans la configuration (par exemple `aes-256-cbc`). La clé doit alors avoir la longueur en octets requise par l'algorithme.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJNb1uD61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/encryption/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Cifratura","summary":"Cifra i valori con ENCRYPT() e DECRYPT(), legali al client di una richiesta con ENCRYPTREQ() e DECRYPTREQ() e scegli il cifrario.","markdown":"---\ntitle: Cifratura\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/encryption/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Cifratura\n\n> Cifra i valori con ENCRYPT() e DECRYPT(), legali al client di una richiesta con ENCRYPTREQ() e DECRYPTREQ() e scegli il cifrario.\n\n`ENCRYPT(value, key)` trasforma qualsiasi valore serializzabile in JSON in una stringa e `DECRYPT(string, key)` lo riconverte, o restituisce `null` per una stringa non valida. Il segreto `CONF.secret` fa parte della chiave.\n\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\nvar data = DECRYPT(token, 'reset');\n```\n\n`ENCRYPTREQ($, value, key)` e `DECRYPTREQ($, value, key)` legano il valore al browser della richiesta (un hash di `User-Agent`, e dell'indirizzo IP con `strict`), così un token copiato su un altro client non viene decifrato:\n\n```js\nvar token = ENCRYPTREQ($, { id: user.id }, 'download');\n// later, in another request of the same browser\nvar data = DECRYPTREQ($, token, 'download');\n```\n\nPer usare un cifrario di Node.js invece dell'algoritmo integrato, imposta `$crypto` nella configurazione (per esempio `aes-256-cbc`). La chiave deve allora avere la lunghezza in byte richiesta dal cifrario.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJNb1uD61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/encryption/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Šifrovanie","summary":"Šifruj hodnoty pomocou ENCRYPT() a DECRYPT(), viaž ich na klienta požiadavky pomocou ENCRYPTREQ() a DECRYPTREQ() a vyber šifru.","markdown":"---\ntitle: \"Šifrovanie\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/encryption/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Šifrovanie\n\n> Šifruj hodnoty pomocou ENCRYPT() a DECRYPT(), viaž ich na klienta požiadavky pomocou ENCRYPTREQ() a DECRYPTREQ() a vyber šifru.\n\n`ENCRYPT(value, key)` zmení ľubovoľnú hodnotu serializovateľnú do JSON na reťazec a `DECRYPT(string, key)` ju zmení späť, alebo vráti `null` pre neplatný reťazec. Tajomstvo `CONF.secret` je súčasťou kľúča.\n\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\nvar data = DECRYPT(token, 'reset');\n```\n\n`ENCRYPTREQ($, value, key)` a `DECRYPTREQ($, value, key)` naviažu hodnotu na prehliadač požiadavky (hash `User-Agent` a so `strict` aj IP adresu), takže token skopírovaný do iného klienta sa nedešifruje:\n\n```js\nvar token = ENCRYPTREQ($, { id: user.id }, 'download');\n// later, in another request of the same browser\nvar data = DECRYPTREQ($, token, 'download');\n```\n\nAk chceš namiesto vstavaného algoritmu použiť šifru Node.js, nastav v konfigurácii `$crypto` (napríklad `aes-256-cbc`). Kľúč potom musí mať dĺžku v bajtoch, ktorú šifra potrebuje.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJSR3oD61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Audit logs","summary":"Record who did what with AUDIT() and $.audit(), audit actions after they succeed, and store the records where you need them.","markdown":"---\ntitle: Audit logs\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/audit-logs/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Audit logs\n\n> Record who did what with AUDIT() and $.audit(), audit actions after they succeed, and store the records where you need them.\n\n`AUDIT()` writes who did what. It reads the user, IP address, user agent, URL and action from `$`:\n\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.audit('Removed order {params.id} by {user.name}');\n\t\t$.success();\n\t}\n});\n```\n\nA record contains `userid`, `createdby` (the `name`, `nick` or `alias` of the user), `sessionid`, `ip`, `ua`, `url`, `action`, `type`, `message`, `app` and `dtcreated`. `data` contains the params, query, model and uploaded files (`name`, `filename`, `size`, `width`, `height`) as JSON, without the fields `password`, `token`, `accesstoken`, `access_token` and `pin`.\n\nEach record is a line of JSON in `/logs/audit.log` (or `/logs/<name>.log` for `AUDIT('name', $, ...)`). Replace `DEF.onAudit` to store records elsewhere. An action with `audit: true` or with a Tangular template (`audit: 'Removed {{ $.params.id }}'`) is audited into `/logs/actions.log` after it succeeds.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJSR3oD61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Audit-Logs","summary":"Protokolliere mit AUDIT() und $.audit(), wer was getan hat, auditiere Aktionen nach ihrem Erfolg und speichere die Einträge, wo du sie brauchst.","markdown":"---\ntitle: Audit-Logs\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/audit-logs/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Audit-Logs\n\n> Protokolliere mit AUDIT() und $.audit(), wer was getan hat, auditiere Aktionen nach ihrem Erfolg und speichere die Einträge, wo du sie brauchst.\n\n`AUDIT()` schreibt, wer was getan hat. Es liest Benutzer, IP-Adresse, User-Agent, URL und Aktion aus `$`:\n\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.audit('Removed order {params.id} by {user.name}');\n\t\t$.success();\n\t}\n});\n```\n\nEin Eintrag enthält `userid`, `createdby` (den `name`, `nick` oder `alias` des Benutzers), `sessionid`, `ip`, `ua`, `url`, `action`, `type`, `message`, `app` und `dtcreated`. `data` enthält die Params, die Query, das Modell und hochgeladene Dateien (`name`, `filename`, `size`, `width`, `height`) als JSON, ohne die Felder `password`, `token`, `accesstoken`, `access_token` und `pin`.\n\nJeder Eintrag ist eine JSON-Zeile in `/logs/audit.log` (oder `/logs/<name>.log` für `AUDIT('name', $, ...)`). Ersetze `DEF.onAudit`, um Einträge anderswo zu speichern. Eine Aktion mit `audit: true` oder mit einem Tangular-Template (`audit: 'Removed {{ $.params.id }}'`) wird nach ihrem Erfolg in `/logs/actions.log` protokolliert.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJSR3oD61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Registros de auditoría","summary":"Registra quién hizo qué con AUDIT() y $.audit(), audita las acciones cuando terminan bien y guarda los registros donde los necesites.","markdown":"---\ntitle: \"Registros de auditoría\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/audit-logs/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Registros de auditoría\n\n> Registra quién hizo qué con AUDIT() y $.audit(), audita las acciones cuando terminan bien y guarda los registros donde los necesites.\n\n`AUDIT()` escribe quién hizo qué. Lee el usuario, la dirección IP, el user agent, la URL y la acción de `$`:\n\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.audit('Removed order {params.id} by {user.name}');\n\t\t$.success();\n\t}\n});\n```\n\nUn registro contiene `userid`, `createdby` (el `name`, `nick` o `alias` del usuario), `sessionid`, `ip`, `ua`, `url`, `action`, `type`, `message`, `app` y `dtcreated`. `data` contiene los params, la query, el modelo y los archivos subidos (`name`, `filename`, `size`, `width`, `height`) como JSON, sin los campos `password`, `token`, `accesstoken`, `access_token` y `pin`.\n\nCada registro es una línea de JSON en `/logs/audit.log` (o `/logs/<name>.log` para `AUDIT('name', $, ...)`). Sustituye `DEF.onAudit` para guardar los registros en otro lugar. Una acción con `audit: true` o con una plantilla Tangular (`audit: 'Removed {{ $.params.id }}'`) se audita en `/logs/actions.log` después de tener éxito.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJSR3oD61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Journaux d'audit","summary":"Enregistre qui a fait quoi avec AUDIT() et $.audit(), audite les actions quand elles réussissent et stocke les enregistrements où tu en as besoin.","markdown":"---\ntitle: \"Journaux d'audit\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/audit-logs/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Journaux d'audit\n\n> Enregistre qui a fait quoi avec AUDIT() et $.audit(), audite les actions quand elles réussissent et stocke les enregistrements où tu en as besoin.\n\n`AUDIT()` enregistre qui a fait quoi. Elle lit l'utilisateur, l'adresse IP, l'user agent, l'URL et l'action depuis `$` :\n\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.audit('Removed order {params.id} by {user.name}');\n\t\t$.success();\n\t}\n});\n```\n\nUn enregistrement contient `userid`, `createdby` (le `name`, `nick` ou `alias` de l'utilisateur), `sessionid`, `ip`, `ua`, `url`, `action`, `type`, `message`, `app` et `dtcreated`. `data` contient les params, la query, le modèle et les fichiers envoyés (`name`, `filename`, `size`, `width`, `height`) en JSON, sans les champs `password`, `token`, `accesstoken`, `access_token` et `pin`.\n\nChaque enregistrement est une ligne JSON dans `/logs/audit.log` (ou `/logs/<name>.log` pour `AUDIT('name', $, ...)`). Remplace `DEF.onAudit` pour stocker les enregistrements ailleurs. Une action avec `audit: true` ou avec un template Tangular (`audit: 'Removed {{ $.params.id }}'`) est auditée dans `/logs/actions.log` après sa réussite.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJSR3oD61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Audit log","summary":"Registra chi ha fatto cosa con AUDIT() e $.audit(), esegui l'audit delle azioni quando riescono e salva i record dove ti servono.","markdown":"---\ntitle: Audit log\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/audit-logs/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Audit log\n\n> Registra chi ha fatto cosa con AUDIT() e $.audit(), esegui l'audit delle azioni quando riescono e salva i record dove ti servono.\n\n`AUDIT()` registra chi ha fatto cosa. Legge l'utente, l'indirizzo IP, lo user agent, l'URL e l'azione da `$`:\n\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.audit('Removed order {params.id} by {user.name}');\n\t\t$.success();\n\t}\n});\n```\n\nUn record contiene `userid`, `createdby` (il `name`, `nick` o `alias` dell'utente), `sessionid`, `ip`, `ua`, `url`, `action`, `type`, `message`, `app` e `dtcreated`. `data` contiene i parametri, la query, il modello e i file caricati (`name`, `filename`, `size`, `width`, `height`) come JSON, senza i campi `password`, `token`, `accesstoken`, `access_token` e `pin`.\n\nOgni record è una riga di JSON in `/logs/audit.log` (o `/logs/<name>.log` per `AUDIT('name', $, ...)`). Sostituisci `DEF.onAudit` per salvare i record altrove. Un'azione con `audit: true` o con un template Tangular (`audit: 'Removed {{ $.params.id }}'`) viene registrata in `/logs/actions.log` dopo che ha avuto successo.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"JafJSR3oD61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Auditné logy","summary":"Zaznamenaj pomocou AUDIT() a $.audit(), kto čo urobil, audituj akcie, keď uspejú, a ukladaj záznamy tam, kde ich potrebuješ.","markdown":"---\ntitle: \"Auditné logy\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/audit-logs/\nupdated: 2026-11-16T15:32:32.495Z\n---\n\n# Auditné logy\n\n> Zaznamenaj pomocou AUDIT() a $.audit(), kto čo urobil, audituj akcie, keď uspejú, a ukladaj záznamy tam, kde ich potrebuješ.\n\n`AUDIT()` zapisuje, kto čo urobil. Z `$` prečíta používateľa, IP adresu, user agenta, URL a akciu:\n\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.audit('Removed order {params.id} by {user.name}');\n\t\t$.success();\n\t}\n});\n```\n\nZáznam obsahuje `userid`, `createdby` (`name`, `nick` alebo `alias` používateľa), `sessionid`, `ip`, `ua`, `url`, `action`, `type`, `message`, `app` a `dtcreated`. `data` obsahuje params, query, model a nahrané súbory (`name`, `filename`, `size`, `width`, `height`) ako JSON, bez polí `password`, `token`, `accesstoken`, `access_token` a `pin`.\n\nKaždý záznam je riadok JSON v `/logs/audit.log` (alebo `/logs/<name>.log` pre `AUDIT('name', $, ...)`). Ak chceš záznamy ukladať inde, nahraď `DEF.onAudit`. Akcia s `audit: true` alebo so šablónou Tangular (`audit: 'Removed {{ $.params.id }}'`) sa po úspechu zaznamená do `/logs/actions.log`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:32.495Z"}
{"id":"Jafiwz4R860f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/middleware/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Middleware","summary":"Run named functions before routes, WebSockets and actions with NEWMIDDLEWARE().","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/middleware/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Middleware\n\n> Run named functions before routes, WebSockets and actions with NEWMIDDLEWARE().\n\n## Creating a middleware\n\nRegister a middleware with `NEWMIDDLEWARE(name, fn)` (`MIDDLEWARE()` is the same function). The function receives the controller `$` and a `next` callback. Call `next()` to continue; answer the request instead to stop it there.\n\n```js\n// middleware/apikey.js\nexports.install = function() {\n\tNEWMIDDLEWARE('apikey', function($, next) {\n\t\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n\nFiles in the `middleware/` folder (and in `plugins/<name>/middleware/`) are loaded at start like controllers: their `install()` function runs. You can also register a middleware from any other file.\n\nThe name is what routes use to refer to it. Use only letters, digits and `_` in the name, because the route flag accepts only these characters.\n\n## Using a middleware in a route\n\nAdd the name with `#` to the route declaration. Several middleware run in the order you write them, and the action runs after the last one calls `next()`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/orders/ #apikey', orders);\n\tROUTE('POST /api/orders/ #apikey #ratelimit', create);\n\tROUTE('SOCKET /live/ #apikey', live);\n};\n\nfunction orders($) {\n\t$.json([]);\n}\n```\n\nFor HTTP routes, middleware runs after the body is parsed and after your `AUTH()` delegate has run, so `$.body`, `$.query`, `$.params` and `$.user` are ready. A name that is not registered is skipped; in a `SOCKET` route, the middleware after it are skipped too. The `#name` flag also works for `API` routes and for `SOCKET` routes (see [WebSockets](../../guides/websockets/)); for a socket, middleware runs before the connection is accepted.\n\nA middleware can also prepare data for the action:\n\n```js\nNEWMIDDLEWARE('company', function($, next) {\n\t$.company = $.headers['x-company'] || 'default';\n\tnext();\n});\n```\n\n## Assigning a middleware to existing routes\n\nThe third argument of `NEWMIDDLEWARE()` adds the middleware to routes that already exist: `'routes'` (or `'dynamic'`) for all HTTP routes, `'websockets'` for all socket routes. Several values are separated by commas. Only routes registered before the call get it, so call it when all routes exist, for example in the `ready` event.\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('audit', function($, next) {\n\t\tconsole.log($.method, $.url);\n\t\tnext();\n\t}, 'routes');\n});\n```\n\n`NEWMIDDLEWARE(name)` without a function removes the middleware: it is deleted from the registry and from every route that uses it.\n\n## Middleware in actions\n\nAn action created with `NEWACTION()` has its own `middleware` option: a list of names separated by commas, spaces or `|`. Here the function receives the action's `$` (the options object of the action) and runs every time the action is called, from a route or from code. A missing name is reported as an error and skipped.\n\n```js\nNEWMIDDLEWARE('tenant', function($, next) {\n\tif ($.user && $.user.tenantid)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\nSee [Actions](../../guides/actions/) for the other options.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafiwz4R860f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/middleware/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Middleware","summary":"Führe mit NEWMIDDLEWARE() benannte Funktionen vor Routen, WebSockets und Aktionen aus.","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/middleware/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Middleware\n\n> Führe mit NEWMIDDLEWARE() benannte Funktionen vor Routen, WebSockets und Aktionen aus.\n\n## Eine Middleware erstellen\n\nRegistriere eine Middleware mit `NEWMIDDLEWARE(name, fn)` (`MIDDLEWARE()` ist dieselbe Funktion). Die Funktion erhält den Controller `$` und einen Callback `next`. Rufe `next()` auf, um fortzufahren; beantworte stattdessen die Anfrage, um sie dort zu beenden.\n\n```js\n// middleware/apikey.js\nexports.install = function() {\n\tNEWMIDDLEWARE('apikey', function($, next) {\n\t\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n\nDateien im Ordner `middleware/` (und in `plugins/<name>/middleware/`) werden beim Start wie Controller geladen: Ihre Funktion `install()` läuft. Du kannst eine Middleware auch aus jeder anderen Datei registrieren.\n\nÜber den Namen verweisen Routen auf sie. Verwende im Namen nur Buchstaben, Ziffern und `_`, da das Flag der Route nur diese Zeichen akzeptiert.\n\n## Eine Middleware in einer Route verwenden\n\nFüge den Namen mit `#` der Routendeklaration hinzu. Mehrere Middlewares laufen in der Reihenfolge, in der du sie schreibst, und die Aktion läuft, nachdem die letzte `next()` aufgerufen hat.\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/orders/ #apikey', orders);\n\tROUTE('POST /api/orders/ #apikey #ratelimit', create);\n\tROUTE('SOCKET /live/ #apikey', live);\n};\n\nfunction orders($) {\n\t$.json([]);\n}\n```\n\nBei HTTP-Routen läuft die Middleware, nachdem der Body geparst wurde und dein Delegate `AUTH()` gelaufen ist, daher sind `$.body`, `$.query`, `$.params` und `$.user` bereit. Ein nicht registrierter Name wird übersprungen; in einer `SOCKET`-Route werden auch die Middlewares danach übersprungen. Das Flag `#name` funktioniert auch für `API`-Routen und für `SOCKET`-Routen (siehe [WebSockets](../../guides/websockets/)); bei einem Socket läuft die Middleware, bevor die Verbindung angenommen wird.\n\nEine Middleware kann auch Daten für die Aktion vorbereiten:\n\n```js\nNEWMIDDLEWARE('company', function($, next) {\n\t$.company = $.headers['x-company'] || 'default';\n\tnext();\n});\n```\n\n## Eine Middleware bestehenden Routen zuweisen\n\nDas dritte Argument von `NEWMIDDLEWARE()` fügt die Middleware Routen hinzu, die bereits existieren: `'routes'` (oder `'dynamic'`) für alle HTTP-Routen, `'websockets'` für alle Socket-Routen. Mehrere Werte werden durch Kommas getrennt. Nur Routen, die vor dem Aufruf registriert wurden, erhalten sie. Rufe es daher auf, wenn alle Routen existieren, zum Beispiel im Event `ready`.\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('audit', function($, next) {\n\t\tconsole.log($.method, $.url);\n\t\tnext();\n\t}, 'routes');\n});\n```\n\n`NEWMIDDLEWARE(name)` ohne Funktion entfernt die Middleware: Sie wird aus der Registry und aus jeder Route gelöscht, die sie verwendet.\n\n## Middleware in Aktionen\n\nEine mit `NEWACTION()` erstellte Aktion hat eine eigene Option `middleware`: eine Liste von Namen, getrennt durch Kommas, Leerzeichen oder `|`. Hier erhält die Funktion das `$` der Aktion (das Optionsobjekt der Aktion) und läuft bei jedem Aufruf der Aktion, aus einer Route oder aus dem Code. Ein fehlender Name wird als Fehler gemeldet und übersprungen.\n\n```js\nNEWMIDDLEWARE('tenant', function($, next) {\n\tif ($.user && $.user.tenantid)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\nSiehe [Aktionen](../../guides/actions/) für die anderen Optionen.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafiwz4R860f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/middleware/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Middleware","summary":"Ejecuta funciones con nombre antes de las rutas, los WebSockets y las acciones con NEWMIDDLEWARE().","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/middleware/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Middleware\n\n> Ejecuta funciones con nombre antes de las rutas, los WebSockets y las acciones con NEWMIDDLEWARE().\n\n## Crear un middleware\n\nRegistra un middleware con `NEWMIDDLEWARE(name, fn)` (`MIDDLEWARE()` es la misma función). La función recibe el controlador `$` y un callback `next`. Llama a `next()` para continuar; responde a la petición en su lugar para detenerla ahí.\n\n```js\n// middleware/apikey.js\nexports.install = function() {\n\tNEWMIDDLEWARE('apikey', function($, next) {\n\t\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n\nLos archivos de la carpeta `middleware/` (y de `plugins/<name>/middleware/`) se cargan al arrancar como los controladores: se ejecuta su función `install()`. También puedes registrar un middleware desde cualquier otro archivo.\n\nEl nombre es lo que usan las rutas para referirse a él. Usa solo letras, dígitos y `_` en el nombre, porque el flag de la ruta solo acepta esos caracteres.\n\n## Usar un middleware en una ruta\n\nAñade el nombre con `#` a la declaración de la ruta. Varios middleware se ejecutan en el orden en que los escribes, y la acción se ejecuta después de que el último llame a `next()`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/orders/ #apikey', orders);\n\tROUTE('POST /api/orders/ #apikey #ratelimit', create);\n\tROUTE('SOCKET /live/ #apikey', live);\n};\n\nfunction orders($) {\n\t$.json([]);\n}\n```\n\nEn las rutas HTTP, el middleware se ejecuta después de parsear el cuerpo y después de que se haya ejecutado tu delegado `AUTH()`, así que `$.body`, `$.query`, `$.params` y `$.user` están listos. Un nombre que no está registrado se omite; en una ruta `SOCKET`, también se omiten los middleware que van después de él. El flag `#name` también funciona para rutas `API` y para rutas `SOCKET` (consulta [WebSockets](../../guides/websockets/)); en un socket, el middleware se ejecuta antes de aceptar la conexión.\n\nUn middleware también puede preparar datos para la acción:\n\n```js\nNEWMIDDLEWARE('company', function($, next) {\n\t$.company = $.headers['x-company'] || 'default';\n\tnext();\n});\n```\n\n## Asignar un middleware a rutas existentes\n\nEl tercer argumento de `NEWMIDDLEWARE()` añade el middleware a rutas que ya existen: `'routes'` (o `'dynamic'`) para todas las rutas HTTP, `'websockets'` para todas las rutas de socket. Varios valores se separan con comas. Solo lo reciben las rutas registradas antes de la llamada, así que llámalo cuando existan todas las rutas, por ejemplo en el evento `ready`.\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('audit', function($, next) {\n\t\tconsole.log($.method, $.url);\n\t\tnext();\n\t}, 'routes');\n});\n```\n\n`NEWMIDDLEWARE(name)` sin función elimina el middleware: se borra del registro y de todas las rutas que lo usan.\n\n## Middleware en acciones\n\nUna acción creada con `NEWACTION()` tiene su propia opción `middleware`: una lista de nombres separados por comas, espacios o `|`. Aquí la función recibe el `$` de la acción (el objeto de opciones de la acción) y se ejecuta cada vez que se llama a la acción, desde una ruta o desde el código. Un nombre que falta se notifica como error y se omite.\n\n```js\nNEWMIDDLEWARE('tenant', function($, next) {\n\tif ($.user && $.user.tenantid)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\nConsulta [Acciones](../../guides/actions/) para las demás opciones.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafiwz4R860f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/middleware/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Middleware","summary":"Exécute des fonctions nommées avant les routes, les WebSockets et les actions avec NEWMIDDLEWARE().","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/middleware/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Middleware\n\n> Exécute des fonctions nommées avant les routes, les WebSockets et les actions avec NEWMIDDLEWARE().\n\n## Créer un middleware\n\nEnregistre un middleware avec `NEWMIDDLEWARE(name, fn)` (`MIDDLEWARE()` est la même fonction). La fonction reçoit le contrôleur `$` et un callback `next`. Appelle `next()` pour continuer ; réponds plutôt à la requête pour l'arrêter là.\n\n```js\n// middleware/apikey.js\nexports.install = function() {\n\tNEWMIDDLEWARE('apikey', function($, next) {\n\t\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n\nLes fichiers du dossier `middleware/` (et de `plugins/<name>/middleware/`) sont chargés au démarrage comme les contrôleurs : leur fonction `install()` s'exécute. Tu peux aussi enregistrer un middleware depuis n'importe quel autre fichier.\n\nLe nom est ce que les routes utilisent pour y faire référence. N'utilise que des lettres, des chiffres et `_` dans le nom, car le flag de route n'accepte que ces caractères.\n\n## Utiliser un middleware dans une route\n\nAjoute le nom avec `#` à la déclaration de la route. Plusieurs middlewares s'exécutent dans l'ordre où tu les écris, et l'action s'exécute après que le dernier a appelé `next()`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/orders/ #apikey', orders);\n\tROUTE('POST /api/orders/ #apikey #ratelimit', create);\n\tROUTE('SOCKET /live/ #apikey', live);\n};\n\nfunction orders($) {\n\t$.json([]);\n}\n```\n\nPour les routes HTTP, le middleware s'exécute après l'analyse du corps et après l'exécution de ton délégué `AUTH()` : `$.body`, `$.query`, `$.params` et `$.user` sont donc prêts. Un nom qui n'est pas enregistré est ignoré ; dans une route `SOCKET`, les middlewares qui le suivent sont aussi ignorés. Le flag `#name` fonctionne aussi pour les routes `API` et les routes `SOCKET` (voir [WebSockets](../../guides/websockets/)) ; pour un socket, le middleware s'exécute avant que la connexion soit acceptée.\n\nUn middleware peut aussi préparer des données pour l'action :\n\n```js\nNEWMIDDLEWARE('company', function($, next) {\n\t$.company = $.headers['x-company'] || 'default';\n\tnext();\n});\n```\n\n## Assigner un middleware aux routes existantes\n\nLe troisième argument de `NEWMIDDLEWARE()` ajoute le middleware aux routes qui existent déjà : `'routes'` (ou `'dynamic'`) pour toutes les routes HTTP, `'websockets'` pour toutes les routes socket. Plusieurs valeurs sont séparées par des virgules. Seules les routes enregistrées avant l'appel le reçoivent : appelle-le donc quand toutes les routes existent, par exemple dans l'événement `ready`.\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('audit', function($, next) {\n\t\tconsole.log($.method, $.url);\n\t\tnext();\n\t}, 'routes');\n});\n```\n\n`NEWMIDDLEWARE(name)` sans fonction supprime le middleware : il est retiré du registre et de chaque route qui l'utilise.\n\n## Middleware dans les actions\n\nUne action créée avec `NEWACTION()` a sa propre option `middleware` : une liste de noms séparés par des virgules, des espaces ou `|`. Ici, la fonction reçoit le `$` de l'action (l'objet d'options de l'action) et s'exécute à chaque appel de l'action, depuis une route ou depuis le code. Un nom manquant est signalé comme erreur et ignoré.\n\n```js\nNEWMIDDLEWARE('tenant', function($, next) {\n\tif ($.user && $.user.tenantid)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\nVoir [Actions](../../guides/actions/) pour les autres options.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafiwz4R860f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/middleware/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Middleware","summary":"Esegui funzioni con nome prima di route, WebSocket e azioni con NEWMIDDLEWARE().","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/middleware/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Middleware\n\n> Esegui funzioni con nome prima di route, WebSocket e azioni con NEWMIDDLEWARE().\n\n## Creare un middleware\n\nRegistra un middleware con `NEWMIDDLEWARE(name, fn)` (`MIDDLEWARE()` è la stessa funzione). La funzione riceve il controller `$` e una callback `next`. Chiama `next()` per proseguire; rispondi invece alla richiesta per fermarla lì.\n\n```js\n// middleware/apikey.js\nexports.install = function() {\n\tNEWMIDDLEWARE('apikey', function($, next) {\n\t\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n\nI file nella cartella `middleware/` (e in `plugins/<name>/middleware/`) vengono caricati all'avvio come i controller: viene eseguita la loro funzione `install()`. Puoi anche registrare un middleware da qualsiasi altro file.\n\nIl nome è ciò che le route usano per farvi riferimento. Usa nel nome solo lettere, cifre e `_`, perché il flag della route accetta solo questi caratteri.\n\n## Usare un middleware in una route\n\nAggiungi il nome con `#` alla dichiarazione della route. Più middleware vengono eseguiti nell'ordine in cui li scrivi, e l'azione viene eseguita dopo che l'ultimo ha chiamato `next()`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/orders/ #apikey', orders);\n\tROUTE('POST /api/orders/ #apikey #ratelimit', create);\n\tROUTE('SOCKET /live/ #apikey', live);\n};\n\nfunction orders($) {\n\t$.json([]);\n}\n```\n\nPer le route HTTP, il middleware viene eseguito dopo il parsing del body e dopo l'esecuzione del tuo delegate `AUTH()`, quindi `$.body`, `$.query`, `$.params` e `$.user` sono pronti. Un nome non registrato viene saltato; in una route `SOCKET` vengono saltati anche i middleware successivi. Il flag `#name` funziona anche per le route `API` e per le route `SOCKET` (vedi [WebSocket](../../guides/websockets/)); per un socket, il middleware viene eseguito prima che la connessione venga accettata.\n\nUn middleware può anche preparare dati per l'azione:\n\n```js\nNEWMIDDLEWARE('company', function($, next) {\n\t$.company = $.headers['x-company'] || 'default';\n\tnext();\n});\n```\n\n## Assegnare un middleware a route esistenti\n\nIl terzo argomento di `NEWMIDDLEWARE()` aggiunge il middleware a route già esistenti: `'routes'` (o `'dynamic'`) per tutte le route HTTP, `'websockets'` per tutte le route socket. Più valori si separano con virgole. Lo ricevono solo le route registrate prima della chiamata, quindi chiamalo quando tutte le route esistono, per esempio nell'evento `ready`.\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('audit', function($, next) {\n\t\tconsole.log($.method, $.url);\n\t\tnext();\n\t}, 'routes');\n});\n```\n\n`NEWMIDDLEWARE(name)` senza funzione rimuove il middleware: viene eliminato dal registro e da ogni route che lo usa.\n\n## Middleware nelle azioni\n\nUn'azione creata con `NEWACTION()` ha una propria opzione `middleware`: un elenco di nomi separati da virgole, spazi o `|`. Qui la funzione riceve il `$` dell'azione (l'oggetto options dell'azione) e viene eseguita ogni volta che l'azione viene chiamata, da una route o dal codice. Un nome mancante viene segnalato come errore e saltato.\n\n```js\nNEWMIDDLEWARE('tenant', function($, next) {\n\tif ($.user && $.user.tenantid)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\nVedi [Azioni](../../guides/actions/) per le altre opzioni.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafiwz4R860f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/middleware/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Middleware","summary":"Spúšťaj pomenované funkcie pred routami, WebSocketmi a akciami pomocou NEWMIDDLEWARE().","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/middleware/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Middleware\n\n> Spúšťaj pomenované funkcie pred routami, WebSocketmi a akciami pomocou NEWMIDDLEWARE().\n\n## Vytvorenie middleware\n\nMiddleware zaregistruješ cez `NEWMIDDLEWARE(name, fn)` (`MIDDLEWARE()` je tá istá funkcia). Funkcia dostane controller `$` a callback `next`. Zavolaj `next()` na pokračovanie; ak namiesto toho na požiadavku odpovieš, zastavíš ju tam.\n\n```js\n// middleware/apikey.js\nexports.install = function() {\n\tNEWMIDDLEWARE('apikey', function($, next) {\n\t\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n\nSúbory v priečinku `middleware/` (a v `plugins/<name>/middleware/`) sa načítajú pri štarte ako controllery: spustí sa ich funkcia `install()`. Middleware môžeš zaregistrovať aj z akéhokoľvek iného súboru.\n\nNázov je to, čím sa naň routy odkazujú. V názve používaj iba písmená, číslice a `_`, pretože flag routy prijíma iba tieto znaky.\n\n## Použitie middleware v route\n\nPridaj názov s `#` do deklarácie routy. Viac middleware sa spustí v poradí, v akom ich napíšeš, a akcia sa spustí, keď posledný zavolá `next()`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/orders/ #apikey', orders);\n\tROUTE('POST /api/orders/ #apikey #ratelimit', create);\n\tROUTE('SOCKET /live/ #apikey', live);\n};\n\nfunction orders($) {\n\t$.json([]);\n}\n```\n\nPri HTTP routách sa middleware spustí po sparsovaní tela a po spustení tvojho delegátu `AUTH()`, takže `$.body`, `$.query`, `$.params` a `$.user` sú pripravené. Názov, ktorý nie je zaregistrovaný, sa preskočí; v route `SOCKET` sa preskočia aj middleware za ním. Flag `#name` funguje aj pre routy `API` a `SOCKET` (pozri [WebSockety](../../guides/websockets/)); pri sockete sa middleware spustí pred prijatím spojenia.\n\nMiddleware môže tiež pripraviť dáta pre akciu:\n\n```js\nNEWMIDDLEWARE('company', function($, next) {\n\t$.company = $.headers['x-company'] || 'default';\n\tnext();\n});\n```\n\n## Priradenie middleware existujúcim routám\n\nTretí argument `NEWMIDDLEWARE()` pridá middleware routám, ktoré už existujú: `'routes'` (alebo `'dynamic'`) pre všetky HTTP routy, `'websockets'` pre všetky socket routy. Viac hodnôt sa oddeľuje čiarkami. Dostanú ho iba routy zaregistrované pred volaním, takže ho volaj, keď existujú všetky routy, napríklad v udalosti `ready`.\n\n```js\nON('ready', function() {\n\tNEWMIDDLEWARE('audit', function($, next) {\n\t\tconsole.log($.method, $.url);\n\t\tnext();\n\t}, 'routes');\n});\n```\n\n`NEWMIDDLEWARE(name)` bez funkcie middleware odstráni: zmaže sa z registra a zo všetkých rout, ktoré ho používajú.\n\n## Middleware v akciách\n\nAkcia vytvorená cez `NEWACTION()` má vlastnú možnosť `middleware`: zoznam názvov oddelených čiarkami, medzerami alebo `|`. Tu funkcia dostane `$` akcie (objekt možností akcie) a spustí sa pri každom volaní akcie, z routy alebo z kódu. Chýbajúci názov sa nahlási ako chyba a preskočí sa.\n\n```js\nNEWMIDDLEWARE('tenant', function($, next) {\n\tif ($.user && $.user.tenantid)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\nĎalšie možnosti nájdeš v [Akcie](../../guides/actions/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafj3e4Wu61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/static-files/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Static files","summary":"Serve the public folder with minification, caching, compression and ranges, and merge files into one.","markdown":"---\ntitle: Static files\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/static-files/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Static files\n\n> Serve the public folder with minification, caching, compression and ranges, and merge files into one.\n\n## The public folder\n\nEvery request whose URL has an extension is a file request. Total.js looks for it in the `public/` folder (`CONF.$dirpublic` changes the folder): `/css/default.css` is `public/css/default.css`. URLs that start with `/_<plugin>/` read from the `public/` folder of that plugin, so `/_shop/logo.png` is `plugins/shop/public/logo.png`. With `CONF.$root`, the root path is removed before the file is looked up.\n\nOnly extensions in `CONF.$httpfiles` are served; other files return 404. The list contains the usual web types (images, fonts, `js`, `mjs`, `css`, `html`, `json`, `svg`, `pdf`, `mp4`, `webmanifest` and more). Add extensions in the config file:\n\n```\n$httpfiles : avif, glb\n```\n\nA `FILE` route (see [Routing](../../guides/routing/)) handles file requests before the `public/` folder; it can send any file, or call `$.resume()` to send the matching file from `public/` the normal way. File requests with `POST`, `PUT`, `PATCH` or `DELETE` are closed without an answer, and `HEAD` returns only the headers.\n\n## Minification and caching\n\nJavaScript, CSS and HTML files are minified when `CONF.$minifyjs`, `CONF.$minifycss` and `CONF.$minifyhtml` are on (the default). Files whose name contains `.min`, `-min` or `@min` are sent unchanged. HTML files are also translated with the language from your `LOCALIZE()` delegate (see [Localization](../../guides/localization/)).\n\nIn release mode, the minified result is written once to the `tmp/` folder and reused. Other files are streamed from disk. The first request reads the file date and size; later requests reuse them, so a browser that sends the same `If-Modified-Since` date gets `304 Not Modified`. Missing files are remembered too and the list of missing files is cleared every minute.\n\nStatic responses carry these headers:\n\n| Header | Value |\n| --- | --- |\n| `Expires` | One year ahead (`CONF.$httpexpire`, refreshed every hour) |\n| `Cache-Control` | `public, must-revalidate, max-age=` + `CONF.$httpmaxage` (60 seconds) |\n| `Last-Modified` | The date of the file |\n| `ETag` | `858` + `CONF.$httpetag` (the app version without dots by default) |\n\n`CONF.$httpcacheoffset` (for example `'1 minute'`) moves the `Last-Modified` date of static files forward by that time; see [Configuration](../../guides/configuration/).\n\n`.zip` and `.rar` files are sent with `Cache-Control: private, no-cache, no-store, max-age=0`. In debug mode, `.js`, `.css` and `.html` files are read and minified again on every request and sent with the same no-cache header, so you always see your last change.\n\nWhen you change a file in `public/` while the app runs in release mode, clear its cached state with `TOUCH()`:\n\n```js\nTOUCH('/css/default.css'); // one file, by its URL\nTOUCH();                   // every static file\n```\n\n## Compression and ranges\n\nWith `CONF.$httpcompress` (on by default) and a client that accepts gzip, text types are compressed: plain text, JavaScript, CSS, HTML, JSON, XML, SVG, Markdown and notebooks. Text types are sent with `charset=utf-8`. Images, video and `.webmanifest` (`application/manifest+json`) are sent as they are.\n\nA request with a `Range` header gets `206 Partial Content`. A range without an end returns at most `CONF.$httprangebuffer` kB (5120, so 5 MB), which is how video and audio players stream large files. A range that starts after the end of the file closes the connection; an end after the end of the file is cut to the last byte. A file that was empty when it was first served returns 404 on the next requests until it is touched with `TOUCH()` or the app restarts.\n\n## Merging files\n\n`MERGE(url, files...)` creates a virtual file made of several files. It returns the URL, which you put in a view or a page.\n\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/jquery.min.js', '/js/app.js', 'https://cdn.componentator.com/spa.min@20.js');\n};\n```\n\nA name without a slash is taken from `public/js/` (for `.js`) or `public/css/` (other types); a path that starts with `/` is relative to `public/`, `~` starts an absolute path, and `http://` or `https://` downloads the file. Each local file is minified by the `$minify*` setting of its type unless its name says it is already minified; downloaded files are added as they are. In release mode the result is built on the first request and saved to `tmp/`; in debug mode it is built on every request, with a comment before each part.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafj3e4Wu61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/static-files/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Statische Dateien","summary":"Liefere den öffentlichen Ordner mit Minifizierung, Caching, Kompression und Ranges aus und führe Dateien zu einer zusammen.","markdown":"---\ntitle: Statische Dateien\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/static-files/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Statische Dateien\n\n> Liefere den öffentlichen Ordner mit Minifizierung, Caching, Kompression und Ranges aus und führe Dateien zu einer zusammen.\n\n## Der öffentliche Ordner\n\nJede Anfrage, deren URL eine Endung hat, ist eine Dateianfrage. Total.js sucht die Datei im Ordner `public/` (`CONF.$dirpublic` ändert den Ordner): `/css/default.css` ist `public/css/default.css`. URLs, die mit `/_<plugin>/` beginnen, lesen aus dem Ordner `public/` dieses Plugins, daher ist `/_shop/logo.png` gleich `plugins/shop/public/logo.png`. Mit `CONF.$root` wird der Stammpfad entfernt, bevor die Datei gesucht wird.\n\nNur Endungen in `CONF.$httpfiles` werden ausgeliefert; andere Dateien liefern 404. Die Liste enthält die üblichen Web-Typen (Bilder, Schriften, `js`, `mjs`, `css`, `html`, `json`, `svg`, `pdf`, `mp4`, `webmanifest` und mehr). Füge Endungen in der Konfigurationsdatei hinzu:\n\n```\n$httpfiles : avif, glb\n```\n\nEine `FILE`-Route (siehe [Routing](../../guides/routing/)) behandelt Dateianfragen vor dem Ordner `public/`; sie kann jede beliebige Datei senden oder `$.resume()` aufrufen, um die passende Datei aus `public/` auf normalem Weg zu senden. Dateianfragen mit `POST`, `PUT`, `PATCH` oder `DELETE` werden ohne Antwort geschlossen, und `HEAD` liefert nur die Header.\n\n## Minifizierung und Caching\n\nJavaScript-, CSS- und HTML-Dateien werden minifiziert, wenn `CONF.$minifyjs`, `CONF.$minifycss` und `CONF.$minifyhtml` aktiv sind (Standard). Dateien, deren Name `.min`, `-min` oder `@min` enthält, werden unverändert gesendet. HTML-Dateien werden außerdem mit der Sprache aus deinem Delegate `LOCALIZE()` übersetzt (siehe [Lokalisierung](../../guides/localization/)).\n\nIm Release-Modus wird das minifizierte Ergebnis einmal in den Ordner `tmp/` geschrieben und wiederverwendet. Andere Dateien werden von der Festplatte gestreamt. Die erste Anfrage liest Datum und Größe der Datei; spätere Anfragen verwenden sie wieder, sodass ein Browser, der dasselbe `If-Modified-Since`-Datum sendet, `304 Not Modified` erhält. Fehlende Dateien werden ebenfalls gemerkt, und die Liste fehlender Dateien wird jede Minute geleert.\n\nStatische Antworten tragen diese Header:\n\n| Header | Wert |\n| --- | --- |\n| `Expires` | Ein Jahr in der Zukunft (`CONF.$httpexpire`, stündlich aktualisiert) |\n| `Cache-Control` | `public, must-revalidate, max-age=` + `CONF.$httpmaxage` (60 Sekunden) |\n| `Last-Modified` | Das Datum der Datei |\n| `ETag` | `858` + `CONF.$httpetag` (standardmäßig die Version der Anwendung ohne Punkte) |\n\n`CONF.$httpcacheoffset` (zum Beispiel `'1 minute'`) verschiebt das `Last-Modified`-Datum statischer Dateien um diese Zeit nach vorn; siehe [Konfiguration](../../guides/configuration/).\n\n`.zip`- und `.rar`-Dateien werden mit `Cache-Control: private, no-cache, no-store, max-age=0` gesendet. Im Debug-Modus werden `.js`-, `.css`- und `.html`-Dateien bei jeder Anfrage neu gelesen und minifiziert und mit demselben No-Cache-Header gesendet, sodass du immer deine letzte Änderung siehst.\n\nWenn du eine Datei in `public/` änderst, während die Anwendung im Release-Modus läuft, leere ihren zwischengespeicherten Zustand mit `TOUCH()`:\n\n```js\nTOUCH('/css/default.css'); // one file, by its URL\nTOUCH();                   // every static file\n```\n\n## Kompression und Ranges\n\nMit `CONF.$httpcompress` (standardmäßig aktiv) und einem Client, der gzip akzeptiert, werden Text-Typen komprimiert: einfacher Text, JavaScript, CSS, HTML, JSON, XML, SVG, Markdown und Notebooks. Text-Typen werden mit `charset=utf-8` gesendet. Bilder, Videos und `.webmanifest` (`application/manifest+json`) werden unverändert gesendet.\n\nEine Anfrage mit einem `Range`-Header erhält `206 Partial Content`. Ein Range ohne Ende liefert höchstens `CONF.$httprangebuffer` kB (5120, also 5 MB). So streamen Video- und Audioplayer große Dateien. Ein Range, der nach dem Ende der Datei beginnt, schließt die Verbindung; ein Ende nach dem Ende der Datei wird auf das letzte Byte gekürzt. Eine Datei, die beim ersten Ausliefern leer war, liefert bei den nächsten Anfragen 404, bis sie mit `TOUCH()` berührt wird oder die Anwendung neu startet.\n\n## Dateien zusammenführen\n\n`MERGE(url, files...)` erstellt eine virtuelle Datei aus mehreren Dateien. Es gibt die URL zurück, die du in eine View oder eine Seite einsetzt.\n\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/jquery.min.js', '/js/app.js', 'https://cdn.componentator.com/spa.min@20.js');\n};\n```\n\nEin Name ohne Schrägstrich wird aus `public/js/` (für `.js`) oder `public/css/` (andere Typen) genommen; ein Pfad, der mit `/` beginnt, ist relativ zu `public/`, `~` leitet einen absoluten Pfad ein, und `http://` oder `https://` lädt die Datei herunter. Jede lokale Datei wird gemäß der Einstellung `$minify*` ihres Typs minifiziert, außer ihr Name zeigt an, dass sie bereits minifiziert ist; heruntergeladene Dateien werden unverändert hinzugefügt. Im Release-Modus wird das Ergebnis bei der ersten Anfrage erzeugt und in `tmp/` gespeichert; im Debug-Modus wird es bei jeder Anfrage erzeugt, mit einem Kommentar vor jedem Teil.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafj3e4Wu61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/static-files/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Archivos estáticos","summary":"Sirve la carpeta pública con minificación, caché, compresión y rangos, y combina archivos en uno.","markdown":"---\ntitle: \"Archivos estáticos\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/static-files/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Archivos estáticos\n\n> Sirve la carpeta pública con minificación, caché, compresión y rangos, y combina archivos en uno.\n\n## La carpeta pública\n\nCada petición cuya URL tiene una extensión es una petición de archivo. Total.js la busca en la carpeta `public/` (`CONF.$dirpublic` cambia la carpeta): `/css/default.css` es `public/css/default.css`. Las URLs que empiezan por `/_<plugin>/` leen de la carpeta `public/` de ese plugin, así que `/_shop/logo.png` es `plugins/shop/public/logo.png`. Con `CONF.$root`, la ruta raíz se elimina antes de buscar el archivo.\n\nSolo se sirven las extensiones de `CONF.$httpfiles`; los demás archivos devuelven 404. La lista contiene los tipos web habituales (imágenes, fuentes, `js`, `mjs`, `css`, `html`, `json`, `svg`, `pdf`, `mp4`, `webmanifest` y más). Añade extensiones en el archivo de configuración:\n\n```\n$httpfiles : avif, glb\n```\n\nUna ruta `FILE` (consulta [Enrutamiento](../../guides/routing/)) gestiona las peticiones de archivos antes que la carpeta `public/`; puede enviar cualquier archivo, o llamar a `$.resume()` para enviar el archivo correspondiente de `public/` de la forma normal. Las peticiones de archivos con `POST`, `PUT`, `PATCH` o `DELETE` se cierran sin respuesta, y `HEAD` devuelve solo las cabeceras.\n\n## Minificación y caché\n\nLos archivos JavaScript, CSS y HTML se minifican cuando `CONF.$minifyjs`, `CONF.$minifycss` y `CONF.$minifyhtml` están activados (por defecto). Los archivos cuyo nombre contiene `.min`, `-min` o `@min` se envían sin cambios. Los archivos HTML también se traducen con el idioma de tu delegado `LOCALIZE()` (consulta [Localización](../../guides/localization/)).\n\nEn modo release, el resultado minificado se escribe una vez en la carpeta `tmp/` y se reutiliza. Los demás archivos se envían en streaming desde el disco. La primera petición lee la fecha y el tamaño del archivo; las peticiones posteriores los reutilizan, así que un navegador que envía la misma fecha `If-Modified-Since` recibe `304 Not Modified`. Los archivos que faltan también se recuerdan, y la lista de archivos que faltan se vacía cada minuto.\n\nLas respuestas estáticas llevan estas cabeceras:\n\n| Cabecera | Valor |\n| --- | --- |\n| `Expires` | Un año en adelante (`CONF.$httpexpire`, actualizado cada hora) |\n| `Cache-Control` | `public, must-revalidate, max-age=` + `CONF.$httpmaxage` (60 segundos) |\n| `Last-Modified` | La fecha del archivo |\n| `ETag` | `858` + `CONF.$httpetag` (la versión de la aplicación sin puntos por defecto) |\n\n`CONF.$httpcacheoffset` (por ejemplo `'1 minute'`) adelanta la fecha `Last-Modified` de los archivos estáticos ese tiempo; consulta [Configuración](../../guides/configuration/).\n\nLos archivos `.zip` y `.rar` se envían con `Cache-Control: private, no-cache, no-store, max-age=0`. En modo debug, los archivos `.js`, `.css` y `.html` se leen y se minifican de nuevo en cada petición y se envían con la misma cabecera no-cache, así que siempre ves tu último cambio.\n\nCuando cambias un archivo de `public/` mientras la aplicación se ejecuta en modo release, limpia su estado en caché con `TOUCH()`:\n\n```js\nTOUCH('/css/default.css'); // one file, by its URL\nTOUCH();                   // every static file\n```\n\n## Compresión y rangos\n\nCon `CONF.$httpcompress` (activado por defecto) y un cliente que acepta gzip, los tipos de texto se comprimen: texto plano, JavaScript, CSS, HTML, JSON, XML, SVG, Markdown y notebooks. Los tipos de texto se envían con `charset=utf-8`. Las imágenes, el vídeo y `.webmanifest` (`application/manifest+json`) se envían tal cual.\n\nUna petición con una cabecera `Range` recibe `206 Partial Content`. Un rango sin final devuelve como máximo `CONF.$httprangebuffer` kB (5120, es decir 5 MB), que es como los reproductores de vídeo y audio transmiten archivos grandes. Un rango que empieza después del final del archivo cierra la conexión; un final posterior al final del archivo se recorta al último byte. Un archivo que estaba vacío la primera vez que se sirvió devuelve 404 en las siguientes peticiones hasta que se toca con `TOUCH()` o se reinicia la aplicación.\n\n## Combinar archivos\n\n`MERGE(url, files...)` crea un archivo virtual formado por varios archivos. Devuelve la URL, que pones en una vista o en una página.\n\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/jquery.min.js', '/js/app.js', 'https://cdn.componentator.com/spa.min@20.js');\n};\n```\n\nUn nombre sin barra se toma de `public/js/` (para `.js`) o de `public/css/` (otros tipos); una ruta que empieza por `/` es relativa a `public/`, `~` inicia una ruta absoluta, y `http://` o `https://` descarga el archivo. Cada archivo local se minifica según el ajuste `$minify*` de su tipo, salvo que su nombre indique que ya está minificado; los archivos descargados se añaden tal cual. En modo release el resultado se construye en la primera petición y se guarda en `tmp/`; en modo debug se construye en cada petición, con un comentario antes de cada parte.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafj3e4Wu61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/static-files/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Fichiers statiques","summary":"Sers le dossier public avec minification, cache, compression et plages, et fusionne des fichiers en un seul.","markdown":"---\ntitle: Fichiers statiques\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/static-files/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Fichiers statiques\n\n> Sers le dossier public avec minification, cache, compression et plages, et fusionne des fichiers en un seul.\n\n## Le dossier public\n\nChaque requête dont l'URL a une extension est une requête de fichier. Total.js le cherche dans le dossier `public/` (`CONF.$dirpublic` change le dossier) : `/css/default.css` correspond à `public/css/default.css`. Les URL qui commencent par `/_<plugin>/` lisent depuis le dossier `public/` de ce plugin : `/_shop/logo.png` correspond donc à `plugins/shop/public/logo.png`. Avec `CONF.$root`, le chemin racine est retiré avant la recherche du fichier.\n\nSeules les extensions de `CONF.$httpfiles` sont servies ; les autres fichiers renvoient 404. La liste contient les types web habituels (images, polices, `js`, `mjs`, `css`, `html`, `json`, `svg`, `pdf`, `mp4`, `webmanifest` et d'autres). Ajoute des extensions dans le fichier de configuration :\n\n```\n$httpfiles : avif, glb\n```\n\nUne route `FILE` (voir [Routage](../../guides/routing/)) traite les requêtes de fichiers avant le dossier `public/` ; elle peut envoyer n'importe quel fichier, ou appeler `$.resume()` pour envoyer normalement le fichier correspondant de `public/`. Les requêtes de fichiers avec `POST`, `PUT`, `PATCH` ou `DELETE` sont fermées sans réponse, et `HEAD` ne renvoie que les en-têtes.\n\n## Minification et cache\n\nLes fichiers JavaScript, CSS et HTML sont minifiés lorsque `CONF.$minifyjs`, `CONF.$minifycss` et `CONF.$minifyhtml` sont activés (par défaut). Les fichiers dont le nom contient `.min`, `-min` ou `@min` sont envoyés sans modification. Les fichiers HTML sont aussi traduits avec la langue de ton délégué `LOCALIZE()` (voir [Localisation](../../guides/localization/)).\n\nEn mode release, le résultat minifié est écrit une fois dans le dossier `tmp/` et réutilisé. Les autres fichiers sont lus en streaming depuis le disque. La première requête lit la date et la taille du fichier ; les requêtes suivantes les réutilisent, si bien qu'un navigateur qui envoie la même date `If-Modified-Since` reçoit `304 Not Modified`. Les fichiers manquants sont mémorisés aussi, et la liste des fichiers manquants est vidée chaque minute.\n\nLes réponses statiques portent ces en-têtes :\n\n| En-tête | Valeur |\n| --- | --- |\n| `Expires` | Un an plus tard (`CONF.$httpexpire`, rafraîchi chaque heure) |\n| `Cache-Control` | `public, must-revalidate, max-age=` + `CONF.$httpmaxage` (60 secondes) |\n| `Last-Modified` | La date du fichier |\n| `ETag` | `858` + `CONF.$httpetag` (la version de l'application sans points par défaut) |\n\n`CONF.$httpcacheoffset` (par exemple `'1 minute'`) avance la date `Last-Modified` des fichiers statiques de cette durée ; voir [Configuration](../../guides/configuration/).\n\nLes fichiers `.zip` et `.rar` sont envoyés avec `Cache-Control: private, no-cache, no-store, max-age=0`. En mode debug, les fichiers `.js`, `.css` et `.html` sont relus et reminifiés à chaque requête et envoyés avec le même en-tête no-cache : tu vois donc toujours ta dernière modification.\n\nQuand tu modifies un fichier de `public/` pendant que l'application tourne en mode release, efface son état en cache avec `TOUCH()` :\n\n```js\nTOUCH('/css/default.css'); // one file, by its URL\nTOUCH();                   // every static file\n```\n\n## Compression et plages\n\nAvec `CONF.$httpcompress` (activé par défaut) et un client qui accepte gzip, les types texte sont compressés : texte brut, JavaScript, CSS, HTML, JSON, XML, SVG, Markdown et notebooks. Les types texte sont envoyés avec `charset=utf-8`. Les images, les vidéos et `.webmanifest` (`application/manifest+json`) sont envoyés tels quels.\n\nUne requête avec un en-tête `Range` reçoit `206 Partial Content`. Une plage sans fin renvoie au plus `CONF.$httprangebuffer` ko (5120, soit 5 Mo) : c'est ainsi que les lecteurs vidéo et audio lisent les gros fichiers en streaming. Une plage qui commence après la fin du fichier ferme la connexion ; une fin située après la fin du fichier est ramenée au dernier octet. Un fichier qui était vide lors de son premier envoi renvoie 404 aux requêtes suivantes jusqu'à ce qu'il soit touché avec `TOUCH()` ou que l'application redémarre.\n\n## Fusionner des fichiers\n\n`MERGE(url, files...)` crée un fichier virtuel composé de plusieurs fichiers. Il renvoie l'URL, que tu places dans une vue ou une page.\n\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/jquery.min.js', '/js/app.js', 'https://cdn.componentator.com/spa.min@20.js');\n};\n```\n\nUn nom sans barre oblique est pris dans `public/js/` (pour `.js`) ou `public/css/` (autres types) ; un chemin qui commence par `/` est relatif à `public/`, `~` commence un chemin absolu, et `http://` ou `https://` télécharge le fichier. Chaque fichier local est minifié selon le réglage `$minify*` de son type, sauf si son nom indique qu'il est déjà minifié ; les fichiers téléchargés sont ajoutés tels quels. En mode release, le résultat est construit à la première requête et enregistré dans `tmp/` ; en mode debug, il est construit à chaque requête, avec un commentaire avant chaque partie.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafj3e4Wu61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/static-files/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"File statici","summary":"Servi la cartella public con minificazione, caching, compressione e range, e unisci più file in uno.","markdown":"---\ntitle: File statici\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/static-files/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# File statici\n\n> Servi la cartella public con minificazione, caching, compressione e range, e unisci più file in uno.\n\n## La cartella public\n\nOgni richiesta il cui URL ha un'estensione è una richiesta di file. Total.js lo cerca nella cartella `public/` (`CONF.$dirpublic` cambia la cartella): `/css/default.css` è `public/css/default.css`. Gli URL che iniziano con `/_<plugin>/` leggono dalla cartella `public/` di quel plugin, quindi `/_shop/logo.png` è `plugins/shop/public/logo.png`. Con `CONF.$root`, il percorso radice viene rimosso prima di cercare il file.\n\nVengono servite solo le estensioni presenti in `CONF.$httpfiles`; gli altri file restituiscono 404. L'elenco contiene i consueti tipi web (immagini, font, `js`, `mjs`, `css`, `html`, `json`, `svg`, `pdf`, `mp4`, `webmanifest` e altri). Aggiungi estensioni nel file di configurazione:\n\n```\n$httpfiles : avif, glb\n```\n\nUna route `FILE` (vedi [Routing](../../guides/routing/)) gestisce le richieste di file prima della cartella `public/`; può inviare qualsiasi file, oppure chiamare `$.resume()` per inviare nel modo normale il file corrispondente da `public/`. Le richieste di file con `POST`, `PUT`, `PATCH` o `DELETE` vengono chiuse senza risposta, e `HEAD` restituisce solo gli header.\n\n## Minificazione e caching\n\nI file JavaScript, CSS e HTML vengono minificati quando `CONF.$minifyjs`, `CONF.$minifycss` e `CONF.$minifyhtml` sono attivi (il valore predefinito). I file il cui nome contiene `.min`, `-min` o `@min` vengono inviati senza modifiche. I file HTML vengono anche tradotti con la lingua del tuo delegate `LOCALIZE()` (vedi [Localizzazione](../../guides/localization/)).\n\nIn modalità release, il risultato minificato viene scritto una volta nella cartella `tmp/` e riutilizzato. Gli altri file vengono inviati in streaming dal disco. La prima richiesta legge la data e la dimensione del file; le richieste successive le riutilizzano, quindi un browser che invia la stessa data `If-Modified-Since` riceve `304 Not Modified`. Anche i file mancanti vengono ricordati, e l'elenco dei file mancanti viene svuotato ogni minuto.\n\nLe risposte statiche includono questi header:\n\n| Header | Valore |\n| --- | --- |\n| `Expires` | Un anno avanti (`CONF.$httpexpire`, aggiornato ogni ora) |\n| `Cache-Control` | `public, must-revalidate, max-age=` + `CONF.$httpmaxage` (60 secondi) |\n| `Last-Modified` | La data del file |\n| `ETag` | `858` + `CONF.$httpetag` (per impostazione predefinita la versione dell'app senza punti) |\n\n`CONF.$httpcacheoffset` (per esempio `'1 minute'`) sposta in avanti di quel tempo la data `Last-Modified` dei file statici; vedi [Configurazione](../../guides/configuration/).\n\nI file `.zip` e `.rar` vengono inviati con `Cache-Control: private, no-cache, no-store, max-age=0`. In modalità debug, i file `.js`, `.css` e `.html` vengono riletti e minificati a ogni richiesta e inviati con lo stesso header no-cache, così vedi sempre la tua ultima modifica.\n\nQuando modifichi un file in `public/` mentre l'app gira in modalità release, svuota il suo stato in cache con `TOUCH()`:\n\n```js\nTOUCH('/css/default.css'); // one file, by its URL\nTOUCH();                   // every static file\n```\n\n## Compressione e range\n\nCon `CONF.$httpcompress` (attivo per impostazione predefinita) e un client che accetta gzip, i tipi testuali vengono compressi: testo semplice, JavaScript, CSS, HTML, JSON, XML, SVG, Markdown e notebook. I tipi testuali vengono inviati con `charset=utf-8`. Immagini, video e `.webmanifest` (`application/manifest+json`) vengono inviati così come sono.\n\nUna richiesta con un header `Range` riceve `206 Partial Content`. Un range senza fine restituisce al massimo `CONF.$httprangebuffer` kB (5120, cioè 5 MB), ed è così che i lettori video e audio riproducono in streaming i file grandi. Un range che inizia dopo la fine del file chiude la connessione; una fine oltre la fine del file viene troncata all'ultimo byte. Un file che era vuoto quando è stato servito la prima volta restituisce 404 alle richieste successive finché non viene aggiornato con `TOUCH()` o l'app non viene riavviata.\n\n## Unire file\n\n`MERGE(url, files...)` crea un file virtuale composto da più file. Restituisce l'URL, che inserisci in una vista o in una pagina.\n\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/jquery.min.js', '/js/app.js', 'https://cdn.componentator.com/spa.min@20.js');\n};\n```\n\nUn nome senza barra viene preso da `public/js/` (per `.js`) o da `public/css/` (altri tipi); un percorso che inizia con `/` è relativo a `public/`, `~` inizia un percorso assoluto, e `http://` o `https://` scarica il file. Ogni file locale viene minificato in base all'impostazione `$minify*` del suo tipo, a meno che il suo nome non indichi che è già minificato; i file scaricati vengono aggiunti così come sono. In modalità release il risultato viene costruito alla prima richiesta e salvato in `tmp/`; in modalità debug viene costruito a ogni richiesta, con un commento prima di ogni parte.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"Jafj3e4Wu61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/static-files/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Statické súbory","summary":"Obsluhuj priečinok public s minifikáciou, cachovaním, kompresiou a rozsahmi a zlučuj súbory do jedného.","markdown":"---\ntitle: \"Statické súbory\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/static-files/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Statické súbory\n\n> Obsluhuj priečinok public s minifikáciou, cachovaním, kompresiou a rozsahmi a zlučuj súbory do jedného.\n\n## Priečinok public\n\nKaždá požiadavka, ktorej URL má príponu, je požiadavka na súbor. Total.js ho hľadá v priečinku `public/` (`CONF.$dirpublic` priečinok mení): `/css/default.css` je `public/css/default.css`. URL, ktoré začínajú `/_<plugin>/`, čítajú z priečinka `public/` daného pluginu, takže `/_shop/logo.png` je `plugins/shop/public/logo.png`. S `CONF.$root` sa koreňová cesta pred vyhľadaním súboru odstráni.\n\nObsluhujú sa iba prípony v `CONF.$httpfiles`; ostatné súbory vrátia 404. Zoznam obsahuje bežné webové typy (obrázky, fonty, `js`, `mjs`, `css`, `html`, `json`, `svg`, `pdf`, `mp4`, `webmanifest` a ďalšie). Prípony pridáš v konfiguračnom súbore:\n\n```\n$httpfiles : avif, glb\n```\n\nRouta `FILE` (pozri [Routing](../../guides/routing/)) spracuje požiadavky na súbory pred priečinkom `public/`; môže poslať akýkoľvek súbor alebo zavolať `$.resume()`, aby sa zodpovedajúci súbor z `public/` poslal bežným spôsobom. Požiadavky na súbory s `POST`, `PUT`, `PATCH` alebo `DELETE` sa zatvoria bez odpovede a `HEAD` vráti iba hlavičky.\n\n## Minifikácia a cachovanie\n\nSúbory JavaScript, CSS a HTML sa minifikujú, keď sú zapnuté `CONF.$minifyjs`, `CONF.$minifycss` a `CONF.$minifyhtml` (predvolene). Súbory, ktorých názov obsahuje `.min`, `-min` alebo `@min`, sa posielajú bez zmeny. HTML súbory sa tiež prekladajú do jazyka z tvojho delegátu `LOCALIZE()` (pozri [Lokalizácia](../../guides/localization/)).\n\nV release režime sa minifikovaný výsledok raz zapíše do priečinka `tmp/` a opakovane sa používa. Ostatné súbory sa streamujú z disku. Prvá požiadavka prečíta dátum a veľkosť súboru; neskoršie ich použijú znova, takže prehliadač, ktorý pošle rovnaký dátum `If-Modified-Since`, dostane `304 Not Modified`. Zapamätajú sa aj chýbajúce súbory a zoznam chýbajúcich súborov sa vyčistí každú minútu.\n\nStatické odpovede nesú tieto hlavičky:\n\n| Hlavička | Hodnota |\n| --- | --- |\n| `Expires` | O rok dopredu (`CONF.$httpexpire`, obnovuje sa každú hodinu) |\n| `Cache-Control` | `public, must-revalidate, max-age=` + `CONF.$httpmaxage` (60 sekúnd) |\n| `Last-Modified` | Dátum súboru |\n| `ETag` | `858` + `CONF.$httpetag` (predvolene verzia aplikácie bez bodiek) |\n\n`CONF.$httpcacheoffset` (napríklad `'1 minute'`) posunie dátum `Last-Modified` statických súborov o tento čas dopredu; pozri [Konfigurácia](../../guides/configuration/).\n\nSúbory `.zip` a `.rar` sa posielajú s `Cache-Control: private, no-cache, no-store, max-age=0`. V debug režime sa súbory `.js`, `.css` a `.html` pri každej požiadavke čítajú a minifikujú znova a posielajú sa s rovnakou no-cache hlavičkou, takže vždy vidíš svoju poslednú zmenu.\n\nKeď zmeníš súbor v `public/`, zatiaľ čo aplikácia beží v release režime, vyčisti jeho cachovaný stav cez `TOUCH()`:\n\n```js\nTOUCH('/css/default.css'); // one file, by its URL\nTOUCH();                   // every static file\n```\n\n## Kompresia a rozsahy\n\nS `CONF.$httpcompress` (predvolene zapnuté) a klientom, ktorý prijíma gzip, sa textové typy komprimujú: čistý text, JavaScript, CSS, HTML, JSON, XML, SVG, Markdown a notebooky. Textové typy sa posielajú s `charset=utf-8`. Obrázky, video a `.webmanifest` (`application/manifest+json`) sa posielajú tak, ako sú.\n\nPožiadavka s hlavičkou `Range` dostane `206 Partial Content`. Rozsah bez konca vráti najviac `CONF.$httprangebuffer` kB (5120, teda 5 MB), čo je spôsob, akým video a audio prehrávače streamujú veľké súbory. Rozsah, ktorý začína za koncom súboru, zatvorí spojenie; koniec za koncom súboru sa skráti na posledný bajt. Súbor, ktorý bol prázdny pri prvom obslúžení, vracia pri ďalších požiadavkách 404, kým sa neaktualizuje cez `TOUCH()` alebo kým sa aplikácia nereštartuje.\n\n## Zlučovanie súborov\n\n`MERGE(url, files...)` vytvorí virtuálny súbor zložený z viacerých súborov. Vráti URL, ktorú vložíš do view alebo stránky.\n\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/jquery.min.js', '/js/app.js', 'https://cdn.componentator.com/spa.min@20.js');\n};\n```\n\nNázov bez lomky sa berie z `public/js/` (pre `.js`) alebo `public/css/` (ostatné typy); cesta, ktorá začína `/`, je relatívna k `public/`, `~` začína absolútnu cestu a `http://` alebo `https://` súbor stiahne. Každý lokálny súbor sa minifikuje podľa nastavenia `$minify*` svojho typu, ak jeho názov nehovorí, že už je minifikovaný; stiahnuté súbory sa pridajú tak, ako sú. V release režime sa výsledok zostaví pri prvej požiadavke a uloží do `tmp/`; v debug režime sa zostavuje pri každej požiadavke s komentárom pred každou časťou.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"JaqmBm22c61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/websockets/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"WebSockets","summary":"Real-time connections with SOCKET routes, the WebSocket object and its clients, compression, ping and the WebSocket client.","markdown":"---\ntitle: WebSockets\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/websockets/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# WebSockets\n\n> Real-time connections with SOCKET routes, the WebSocket object and its clients, compression, ping and the WebSocket client.\n\nA WebSocket route keeps a connection open between the browser (or another server) and your application, so both sides can send messages at any time. Total.js handles the handshake, the frames, compression, ping and JSON for you.\n\n## A WebSocket route\n\nDeclare it with the `SOCKET` method. The action runs with a **WebSocket** object as `this` (and as the first argument). You attach events to it; each connected browser arrives as a **client**.\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// message is already parsed from JSON\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client, code, reason) {\n\t\tself.send({ type: 'left', id: client.id });\n\t});\n}\n```\n\nIn the browser:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/chat/');\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n};\nws.onopen = function() {\n\tws.send(JSON.stringify({ body: 'Hello' }));\n};\n```\n\nThe route syntax is the same as for HTTP routes (see [Routing](../routing/)): dynamic parameters `{name}`, a wildcard `*`, the flags `@text`, `@binary` and `@csrf`, middleware with `#`, and `+SOCKET` / `-SOCKET` for authorized and unauthorized users. The maximum size of one message is `CONF.$wsmaxsize` (256 kB). Change it per route with a third argument in bytes, or with `<1MB` in the URL:\n\n```js\nROUTE('SOCKET /upload/ <5MB', upload);\nROUTE('SOCKET /feed/', feed, 1024 * 1024);\n```\n\n## One WebSocket object per URL\n\nThe action does not run for each client. It runs **once per URL**, when the first client connects; later clients join the same WebSocket object. With a dynamic route, every distinct URL gets its own object, so `/room/sport/` and `/room/music/` are two separate groups of clients:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\t// self.params.name === 'sport'\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: self.params.name, body: message.body });\n\t});\n}\n```\n\n`self.url`, `self.params`, `self.online` (the number of connected clients) and `self.connections` (an object `{ id: client }`) describe the group.\n\n## Message formats\n\nA route reads and writes JSON by default: an incoming message is parsed (messages that are not valid JSON are ignored), and `send()` serializes objects with `JSON.stringify()`. Two flags change it:\n\n| Flag | `message` event receives | `send()` writes |\n| --- | --- | --- |\n| (none) | a parsed object | JSON |\n| `@text` | a string | JSON, or the string as it is with `client.send(text, true)` |\n\n\n```js\nROUTE('SOCKET /terminal/ @text', function() {\n\tthis.on('message', function(client, text) {\n\t\tclient.send(text.toUpperCase(), true);\n\t});\n});\n```\n\nThe `message` event also gets the size of the message in bytes as its third argument.\n\n## Sending messages\n\n`client.send(message)` writes to one client. `websocket.send(message, [comparer])` writes to every client of the group; the optional `comparer(client, message)` returns `true` for the clients that should get it:\n\n```js\nself.send({ type: 'notify' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n`websocket.find(fn)` returns the first client for which `fn(client)` returns `true`:\n\n```js\nvar target = self.find(function(client) {\n\treturn client.user && client.user.id === message.to;\n});\ntarget && target.send({ type: 'private', body: message.body });\n```\n\n## Notifying clients from outside the route\n\nAn action or an HTTP route often changes data that connected clients have to know about. The WebSocket object is created inside the `SOCKET` route, so keep a reference to it in the global `MAIN` object and use that reference from any other file.\n\nCreate `controllers/live.js`:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /live/', live);\n\tROUTE('POST /api/products/ --> products_create');\n\tROUTE('POST /api/maintenance/', maintenance);\n};\n\nfunction live() {\n\tMAIN.live = this;\n}\n\nfunction maintenance($) {\n\tMAIN.live && MAIN.live.send({ type: 'maintenance', message: $.body.message });\n\t$.success();\n}\n```\n\nCreate `actions/products.js` (see [Actions](../actions/)):\n\n```js\nvar products = [];\n\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\n\t\tvar product = { id: UID(), name: model.name };\n\t\tproducts.push(product);\n\n\t\tMAIN.live && MAIN.live.send({ type: 'product_created', product: product });\n\n\t\t$.callback(product);\n\t}\n});\n```\n\nConnect from the browser:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/live/');\n\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n\tif (msg.type === 'product_created')\n\t\tconsole.log('New product:', msg.product.name);\n};\n```\n\nA request to `POST /api/products/` with the body `{\"name\":\"Keyboard\"}` now saves the product, sends the `product_created` message to every connected client and answers the request. The route `POST /api/maintenance/` does the same from a plain route function. A request that fails the validation of the action sends no message.\n\nThe route action runs when the first client connects, so `MAIN.live` is `undefined` until then. The check `MAIN.live &&` covers that moment: the action or the route answers normally and no message is sent. After the last client leaves, `MAIN.live` stays set and `send()` reaches nobody. Messages are not stored, so a client that connects later receives only the messages sent after it connected.\n\nWhen the route uses `autodestroy()`, clear the reference in its callback. The next client that connects runs the route action again and sets a new reference:\n\n```js\nfunction live() {\n\tvar self = this;\n\tMAIN.live = self;\n\tself.autodestroy(function() {\n\t\tMAIN.live = null;\n\t});\n}\n```\n\nA route with a dynamic URL has one WebSocket object per URL, so keep one reference per URL:\n\n```js\nMAIN.rooms = {};\n\nexports.install = function() {\n\tROUTE('SOCKET /rooms/{name}/', room);\n\tROUTE('POST /api/rooms/{name}/', notify);\n};\n\nfunction room() {\n\tMAIN.rooms[this.params.name] = this;\n}\n\nfunction notify($) {\n\tvar room = MAIN.rooms[$.params.name];\n\troom && room.send({ type: 'notice', message: $.body.message });\n\t$.success();\n}\n```\n\n## The client\n\nEach client is a WebSocket controller with the data of the HTTP upgrade request: `client.id`, `client.ip`, `client.user`, `client.query`, `client.params`, `client.headers`, `client.url`, `client.ua`, `client.mobile`, `client.robot`, `client.language` and `client.latency`. `client.cookie(name)` reads a cookie. Store your own data on the object if you need it later:\n\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n## Authorization, CSRF and middleware\n\nBefore a client is accepted, the framework calls your authorization delegate (see [Authorization](../authorization/)). The user it returns is in `client.user`. A route declared with `+SOCKET` accepts only authorized users and `-SOCKET` only anonymous ones; a client that does not match any route gets the handshake and is then closed with the code `4001`, so the browser sees a normal `close` event with that code and can, for example, ask the user to sign in:\n\n```js\nROUTE('+SOCKET /notifications/', notifications);\n```\n\nThe `@csrf` flag requires a valid CSRF token in the `x-csrf-token` header or in the `?csrf=` query argument (browsers cannot set headers on a WebSocket, so use the query). Middleware declared with `#name` runs before the connection is upgraded (see [Middleware](../middleware/)). Requests from IP addresses in `CONF.$blacklist` are refused.\n\n## Closing and cleaning up\n\n`client.close([code], [message])` closes one client, `websocket.close([code], [message])` closes all of them. The default code is `1000`. A message larger than the route size closes the client with `1009`; invalid compressed data with `1003`.\n\n`websocket.destroy()` closes all clients, emits `destroy` and removes the object; the next client that connects runs the action again. `websocket.autodestroy([callback])` does it for you 5 seconds after the last client leaves, which is the usual choice for dynamic rooms:\n\n```js\nfunction room() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tself.send({ type: 'tick' });\n\t}, 1000);\n\tself.autodestroy(function() {\n\t\tclearInterval(timer);\n\t});\n}\n```\n\nThe global event `websocket_end` is emitted when any client disconnects: `ON('websocket_end', function(websocket, client) {})`.\n\n## Compression and encoding\n\nWhen the browser offers `permessage-deflate` and `CONF.$wscompress` is `true` (default), messages are compressed in both directions, text and binary (`@binary`) messages alike. An error of the compression reaches the `error` event of the WebSocket object. Two more options transform every message:\n\n- `CONF.$wsencodedecode = true` sends messages through `encodeURIComponent()` and decodes incoming messages with `decodeURIComponent()`.\n- `websocket.encrypt()` encrypts outgoing and decrypts incoming messages of the group with `CONF.secret_encryption`. Both sides must use the same key.\n\n## Ping and latency\n\nThree times a minute (15, 30 and 60 seconds into each minute) the framework pings all clients of all WebSocket routes and measures `client.latency` from the pong. Before each ping it checks the clients: a client that has not answered the previous ping, or whose latency is higher than `CONF.$wsmaxlatency` (2000 ms), is closed. This removes dead connections without your code.\n\n`client.ping()` pings one client yourself.\n\n## Removing a route\n\n`ROUTE()` returns the route. `route.remove()` removes it and destroys all its WebSocket objects, so every client is disconnected:\n\n```js\nvar route = ROUTE('SOCKET /live/', live);\n\n// later\nroute.remove();\n```\n\n## WebSocket client\n\n`WEBSOCKETCLIENT([callback])` connects your application to another WebSocket server. Set the options and the events, then call `connect()`:\n\n```js\nvar client = WEBSOCKETCLIENT();\n\nclient.options.reconnect = 5000;\nclient.headers['x-token'] = CONF.token;\n\nclient.on('open', function() {\n\tclient.send({ type: 'hello' });\n});\n\nclient.on('message', function(message) {\n\tconsole.log(message);\n});\n\nclient.on('close', function(code, reason) {\n\tconsole.log('closed', code, reason);\n});\n\nclient.connect('wss://example.com/live/');\n```\n\nOptions of `client.options`:\n\n| Option | Default | Description |\n| --- | --- | --- |\n| `type` | `'json'` | `'json'`, `'text'` or `'binary'` |\n| `compress` | `true` | Offer `permessage-deflate` to the server |\n| `reconnect` | `3000` | Delay in ms before a reconnection after the connection closes; `0` disables it |\n| `reconnectserver` | | `true` also reconnects when the connection cannot be opened |\n| `masking` | `false` | Mask outgoing frames (required by servers that follow the RFC strictly) |\n| `encodedecode` | `false` | Encode/decode messages with `encodeURIComponent()` |\n| `encrypt` | | A key: messages are encrypted and decrypted with it |\n| `size` | `0` | Max. size in bytes of a decompressed message (`0` no limit) |\n| `rejectunauthorized` | `false` | Reject invalid TLS certificates |\n| `timeout` | `30000` | TCP keep-alive delay in ms for the socket (`0` disables it) |\n\n`key`, `cert` and `dhparam` are passed to the TLS connection. `client.close([code], [message])` closes the connection and stops reconnecting; `client.close(code, true)` closes it and keeps the reconnection. `client.ping([timeout])` sends a ping; when the pong does not arrive in `timeout` ms (3000), the client emits `error` with a `Timeout` error, closes the connection and reconnects. `client.latency` holds the last measured time in ms.\n\n## Configuration\n\n| Key | Default | Description |\n| --- | --- | --- |\n| `$wsmaxsize` | `256` | Max. size of a message in kB |\n| `$wscompress` | `true` | Allow `permessage-deflate` compression |\n| `$wsencodedecode` | `false` | Encode/decode all messages with URI encoding |\n| `$wsmaxlatency` | `2000` | Max. latency in ms before a client is closed by the ping check |\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JaqmBm22c61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/websockets/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"WebSockets","summary":"Echtzeitverbindungen mit SOCKET-Routen, das WebSocket-Objekt und seine Clients, Komprimierung, Ping und der WebSocket-Client.","markdown":"---\ntitle: WebSockets\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/websockets/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# WebSockets\n\n> Echtzeitverbindungen mit SOCKET-Routen, das WebSocket-Objekt und seine Clients, Komprimierung, Ping und der WebSocket-Client.\n\nEine WebSocket-Route hält eine Verbindung zwischen dem Browser (oder einem anderen Server) und deiner Anwendung offen, sodass beide Seiten jederzeit Nachrichten senden können. Total.js kümmert sich für dich um den Handshake, die Frames, die Komprimierung, den Ping und JSON.\n\n## Eine WebSocket-Route\n\nDeklariere sie mit der Methode `SOCKET`. Die Aktion läuft mit einem **WebSocket**-Objekt als `this` (und als erstem Argument). Du hängst Events daran; jeder verbundene Browser kommt als **Client** an.\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// message is already parsed from JSON\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client, code, reason) {\n\t\tself.send({ type: 'left', id: client.id });\n\t});\n}\n```\n\nIm Browser:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/chat/');\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n};\nws.onopen = function() {\n\tws.send(JSON.stringify({ body: 'Hello' }));\n};\n```\n\nDie Routensyntax ist dieselbe wie bei HTTP-Routen (siehe [Routing](../routing/)): dynamische Parameter `{name}`, ein Platzhalter `*`, die Flags `@text`, `@binary` und `@csrf`, Middleware mit `#` sowie `+SOCKET` / `-SOCKET` für angemeldete und nicht angemeldete Benutzer. Die maximale Größe einer Nachricht ist `CONF.$wsmaxsize` (256 kB). Ändere sie pro Route mit einem dritten Argument in Bytes oder mit `<1MB` in der URL:\n\n```js\nROUTE('SOCKET /upload/ <5MB', upload);\nROUTE('SOCKET /feed/', feed, 1024 * 1024);\n```\n\n## Ein WebSocket-Objekt pro URL\n\nDie Aktion läuft nicht für jeden Client. Sie läuft **einmal pro URL**, wenn sich der erste Client verbindet; spätere Clients treten demselben WebSocket-Objekt bei. Bei einer dynamischen Route bekommt jede eigene URL ihr eigenes Objekt, sodass `/room/sport/` und `/room/music/` zwei getrennte Gruppen von Clients sind:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\t// self.params.name === 'sport'\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: self.params.name, body: message.body });\n\t});\n}\n```\n\n`self.url`, `self.params`, `self.online` (die Anzahl der verbundenen Clients) und `self.connections` (ein Objekt `{ id: client }`) beschreiben die Gruppe.\n\n## Nachrichtenformate\n\nEine Route liest und schreibt standardmäßig JSON: Eine eingehende Nachricht wird geparst (Nachrichten, die kein gültiges JSON sind, werden ignoriert), und `send()` serialisiert Objekte mit `JSON.stringify()`. Zwei Flags ändern das:\n\n| Flag | Das Event `message` erhält | `send()` schreibt |\n| --- | --- | --- |\n| (keins) | ein geparstes Objekt | JSON |\n| `@text` | einen String | JSON, oder mit `client.send(text, true)` den String so, wie er ist |\n\n\n```js\nROUTE('SOCKET /terminal/ @text', function() {\n\tthis.on('message', function(client, text) {\n\t\tclient.send(text.toUpperCase(), true);\n\t});\n});\n```\n\nDas Event `message` erhält als drittes Argument außerdem die Größe der Nachricht in Bytes.\n\n## Nachrichten senden\n\n`client.send(message)` schreibt an einen Client. `websocket.send(message, [comparer])` schreibt an jeden Client der Gruppe; der optionale `comparer(client, message)` gibt `true` für die Clients zurück, die sie bekommen sollen:\n\n```js\nself.send({ type: 'notify' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n`websocket.find(fn)` gibt den ersten Client zurück, für den `fn(client)` `true` zurückgibt:\n\n```js\nvar target = self.find(function(client) {\n\treturn client.user && client.user.id === message.to;\n});\ntarget && target.send({ type: 'private', body: message.body });\n```\n\n## Clients von außerhalb der Route benachrichtigen\n\nEine Aktion oder eine HTTP-Route ändert oft Daten, von denen verbundene Clients erfahren müssen. Das WebSocket-Objekt wird innerhalb der `SOCKET`-Route erstellt, also bewahre eine Referenz darauf im globalen Objekt `MAIN` auf und verwende diese Referenz aus jeder anderen Datei.\n\nErstelle `controllers/live.js`:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /live/', live);\n\tROUTE('POST /api/products/ --> products_create');\n\tROUTE('POST /api/maintenance/', maintenance);\n};\n\nfunction live() {\n\tMAIN.live = this;\n}\n\nfunction maintenance($) {\n\tMAIN.live && MAIN.live.send({ type: 'maintenance', message: $.body.message });\n\t$.success();\n}\n```\n\nErstelle `actions/products.js` (siehe [Aktionen](../actions/)):\n\n```js\nvar products = [];\n\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\n\t\tvar product = { id: UID(), name: model.name };\n\t\tproducts.push(product);\n\n\t\tMAIN.live && MAIN.live.send({ type: 'product_created', product: product });\n\n\t\t$.callback(product);\n\t}\n});\n```\n\nVerbinde dich aus dem Browser:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/live/');\n\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n\tif (msg.type === 'product_created')\n\t\tconsole.log('New product:', msg.product.name);\n};\n```\n\nEine Anfrage an `POST /api/products/` mit dem Body `{\"name\":\"Keyboard\"}` speichert jetzt das Produkt, sendet die Nachricht `product_created` an jeden verbundenen Client und beantwortet die Anfrage. Die Route `POST /api/maintenance/` macht dasselbe aus einer einfachen Routenfunktion. Eine Anfrage, die bei der Validierung der Aktion scheitert, sendet keine Nachricht.\n\nDie Aktion der Route läuft, wenn sich der erste Client verbindet, daher ist `MAIN.live` bis dahin `undefined`. Die Prüfung `MAIN.live &&` deckt diesen Moment ab: Die Aktion oder die Route antwortet normal, und es wird keine Nachricht gesendet. Nachdem der letzte Client gegangen ist, bleibt `MAIN.live` gesetzt, und `send()` erreicht niemanden. Nachrichten werden nicht gespeichert, also erhält ein Client, der sich später verbindet, nur die Nachrichten, die nach seiner Verbindung gesendet wurden.\n\nWenn die Route `autodestroy()` verwendet, lösche die Referenz in ihrem Callback. Der nächste Client, der sich verbindet, führt die Aktion der Route erneut aus und setzt eine neue Referenz:\n\n```js\nfunction live() {\n\tvar self = this;\n\tMAIN.live = self;\n\tself.autodestroy(function() {\n\t\tMAIN.live = null;\n\t});\n}\n```\n\nEine Route mit einer dynamischen URL hat ein WebSocket-Objekt pro URL, also bewahre eine Referenz pro URL auf:\n\n```js\nMAIN.rooms = {};\n\nexports.install = function() {\n\tROUTE('SOCKET /rooms/{name}/', room);\n\tROUTE('POST /api/rooms/{name}/', notify);\n};\n\nfunction room() {\n\tMAIN.rooms[this.params.name] = this;\n}\n\nfunction notify($) {\n\tvar room = MAIN.rooms[$.params.name];\n\troom && room.send({ type: 'notice', message: $.body.message });\n\t$.success();\n}\n```\n\n## Der Client\n\nJeder Client ist ein WebSocket-Controller mit den Daten der HTTP-Upgrade-Anfrage: `client.id`, `client.ip`, `client.user`, `client.query`, `client.params`, `client.headers`, `client.url`, `client.ua`, `client.mobile`, `client.robot`, `client.language` und `client.latency`. `client.cookie(name)` liest ein Cookie. Speichere deine eigenen Daten am Objekt, wenn du sie später brauchst:\n\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n## Autorisierung, CSRF und Middleware\n\nBevor ein Client angenommen wird, ruft das Framework dein Autorisierungs-Delegate auf (siehe [Autorisierung](../authorization/)). Der Benutzer, den es zurückgibt, steht in `client.user`. Eine mit `+SOCKET` deklarierte Route nimmt nur angemeldete Benutzer an und `-SOCKET` nur anonyme; ein Client, der zu keiner Route passt, bekommt den Handshake und wird dann mit dem Code `4001` geschlossen, sodass der Browser ein normales `close`-Event mit diesem Code sieht und zum Beispiel den Benutzer bitten kann, sich anzumelden:\n\n```js\nROUTE('+SOCKET /notifications/', notifications);\n```\n\nDas Flag `@csrf` verlangt ein gültiges CSRF-Token im Header `x-csrf-token` oder im Query-Argument `?csrf=` (Browser können bei einem WebSocket keine Header setzen, also verwende die Query). Mit `#name` deklarierte Middleware läuft, bevor die Verbindung umgestellt wird (siehe [Middleware](../middleware/)). Anfragen von IP-Adressen in `CONF.$blacklist` werden abgelehnt.\n\n## Schließen und Aufräumen\n\n`client.close([code], [message])` schließt einen Client, `websocket.close([code], [message])` schließt alle. Der Standardcode ist `1000`. Eine Nachricht, die größer als die Größe der Route ist, schließt den Client mit `1009`; ungültige komprimierte Daten mit `1003`.\n\n`websocket.destroy()` schließt alle Clients, löst `destroy` aus und entfernt das Objekt; der nächste Client, der sich verbindet, führt die Aktion erneut aus. `websocket.autodestroy([callback])` erledigt das für dich 5 Sekunden, nachdem der letzte Client gegangen ist, was die übliche Wahl für dynamische Räume ist:\n\n```js\nfunction room() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tself.send({ type: 'tick' });\n\t}, 1000);\n\tself.autodestroy(function() {\n\t\tclearInterval(timer);\n\t});\n}\n```\n\nDas globale Event `websocket_end` wird ausgelöst, wenn sich irgendein Client trennt: `ON('websocket_end', function(websocket, client) {})`.\n\n## Komprimierung und Kodierung\n\nWenn der Browser `permessage-deflate` anbietet und `CONF.$wscompress` `true` ist (Standard), werden Nachrichten in beide Richtungen komprimiert, Text- und Binärnachrichten (`@binary`) gleichermaßen. Ein Fehler der Komprimierung erreicht das Event `error` des WebSocket-Objekts. Zwei weitere Optionen verändern jede Nachricht:\n\n- `CONF.$wsencodedecode = true` schickt Nachrichten durch `encodeURIComponent()` und dekodiert eingehende Nachrichten mit `decodeURIComponent()`.\n- `websocket.encrypt()` verschlüsselt ausgehende und entschlüsselt eingehende Nachrichten der Gruppe mit `CONF.secret_encryption`. Beide Seiten müssen denselben Schlüssel verwenden.\n\n## Ping und Latenz\n\nDreimal pro Minute (15, 30 und 60 Sekunden nach Beginn jeder Minute) pingt das Framework alle Clients aller WebSocket-Routen an und misst `client.latency` anhand des Pongs. Vor jedem Ping prüft es die Clients: Ein Client, der auf den vorherigen Ping nicht geantwortet hat oder dessen Latenz höher als `CONF.$wsmaxlatency` (2000 ms) ist, wird geschlossen. So werden tote Verbindungen ohne deinen Code entfernt.\n\n`client.ping()` pingt selbst einen Client an.\n\n## Eine Route entfernen\n\n`ROUTE()` gibt die Route zurück. `route.remove()` entfernt sie und zerstört alle ihre WebSocket-Objekte, sodass jeder Client getrennt wird:\n\n```js\nvar route = ROUTE('SOCKET /live/', live);\n\n// later\nroute.remove();\n```\n\n## WebSocket-Client\n\n`WEBSOCKETCLIENT([callback])` verbindet deine Anwendung mit einem anderen WebSocket-Server. Setze die Optionen und die Events, dann rufe `connect()` auf:\n\n```js\nvar client = WEBSOCKETCLIENT();\n\nclient.options.reconnect = 5000;\nclient.headers['x-token'] = CONF.token;\n\nclient.on('open', function() {\n\tclient.send({ type: 'hello' });\n});\n\nclient.on('message', function(message) {\n\tconsole.log(message);\n});\n\nclient.on('close', function(code, reason) {\n\tconsole.log('closed', code, reason);\n});\n\nclient.connect('wss://example.com/live/');\n```\n\nOptionen von `client.options`:\n\n| Option | Standard | Beschreibung |\n| --- | --- | --- |\n| `type` | `'json'` | `'json'`, `'text'` oder `'binary'` |\n| `compress` | `true` | Dem Server `permessage-deflate` anbieten |\n| `reconnect` | `3000` | Verzögerung in ms vor einer erneuten Verbindung, nachdem die Verbindung geschlossen wurde; `0` schaltet sie ab |\n| `reconnectserver` | | `true` verbindet sich auch dann erneut, wenn die Verbindung nicht geöffnet werden kann |\n| `masking` | `false` | Ausgehende Frames maskieren (erforderlich bei Servern, die dem RFC streng folgen) |\n| `encodedecode` | `false` | Nachrichten mit `encodeURIComponent()` kodieren/dekodieren |\n| `encrypt` | | Ein Schlüssel: Nachrichten werden damit verschlüsselt und entschlüsselt |\n| `size` | `0` | Max. Größe einer dekomprimierten Nachricht in Bytes (`0` ohne Limit) |\n| `rejectunauthorized` | `false` | Ungültige TLS-Zertifikate ablehnen |\n| `timeout` | `30000` | TCP-Keep-Alive-Verzögerung in ms für den Socket (`0` schaltet sie ab) |\n\n`key`, `cert` und `dhparam` werden an die TLS-Verbindung übergeben. `client.close([code], [message])` schließt die Verbindung und beendet die erneuten Verbindungsversuche; `client.close(code, true)` schließt sie und behält die erneute Verbindung bei. `client.ping([timeout])` sendet einen Ping; wenn der Pong nicht innerhalb von `timeout` ms (3000) eintrifft, löst der Client `error` mit einem `Timeout`-Fehler aus, schließt die Verbindung und verbindet sich erneut. `client.latency` enthält die zuletzt gemessene Zeit in ms.\n\n## Konfiguration\n\n| Schlüssel | Standard | Beschreibung |\n| --- | --- | --- |\n| `$wsmaxsize` | `256` | Max. Größe einer Nachricht in kB |\n| `$wscompress` | `true` | Komprimierung mit `permessage-deflate` erlauben |\n| `$wsencodedecode` | `false` | Alle Nachrichten mit URI-Kodierung kodieren/dekodieren |\n| `$wsmaxlatency` | `2000` | Max. Latenz in ms, bevor ein Client von der Ping-Prüfung geschlossen wird |\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JaqmBm22c61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/websockets/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"WebSockets","summary":"Conexiones en tiempo real con rutas SOCKET, el objeto WebSocket y sus clientes, compresión, ping y el cliente WebSocket.","markdown":"---\ntitle: WebSockets\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/websockets/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# WebSockets\n\n> Conexiones en tiempo real con rutas SOCKET, el objeto WebSocket y sus clientes, compresión, ping y el cliente WebSocket.\n\nUna ruta WebSocket mantiene abierta una conexión entre el navegador (u otro servidor) y tu aplicación, así ambos lados pueden enviar mensajes en cualquier momento. Total.js se encarga por ti del handshake, los frames, la compresión, el ping y el JSON.\n\n## Una ruta WebSocket\n\nDeclárala con el método `SOCKET`. La acción se ejecuta con un objeto **WebSocket** como `this` (y como primer argumento). Le añades eventos; cada navegador conectado llega como un **cliente**.\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// message is already parsed from JSON\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client, code, reason) {\n\t\tself.send({ type: 'left', id: client.id });\n\t});\n}\n```\n\nEn el navegador:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/chat/');\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n};\nws.onopen = function() {\n\tws.send(JSON.stringify({ body: 'Hello' }));\n};\n```\n\nLa sintaxis de la ruta es la misma que la de las rutas HTTP (consulta [Enrutamiento](../routing/)): parámetros dinámicos `{name}`, un comodín `*`, los flags `@text`, `@binary` y `@csrf`, middleware con `#`, y `+SOCKET` / `-SOCKET` para usuarios autorizados y no autorizados. El tamaño máximo de un mensaje es `CONF.$wsmaxsize` (256 kB). Cámbialo por ruta con un tercer argumento en bytes, o con `<1MB` en la URL:\n\n```js\nROUTE('SOCKET /upload/ <5MB', upload);\nROUTE('SOCKET /feed/', feed, 1024 * 1024);\n```\n\n## Un objeto WebSocket por URL\n\nLa acción no se ejecuta para cada cliente. Se ejecuta **una vez por URL**, cuando se conecta el primer cliente; los clientes posteriores se unen al mismo objeto WebSocket. Con una ruta dinámica, cada URL distinta tiene su propio objeto, así que `/room/sport/` y `/room/music/` son dos grupos de clientes separados:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\t// self.params.name === 'sport'\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: self.params.name, body: message.body });\n\t});\n}\n```\n\n`self.url`, `self.params`, `self.online` (el número de clientes conectados) y `self.connections` (un objeto `{ id: client }`) describen el grupo.\n\n## Formatos de los mensajes\n\nUna ruta lee y escribe JSON por defecto: un mensaje entrante se parsea (los mensajes que no son JSON válido se ignoran), y `send()` serializa los objetos con `JSON.stringify()`. Dos flags lo cambian:\n\n| Flag | El evento `message` recibe | `send()` escribe |\n| --- | --- | --- |\n| (ninguno) | un objeto parseado | JSON |\n| `@text` | un string | JSON, o el string tal cual con `client.send(text, true)` |\n\n\n```js\nROUTE('SOCKET /terminal/ @text', function() {\n\tthis.on('message', function(client, text) {\n\t\tclient.send(text.toUpperCase(), true);\n\t});\n});\n```\n\nEl evento `message` también recibe como tercer argumento el tamaño del mensaje en bytes.\n\n## Enviar mensajes\n\n`client.send(message)` escribe a un cliente. `websocket.send(message, [comparer])` escribe a todos los clientes del grupo; el `comparer(client, message)` opcional devuelve `true` para los clientes que deben recibirlo:\n\n```js\nself.send({ type: 'notify' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n`websocket.find(fn)` devuelve el primer cliente para el que `fn(client)` devuelve `true`:\n\n```js\nvar target = self.find(function(client) {\n\treturn client.user && client.user.id === message.to;\n});\ntarget && target.send({ type: 'private', body: message.body });\n```\n\n## Notificar a los clientes desde fuera de la ruta\n\nUna acción o una ruta HTTP a menudo cambia datos que los clientes conectados tienen que conocer. El objeto WebSocket se crea dentro de la ruta `SOCKET`, así que guarda una referencia a él en el objeto global `MAIN` y usa esa referencia desde cualquier otro archivo.\n\nCrea `controllers/live.js`:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /live/', live);\n\tROUTE('POST /api/products/ --> products_create');\n\tROUTE('POST /api/maintenance/', maintenance);\n};\n\nfunction live() {\n\tMAIN.live = this;\n}\n\nfunction maintenance($) {\n\tMAIN.live && MAIN.live.send({ type: 'maintenance', message: $.body.message });\n\t$.success();\n}\n```\n\nCrea `actions/products.js` (consulta [Acciones](../actions/)):\n\n```js\nvar products = [];\n\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\n\t\tvar product = { id: UID(), name: model.name };\n\t\tproducts.push(product);\n\n\t\tMAIN.live && MAIN.live.send({ type: 'product_created', product: product });\n\n\t\t$.callback(product);\n\t}\n});\n```\n\nConéctate desde el navegador:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/live/');\n\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n\tif (msg.type === 'product_created')\n\t\tconsole.log('New product:', msg.product.name);\n};\n```\n\nUna petición a `POST /api/products/` con el cuerpo `{\"name\":\"Keyboard\"}` ahora guarda el producto, envía el mensaje `product_created` a todos los clientes conectados y responde a la petición. La ruta `POST /api/maintenance/` hace lo mismo desde una función de ruta normal. Una petición que no pasa la validación de la acción no envía ningún mensaje.\n\nLa acción de la ruta se ejecuta cuando se conecta el primer cliente, así que `MAIN.live` es `undefined` hasta entonces. La comprobación `MAIN.live &&` cubre ese momento: la acción o la ruta responde con normalidad y no se envía ningún mensaje. Después de que se vaya el último cliente, `MAIN.live` sigue establecido y `send()` no llega a nadie. Los mensajes no se guardan, así que un cliente que se conecta más tarde solo recibe los mensajes enviados después de conectarse.\n\nCuando la ruta usa `autodestroy()`, borra la referencia en su callback. El siguiente cliente que se conecte vuelve a ejecutar la acción de la ruta y establece una referencia nueva:\n\n```js\nfunction live() {\n\tvar self = this;\n\tMAIN.live = self;\n\tself.autodestroy(function() {\n\t\tMAIN.live = null;\n\t});\n}\n```\n\nUna ruta con una URL dinámica tiene un objeto WebSocket por URL, así que guarda una referencia por URL:\n\n```js\nMAIN.rooms = {};\n\nexports.install = function() {\n\tROUTE('SOCKET /rooms/{name}/', room);\n\tROUTE('POST /api/rooms/{name}/', notify);\n};\n\nfunction room() {\n\tMAIN.rooms[this.params.name] = this;\n}\n\nfunction notify($) {\n\tvar room = MAIN.rooms[$.params.name];\n\troom && room.send({ type: 'notice', message: $.body.message });\n\t$.success();\n}\n```\n\n## El cliente\n\nCada cliente es un controlador WebSocket con los datos de la petición HTTP de upgrade: `client.id`, `client.ip`, `client.user`, `client.query`, `client.params`, `client.headers`, `client.url`, `client.ua`, `client.mobile`, `client.robot`, `client.language` y `client.latency`. `client.cookie(name)` lee una cookie. Guarda tus propios datos en el objeto si los necesitas más tarde:\n\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n## Autorización, CSRF y middleware\n\nAntes de aceptar a un cliente, el framework llama a tu delegado de autorización (consulta [Autorización](../authorization/)). El usuario que devuelve está en `client.user`. Una ruta declarada con `+SOCKET` solo acepta usuarios autorizados y `-SOCKET` solo anónimos; un cliente que no coincide con ninguna ruta recibe el handshake y luego se cierra con el código `4001`, así el navegador ve un evento `close` normal con ese código y puede, por ejemplo, pedir al usuario que inicie sesión:\n\n```js\nROUTE('+SOCKET /notifications/', notifications);\n```\n\nEl flag `@csrf` exige un token CSRF válido en la cabecera `x-csrf-token` o en el argumento de query `?csrf=` (los navegadores no pueden poner cabeceras en un WebSocket, así que usa el query). El middleware declarado con `#name` se ejecuta antes de que se haga el upgrade de la conexión (consulta [Middleware](../middleware/)). Las peticiones de direcciones IP que están en `CONF.$blacklist` se rechazan.\n\n## Cerrar y limpiar\n\n`client.close([code], [message])` cierra un cliente, `websocket.close([code], [message])` los cierra todos. El código por defecto es `1000`. Un mensaje mayor que el tamaño de la ruta cierra el cliente con `1009`; los datos comprimidos no válidos, con `1003`.\n\n`websocket.destroy()` cierra todos los clientes, emite `destroy` y elimina el objeto; el siguiente cliente que se conecte vuelve a ejecutar la acción. `websocket.autodestroy([callback])` lo hace por ti 5 segundos después de que se vaya el último cliente, que es la opción habitual para salas dinámicas:\n\n```js\nfunction room() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tself.send({ type: 'tick' });\n\t}, 1000);\n\tself.autodestroy(function() {\n\t\tclearInterval(timer);\n\t});\n}\n```\n\nEl evento global `websocket_end` se emite cuando se desconecta cualquier cliente: `ON('websocket_end', function(websocket, client) {})`.\n\n## Compresión y codificación\n\nCuando el navegador ofrece `permessage-deflate` y `CONF.$wscompress` es `true` (por defecto), los mensajes se comprimen en ambas direcciones, tanto los de texto como los binarios (`@binary`). Un error de la compresión llega al evento `error` del objeto WebSocket. Dos opciones más transforman cada mensaje:\n\n- `CONF.$wsencodedecode = true` pasa los mensajes enviados por `encodeURIComponent()` y decodifica los mensajes entrantes con `decodeURIComponent()`.\n- `websocket.encrypt()` cifra los mensajes salientes y descifra los entrantes del grupo con `CONF.secret_encryption`. Ambos lados deben usar la misma clave.\n\n## Ping y latencia\n\nTres veces por minuto (a los 15, 30 y 60 segundos de cada minuto) el framework hace ping a todos los clientes de todas las rutas WebSocket y mide `client.latency` a partir del pong. Antes de cada ping comprueba los clientes: un cliente que no ha respondido al ping anterior, o cuya latencia es mayor que `CONF.$wsmaxlatency` (2000 ms), se cierra. Así se eliminan las conexiones muertas sin que tengas que escribir código.\n\n`client.ping()` hace ping tú mismo a un cliente.\n\n## Eliminar una ruta\n\n`ROUTE()` devuelve la ruta. `route.remove()` la elimina y destruye todos sus objetos WebSocket, así que todos los clientes se desconectan:\n\n```js\nvar route = ROUTE('SOCKET /live/', live);\n\n// later\nroute.remove();\n```\n\n## Cliente WebSocket\n\n`WEBSOCKETCLIENT([callback])` conecta tu aplicación a otro servidor WebSocket. Establece las opciones y los eventos, y luego llama a `connect()`:\n\n```js\nvar client = WEBSOCKETCLIENT();\n\nclient.options.reconnect = 5000;\nclient.headers['x-token'] = CONF.token;\n\nclient.on('open', function() {\n\tclient.send({ type: 'hello' });\n});\n\nclient.on('message', function(message) {\n\tconsole.log(message);\n});\n\nclient.on('close', function(code, reason) {\n\tconsole.log('closed', code, reason);\n});\n\nclient.connect('wss://example.com/live/');\n```\n\nOpciones de `client.options`:\n\n| Opción | Por defecto | Descripción |\n| --- | --- | --- |\n| `type` | `'json'` | `'json'`, `'text'` o `'binary'` |\n| `compress` | `true` | Ofrece `permessage-deflate` al servidor |\n| `reconnect` | `3000` | Espera en ms antes de reconectar cuando se cierra la conexión; `0` lo desactiva |\n| `reconnectserver` | | `true` también reconecta cuando no se puede abrir la conexión |\n| `masking` | `false` | Enmascara los frames salientes (lo exigen los servidores que siguen el RFC estrictamente) |\n| `encodedecode` | `false` | Codifica/decodifica los mensajes con `encodeURIComponent()` |\n| `encrypt` | | Una clave: los mensajes se cifran y descifran con ella |\n| `size` | `0` | Tamaño máx. en bytes de un mensaje descomprimido (`0` sin límite) |\n| `rejectunauthorized` | `false` | Rechaza los certificados TLS no válidos |\n| `timeout` | `30000` | Espera del keep-alive TCP en ms para el socket (`0` lo desactiva) |\n\n`key`, `cert` y `dhparam` se pasan a la conexión TLS. `client.close([code], [message])` cierra la conexión y deja de reconectar; `client.close(code, true)` la cierra y mantiene la reconexión. `client.ping([timeout])` envía un ping; cuando el pong no llega en `timeout` ms (3000), el cliente emite `error` con un error `Timeout`, cierra la conexión y reconecta. `client.latency` contiene el último tiempo medido en ms.\n\n## Configuración\n\n| Clave | Por defecto | Descripción |\n| --- | --- | --- |\n| `$wsmaxsize` | `256` | Tamaño máx. de un mensaje en kB |\n| `$wscompress` | `true` | Permite la compresión `permessage-deflate` |\n| `$wsencodedecode` | `false` | Codifica/decodifica todos los mensajes con codificación URI |\n| `$wsmaxlatency` | `2000` | Latencia máx. en ms antes de que la comprobación del ping cierre un cliente |\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JaqmBm22c61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/websockets/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"WebSockets","summary":"Connexions en temps réel avec les routes SOCKET, l'objet WebSocket et ses clients, la compression, le ping et le client WebSocket.","markdown":"---\ntitle: WebSockets\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/websockets/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# WebSockets\n\n> Connexions en temps réel avec les routes SOCKET, l'objet WebSocket et ses clients, la compression, le ping et le client WebSocket.\n\nUne route WebSocket garde une connexion ouverte entre le navigateur (ou un autre serveur) et ton application, pour que les deux côtés puissent envoyer des messages à tout moment. Total.js gère pour toi le handshake, les frames, la compression, le ping et le JSON.\n\n## Une route WebSocket\n\nDéclare-la avec la méthode `SOCKET`. L'action s'exécute avec un objet **WebSocket** comme `this` (et comme premier argument). Tu y attaches des événements ; chaque navigateur connecté arrive comme un **client**.\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// message is already parsed from JSON\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client, code, reason) {\n\t\tself.send({ type: 'left', id: client.id });\n\t});\n}\n```\n\nDans le navigateur :\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/chat/');\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n};\nws.onopen = function() {\n\tws.send(JSON.stringify({ body: 'Hello' }));\n};\n```\n\nLa syntaxe de la route est la même que pour les routes HTTP (voir [Routage](../routing/)) : les paramètres dynamiques `{name}`, un joker `*`, les flags `@text`, `@binary` et `@csrf`, le middleware avec `#`, et `+SOCKET` / `-SOCKET` pour les utilisateurs autorisés et non autorisés. La taille maximale d'un message est `CONF.$wsmaxsize` (256 kB). Change-la par route avec un troisième argument en octets, ou avec `<1MB` dans l'URL :\n\n```js\nROUTE('SOCKET /upload/ <5MB', upload);\nROUTE('SOCKET /feed/', feed, 1024 * 1024);\n```\n\n## Un objet WebSocket par URL\n\nL'action ne s'exécute pas pour chaque client. Elle s'exécute **une fois par URL**, quand le premier client se connecte ; les clients suivants rejoignent le même objet WebSocket. Avec une route dynamique, chaque URL distincte a son propre objet : `/room/sport/` et `/room/music/` sont donc deux groupes de clients séparés :\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\t// self.params.name === 'sport'\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: self.params.name, body: message.body });\n\t});\n}\n```\n\n`self.url`, `self.params`, `self.online` (le nombre de clients connectés) et `self.connections` (un objet `{ id: client }`) décrivent le groupe.\n\n## Formats des messages\n\nPar défaut, une route lit et écrit du JSON : un message entrant est analysé (les messages qui ne sont pas du JSON valide sont ignorés), et `send()` sérialise les objets avec `JSON.stringify()`. Deux flags changent cela :\n\n| Flag | L'événement `message` reçoit | `send()` écrit |\n| --- | --- | --- |\n| (aucun) | un objet analysé | du JSON |\n| `@text` | une chaîne | du JSON, ou la chaîne telle quelle avec `client.send(text, true)` |\n\n\n```js\nROUTE('SOCKET /terminal/ @text', function() {\n\tthis.on('message', function(client, text) {\n\t\tclient.send(text.toUpperCase(), true);\n\t});\n});\n```\n\nL'événement `message` reçoit aussi la taille du message en octets comme troisième argument.\n\n## Envoyer des messages\n\n`client.send(message)` écrit à un seul client. `websocket.send(message, [comparer])` écrit à chaque client du groupe ; le `comparer(client, message)` facultatif renvoie `true` pour les clients qui doivent le recevoir :\n\n```js\nself.send({ type: 'notify' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n`websocket.find(fn)` renvoie le premier client pour lequel `fn(client)` renvoie `true` :\n\n```js\nvar target = self.find(function(client) {\n\treturn client.user && client.user.id === message.to;\n});\ntarget && target.send({ type: 'private', body: message.body });\n```\n\n## Notifier les clients depuis l'extérieur de la route\n\nUne action ou une route HTTP modifie souvent des données que les clients connectés doivent connaître. L'objet WebSocket est créé dans la route `SOCKET`, alors garde une référence vers lui dans l'objet global `MAIN` et utilise cette référence depuis n'importe quel autre fichier.\n\nCrée `controllers/live.js` :\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /live/', live);\n\tROUTE('POST /api/products/ --> products_create');\n\tROUTE('POST /api/maintenance/', maintenance);\n};\n\nfunction live() {\n\tMAIN.live = this;\n}\n\nfunction maintenance($) {\n\tMAIN.live && MAIN.live.send({ type: 'maintenance', message: $.body.message });\n\t$.success();\n}\n```\n\nCrée `actions/products.js` (voir [Actions](../actions/)) :\n\n```js\nvar products = [];\n\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\n\t\tvar product = { id: UID(), name: model.name };\n\t\tproducts.push(product);\n\n\t\tMAIN.live && MAIN.live.send({ type: 'product_created', product: product });\n\n\t\t$.callback(product);\n\t}\n});\n```\n\nConnecte-toi depuis le navigateur :\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/live/');\n\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n\tif (msg.type === 'product_created')\n\t\tconsole.log('New product:', msg.product.name);\n};\n```\n\nUne requête vers `POST /api/products/` avec le corps `{\"name\":\"Keyboard\"}` enregistre maintenant le produit, envoie le message `product_created` à chaque client connecté et répond à la requête. La route `POST /api/maintenance/` fait la même chose depuis une simple fonction de route. Une requête qui échoue à la validation de l'action n'envoie aucun message.\n\nL'action de la route s'exécute quand le premier client se connecte, donc `MAIN.live` vaut `undefined` jusque-là. La vérification `MAIN.live &&` couvre ce moment : l'action ou la route répond normalement et aucun message n'est envoyé. Après le départ du dernier client, `MAIN.live` reste défini et `send()` n'atteint personne. Les messages ne sont pas stockés : un client qui se connecte plus tard ne reçoit que les messages envoyés après sa connexion.\n\nQuand la route utilise `autodestroy()`, efface la référence dans son callback. Le prochain client qui se connecte exécute à nouveau l'action de la route et définit une nouvelle référence :\n\n```js\nfunction live() {\n\tvar self = this;\n\tMAIN.live = self;\n\tself.autodestroy(function() {\n\t\tMAIN.live = null;\n\t});\n}\n```\n\nUne route avec une URL dynamique a un objet WebSocket par URL, alors garde une référence par URL :\n\n```js\nMAIN.rooms = {};\n\nexports.install = function() {\n\tROUTE('SOCKET /rooms/{name}/', room);\n\tROUTE('POST /api/rooms/{name}/', notify);\n};\n\nfunction room() {\n\tMAIN.rooms[this.params.name] = this;\n}\n\nfunction notify($) {\n\tvar room = MAIN.rooms[$.params.name];\n\troom && room.send({ type: 'notice', message: $.body.message });\n\t$.success();\n}\n```\n\n## Le client\n\nChaque client est un contrôleur WebSocket avec les données de la requête HTTP d'upgrade : `client.id`, `client.ip`, `client.user`, `client.query`, `client.params`, `client.headers`, `client.url`, `client.ua`, `client.mobile`, `client.robot`, `client.language` et `client.latency`. `client.cookie(name)` lit un cookie. Stocke tes propres données sur l'objet si tu en as besoin plus tard :\n\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n## Autorisation, CSRF et middleware\n\nAvant qu'un client soit accepté, le framework appelle ton délégué d'autorisation (voir [Autorisation](../authorization/)). L'utilisateur qu'il renvoie se trouve dans `client.user`. Une route déclarée avec `+SOCKET` n'accepte que les utilisateurs autorisés, et `-SOCKET` que les anonymes ; un client qui ne correspond à aucune route reçoit le handshake puis est fermé avec le code `4001` : le navigateur voit donc un événement `close` normal avec ce code et peut, par exemple, demander à l'utilisateur de se connecter :\n\n```js\nROUTE('+SOCKET /notifications/', notifications);\n```\n\nLe flag `@csrf` exige un token CSRF valide dans l'en-tête `x-csrf-token` ou dans l'argument de query `?csrf=` (les navigateurs ne peuvent pas définir d'en-têtes sur un WebSocket, alors utilise la query). Le middleware déclaré avec `#name` s'exécute avant l'upgrade de la connexion (voir [Middleware](../middleware/)). Les requêtes venant d'adresses IP de `CONF.$blacklist` sont refusées.\n\n## Fermeture et nettoyage\n\n`client.close([code], [message])` ferme un client, `websocket.close([code], [message])` les ferme tous. Le code par défaut est `1000`. Un message plus grand que la taille de la route ferme le client avec `1009` ; des données compressées invalides avec `1003`.\n\n`websocket.destroy()` ferme tous les clients, émet `destroy` et supprime l'objet ; le prochain client qui se connecte exécute à nouveau l'action. `websocket.autodestroy([callback])` le fait pour toi 5 secondes après le départ du dernier client, ce qui est le choix habituel pour les salons dynamiques :\n\n```js\nfunction room() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tself.send({ type: 'tick' });\n\t}, 1000);\n\tself.autodestroy(function() {\n\t\tclearInterval(timer);\n\t});\n}\n```\n\nL'événement global `websocket_end` est émis quand un client se déconnecte : `ON('websocket_end', function(websocket, client) {})`.\n\n## Compression et encodage\n\nQuand le navigateur propose `permessage-deflate` et que `CONF.$wscompress` vaut `true` (par défaut), les messages sont compressés dans les deux sens, les messages texte comme les messages binaires (`@binary`). Une erreur de compression arrive à l'événement `error` de l'objet WebSocket. Deux autres options transforment chaque message :\n\n- `CONF.$wsencodedecode = true` fait passer les messages par `encodeURIComponent()` et décode les messages entrants avec `decodeURIComponent()`.\n- `websocket.encrypt()` chiffre les messages sortants et déchiffre les messages entrants du groupe avec `CONF.secret_encryption`. Les deux côtés doivent utiliser la même clé.\n\n## Ping et latence\n\nTrois fois par minute (à 15, 30 et 60 secondes de chaque minute), le framework envoie un ping à tous les clients de toutes les routes WebSocket et mesure `client.latency` à partir du pong. Avant chaque ping, il vérifie les clients : un client qui n'a pas répondu au ping précédent, ou dont la latence dépasse `CONF.$wsmaxlatency` (2000 ms), est fermé. Cela supprime les connexions mortes sans ton code.\n\n`client.ping()` envoie toi-même un ping à un client.\n\n## Supprimer une route\n\n`ROUTE()` renvoie la route. `route.remove()` la supprime et détruit tous ses objets WebSocket : chaque client est donc déconnecté :\n\n```js\nvar route = ROUTE('SOCKET /live/', live);\n\n// later\nroute.remove();\n```\n\n## Client WebSocket\n\n`WEBSOCKETCLIENT([callback])` connecte ton application à un autre serveur WebSocket. Définis les options et les événements, puis appelle `connect()` :\n\n```js\nvar client = WEBSOCKETCLIENT();\n\nclient.options.reconnect = 5000;\nclient.headers['x-token'] = CONF.token;\n\nclient.on('open', function() {\n\tclient.send({ type: 'hello' });\n});\n\nclient.on('message', function(message) {\n\tconsole.log(message);\n});\n\nclient.on('close', function(code, reason) {\n\tconsole.log('closed', code, reason);\n});\n\nclient.connect('wss://example.com/live/');\n```\n\nOptions de `client.options` :\n\n| Option | Par défaut | Description |\n| --- | --- | --- |\n| `type` | `'json'` | `'json'`, `'text'` ou `'binary'` |\n| `compress` | `true` | Proposer `permessage-deflate` au serveur |\n| `reconnect` | `3000` | Délai en ms avant une reconnexion après la fermeture de la connexion ; `0` la désactive |\n| `reconnectserver` | | `true` reconnecte aussi quand la connexion ne peut pas être ouverte |\n| `masking` | `false` | Masquer les frames sortantes (exigé par les serveurs qui suivent strictement la RFC) |\n| `encodedecode` | `false` | Encoder/décoder les messages avec `encodeURIComponent()` |\n| `encrypt` | | Une clé : les messages sont chiffrés et déchiffrés avec elle |\n| `size` | `0` | Taille max. en octets d'un message décompressé (`0` sans limite) |\n| `rejectunauthorized` | `false` | Rejeter les certificats TLS invalides |\n| `timeout` | `30000` | Délai de keep-alive TCP en ms pour le socket (`0` le désactive) |\n\n`key`, `cert` et `dhparam` sont transmis à la connexion TLS. `client.close([code], [message])` ferme la connexion et arrête la reconnexion ; `client.close(code, true)` la ferme et garde la reconnexion. `client.ping([timeout])` envoie un ping ; quand le pong n'arrive pas dans les `timeout` ms (3000), le client émet `error` avec une erreur `Timeout`, ferme la connexion et se reconnecte. `client.latency` contient le dernier temps mesuré en ms.\n\n## Configuration\n\n| Clé | Par défaut | Description |\n| --- | --- | --- |\n| `$wsmaxsize` | `256` | Taille max. d'un message en kB |\n| `$wscompress` | `true` | Autoriser la compression `permessage-deflate` |\n| `$wsencodedecode` | `false` | Encoder/décoder tous les messages avec l'encodage URI |\n| `$wsmaxlatency` | `2000` | Latence max. en ms avant qu'un client soit fermé par la vérification du ping |\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JaqmBm22c61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/websockets/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"WebSocket","summary":"Connessioni in tempo reale con le route SOCKET, l'oggetto WebSocket e i suoi client, compressione, ping e il client WebSocket.","markdown":"---\ntitle: WebSocket\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/websockets/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# WebSocket\n\n> Connessioni in tempo reale con le route SOCKET, l'oggetto WebSocket e i suoi client, compressione, ping e il client WebSocket.\n\nUna route WebSocket tiene aperta una connessione tra il browser (o un altro server) e la tua applicazione, così entrambe le parti possono inviare messaggi in qualsiasi momento. Total.js gestisce per te l'handshake, i frame, la compressione, il ping e il JSON.\n\n## Una route WebSocket\n\nDichiarala con il metodo `SOCKET`. L'azione viene eseguita con un oggetto **WebSocket** come `this` (e come primo argomento). Gli colleghi degli eventi; ogni browser connesso arriva come **client**.\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// message is already parsed from JSON\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client, code, reason) {\n\t\tself.send({ type: 'left', id: client.id });\n\t});\n}\n```\n\nNel browser:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/chat/');\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n};\nws.onopen = function() {\n\tws.send(JSON.stringify({ body: 'Hello' }));\n};\n```\n\nLa sintassi della route è la stessa delle route HTTP (vedi [Routing](../routing/)): parametri dinamici `{name}`, un carattere jolly `*`, i flag `@text`, `@binary` e `@csrf`, middleware con `#`, e `+SOCKET` / `-SOCKET` per utenti autorizzati e non autorizzati. La dimensione massima di un messaggio è `CONF.$wsmaxsize` (256 kB). Cambiala per una singola route con un terzo argomento in byte, oppure con `<1MB` nell'URL:\n\n```js\nROUTE('SOCKET /upload/ <5MB', upload);\nROUTE('SOCKET /feed/', feed, 1024 * 1024);\n```\n\n## Un oggetto WebSocket per URL\n\nL'azione non viene eseguita per ogni client. Viene eseguita **una volta per URL**, quando si connette il primo client; i client successivi si uniscono allo stesso oggetto WebSocket. Con una route dinamica, ogni URL distinto ottiene il proprio oggetto, quindi `/room/sport/` e `/room/music/` sono due gruppi di client separati:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\t// self.params.name === 'sport'\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: self.params.name, body: message.body });\n\t});\n}\n```\n\n`self.url`, `self.params`, `self.online` (il numero di client connessi) e `self.connections` (un oggetto `{ id: client }`) descrivono il gruppo.\n\n## Formati dei messaggi\n\nUna route legge e scrive JSON per impostazione predefinita: un messaggio in arrivo viene interpretato (i messaggi che non sono JSON valido vengono ignorati), e `send()` serializza gli oggetti con `JSON.stringify()`. Due flag cambiano questo comportamento:\n\n| Flag | L'evento `message` riceve | `send()` scrive |\n| --- | --- | --- |\n| (nessuno) | un oggetto interpretato | JSON |\n| `@text` | una stringa | JSON, oppure la stringa così com'è con `client.send(text, true)` |\n\n\n```js\nROUTE('SOCKET /terminal/ @text', function() {\n\tthis.on('message', function(client, text) {\n\t\tclient.send(text.toUpperCase(), true);\n\t});\n});\n```\n\nL'evento `message` riceve anche la dimensione del messaggio in byte come terzo argomento.\n\n## Inviare messaggi\n\n`client.send(message)` scrive a un client. `websocket.send(message, [comparer])` scrive a ogni client del gruppo; il `comparer(client, message)` facoltativo restituisce `true` per i client che devono riceverlo:\n\n```js\nself.send({ type: 'notify' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n`websocket.find(fn)` restituisce il primo client per cui `fn(client)` restituisce `true`:\n\n```js\nvar target = self.find(function(client) {\n\treturn client.user && client.user.id === message.to;\n});\ntarget && target.send({ type: 'private', body: message.body });\n```\n\n## Avvisare i client dall'esterno della route\n\nUn'azione o una route HTTP spesso modifica dati che i client connessi devono conoscere. L'oggetto WebSocket viene creato dentro la route `SOCKET`, quindi tieni un riferimento a esso nell'oggetto globale `MAIN` e usa quel riferimento da qualsiasi altro file.\n\nCrea `controllers/live.js`:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /live/', live);\n\tROUTE('POST /api/products/ --> products_create');\n\tROUTE('POST /api/maintenance/', maintenance);\n};\n\nfunction live() {\n\tMAIN.live = this;\n}\n\nfunction maintenance($) {\n\tMAIN.live && MAIN.live.send({ type: 'maintenance', message: $.body.message });\n\t$.success();\n}\n```\n\nCrea `actions/products.js` (vedi [Azioni](../actions/)):\n\n```js\nvar products = [];\n\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\n\t\tvar product = { id: UID(), name: model.name };\n\t\tproducts.push(product);\n\n\t\tMAIN.live && MAIN.live.send({ type: 'product_created', product: product });\n\n\t\t$.callback(product);\n\t}\n});\n```\n\nCollegati dal browser:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/live/');\n\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n\tif (msg.type === 'product_created')\n\t\tconsole.log('New product:', msg.product.name);\n};\n```\n\nUna richiesta a `POST /api/products/` con il body `{\"name\":\"Keyboard\"}` ora salva il prodotto, invia il messaggio `product_created` a ogni client connesso e risponde alla richiesta. La route `POST /api/maintenance/` fa lo stesso da una semplice funzione di route. Una richiesta che non supera la validazione dell'azione non invia alcun messaggio.\n\nL'azione della route viene eseguita quando si connette il primo client, quindi `MAIN.live` è `undefined` fino a quel momento. Il controllo `MAIN.live &&` copre quel momento: l'azione o la route risponde normalmente e non viene inviato alcun messaggio. Dopo che l'ultimo client se ne va, `MAIN.live` resta impostato e `send()` non raggiunge nessuno. I messaggi non vengono conservati, quindi un client che si connette più tardi riceve solo i messaggi inviati dopo la sua connessione.\n\nQuando la route usa `autodestroy()`, cancella il riferimento nella sua callback. Il prossimo client che si connette esegue di nuovo l'azione della route e imposta un nuovo riferimento:\n\n```js\nfunction live() {\n\tvar self = this;\n\tMAIN.live = self;\n\tself.autodestroy(function() {\n\t\tMAIN.live = null;\n\t});\n}\n```\n\nUna route con un URL dinamico ha un oggetto WebSocket per URL, quindi tieni un riferimento per URL:\n\n```js\nMAIN.rooms = {};\n\nexports.install = function() {\n\tROUTE('SOCKET /rooms/{name}/', room);\n\tROUTE('POST /api/rooms/{name}/', notify);\n};\n\nfunction room() {\n\tMAIN.rooms[this.params.name] = this;\n}\n\nfunction notify($) {\n\tvar room = MAIN.rooms[$.params.name];\n\troom && room.send({ type: 'notice', message: $.body.message });\n\t$.success();\n}\n```\n\n## Il client\n\nOgni client è un controller WebSocket con i dati della richiesta HTTP di upgrade: `client.id`, `client.ip`, `client.user`, `client.query`, `client.params`, `client.headers`, `client.url`, `client.ua`, `client.mobile`, `client.robot`, `client.language` e `client.latency`. `client.cookie(name)` legge un cookie. Salva i tuoi dati sull'oggetto se ti servono più tardi:\n\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n## Autorizzazione, CSRF e middleware\n\nPrima che un client venga accettato, il framework chiama il tuo delegate di autorizzazione (vedi [Autorizzazione](../authorization/)). L'utente che restituisce si trova in `client.user`. Una route dichiarata con `+SOCKET` accetta solo utenti autorizzati e `-SOCKET` solo utenti anonimi; un client che non corrisponde a nessuna route riceve l'handshake e poi viene chiuso con il codice `4001`, così il browser vede un normale evento `close` con quel codice e può, per esempio, chiedere all'utente di accedere:\n\n```js\nROUTE('+SOCKET /notifications/', notifications);\n```\n\nIl flag `@csrf` richiede un token CSRF valido nell'header `x-csrf-token` o nell'argomento di query `?csrf=` (i browser non possono impostare header su un WebSocket, quindi usa la query). Il middleware dichiarato con `#name` viene eseguito prima dell'upgrade della connessione (vedi [Middleware](../middleware/)). Le richieste dagli indirizzi IP in `CONF.$blacklist` vengono rifiutate.\n\n## Chiusura e pulizia\n\n`client.close([code], [message])` chiude un client, `websocket.close([code], [message])` li chiude tutti. Il codice predefinito è `1000`. Un messaggio più grande della dimensione della route chiude il client con `1009`; dati compressi non validi con `1003`.\n\n`websocket.destroy()` chiude tutti i client, emette `destroy` e rimuove l'oggetto; il prossimo client che si connette esegue di nuovo l'azione. `websocket.autodestroy([callback])` lo fa per te 5 secondi dopo che l'ultimo client se ne è andato, ed è la scelta abituale per le stanze dinamiche:\n\n```js\nfunction room() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tself.send({ type: 'tick' });\n\t}, 1000);\n\tself.autodestroy(function() {\n\t\tclearInterval(timer);\n\t});\n}\n```\n\nL'evento globale `websocket_end` viene emesso quando un client qualsiasi si disconnette: `ON('websocket_end', function(websocket, client) {})`.\n\n## Compressione e codifica\n\nQuando il browser offre `permessage-deflate` e `CONF.$wscompress` è `true` (predefinito), i messaggi vengono compressi in entrambe le direzioni, sia i messaggi di testo sia quelli binari (`@binary`). Un errore della compressione arriva all'evento `error` dell'oggetto WebSocket. Altre due opzioni trasformano ogni messaggio:\n\n- `CONF.$wsencodedecode = true` invia i messaggi passandoli per `encodeURIComponent()` e decodifica i messaggi in arrivo con `decodeURIComponent()`.\n- `websocket.encrypt()` cifra i messaggi in uscita e decifra quelli in arrivo del gruppo con `CONF.secret_encryption`. Entrambe le parti devono usare la stessa chiave.\n\n## Ping e latenza\n\nTre volte al minuto (a 15, 30 e 60 secondi di ogni minuto) il framework invia un ping a tutti i client di tutte le route WebSocket e misura `client.latency` dal pong. Prima di ogni ping controlla i client: un client che non ha risposto al ping precedente, o la cui latenza è superiore a `CONF.$wsmaxlatency` (2000 ms), viene chiuso. Così le connessioni morte vengono rimosse senza il tuo codice.\n\n`client.ping()` invia tu stesso un ping a un client.\n\n## Rimuovere una route\n\n`ROUTE()` restituisce la route. `route.remove()` la rimuove e distrugge tutti i suoi oggetti WebSocket, quindi ogni client viene disconnesso:\n\n```js\nvar route = ROUTE('SOCKET /live/', live);\n\n// later\nroute.remove();\n```\n\n## Client WebSocket\n\n`WEBSOCKETCLIENT([callback])` collega la tua applicazione a un altro server WebSocket. Imposta le opzioni e gli eventi, poi chiama `connect()`:\n\n```js\nvar client = WEBSOCKETCLIENT();\n\nclient.options.reconnect = 5000;\nclient.headers['x-token'] = CONF.token;\n\nclient.on('open', function() {\n\tclient.send({ type: 'hello' });\n});\n\nclient.on('message', function(message) {\n\tconsole.log(message);\n});\n\nclient.on('close', function(code, reason) {\n\tconsole.log('closed', code, reason);\n});\n\nclient.connect('wss://example.com/live/');\n```\n\nOpzioni di `client.options`:\n\n| Opzione | Predefinito | Descrizione |\n| --- | --- | --- |\n| `type` | `'json'` | `'json'`, `'text'` o `'binary'` |\n| `compress` | `true` | Offre `permessage-deflate` al server |\n| `reconnect` | `3000` | Attesa in ms prima di ricollegarsi dopo la chiusura della connessione; `0` la disattiva |\n| `reconnectserver` | | `true` si ricollega anche quando la connessione non si può aprire |\n| `masking` | `false` | Maschera i frame in uscita (richiesto dai server che seguono rigorosamente la RFC) |\n| `encodedecode` | `false` | Codifica/decodifica i messaggi con `encodeURIComponent()` |\n| `encrypt` | | Una chiave: i messaggi vengono cifrati e decifrati con essa |\n| `size` | `0` | Dimensione massima in byte di un messaggio decompresso (`0` nessun limite) |\n| `rejectunauthorized` | `false` | Rifiuta i certificati TLS non validi |\n| `timeout` | `30000` | Ritardo del keep-alive TCP in ms per il socket (`0` lo disattiva) |\n\n`key`, `cert` e `dhparam` vengono passati alla connessione TLS. `client.close([code], [message])` chiude la connessione e smette di ricollegarsi; `client.close(code, true)` la chiude e mantiene la riconnessione. `client.ping([timeout])` invia un ping; quando il pong non arriva entro `timeout` ms (3000), il client emette `error` con un errore `Timeout`, chiude la connessione e si ricollega. `client.latency` contiene l'ultimo tempo misurato in ms.\n\n## Configurazione\n\n| Chiave | Predefinito | Descrizione |\n| --- | --- | --- |\n| `$wsmaxsize` | `256` | Dimensione massima di un messaggio in kB |\n| `$wscompress` | `true` | Consente la compressione `permessage-deflate` |\n| `$wsencodedecode` | `false` | Codifica/decodifica tutti i messaggi con la codifica URI |\n| `$wsmaxlatency` | `2000` | Latenza massima in ms prima che un client venga chiuso dal controllo del ping |\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JaqmBm22c61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/websockets/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"WebSockety","summary":"Spojenia v reálnom čase s trasami SOCKET, objekt WebSocket a jeho klienti, kompresia, ping a WebSocket klient.","markdown":"---\ntitle: WebSockety\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/websockets/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# WebSockety\n\n> Spojenia v reálnom čase s trasami SOCKET, objekt WebSocket a jeho klienti, kompresia, ping a WebSocket klient.\n\nWebSocket trasa drží otvorené spojenie medzi prehliadačom (alebo iným serverom) a tvojou aplikáciou, takže obe strany môžu posielať správy kedykoľvek. Total.js sa za teba postará o handshake, rámce, kompresiu, ping a JSON.\n\n## WebSocket trasa\n\nDeklaruješ ju metódou `SOCKET`. Akcia beží s objektom **WebSocket** ako `this` (a ako prvým argumentom). Pripájaš k nemu udalosti; každý pripojený prehliadač prichádza ako **klient**.\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// message is already parsed from JSON\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client, code, reason) {\n\t\tself.send({ type: 'left', id: client.id });\n\t});\n}\n```\n\nV prehliadači:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/chat/');\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n};\nws.onopen = function() {\n\tws.send(JSON.stringify({ body: 'Hello' }));\n};\n```\n\nSyntax trasy je rovnaká ako pri HTTP trasách (pozri [Routing](../routing/)): dynamické parametre `{name}`, wildcard `*`, flagy `@text`, `@binary` a `@csrf`, middleware cez `#` a `+SOCKET` / `-SOCKET` pre prihlásených a neprihlásených používateľov. Maximálna veľkosť jednej správy je `CONF.$wsmaxsize` (256 kB). Pre jednotlivú trasu ju zmeníš tretím argumentom v bajtoch alebo cez `<1MB` v URL:\n\n```js\nROUTE('SOCKET /upload/ <5MB', upload);\nROUTE('SOCKET /feed/', feed, 1024 * 1024);\n```\n\n## Jeden objekt WebSocket na URL\n\nAkcia sa nespúšťa pre každého klienta. Spustí sa **raz na URL**, keď sa pripojí prvý klient; ďalší klienti sa pridajú k tomu istému objektu WebSocket. Pri dynamickej trase dostane každá odlišná URL vlastný objekt, takže `/room/sport/` a `/room/music/` sú dve samostatné skupiny klientov:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\t// self.params.name === 'sport'\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: self.params.name, body: message.body });\n\t});\n}\n```\n\n`self.url`, `self.params`, `self.online` (počet pripojených klientov) a `self.connections` (objekt `{ id: client }`) opisujú skupinu.\n\n## Formáty správ\n\nTrasa predvolene číta a zapisuje JSON: prichádzajúca správa sa sparsuje (správy, ktoré nie sú platný JSON, sa ignorujú) a `send()` serializuje objekty cez `JSON.stringify()`. Dva flagy to menia:\n\n| Flag | Udalosť `message` dostane | `send()` zapíše |\n| --- | --- | --- |\n| (žiadny) | sparsovaný objekt | JSON |\n| `@text` | reťazec | JSON alebo reťazec tak, ako je, s `client.send(text, true)` |\n\n\n```js\nROUTE('SOCKET /terminal/ @text', function() {\n\tthis.on('message', function(client, text) {\n\t\tclient.send(text.toUpperCase(), true);\n\t});\n});\n```\n\nUdalosť `message` dostane ako tretí argument aj veľkosť správy v bajtoch.\n\n## Posielanie správ\n\n`client.send(message)` zapíše jednému klientovi. `websocket.send(message, [comparer])` zapíše všetkým klientom skupiny; voliteľný `comparer(client, message)` vráti `true` pre klientov, ktorí ju majú dostať:\n\n```js\nself.send({ type: 'notify' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n`websocket.find(fn)` vráti prvého klienta, pre ktorého `fn(client)` vráti `true`:\n\n```js\nvar target = self.find(function(client) {\n\treturn client.user && client.user.id === message.to;\n});\ntarget && target.send({ type: 'private', body: message.body });\n```\n\n## Upozornenie klientov mimo trasy\n\nAkcia alebo HTTP trasa často mení dáta, o ktorých musia pripojení klienti vedieť. Objekt WebSocket sa vytvára vnútri trasy `SOCKET`, takže si odkaz naň ulož do globálneho objektu `MAIN` a tento odkaz používaj z akéhokoľvek iného súboru.\n\nVytvor `controllers/live.js`:\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /live/', live);\n\tROUTE('POST /api/products/ --> products_create');\n\tROUTE('POST /api/maintenance/', maintenance);\n};\n\nfunction live() {\n\tMAIN.live = this;\n}\n\nfunction maintenance($) {\n\tMAIN.live && MAIN.live.send({ type: 'maintenance', message: $.body.message });\n\t$.success();\n}\n```\n\nVytvor `actions/products.js` (pozri [Akcie](../actions/)):\n\n```js\nvar products = [];\n\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\n\t\tvar product = { id: UID(), name: model.name };\n\t\tproducts.push(product);\n\n\t\tMAIN.live && MAIN.live.send({ type: 'product_created', product: product });\n\n\t\t$.callback(product);\n\t}\n});\n```\n\nPripoj sa z prehliadača:\n\n```js\nvar ws = new WebSocket('ws://localhost:8000/live/');\n\nws.onmessage = function(e) {\n\tvar msg = JSON.parse(e.data);\n\tif (msg.type === 'product_created')\n\t\tconsole.log('New product:', msg.product.name);\n};\n```\n\nPožiadavka na `POST /api/products/` s telom `{\"name\":\"Keyboard\"}` teraz uloží produkt, pošle správu `product_created` každému pripojenému klientovi a odpovie na požiadavku. Trasa `POST /api/maintenance/` robí to isté z obyčajnej funkcie trasy. Požiadavka, ktorá neprejde validáciou akcie, žiadnu správu nepošle.\n\nAkcia trasy sa spustí, keď sa pripojí prvý klient, takže `MAIN.live` je dovtedy `undefined`. Kontrola `MAIN.live &&` pokrýva tento okamih: akcia alebo trasa odpovie normálne a žiadna správa sa nepošle. Keď odíde posledný klient, `MAIN.live` zostane nastavený a `send()` nedosiahne nikoho. Správy sa neukladajú, takže klient, ktorý sa pripojí neskôr, dostane iba správy poslané po jeho pripojení.\n\nKeď trasa používa `autodestroy()`, vymaž odkaz v jeho callbacku. Ďalší klient, ktorý sa pripojí, spustí akciu trasy znova a nastaví nový odkaz:\n\n```js\nfunction live() {\n\tvar self = this;\n\tMAIN.live = self;\n\tself.autodestroy(function() {\n\t\tMAIN.live = null;\n\t});\n}\n```\n\nTrasa s dynamickou URL má jeden objekt WebSocket na URL, takže si drž jeden odkaz na URL:\n\n```js\nMAIN.rooms = {};\n\nexports.install = function() {\n\tROUTE('SOCKET /rooms/{name}/', room);\n\tROUTE('POST /api/rooms/{name}/', notify);\n};\n\nfunction room() {\n\tMAIN.rooms[this.params.name] = this;\n}\n\nfunction notify($) {\n\tvar room = MAIN.rooms[$.params.name];\n\troom && room.send({ type: 'notice', message: $.body.message });\n\t$.success();\n}\n```\n\n## Klient\n\nKaždý klient je WebSocket controller s dátami HTTP upgrade požiadavky: `client.id`, `client.ip`, `client.user`, `client.query`, `client.params`, `client.headers`, `client.url`, `client.ua`, `client.mobile`, `client.robot`, `client.language` a `client.latency`. `client.cookie(name)` prečíta cookie. Ak budeš neskôr potrebovať vlastné dáta, ulož si ich na objekt:\n\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n## Autorizácia, CSRF a middleware\n\nPredtým, ako sa klient prijme, framework zavolá tvoj autorizačný delegát (pozri [Autorizácia](../authorization/)). Používateľ, ktorého vráti, je v `client.user`. Trasa deklarovaná s `+SOCKET` prijíma iba prihlásených používateľov a `-SOCKET` iba anonymných; klient, ktorý nezodpovedá žiadnej trase, dostane handshake a potom sa zatvorí s kódom `4001`, takže prehliadač uvidí normálnu udalosť `close` s týmto kódom a môže napríklad používateľa požiadať, aby sa prihlásil:\n\n```js\nROUTE('+SOCKET /notifications/', notifications);\n```\n\nFlag `@csrf` vyžaduje platný CSRF token v hlavičke `x-csrf-token` alebo v argumente query `?csrf=` (prehliadače nedokážu nastaviť hlavičky na WebSockete, takže použi query). Middleware deklarovaný cez `#name` beží pred upgradom spojenia (pozri [Middleware](../middleware/)). Požiadavky z IP adries v `CONF.$blacklist` sa odmietnu.\n\n## Zatváranie a upratovanie\n\n`client.close([code], [message])` zatvorí jedného klienta, `websocket.close([code], [message])` zatvorí všetkých. Predvolený kód je `1000`. Správa väčšia ako veľkosť trasy zatvorí klienta s `1009`; neplatné komprimované dáta s `1003`.\n\n`websocket.destroy()` zatvorí všetkých klientov, vyšle `destroy` a odstráni objekt; ďalší klient, ktorý sa pripojí, spustí akciu znova. `websocket.autodestroy([callback])` to urobí za teba 5 sekúnd po odchode posledného klienta, čo je bežná voľba pre dynamické miestnosti:\n\n```js\nfunction room() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tself.send({ type: 'tick' });\n\t}, 1000);\n\tself.autodestroy(function() {\n\t\tclearInterval(timer);\n\t});\n}\n```\n\nGlobálna udalosť `websocket_end` sa vyšle, keď sa odpojí ktorýkoľvek klient: `ON('websocket_end', function(websocket, client) {})`.\n\n## Kompresia a kódovanie\n\nKeď prehliadač ponúkne `permessage-deflate` a `CONF.$wscompress` je `true` (predvolené), správy sa komprimujú v oboch smeroch, textové aj binárne (`@binary`) správy. Chyba kompresie sa dostane do udalosti `error` objektu WebSocket. Ďalšie dve voľby menia každú správu:\n\n- `CONF.$wsencodedecode = true` posiela správy cez `encodeURIComponent()` a prichádzajúce správy dekóduje cez `decodeURIComponent()`.\n- `websocket.encrypt()` šifruje odchádzajúce a dešifruje prichádzajúce správy skupiny pomocou `CONF.secret_encryption`. Obe strany musia používať ten istý kľúč.\n\n## Ping a latencia\n\nTrikrát za minútu (v 15., 30. a 60. sekunde každej minúty) framework pingne všetkých klientov všetkých WebSocket trás a z pongu zmeria `client.latency`. Pred každým pingom skontroluje klientov: klient, ktorý neodpovedal na predchádzajúci ping, alebo ktorého latencia je vyššia ako `CONF.$wsmaxlatency` (2000 ms), sa zatvorí. Takto sa mŕtve spojenia odstránia bez tvojho kódu.\n\n`client.ping()` pingne jedného klienta sám.\n\n## Odstránenie trasy\n\n`ROUTE()` vráti trasu. `route.remove()` ju odstráni a zničí všetky jej objekty WebSocket, takže sa odpojí každý klient:\n\n```js\nvar route = ROUTE('SOCKET /live/', live);\n\n// later\nroute.remove();\n```\n\n## WebSocket klient\n\n`WEBSOCKETCLIENT([callback])` pripojí tvoju aplikáciu k inému WebSocket serveru. Nastav voľby a udalosti a potom zavolaj `connect()`:\n\n```js\nvar client = WEBSOCKETCLIENT();\n\nclient.options.reconnect = 5000;\nclient.headers['x-token'] = CONF.token;\n\nclient.on('open', function() {\n\tclient.send({ type: 'hello' });\n});\n\nclient.on('message', function(message) {\n\tconsole.log(message);\n});\n\nclient.on('close', function(code, reason) {\n\tconsole.log('closed', code, reason);\n});\n\nclient.connect('wss://example.com/live/');\n```\n\nVoľby `client.options`:\n\n| Voľba | Predvolené | Popis |\n| --- | --- | --- |\n| `type` | `'json'` | `'json'`, `'text'` alebo `'binary'` |\n| `compress` | `true` | Ponúkne serveru `permessage-deflate` |\n| `reconnect` | `3000` | Oneskorenie v ms pred opätovným pripojením po zatvorení spojenia; `0` ho vypne |\n| `reconnectserver` | | `true` sa pripojí znova aj vtedy, keď sa spojenie nedá otvoriť |\n| `masking` | `false` | Maskuje odchádzajúce rámce (vyžadujú to servery, ktoré striktne dodržiavajú RFC) |\n| `encodedecode` | `false` | Kóduje/dekóduje správy cez `encodeURIComponent()` |\n| `encrypt` | | Kľúč: správy sa ním šifrujú a dešifrujú |\n| `size` | `0` | Max. veľkosť dekomprimovanej správy v bajtoch (`0` bez limitu) |\n| `rejectunauthorized` | `false` | Odmieta neplatné TLS certifikáty |\n| `timeout` | `30000` | Oneskorenie TCP keep-alive pre socket v ms (`0` ho vypne) |\n\n`key`, `cert` a `dhparam` sa odovzdajú TLS spojeniu. `client.close([code], [message])` zatvorí spojenie a zastaví opätovné pripájanie; `client.close(code, true)` ho zatvorí a opätovné pripájanie ponechá. `client.ping([timeout])` pošle ping; keď pong nepríde do `timeout` ms (3000), klient vyšle `error` s chybou `Timeout`, zatvorí spojenie a pripojí sa znova. `client.latency` obsahuje posledný nameraný čas v ms.\n\n## Konfigurácia\n\n| Kľúč | Predvolené | Popis |\n| --- | --- | --- |\n| `$wsmaxsize` | `256` | Max. veľkosť správy v kB |\n| `$wscompress` | `true` | Povolí kompresiu `permessage-deflate` |\n| `$wsencodedecode` | `false` | Kóduje/dekóduje všetky správy URI kódovaním |\n| `$wsmaxlatency` | `2000` | Max. latencia v ms, po ktorej kontrola pingom zatvorí klienta |\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JaqmBV1vc60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/nosql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"NoSQL database","summary":"The embedded NoSQL database: NOSQL(name), files in databases/, inserting, finding, updating and removing documents with the query builder.","markdown":"---\ntitle: NoSQL database\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/nosql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# NoSQL database\n\n> The embedded NoSQL database: NOSQL(name), files in databases/, inserting, finding, updating and removing documents with the query builder.\n\nTotal.js 5 includes a small embedded **NoSQL** database. It needs no server and no driver: each database is a text file in the `databases/` directory with one JSON document per line. It is a good fit for settings, logs, small catalogs and prototypes.\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', age: 33, dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\t// response is an array of documents\n});\n```\n\n`NOSQL(name)` returns a small object with the methods `insert()`, `find()`, `read()`, `update()` (alias `modify()`), `remove()`, `clear()` and `clean()`. Each of them returns a **query builder** where you add filters and options and then read the result with `.callback()` or `.promise()`. The full list is in the reference [NoSQL database](../../reference/nosql/).\n\n## Files in databases/\n\n`NOSQL('users')` uses the file `databases/users.nosql` in the root of the application. The directory and the file are created when they are needed, so you do not have to prepare anything. Use the configuration key `$dirdatabases` to move the directory somewhere else.\n\nA name that contains a slash is used as a file path as it is, without the `.nosql` extension:\n\n```js\nNOSQL('/data/shared/orders.nosql').find().callback(console.log);\n```\n\nThe file is plain text. Every insert appends a new line with the JSON document. A removed document stays in the file and its line is marked with `-` at the beginning; such lines are skipped by every read. An update that keeps the same length rewrites the line in place; otherwise the old line is marked as removed and the new version is appended at the end. Call `clean()` from time to time to drop the marked lines and make the file smaller.\n\nAll operations on one file go through a queue: writes (insert, update, remove) run one after another and never at the same time as `clear()` or `clean()`; up to three reads can run at the same time.\n\n## Inserting\n\n`insert(doc)` appends the document. NoSQL does not generate any identifier, so add your own `id` (for example with `UID()`). The response is `1`.\n\n```js\nNOSQL('products').insert({ id: UID(), name: 'Keyboard', price: 49.9, tags: ['usb', 'black'], dtcreated: NOW }).callback(function(err, response) {\n\tconsole.log('inserted', response);\n});\n```\n\nDates are stored as ISO strings and every read converts them back to `Date` objects, so you can compare them and sort by them.\n\n## Finding documents\n\n`find()` returns all documents that match the filter as an array (an empty array when nothing matches). `read()` returns one document, or `undefined` when nothing matches.\n\nWithout `sort()`, documents come from the end of the file: the most recently written first. Add `sort()` when the order matters.\n\n```js\nNOSQL('products').find().where('price', '<', 100).in('tags', ['usb']).fields('id,name,price').sort('price', true).take(20).callback(function(err, items) {\n\tconsole.log(items);\n});\n\nNOSQL('products').read().id('1abc8d001').callback(function(err, product) {\n\tconsole.log(product ? product.name : 'not found');\n});\n```\n\n### Filters\n\nEvery filter is joined with AND. Field names can be nested with a dot (`address.city`).\n\n| Method | Matches when |\n| --- | --- |\n| `where(name, [comparer], value)` | the field compares with the value; comparers `=` (default), `<>`, `!=`, `>`, `>=`, `<`, `<=` |\n| `id(value)`, `userid(value)` | the `id` or `userid` field equals the value (an array means \"one of\") |\n| `equal(obj)` | every key of the object equals its value |\n| `in(name, values)`, `notin(name, values)` | the field is (or is not) one of the values; an array field matches when any item is one of them |\n| `between(name, a, b)` | the field is `>= a` and `<= b` |\n| `search(name, text, [where])` | the field contains the text (case-insensitive); `where` is `'beg'` or `'end'` |\n| `contains(name)`, `empty(name)` | the field has a value (a non-empty array), or it does not |\n| `year()`, `month()`, `day()` | a part of a `Date` field compares with a number |\n| `query(code)` | a JavaScript expression with `doc` is true |\n\n`or(fn)` groups the filters added inside the function with OR:\n\n```js\nNOSQL('users').find().where('active', true).or(function(builder) {\n\tbuilder.search('name', 'peter');\n\tbuilder.search('email', 'peter');\n}).callback(console.log);\n```\n\n`query()` (and `where()` with only one argument) takes a raw JavaScript condition. The document is `doc`. Do not put user input into it.\n\n```js\nNOSQL('orders').find().query('doc.items.length > 2 && doc.price > 100').callback(console.log);\n```\n\n### Fields, sorting and paging\n\n- `fields('id,name,price')` returns only these fields; `fields('-password,-token')` returns everything except these fields.\n- `sort(name, [desc])` sorts by a field; call it again for a second key. `desc` is `true` or `'desc'`.\n- `take(count)` (alias `limit()`), `skip(count)` and `first()` limit the result. `first()` returns one object instead of an array.\n- `page(page, limit)` and `paginate(page, limit, maxlimit)` compute `skip` and `take` from a page number, which is handy with values from the query string.\n\n```js\nfunction list($) {\n\tNOSQL('articles').find().where('published', true).sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n}\n```\n\n## Updating\n\n`update(data)` (alias `modify()`) changes the documents that match the filter. Only the keys of `data` are written; other fields stay. The response is the number of updated documents.\n\n```js\nNOSQL('products').update({ price: 39.9, dtupdated: NOW }).id('1abc8d001').callback(function(err, count) {\n\tconsole.log('updated', count);\n});\n```\n\nA prefix in a key changes how the value is applied:\n\n| Key | Effect |\n| --- | --- |\n| `'+stock': 5` | adds the number to the field (a missing field counts as `0`) |\n| `'-stock': 1`, `'*price': 1.1`, `'/price': 2` | subtracts, multiplies or divides the field by the number |\n| `'>maxorder': 3` | writes the value only when it is greater than the field (a missing field takes it) |\n| `'<minprice': 9` | writes the value only when it is smaller than the field |\n| `'!active': 1` | toggles a boolean field (the value is ignored) |\n| `'=total': 'doc.price * doc.count'` | evaluates a JavaScript expression with `doc` |\n\n```js\nNOSQL('products').update({ '+stock': -1, '+sold': 1 }).id(id).callback(console.log);\n```\n\nIn `insert()` the prefixes are removed: `'+stock': 5` stores `stock: 5` and `'!active'` stores `true`.\n\n## Removing and maintenance\n\n`remove()` removes the documents that match the filter and responds with their count. Without a filter it removes all documents.\n\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(function(err, count) {\n\tconsole.log('removed', count);\n});\n```\n\n- `clear()` deletes the whole file with all documents.\n- `clean()` rewrites the file without the lines of removed and replaced documents.\n\n```js\nON('service', function(counter) {\n\t// once a day\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n## Getting the result\n\nAll builders end in the same way:\n\n- `callback(fn)` (alias `pipe()`) calls `fn(err, response)`. In an action you can pass `$`, and the response goes straight to the client.\n- `promise([$])` returns a Promise; with `$` an error goes to `$.invalid()`.\n- `done($, fn)` calls `fn(response)` and sends an error to `$.invalid()`.\n- `data(fn)` and `fail(fn)` are called only with the response or only with the error.\n- `error(message)` turns an empty result (`undefined`, an empty array, `0` updated or removed) into an error.\n\n```js\nNEWACTION('Products/detail', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await NOSQL('products').read().id($.params.id).error('Not found').promise($);\n\t\t$.callback(item);\n\t}\n});\n```\n\n`debug()` prints the compiled filter to the console. The operation runs on the next tick, so add every filter and option in the same synchronous chain.\n\n## NoSQL through DATA\n\nNoSQL is also an engine of the global query builder `DATA` under the name `nosql`: `DATA.find('nosql/users')` is the same as `NOSQL('users').find()`. `DATA` adds a few reads that `NOSQL()` does not have:\n\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\t// response.count\n});\n\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\t// exists is true or false\n});\n\nDATA.scalar('nosql/orders', 'sum', 'price').callback(function(err, response) {\n\t// response.value\n});\n\nDATA.list('nosql/orders').page(2, 20).callback(function(err, response) {\n\t// response.items, response.count (all matching documents), response.page, response.pages\n});\n```\n\n`scalar()` computes `sum`, `min`, `max`, `avg` and `count` of a field; without a field it counts the documents. `list()` reads one page and the total `count` of the matching documents.\n\nFor `DATA` with SQL databases see [QueryBuilder](../../guides/querybuilder/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JaqmBV1vc60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/nosql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"NoSQL-Datenbank","summary":"Die eingebettete NoSQL-Datenbank: NOSQL(name), Dateien in databases/, Einfügen, Finden, Aktualisieren und Entfernen von Dokumenten mit dem Query Builder.","markdown":"---\ntitle: NoSQL-Datenbank\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/nosql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# NoSQL-Datenbank\n\n> Die eingebettete NoSQL-Datenbank: NOSQL(name), Dateien in databases/, Einfügen, Finden, Aktualisieren und Entfernen von Dokumenten mit dem Query Builder.\n\nTotal.js 5 enthält eine kleine eingebettete **NoSQL**-Datenbank. Sie braucht keinen Server und keinen Treiber: Jede Datenbank ist eine Textdatei im Verzeichnis `databases/` mit einem JSON-Dokument pro Zeile. Sie eignet sich gut für Einstellungen, Logs, kleine Kataloge und Prototypen.\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', age: 33, dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\t// response is an array of documents\n});\n```\n\n`NOSQL(name)` gibt ein kleines Objekt mit den Methoden `insert()`, `find()`, `read()`, `update()` (Alias `modify()`), `remove()`, `clear()` und `clean()` zurück. Jede davon gibt einen **Query Builder** zurück, an dem du Filter und Optionen hinzufügst und dann das Ergebnis mit `.callback()` oder `.promise()` liest. Die vollständige Liste steht in der Referenz [NoSQL-Datenbank](../../reference/nosql/).\n\n## Dateien in databases/\n\n`NOSQL('users')` verwendet die Datei `databases/users.nosql` im Stammverzeichnis der Anwendung. Das Verzeichnis und die Datei werden erstellt, wenn sie gebraucht werden, du musst also nichts vorbereiten. Mit dem Konfigurationsschlüssel `$dirdatabases` verschiebst du das Verzeichnis an einen anderen Ort.\n\nEin Name, der einen Schrägstrich enthält, wird so, wie er ist, als Dateipfad verwendet, ohne die Endung `.nosql`:\n\n```js\nNOSQL('/data/shared/orders.nosql').find().callback(console.log);\n```\n\nDie Datei ist reiner Text. Jedes Einfügen hängt eine neue Zeile mit dem JSON-Dokument an. Ein entferntes Dokument bleibt in der Datei, und seine Zeile wird am Anfang mit `-` markiert; solche Zeilen werden von jedem Lesevorgang übersprungen. Eine Aktualisierung, die dieselbe Länge behält, schreibt die Zeile an Ort und Stelle neu; andernfalls wird die alte Zeile als entfernt markiert und die neue Version am Ende angehängt. Rufe von Zeit zu Zeit `clean()` auf, um die markierten Zeilen zu verwerfen und die Datei kleiner zu machen.\n\nAlle Operationen auf einer Datei laufen über eine Warteschlange: Schreibvorgänge (Einfügen, Aktualisieren, Entfernen) laufen nacheinander und nie gleichzeitig mit `clear()` oder `clean()`; bis zu drei Lesevorgänge können gleichzeitig laufen.\n\n## Einfügen\n\n`insert(doc)` hängt das Dokument an. NoSQL erzeugt keine Kennung, also füge deine eigene `id` hinzu (zum Beispiel mit `UID()`). Die Antwort ist `1`.\n\n```js\nNOSQL('products').insert({ id: UID(), name: 'Keyboard', price: 49.9, tags: ['usb', 'black'], dtcreated: NOW }).callback(function(err, response) {\n\tconsole.log('inserted', response);\n});\n```\n\nDatumswerte werden als ISO-Strings gespeichert, und jeder Lesevorgang wandelt sie zurück in `Date`-Objekte, sodass du sie vergleichen und nach ihnen sortieren kannst.\n\n## Dokumente finden\n\n`find()` gibt alle Dokumente, die zum Filter passen, als Array zurück (ein leeres Array, wenn nichts passt). `read()` gibt ein Dokument zurück, oder `undefined`, wenn nichts passt.\n\nOhne `sort()` kommen die Dokumente vom Ende der Datei: die zuletzt geschriebenen zuerst. Füge `sort()` hinzu, wenn die Reihenfolge wichtig ist.\n\n```js\nNOSQL('products').find().where('price', '<', 100).in('tags', ['usb']).fields('id,name,price').sort('price', true).take(20).callback(function(err, items) {\n\tconsole.log(items);\n});\n\nNOSQL('products').read().id('1abc8d001').callback(function(err, product) {\n\tconsole.log(product ? product.name : 'not found');\n});\n```\n\n### Filter\n\nAlle Filter werden mit UND verknüpft. Feldnamen können mit einem Punkt verschachtelt werden (`address.city`).\n\n| Methode | Passt, wenn |\n| --- | --- |\n| `where(name, [comparer], value)` | das Feld mit dem Wert verglichen zutrifft; Vergleichsoperatoren `=` (Standard), `<>`, `!=`, `>`, `>=`, `<`, `<=` |\n| `id(value)`, `userid(value)` | das Feld `id` oder `userid` gleich dem Wert ist (ein Array bedeutet „einer davon“) |\n| `equal(obj)` | jeder Schlüssel des Objekts gleich seinem Wert ist |\n| `in(name, values)`, `notin(name, values)` | das Feld einer der Werte ist (oder nicht ist); ein Array-Feld passt, wenn irgendein Element einer davon ist |\n| `between(name, a, b)` | das Feld `>= a` und `<= b` ist |\n| `search(name, text, [where])` | das Feld den Text enthält (ohne Unterscheidung von Groß- und Kleinschreibung); `where` ist `'beg'` oder `'end'` |\n| `contains(name)`, `empty(name)` | das Feld einen Wert hat (ein nicht leeres Array) oder keinen |\n| `year()`, `month()`, `day()` | ein Teil eines `Date`-Feldes mit einer Zahl verglichen zutrifft |\n| `query(code)` | ein JavaScript-Ausdruck mit `doc` wahr ist |\n\n`or(fn)` gruppiert die innerhalb der Funktion hinzugefügten Filter mit ODER:\n\n```js\nNOSQL('users').find().where('active', true).or(function(builder) {\n\tbuilder.search('name', 'peter');\n\tbuilder.search('email', 'peter');\n}).callback(console.log);\n```\n\n`query()` (und `where()` mit nur einem Argument) nimmt eine rohe JavaScript-Bedingung. Das Dokument ist `doc`. Setze keine Benutzereingaben hinein.\n\n```js\nNOSQL('orders').find().query('doc.items.length > 2 && doc.price > 100').callback(console.log);\n```\n\n### Felder, Sortieren und Seiten\n\n- `fields('id,name,price')` gibt nur diese Felder zurück; `fields('-password,-token')` gibt alles außer diesen Feldern zurück.\n- `sort(name, [desc])` sortiert nach einem Feld; rufe es für einen zweiten Schlüssel erneut auf. `desc` ist `true` oder `'desc'`.\n- `take(count)` (Alias `limit()`), `skip(count)` und `first()` begrenzen das Ergebnis. `first()` gibt ein Objekt statt eines Arrays zurück.\n- `page(page, limit)` und `paginate(page, limit, maxlimit)` berechnen `skip` und `take` aus einer Seitenzahl, was mit Werten aus dem Query String praktisch ist.\n\n```js\nfunction list($) {\n\tNOSQL('articles').find().where('published', true).sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n}\n```\n\n## Aktualisieren\n\n`update(data)` (Alias `modify()`) ändert die Dokumente, die zum Filter passen. Nur die Schlüssel von `data` werden geschrieben; andere Felder bleiben. Die Antwort ist die Anzahl der aktualisierten Dokumente.\n\n```js\nNOSQL('products').update({ price: 39.9, dtupdated: NOW }).id('1abc8d001').callback(function(err, count) {\n\tconsole.log('updated', count);\n});\n```\n\nEin Präfix in einem Schlüssel ändert, wie der Wert angewendet wird:\n\n| Schlüssel | Wirkung |\n| --- | --- |\n| `'+stock': 5` | addiert die Zahl zum Feld (ein fehlendes Feld zählt als `0`) |\n| `'-stock': 1`, `'*price': 1.1`, `'/price': 2` | subtrahiert die Zahl vom Feld, multipliziert oder dividiert das Feld durch sie |\n| `'>maxorder': 3` | schreibt den Wert nur, wenn er größer als das Feld ist (ein fehlendes Feld übernimmt ihn) |\n| `'<minprice': 9` | schreibt den Wert nur, wenn er kleiner als das Feld ist |\n| `'!active': 1` | schaltet ein boolesches Feld um (der Wert wird ignoriert) |\n| `'=total': 'doc.price * doc.count'` | wertet einen JavaScript-Ausdruck mit `doc` aus |\n\n```js\nNOSQL('products').update({ '+stock': -1, '+sold': 1 }).id(id).callback(console.log);\n```\n\nIn `insert()` werden die Präfixe entfernt: `'+stock': 5` speichert `stock: 5` und `'!active'` speichert `true`.\n\n## Entfernen und Wartung\n\n`remove()` entfernt die Dokumente, die zum Filter passen, und antwortet mit ihrer Anzahl. Ohne Filter entfernt es alle Dokumente.\n\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(function(err, count) {\n\tconsole.log('removed', count);\n});\n```\n\n- `clear()` löscht die ganze Datei mit allen Dokumenten.\n- `clean()` schreibt die Datei ohne die Zeilen entfernter und ersetzter Dokumente neu.\n\n```js\nON('service', function(counter) {\n\t// once a day\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n## Das Ergebnis erhalten\n\nAlle Builder enden auf dieselbe Weise:\n\n- `callback(fn)` (Alias `pipe()`) ruft `fn(err, response)` auf. In einer Aktion kannst du `$` übergeben, und die Antwort geht direkt an den Client.\n- `promise([$])` gibt ein Promise zurück; mit `$` geht ein Fehler an `$.invalid()`.\n- `done($, fn)` ruft `fn(response)` auf und sendet einen Fehler an `$.invalid()`.\n- `data(fn)` und `fail(fn)` werden nur mit der Antwort oder nur mit dem Fehler aufgerufen.\n- `error(message)` macht aus einem leeren Ergebnis (`undefined`, ein leeres Array, `0` aktualisierte oder entfernte) einen Fehler.\n\n```js\nNEWACTION('Products/detail', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await NOSQL('products').read().id($.params.id).error('Not found').promise($);\n\t\t$.callback(item);\n\t}\n});\n```\n\n`debug()` gibt den kompilierten Filter in der Konsole aus. Die Operation läuft im nächsten Tick, also füge jeden Filter und jede Option in derselben synchronen Kette hinzu.\n\n## NoSQL über DATA\n\nNoSQL ist außerdem eine Engine des globalen Query Builders `DATA` unter dem Namen `nosql`: `DATA.find('nosql/users')` ist dasselbe wie `NOSQL('users').find()`. `DATA` bietet ein paar Lesevorgänge, die `NOSQL()` nicht hat:\n\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\t// response.count\n});\n\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\t// exists is true or false\n});\n\nDATA.scalar('nosql/orders', 'sum', 'price').callback(function(err, response) {\n\t// response.value\n});\n\nDATA.list('nosql/orders').page(2, 20).callback(function(err, response) {\n\t// response.items, response.count (all matching documents), response.page, response.pages\n});\n```\n\n`scalar()` berechnet `sum`, `min`, `max`, `avg` und `count` eines Feldes; ohne Feld zählt es die Dokumente. `list()` liest eine Seite und die Gesamtzahl `count` der passenden Dokumente.\n\nFür `DATA` mit SQL-Datenbanken siehe [QueryBuilder](../../guides/querybuilder/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JaqmBV1vc60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/nosql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Base de datos NoSQL","summary":"La base de datos NoSQL integrada: NOSQL(name), archivos en databases/, insertar, buscar, actualizar y eliminar documentos con el query builder.","markdown":"---\ntitle: Base de datos NoSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/nosql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# Base de datos NoSQL\n\n> La base de datos NoSQL integrada: NOSQL(name), archivos en databases/, insertar, buscar, actualizar y eliminar documentos con el query builder.\n\nTotal.js 5 incluye una pequeña base de datos **NoSQL** integrada. No necesita servidor ni driver: cada base de datos es un archivo de texto en el directorio `databases/` con un documento JSON por línea. Encaja bien para ajustes, logs, catálogos pequeños y prototipos.\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', age: 33, dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\t// response is an array of documents\n});\n```\n\n`NOSQL(name)` devuelve un pequeño objeto con los métodos `insert()`, `find()`, `read()`, `update()` (alias `modify()`), `remove()`, `clear()` y `clean()`. Cada uno devuelve un **query builder** al que añades filtros y opciones, y luego lees el resultado con `.callback()` o `.promise()`. La lista completa está en la referencia [Base de datos NoSQL](../../reference/nosql/).\n\n## Archivos en databases/\n\n`NOSQL('users')` usa el archivo `databases/users.nosql` en la raíz de la aplicación. El directorio y el archivo se crean cuando hacen falta, así que no tienes que preparar nada. Usa la clave de configuración `$dirdatabases` para mover el directorio a otro sitio.\n\nUn nombre que contiene una barra se usa tal cual como ruta de archivo, sin la extensión `.nosql`:\n\n```js\nNOSQL('/data/shared/orders.nosql').find().callback(console.log);\n```\n\nEl archivo es texto plano. Cada inserción añade una línea nueva con el documento JSON. Un documento eliminado se queda en el archivo y su línea se marca con `-` al principio; todas las lecturas se saltan esas líneas. Una actualización que mantiene la misma longitud reescribe la línea en su sitio; si no, la línea antigua se marca como eliminada y la nueva versión se añade al final. Llama a `clean()` de vez en cuando para quitar las líneas marcadas y hacer el archivo más pequeño.\n\nTodas las operaciones sobre un archivo pasan por una cola: las escrituras (insert, update, remove) se ejecutan una tras otra y nunca a la vez que `clear()` o `clean()`; se pueden ejecutar hasta tres lecturas a la vez.\n\n## Insertar\n\n`insert(doc)` añade el documento. NoSQL no genera ningún identificador, así que añade tu propio `id` (por ejemplo con `UID()`). La respuesta es `1`.\n\n```js\nNOSQL('products').insert({ id: UID(), name: 'Keyboard', price: 49.9, tags: ['usb', 'black'], dtcreated: NOW }).callback(function(err, response) {\n\tconsole.log('inserted', response);\n});\n```\n\nLas fechas se guardan como strings ISO y cada lectura las vuelve a convertir en objetos `Date`, así puedes compararlas y ordenar por ellas.\n\n## Buscar documentos\n\n`find()` devuelve como array todos los documentos que cumplen el filtro (un array vacío cuando ninguno lo cumple). `read()` devuelve un documento, o `undefined` cuando ninguno lo cumple.\n\nSin `sort()`, los documentos vienen desde el final del archivo: primero los escritos más recientemente. Añade `sort()` cuando el orden importe.\n\n```js\nNOSQL('products').find().where('price', '<', 100).in('tags', ['usb']).fields('id,name,price').sort('price', true).take(20).callback(function(err, items) {\n\tconsole.log(items);\n});\n\nNOSQL('products').read().id('1abc8d001').callback(function(err, product) {\n\tconsole.log(product ? product.name : 'not found');\n});\n```\n\n### Filtros\n\nTodos los filtros se unen con AND. Los nombres de campo pueden anidarse con un punto (`address.city`).\n\n| Método | Coincide cuando |\n| --- | --- |\n| `where(name, [comparer], value)` | el campo se compara con el valor; comparadores `=` (por defecto), `<>`, `!=`, `>`, `>=`, `<`, `<=` |\n| `id(value)`, `userid(value)` | el campo `id` o `userid` es igual al valor (un array significa \"uno de\") |\n| `equal(obj)` | cada clave del objeto es igual a su valor |\n| `in(name, values)`, `notin(name, values)` | el campo es (o no es) uno de los valores; un campo array coincide cuando alguno de sus elementos es uno de ellos |\n| `between(name, a, b)` | el campo es `>= a` y `<= b` |\n| `search(name, text, [where])` | el campo contiene el texto (sin distinguir mayúsculas y minúsculas); `where` es `'beg'` o `'end'` |\n| `contains(name)`, `empty(name)` | el campo tiene un valor (un array no vacío), o no lo tiene |\n| `year()`, `month()`, `day()` | una parte de un campo `Date` se compara con un número |\n| `query(code)` | una expresión JavaScript con `doc` es verdadera |\n\n`or(fn)` agrupa con OR los filtros añadidos dentro de la función:\n\n```js\nNOSQL('users').find().where('active', true).or(function(builder) {\n\tbuilder.search('name', 'peter');\n\tbuilder.search('email', 'peter');\n}).callback(console.log);\n```\n\n`query()` (y `where()` con un solo argumento) recibe una condición JavaScript en bruto. El documento es `doc`. No metas en ella datos del usuario.\n\n```js\nNOSQL('orders').find().query('doc.items.length > 2 && doc.price > 100').callback(console.log);\n```\n\n### Campos, ordenación y paginación\n\n- `fields('id,name,price')` devuelve solo estos campos; `fields('-password,-token')` devuelve todo excepto estos campos.\n- `sort(name, [desc])` ordena por un campo; llámalo otra vez para una segunda clave. `desc` es `true` o `'desc'`.\n- `take(count)` (alias `limit()`), `skip(count)` y `first()` limitan el resultado. `first()` devuelve un objeto en lugar de un array.\n- `page(page, limit)` y `paginate(page, limit, maxlimit)` calculan `skip` y `take` a partir de un número de página, algo práctico con valores del query string.\n\n```js\nfunction list($) {\n\tNOSQL('articles').find().where('published', true).sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n}\n```\n\n## Actualizar\n\n`update(data)` (alias `modify()`) cambia los documentos que cumplen el filtro. Solo se escriben las claves de `data`; los demás campos se quedan como están. La respuesta es el número de documentos actualizados.\n\n```js\nNOSQL('products').update({ price: 39.9, dtupdated: NOW }).id('1abc8d001').callback(function(err, count) {\n\tconsole.log('updated', count);\n});\n```\n\nUn prefijo en una clave cambia cómo se aplica el valor:\n\n| Clave | Efecto |\n| --- | --- |\n| `'+stock': 5` | suma el número al campo (un campo que falta cuenta como `0`) |\n| `'-stock': 1`, `'*price': 1.1`, `'/price': 2` | resta, multiplica o divide el campo por el número |\n| `'>maxorder': 3` | escribe el valor solo cuando es mayor que el campo (un campo que falta lo recibe) |\n| `'<minprice': 9` | escribe el valor solo cuando es menor que el campo |\n| `'!active': 1` | invierte un campo booleano (el valor se ignora) |\n| `'=total': 'doc.price * doc.count'` | evalúa una expresión JavaScript con `doc` |\n\n```js\nNOSQL('products').update({ '+stock': -1, '+sold': 1 }).id(id).callback(console.log);\n```\n\nEn `insert()` los prefijos se quitan: `'+stock': 5` guarda `stock: 5` y `'!active'` guarda `true`.\n\n## Eliminar y mantenimiento\n\n`remove()` elimina los documentos que cumplen el filtro y responde con su número. Sin filtro elimina todos los documentos.\n\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(function(err, count) {\n\tconsole.log('removed', count);\n});\n```\n\n- `clear()` borra el archivo entero con todos los documentos.\n- `clean()` reescribe el archivo sin las líneas de los documentos eliminados y sustituidos.\n\n```js\nON('service', function(counter) {\n\t// once a day\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n## Obtener el resultado\n\nTodos los builders terminan de la misma forma:\n\n- `callback(fn)` (alias `pipe()`) llama a `fn(err, response)`. En una acción puedes pasar `$`, y la respuesta va directamente al cliente.\n- `promise([$])` devuelve una Promise; con `$` un error va a `$.invalid()`.\n- `done($, fn)` llama a `fn(response)` y envía un error a `$.invalid()`.\n- `data(fn)` y `fail(fn)` se llaman solo con la respuesta o solo con el error.\n- `error(message)` convierte un resultado vacío (`undefined`, un array vacío, `0` actualizados o eliminados) en un error.\n\n```js\nNEWACTION('Products/detail', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await NOSQL('products').read().id($.params.id).error('Not found').promise($);\n\t\t$.callback(item);\n\t}\n});\n```\n\n`debug()` imprime en la consola el filtro compilado. La operación se ejecuta en el siguiente tick, así que añade todos los filtros y opciones en la misma cadena síncrona.\n\n## NoSQL a través de DATA\n\nNoSQL también es un motor del query builder global `DATA` con el nombre `nosql`: `DATA.find('nosql/users')` es lo mismo que `NOSQL('users').find()`. `DATA` añade algunas lecturas que `NOSQL()` no tiene:\n\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\t// response.count\n});\n\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\t// exists is true or false\n});\n\nDATA.scalar('nosql/orders', 'sum', 'price').callback(function(err, response) {\n\t// response.value\n});\n\nDATA.list('nosql/orders').page(2, 20).callback(function(err, response) {\n\t// response.items, response.count (all matching documents), response.page, response.pages\n});\n```\n\n`scalar()` calcula `sum`, `min`, `max`, `avg` y `count` de un campo; sin campo cuenta los documentos. `list()` lee una página y el `count` total de los documentos que cumplen el filtro.\n\nPara `DATA` con bases de datos SQL consulta [QueryBuilder](../../guides/querybuilder/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JaqmBV1vc60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/nosql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Base de données NoSQL","summary":"La base de données NoSQL intégrée : NOSQL(name), les fichiers dans databases/, l'insertion, la recherche, la mise à jour et la suppression de documents avec le query builder.","markdown":"---\ntitle: \"Base de données NoSQL\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/nosql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# Base de données NoSQL\n\n> La base de données NoSQL intégrée : NOSQL(name), les fichiers dans databases/, l'insertion, la recherche, la mise à jour et la suppression de documents avec le query builder.\n\nTotal.js 5 inclut une petite base de données **NoSQL** intégrée. Elle n'a besoin ni de serveur ni de driver : chaque base de données est un fichier texte dans le répertoire `databases/`, avec un document JSON par ligne. Elle convient bien aux réglages, aux logs, aux petits catalogues et aux prototypes.\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', age: 33, dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\t// response is an array of documents\n});\n```\n\n`NOSQL(name)` renvoie un petit objet avec les méthodes `insert()`, `find()`, `read()`, `update()` (alias `modify()`), `remove()`, `clear()` et `clean()`. Chacune renvoie un **query builder** auquel tu ajoutes des filtres et des options, puis tu lis le résultat avec `.callback()` ou `.promise()`. La liste complète se trouve dans la référence [Base de données NoSQL](../../reference/nosql/).\n\n## Les fichiers dans databases/\n\n`NOSQL('users')` utilise le fichier `databases/users.nosql` à la racine de l'application. Le répertoire et le fichier sont créés quand ils sont nécessaires, tu n'as donc rien à préparer. Utilise la clé de configuration `$dirdatabases` pour déplacer le répertoire ailleurs.\n\nUn nom qui contient une barre oblique est utilisé tel quel comme chemin de fichier, sans l'extension `.nosql` :\n\n```js\nNOSQL('/data/shared/orders.nosql').find().callback(console.log);\n```\n\nLe fichier est du texte brut. Chaque insertion ajoute à la fin une nouvelle ligne avec le document JSON. Un document supprimé reste dans le fichier et sa ligne est marquée par `-` au début ; ces lignes sont ignorées par toutes les lectures. Une mise à jour qui garde la même longueur réécrit la ligne sur place ; sinon, l'ancienne ligne est marquée comme supprimée et la nouvelle version est ajoutée à la fin. Appelle `clean()` de temps en temps pour retirer les lignes marquées et rendre le fichier plus petit.\n\nToutes les opérations sur un fichier passent par une file : les écritures (insertion, mise à jour, suppression) s'exécutent l'une après l'autre et jamais en même temps que `clear()` ou `clean()` ; jusqu'à trois lectures peuvent s'exécuter en même temps.\n\n## Insérer\n\n`insert(doc)` ajoute le document à la fin. NoSQL ne génère aucun identifiant, alors ajoute ton propre `id` (par exemple avec `UID()`). La réponse est `1`.\n\n```js\nNOSQL('products').insert({ id: UID(), name: 'Keyboard', price: 49.9, tags: ['usb', 'black'], dtcreated: NOW }).callback(function(err, response) {\n\tconsole.log('inserted', response);\n});\n```\n\nLes dates sont stockées sous forme de chaînes ISO et chaque lecture les reconvertit en objets `Date` : tu peux donc les comparer et trier selon elles.\n\n## Trouver des documents\n\n`find()` renvoie tous les documents qui correspondent au filtre, sous forme de tableau (un tableau vide quand rien ne correspond). `read()` renvoie un document, ou `undefined` quand rien ne correspond.\n\nSans `sort()`, les documents viennent de la fin du fichier : les plus récemment écrits d'abord. Ajoute `sort()` quand l'ordre compte.\n\n```js\nNOSQL('products').find().where('price', '<', 100).in('tags', ['usb']).fields('id,name,price').sort('price', true).take(20).callback(function(err, items) {\n\tconsole.log(items);\n});\n\nNOSQL('products').read().id('1abc8d001').callback(function(err, product) {\n\tconsole.log(product ? product.name : 'not found');\n});\n```\n\n### Filtres\n\nTous les filtres sont combinés avec AND. Les noms de champs peuvent être imbriqués avec un point (`address.city`).\n\n| Méthode | Correspond quand |\n| --- | --- |\n| `where(name, [comparer], value)` | le champ se compare à la valeur ; comparateurs `=` (par défaut), `<>`, `!=`, `>`, `>=`, `<`, `<=` |\n| `id(value)`, `userid(value)` | le champ `id` ou `userid` est égal à la valeur (un tableau signifie « l'une de ») |\n| `equal(obj)` | chaque clé de l'objet est égale à sa valeur |\n| `in(name, values)`, `notin(name, values)` | le champ est (ou n'est pas) l'une des valeurs ; un champ tableau correspond quand l'un de ses éléments est l'une d'elles |\n| `between(name, a, b)` | le champ est `>= a` et `<= b` |\n| `search(name, text, [where])` | le champ contient le texte (sans tenir compte de la casse) ; `where` vaut `'beg'` ou `'end'` |\n| `contains(name)`, `empty(name)` | le champ a une valeur (un tableau non vide), ou n'en a pas |\n| `year()`, `month()`, `day()` | une partie d'un champ `Date` se compare à un nombre |\n| `query(code)` | une expression JavaScript avec `doc` est vraie |\n\n`or(fn)` regroupe avec OR les filtres ajoutés dans la fonction :\n\n```js\nNOSQL('users').find().where('active', true).or(function(builder) {\n\tbuilder.search('name', 'peter');\n\tbuilder.search('email', 'peter');\n}).callback(console.log);\n```\n\n`query()` (et `where()` avec un seul argument) prend une condition JavaScript brute. Le document est `doc`. N'y mets pas de saisie de l'utilisateur.\n\n```js\nNOSQL('orders').find().query('doc.items.length > 2 && doc.price > 100').callback(console.log);\n```\n\n### Champs, tri et pagination\n\n- `fields('id,name,price')` renvoie seulement ces champs ; `fields('-password,-token')` renvoie tout sauf ces champs.\n- `sort(name, [desc])` trie selon un champ ; appelle-la à nouveau pour une deuxième clé. `desc` vaut `true` ou `'desc'`.\n- `take(count)` (alias `limit()`), `skip(count)` et `first()` limitent le résultat. `first()` renvoie un seul objet au lieu d'un tableau.\n- `page(page, limit)` et `paginate(page, limit, maxlimit)` calculent `skip` et `take` à partir d'un numéro de page, ce qui est pratique avec les valeurs de la query string.\n\n```js\nfunction list($) {\n\tNOSQL('articles').find().where('published', true).sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n}\n```\n\n## Mettre à jour\n\n`update(data)` (alias `modify()`) modifie les documents qui correspondent au filtre. Seules les clés de `data` sont écrites ; les autres champs restent. La réponse est le nombre de documents mis à jour.\n\n```js\nNOSQL('products').update({ price: 39.9, dtupdated: NOW }).id('1abc8d001').callback(function(err, count) {\n\tconsole.log('updated', count);\n});\n```\n\nUn préfixe dans une clé change la façon dont la valeur est appliquée :\n\n| Clé | Effet |\n| --- | --- |\n| `'+stock': 5` | ajoute le nombre au champ (un champ manquant compte comme `0`) |\n| `'-stock': 1`, `'*price': 1.1`, `'/price': 2` | soustrait le nombre du champ, ou multiplie ou divise le champ par le nombre |\n| `'>maxorder': 3` | écrit la valeur seulement quand elle est plus grande que le champ (un champ manquant la prend) |\n| `'<minprice': 9` | écrit la valeur seulement quand elle est plus petite que le champ |\n| `'!active': 1` | inverse un champ booléen (la valeur est ignorée) |\n| `'=total': 'doc.price * doc.count'` | évalue une expression JavaScript avec `doc` |\n\n```js\nNOSQL('products').update({ '+stock': -1, '+sold': 1 }).id(id).callback(console.log);\n```\n\nDans `insert()`, les préfixes sont retirés : `'+stock': 5` stocke `stock: 5` et `'!active'` stocke `true`.\n\n## Suppression et maintenance\n\n`remove()` supprime les documents qui correspondent au filtre et répond avec leur nombre. Sans filtre, elle supprime tous les documents.\n\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(function(err, count) {\n\tconsole.log('removed', count);\n});\n```\n\n- `clear()` supprime tout le fichier avec tous les documents.\n- `clean()` réécrit le fichier sans les lignes des documents supprimés et remplacés.\n\n```js\nON('service', function(counter) {\n\t// once a day\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n## Obtenir le résultat\n\nTous les builders se terminent de la même façon :\n\n- `callback(fn)` (alias `pipe()`) appelle `fn(err, response)`. Dans une action, tu peux passer `$`, et la réponse va directement au client.\n- `promise([$])` renvoie une Promise ; avec `$`, une erreur va à `$.invalid()`.\n- `done($, fn)` appelle `fn(response)` et envoie une erreur à `$.invalid()`.\n- `data(fn)` et `fail(fn)` ne sont appelées qu'avec la réponse ou qu'avec l'erreur.\n- `error(message)` transforme un résultat vide (`undefined`, un tableau vide, `0` mis à jour ou supprimé) en erreur.\n\n```js\nNEWACTION('Products/detail', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await NOSQL('products').read().id($.params.id).error('Not found').promise($);\n\t\t$.callback(item);\n\t}\n});\n```\n\n`debug()` affiche le filtre compilé dans la console. L'opération s'exécute au tick suivant, alors ajoute chaque filtre et chaque option dans la même chaîne synchrone.\n\n## NoSQL via DATA\n\nNoSQL est aussi un moteur du query builder global `DATA`, sous le nom `nosql` : `DATA.find('nosql/users')` équivaut à `NOSQL('users').find()`. `DATA` ajoute quelques lectures que `NOSQL()` n'a pas :\n\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\t// response.count\n});\n\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\t// exists is true or false\n});\n\nDATA.scalar('nosql/orders', 'sum', 'price').callback(function(err, response) {\n\t// response.value\n});\n\nDATA.list('nosql/orders').page(2, 20).callback(function(err, response) {\n\t// response.items, response.count (all matching documents), response.page, response.pages\n});\n```\n\n`scalar()` calcule `sum`, `min`, `max`, `avg` et `count` d'un champ ; sans champ, elle compte les documents. `list()` lit une page et le `count` total des documents correspondants.\n\nPour `DATA` avec des bases de données SQL, voir [QueryBuilder](../../guides/querybuilder/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JaqmBV1vc60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/nosql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Database NoSQL","summary":"Il database NoSQL integrato: NOSQL(name), file in databases/, inserimento, ricerca, aggiornamento e rimozione di documenti con il query builder.","markdown":"---\ntitle: Database NoSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/nosql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# Database NoSQL\n\n> Il database NoSQL integrato: NOSQL(name), file in databases/, inserimento, ricerca, aggiornamento e rimozione di documenti con il query builder.\n\nTotal.js 5 include un piccolo database **NoSQL** integrato. Non ha bisogno di un server né di un driver: ogni database è un file di testo nella directory `databases/` con un documento JSON per riga. È adatto a impostazioni, log, piccoli cataloghi e prototipi.\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', age: 33, dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\t// response is an array of documents\n});\n```\n\n`NOSQL(name)` restituisce un piccolo oggetto con i metodi `insert()`, `find()`, `read()`, `update()` (alias `modify()`), `remove()`, `clear()` e `clean()`. Ognuno restituisce un **query builder** a cui aggiungi filtri e opzioni, e poi leggi il risultato con `.callback()` o `.promise()`. L'elenco completo è nel riferimento [Database NoSQL](../../reference/nosql/).\n\n## I file in databases/\n\n`NOSQL('users')` usa il file `databases/users.nosql` nella radice dell'applicazione. La directory e il file vengono creati quando servono, quindi non devi preparare nulla. Usa la chiave di configurazione `$dirdatabases` per spostare la directory altrove.\n\nUn nome che contiene una barra viene usato così com'è come percorso di file, senza l'estensione `.nosql`:\n\n```js\nNOSQL('/data/shared/orders.nosql').find().callback(console.log);\n```\n\nIl file è testo semplice. Ogni inserimento aggiunge in coda una nuova riga con il documento JSON. Un documento rimosso resta nel file e la sua riga viene marcata con `-` all'inizio; queste righe vengono saltate da ogni lettura. Un aggiornamento che mantiene la stessa lunghezza riscrive la riga sul posto; altrimenti la vecchia riga viene marcata come rimossa e la nuova versione viene aggiunta alla fine. Chiama `clean()` di tanto in tanto per eliminare le righe marcate e ridurre il file.\n\nTutte le operazioni su un file passano per una coda: le scritture (inserimento, aggiornamento, rimozione) vengono eseguite una dopo l'altra e mai insieme a `clear()` o `clean()`; possono essere eseguite fino a tre letture contemporaneamente.\n\n## Inserire\n\n`insert(doc)` aggiunge il documento in coda. NoSQL non genera alcun identificatore, quindi aggiungi tu un `id` (per esempio con `UID()`). La risposta è `1`.\n\n```js\nNOSQL('products').insert({ id: UID(), name: 'Keyboard', price: 49.9, tags: ['usb', 'black'], dtcreated: NOW }).callback(function(err, response) {\n\tconsole.log('inserted', response);\n});\n```\n\nLe date vengono salvate come stringhe ISO e ogni lettura le riconverte in oggetti `Date`, così puoi confrontarle e ordinare in base a esse.\n\n## Trovare documenti\n\n`find()` restituisce come array tutti i documenti che corrispondono al filtro (un array vuoto quando non corrisponde nulla). `read()` restituisce un documento, oppure `undefined` quando non corrisponde nulla.\n\nSenza `sort()`, i documenti arrivano dalla fine del file: prima quelli scritti più di recente. Aggiungi `sort()` quando l'ordine conta.\n\n```js\nNOSQL('products').find().where('price', '<', 100).in('tags', ['usb']).fields('id,name,price').sort('price', true).take(20).callback(function(err, items) {\n\tconsole.log(items);\n});\n\nNOSQL('products').read().id('1abc8d001').callback(function(err, product) {\n\tconsole.log(product ? product.name : 'not found');\n});\n```\n\n### Filtri\n\nTutti i filtri vengono uniti con AND. I nomi dei campi possono essere annidati con un punto (`address.city`).\n\n| Metodo | Corrisponde quando |\n| --- | --- |\n| `where(name, [comparer], value)` | il campo è confrontato con il valore; comparatori `=` (predefinito), `<>`, `!=`, `>`, `>=`, `<`, `<=` |\n| `id(value)`, `userid(value)` | il campo `id` o `userid` è uguale al valore (un array significa \"uno tra\") |\n| `equal(obj)` | ogni chiave dell'oggetto è uguale al suo valore |\n| `in(name, values)`, `notin(name, values)` | il campo è (o non è) uno dei valori; un campo array corrisponde quando uno qualsiasi dei suoi elementi è uno di essi |\n| `between(name, a, b)` | il campo è `>= a` e `<= b` |\n| `search(name, text, [where])` | il campo contiene il testo (senza distinzione tra maiuscole e minuscole); `where` è `'beg'` o `'end'` |\n| `contains(name)`, `empty(name)` | il campo ha un valore (un array non vuoto), oppure non lo ha |\n| `year()`, `month()`, `day()` | una parte di un campo `Date` è confrontata con un numero |\n| `query(code)` | un'espressione JavaScript con `doc` è vera |\n\n`or(fn)` raggruppa con OR i filtri aggiunti dentro la funzione:\n\n```js\nNOSQL('users').find().where('active', true).or(function(builder) {\n\tbuilder.search('name', 'peter');\n\tbuilder.search('email', 'peter');\n}).callback(console.log);\n```\n\n`query()` (e `where()` con un solo argomento) accetta una condizione JavaScript grezza. Il documento è `doc`. Non metterci input dell'utente.\n\n```js\nNOSQL('orders').find().query('doc.items.length > 2 && doc.price > 100').callback(console.log);\n```\n\n### Campi, ordinamento e paginazione\n\n- `fields('id,name,price')` restituisce solo questi campi; `fields('-password,-token')` restituisce tutto tranne questi campi.\n- `sort(name, [desc])` ordina per un campo; chiamalo di nuovo per una seconda chiave. `desc` è `true` o `'desc'`.\n- `take(count)` (alias `limit()`), `skip(count)` e `first()` limitano il risultato. `first()` restituisce un oggetto invece di un array.\n- `page(page, limit)` e `paginate(page, limit, maxlimit)` calcolano `skip` e `take` da un numero di pagina, cosa comoda con i valori della query string.\n\n```js\nfunction list($) {\n\tNOSQL('articles').find().where('published', true).sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n}\n```\n\n## Aggiornare\n\n`update(data)` (alias `modify()`) modifica i documenti che corrispondono al filtro. Vengono scritte solo le chiavi di `data`; gli altri campi restano. La risposta è il numero di documenti aggiornati.\n\n```js\nNOSQL('products').update({ price: 39.9, dtupdated: NOW }).id('1abc8d001').callback(function(err, count) {\n\tconsole.log('updated', count);\n});\n```\n\nUn prefisso in una chiave cambia il modo in cui il valore viene applicato:\n\n| Chiave | Effetto |\n| --- | --- |\n| `'+stock': 5` | aggiunge il numero al campo (un campo mancante vale `0`) |\n| `'-stock': 1`, `'*price': 1.1`, `'/price': 2` | sottrae il numero dal campo, o moltiplica o divide il campo per il numero |\n| `'>maxorder': 3` | scrive il valore solo quando è maggiore del campo (un campo mancante lo riceve) |\n| `'<minprice': 9` | scrive il valore solo quando è minore del campo |\n| `'!active': 1` | inverte un campo booleano (il valore viene ignorato) |\n| `'=total': 'doc.price * doc.count'` | valuta un'espressione JavaScript con `doc` |\n\n```js\nNOSQL('products').update({ '+stock': -1, '+sold': 1 }).id(id).callback(console.log);\n```\n\nIn `insert()` i prefissi vengono rimossi: `'+stock': 5` salva `stock: 5` e `'!active'` salva `true`.\n\n## Rimozione e manutenzione\n\n`remove()` rimuove i documenti che corrispondono al filtro e risponde con il loro numero. Senza filtro rimuove tutti i documenti.\n\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(function(err, count) {\n\tconsole.log('removed', count);\n});\n```\n\n- `clear()` elimina l'intero file con tutti i documenti.\n- `clean()` riscrive il file senza le righe dei documenti rimossi e sostituiti.\n\n```js\nON('service', function(counter) {\n\t// once a day\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n## Ottenere il risultato\n\nTutti i builder terminano allo stesso modo:\n\n- `callback(fn)` (alias `pipe()`) chiama `fn(err, response)`. In un'azione puoi passare `$`, e la risposta va direttamente al client.\n- `promise([$])` restituisce una Promise; con `$` un errore va a `$.invalid()`.\n- `done($, fn)` chiama `fn(response)` e invia un errore a `$.invalid()`.\n- `data(fn)` e `fail(fn)` vengono chiamati solo con la risposta o solo con l'errore.\n- `error(message)` trasforma un risultato vuoto (`undefined`, un array vuoto, `0` aggiornati o rimossi) in un errore.\n\n```js\nNEWACTION('Products/detail', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await NOSQL('products').read().id($.params.id).error('Not found').promise($);\n\t\t$.callback(item);\n\t}\n});\n```\n\n`debug()` stampa nella console il filtro compilato. L'operazione viene eseguita al tick successivo, quindi aggiungi tutti i filtri e le opzioni nella stessa catena sincrona.\n\n## NoSQL tramite DATA\n\nNoSQL è anche un motore del query builder globale `DATA` con il nome `nosql`: `DATA.find('nosql/users')` equivale a `NOSQL('users').find()`. `DATA` aggiunge alcune letture che `NOSQL()` non ha:\n\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\t// response.count\n});\n\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\t// exists is true or false\n});\n\nDATA.scalar('nosql/orders', 'sum', 'price').callback(function(err, response) {\n\t// response.value\n});\n\nDATA.list('nosql/orders').page(2, 20).callback(function(err, response) {\n\t// response.items, response.count (all matching documents), response.page, response.pages\n});\n```\n\n`scalar()` calcola `sum`, `min`, `max`, `avg` e `count` di un campo; senza campo conta i documenti. `list()` legge una pagina e il `count` totale dei documenti corrispondenti.\n\nPer `DATA` con i database SQL vedi [QueryBuilder](../../guides/querybuilder/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JaqmBV1vc60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/nosql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"NoSQL databáza","summary":"Vstavaná NoSQL databáza: NOSQL(name), súbory v databases/, vkladanie, vyhľadávanie, aktualizácia a odstraňovanie dokumentov pomocou query buildera.","markdown":"---\ntitle: \"NoSQL databáza\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/nosql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# NoSQL databáza\n\n> Vstavaná NoSQL databáza: NOSQL(name), súbory v databases/, vkladanie, vyhľadávanie, aktualizácia a odstraňovanie dokumentov pomocou query buildera.\n\nTotal.js 5 obsahuje malú vstavanú **NoSQL** databázu. Nepotrebuje server ani ovládač: každá databáza je textový súbor v priečinku `databases/` s jedným JSON dokumentom na riadok. Hodí sa na nastavenia, logy, malé katalógy a prototypy.\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', age: 33, dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\t// response is an array of documents\n});\n```\n\n`NOSQL(name)` vráti malý objekt s metódami `insert()`, `find()`, `read()`, `update()` (alias `modify()`), `remove()`, `clear()` a `clean()`. Každá z nich vráti **query builder**, do ktorého pridáš filtre a voľby a potom prečítaš výsledok cez `.callback()` alebo `.promise()`. Úplný zoznam je v referencii [NoSQL databáza](../../reference/nosql/).\n\n## Súbory v databases/\n\n`NOSQL('users')` používa súbor `databases/users.nosql` v koreni aplikácie. Priečinok aj súbor sa vytvoria, keď sú potrebné, takže nemusíš nič pripravovať. Konfiguračným kľúčom `$dirdatabases` presunieš priečinok inam.\n\nNázov, ktorý obsahuje lomku, sa použije ako cesta k súboru tak, ako je, bez prípony `.nosql`:\n\n```js\nNOSQL('/data/shared/orders.nosql').find().callback(console.log);\n```\n\nSúbor je obyčajný text. Každé vloženie pripojí nový riadok s JSON dokumentom. Odstránený dokument zostane v súbore a jeho riadok sa na začiatku označí `-`; takéto riadky každé čítanie preskočí. Aktualizácia, ktorá zachová rovnakú dĺžku, prepíše riadok na mieste; inak sa starý riadok označí ako odstránený a nová verzia sa pripojí na koniec. Z času na čas zavolaj `clean()`, aby si označené riadky odstránil a súbor zmenšil.\n\nVšetky operácie s jedným súborom idú cez frontu: zápisy (vloženie, aktualizácia, odstránenie) bežia jeden po druhom a nikdy súčasne s `clear()` alebo `clean()`; súčasne môžu bežať až tri čítania.\n\n## Vkladanie\n\n`insert(doc)` pripojí dokument. NoSQL negeneruje žiadny identifikátor, takže pridaj vlastné `id` (napríklad cez `UID()`). Odpoveď je `1`.\n\n```js\nNOSQL('products').insert({ id: UID(), name: 'Keyboard', price: 49.9, tags: ['usb', 'black'], dtcreated: NOW }).callback(function(err, response) {\n\tconsole.log('inserted', response);\n});\n```\n\nDátumy sa ukladajú ako ISO reťazce a každé čítanie ich prevedie späť na objekty `Date`, takže ich môžeš porovnávať a triediť podľa nich.\n\n## Vyhľadávanie dokumentov\n\n`find()` vráti všetky dokumenty, ktoré zodpovedajú filtru, ako pole (prázdne pole, keď nič nezodpovedá). `read()` vráti jeden dokument alebo `undefined`, keď nič nezodpovedá.\n\nBez `sort()` prichádzajú dokumenty od konca súboru: najnovšie zapísané ako prvé. Keď na poradí záleží, pridaj `sort()`.\n\n```js\nNOSQL('products').find().where('price', '<', 100).in('tags', ['usb']).fields('id,name,price').sort('price', true).take(20).callback(function(err, items) {\n\tconsole.log(items);\n});\n\nNOSQL('products').read().id('1abc8d001').callback(function(err, product) {\n\tconsole.log(product ? product.name : 'not found');\n});\n```\n\n### Filtre\n\nVšetky filtre sa spájajú cez AND. Názvy polí môžu byť vnorené cez bodku (`address.city`).\n\n| Metóda | Zodpovedá, keď |\n| --- | --- |\n| `where(name, [comparer], value)` | pole sa porovná s hodnotou; porovnávače `=` (predvolený), `<>`, `!=`, `>`, `>=`, `<`, `<=` |\n| `id(value)`, `userid(value)` | pole `id` alebo `userid` sa rovná hodnote (pole znamená „jedna z“) |\n| `equal(obj)` | každý kľúč objektu sa rovná svojej hodnote |\n| `in(name, values)`, `notin(name, values)` | pole je (alebo nie je) jednou z hodnôt; pole typu array zodpovedá, keď je ktorákoľvek položka jednou z nich |\n| `between(name, a, b)` | pole je `>= a` a `<= b` |\n| `search(name, text, [where])` | pole obsahuje text (bez ohľadu na veľkosť písmen); `where` je `'beg'` alebo `'end'` |\n| `contains(name)`, `empty(name)` | pole má hodnotu (neprázdne pole), alebo nemá |\n| `year()`, `month()`, `day()` | časť poľa `Date` sa porovná s číslom |\n| `query(code)` | JavaScript výraz s `doc` je pravdivý |\n\n`or(fn)` zoskupí filtre pridané vnútri funkcie cez OR:\n\n```js\nNOSQL('users').find().where('active', true).or(function(builder) {\n\tbuilder.search('name', 'peter');\n\tbuilder.search('email', 'peter');\n}).callback(console.log);\n```\n\n`query()` (a `where()` iba s jedným argumentom) prijíma surovú JavaScript podmienku. Dokument je `doc`. Nevkladaj do nej vstup od používateľa.\n\n```js\nNOSQL('orders').find().query('doc.items.length > 2 && doc.price > 100').callback(console.log);\n```\n\n### Polia, triedenie a stránkovanie\n\n- `fields('id,name,price')` vráti iba tieto polia; `fields('-password,-token')` vráti všetko okrem týchto polí.\n- `sort(name, [desc])` triedi podľa poľa; pre druhý kľúč ho zavolaj znova. `desc` je `true` alebo `'desc'`.\n- `take(count)` (alias `limit()`), `skip(count)` a `first()` obmedzia výsledok. `first()` vráti namiesto poľa jeden objekt.\n- `page(page, limit)` a `paginate(page, limit, maxlimit)` vypočítajú `skip` a `take` z čísla stránky, čo sa hodí s hodnotami z query stringu.\n\n```js\nfunction list($) {\n\tNOSQL('articles').find().where('published', true).sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n}\n```\n\n## Aktualizácia\n\n`update(data)` (alias `modify()`) zmení dokumenty, ktoré zodpovedajú filtru. Zapíšu sa iba kľúče z `data`; ostatné polia zostanú. Odpoveď je počet aktualizovaných dokumentov.\n\n```js\nNOSQL('products').update({ price: 39.9, dtupdated: NOW }).id('1abc8d001').callback(function(err, count) {\n\tconsole.log('updated', count);\n});\n```\n\nPrefix v kľúči mení, ako sa hodnota použije:\n\n| Kľúč | Účinok |\n| --- | --- |\n| `'+stock': 5` | pripočíta číslo k poľu (chýbajúce pole sa počíta ako `0`) |\n| `'-stock': 1`, `'*price': 1.1`, `'/price': 2` | odpočíta, vynásobí alebo vydelí pole číslom |\n| `'>maxorder': 3` | zapíše hodnotu, iba keď je väčšia ako pole (chýbajúce pole ju prevezme) |\n| `'<minprice': 9` | zapíše hodnotu, iba keď je menšia ako pole |\n| `'!active': 1` | prepne booleovské pole (hodnota sa ignoruje) |\n| `'=total': 'doc.price * doc.count'` | vyhodnotí JavaScript výraz s `doc` |\n\n```js\nNOSQL('products').update({ '+stock': -1, '+sold': 1 }).id(id).callback(console.log);\n```\n\nV `insert()` sa prefixy odstránia: `'+stock': 5` uloží `stock: 5` a `'!active'` uloží `true`.\n\n## Odstraňovanie a údržba\n\n`remove()` odstráni dokumenty, ktoré zodpovedajú filtru, a odpovie ich počtom. Bez filtra odstráni všetky dokumenty.\n\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(function(err, count) {\n\tconsole.log('removed', count);\n});\n```\n\n- `clear()` zmaže celý súbor so všetkými dokumentmi.\n- `clean()` prepíše súbor bez riadkov odstránených a nahradených dokumentov.\n\n```js\nON('service', function(counter) {\n\t// once a day\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n## Získanie výsledku\n\nVšetky buildery končia rovnako:\n\n- `callback(fn)` (alias `pipe()`) zavolá `fn(err, response)`. V akcii môžeš odovzdať `$` a odpoveď ide rovno klientovi.\n- `promise([$])` vráti Promise; s `$` ide chyba do `$.invalid()`.\n- `done($, fn)` zavolá `fn(response)` a chybu pošle do `$.invalid()`.\n- `data(fn)` a `fail(fn)` sa zavolajú iba s odpoveďou alebo iba s chybou.\n- `error(message)` zmení prázdny výsledok (`undefined`, prázdne pole, `0` aktualizovaných alebo odstránených) na chybu.\n\n```js\nNEWACTION('Products/detail', {\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar item = await NOSQL('products').read().id($.params.id).error('Not found').promise($);\n\t\t$.callback(item);\n\t}\n});\n```\n\n`debug()` vypíše skompilovaný filter do konzoly. Operácia sa spustí v ďalšom ticku, takže všetky filtre a voľby pridaj v tom istom synchrónnom reťazci.\n\n## NoSQL cez DATA\n\nNoSQL je aj engine globálneho query buildera `DATA` pod názvom `nosql`: `DATA.find('nosql/users')` je to isté ako `NOSQL('users').find()`. `DATA` pridáva niekoľko čítaní, ktoré `NOSQL()` nemá:\n\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\t// response.count\n});\n\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\t// exists is true or false\n});\n\nDATA.scalar('nosql/orders', 'sum', 'price').callback(function(err, response) {\n\t// response.value\n});\n\nDATA.list('nosql/orders').page(2, 20).callback(function(err, response) {\n\t// response.items, response.count (all matching documents), response.page, response.pages\n});\n```\n\n`scalar()` vypočíta `sum`, `min`, `max`, `avg` a `count` poľa; bez poľa spočíta dokumenty. `list()` prečíta jednu stránku a celkový `count` zodpovedajúcich dokumentov.\n\n`DATA` so SQL databázami nájdeš v [QueryBuilder](../../guides/querybuilder/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JafwRj1cx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"QueryBuilder","summary":"Query any database with one QueryBuilder: DATA, DB(), adapters, filters, paging and autoquery.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> Query any database with one QueryBuilder: DATA, DB(), adapters, filters, paging and autoquery.\n\nTotal.js 5 has one **QueryBuilder** for every database. You describe a query with methods (`find`, `where`, `sort`, `take`…), the QueryBuilder turns the calls into a plain object of options, and an **adapter** for your database engine turns that object into a real query. Your code stays the same when you change the engine; only the adapter changes.\n\n```js\nDATA.find('users').where('isremoved', false).sort('name').take(20).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nThe full list of methods is in the reference of [QueryBuilder](../../reference/querybuilder/).\n\n## The parts\n\n| Name | What it is |\n| --- | --- |\n| `DATA` | A global, shared database object. Every call on it starts one query at once. |\n| `DB()` | Creates a new database object that runs several queries one after another and collects their results. |\n| `NEWDB(name, fn)` | Registers an adapter: the function that executes the queries for the connection `name`. |\n| QueryBuilder | The object that `find()`, `insert()` and the other operations return. You chain filters on it. |\n\n## Registering an adapter\n\nThe QueryBuilder does not talk to any database itself. An adapter is a function registered with `NEWDB()`. It receives the options of the query and a callback:\n\n```js\nNEWDB('default', function(filter, callback) {\n\t// filter.exec     the operation: find, list, read, check, count, scalar,\n\t//                 insert, update, remove, query, drop, truncate, command\n\t// filter.table    the table name\n\t// filter.filter   the conditions: [{ type: 'where', name, comparer, value }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload ...\n\tcallback(null, []);\n});\n```\n\nThe adapter of the connection is chosen by the table name. `'users'` uses the connection `default`, `'logs/requests'` uses the connection `logs` and the table `requests`. When no adapter has that name, the adapter `*` is used if it exists; otherwise the query fails with the error `Database is not initialized`. Calling `NEWDB(name)` without a function removes the adapter.\n\nThe framework ships the adapter `nosql`, which runs the QueryBuilder against the embedded NoSQL files: `DATA.find('nosql/users')`. See [NoSQL](../../guides/nosql/). For PostgreSQL, `DATA.init('default', 'postgresql://…')` registers an adapter that writes the SQL; see [PostgreSQL](../../guides/postgresql/).\n\n## Reading data\n\n```js\n// all rows that match\nDATA.find('products').where('price', '>', 100).sort('price', true).callback(console.log);\n\n// one row (or null)\nDATA.read('products').id('p123').callback(console.log);\n\n// a page with metadata\nDATA.list('products').search('name', 'phone').page(2, 25).callback(function(err, response) {\n\t// response.items, response.count (from the adapter)\n\t// response.page, response.limit, response.pages (added by the QueryBuilder)\n});\n\n// true or false\nDATA.check('users').where('email', 'peter@example.com').callback(console.log);\n\n// number of rows\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n`list()` starts with `skip` 0 and `take` 100. `read()` and `check()` take one row; when the adapter returns an array, `read()` gives its first item or `null`.\n\n`scalar(table, type, key, key2)` computes a value such as `'sum'`, `'avg'`, `'min'`, `'max'` or `'count'` over a column; the adapter decides what each type returns.\n\n## Writing data\n\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').callback(console.log);\n\nDATA.remove('users').where('id', 'u1').callback(console.log);\n```\n\nPass `true` as the third argument of `update()` for an **upsert**: when the update changes nothing, the QueryBuilder clears the conditions and runs the same payload as an `insert`. With `.insert(fn)` you can change the payload just before that insert:\n\n```js\nDATA.update('pages', { name: 'Home', dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n`returning('id,name')` asks the adapter to return those columns of the changed rows.\n\n## Filters\n\nAll filters are joined with AND. Put a group in `or()` to join it with OR.\n\n```js\nDATA.find('users')\n\t.where('age', '>=', 18)             // =, <>, >, <, >=, <= (== and != work too)\n\t.in('role', ['admin', 'editor'])\n\t.notin('id', ['u1', 'u2'])\n\t.between('dtcreated', NOW.add('-7 days'), NOW)\n\t.search('name', 'pet')              // contains the text\n\t.or(function(builder) {\n\t\tbuilder.where('isblocked', false);\n\t\tbuilder.empty('dtblocked');\n\t})\n\t.fields('id,name,email')\n\t.callback(console.log);\n```\n\n| Method | Condition |\n| --- | --- |\n| `where(name, [comparer], value)` | Compare a column. With one argument it is a raw condition (`query()`). |\n| `id(value)`, `userid(value)` | `where('id', …)`, or `in('id', …)` for an array |\n| `equal(obj)` | One `where()` per key of the object |\n| `in()`, `notin()` | The value is (not) in a list |\n| `between(name, a, b)` | Between two values |\n| `search(name, value, [where])` | Text search; `where` can be `'beg'` or `'end'` |\n| `contains(name)`, `empty(name)` | The column has a value, or is empty |\n| `array(name, [comparer], value)` | A condition on an array column (`&&` by default) |\n| `year()`, `month()`, `day()`, `hour()`, `minute()` | Compare a part of a date |\n| `query(sql)` | A raw condition passed to the adapter as it is |\n\nThe adapter translates these items into its own syntax, so which comparers and raw conditions work depends on the engine.\n\n## Sorting and paging\n\n```js\nDATA.find('products')\n\t.sort('price', 'desc')       // or true\n\t.sort('name')                // ascending\n\t.page(3, 20)                 // skip 40, take 20\n\t.callback(console.log);\n```\n\n`take()` (alias `limit()`), `skip()` and `first()` set the numbers directly. `paginate(page, limit, maxlimit)` accepts values straight from a query string and keeps the limit under `maxlimit`. `gridsort('name_asc,dtcreated_desc')` reads a sort string.\n\n## Filters from a query string\n\n`autoquery()` builds the whole query from the query string of a request. You list the allowed fields and their types; everything else is ignored.\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('products').autoquery($.query, 'id,name:string,price:number,dtcreated:date,ispublished:boolean', 'dtcreated_desc', 100).callback($);\n\t}\n});\n```\n\nWith `?fields=id,name&name=phone&price=>100&sort=price_asc&page=2&limit=50` this selects only `id` and `name`, searches `name`, keeps rows with `price` above 100, sorts by `price` and returns the second page of 50 rows (never more than 100). The second argument can also be `'@SchemaName'` to take the fields and types from a JSON schema.\n\n`autoqueryjson($, column, schema, [defsort], [maxlimit])` does the same for properties stored in one JSON column. The QueryBuilder gives the adapter each property as the name `json:column:property:type` (for example `json:data:weight:number`), and the adapter translates it into its own syntax. The PostgreSQL adapter does it; see [PostgreSQL](../../guides/postgresql/).\n\n`gridfields(fields, allowed)` selects the columns from a comma-separated list, usually `$.query.fields`, and keeps only the allowed ones. When the list is empty or missing, or none of them is allowed, the query reads all columns:\n\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n`gridfilter(name, query, type, [column])` does the same for one field. The value of the query string decides the condition:\n\n| Value | Condition |\n| --- | --- |\n| `phone` | `search` for text, `=` for other types |\n| `=phone` | Exact match |\n| `a,b,c` | Text: any of the words (OR of `search`); other types: `in` |\n| `=a,b` | Text: `in` with the exact values |\n| `10 - 20` | `between` |\n| `>10`, `<10` | Greater or less than (numbers and dates) |\n| `today`, `yesterday`, `2024-05-01` | The whole day (dates) |\n| `2024`, `5` | The year (a number above 1000) or the month (dates) |\n\n## Inside actions\n\n`callback($)` passes the result straight to the action. `promise($)` gives a promise; with `$` an error goes to `$.invalid()`.\n\n```js\nNEWACTION('Users/read', {\n\tname: 'Read user',\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar user = await DATA.read('users').id($.params.id).error('@(User not found)').promise($);\n\t\t$.callback(user);\n\t}\n});\n```\n\n`error(message)` turns an empty result (no row, an empty array) into an error with that message. With `error(message, true)` it is the other way: a result is an error, which is useful for \"already exists\" checks. `done($, fn)` calls `fn(response)` on success and `$.invalid(err)` on error. `audit($, message)` writes an audit record after a successful operation; `{data.name}` in the message is replaced from the payload. See [Actions](../../guides/actions/).\n\n## Several queries with DB()\n\n`DB()` runs its queries one after another, in the order you add them. `set(name)` stores the result of a query under a key of the final response; without it the response is the result of the last query.\n\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user').error('@(User not found)');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nThe first error stops the chain. `db.promise($)` and `db.done($, fn)` work like the methods of the QueryBuilder. `db.debug()` sets the `debug` option on every query, so adapters that support it can print the generated queries.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRj1cx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"QueryBuilder","summary":"Frage jede Datenbank mit einem QueryBuilder ab: DATA, DB(), Adapter, Filter, Paging und autoquery.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> Frage jede Datenbank mit einem QueryBuilder ab: DATA, DB(), Adapter, Filter, Paging und autoquery.\n\nTotal.js 5 hat einen **QueryBuilder** für jede Datenbank. Du beschreibst eine Abfrage mit Methoden (`find`, `where`, `sort`, `take`…), der QueryBuilder macht aus den Aufrufen ein einfaches Optionsobjekt, und ein **Adapter** für deine Datenbank-Engine macht aus diesem Objekt eine echte Abfrage. Dein Code bleibt gleich, wenn du die Engine wechselst; nur der Adapter ändert sich.\n\n```js\nDATA.find('users').where('isremoved', false).sort('name').take(20).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nDie vollständige Liste der Methoden steht in der Referenz zu [QueryBuilder](../../reference/querybuilder/).\n\n## Die Bestandteile\n\n| Name | Was es ist |\n| --- | --- |\n| `DATA` | Ein globales, gemeinsam genutztes Datenbankobjekt. Jeder Aufruf darauf startet sofort eine Abfrage. |\n| `DB()` | Erstellt ein neues Datenbankobjekt, das mehrere Abfragen nacheinander ausführt und ihre Ergebnisse sammelt. |\n| `NEWDB(name, fn)` | Registriert einen Adapter: die Funktion, die die Abfragen für die Verbindung `name` ausführt. |\n| QueryBuilder | Das Objekt, das `find()`, `insert()` und die übrigen Operationen zurückgeben. Du verkettest Filter darauf. |\n\n## Einen Adapter registrieren\n\nDer QueryBuilder spricht selbst mit keiner Datenbank. Ein Adapter ist eine mit `NEWDB()` registrierte Funktion. Sie erhält die Optionen der Abfrage und einen Callback:\n\n```js\nNEWDB('default', function(filter, callback) {\n\t// filter.exec     the operation: find, list, read, check, count, scalar,\n\t//                 insert, update, remove, query, drop, truncate, command\n\t// filter.table    the table name\n\t// filter.filter   the conditions: [{ type: 'where', name, comparer, value }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload ...\n\tcallback(null, []);\n});\n```\n\nDer Adapter der Verbindung wird anhand des Tabellennamens gewählt. `'users'` verwendet die Verbindung `default`, `'logs/requests'` verwendet die Verbindung `logs` und die Tabelle `requests`. Hat kein Adapter diesen Namen, wird der Adapter `*` verwendet, falls er existiert; andernfalls schlägt die Abfrage mit dem Fehler `Database is not initialized` fehl. Ein Aufruf von `NEWDB(name)` ohne Funktion entfernt den Adapter.\n\nDas Framework liefert den Adapter `nosql` mit, der den QueryBuilder auf die eingebetteten NoSQL-Dateien anwendet: `DATA.find('nosql/users')`. Siehe [NoSQL](../../guides/nosql/). Für PostgreSQL registriert `DATA.init('default', 'postgresql://…')` einen Adapter, der das SQL schreibt; siehe [PostgreSQL](../../guides/postgresql/).\n\n## Daten lesen\n\n```js\n// all rows that match\nDATA.find('products').where('price', '>', 100).sort('price', true).callback(console.log);\n\n// one row (or null)\nDATA.read('products').id('p123').callback(console.log);\n\n// a page with metadata\nDATA.list('products').search('name', 'phone').page(2, 25).callback(function(err, response) {\n\t// response.items, response.count (from the adapter)\n\t// response.page, response.limit, response.pages (added by the QueryBuilder)\n});\n\n// true or false\nDATA.check('users').where('email', 'peter@example.com').callback(console.log);\n\n// number of rows\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n`list()` beginnt mit `skip` 0 und `take` 100. `read()` und `check()` nehmen eine Zeile; gibt der Adapter ein Array zurück, liefert `read()` dessen erstes Element oder `null`.\n\n`scalar(table, type, key, key2)` berechnet einen Wert wie `'sum'`, `'avg'`, `'min'`, `'max'` oder `'count'` über eine Spalte; der Adapter entscheidet, was jeder Typ zurückgibt.\n\n## Daten schreiben\n\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').callback(console.log);\n\nDATA.remove('users').where('id', 'u1').callback(console.log);\n```\n\nÜbergib `true` als drittes Argument von `update()` für ein **Upsert**: Ändert das Update nichts, entfernt der QueryBuilder die Bedingungen und führt denselben Payload als `insert` aus. Mit `.insert(fn)` kannst du den Payload direkt vor diesem Insert ändern:\n\n```js\nDATA.update('pages', { name: 'Home', dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n`returning('id,name')` bittet den Adapter, diese Spalten der geänderten Zeilen zurückzugeben.\n\n## Filter\n\nAlle Filter werden mit AND verbunden. Setze eine Gruppe in `or()`, um sie mit OR zu verbinden.\n\n```js\nDATA.find('users')\n\t.where('age', '>=', 18)             // =, <>, >, <, >=, <= (== and != work too)\n\t.in('role', ['admin', 'editor'])\n\t.notin('id', ['u1', 'u2'])\n\t.between('dtcreated', NOW.add('-7 days'), NOW)\n\t.search('name', 'pet')              // contains the text\n\t.or(function(builder) {\n\t\tbuilder.where('isblocked', false);\n\t\tbuilder.empty('dtblocked');\n\t})\n\t.fields('id,name,email')\n\t.callback(console.log);\n```\n\n| Methode | Bedingung |\n| --- | --- |\n| `where(name, [comparer], value)` | Vergleicht eine Spalte. Mit einem Argument ist es eine rohe Bedingung (`query()`). |\n| `id(value)`, `userid(value)` | `where('id', …)` oder `in('id', …)` bei einem Array |\n| `equal(obj)` | Ein `where()` pro Schlüssel des Objekts |\n| `in()`, `notin()` | Der Wert ist (nicht) in einer Liste |\n| `between(name, a, b)` | Zwischen zwei Werten |\n| `search(name, value, [where])` | Textsuche; `where` kann `'beg'` oder `'end'` sein |\n| `contains(name)`, `empty(name)` | Die Spalte hat einen Wert oder ist leer |\n| `array(name, [comparer], value)` | Eine Bedingung auf eine Array-Spalte (standardmäßig `&&`) |\n| `year()`, `month()`, `day()`, `hour()`, `minute()` | Vergleicht einen Teil eines Datums |\n| `query(sql)` | Eine rohe Bedingung, die unverändert an den Adapter geht |\n\nDer Adapter übersetzt diese Elemente in seine eigene Syntax, daher hängt es von der Engine ab, welche Vergleichsoperatoren und rohen Bedingungen funktionieren.\n\n## Sortieren und Paging\n\n```js\nDATA.find('products')\n\t.sort('price', 'desc')       // or true\n\t.sort('name')                // ascending\n\t.page(3, 20)                 // skip 40, take 20\n\t.callback(console.log);\n```\n\n`take()` (Alias `limit()`), `skip()` und `first()` setzen die Zahlen direkt. `paginate(page, limit, maxlimit)` akzeptiert Werte direkt aus einem Query-String und hält das Limit unter `maxlimit`. `gridsort('name_asc,dtcreated_desc')` liest einen Sortier-String.\n\n## Filter aus einem Query-String\n\n`autoquery()` baut die gesamte Abfrage aus dem Query-String eines Requests auf. Du listest die erlaubten Felder und ihre Typen auf; alles andere wird ignoriert.\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('products').autoquery($.query, 'id,name:string,price:number,dtcreated:date,ispublished:boolean', 'dtcreated_desc', 100).callback($);\n\t}\n});\n```\n\nMit `?fields=id,name&name=phone&price=>100&sort=price_asc&page=2&limit=50` wählt das nur `id` und `name` aus, durchsucht `name`, behält Zeilen mit `price` über 100, sortiert nach `price` und gibt die zweite Seite mit 50 Zeilen zurück (nie mehr als 100). Das zweite Argument kann auch `'@SchemaName'` sein, um Felder und Typen aus einem JSON-Schema zu übernehmen.\n\n`autoqueryjson($, column, schema, [defsort], [maxlimit])` macht dasselbe für Eigenschaften, die in einer JSON-Spalte gespeichert sind. Der QueryBuilder übergibt dem Adapter jede Eigenschaft als Namen `json:column:property:type` (zum Beispiel `json:data:weight:number`), und der Adapter übersetzt ihn in seine eigene Syntax. Der PostgreSQL-Adapter tut das; siehe [PostgreSQL](../../guides/postgresql/).\n\n`gridfields(fields, allowed)` wählt die Spalten aus einer kommagetrennten Liste aus, meist `$.query.fields`, und behält nur die erlaubten. Wenn die Liste leer ist oder fehlt oder keine davon erlaubt ist, liest die Abfrage alle Spalten:\n\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n`gridfilter(name, query, type, [column])` macht dasselbe für ein Feld. Der Wert im Query-String bestimmt die Bedingung:\n\n| Wert | Bedingung |\n| --- | --- |\n| `phone` | `search` für Text, `=` für andere Typen |\n| `=phone` | Exakte Übereinstimmung |\n| `a,b,c` | Text: eines der Wörter (OR aus `search`); andere Typen: `in` |\n| `=a,b` | Text: `in` mit den exakten Werten |\n| `10 - 20` | `between` |\n| `>10`, `<10` | Größer oder kleiner als (Zahlen und Datumswerte) |\n| `today`, `yesterday`, `2024-05-01` | Der ganze Tag (Datumswerte) |\n| `2024`, `5` | Das Jahr (eine Zahl über 1000) oder der Monat (Datumswerte) |\n\n## Innerhalb von Aktionen\n\n`callback($)` gibt das Ergebnis direkt an die Aktion weiter. `promise($)` liefert ein Promise; mit `$` geht ein Fehler an `$.invalid()`.\n\n```js\nNEWACTION('Users/read', {\n\tname: 'Read user',\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar user = await DATA.read('users').id($.params.id).error('@(User not found)').promise($);\n\t\t$.callback(user);\n\t}\n});\n```\n\n`error(message)` macht aus einem leeren Ergebnis (keine Zeile, ein leeres Array) einen Fehler mit dieser Meldung. Mit `error(message, true)` ist es umgekehrt: Ein Ergebnis ist ein Fehler, was für Prüfungen wie \"existiert bereits\" nützlich ist. `done($, fn)` ruft bei Erfolg `fn(response)` und bei einem Fehler `$.invalid(err)` auf. `audit($, message)` schreibt nach einer erfolgreichen Operation einen Audit-Eintrag; `{data.name}` in der Nachricht wird aus dem Payload ersetzt. Siehe [Aktionen](../../guides/actions/).\n\n## Mehrere Abfragen mit DB()\n\n`DB()` führt seine Abfragen nacheinander aus, in der Reihenfolge, in der du sie hinzufügst. `set(name)` speichert das Ergebnis einer Abfrage unter einem Schlüssel der endgültigen Antwort; ohne es ist die Antwort das Ergebnis der letzten Abfrage.\n\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user').error('@(User not found)');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nDer erste Fehler beendet die Kette. `db.promise($)` und `db.done($, fn)` funktionieren wie die Methoden des QueryBuilders. `db.debug()` setzt die Option `debug` bei jeder Abfrage, sodass Adapter, die sie unterstützen, die erzeugten Abfragen ausgeben können.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRj1cx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"QueryBuilder","summary":"Consulta cualquier base de datos con un solo QueryBuilder: DATA, DB(), adaptadores, filtros, paginación y autoquery.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> Consulta cualquier base de datos con un solo QueryBuilder: DATA, DB(), adaptadores, filtros, paginación y autoquery.\n\nTotal.js 5 tiene un único **QueryBuilder** para todas las bases de datos. Describes una consulta con métodos (`find`, `where`, `sort`, `take`…), el QueryBuilder convierte las llamadas en un objeto simple de opciones, y un **adaptador** para tu motor de base de datos convierte ese objeto en una consulta real. Tu código sigue igual cuando cambias de motor; solo cambia el adaptador.\n\n```js\nDATA.find('users').where('isremoved', false).sort('name').take(20).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nLa lista completa de métodos está en la referencia de [QueryBuilder](../../reference/querybuilder/).\n\n## Las partes\n\n| Nombre | Qué es |\n| --- | --- |\n| `DATA` | Un objeto de base de datos global y compartido. Cada llamada sobre él inicia una consulta de inmediato. |\n| `DB()` | Crea un nuevo objeto de base de datos que ejecuta varias consultas una tras otra y recoge sus resultados. |\n| `NEWDB(name, fn)` | Registra un adaptador: la función que ejecuta las consultas de la conexión `name`. |\n| QueryBuilder | El objeto que devuelven `find()`, `insert()` y las demás operaciones. Encadenas filtros sobre él. |\n\n## Registrar un adaptador\n\nEl QueryBuilder no habla por sí mismo con ninguna base de datos. Un adaptador es una función registrada con `NEWDB()`. Recibe las opciones de la consulta y un callback:\n\n```js\nNEWDB('default', function(filter, callback) {\n\t// filter.exec     the operation: find, list, read, check, count, scalar,\n\t//                 insert, update, remove, query, drop, truncate, command\n\t// filter.table    the table name\n\t// filter.filter   the conditions: [{ type: 'where', name, comparer, value }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload ...\n\tcallback(null, []);\n});\n```\n\nEl adaptador de la conexión se elige por el nombre de la tabla. `'users'` usa la conexión `default`, `'logs/requests'` usa la conexión `logs` y la tabla `requests`. Cuando ningún adaptador tiene ese nombre, se usa el adaptador `*` si existe; si no, la consulta falla con el error `Database is not initialized`. Llamar a `NEWDB(name)` sin una función elimina el adaptador.\n\nEl framework incluye el adaptador `nosql`, que ejecuta el QueryBuilder sobre los archivos NoSQL integrados: `DATA.find('nosql/users')`. Consulta [NoSQL](../../guides/nosql/). Para PostgreSQL, `DATA.init('default', 'postgresql://…')` registra un adaptador que escribe el SQL; consulta [PostgreSQL](../../guides/postgresql/).\n\n## Leer datos\n\n```js\n// all rows that match\nDATA.find('products').where('price', '>', 100).sort('price', true).callback(console.log);\n\n// one row (or null)\nDATA.read('products').id('p123').callback(console.log);\n\n// a page with metadata\nDATA.list('products').search('name', 'phone').page(2, 25).callback(function(err, response) {\n\t// response.items, response.count (from the adapter)\n\t// response.page, response.limit, response.pages (added by the QueryBuilder)\n});\n\n// true or false\nDATA.check('users').where('email', 'peter@example.com').callback(console.log);\n\n// number of rows\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n`list()` empieza con `skip` 0 y `take` 100. `read()` y `check()` toman una fila; cuando el adaptador devuelve un array, `read()` da su primer elemento o `null`.\n\n`scalar(table, type, key, key2)` calcula un valor como `'sum'`, `'avg'`, `'min'`, `'max'` o `'count'` sobre una columna; el adaptador decide qué devuelve cada tipo.\n\n## Escribir datos\n\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').callback(console.log);\n\nDATA.remove('users').where('id', 'u1').callback(console.log);\n```\n\nPasa `true` como tercer argumento de `update()` para hacer un **upsert**: cuando la actualización no cambia nada, el QueryBuilder borra las condiciones y ejecuta el mismo payload como un `insert`. Con `.insert(fn)` puedes cambiar el payload justo antes de ese insert:\n\n```js\nDATA.update('pages', { name: 'Home', dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n`returning('id,name')` pide al adaptador que devuelva esas columnas de las filas modificadas.\n\n## Filtros\n\nTodos los filtros se unen con AND. Pon un grupo en `or()` para unirlo con OR.\n\n```js\nDATA.find('users')\n\t.where('age', '>=', 18)             // =, <>, >, <, >=, <= (== and != work too)\n\t.in('role', ['admin', 'editor'])\n\t.notin('id', ['u1', 'u2'])\n\t.between('dtcreated', NOW.add('-7 days'), NOW)\n\t.search('name', 'pet')              // contains the text\n\t.or(function(builder) {\n\t\tbuilder.where('isblocked', false);\n\t\tbuilder.empty('dtblocked');\n\t})\n\t.fields('id,name,email')\n\t.callback(console.log);\n```\n\n| Método | Condición |\n| --- | --- |\n| `where(name, [comparer], value)` | Compara una columna. Con un argumento es una condición sin procesar (`query()`). |\n| `id(value)`, `userid(value)` | `where('id', …)`, o `in('id', …)` para un array |\n| `equal(obj)` | Un `where()` por cada clave del objeto |\n| `in()`, `notin()` | El valor (no) está en una lista |\n| `between(name, a, b)` | Entre dos valores |\n| `search(name, value, [where])` | Búsqueda de texto; `where` puede ser `'beg'` o `'end'` |\n| `contains(name)`, `empty(name)` | La columna tiene un valor, o está vacía |\n| `array(name, [comparer], value)` | Una condición sobre una columna de array (`&&` por defecto) |\n| `year()`, `month()`, `day()`, `hour()`, `minute()` | Compara una parte de una fecha |\n| `query(sql)` | Una condición sin procesar que se pasa al adaptador tal cual |\n\nEl adaptador traduce estos elementos a su propia sintaxis, así que los comparadores y las condiciones sin procesar que funcionan dependen del motor.\n\n## Ordenación y paginación\n\n```js\nDATA.find('products')\n\t.sort('price', 'desc')       // or true\n\t.sort('name')                // ascending\n\t.page(3, 20)                 // skip 40, take 20\n\t.callback(console.log);\n```\n\n`take()` (alias `limit()`), `skip()` y `first()` establecen los números directamente. `paginate(page, limit, maxlimit)` acepta valores directamente de una query string y mantiene el límite por debajo de `maxlimit`. `gridsort('name_asc,dtcreated_desc')` lee una cadena de ordenación.\n\n## Filtros desde una query string\n\n`autoquery()` construye toda la consulta a partir de la query string de una petición. Enumeras los campos permitidos y sus tipos; todo lo demás se ignora.\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('products').autoquery($.query, 'id,name:string,price:number,dtcreated:date,ispublished:boolean', 'dtcreated_desc', 100).callback($);\n\t}\n});\n```\n\nCon `?fields=id,name&name=phone&price=>100&sort=price_asc&page=2&limit=50` esto selecciona solo `id` y `name`, busca en `name`, conserva las filas con `price` mayor que 100, ordena por `price` y devuelve la segunda página de 50 filas (nunca más de 100). El segundo argumento también puede ser `'@SchemaName'` para tomar los campos y los tipos de un esquema JSON.\n\n`autoqueryjson($, column, schema, [defsort], [maxlimit])` hace lo mismo con propiedades guardadas en una sola columna JSON. El QueryBuilder pasa al adaptador cada propiedad con el nombre `json:column:property:type` (por ejemplo `json:data:weight:number`), y el adaptador lo traduce a su propia sintaxis. El adaptador de PostgreSQL lo hace; consulta [PostgreSQL](../../guides/postgresql/).\n\n`gridfields(fields, allowed)` selecciona las columnas de una lista separada por comas, normalmente `$.query.fields`, y conserva solo las permitidas. Cuando la lista está vacía o falta, o ninguna está permitida, la consulta lee todas las columnas:\n\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n`gridfilter(name, query, type, [column])` hace lo mismo para un solo campo. El valor de la query string decide la condición:\n\n| Valor | Condición |\n| --- | --- |\n| `phone` | `search` para texto, `=` para los demás tipos |\n| `=phone` | Coincidencia exacta |\n| `a,b,c` | Texto: cualquiera de las palabras (OR de `search`); otros tipos: `in` |\n| `=a,b` | Texto: `in` con los valores exactos |\n| `10 - 20` | `between` |\n| `>10`, `<10` | Mayor o menor que (números y fechas) |\n| `today`, `yesterday`, `2024-05-01` | El día completo (fechas) |\n| `2024`, `5` | El año (un número mayor que 1000) o el mes (fechas) |\n\n## Dentro de las acciones\n\n`callback($)` pasa el resultado directamente a la acción. `promise($)` devuelve una promesa; con `$`, un error va a `$.invalid()`.\n\n```js\nNEWACTION('Users/read', {\n\tname: 'Read user',\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar user = await DATA.read('users').id($.params.id).error('@(User not found)').promise($);\n\t\t$.callback(user);\n\t}\n});\n```\n\n`error(message)` convierte un resultado vacío (ninguna fila, un array vacío) en un error con ese mensaje. Con `error(message, true)` es al revés: un resultado es un error, lo que resulta útil para comprobaciones de \"ya existe\". `done($, fn)` llama a `fn(response)` si hay éxito y a `$.invalid(err)` si hay error. `audit($, message)` escribe un registro de auditoría después de una operación correcta; `{data.name}` en el mensaje se reemplaza con el payload. Consulta [Acciones](../../guides/actions/).\n\n## Varias consultas con DB()\n\n`DB()` ejecuta sus consultas una tras otra, en el orden en que las añades. `set(name)` guarda el resultado de una consulta bajo una clave de la respuesta final; sin él, la respuesta es el resultado de la última consulta.\n\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user').error('@(User not found)');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nEl primer error detiene la cadena. `db.promise($)` y `db.done($, fn)` funcionan como los métodos del QueryBuilder. `db.debug()` establece la opción `debug` en todas las consultas, así que los adaptadores que la admiten pueden imprimir las consultas generadas.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRj1cx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"QueryBuilder","summary":"Interroge n'importe quelle base de données avec un seul QueryBuilder : DATA, DB(), adaptateurs, filtres, pagination et autoquery.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> Interroge n'importe quelle base de données avec un seul QueryBuilder : DATA, DB(), adaptateurs, filtres, pagination et autoquery.\n\nTotal.js 5 dispose d'un seul **QueryBuilder** pour toutes les bases de données. Tu décris une requête avec des méthodes (`find`, `where`, `sort`, `take`…), le QueryBuilder transforme les appels en un simple objet d'options, et un **adaptateur** pour ton moteur de base de données transforme cet objet en véritable requête. Ton code reste le même lorsque tu changes de moteur ; seul l'adaptateur change.\n\n```js\nDATA.find('users').where('isremoved', false).sort('name').take(20).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nLa liste complète des méthodes se trouve dans la référence [QueryBuilder](../../reference/querybuilder/).\n\n## Les composants\n\n| Nom | Ce que c'est |\n| --- | --- |\n| `DATA` | Un objet de base de données global et partagé. Chaque appel sur celui-ci lance immédiatement une requête. |\n| `DB()` | Crée un nouvel objet de base de données qui exécute plusieurs requêtes l'une après l'autre et collecte leurs résultats. |\n| `NEWDB(name, fn)` | Enregistre un adaptateur : la fonction qui exécute les requêtes pour la connexion `name`. |\n| QueryBuilder | L'objet que retournent `find()`, `insert()` et les autres opérations. Tu y chaînes des filtres. |\n\n## Enregistrer un adaptateur\n\nLe QueryBuilder ne communique lui-même avec aucune base de données. Un adaptateur est une fonction enregistrée avec `NEWDB()`. Elle reçoit les options de la requête et un callback :\n\n```js\nNEWDB('default', function(filter, callback) {\n\t// filter.exec     the operation: find, list, read, check, count, scalar,\n\t//                 insert, update, remove, query, drop, truncate, command\n\t// filter.table    the table name\n\t// filter.filter   the conditions: [{ type: 'where', name, comparer, value }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload ...\n\tcallback(null, []);\n});\n```\n\nL'adaptateur de la connexion est choisi d'après le nom de la table. `'users'` utilise la connexion `default`, `'logs/requests'` utilise la connexion `logs` et la table `requests`. Lorsqu'aucun adaptateur ne porte ce nom, l'adaptateur `*` est utilisé s'il existe ; sinon, la requête échoue avec l'erreur `Database is not initialized`. Appeler `NEWDB(name)` sans fonction supprime l'adaptateur.\n\nLe framework fournit l'adaptateur `nosql`, qui exécute le QueryBuilder sur les fichiers NoSQL embarqués : `DATA.find('nosql/users')`. Voir [NoSQL](../../guides/nosql/). Pour PostgreSQL, `DATA.init('default', 'postgresql://…')` enregistre un adaptateur qui écrit le SQL ; voir [PostgreSQL](../../guides/postgresql/).\n\n## Lire des données\n\n```js\n// all rows that match\nDATA.find('products').where('price', '>', 100).sort('price', true).callback(console.log);\n\n// one row (or null)\nDATA.read('products').id('p123').callback(console.log);\n\n// a page with metadata\nDATA.list('products').search('name', 'phone').page(2, 25).callback(function(err, response) {\n\t// response.items, response.count (from the adapter)\n\t// response.page, response.limit, response.pages (added by the QueryBuilder)\n});\n\n// true or false\nDATA.check('users').where('email', 'peter@example.com').callback(console.log);\n\n// number of rows\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n`list()` commence avec `skip` à 0 et `take` à 100. `read()` et `check()` prennent une seule ligne ; lorsque l'adaptateur retourne un tableau, `read()` donne son premier élément ou `null`.\n\n`scalar(table, type, key, key2)` calcule une valeur comme `'sum'`, `'avg'`, `'min'`, `'max'` ou `'count'` sur une colonne ; l'adaptateur décide de ce que retourne chaque type.\n\n## Écrire des données\n\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').callback(console.log);\n\nDATA.remove('users').where('id', 'u1').callback(console.log);\n```\n\nPasse `true` comme troisième argument de `update()` pour un **upsert** : lorsque la mise à jour ne modifie rien, le QueryBuilder efface les conditions et exécute le même payload en tant qu'`insert`. Avec `.insert(fn)`, tu peux modifier le payload juste avant cet insert :\n\n```js\nDATA.update('pages', { name: 'Home', dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n`returning('id,name')` demande à l'adaptateur de retourner ces colonnes des lignes modifiées.\n\n## Filtres\n\nTous les filtres sont combinés avec AND. Place un groupe dans `or()` pour le combiner avec OR.\n\n```js\nDATA.find('users')\n\t.where('age', '>=', 18)             // =, <>, >, <, >=, <= (== and != work too)\n\t.in('role', ['admin', 'editor'])\n\t.notin('id', ['u1', 'u2'])\n\t.between('dtcreated', NOW.add('-7 days'), NOW)\n\t.search('name', 'pet')              // contains the text\n\t.or(function(builder) {\n\t\tbuilder.where('isblocked', false);\n\t\tbuilder.empty('dtblocked');\n\t})\n\t.fields('id,name,email')\n\t.callback(console.log);\n```\n\n| Méthode | Condition |\n| --- | --- |\n| `where(name, [comparer], value)` | Compare une colonne. Avec un seul argument, c'est une condition brute (`query()`). |\n| `id(value)`, `userid(value)` | `where('id', …)`, ou `in('id', …)` pour un tableau |\n| `equal(obj)` | Un `where()` par clé de l'objet |\n| `in()`, `notin()` | La valeur est (ou n'est pas) dans une liste |\n| `between(name, a, b)` | Entre deux valeurs |\n| `search(name, value, [where])` | Recherche textuelle ; `where` peut valoir `'beg'` ou `'end'` |\n| `contains(name)`, `empty(name)` | La colonne a une valeur, ou est vide |\n| `array(name, [comparer], value)` | Une condition sur une colonne de type tableau (`&&` par défaut) |\n| `year()`, `month()`, `day()`, `hour()`, `minute()` | Compare une partie d'une date |\n| `query(sql)` | Une condition brute transmise telle quelle à l'adaptateur |\n\nL'adaptateur traduit ces éléments dans sa propre syntaxe : les comparateurs et les conditions brutes qui fonctionnent dépendent donc du moteur.\n\n## Tri et pagination\n\n```js\nDATA.find('products')\n\t.sort('price', 'desc')       // or true\n\t.sort('name')                // ascending\n\t.page(3, 20)                 // skip 40, take 20\n\t.callback(console.log);\n```\n\n`take()` (alias `limit()`), `skip()` et `first()` définissent directement les nombres. `paginate(page, limit, maxlimit)` accepte des valeurs provenant directement d'une query string et maintient la limite sous `maxlimit`. `gridsort('name_asc,dtcreated_desc')` lit une chaîne de tri.\n\n## Filtres depuis une query string\n\n`autoquery()` construit toute la requête à partir de la query string d'une requête HTTP. Tu listes les champs autorisés et leurs types ; tout le reste est ignoré.\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('products').autoquery($.query, 'id,name:string,price:number,dtcreated:date,ispublished:boolean', 'dtcreated_desc', 100).callback($);\n\t}\n});\n```\n\nAvec `?fields=id,name&name=phone&price=>100&sort=price_asc&page=2&limit=50`, cela sélectionne uniquement `id` et `name`, recherche dans `name`, conserve les lignes dont `price` est supérieur à 100, trie par `price` et retourne la deuxième page de 50 lignes (jamais plus de 100). Le second argument peut aussi être `'@SchemaName'` pour prendre les champs et les types d'un schéma JSON.\n\n`autoqueryjson($, column, schema, [defsort], [maxlimit])` fait la même chose pour des propriétés stockées dans une seule colonne JSON. Le QueryBuilder donne chaque propriété à l'adaptateur sous le nom `json:column:property:type` (par exemple `json:data:weight:number`), et l'adaptateur la traduit dans sa propre syntaxe. L'adaptateur PostgreSQL le fait ; voir [PostgreSQL](../../guides/postgresql/).\n\n`gridfields(fields, allowed)` sélectionne les colonnes à partir d'une liste séparée par des virgules, généralement `$.query.fields`, et ne garde que celles qui sont autorisées. Quand la liste est vide ou absente, ou qu'aucune n'est autorisée, la requête lit toutes les colonnes :\n\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n`gridfilter(name, query, type, [column])` fait de même pour un seul champ. La valeur de la query string détermine la condition :\n\n| Valeur | Condition |\n| --- | --- |\n| `phone` | `search` pour du texte, `=` pour les autres types |\n| `=phone` | Correspondance exacte |\n| `a,b,c` | Texte : l'un des mots (OR de `search`) ; autres types : `in` |\n| `=a,b` | Texte : `in` avec les valeurs exactes |\n| `10 - 20` | `between` |\n| `>10`, `<10` | Supérieur ou inférieur à (nombres et dates) |\n| `today`, `yesterday`, `2024-05-01` | La journée entière (dates) |\n| `2024`, `5` | L'année (un nombre supérieur à 1000) ou le mois (dates) |\n\n## Dans les actions\n\n`callback($)` transmet le résultat directement à l'action. `promise($)` fournit une promesse ; avec `$`, une erreur va dans `$.invalid()`.\n\n```js\nNEWACTION('Users/read', {\n\tname: 'Read user',\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar user = await DATA.read('users').id($.params.id).error('@(User not found)').promise($);\n\t\t$.callback(user);\n\t}\n});\n```\n\n`error(message)` transforme un résultat vide (aucune ligne, un tableau vide) en erreur avec ce message. Avec `error(message, true)`, c'est l'inverse : un résultat est une erreur, ce qui est utile pour les vérifications du type \"existe déjà\". `done($, fn)` appelle `fn(response)` en cas de succès et `$.invalid(err)` en cas d'erreur. `audit($, message)` écrit un enregistrement d'audit après une opération réussie ; `{data.name}` dans le message est remplacé à partir du payload. Voir [Actions](../../guides/actions/).\n\n## Plusieurs requêtes avec DB()\n\n`DB()` exécute ses requêtes l'une après l'autre, dans l'ordre où tu les ajoutes. `set(name)` stocke le résultat d'une requête sous une clé de la réponse finale ; sans lui, la réponse est le résultat de la dernière requête.\n\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user').error('@(User not found)');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nLa première erreur arrête la chaîne. `db.promise($)` et `db.done($, fn)` fonctionnent comme les méthodes du QueryBuilder. `db.debug()` définit l'option `debug` sur chaque requête, afin que les adaptateurs qui la prennent en charge puissent afficher les requêtes générées.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRj1cx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"QueryBuilder","summary":"Interroga qualsiasi database con un unico QueryBuilder: DATA, DB(), adapter, filtri, paginazione e autoquery.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> Interroga qualsiasi database con un unico QueryBuilder: DATA, DB(), adapter, filtri, paginazione e autoquery.\n\nTotal.js 5 ha un unico **QueryBuilder** per ogni database. Descrivi una query con dei metodi (`find`, `where`, `sort`, `take`…), il QueryBuilder trasforma le chiamate in un semplice oggetto di opzioni, e un **adapter** per il tuo motore di database trasforma quell'oggetto in una query reale. Il tuo codice resta lo stesso quando cambi motore; cambia solo l'adapter.\n\n```js\nDATA.find('users').where('isremoved', false).sort('name').take(20).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nL'elenco completo dei metodi è nel riferimento [QueryBuilder](../../reference/querybuilder/).\n\n## Le parti\n\n| Nome | Che cos'è |\n| --- | --- |\n| `DATA` | Un oggetto database globale e condiviso. Ogni chiamata su di esso avvia subito una query. |\n| `DB()` | Crea un nuovo oggetto database che esegue più query una dopo l'altra e ne raccoglie i risultati. |\n| `NEWDB(name, fn)` | Registra un adapter: la funzione che esegue le query per la connessione `name`. |\n| QueryBuilder | L'oggetto restituito da `find()`, `insert()` e dalle altre operazioni. Su di esso concateni i filtri. |\n\n## Registrare un adapter\n\nIl QueryBuilder non comunica da sé con alcun database. Un adapter è una funzione registrata con `NEWDB()`. Riceve le opzioni della query e una callback:\n\n```js\nNEWDB('default', function(filter, callback) {\n\t// filter.exec     the operation: find, list, read, check, count, scalar,\n\t//                 insert, update, remove, query, drop, truncate, command\n\t// filter.table    the table name\n\t// filter.filter   the conditions: [{ type: 'where', name, comparer, value }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload ...\n\tcallback(null, []);\n});\n```\n\nL'adapter della connessione viene scelto in base al nome della tabella. `'users'` usa la connessione `default`, `'logs/requests'` usa la connessione `logs` e la tabella `requests`. Quando nessun adapter ha quel nome, viene usato l'adapter `*` se esiste; altrimenti la query fallisce con l'errore `Database is not initialized`. Chiamare `NEWDB(name)` senza una funzione rimuove l'adapter.\n\nIl framework include l'adapter `nosql`, che esegue il QueryBuilder sui file NoSQL integrati: `DATA.find('nosql/users')`. Vedi [NoSQL](../../guides/nosql/). Per PostgreSQL, `DATA.init('default', 'postgresql://…')` registra un adapter che scrive l'SQL; vedi [PostgreSQL](../../guides/postgresql/).\n\n## Leggere i dati\n\n```js\n// all rows that match\nDATA.find('products').where('price', '>', 100).sort('price', true).callback(console.log);\n\n// one row (or null)\nDATA.read('products').id('p123').callback(console.log);\n\n// a page with metadata\nDATA.list('products').search('name', 'phone').page(2, 25).callback(function(err, response) {\n\t// response.items, response.count (from the adapter)\n\t// response.page, response.limit, response.pages (added by the QueryBuilder)\n});\n\n// true or false\nDATA.check('users').where('email', 'peter@example.com').callback(console.log);\n\n// number of rows\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n`list()` parte con `skip` 0 e `take` 100. `read()` e `check()` prendono una riga; quando l'adapter restituisce un array, `read()` restituisce il suo primo elemento o `null`.\n\n`scalar(table, type, key, key2)` calcola un valore come `'sum'`, `'avg'`, `'min'`, `'max'` o `'count'` su una colonna; è l'adapter a decidere cosa restituisce ogni tipo.\n\n## Scrivere i dati\n\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').callback(console.log);\n\nDATA.remove('users').where('id', 'u1').callback(console.log);\n```\n\nPassa `true` come terzo argomento di `update()` per un **upsert**: quando l'aggiornamento non modifica nulla, il QueryBuilder rimuove le condizioni ed esegue lo stesso payload come `insert`. Con `.insert(fn)` puoi modificare il payload subito prima di quell'insert:\n\n```js\nDATA.update('pages', { name: 'Home', dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n`returning('id,name')` chiede all'adapter di restituire quelle colonne delle righe modificate.\n\n## Filtri\n\nTutti i filtri sono uniti con AND. Metti un gruppo in `or()` per unirlo con OR.\n\n```js\nDATA.find('users')\n\t.where('age', '>=', 18)             // =, <>, >, <, >=, <= (== and != work too)\n\t.in('role', ['admin', 'editor'])\n\t.notin('id', ['u1', 'u2'])\n\t.between('dtcreated', NOW.add('-7 days'), NOW)\n\t.search('name', 'pet')              // contains the text\n\t.or(function(builder) {\n\t\tbuilder.where('isblocked', false);\n\t\tbuilder.empty('dtblocked');\n\t})\n\t.fields('id,name,email')\n\t.callback(console.log);\n```\n\n| Metodo | Condizione |\n| --- | --- |\n| `where(name, [comparer], value)` | Confronta una colonna. Con un solo argomento è una condizione grezza (`query()`). |\n| `id(value)`, `userid(value)` | `where('id', …)`, o `in('id', …)` per un array |\n| `equal(obj)` | Un `where()` per ogni chiave dell'oggetto |\n| `in()`, `notin()` | Il valore è (o non è) in un elenco |\n| `between(name, a, b)` | Tra due valori |\n| `search(name, value, [where])` | Ricerca testuale; `where` può essere `'beg'` o `'end'` |\n| `contains(name)`, `empty(name)` | La colonna ha un valore, o è vuota |\n| `array(name, [comparer], value)` | Una condizione su una colonna di tipo array (`&&` di default) |\n| `year()`, `month()`, `day()`, `hour()`, `minute()` | Confronta una parte di una data |\n| `query(sql)` | Una condizione grezza passata all'adapter così com'è |\n\nL'adapter traduce questi elementi nella propria sintassi, quindi quali comparatori e condizioni grezze funzionano dipende dal motore.\n\n## Ordinamento e paginazione\n\n```js\nDATA.find('products')\n\t.sort('price', 'desc')       // or true\n\t.sort('name')                // ascending\n\t.page(3, 20)                 // skip 40, take 20\n\t.callback(console.log);\n```\n\n`take()` (alias `limit()`), `skip()` e `first()` impostano direttamente i numeri. `paginate(page, limit, maxlimit)` accetta valori presi direttamente da una query string e mantiene il limite sotto `maxlimit`. `gridsort('name_asc,dtcreated_desc')` legge una stringa di ordinamento.\n\n## Filtri da una query string\n\n`autoquery()` costruisce l'intera query a partire dalla query string di una richiesta. Elenchi i campi consentiti e i loro tipi; tutto il resto viene ignorato.\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('products').autoquery($.query, 'id,name:string,price:number,dtcreated:date,ispublished:boolean', 'dtcreated_desc', 100).callback($);\n\t}\n});\n```\n\nCon `?fields=id,name&name=phone&price=>100&sort=price_asc&page=2&limit=50` questo seleziona solo `id` e `name`, cerca in `name`, mantiene le righe con `price` superiore a 100, ordina per `price` e restituisce la seconda pagina di 50 righe (mai più di 100). Il secondo argomento può anche essere `'@SchemaName'` per prendere campi e tipi da uno schema JSON.\n\n`autoqueryjson($, column, schema, [defsort], [maxlimit])` fa lo stesso per le proprietà salvate in una colonna JSON. Il QueryBuilder passa all'adapter ogni proprietà con il nome `json:column:property:type` (per esempio `json:data:weight:number`) e l'adapter lo traduce nella propria sintassi. L'adapter PostgreSQL lo fa; vedi [PostgreSQL](../../guides/postgresql/).\n\n`gridfields(fields, allowed)` seleziona le colonne da un elenco separato da virgole, di solito `$.query.fields`, e mantiene solo quelle consentite. Quando l'elenco è vuoto o manca, oppure nessuna è consentita, la query legge tutte le colonne:\n\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n`gridfilter(name, query, type, [column])` fa lo stesso per un singolo campo. Il valore della query string determina la condizione:\n\n| Valore | Condizione |\n| --- | --- |\n| `phone` | `search` per il testo, `=` per gli altri tipi |\n| `=phone` | Corrispondenza esatta |\n| `a,b,c` | Testo: una qualsiasi delle parole (OR di `search`); altri tipi: `in` |\n| `=a,b` | Testo: `in` con i valori esatti |\n| `10 - 20` | `between` |\n| `>10`, `<10` | Maggiore o minore di (numeri e date) |\n| `today`, `yesterday`, `2024-05-01` | L'intera giornata (date) |\n| `2024`, `5` | L'anno (un numero superiore a 1000) o il mese (date) |\n\n## All'interno delle azioni\n\n`callback($)` passa il risultato direttamente all'azione. `promise($)` restituisce una promise; con `$` un errore va a `$.invalid()`.\n\n```js\nNEWACTION('Users/read', {\n\tname: 'Read user',\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar user = await DATA.read('users').id($.params.id).error('@(User not found)').promise($);\n\t\t$.callback(user);\n\t}\n});\n```\n\n`error(message)` trasforma un risultato vuoto (nessuna riga, un array vuoto) in un errore con quel messaggio. Con `error(message, true)` è il contrario: un risultato è un errore, il che è utile per i controlli \"esiste già\". `done($, fn)` chiama `fn(response)` in caso di successo e `$.invalid(err)` in caso di errore. `audit($, message)` scrive un record di audit dopo un'operazione riuscita; `{data.name}` nel messaggio viene sostituito con il valore del payload. Vedi [Azioni](../../guides/actions/).\n\n## Più query con DB()\n\n`DB()` esegue le sue query una dopo l'altra, nell'ordine in cui le aggiungi. `set(name)` salva il risultato di una query sotto una chiave della risposta finale; senza di esso la risposta è il risultato dell'ultima query.\n\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user').error('@(User not found)');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nIl primo errore interrompe la catena. `db.promise($)` e `db.done($, fn)` funzionano come i metodi del QueryBuilder. `db.debug()` imposta l'opzione `debug` su ogni query, così gli adapter che la supportano possono stampare le query generate.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRj1cx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"QueryBuilder","summary":"Dotazuj akúkoľvek databázu jedným QueryBuilderom: DATA, DB(), adaptéry, filtre, stránkovanie a autoquery.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> Dotazuj akúkoľvek databázu jedným QueryBuilderom: DATA, DB(), adaptéry, filtre, stránkovanie a autoquery.\n\nTotal.js 5 má jeden **QueryBuilder** pre každú databázu. Dotaz opíšeš metódami (`find`, `where`, `sort`, `take`…), QueryBuilder zmení volania na obyčajný objekt volieb a **adaptér** pre tvoj databázový engine zmení tento objekt na skutočný dotaz. Keď zmeníš engine, tvoj kód zostane rovnaký; zmení sa len adaptér.\n\n```js\nDATA.find('users').where('isremoved', false).sort('name').take(20).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nÚplný zoznam metód je v referencii [QueryBuilder](../../reference/querybuilder/).\n\n## Časti\n\n| Meno | Čo to je |\n| --- | --- |\n| `DATA` | Globálny zdieľaný databázový objekt. Každé volanie na ňom okamžite spustí jeden dotaz. |\n| `DB()` | Vytvorí nový databázový objekt, ktorý spúšťa viac dotazov za sebou a zbiera ich výsledky. |\n| `NEWDB(name, fn)` | Zaregistruje adaptér: funkciu, ktorá vykonáva dotazy pre spojenie `name`. |\n| QueryBuilder | Objekt, ktorý vracajú `find()`, `insert()` a ostatné operácie. Reťazíš na ňom filtre. |\n\n## Registrácia adaptéra\n\nQueryBuilder sám s databázou nekomunikuje. Adaptér je funkcia zaregistrovaná cez `NEWDB()`. Dostane voľby dotazu a callback:\n\n```js\nNEWDB('default', function(filter, callback) {\n\t// filter.exec     the operation: find, list, read, check, count, scalar,\n\t//                 insert, update, remove, query, drop, truncate, command\n\t// filter.table    the table name\n\t// filter.filter   the conditions: [{ type: 'where', name, comparer, value }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload ...\n\tcallback(null, []);\n});\n```\n\nAdaptér spojenia sa vyberie podľa mena tabuľky. `'users'` používa spojenie `default`, `'logs/requests'` používa spojenie `logs` a tabuľku `requests`. Keď žiadny adaptér nemá také meno, použije sa adaptér `*`, ak existuje; inak dotaz zlyhá s chybou `Database is not initialized`. Volanie `NEWDB(name)` bez funkcie adaptér odstráni.\n\nFramework obsahuje adaptér `nosql`, ktorý spúšťa QueryBuilder nad vstavanými NoSQL súbormi: `DATA.find('nosql/users')`. Pozri [NoSQL](../../guides/nosql/). Pre PostgreSQL zaregistruje `DATA.init('default', 'postgresql://…')` adaptér, ktorý píše SQL; pozri [PostgreSQL](../../guides/postgresql/).\n\n## Čítanie dát\n\n```js\n// all rows that match\nDATA.find('products').where('price', '>', 100).sort('price', true).callback(console.log);\n\n// one row (or null)\nDATA.read('products').id('p123').callback(console.log);\n\n// a page with metadata\nDATA.list('products').search('name', 'phone').page(2, 25).callback(function(err, response) {\n\t// response.items, response.count (from the adapter)\n\t// response.page, response.limit, response.pages (added by the QueryBuilder)\n});\n\n// true or false\nDATA.check('users').where('email', 'peter@example.com').callback(console.log);\n\n// number of rows\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n`list()` začína so `skip` 0 a `take` 100. `read()` a `check()` berú jeden riadok; keď adaptér vráti pole, `read()` dá jeho prvú položku alebo `null`.\n\n`scalar(table, type, key, key2)` vypočíta hodnotu ako `'sum'`, `'avg'`, `'min'`, `'max'` alebo `'count'` nad stĺpcom; čo každý typ vráti, rozhoduje adaptér.\n\n## Zápis dát\n\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').callback(console.log);\n\nDATA.remove('users').where('id', 'u1').callback(console.log);\n```\n\nOdovzdaj `true` ako tretí argument `update()` pre **upsert**: keď aktualizácia nič nezmení, QueryBuilder vymaže podmienky a spustí ten istý payload ako `insert`. Cez `.insert(fn)` môžeš payload zmeniť tesne pred týmto insertom:\n\n```js\nDATA.update('pages', { name: 'Home', dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n`returning('id,name')` požiada adaptér o vrátenie týchto stĺpcov zmenených riadkov.\n\n## Filtre\n\nVšetky filtre sa spájajú cez AND. Skupinu daj do `or()`, ak ju chceš spojiť cez OR.\n\n```js\nDATA.find('users')\n\t.where('age', '>=', 18)             // =, <>, >, <, >=, <= (== and != work too)\n\t.in('role', ['admin', 'editor'])\n\t.notin('id', ['u1', 'u2'])\n\t.between('dtcreated', NOW.add('-7 days'), NOW)\n\t.search('name', 'pet')              // contains the text\n\t.or(function(builder) {\n\t\tbuilder.where('isblocked', false);\n\t\tbuilder.empty('dtblocked');\n\t})\n\t.fields('id,name,email')\n\t.callback(console.log);\n```\n\n| Metóda | Podmienka |\n| --- | --- |\n| `where(name, [comparer], value)` | Porovná stĺpec. S jedným argumentom je to surová podmienka (`query()`). |\n| `id(value)`, `userid(value)` | `where('id', …)` alebo pre pole `in('id', …)` |\n| `equal(obj)` | Jedno `where()` pre každý kľúč objektu |\n| `in()`, `notin()` | Hodnota (ne)je v zozname |\n| `between(name, a, b)` | Medzi dvoma hodnotami |\n| `search(name, value, [where])` | Textové vyhľadávanie; `where` môže byť `'beg'` alebo `'end'` |\n| `contains(name)`, `empty(name)` | Stĺpec má hodnotu alebo je prázdny |\n| `array(name, [comparer], value)` | Podmienka na stĺpec typu pole (predvolene `&&`) |\n| `year()`, `month()`, `day()`, `hour()`, `minute()` | Porovná časť dátumu |\n| `query(sql)` | Surová podmienka odovzdaná adaptéru tak, ako je |\n\nAdaptér preloží tieto položky do vlastnej syntaxe, takže to, ktoré porovnávače a surové podmienky fungujú, závisí od enginu.\n\n## Triedenie a stránkovanie\n\n```js\nDATA.find('products')\n\t.sort('price', 'desc')       // or true\n\t.sort('name')                // ascending\n\t.page(3, 20)                 // skip 40, take 20\n\t.callback(console.log);\n```\n\n`take()` (alias `limit()`), `skip()` a `first()` nastavujú čísla priamo. `paginate(page, limit, maxlimit)` prijíma hodnoty priamo z query stringu a drží limit pod `maxlimit`. `gridsort('name_asc,dtcreated_desc')` prečíta reťazec triedenia.\n\n## Filtre z query stringu\n\n`autoquery()` zostaví celý dotaz z query stringu požiadavky. Uvedieš povolené polia a ich typy; všetko ostatné sa ignoruje.\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('products').autoquery($.query, 'id,name:string,price:number,dtcreated:date,ispublished:boolean', 'dtcreated_desc', 100).callback($);\n\t}\n});\n```\n\nS `?fields=id,name&name=phone&price=>100&sort=price_asc&page=2&limit=50` vyberie len `id` a `name`, vyhľadá v `name`, ponechá riadky s `price` nad 100, zotriedi podľa `price` a vráti druhú stranu s 50 riadkami (nikdy viac ako 100). Druhý argument môže byť aj `'@SchemaName'`, aby sa polia a typy vzali z JSON schémy.\n\n`autoqueryjson($, column, schema, [defsort], [maxlimit])` robí to isté pre vlastnosti uložené v jednom JSON stĺpci. QueryBuilder odovzdá adaptéru každú vlastnosť ako názov `json:column:property:type` (napríklad `json:data:weight:number`) a adaptér ho preloží do vlastnej syntaxe. Adaptér PostgreSQL to robí; pozri [PostgreSQL](../../guides/postgresql/).\n\n`gridfields(fields, allowed)` vyberie stĺpce zo zoznamu oddeleného čiarkami, zvyčajne `$.query.fields`, a ponechá iba povolené. Keď je zoznam prázdny alebo chýba, alebo nie je povolený žiadny z nich, dopyt načíta všetky stĺpce:\n\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n`gridfilter(name, query, type, [column])` robí to isté pre jedno pole. Podmienku určuje hodnota query stringu:\n\n| Hodnota | Podmienka |\n| --- | --- |\n| `phone` | `search` pre text, `=` pre ostatné typy |\n| `=phone` | Presná zhoda |\n| `a,b,c` | Text: ktorékoľvek zo slov (OR z `search`); ostatné typy: `in` |\n| `=a,b` | Text: `in` s presnými hodnotami |\n| `10 - 20` | `between` |\n| `>10`, `<10` | Väčšie alebo menšie ako (čísla a dátumy) |\n| `today`, `yesterday`, `2024-05-01` | Celý deň (dátumy) |\n| `2024`, `5` | Rok (číslo nad 1000) alebo mesiac (dátumy) |\n\n## Vnútri akcií\n\n`callback($)` odovzdá výsledok priamo akcii. `promise($)` dá promise; s `$` ide chyba do `$.invalid()`.\n\n```js\nNEWACTION('Users/read', {\n\tname: 'Read user',\n\tparams: '*id:UID',\n\taction: async function($) {\n\t\tvar user = await DATA.read('users').id($.params.id).error('@(User not found)').promise($);\n\t\t$.callback(user);\n\t}\n});\n```\n\n`error(message)` zmení prázdny výsledok (žiadny riadok, prázdne pole) na chybu s touto správou. S `error(message, true)` je to naopak: výsledok je chyba, čo sa hodí na kontroly typu „už existuje“. `done($, fn)` zavolá `fn(response)` pri úspechu a `$.invalid(err)` pri chybe. `audit($, message)` zapíše po úspešnej operácii auditný záznam; `{data.name}` v správe sa nahradí z payloadu. Pozri [Akcie](../../guides/actions/).\n\n## Viac dotazov cez DB()\n\n`DB()` spúšťa svoje dotazy za sebou, v poradí, v akom ich pridáš. `set(name)` uloží výsledok dotazu pod kľúč výslednej odpovede; bez neho je odpoveďou výsledok posledného dotazu.\n\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user').error('@(User not found)');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nPrvá chyba zastaví reťazec. `db.promise($)` a `db.done($, fn)` fungujú ako metódy QueryBuildera. `db.debug()` nastaví voľbu `debug` pre každý dotaz, takže adaptéry, ktoré ju podporujú, môžu vypísať vygenerované dotazy.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwS73Wx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/postgresql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"PostgreSQL","summary":"Connect to PostgreSQL with DATA.init() and run the QueryBuilder, raw SQL and transactions on it.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/postgresql/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# PostgreSQL\n\n> Connect to PostgreSQL with DATA.init() and run the QueryBuilder, raw SQL and transactions on it.\n\nTotal.js 5 has its own PostgreSQL client, written for the framework and without other npm packages, and an adapter that runs the QueryBuilder on PostgreSQL. You register a connection once with `DATA.init()`. After that `DATA`, `DB()` and every method of the QueryBuilder work as described in [QueryBuilder](../../guides/querybuilder/), and the adapter writes the SQL.\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n\nDATA.find('tbl_product').where('price', '>', 100).sort('name').take(20).callback(console.log);\n// SELECT * FROM tbl_product WHERE \"price\">100 ORDER BY \"name\" ASC LIMIT 20\n```\n\nThe full list of options and functions is in the reference of [PostgreSQL](../../reference/postgresql/).\n\n## Connecting\n\nKeep the connection string in the `config` file:\n\n```\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nRegister the connection when the application starts, for example in `definitions/db.js`:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nThe first argument is the connection name. The connection `default` serves the tables without a prefix (`DATA.find('tbl_product')`). A connection with another name serves the tables with that prefix:\n\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nCalling `DATA.init()` again with the same name closes the old connections and replaces them. `DATA.init(name)` without a connection string removes the connection; its queries then fail with `Database is not initialized`.\n\n## The connection string\n\nThe connection string is a URL: `postgresql://user:password@host:port/database`. The port defaults to `5432`. Without a database name the client uses the database named like the user. Encode special characters in the user name and the password with `encodeURIComponent()`.\n\nOptions go in the query string, joined with `&`:\n\n| Option | What it does |\n| --- | --- |\n| `pooling=10` | Keeps a pool of up to 10 connections. Without it every query opens a new connection and closes it at the end. |\n| `schema=eshop` | The schema of the tables: `DATA.find('tbl_product')` reads `eshop.tbl_product`. |\n| `sslmode=require` | Encrypts the connection (see below). `ssl=true` is the same. |\n| `connect_timeout=5` | Seconds to wait for the connection. Then the query fails with `Connection timeout`. |\n| `application_name=eshop` | The name of the connections in `pg_stat_activity`. |\n| `host`, `port`, `user`, `password`, `dbname` | Replace the parts of the URL. A `host` that starts with `/` is the directory of a Unix socket. |\n\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\nThe values of `sslmode`:\n\n| Value | Connection |\n| --- | --- |\n| `disable` (default) | Not encrypted. |\n| `prefer`, `allow` | Encrypted when the server supports SSL, otherwise not encrypted. |\n| `require`, `no-verify` | Encrypted, the certificate is not checked. A server without SSL gives the error `The server does not support SSL connections`. |\n| `verify-ca`, `verify-full` | Encrypted, the certificate of the server must be valid. |\n\nThe client signs in with a password in plain text, MD5 or SCRAM-SHA-256, as the server asks.\n\nIn a pool, an idle connection closes after 10 seconds. A connection that comes back to the pool inside an open transaction is closed and not used again.\n\n## Schemas\n\n`schema` in the connection string sets the schema for every table of the connection. `schema(name)` on the QueryBuilder changes it for one query:\n\n```js\nDATA.find('tbl_product').schema('archive').callback(console.log);\n// SELECT * FROM archive.tbl_product\n```\n\nRaw queries (`DATA.query()`) do not use the schema; write it in the SQL.\n\n## The SQL of the QueryBuilder\n\nColumn names are written in double quotes (`\"price\"`). A name with a space, a dot, a colon or a double quote is written as it is, so a field can be an expression:\n\n```js\nDATA.find('tbl_product')\n\t.where('isremoved', false)\n\t.in('id', ['p1', 'p2'])\n\t.search('name', 'pho')\n\t.array('tags', ['sale'])\n\t.fields('id, name, UPPER(name) AS code')\n\t.callback(console.log);\n\n// SELECT \"id\",\"name\",UPPER(name) AS code FROM tbl_product\n// WHERE \"isremoved\"=false AND \"id\" IN ('p1','p2') AND \"name\"::text ILIKE '%pho%' AND \"tags\" && ARRAY['sale']\n```\n\nThe values of conditions are escaped and written into the SQL. The payload of `insert()` and `update()` goes to the server as parameters (`$1`, `$2`…).\n\n| Method | SQL |\n| --- | --- |\n| `where('age', '>', 20)` | `\"age\">20` |\n| `where('dtremoved', null)` | `\"dtremoved\" IS NULL` (`IS NOT NULL` with the comparer `<>`) |\n| `in('id', ['a', 'b'])`, `notin()` | `\"id\" IN ('a','b')`, `\"id\" NOT IN (…)` |\n| `between('age', 20, 30)` | `(\"age\" BETWEEN 20 AND 30)` |\n| `search('name', 'pet')` | `\"name\"::text ILIKE '%pet%'` |\n| `search('name', 'pet', 'beg')` | `\"name\"::text ILIKE 'pet%'` (the text is at the beginning) |\n| `search('name', 'pet', 'end')` | `\"name\"::text ILIKE '%pet'` (the text is at the end) |\n| `array('tags', ['a'])` | `\"tags\" && ARRAY['a']`; another comparer, for example `array('tags', '@>', ['a'])`, replaces `&&` |\n| `year('dtcreated', 2024)` | `EXTRACT(year from \"dtcreated\")=2024`; `month()`, `day()`, `hour()` and `minute()` work in the same way |\n| `contains('tags')` | `LENGTH(\"tags\"::text)>0` |\n| `empty('tags')` | `(\"tags\" IS NULL OR LENGTH(\"tags\"::text)=0)` |\n| `query('age % 2 = 0')` | `(age % 2 = 0)` |\n| `or(fn)` | `(… OR …)` |\n| `permit('permissions', 'R', ['admin'], userid)` | `(userid='…' OR array_length(\"permissions\",1) IS NULL OR \"permissions\"::_text && ARRAY['Radmin'])`; with `required` set to `false` the `array_length()` part is left out |\n| `sort('name', true)` | `ORDER BY \"name\" DESC` |\n| `take(20)`, `skip(40)` | `LIMIT 20 OFFSET 40` |\n\n`join()` adds nothing to the SQL; write joins in a raw query. A column name that ends with `§` gets the language of the query: with `language('sk', '_')` the field `name§` is read as `\"name_sk\" AS \"name\"`.\n\n## Results\n\n| Operation | Result |\n| --- | --- |\n| `find()` | An array of rows. |\n| `read()` | One row or `null`. |\n| `list()` | `{ items, count, page, limit, pages }`. The adapter runs two queries: the page and `SELECT COUNT(1)`. |\n| `check()` | `true` or `false`. |\n| `count()` | A number. |\n| `scalar(table, 'sum', 'price')` | A number; also `avg`, `min`, `max` and `count`. |\n| `scalar(table, 'group', 'kind', 'price')` | Rows `{ kind, value }`: the sum of `price` for each `kind` (without the fourth argument the number of rows). |\n| `insert()` | The number of inserted rows. With `primarykey('id')` the value of that column, with `returning('id,dtcreated')` the inserted row. |\n| `update()` | The number of changed rows. With `returning()` an array of the changed rows, with `returning()` and `first()` one row. |\n| `remove()` | The number of removed rows. With `returning()` an array of the removed rows. |\n| `query()` | An array of rows. |\n| `truncate()` | Runs `TRUNCATE TABLE … RESTART IDENTITY`. |\n| `drop()` | Runs `DROP TABLE …`. |\n\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n\nDATA.update('tbl_product', { '*price': 0.9 }).where('price', '>', 100).returning('id,price').callback(console.log);\n// null [ { id: 'p2', price: 270 }, { id: 'p1', price: 108 } ]\n```\n\n## Operators in the payload\n\nThe first character of a key in the payload of `update()` can change the value in the database instead of replacing it:\n\n| Key | SQL |\n| --- | --- |\n| `'+stock': 5` | `\"stock\"=COALESCE(\"stock\",0)+$1`; also `-`, `*` and `/` |\n| `'>price': 10` | `\"price\"=GREATEST(\"price\",$1)` |\n| `'<price': 10` | `\"price\"=LEAST(\"price\",$1)` |\n| `'!isread': 1` | `\"isread\"=NOT \"isread\"` |\n| `'=dtupdated': 'NOW()'` | `\"dtupdated\"=NOW()`, the value is raw SQL |\n| `'#dtupdated': 'NOW()'` | The same as `=`, but `insert()` leaves the key out |\n\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n// UPDATE tbl_product SET \"stock\"=COALESCE(\"stock\",0)+$1,\"reserved\"=COALESCE(\"reserved\",0)-$2,\"dtupdated\"=NOW() WHERE \"id\"='p1'\n```\n\nIn `insert()` the character is removed: the column gets the value (`0` when the value is empty), `!` inserts `FALSE` and `=` inserts the raw SQL. So the same payload works in an upsert. This counter adds a row for the day and then increases it:\n\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n// the first call: INSERT INTO tbl_visitor (\"count\",\"dtupdated\",\"id\") VALUES($1,NOW(),$2)\n// the next calls: UPDATE tbl_visitor SET \"count\"=COALESCE(\"count\",0)+$1,\"dtupdated\"=NOW() WHERE \"id\"='2026-11-16'\n```\n\n## Properties of a JSON column\n\n`autoqueryjson()` works like `autoquery()`, but for properties stored in one JSON or JSONB column. It reads fields, filters, sort and paging from the query string, and the adapter reads each property with `->>` and converts it to its type:\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('tbl_product')\n\t\t\t.autoquery($.query, 'id,name,price:number', 'name_asc', 100)\n\t\t\t.autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date')\n\t\t\t.callback($);\n\t}\n});\n```\n\nWith `?fields=id,name,color,weight&color=red&weight=<100` the response has the columns `id` and `name` and the properties `color` and `weight` of the column `data`, for the red products lighter than 100:\n\n```js\n{ items: [{ id: 'p3', name: \"Kid's watch\", color: 'red', weight: 40 }], count: 1, page: 1, limit: 100, pages: 1 }\n```\n\nA value of a wrong type never makes the query fail:\n\n| Type | Result |\n| --- | --- |\n| `string` (default) | The text. |\n| `number` | A number; `0` when the value is not a number. |\n| `boolean` | `true` for `true`, `1`, `on` and `yes`, otherwise `false`. |\n| `date` | A `Date`; `null` when the value is not a valid date (`2024-02-30`). |\n| `[string]` | An array of strings; `[]` when the value is not an array. |\n\nA missing property is `null`. The filters, the sort and the types of the values are the same as in `autoquery()`.\n\n## Raw queries\n\n`DATA.query()` sends the SQL as it is. Parameters are `$1`, `$2`… and their values go in an array:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1 ORDER BY id', [100]).callback(console.log);\n```\n\nConditions added with the QueryBuilder replace the text `{where}`, or are added at the end of the SQL when it has no `{where}`:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product {where} ORDER BY id').where('isremoved', false).search('name', 'a').callback(console.log);\n// SELECT id, name FROM eshop.tbl_product WHERE \"isremoved\"=false AND \"name\"::text ILIKE '%a%' ORDER BY id\n```\n\n## Transactions\n\nEach query of `DATA` and `DB()` gets its own connection, so a `BEGIN` in one query and a `COMMIT` in the next one do not belong together. Write the whole transaction as one raw query without parameters. When a statement fails, PostgreSQL rolls back the whole transaction and the callback gets the error. A query with several statements returns no rows (`undefined`):\n\n```js\nDATA.query(`BEGIN;\nUPDATE eshop.tbl_product SET stock=stock-1 WHERE id='p1';\nINSERT INTO eshop.tbl_order (id, productid, count) VALUES('o1', 'p1', 1);\nCOMMIT`).callback(console.log);\n```\n\nWhen the transaction needs parameters or JavaScript between the statements, use the client directly (see below).\n\n## Errors and debugging\n\nAn error of the server is an `Error` with the message of PostgreSQL and the fields of the server: `code`, `detail`, `hint`, `position`, `schema`, `table`, `column`, `constraint`, `severity` and others.\n\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\nEvery failed query is also logged with `ERROR()`, with the first 100 characters of the SQL. A function as the third argument of `DATA.init()` gets this text instead:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n\t// SQL error: Error: column \"unknown\" does not exist - SELECT * FROM tbl_product WHERE \"unknown\"=1\n});\n```\n\n`debug()` on a query (or on a `DB()` chain) prints the SQL and the parameters to the console:\n\n```\n-- PostgreSQL --> SELECT \"id\",\"name\" FROM eshop.tbl_product ORDER BY \"price\" DESC LIMIT 2 undefined\n```\n\n## Types of values\n\n| PostgreSQL | JavaScript |\n| --- | --- |\n| `boolean` | `Boolean` |\n| `smallint`, `integer`, `real`, `double precision`, `numeric` | `Number` |\n| `bigint` | `String` (it does not always fit into a JavaScript number) |\n| `json`, `jsonb` | The parsed value; texts in the ISO date format become `Date` objects |\n| `date`, `timestamp`, `timestamptz` | `Date` |\n| `bytea` | `Buffer` |\n| arrays | `Array` of the same types |\n| other types | `String` |\n\n`COUNT(*)` in raw SQL is a `bigint`, so it comes as a string. Cast it (`COUNT(*)::int`), or change the parser of the type with its OID:\n\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value; // bigint as a number\n```\n\nIn parameters, a `Date` is sent with its time zone, an object as JSON, a `Buffer` as binary data, and an array as a PostgreSQL array, or as JSON when the parameter is a `json` or `jsonb` column.\n\n## The client without the QueryBuilder\n\nThe client is a module of the framework: `require('total5/client-postgresql')`. Use it when you need one connection for several queries, for example a transaction with parameters:\n\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n`client.query()` and `pool.query()` return `{ command, rowCount, rows, fields }`, through a callback or a promise.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwS73Wx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/postgresql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"PostgreSQL","summary":"Mit DATA.init() eine Verbindung zu PostgreSQL herstellen und darauf den QueryBuilder, rohes SQL und Transaktionen ausführen.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/postgresql/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# PostgreSQL\n\n> Mit DATA.init() eine Verbindung zu PostgreSQL herstellen und darauf den QueryBuilder, rohes SQL und Transaktionen ausführen.\n\nTotal.js 5 hat einen eigenen PostgreSQL-Client, geschrieben für das Framework und ohne weitere npm-Pakete, und einen Adapter, der den QueryBuilder auf PostgreSQL ausführt. Du registrierst eine Verbindung einmal mit `DATA.init()`. Danach funktionieren `DATA`, `DB()` und jede Methode des QueryBuilders wie in [QueryBuilder](../../guides/querybuilder/) beschrieben, und der Adapter schreibt das SQL.\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n\nDATA.find('tbl_product').where('price', '>', 100).sort('name').take(20).callback(console.log);\n// SELECT * FROM tbl_product WHERE \"price\">100 ORDER BY \"name\" ASC LIMIT 20\n```\n\nDie vollständige Liste der Optionen und Funktionen steht in der Referenz [PostgreSQL](../../reference/postgresql/).\n\n## Verbinden\n\nLege den Connection String in der Datei `config` ab:\n\n```\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nRegistriere die Verbindung beim Start der Anwendung, zum Beispiel in `definitions/db.js`:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nDas erste Argument ist der Name der Verbindung. Die Verbindung `default` bedient die Tabellen ohne Präfix (`DATA.find('tbl_product')`). Eine Verbindung mit einem anderen Namen bedient die Tabellen mit diesem Präfix:\n\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nEin erneuter Aufruf von `DATA.init()` mit demselben Namen schließt die alten Verbindungen und ersetzt sie. `DATA.init(name)` ohne Connection String entfernt die Verbindung; ihre Abfragen schlagen dann mit `Database is not initialized` fehl.\n\n## Der Connection String\n\nDer Connection String ist eine URL: `postgresql://user:password@host:port/database`. Der Port ist standardmäßig `5432`. Ohne Datenbanknamen verwendet der Client die Datenbank, die wie der Benutzer heißt. Kodiere Sonderzeichen im Benutzernamen und im Passwort mit `encodeURIComponent()`.\n\nOptionen stehen im Query String, verbunden mit `&`:\n\n| Option | Was sie bewirkt |\n| --- | --- |\n| `pooling=10` | Hält einen Pool von bis zu 10 Verbindungen. Ohne diese Option öffnet jede Abfrage eine neue Verbindung und schließt sie am Ende. |\n| `schema=eshop` | Das Schema der Tabellen: `DATA.find('tbl_product')` liest `eshop.tbl_product`. |\n| `sslmode=require` | Verschlüsselt die Verbindung (siehe unten). `ssl=true` ist dasselbe. |\n| `connect_timeout=5` | Sekunden, die auf die Verbindung gewartet wird. Danach schlägt die Abfrage mit `Connection timeout` fehl. |\n| `application_name=eshop` | Der Name der Verbindungen in `pg_stat_activity`. |\n| `host`, `port`, `user`, `password`, `dbname` | Ersetzen die Teile der URL. Ein `host`, der mit `/` beginnt, ist das Verzeichnis eines Unix-Sockets. |\n\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\nDie Werte von `sslmode`:\n\n| Wert | Verbindung |\n| --- | --- |\n| `disable` (Standard) | Nicht verschlüsselt. |\n| `prefer`, `allow` | Verschlüsselt, wenn der Server SSL unterstützt, sonst nicht verschlüsselt. |\n| `require`, `no-verify` | Verschlüsselt, das Zertifikat wird nicht geprüft. Ein Server ohne SSL liefert den Fehler `The server does not support SSL connections`. |\n| `verify-ca`, `verify-full` | Verschlüsselt, das Zertifikat des Servers muss gültig sein. |\n\nDer Client meldet sich mit einem Passwort im Klartext, mit MD5 oder mit SCRAM-SHA-256 an, je nachdem, was der Server verlangt.\n\nIn einem Pool wird eine unbenutzte Verbindung nach 10 Sekunden geschlossen. Eine Verbindung, die innerhalb einer offenen Transaktion in den Pool zurückkommt, wird geschlossen und nicht mehr verwendet.\n\n## Schemas\n\n`schema` im Connection String setzt das Schema für jede Tabelle der Verbindung. `schema(name)` am QueryBuilder ändert es für eine einzelne Abfrage:\n\n```js\nDATA.find('tbl_product').schema('archive').callback(console.log);\n// SELECT * FROM archive.tbl_product\n```\n\nRohe Abfragen (`DATA.query()`) verwenden das Schema nicht; schreib es ins SQL.\n\n## Das SQL des QueryBuilders\n\nSpaltennamen werden in doppelten Anführungszeichen geschrieben (`\"price\"`). Ein Name mit einem Leerzeichen, einem Punkt, einem Doppelpunkt oder einem doppelten Anführungszeichen wird so geschrieben, wie er ist, daher kann ein Feld ein Ausdruck sein:\n\n```js\nDATA.find('tbl_product')\n\t.where('isremoved', false)\n\t.in('id', ['p1', 'p2'])\n\t.search('name', 'pho')\n\t.array('tags', ['sale'])\n\t.fields('id, name, UPPER(name) AS code')\n\t.callback(console.log);\n\n// SELECT \"id\",\"name\",UPPER(name) AS code FROM tbl_product\n// WHERE \"isremoved\"=false AND \"id\" IN ('p1','p2') AND \"name\"::text ILIKE '%pho%' AND \"tags\" && ARRAY['sale']\n```\n\nDie Werte von Bedingungen werden escaped und ins SQL geschrieben. Der Payload von `insert()` und `update()` geht als Parameter (`$1`, `$2`…) an den Server.\n\n| Methode | SQL |\n| --- | --- |\n| `where('age', '>', 20)` | `\"age\">20` |\n| `where('dtremoved', null)` | `\"dtremoved\" IS NULL` (`IS NOT NULL` mit dem Vergleichsoperator `<>`) |\n| `in('id', ['a', 'b'])`, `notin()` | `\"id\" IN ('a','b')`, `\"id\" NOT IN (…)` |\n| `between('age', 20, 30)` | `(\"age\" BETWEEN 20 AND 30)` |\n| `search('name', 'pet')` | `\"name\"::text ILIKE '%pet%'` |\n| `search('name', 'pet', 'beg')` | `\"name\"::text ILIKE 'pet%'` (der Text steht am Anfang) |\n| `search('name', 'pet', 'end')` | `\"name\"::text ILIKE '%pet'` (der Text steht am Ende) |\n| `array('tags', ['a'])` | `\"tags\" && ARRAY['a']`; ein anderer Vergleichsoperator, zum Beispiel `array('tags', '@>', ['a'])`, ersetzt `&&` |\n| `year('dtcreated', 2024)` | `EXTRACT(year from \"dtcreated\")=2024`; `month()`, `day()`, `hour()` und `minute()` funktionieren genauso |\n| `contains('tags')` | `LENGTH(\"tags\"::text)>0` |\n| `empty('tags')` | `(\"tags\" IS NULL OR LENGTH(\"tags\"::text)=0)` |\n| `query('age % 2 = 0')` | `(age % 2 = 0)` |\n| `or(fn)` | `(… OR …)` |\n| `permit('permissions', 'R', ['admin'], userid)` | `(userid='…' OR array_length(\"permissions\",1) IS NULL OR \"permissions\"::_text && ARRAY['Radmin'])`; wenn `required` auf `false` steht, entfällt der Teil mit `array_length()` |\n| `sort('name', true)` | `ORDER BY \"name\" DESC` |\n| `take(20)`, `skip(40)` | `LIMIT 20 OFFSET 40` |\n\n`join()` fügt dem SQL nichts hinzu; schreib Joins in einer rohen Abfrage. Ein Spaltenname, der mit `§` endet, erhält die Sprache der Abfrage: Mit `language('sk', '_')` wird das Feld `name§` als `\"name_sk\" AS \"name\"` gelesen.\n\n## Ergebnisse\n\n| Operation | Ergebnis |\n| --- | --- |\n| `find()` | Ein Array von Zeilen. |\n| `read()` | Eine Zeile oder `null`. |\n| `list()` | `{ items, count, page, limit, pages }`. Der Adapter führt zwei Abfragen aus: die Seite und `SELECT COUNT(1)`. |\n| `check()` | `true` oder `false`. |\n| `count()` | Eine Zahl. |\n| `scalar(table, 'sum', 'price')` | Eine Zahl; ebenso `avg`, `min`, `max` und `count`. |\n| `scalar(table, 'group', 'kind', 'price')` | Zeilen `{ kind, value }`: die Summe von `price` für jedes `kind` (ohne das vierte Argument die Anzahl der Zeilen). |\n| `insert()` | Die Anzahl der eingefügten Zeilen. Mit `primarykey('id')` der Wert dieser Spalte, mit `returning('id,dtcreated')` die eingefügte Zeile. |\n| `update()` | Die Anzahl der geänderten Zeilen. Mit `returning()` ein Array der geänderten Zeilen, mit `returning()` und `first()` eine Zeile. |\n| `remove()` | Die Anzahl der entfernten Zeilen. Mit `returning()` ein Array der entfernten Zeilen. |\n| `query()` | Ein Array von Zeilen. |\n| `truncate()` | Führt `TRUNCATE TABLE … RESTART IDENTITY` aus. |\n| `drop()` | Führt `DROP TABLE …` aus. |\n\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n\nDATA.update('tbl_product', { '*price': 0.9 }).where('price', '>', 100).returning('id,price').callback(console.log);\n// null [ { id: 'p2', price: 270 }, { id: 'p1', price: 108 } ]\n```\n\n## Operatoren im Payload\n\nDas erste Zeichen eines Schlüssels im Payload von `update()` kann den Wert in der Datenbank verändern, statt ihn zu ersetzen:\n\n| Schlüssel | SQL |\n| --- | --- |\n| `'+stock': 5` | `\"stock\"=COALESCE(\"stock\",0)+$1`; ebenso `-`, `*` und `/` |\n| `'>price': 10` | `\"price\"=GREATEST(\"price\",$1)` |\n| `'<price': 10` | `\"price\"=LEAST(\"price\",$1)` |\n| `'!isread': 1` | `\"isread\"=NOT \"isread\"` |\n| `'=dtupdated': 'NOW()'` | `\"dtupdated\"=NOW()`, der Wert ist rohes SQL |\n| `'#dtupdated': 'NOW()'` | Dasselbe wie `=`, aber `insert()` lässt den Schlüssel weg |\n\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n// UPDATE tbl_product SET \"stock\"=COALESCE(\"stock\",0)+$1,\"reserved\"=COALESCE(\"reserved\",0)-$2,\"dtupdated\"=NOW() WHERE \"id\"='p1'\n```\n\nIn `insert()` wird das Zeichen entfernt: Die Spalte erhält den Wert (`0`, wenn der Wert leer ist), `!` fügt `FALSE` ein und `=` das rohe SQL. So funktioniert derselbe Payload in einem Upsert. Dieser Zähler legt eine Zeile für den Tag an und erhöht sie danach:\n\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n// the first call: INSERT INTO tbl_visitor (\"count\",\"dtupdated\",\"id\") VALUES($1,NOW(),$2)\n// the next calls: UPDATE tbl_visitor SET \"count\"=COALESCE(\"count\",0)+$1,\"dtupdated\"=NOW() WHERE \"id\"='2026-11-16'\n```\n\n## Eigenschaften einer JSON-Spalte\n\n`autoqueryjson()` funktioniert wie `autoquery()`, aber für Eigenschaften, die in einer JSON- oder JSONB-Spalte gespeichert sind. Es liest Felder, Filter, Sortierung und Paging aus dem Query String, und der Adapter liest jede Eigenschaft mit `->>` und wandelt sie in ihren Typ um:\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('tbl_product')\n\t\t\t.autoquery($.query, 'id,name,price:number', 'name_asc', 100)\n\t\t\t.autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date')\n\t\t\t.callback($);\n\t}\n});\n```\n\nMit `?fields=id,name,color,weight&color=red&weight=<100` enthält die Antwort die Spalten `id` und `name` sowie die Eigenschaften `color` und `weight` der Spalte `data`, für die roten Produkte, die leichter als 100 sind:\n\n```js\n{ items: [{ id: 'p3', name: \"Kid's watch\", color: 'red', weight: 40 }], count: 1, page: 1, limit: 100, pages: 1 }\n```\n\nEin Wert mit falschem Typ lässt die Abfrage nie fehlschlagen:\n\n| Typ | Ergebnis |\n| --- | --- |\n| `string` (Standard) | Der Text. |\n| `number` | Eine Zahl; `0`, wenn der Wert keine Zahl ist. |\n| `boolean` | `true` für `true`, `1`, `on` und `yes`, sonst `false`. |\n| `date` | Ein `Date`; `null`, wenn der Wert kein gültiges Datum ist (`2024-02-30`). |\n| `[string]` | Ein Array von Strings; `[]`, wenn der Wert kein Array ist. |\n\nEine fehlende Eigenschaft ist `null`. Die Filter, die Sortierung und die Typen der Werte sind dieselben wie in `autoquery()`.\n\n## Rohe Abfragen\n\n`DATA.query()` sendet das SQL so, wie es ist. Parameter sind `$1`, `$2`…, und ihre Werte stehen in einem Array:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1 ORDER BY id', [100]).callback(console.log);\n```\n\nBedingungen, die mit dem QueryBuilder hinzugefügt werden, ersetzen den Text `{where}` oder werden ans Ende des SQL angehängt, wenn es kein `{where}` enthält:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product {where} ORDER BY id').where('isremoved', false).search('name', 'a').callback(console.log);\n// SELECT id, name FROM eshop.tbl_product WHERE \"isremoved\"=false AND \"name\"::text ILIKE '%a%' ORDER BY id\n```\n\n## Transaktionen\n\nJede Abfrage von `DATA` und `DB()` erhält ihre eigene Verbindung, daher gehören ein `BEGIN` in einer Abfrage und ein `COMMIT` in der nächsten nicht zusammen. Schreib die ganze Transaktion als eine rohe Abfrage ohne Parameter. Wenn eine Anweisung fehlschlägt, rollt PostgreSQL die ganze Transaktion zurück, und der Callback erhält den Fehler. Eine Abfrage mit mehreren Anweisungen gibt keine Zeilen zurück (`undefined`):\n\n```js\nDATA.query(`BEGIN;\nUPDATE eshop.tbl_product SET stock=stock-1 WHERE id='p1';\nINSERT INTO eshop.tbl_order (id, productid, count) VALUES('o1', 'p1', 1);\nCOMMIT`).callback(console.log);\n```\n\nWenn die Transaktion Parameter oder JavaScript zwischen den Anweisungen braucht, verwende den Client direkt (siehe unten).\n\n## Fehler und Debugging\n\nEin Fehler des Servers ist ein `Error` mit der Meldung von PostgreSQL und den Feldern des Servers: `code`, `detail`, `hint`, `position`, `schema`, `table`, `column`, `constraint`, `severity` und weiteren.\n\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\nJede fehlgeschlagene Abfrage wird außerdem mit `ERROR()` geloggt, mit den ersten 100 Zeichen des SQL. Eine Funktion als drittes Argument von `DATA.init()` erhält stattdessen diesen Text:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n\t// SQL error: Error: column \"unknown\" does not exist - SELECT * FROM tbl_product WHERE \"unknown\"=1\n});\n```\n\n`debug()` an einer Abfrage (oder an einer `DB()`-Kette) gibt das SQL und die Parameter in der Konsole aus:\n\n```\n-- PostgreSQL --> SELECT \"id\",\"name\" FROM eshop.tbl_product ORDER BY \"price\" DESC LIMIT 2 undefined\n```\n\n## Typen der Werte\n\n| PostgreSQL | JavaScript |\n| --- | --- |\n| `boolean` | `Boolean` |\n| `smallint`, `integer`, `real`, `double precision`, `numeric` | `Number` |\n| `bigint` | `String` (passt nicht immer in eine JavaScript-Zahl) |\n| `json`, `jsonb` | Der geparste Wert; Texte im ISO-Datumsformat werden zu `Date`-Objekten |\n| `date`, `timestamp`, `timestamptz` | `Date` |\n| `bytea` | `Buffer` |\n| Arrays | `Array` derselben Typen |\n| andere Typen | `String` |\n\n`COUNT(*)` ist in rohem SQL ein `bigint` und kommt daher als String. Caste es (`COUNT(*)::int`) oder ändere den Parser des Typs über seine OID:\n\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value; // bigint as a number\n```\n\nIn Parametern wird ein `Date` mit seiner Zeitzone gesendet, ein Objekt als JSON, ein `Buffer` als Binärdaten und ein Array als PostgreSQL-Array oder als JSON, wenn der Parameter eine `json`- oder `jsonb`-Spalte ist.\n\n## Der Client ohne QueryBuilder\n\nDer Client ist ein Modul des Frameworks: `require('total5/client-postgresql')`. Verwende ihn, wenn du eine Verbindung für mehrere Abfragen brauchst, zum Beispiel für eine Transaktion mit Parametern:\n\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n`client.query()` und `pool.query()` geben `{ command, rowCount, rows, fields }` zurück, über einen Callback oder eine Promise.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwS73Wx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/postgresql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"PostgreSQL","summary":"Conéctate a PostgreSQL con DATA.init() y ejecuta sobre él el QueryBuilder, SQL en bruto y transacciones.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/postgresql/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# PostgreSQL\n\n> Conéctate a PostgreSQL con DATA.init() y ejecuta sobre él el QueryBuilder, SQL en bruto y transacciones.\n\nTotal.js 5 tiene su propio cliente de PostgreSQL, escrito para el framework y sin otros paquetes de npm, y un adaptador que ejecuta el QueryBuilder sobre PostgreSQL. Registras una conexión una sola vez con `DATA.init()`. Después, `DATA`, `DB()` y todos los métodos del QueryBuilder funcionan como se describe en [QueryBuilder](../../guides/querybuilder/), y el adaptador escribe el SQL.\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n\nDATA.find('tbl_product').where('price', '>', 100).sort('name').take(20).callback(console.log);\n// SELECT * FROM tbl_product WHERE \"price\">100 ORDER BY \"name\" ASC LIMIT 20\n```\n\nLa lista completa de opciones y funciones está en la referencia de [PostgreSQL](../../reference/postgresql/).\n\n## Conectar\n\nGuarda la cadena de conexión en el archivo `config`:\n\n```\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nRegistra la conexión cuando arranca la aplicación, por ejemplo en `definitions/db.js`:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nEl primer argumento es el nombre de la conexión. La conexión `default` atiende las tablas sin prefijo (`DATA.find('tbl_product')`). Una conexión con otro nombre atiende las tablas con ese prefijo:\n\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nLlamar de nuevo a `DATA.init()` con el mismo nombre cierra las conexiones antiguas y las sustituye. `DATA.init(name)` sin cadena de conexión elimina la conexión; sus consultas fallan entonces con `Database is not initialized`.\n\n## La cadena de conexión\n\nLa cadena de conexión es una URL: `postgresql://user:password@host:port/database`. El puerto por defecto es `5432`. Sin nombre de base de datos, el cliente usa la base de datos que se llama como el usuario. Codifica los caracteres especiales del nombre de usuario y de la contraseña con `encodeURIComponent()`.\n\nLas opciones van en el query string, unidas con `&`:\n\n| Opción | Qué hace |\n| --- | --- |\n| `pooling=10` | Mantiene un pool de hasta 10 conexiones. Sin ella, cada consulta abre una conexión nueva y la cierra al terminar. |\n| `schema=eshop` | El esquema de las tablas: `DATA.find('tbl_product')` lee `eshop.tbl_product`. |\n| `sslmode=require` | Cifra la conexión (ver abajo). `ssl=true` es lo mismo. |\n| `connect_timeout=5` | Segundos de espera para la conexión. Después la consulta falla con `Connection timeout`. |\n| `application_name=eshop` | El nombre de las conexiones en `pg_stat_activity`. |\n| `host`, `port`, `user`, `password`, `dbname` | Sustituyen las partes de la URL. Un `host` que empieza por `/` es el directorio de un socket Unix. |\n\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\nLos valores de `sslmode`:\n\n| Valor | Conexión |\n| --- | --- |\n| `disable` (por defecto) | Sin cifrar. |\n| `prefer`, `allow` | Cifrada cuando el servidor admite SSL; si no, sin cifrar. |\n| `require`, `no-verify` | Cifrada, el certificado no se comprueba. Un servidor sin SSL da el error `The server does not support SSL connections`. |\n| `verify-ca`, `verify-full` | Cifrada, el certificado del servidor debe ser válido. |\n\nEl cliente inicia sesión con una contraseña en texto plano, MD5 o SCRAM-SHA-256, según lo pida el servidor.\n\nEn un pool, una conexión inactiva se cierra a los 10 segundos. Una conexión que vuelve al pool dentro de una transacción abierta se cierra y no se vuelve a usar.\n\n## Esquemas\n\n`schema` en la cadena de conexión establece el esquema para todas las tablas de la conexión. `schema(name)` en el QueryBuilder lo cambia para una consulta:\n\n```js\nDATA.find('tbl_product').schema('archive').callback(console.log);\n// SELECT * FROM archive.tbl_product\n```\n\nLas consultas en bruto (`DATA.query()`) no usan el esquema; escríbelo en el SQL.\n\n## El SQL del QueryBuilder\n\nLos nombres de columna se escriben entre comillas dobles (`\"price\"`). Un nombre con un espacio, un punto, dos puntos o comillas dobles se escribe tal cual, así que un campo puede ser una expresión:\n\n```js\nDATA.find('tbl_product')\n\t.where('isremoved', false)\n\t.in('id', ['p1', 'p2'])\n\t.search('name', 'pho')\n\t.array('tags', ['sale'])\n\t.fields('id, name, UPPER(name) AS code')\n\t.callback(console.log);\n\n// SELECT \"id\",\"name\",UPPER(name) AS code FROM tbl_product\n// WHERE \"isremoved\"=false AND \"id\" IN ('p1','p2') AND \"name\"::text ILIKE '%pho%' AND \"tags\" && ARRAY['sale']\n```\n\nLos valores de las condiciones se escapan y se escriben en el SQL. La carga útil de `insert()` y `update()` va al servidor como parámetros (`$1`, `$2`…).\n\n| Método | SQL |\n| --- | --- |\n| `where('age', '>', 20)` | `\"age\">20` |\n| `where('dtremoved', null)` | `\"dtremoved\" IS NULL` (`IS NOT NULL` con el comparador `<>`) |\n| `in('id', ['a', 'b'])`, `notin()` | `\"id\" IN ('a','b')`, `\"id\" NOT IN (…)` |\n| `between('age', 20, 30)` | `(\"age\" BETWEEN 20 AND 30)` |\n| `search('name', 'pet')` | `\"name\"::text ILIKE '%pet%'` |\n| `search('name', 'pet', 'beg')` | `\"name\"::text ILIKE 'pet%'` (el texto está al principio) |\n| `search('name', 'pet', 'end')` | `\"name\"::text ILIKE '%pet'` (el texto está al final) |\n| `array('tags', ['a'])` | `\"tags\" && ARRAY['a']`; otro comparador, por ejemplo `array('tags', '@>', ['a'])`, sustituye a `&&` |\n| `year('dtcreated', 2024)` | `EXTRACT(year from \"dtcreated\")=2024`; `month()`, `day()`, `hour()` y `minute()` funcionan igual |\n| `contains('tags')` | `LENGTH(\"tags\"::text)>0` |\n| `empty('tags')` | `(\"tags\" IS NULL OR LENGTH(\"tags\"::text)=0)` |\n| `query('age % 2 = 0')` | `(age % 2 = 0)` |\n| `or(fn)` | `(… OR …)` |\n| `permit('permissions', 'R', ['admin'], userid)` | `(userid='…' OR array_length(\"permissions\",1) IS NULL OR \"permissions\"::_text && ARRAY['Radmin'])`; con `required` en `false` se omite la parte de `array_length()` |\n| `sort('name', true)` | `ORDER BY \"name\" DESC` |\n| `take(20)`, `skip(40)` | `LIMIT 20 OFFSET 40` |\n\n`join()` no añade nada al SQL; escribe los joins en una consulta en bruto. Un nombre de columna que termina en `§` recibe el idioma de la consulta: con `language('sk', '_')` el campo `name§` se lee como `\"name_sk\" AS \"name\"`.\n\n## Resultados\n\n| Operación | Resultado |\n| --- | --- |\n| `find()` | Un array de filas. |\n| `read()` | Una fila o `null`. |\n| `list()` | `{ items, count, page, limit, pages }`. El adaptador ejecuta dos consultas: la página y `SELECT COUNT(1)`. |\n| `check()` | `true` o `false`. |\n| `count()` | Un número. |\n| `scalar(table, 'sum', 'price')` | Un número; también `avg`, `min`, `max` y `count`. |\n| `scalar(table, 'group', 'kind', 'price')` | Filas `{ kind, value }`: la suma de `price` para cada `kind` (sin el cuarto argumento, el número de filas). |\n| `insert()` | El número de filas insertadas. Con `primarykey('id')`, el valor de esa columna; con `returning('id,dtcreated')`, la fila insertada. |\n| `update()` | El número de filas modificadas. Con `returning()`, un array de las filas modificadas; con `returning()` y `first()`, una fila. |\n| `remove()` | El número de filas eliminadas. Con `returning()`, un array de las filas eliminadas. |\n| `query()` | Un array de filas. |\n| `truncate()` | Ejecuta `TRUNCATE TABLE … RESTART IDENTITY`. |\n| `drop()` | Ejecuta `DROP TABLE …`. |\n\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n\nDATA.update('tbl_product', { '*price': 0.9 }).where('price', '>', 100).returning('id,price').callback(console.log);\n// null [ { id: 'p2', price: 270 }, { id: 'p1', price: 108 } ]\n```\n\n## Operadores en la carga útil\n\nEl primer carácter de una clave en la carga útil de `update()` puede cambiar el valor en la base de datos en lugar de sustituirlo:\n\n| Clave | SQL |\n| --- | --- |\n| `'+stock': 5` | `\"stock\"=COALESCE(\"stock\",0)+$1`; también `-`, `*` y `/` |\n| `'>price': 10` | `\"price\"=GREATEST(\"price\",$1)` |\n| `'<price': 10` | `\"price\"=LEAST(\"price\",$1)` |\n| `'!isread': 1` | `\"isread\"=NOT \"isread\"` |\n| `'=dtupdated': 'NOW()'` | `\"dtupdated\"=NOW()`, el valor es SQL en bruto |\n| `'#dtupdated': 'NOW()'` | Igual que `=`, pero `insert()` omite la clave |\n\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n// UPDATE tbl_product SET \"stock\"=COALESCE(\"stock\",0)+$1,\"reserved\"=COALESCE(\"reserved\",0)-$2,\"dtupdated\"=NOW() WHERE \"id\"='p1'\n```\n\nEn `insert()` el carácter se quita: la columna recibe el valor (`0` cuando el valor está vacío), `!` inserta `FALSE` y `=` inserta el SQL en bruto. Así la misma carga útil funciona en un upsert. Este contador añade una fila para el día y después la incrementa:\n\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n// the first call: INSERT INTO tbl_visitor (\"count\",\"dtupdated\",\"id\") VALUES($1,NOW(),$2)\n// the next calls: UPDATE tbl_visitor SET \"count\"=COALESCE(\"count\",0)+$1,\"dtupdated\"=NOW() WHERE \"id\"='2026-11-16'\n```\n\n## Propiedades de una columna JSON\n\n`autoqueryjson()` funciona como `autoquery()`, pero para propiedades guardadas en una sola columna JSON o JSONB. Lee los campos, los filtros, el orden y la paginación del query string, y el adaptador lee cada propiedad con `->>` y la convierte a su tipo:\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('tbl_product')\n\t\t\t.autoquery($.query, 'id,name,price:number', 'name_asc', 100)\n\t\t\t.autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date')\n\t\t\t.callback($);\n\t}\n});\n```\n\nCon `?fields=id,name,color,weight&color=red&weight=<100` la respuesta tiene las columnas `id` y `name` y las propiedades `color` y `weight` de la columna `data`, para los productos rojos de menos de 100:\n\n```js\n{ items: [{ id: 'p3', name: \"Kid's watch\", color: 'red', weight: 40 }], count: 1, page: 1, limit: 100, pages: 1 }\n```\n\nUn valor de un tipo incorrecto nunca hace fallar la consulta:\n\n| Tipo | Resultado |\n| --- | --- |\n| `string` (por defecto) | El texto. |\n| `number` | Un número; `0` cuando el valor no es un número. |\n| `boolean` | `true` para `true`, `1`, `on` y `yes`; si no, `false`. |\n| `date` | Un `Date`; `null` cuando el valor no es una fecha válida (`2024-02-30`). |\n| `[string]` | Un array de strings; `[]` cuando el valor no es un array. |\n\nUna propiedad que falta es `null`. Los filtros, el orden y los tipos de los valores son los mismos que en `autoquery()`.\n\n## Consultas en bruto\n\n`DATA.query()` envía el SQL tal cual. Los parámetros son `$1`, `$2`… y sus valores van en un array:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1 ORDER BY id', [100]).callback(console.log);\n```\n\nLas condiciones añadidas con el QueryBuilder sustituyen el texto `{where}`, o se añaden al final del SQL cuando no tiene `{where}`:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product {where} ORDER BY id').where('isremoved', false).search('name', 'a').callback(console.log);\n// SELECT id, name FROM eshop.tbl_product WHERE \"isremoved\"=false AND \"name\"::text ILIKE '%a%' ORDER BY id\n```\n\n## Transacciones\n\nCada consulta de `DATA` y `DB()` recibe su propia conexión, así que un `BEGIN` en una consulta y un `COMMIT` en la siguiente no van juntos. Escribe toda la transacción como una sola consulta en bruto sin parámetros. Cuando falla una sentencia, PostgreSQL revierte toda la transacción y el callback recibe el error. Una consulta con varias sentencias no devuelve filas (`undefined`):\n\n```js\nDATA.query(`BEGIN;\nUPDATE eshop.tbl_product SET stock=stock-1 WHERE id='p1';\nINSERT INTO eshop.tbl_order (id, productid, count) VALUES('o1', 'p1', 1);\nCOMMIT`).callback(console.log);\n```\n\nCuando la transacción necesita parámetros o JavaScript entre las sentencias, usa el cliente directamente (ver abajo).\n\n## Errores y depuración\n\nUn error del servidor es un `Error` con el mensaje de PostgreSQL y los campos del servidor: `code`, `detail`, `hint`, `position`, `schema`, `table`, `column`, `constraint`, `severity` y otros.\n\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\nCada consulta fallida también se registra con `ERROR()`, con los primeros 100 caracteres del SQL. Una función como tercer argumento de `DATA.init()` recibe este texto en su lugar:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n\t// SQL error: Error: column \"unknown\" does not exist - SELECT * FROM tbl_product WHERE \"unknown\"=1\n});\n```\n\n`debug()` en una consulta (o en una cadena `DB()`) imprime el SQL y los parámetros en la consola:\n\n```\n-- PostgreSQL --> SELECT \"id\",\"name\" FROM eshop.tbl_product ORDER BY \"price\" DESC LIMIT 2 undefined\n```\n\n## Tipos de valores\n\n| PostgreSQL | JavaScript |\n| --- | --- |\n| `boolean` | `Boolean` |\n| `smallint`, `integer`, `real`, `double precision`, `numeric` | `Number` |\n| `bigint` | `String` (no siempre cabe en un número de JavaScript) |\n| `json`, `jsonb` | El valor parseado; los textos en formato de fecha ISO se convierten en objetos `Date` |\n| `date`, `timestamp`, `timestamptz` | `Date` |\n| `bytea` | `Buffer` |\n| arrays | `Array` de los mismos tipos |\n| otros tipos | `String` |\n\n`COUNT(*)` en SQL en bruto es un `bigint`, así que llega como string. Conviértelo (`COUNT(*)::int`), o cambia el parser del tipo con su OID:\n\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value; // bigint as a number\n```\n\nEn los parámetros, un `Date` se envía con su zona horaria, un objeto como JSON, un `Buffer` como datos binarios y un array como array de PostgreSQL, o como JSON cuando el parámetro es una columna `json` o `jsonb`.\n\n## El cliente sin el QueryBuilder\n\nEl cliente es un módulo del framework: `require('total5/client-postgresql')`. Úsalo cuando necesites una sola conexión para varias consultas, por ejemplo una transacción con parámetros:\n\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n`client.query()` y `pool.query()` devuelven `{ command, rowCount, rows, fields }`, mediante un callback o una promesa.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwS73Wx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/postgresql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"PostgreSQL","summary":"Connecte-toi à PostgreSQL avec DATA.init() et exécute dessus le QueryBuilder, du SQL brut et des transactions.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/postgresql/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# PostgreSQL\n\n> Connecte-toi à PostgreSQL avec DATA.init() et exécute dessus le QueryBuilder, du SQL brut et des transactions.\n\nTotal.js 5 a son propre client PostgreSQL, écrit pour le framework et sans autres paquets npm, et un adaptateur qui exécute le QueryBuilder sur PostgreSQL. Tu enregistres une connexion une seule fois avec `DATA.init()`. Ensuite `DATA`, `DB()` et toutes les méthodes du QueryBuilder fonctionnent comme décrit dans [QueryBuilder](../../guides/querybuilder/), et l'adaptateur écrit le SQL.\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n\nDATA.find('tbl_product').where('price', '>', 100).sort('name').take(20).callback(console.log);\n// SELECT * FROM tbl_product WHERE \"price\">100 ORDER BY \"name\" ASC LIMIT 20\n```\n\nLa liste complète des options et des fonctions se trouve dans la référence de [PostgreSQL](../../reference/postgresql/).\n\n## Se connecter\n\nGarde la chaîne de connexion dans le fichier `config` :\n\n```\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nEnregistre la connexion au démarrage de l'application, par exemple dans `definitions/db.js` :\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nLe premier argument est le nom de la connexion. La connexion `default` sert les tables sans préfixe (`DATA.find('tbl_product')`). Une connexion avec un autre nom sert les tables avec ce préfixe :\n\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nAppeler à nouveau `DATA.init()` avec le même nom ferme les anciennes connexions et les remplace. `DATA.init(name)` sans chaîne de connexion supprime la connexion ; ses requêtes échouent alors avec `Database is not initialized`.\n\n## La chaîne de connexion\n\nLa chaîne de connexion est une URL : `postgresql://user:password@host:port/database`. Le port vaut par défaut `5432`. Sans nom de base de données, le client utilise la base de données qui porte le nom de l'utilisateur. Encode les caractères spéciaux du nom d'utilisateur et du mot de passe avec `encodeURIComponent()`.\n\nLes options vont dans la query string, reliées par `&` :\n\n| Option | Ce qu'elle fait |\n| --- | --- |\n| `pooling=10` | Garde un pool de 10 connexions au maximum. Sans elle, chaque requête ouvre une nouvelle connexion et la ferme à la fin. |\n| `schema=eshop` | Le schéma des tables : `DATA.find('tbl_product')` lit `eshop.tbl_product`. |\n| `sslmode=require` | Chiffre la connexion (voir ci-dessous). `ssl=true` est identique. |\n| `connect_timeout=5` | Secondes d'attente pour la connexion. Ensuite la requête échoue avec `Connection timeout`. |\n| `application_name=eshop` | Le nom des connexions dans `pg_stat_activity`. |\n| `host`, `port`, `user`, `password`, `dbname` | Remplacent les parties de l'URL. Un `host` qui commence par `/` est le dossier d'un socket Unix. |\n\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\nLes valeurs de `sslmode` :\n\n| Valeur | Connexion |\n| --- | --- |\n| `disable` (par défaut) | Non chiffrée. |\n| `prefer`, `allow` | Chiffrée quand le serveur prend en charge SSL, sinon non chiffrée. |\n| `require`, `no-verify` | Chiffrée, le certificat n'est pas vérifié. Un serveur sans SSL donne l'erreur `The server does not support SSL connections`. |\n| `verify-ca`, `verify-full` | Chiffrée, le certificat du serveur doit être valide. |\n\nLe client se connecte avec un mot de passe en texte clair, MD5 ou SCRAM-SHA-256, selon ce que demande le serveur.\n\nDans un pool, une connexion inactive se ferme après 10 secondes. Une connexion qui revient dans le pool au milieu d'une transaction ouverte est fermée et n'est plus utilisée.\n\n## Schémas\n\n`schema` dans la chaîne de connexion définit le schéma de toutes les tables de la connexion. `schema(name)` sur le QueryBuilder le change pour une seule requête :\n\n```js\nDATA.find('tbl_product').schema('archive').callback(console.log);\n// SELECT * FROM archive.tbl_product\n```\n\nLes requêtes brutes (`DATA.query()`) n'utilisent pas le schéma ; écris-le dans le SQL.\n\n## Le SQL du QueryBuilder\n\nLes noms de colonnes sont écrits entre guillemets doubles (`\"price\"`). Un nom qui contient une espace, un point, deux-points ou un guillemet double est écrit tel quel, donc un champ peut être une expression :\n\n```js\nDATA.find('tbl_product')\n\t.where('isremoved', false)\n\t.in('id', ['p1', 'p2'])\n\t.search('name', 'pho')\n\t.array('tags', ['sale'])\n\t.fields('id, name, UPPER(name) AS code')\n\t.callback(console.log);\n\n// SELECT \"id\",\"name\",UPPER(name) AS code FROM tbl_product\n// WHERE \"isremoved\"=false AND \"id\" IN ('p1','p2') AND \"name\"::text ILIKE '%pho%' AND \"tags\" && ARRAY['sale']\n```\n\nLes valeurs des conditions sont échappées et écrites dans le SQL. Les données envoyées à `insert()` et `update()` vont au serveur sous forme de paramètres (`$1`, `$2`…).\n\n| Méthode | SQL |\n| --- | --- |\n| `where('age', '>', 20)` | `\"age\">20` |\n| `where('dtremoved', null)` | `\"dtremoved\" IS NULL` (`IS NOT NULL` avec le comparateur `<>`) |\n| `in('id', ['a', 'b'])`, `notin()` | `\"id\" IN ('a','b')`, `\"id\" NOT IN (…)` |\n| `between('age', 20, 30)` | `(\"age\" BETWEEN 20 AND 30)` |\n| `search('name', 'pet')` | `\"name\"::text ILIKE '%pet%'` |\n| `search('name', 'pet', 'beg')` | `\"name\"::text ILIKE 'pet%'` (le texte est au début) |\n| `search('name', 'pet', 'end')` | `\"name\"::text ILIKE '%pet'` (le texte est à la fin) |\n| `array('tags', ['a'])` | `\"tags\" && ARRAY['a']` ; un autre comparateur, par exemple `array('tags', '@>', ['a'])`, remplace `&&` |\n| `year('dtcreated', 2024)` | `EXTRACT(year from \"dtcreated\")=2024` ; `month()`, `day()`, `hour()` et `minute()` fonctionnent de la même façon |\n| `contains('tags')` | `LENGTH(\"tags\"::text)>0` |\n| `empty('tags')` | `(\"tags\" IS NULL OR LENGTH(\"tags\"::text)=0)` |\n| `query('age % 2 = 0')` | `(age % 2 = 0)` |\n| `or(fn)` | `(… OR …)` |\n| `permit('permissions', 'R', ['admin'], userid)` | `(userid='…' OR array_length(\"permissions\",1) IS NULL OR \"permissions\"::_text && ARRAY['Radmin'])` ; avec `required` à `false`, la partie `array_length()` est omise |\n| `sort('name', true)` | `ORDER BY \"name\" DESC` |\n| `take(20)`, `skip(40)` | `LIMIT 20 OFFSET 40` |\n\n`join()` n'ajoute rien au SQL ; écris les jointures dans une requête brute. Un nom de colonne qui se termine par `§` reçoit la langue de la requête : avec `language('sk', '_')`, le champ `name§` est lu comme `\"name_sk\" AS \"name\"`.\n\n## Résultats\n\n| Opération | Résultat |\n| --- | --- |\n| `find()` | Un tableau de lignes. |\n| `read()` | Une ligne ou `null`. |\n| `list()` | `{ items, count, page, limit, pages }`. L'adaptateur exécute deux requêtes : la page et `SELECT COUNT(1)`. |\n| `check()` | `true` ou `false`. |\n| `count()` | Un nombre. |\n| `scalar(table, 'sum', 'price')` | Un nombre ; aussi `avg`, `min`, `max` et `count`. |\n| `scalar(table, 'group', 'kind', 'price')` | Des lignes `{ kind, value }` : la somme de `price` pour chaque `kind` (sans le quatrième argument, le nombre de lignes). |\n| `insert()` | Le nombre de lignes insérées. Avec `primarykey('id')`, la valeur de cette colonne, avec `returning('id,dtcreated')`, la ligne insérée. |\n| `update()` | Le nombre de lignes modifiées. Avec `returning()`, un tableau des lignes modifiées, avec `returning()` et `first()`, une seule ligne. |\n| `remove()` | Le nombre de lignes supprimées. Avec `returning()`, un tableau des lignes supprimées. |\n| `query()` | Un tableau de lignes. |\n| `truncate()` | Exécute `TRUNCATE TABLE … RESTART IDENTITY`. |\n| `drop()` | Exécute `DROP TABLE …`. |\n\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n\nDATA.update('tbl_product', { '*price': 0.9 }).where('price', '>', 100).returning('id,price').callback(console.log);\n// null [ { id: 'p2', price: 270 }, { id: 'p1', price: 108 } ]\n```\n\n## Opérateurs dans les données envoyées\n\nLe premier caractère d'une clé dans les données envoyées à `update()` peut modifier la valeur dans la base de données au lieu de la remplacer :\n\n| Clé | SQL |\n| --- | --- |\n| `'+stock': 5` | `\"stock\"=COALESCE(\"stock\",0)+$1` ; aussi `-`, `*` et `/` |\n| `'>price': 10` | `\"price\"=GREATEST(\"price\",$1)` |\n| `'<price': 10` | `\"price\"=LEAST(\"price\",$1)` |\n| `'!isread': 1` | `\"isread\"=NOT \"isread\"` |\n| `'=dtupdated': 'NOW()'` | `\"dtupdated\"=NOW()`, la valeur est du SQL brut |\n| `'#dtupdated': 'NOW()'` | Identique à `=`, mais `insert()` omet la clé |\n\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n// UPDATE tbl_product SET \"stock\"=COALESCE(\"stock\",0)+$1,\"reserved\"=COALESCE(\"reserved\",0)-$2,\"dtupdated\"=NOW() WHERE \"id\"='p1'\n```\n\nDans `insert()`, le caractère est supprimé : la colonne reçoit la valeur (`0` quand la valeur est vide), `!` insère `FALSE` et `=` insère le SQL brut. Ainsi, les mêmes données fonctionnent dans un upsert. Ce compteur ajoute une ligne pour le jour, puis l'incrémente :\n\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n// the first call: INSERT INTO tbl_visitor (\"count\",\"dtupdated\",\"id\") VALUES($1,NOW(),$2)\n// the next calls: UPDATE tbl_visitor SET \"count\"=COALESCE(\"count\",0)+$1,\"dtupdated\"=NOW() WHERE \"id\"='2026-11-16'\n```\n\n## Propriétés d'une colonne JSON\n\n`autoqueryjson()` fonctionne comme `autoquery()`, mais pour des propriétés stockées dans une seule colonne JSON ou JSONB. Elle lit les champs, les filtres, le tri et la pagination dans la query string, et l'adaptateur lit chaque propriété avec `->>` et la convertit dans son type :\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('tbl_product')\n\t\t\t.autoquery($.query, 'id,name,price:number', 'name_asc', 100)\n\t\t\t.autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date')\n\t\t\t.callback($);\n\t}\n});\n```\n\nAvec `?fields=id,name,color,weight&color=red&weight=<100`, la réponse contient les colonnes `id` et `name` et les propriétés `color` et `weight` de la colonne `data`, pour les produits rouges de moins de 100 :\n\n```js\n{ items: [{ id: 'p3', name: \"Kid's watch\", color: 'red', weight: 40 }], count: 1, page: 1, limit: 100, pages: 1 }\n```\n\nUne valeur d'un mauvais type ne fait jamais échouer la requête :\n\n| Type | Résultat |\n| --- | --- |\n| `string` (par défaut) | Le texte. |\n| `number` | Un nombre ; `0` quand la valeur n'est pas un nombre. |\n| `boolean` | `true` pour `true`, `1`, `on` et `yes`, sinon `false`. |\n| `date` | Une `Date` ; `null` quand la valeur n'est pas une date valide (`2024-02-30`). |\n| `[string]` | Un tableau de chaînes ; `[]` quand la valeur n'est pas un tableau. |\n\nUne propriété absente vaut `null`. Les filtres, le tri et les types des valeurs sont les mêmes que dans `autoquery()`.\n\n## Requêtes brutes\n\n`DATA.query()` envoie le SQL tel quel. Les paramètres sont `$1`, `$2`… et leurs valeurs vont dans un tableau :\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1 ORDER BY id', [100]).callback(console.log);\n```\n\nLes conditions ajoutées avec le QueryBuilder remplacent le texte `{where}`, ou sont ajoutées à la fin du SQL quand il n'a pas de `{where}` :\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product {where} ORDER BY id').where('isremoved', false).search('name', 'a').callback(console.log);\n// SELECT id, name FROM eshop.tbl_product WHERE \"isremoved\"=false AND \"name\"::text ILIKE '%a%' ORDER BY id\n```\n\n## Transactions\n\nChaque requête de `DATA` et de `DB()` obtient sa propre connexion, donc un `BEGIN` dans une requête et un `COMMIT` dans la suivante ne vont pas ensemble. Écris toute la transaction comme une seule requête brute sans paramètres. Quand une instruction échoue, PostgreSQL annule toute la transaction et le callback reçoit l'erreur. Une requête avec plusieurs instructions ne renvoie aucune ligne (`undefined`) :\n\n```js\nDATA.query(`BEGIN;\nUPDATE eshop.tbl_product SET stock=stock-1 WHERE id='p1';\nINSERT INTO eshop.tbl_order (id, productid, count) VALUES('o1', 'p1', 1);\nCOMMIT`).callback(console.log);\n```\n\nQuand la transaction a besoin de paramètres ou de JavaScript entre les instructions, utilise directement le client (voir ci-dessous).\n\n## Erreurs et débogage\n\nUne erreur du serveur est une `Error` avec le message de PostgreSQL et les champs du serveur : `code`, `detail`, `hint`, `position`, `schema`, `table`, `column`, `constraint`, `severity` et d'autres.\n\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\nChaque requête qui échoue est aussi enregistrée avec `ERROR()`, avec les 100 premiers caractères du SQL. Une fonction passée comme troisième argument de `DATA.init()` reçoit ce texte à la place :\n\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n\t// SQL error: Error: column \"unknown\" does not exist - SELECT * FROM tbl_product WHERE \"unknown\"=1\n});\n```\n\n`debug()` sur une requête (ou sur une chaîne `DB()`) affiche le SQL et les paramètres dans la console :\n\n```\n-- PostgreSQL --> SELECT \"id\",\"name\" FROM eshop.tbl_product ORDER BY \"price\" DESC LIMIT 2 undefined\n```\n\n## Types des valeurs\n\n| PostgreSQL | JavaScript |\n| --- | --- |\n| `boolean` | `Boolean` |\n| `smallint`, `integer`, `real`, `double precision`, `numeric` | `Number` |\n| `bigint` | `String` (il ne tient pas toujours dans un nombre JavaScript) |\n| `json`, `jsonb` | La valeur analysée ; les textes au format de date ISO deviennent des objets `Date` |\n| `date`, `timestamp`, `timestamptz` | `Date` |\n| `bytea` | `Buffer` |\n| tableaux | `Array` des mêmes types |\n| autres types | `String` |\n\n`COUNT(*)` en SQL brut est un `bigint`, il arrive donc sous forme de chaîne. Convertis-le (`COUNT(*)::int`), ou change le parseur du type avec son OID :\n\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value; // bigint as a number\n```\n\nDans les paramètres, une `Date` est envoyée avec son fuseau horaire, un objet en JSON, un `Buffer` en données binaires, et un tableau en tableau PostgreSQL, ou en JSON quand le paramètre est une colonne `json` ou `jsonb`.\n\n## Le client sans le QueryBuilder\n\nLe client est un module du framework : `require('total5/client-postgresql')`. Utilise-le quand tu as besoin d'une seule connexion pour plusieurs requêtes, par exemple une transaction avec des paramètres :\n\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n`client.query()` et `pool.query()` renvoient `{ command, rowCount, rows, fields }`, via un callback ou une promesse.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwS73Wx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/postgresql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"PostgreSQL","summary":"Connettiti a PostgreSQL con DATA.init() ed esegui su di esso il QueryBuilder, SQL grezzo e transazioni.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/postgresql/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# PostgreSQL\n\n> Connettiti a PostgreSQL con DATA.init() ed esegui su di esso il QueryBuilder, SQL grezzo e transazioni.\n\nTotal.js 5 ha un proprio client PostgreSQL, scritto per il framework e senza altri pacchetti npm, e un adapter che esegue il QueryBuilder su PostgreSQL. Registri una connessione una sola volta con `DATA.init()`. Dopo di che `DATA`, `DB()` e ogni metodo del QueryBuilder funzionano come descritto in [QueryBuilder](../../guides/querybuilder/), e l'adapter scrive l'SQL.\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n\nDATA.find('tbl_product').where('price', '>', 100).sort('name').take(20).callback(console.log);\n// SELECT * FROM tbl_product WHERE \"price\">100 ORDER BY \"name\" ASC LIMIT 20\n```\n\nL'elenco completo di opzioni e funzioni è nel riferimento di [PostgreSQL](../../reference/postgresql/).\n\n## Connessione\n\nTieni la stringa di connessione nel file `config`:\n\n```\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nRegistra la connessione all'avvio dell'applicazione, per esempio in `definitions/db.js`:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nIl primo argomento è il nome della connessione. La connessione `default` serve le tabelle senza prefisso (`DATA.find('tbl_product')`). Una connessione con un altro nome serve le tabelle con quel prefisso:\n\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nChiamare di nuovo `DATA.init()` con lo stesso nome chiude le vecchie connessioni e le sostituisce. `DATA.init(name)` senza stringa di connessione rimuove la connessione; le sue query falliscono poi con `Database is not initialized`.\n\n## La stringa di connessione\n\nLa stringa di connessione è un URL: `postgresql://user:password@host:port/database`. La porta predefinita è `5432`. Senza il nome del database il client usa il database che ha il nome dell'utente. Codifica i caratteri speciali nel nome utente e nella password con `encodeURIComponent()`.\n\nLe opzioni vanno nella query string, unite con `&`:\n\n| Opzione | Cosa fa |\n| --- | --- |\n| `pooling=10` | Mantiene un pool fino a 10 connessioni. Senza di essa ogni query apre una nuova connessione e la chiude alla fine. |\n| `schema=eshop` | Lo schema delle tabelle: `DATA.find('tbl_product')` legge `eshop.tbl_product`. |\n| `sslmode=require` | Cifra la connessione (vedi sotto). `ssl=true` è la stessa cosa. |\n| `connect_timeout=5` | Secondi di attesa per la connessione. Poi la query fallisce con `Connection timeout`. |\n| `application_name=eshop` | Il nome delle connessioni in `pg_stat_activity`. |\n| `host`, `port`, `user`, `password`, `dbname` | Sostituiscono le parti dell'URL. Un `host` che inizia con `/` è la cartella di un socket Unix. |\n\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\nI valori di `sslmode`:\n\n| Valore | Connessione |\n| --- | --- |\n| `disable` (predefinito) | Non cifrata. |\n| `prefer`, `allow` | Cifrata quando il server supporta SSL, altrimenti non cifrata. |\n| `require`, `no-verify` | Cifrata, il certificato non viene controllato. Un server senza SSL dà l'errore `The server does not support SSL connections`. |\n| `verify-ca`, `verify-full` | Cifrata, il certificato del server deve essere valido. |\n\nIl client si autentica con una password in chiaro, MD5 o SCRAM-SHA-256, come chiede il server.\n\nIn un pool, una connessione inattiva si chiude dopo 10 secondi. Una connessione che torna nel pool dentro una transazione aperta viene chiusa e non viene più usata.\n\n## Schemi\n\n`schema` nella stringa di connessione imposta lo schema per ogni tabella della connessione. `schema(name)` sul QueryBuilder lo cambia per una sola query:\n\n```js\nDATA.find('tbl_product').schema('archive').callback(console.log);\n// SELECT * FROM archive.tbl_product\n```\n\nLe query grezze (`DATA.query()`) non usano lo schema; scrivilo nell'SQL.\n\n## L'SQL del QueryBuilder\n\nI nomi delle colonne vengono scritti tra virgolette doppie (`\"price\"`). Un nome con uno spazio, un punto, i due punti o una virgoletta doppia viene scritto così com'è, quindi un campo può essere un'espressione:\n\n```js\nDATA.find('tbl_product')\n\t.where('isremoved', false)\n\t.in('id', ['p1', 'p2'])\n\t.search('name', 'pho')\n\t.array('tags', ['sale'])\n\t.fields('id, name, UPPER(name) AS code')\n\t.callback(console.log);\n\n// SELECT \"id\",\"name\",UPPER(name) AS code FROM tbl_product\n// WHERE \"isremoved\"=false AND \"id\" IN ('p1','p2') AND \"name\"::text ILIKE '%pho%' AND \"tags\" && ARRAY['sale']\n```\n\nI valori delle condizioni vengono sottoposti a escape e scritti nell'SQL. Il payload di `insert()` e `update()` va al server come parametri (`$1`, `$2`…).\n\n| Metodo | SQL |\n| --- | --- |\n| `where('age', '>', 20)` | `\"age\">20` |\n| `where('dtremoved', null)` | `\"dtremoved\" IS NULL` (`IS NOT NULL` con il comparatore `<>`) |\n| `in('id', ['a', 'b'])`, `notin()` | `\"id\" IN ('a','b')`, `\"id\" NOT IN (…)` |\n| `between('age', 20, 30)` | `(\"age\" BETWEEN 20 AND 30)` |\n| `search('name', 'pet')` | `\"name\"::text ILIKE '%pet%'` |\n| `search('name', 'pet', 'beg')` | `\"name\"::text ILIKE 'pet%'` (il testo è all'inizio) |\n| `search('name', 'pet', 'end')` | `\"name\"::text ILIKE '%pet'` (il testo è alla fine) |\n| `array('tags', ['a'])` | `\"tags\" && ARRAY['a']`; un altro comparatore, per esempio `array('tags', '@>', ['a'])`, sostituisce `&&` |\n| `year('dtcreated', 2024)` | `EXTRACT(year from \"dtcreated\")=2024`; `month()`, `day()`, `hour()` e `minute()` funzionano allo stesso modo |\n| `contains('tags')` | `LENGTH(\"tags\"::text)>0` |\n| `empty('tags')` | `(\"tags\" IS NULL OR LENGTH(\"tags\"::text)=0)` |\n| `query('age % 2 = 0')` | `(age % 2 = 0)` |\n| `or(fn)` | `(… OR …)` |\n| `permit('permissions', 'R', ['admin'], userid)` | `(userid='…' OR array_length(\"permissions\",1) IS NULL OR \"permissions\"::_text && ARRAY['Radmin'])`; con `required` impostato a `false` la parte `array_length()` viene omessa |\n| `sort('name', true)` | `ORDER BY \"name\" DESC` |\n| `take(20)`, `skip(40)` | `LIMIT 20 OFFSET 40` |\n\n`join()` non aggiunge nulla all'SQL; scrivi i join in una query grezza. Un nome di colonna che finisce con `§` riceve la lingua della query: con `language('sk', '_')` il campo `name§` viene letto come `\"name_sk\" AS \"name\"`.\n\n## Risultati\n\n| Operazione | Risultato |\n| --- | --- |\n| `find()` | Un array di righe. |\n| `read()` | Una riga oppure `null`. |\n| `list()` | `{ items, count, page, limit, pages }`. L'adapter esegue due query: la pagina e `SELECT COUNT(1)`. |\n| `check()` | `true` o `false`. |\n| `count()` | Un numero. |\n| `scalar(table, 'sum', 'price')` | Un numero; anche `avg`, `min`, `max` e `count`. |\n| `scalar(table, 'group', 'kind', 'price')` | Righe `{ kind, value }`: la somma di `price` per ogni `kind` (senza il quarto argomento il numero di righe). |\n| `insert()` | Il numero di righe inserite. Con `primarykey('id')` il valore di quella colonna, con `returning('id,dtcreated')` la riga inserita. |\n| `update()` | Il numero di righe modificate. Con `returning()` un array delle righe modificate, con `returning()` e `first()` una riga. |\n| `remove()` | Il numero di righe rimosse. Con `returning()` un array delle righe rimosse. |\n| `query()` | Un array di righe. |\n| `truncate()` | Esegue `TRUNCATE TABLE … RESTART IDENTITY`. |\n| `drop()` | Esegue `DROP TABLE …`. |\n\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n\nDATA.update('tbl_product', { '*price': 0.9 }).where('price', '>', 100).returning('id,price').callback(console.log);\n// null [ { id: 'p2', price: 270 }, { id: 'p1', price: 108 } ]\n```\n\n## Operatori nel payload\n\nIl primo carattere di una chiave nel payload di `update()` può modificare il valore nel database invece di sostituirlo:\n\n| Chiave | SQL |\n| --- | --- |\n| `'+stock': 5` | `\"stock\"=COALESCE(\"stock\",0)+$1`; anche `-`, `*` e `/` |\n| `'>price': 10` | `\"price\"=GREATEST(\"price\",$1)` |\n| `'<price': 10` | `\"price\"=LEAST(\"price\",$1)` |\n| `'!isread': 1` | `\"isread\"=NOT \"isread\"` |\n| `'=dtupdated': 'NOW()'` | `\"dtupdated\"=NOW()`, il valore è SQL grezzo |\n| `'#dtupdated': 'NOW()'` | Come `=`, ma `insert()` omette la chiave |\n\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n// UPDATE tbl_product SET \"stock\"=COALESCE(\"stock\",0)+$1,\"reserved\"=COALESCE(\"reserved\",0)-$2,\"dtupdated\"=NOW() WHERE \"id\"='p1'\n```\n\nIn `insert()` il carattere viene rimosso: la colonna riceve il valore (`0` quando il valore è vuoto), `!` inserisce `FALSE` e `=` inserisce l'SQL grezzo. Così lo stesso payload funziona in un upsert. Questo contatore aggiunge una riga per il giorno e poi la incrementa:\n\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n// the first call: INSERT INTO tbl_visitor (\"count\",\"dtupdated\",\"id\") VALUES($1,NOW(),$2)\n// the next calls: UPDATE tbl_visitor SET \"count\"=COALESCE(\"count\",0)+$1,\"dtupdated\"=NOW() WHERE \"id\"='2026-11-16'\n```\n\n## Proprietà di una colonna JSON\n\n`autoqueryjson()` funziona come `autoquery()`, ma per le proprietà salvate in una colonna JSON o JSONB. Legge campi, filtri, ordinamento e paginazione dalla query string, e l'adapter legge ogni proprietà con `->>` e la converte nel suo tipo:\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('tbl_product')\n\t\t\t.autoquery($.query, 'id,name,price:number', 'name_asc', 100)\n\t\t\t.autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date')\n\t\t\t.callback($);\n\t}\n});\n```\n\nCon `?fields=id,name,color,weight&color=red&weight=<100` la risposta ha le colonne `id` e `name` e le proprietà `color` e `weight` della colonna `data`, per i prodotti rossi più leggeri di 100:\n\n```js\n{ items: [{ id: 'p3', name: \"Kid's watch\", color: 'red', weight: 40 }], count: 1, page: 1, limit: 100, pages: 1 }\n```\n\nUn valore di tipo sbagliato non fa mai fallire la query:\n\n| Tipo | Risultato |\n| --- | --- |\n| `string` (predefinito) | Il testo. |\n| `number` | Un numero; `0` quando il valore non è un numero. |\n| `boolean` | `true` per `true`, `1`, `on` e `yes`, altrimenti `false`. |\n| `date` | Una `Date`; `null` quando il valore non è una data valida (`2024-02-30`). |\n| `[string]` | Un array di stringhe; `[]` quando il valore non è un array. |\n\nUna proprietà mancante è `null`. I filtri, l'ordinamento e i tipi dei valori sono gli stessi di `autoquery()`.\n\n## Query grezze\n\n`DATA.query()` invia l'SQL così com'è. I parametri sono `$1`, `$2`… e i loro valori vanno in un array:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1 ORDER BY id', [100]).callback(console.log);\n```\n\nLe condizioni aggiunte con il QueryBuilder sostituiscono il testo `{where}`, oppure vengono aggiunte alla fine dell'SQL quando non ha `{where}`:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product {where} ORDER BY id').where('isremoved', false).search('name', 'a').callback(console.log);\n// SELECT id, name FROM eshop.tbl_product WHERE \"isremoved\"=false AND \"name\"::text ILIKE '%a%' ORDER BY id\n```\n\n## Transazioni\n\nOgni query di `DATA` e `DB()` riceve una propria connessione, quindi un `BEGIN` in una query e un `COMMIT` nella successiva non vanno insieme. Scrivi l'intera transazione come una sola query grezza senza parametri. Quando un'istruzione fallisce, PostgreSQL annulla l'intera transazione e la callback riceve l'errore. Una query con più istruzioni non restituisce righe (`undefined`):\n\n```js\nDATA.query(`BEGIN;\nUPDATE eshop.tbl_product SET stock=stock-1 WHERE id='p1';\nINSERT INTO eshop.tbl_order (id, productid, count) VALUES('o1', 'p1', 1);\nCOMMIT`).callback(console.log);\n```\n\nQuando la transazione ha bisogno di parametri o di JavaScript tra le istruzioni, usa direttamente il client (vedi sotto).\n\n## Errori e debug\n\nUn errore del server è un `Error` con il messaggio di PostgreSQL e i campi del server: `code`, `detail`, `hint`, `position`, `schema`, `table`, `column`, `constraint`, `severity` e altri.\n\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\nOgni query fallita viene anche registrata con `ERROR()`, con i primi 100 caratteri dell'SQL. Una funzione come terzo argomento di `DATA.init()` riceve invece questo testo:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n\t// SQL error: Error: column \"unknown\" does not exist - SELECT * FROM tbl_product WHERE \"unknown\"=1\n});\n```\n\n`debug()` su una query (o su una catena `DB()`) stampa l'SQL e i parametri nella console:\n\n```\n-- PostgreSQL --> SELECT \"id\",\"name\" FROM eshop.tbl_product ORDER BY \"price\" DESC LIMIT 2 undefined\n```\n\n## Tipi dei valori\n\n| PostgreSQL | JavaScript |\n| --- | --- |\n| `boolean` | `Boolean` |\n| `smallint`, `integer`, `real`, `double precision`, `numeric` | `Number` |\n| `bigint` | `String` (non sempre entra in un numero JavaScript) |\n| `json`, `jsonb` | Il valore interpretato; i testi nel formato di data ISO diventano oggetti `Date` |\n| `date`, `timestamp`, `timestamptz` | `Date` |\n| `bytea` | `Buffer` |\n| array | `Array` degli stessi tipi |\n| altri tipi | `String` |\n\n`COUNT(*)` nell'SQL grezzo è un `bigint`, quindi arriva come stringa. Fai il cast (`COUNT(*)::int`), oppure cambia il parser del tipo con il suo OID:\n\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value; // bigint as a number\n```\n\nNei parametri, una `Date` viene inviata con il suo fuso orario, un oggetto come JSON, un `Buffer` come dati binari e un array come array PostgreSQL, oppure come JSON quando il parametro è una colonna `json` o `jsonb`.\n\n## Il client senza il QueryBuilder\n\nIl client è un modulo del framework: `require('total5/client-postgresql')`. Usalo quando ti serve una sola connessione per più query, per esempio una transazione con parametri:\n\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n`client.query()` e `pool.query()` restituiscono `{ command, rowCount, rows, fields }`, tramite una callback o una promise.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwS73Wx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/postgresql/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"PostgreSQL","summary":"Pripoj sa k PostgreSQL cez DATA.init() a spúšťaj na ňom QueryBuilder, čisté SQL a transakcie.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/postgresql/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# PostgreSQL\n\n> Pripoj sa k PostgreSQL cez DATA.init() a spúšťaj na ňom QueryBuilder, čisté SQL a transakcie.\n\nTotal.js 5 má vlastného klienta PostgreSQL, napísaného pre framework a bez ďalších npm balíčkov, a adaptér, ktorý spúšťa QueryBuilder na PostgreSQL. Pripojenie zaregistruješ raz cez `DATA.init()`. Potom `DATA`, `DB()` a každá metóda QueryBuildera fungujú tak, ako je opísané v [QueryBuilder](../../guides/querybuilder/), a SQL píše adaptér.\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n\nDATA.find('tbl_product').where('price', '>', 100).sort('name').take(20).callback(console.log);\n// SELECT * FROM tbl_product WHERE \"price\">100 ORDER BY \"name\" ASC LIMIT 20\n```\n\nÚplný zoznam možností a funkcií je v referencii [PostgreSQL](../../reference/postgresql/).\n\n## Pripojenie\n\nConnection string drž v súbore `config`:\n\n```\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nPripojenie zaregistruj pri štarte aplikácie, napríklad v `definitions/db.js`:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nPrvý argument je názov pripojenia. Pripojenie `default` obsluhuje tabuľky bez prefixu (`DATA.find('tbl_product')`). Pripojenie s iným názvom obsluhuje tabuľky s týmto prefixom:\n\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nĎalšie volanie `DATA.init()` s rovnakým názvom zatvorí staré pripojenia a nahradí ich. `DATA.init(name)` bez connection stringu pripojenie odstráni; jeho dopyty potom zlyhajú s `Database is not initialized`.\n\n## Connection string\n\nConnection string je URL: `postgresql://user:password@host:port/database`. Port je predvolene `5432`. Bez názvu databázy klient použije databázu pomenovanú ako používateľ. Špeciálne znaky v mene používateľa a v hesle zakóduj cez `encodeURIComponent()`.\n\nMožnosti idú do query stringu, spojené znakom `&`:\n\n| Možnosť | Čo robí |\n| --- | --- |\n| `pooling=10` | Drží pool až 10 pripojení. Bez nej každý dopyt otvorí nové pripojenie a na konci ho zatvorí. |\n| `schema=eshop` | Schéma tabuliek: `DATA.find('tbl_product')` číta `eshop.tbl_product`. |\n| `sslmode=require` | Zašifruje pripojenie (pozri nižšie). `ssl=true` je to isté. |\n| `connect_timeout=5` | Počet sekúnd čakania na pripojenie. Potom dopyt zlyhá s `Connection timeout`. |\n| `application_name=eshop` | Názov pripojení v `pg_stat_activity`. |\n| `host`, `port`, `user`, `password`, `dbname` | Nahradia časti URL. `host`, ktorý začína na `/`, je adresár Unix socketu. |\n\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\nHodnoty `sslmode`:\n\n| Hodnota | Pripojenie |\n| --- | --- |\n| `disable` (predvolené) | Nešifrované. |\n| `prefer`, `allow` | Šifrované, keď server podporuje SSL, inak nešifrované. |\n| `require`, `no-verify` | Šifrované, certifikát sa nekontroluje. Server bez SSL vráti chybu `The server does not support SSL connections`. |\n| `verify-ca`, `verify-full` | Šifrované, certifikát servera musí byť platný. |\n\nKlient sa prihlási heslom v čistom texte, MD5 alebo SCRAM-SHA-256, podľa toho, čo server žiada.\n\nV poole sa nečinné pripojenie zatvorí po 10 sekundách. Pripojenie, ktoré sa vráti do poolu uprostred otvorenej transakcie, sa zatvorí a už sa nepoužije.\n\n## Schémy\n\n`schema` v connection stringu nastaví schému pre každú tabuľku pripojenia. `schema(name)` na QueryBuilderi ju zmení pre jeden dopyt:\n\n```js\nDATA.find('tbl_product').schema('archive').callback(console.log);\n// SELECT * FROM archive.tbl_product\n```\n\nČisté dopyty (`DATA.query()`) schému nepoužívajú; napíš ju do SQL.\n\n## SQL QueryBuildera\n\nNázvy stĺpcov sa píšu v dvojitých úvodzovkách (`\"price\"`). Názov s medzerou, bodkou, dvojbodkou alebo dvojitou úvodzovkou sa zapíše tak, ako je, takže pole môže byť výraz:\n\n```js\nDATA.find('tbl_product')\n\t.where('isremoved', false)\n\t.in('id', ['p1', 'p2'])\n\t.search('name', 'pho')\n\t.array('tags', ['sale'])\n\t.fields('id, name, UPPER(name) AS code')\n\t.callback(console.log);\n\n// SELECT \"id\",\"name\",UPPER(name) AS code FROM tbl_product\n// WHERE \"isremoved\"=false AND \"id\" IN ('p1','p2') AND \"name\"::text ILIKE '%pho%' AND \"tags\" && ARRAY['sale']\n```\n\nHodnoty podmienok sa escapujú a zapíšu do SQL. Payload `insert()` a `update()` ide na server ako parametre (`$1`, `$2`…).\n\n| Metóda | SQL |\n| --- | --- |\n| `where('age', '>', 20)` | `\"age\">20` |\n| `where('dtremoved', null)` | `\"dtremoved\" IS NULL` (`IS NOT NULL` s porovnávačom `<>`) |\n| `in('id', ['a', 'b'])`, `notin()` | `\"id\" IN ('a','b')`, `\"id\" NOT IN (…)` |\n| `between('age', 20, 30)` | `(\"age\" BETWEEN 20 AND 30)` |\n| `search('name', 'pet')` | `\"name\"::text ILIKE '%pet%'` |\n| `search('name', 'pet', 'beg')` | `\"name\"::text ILIKE 'pet%'` (text je na začiatku) |\n| `search('name', 'pet', 'end')` | `\"name\"::text ILIKE '%pet'` (text je na konci) |\n| `array('tags', ['a'])` | `\"tags\" && ARRAY['a']`; iný porovnávač, napríklad `array('tags', '@>', ['a'])`, nahradí `&&` |\n| `year('dtcreated', 2024)` | `EXTRACT(year from \"dtcreated\")=2024`; `month()`, `day()`, `hour()` a `minute()` fungujú rovnako |\n| `contains('tags')` | `LENGTH(\"tags\"::text)>0` |\n| `empty('tags')` | `(\"tags\" IS NULL OR LENGTH(\"tags\"::text)=0)` |\n| `query('age % 2 = 0')` | `(age % 2 = 0)` |\n| `or(fn)` | `(… OR …)` |\n| `permit('permissions', 'R', ['admin'], userid)` | `(userid='…' OR array_length(\"permissions\",1) IS NULL OR \"permissions\"::_text && ARRAY['Radmin'])`; keď je `required` nastavené na `false`, časť `array_length()` sa vynechá |\n| `sort('name', true)` | `ORDER BY \"name\" DESC` |\n| `take(20)`, `skip(40)` | `LIMIT 20 OFFSET 40` |\n\n`join()` do SQL nič nepridá; joiny napíš v čistom dopyte. Názov stĺpca, ktorý končí na `§`, dostane jazyk dopytu: s `language('sk', '_')` sa pole `name§` načíta ako `\"name_sk\" AS \"name\"`.\n\n## Výsledky\n\n| Operácia | Výsledok |\n| --- | --- |\n| `find()` | Pole riadkov. |\n| `read()` | Jeden riadok alebo `null`. |\n| `list()` | `{ items, count, page, limit, pages }`. Adaptér spustí dva dopyty: stránku a `SELECT COUNT(1)`. |\n| `check()` | `true` alebo `false`. |\n| `count()` | Číslo. |\n| `scalar(table, 'sum', 'price')` | Číslo; aj `avg`, `min`, `max` a `count`. |\n| `scalar(table, 'group', 'kind', 'price')` | Riadky `{ kind, value }`: súčet `price` pre každý `kind` (bez štvrtého argumentu počet riadkov). |\n| `insert()` | Počet vložených riadkov. S `primarykey('id')` hodnota tohto stĺpca, s `returning('id,dtcreated')` vložený riadok. |\n| `update()` | Počet zmenených riadkov. S `returning()` pole zmenených riadkov, s `returning()` a `first()` jeden riadok. |\n| `remove()` | Počet odstránených riadkov. S `returning()` pole odstránených riadkov. |\n| `query()` | Pole riadkov. |\n| `truncate()` | Spustí `TRUNCATE TABLE … RESTART IDENTITY`. |\n| `drop()` | Spustí `DROP TABLE …`. |\n\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n\nDATA.update('tbl_product', { '*price': 0.9 }).where('price', '>', 100).returning('id,price').callback(console.log);\n// null [ { id: 'p2', price: 270 }, { id: 'p1', price: 108 } ]\n```\n\n## Operátory v payloade\n\nPrvý znak kľúča v payloade `update()` môže hodnotu v databáze zmeniť namiesto toho, aby ju nahradil:\n\n| Kľúč | SQL |\n| --- | --- |\n| `'+stock': 5` | `\"stock\"=COALESCE(\"stock\",0)+$1`; aj `-`, `*` a `/` |\n| `'>price': 10` | `\"price\"=GREATEST(\"price\",$1)` |\n| `'<price': 10` | `\"price\"=LEAST(\"price\",$1)` |\n| `'!isread': 1` | `\"isread\"=NOT \"isread\"` |\n| `'=dtupdated': 'NOW()'` | `\"dtupdated\"=NOW()`, hodnota je čisté SQL |\n| `'#dtupdated': 'NOW()'` | To isté ako `=`, ale `insert()` kľúč vynechá |\n\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n// UPDATE tbl_product SET \"stock\"=COALESCE(\"stock\",0)+$1,\"reserved\"=COALESCE(\"reserved\",0)-$2,\"dtupdated\"=NOW() WHERE \"id\"='p1'\n```\n\nV `insert()` sa znak odstráni: stĺpec dostane hodnotu (`0`, keď je hodnota prázdna), `!` vloží `FALSE` a `=` vloží čisté SQL. Rovnaký payload teda funguje aj v upserte. Toto počítadlo pridá riadok pre deň a potom ho zvyšuje:\n\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n// the first call: INSERT INTO tbl_visitor (\"count\",\"dtupdated\",\"id\") VALUES($1,NOW(),$2)\n// the next calls: UPDATE tbl_visitor SET \"count\"=COALESCE(\"count\",0)+$1,\"dtupdated\"=NOW() WHERE \"id\"='2026-11-16'\n```\n\n## Vlastnosti JSON stĺpca\n\n`autoqueryjson()` funguje ako `autoquery()`, ale pre vlastnosti uložené v jednom JSON alebo JSONB stĺpci. Z query stringu načíta polia, filtre, triedenie a stránkovanie a adaptér každú vlastnosť načíta cez `->>` a skonvertuje na jej typ:\n\n```js\nNEWACTION('Products/list', {\n\tname: 'List of products',\n\taction: function($) {\n\t\tDATA.list('tbl_product')\n\t\t\t.autoquery($.query, 'id,name,price:number', 'name_asc', 100)\n\t\t\t.autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date')\n\t\t\t.callback($);\n\t}\n});\n```\n\nS `?fields=id,name,color,weight&color=red&weight=<100` má odpoveď stĺpce `id` a `name` a vlastnosti `color` a `weight` stĺpca `data`, pre červené produkty ľahšie ako 100:\n\n```js\n{ items: [{ id: 'p3', name: \"Kid's watch\", color: 'red', weight: 40 }], count: 1, page: 1, limit: 100, pages: 1 }\n```\n\nHodnota nesprávneho typu nikdy nespôsobí zlyhanie dopytu:\n\n| Typ | Výsledok |\n| --- | --- |\n| `string` (predvolený) | Text. |\n| `number` | Číslo; `0`, keď hodnota nie je číslo. |\n| `boolean` | `true` pre `true`, `1`, `on` a `yes`, inak `false`. |\n| `date` | `Date`; `null`, keď hodnota nie je platný dátum (`2024-02-30`). |\n| `[string]` | Pole reťazcov; `[]`, keď hodnota nie je pole. |\n\nChýbajúca vlastnosť je `null`. Filtre, triedenie a typy hodnôt sú rovnaké ako v `autoquery()`.\n\n## Čisté dopyty\n\n`DATA.query()` pošle SQL tak, ako je. Parametre sú `$1`, `$2`… a ich hodnoty idú do poľa:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1 ORDER BY id', [100]).callback(console.log);\n```\n\nPodmienky pridané cez QueryBuilder nahradia text `{where}` alebo sa pridajú na koniec SQL, keď `{where}` neobsahuje:\n\n```js\nDATA.query('SELECT id, name FROM eshop.tbl_product {where} ORDER BY id').where('isremoved', false).search('name', 'a').callback(console.log);\n// SELECT id, name FROM eshop.tbl_product WHERE \"isremoved\"=false AND \"name\"::text ILIKE '%a%' ORDER BY id\n```\n\n## Transakcie\n\nKaždý dopyt `DATA` a `DB()` dostane vlastné pripojenie, takže `BEGIN` v jednom dopyte a `COMMIT` v ďalšom k sebe nepatria. Celú transakciu napíš ako jeden čistý dopyt bez parametrov. Keď príkaz zlyhá, PostgreSQL vráti späť celú transakciu a callback dostane chybu. Dopyt s viacerými príkazmi nevracia žiadne riadky (`undefined`):\n\n```js\nDATA.query(`BEGIN;\nUPDATE eshop.tbl_product SET stock=stock-1 WHERE id='p1';\nINSERT INTO eshop.tbl_order (id, productid, count) VALUES('o1', 'p1', 1);\nCOMMIT`).callback(console.log);\n```\n\nKeď transakcia potrebuje parametre alebo JavaScript medzi príkazmi, použi priamo klienta (pozri nižšie).\n\n## Chyby a ladenie\n\nChyba servera je `Error` so správou PostgreSQL a s poľami servera: `code`, `detail`, `hint`, `position`, `schema`, `table`, `column`, `constraint`, `severity` a ďalšími.\n\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\nKaždý neúspešný dopyt sa zároveň zaloguje cez `ERROR()` s prvými 100 znakmi SQL. Funkcia ako tretí argument `DATA.init()` dostane tento text namiesto toho:\n\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n\t// SQL error: Error: column \"unknown\" does not exist - SELECT * FROM tbl_product WHERE \"unknown\"=1\n});\n```\n\n`debug()` na dopyte (alebo na reťazci `DB()`) vypíše SQL a parametre do konzoly:\n\n```\n-- PostgreSQL --> SELECT \"id\",\"name\" FROM eshop.tbl_product ORDER BY \"price\" DESC LIMIT 2 undefined\n```\n\n## Typy hodnôt\n\n| PostgreSQL | JavaScript |\n| --- | --- |\n| `boolean` | `Boolean` |\n| `smallint`, `integer`, `real`, `double precision`, `numeric` | `Number` |\n| `bigint` | `String` (nie vždy sa zmestí do čísla JavaScriptu) |\n| `json`, `jsonb` | Sparsovaná hodnota; texty vo formáte dátumu ISO sa zmenia na objekty `Date` |\n| `date`, `timestamp`, `timestamptz` | `Date` |\n| `bytea` | `Buffer` |\n| polia | `Array` rovnakých typov |\n| ostatné typy | `String` |\n\n`COUNT(*)` v čistom SQL je `bigint`, takže príde ako reťazec. Pretypuj ho (`COUNT(*)::int`) alebo zmeň parser typu podľa jeho OID:\n\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value; // bigint as a number\n```\n\nV parametroch sa `Date` posiela s časovou zónou, objekt ako JSON, `Buffer` ako binárne dáta a pole ako pole PostgreSQL, alebo ako JSON, keď je parameter stĺpec `json` alebo `jsonb`.\n\n## Klient bez QueryBuildera\n\nKlient je modul frameworku: `require('total5/client-postgresql')`. Použi ho, keď potrebuješ jedno pripojenie pre viac dopytov, napríklad transakciu s parametrami:\n\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n`client.query()` a `pool.query()` vrátia `{ command, rowCount, rows, fields }` cez callback alebo promise.\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JaedDbAhT60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/localization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Localization","summary":"Translate views, files and messages with resource files, choose the language of each request and create dictionaries with total5 translate.","markdown":"---\ntitle: Localization\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/localization/\nupdated: 2026-11-16T15:32:47.498Z\n---\n\n# Localization\n\n> Translate views, files and messages with resource files, choose the language of each request and create dictionaries with total5 translate.\n\nTotal.js translates text that you mark with `@(...)`. The text stays readable in your views and code, and the framework replaces it with its translation from a **resource file** of the current language. Text without a translation stays as it is, so an application works before any translation exists.\n\n```html\n<!-- /views/index.html -->\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n```\n# /resources/sk.resource\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\n```\n\nThe key of a translation is `T` followed by a hash of the original text (`'T' + 'Welcome'.hash(true).toString(36)` is `T1bx8wg2`). You do not compute the keys yourself: the `total5 translate` command collects all `@(...)` texts of the project into a resource file for you.\n\n## Resource files\n\nA resource file is a plain text file with the `.resource` extension in the `/resources/` folder (subfolders are read too). The name of the file without the extension is the name of the dictionary, usually a language code: `sk.resource` is the dictionary `sk`. Files whose path contains `-bk` or `_bk` are skipped. The files are loaded when the application starts.\n\nEach line is a key, a separator and a value:\n\n```\n# a comment\n// also a comment\nT1bx8wg2      : Vitajte\nname          : Meno\ntitle = Obchod\n```\n\n- The separator is the first `:` of the line, or the first `=` when the line has no `:`. Keep one space after the separator: the value starts at the second character after it.\n- The key and the value are trimmed, so you can align the values with spaces. A value can contain more `:` characters.\n- Empty lines and lines that start with `#` or `//` are ignored.\n\nEach dictionary is a plain object in `F.resources`. Loading a dictionary of the same name again replaces it as a whole; it does not merge the keys.\n\n### The default dictionary\n\n`default.resource` is the fallback. When a key is missing in the dictionary of the current language, or the language has no dictionary, the key is read from `default`. Text in `@(...)` without a translation in either dictionary stays untranslated.\n\n## Creating the dictionary\n\nRun the `translate` command of the `total5` tool in the root of your project:\n\n```bash\ntotal5 translate\ntotal5 translate resources/sk.resource\n```\n\nIt reads all `.js` and `.html` files in the current directory and its subfolders, finds every `@(...)` text and writes the file (`translate.resource` when you do not give a name). Each line has the key and the original text:\n\n```\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\nCopy the file into `/resources/` under the name of a language and translate the values.\n\n## Choosing the language\n\nThe language of a request is a string in `$.language`. It is empty by default, which means the `default` dictionary. Register a delegate with `LOCALIZE()` that returns the language for each request:\n\n```js\n// /definitions/localize.js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nThe delegate gets the controller of the request. It runs after the authorization, so `$.user` is set and you can return the language of the user:\n\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\nThe delegate runs for routes (before their middleware), for static `.html` files and for WebSocket routes. It is not called when the language is already set, for example by the `localize` option of the built-in session authorization (see [Authorization](../../guides/authorization/)). In a route you can also set the language yourself before you render a view:\n\n```js\nfunction index($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\nInside an action, `$.language` returns the language of the request that called the action. It is read-only there.\n\n## Views and static HTML files\n\nA view is translated when it is compiled, before its commands run, so `@(...)` holds plain text only. In release mode every language gets its own compiled copy of the view. The language of the view is the language of the request at the time you call `$.view()`; `@{language}` prints it. For `F.view()` set `view.language` in the `prepare` function; `@{language}` is empty there. The [Views](../../guides/views/) guide explains the rest.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\nStatic `.html` files from `/public/` are translated the same way and cached per language, except files whose name contains `.min`, `-min` or `@min`.\n\n## Translating in code\n\n`TRANSLATE(language, text)` replaces every `@(...)` in a string and returns the result. Use it for text you build in code, JSON responses or files.\n\n```js\nvar title = TRANSLATE($.language, '@(Order) #' + order.number);\n```\n\n`F.resource(language, key)` reads one key of a dictionary by its own name, with the same fallback to `default`. It returns an empty string when the key does not exist.\n\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n## Error messages\n\nErrors are translated into the language of the request when they are sent. A message in `@(...)` is translated like any other text:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tif (!model.name.trim()) {\n\t\t\t$.invalid('@(The name is required)');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t}\n});\n```\n\nA field that fails the validation of a schema is looked up in the resources by the name of the field (`name : Enter your name`). Without such a key the message is `The field \"name\" is invalid`. `ErrorBuilder.output(language)` and `toString(language)` translate the errors when you work with an `ErrorBuilder` yourself.\n\n## E-mails and templates\n\n`MAIL()` takes the language after the model. The subject and the view are translated into that language:\n\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language, function(err) {\n\terr && console.error(err);\n});\n```\n\n`HTMLMAIL(email, subject, body, [language], [callback])` translates the subject and the HTML body. `TEMPLATE(body, model, $)` translates the template into `$.language`. The [Mail](../../guides/mail/) and [Views](../../guides/views/) guides have the details.\n\n## Names of months and days\n\n`date.format(format, [dictionary])` reads the names of months (`MMMM`, `MMM`) and days (`dddd`, `ddd`) from a dictionary, with the English name as the key:\n\n```\n# /resources/sk.resource\nJanuary : január\nMonday  : pondelok\n```\n\n```js\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // pondelok 1. január\n```\n\n## Loading resources from code\n\n`LOADRESOURCE(name, text)` parses the text of a resource file and stores it as a dictionary. Without the text, the first argument is a URL: the framework downloads it and loads every dictionary in the JSON response.\n\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte');\nLOADRESOURCE('https://example.com/translations.json');\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:47.498Z"}
{"id":"JaedDbAhT60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/localization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Lokalisierung","summary":"Übersetze Views, Dateien und Nachrichten mit Ressourcendateien, wähle die Sprache jeder Anfrage und erstelle Wörterbücher mit total5 translate.","markdown":"---\ntitle: Lokalisierung\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/localization/\nupdated: 2026-11-16T15:32:47.498Z\n---\n\n# Lokalisierung\n\n> Übersetze Views, Dateien und Nachrichten mit Ressourcendateien, wähle die Sprache jeder Anfrage und erstelle Wörterbücher mit total5 translate.\n\nTotal.js übersetzt Text, den du mit `@(...)` markierst. Der Text bleibt in deinen Views und deinem Code lesbar, und das Framework ersetzt ihn durch seine Übersetzung aus einer **Ressourcendatei** der aktuellen Sprache. Text ohne Übersetzung bleibt unverändert, sodass eine Anwendung schon funktioniert, bevor es Übersetzungen gibt.\n\n```html\n<!-- /views/index.html -->\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n```\n# /resources/sk.resource\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\n```\n\nDer Schlüssel einer Übersetzung ist `T`, gefolgt von einem Hash des Originaltexts (`'T' + 'Welcome'.hash(true).toString(36)` ist `T1bx8wg2`). Du berechnest die Schlüssel nicht selbst: Der Befehl `total5 translate` sammelt alle `@(...)`-Texte des Projekts für dich in einer Ressourcendatei.\n\n## Ressourcendateien\n\nEine Ressourcendatei ist eine einfache Textdatei mit der Endung `.resource` im Ordner `/resources/` (Unterordner werden ebenfalls gelesen). Der Dateiname ohne Endung ist der Name des Wörterbuchs, meist ein Sprachcode: `sk.resource` ist das Wörterbuch `sk`. Dateien, deren Pfad `-bk` oder `_bk` enthält, werden übersprungen. Die Dateien werden beim Start der Anwendung geladen.\n\nJede Zeile besteht aus einem Schlüssel, einem Trennzeichen und einem Wert:\n\n```\n# a comment\n// also a comment\nT1bx8wg2      : Vitajte\nname          : Meno\ntitle = Obchod\n```\n\n- Das Trennzeichen ist der erste `:` der Zeile oder das erste `=`, wenn die Zeile keinen `:` hat. Lass nach dem Trennzeichen ein Leerzeichen: Der Wert beginnt beim zweiten Zeichen danach.\n- Der Schlüssel und der Wert werden getrimmt, sodass du die Werte mit Leerzeichen ausrichten kannst. Ein Wert kann weitere `:`-Zeichen enthalten.\n- Leere Zeilen und Zeilen, die mit `#` oder `//` beginnen, werden ignoriert.\n\nJedes Wörterbuch ist ein einfaches Objekt in `F.resources`. Lädst du ein Wörterbuch mit demselben Namen erneut, wird es vollständig ersetzt; die Schlüssel werden nicht zusammengeführt.\n\n### Das Standardwörterbuch\n\n`default.resource` ist der Fallback. Fehlt ein Schlüssel im Wörterbuch der aktuellen Sprache oder hat die Sprache kein Wörterbuch, wird der Schlüssel aus `default` gelesen. Text in `@(...)` ohne Übersetzung in einem der beiden Wörterbücher bleibt unübersetzt.\n\n## Das Wörterbuch erstellen\n\nFühre den Befehl `translate` des Werkzeugs `total5` im Stammverzeichnis deines Projekts aus:\n\n```bash\ntotal5 translate\ntotal5 translate resources/sk.resource\n```\n\nEr liest alle `.js`- und `.html`-Dateien im aktuellen Verzeichnis und seinen Unterordnern, findet jeden `@(...)`-Text und schreibt die Datei (`translate.resource`, wenn du keinen Namen angibst). Jede Zeile enthält den Schlüssel und den Originaltext:\n\n```\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\nKopiere die Datei unter dem Namen einer Sprache nach `/resources/` und übersetze die Werte.\n\n## Die Sprache wählen\n\nDie Sprache einer Anfrage ist ein String in `$.language`. Standardmäßig ist er leer, was das Wörterbuch `default` bedeutet. Registriere mit `LOCALIZE()` einen Delegate, der für jede Anfrage die Sprache zurückgibt:\n\n```js\n// /definitions/localize.js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nDer Delegate erhält den Controller der Anfrage. Er läuft nach der Autorisierung, sodass `$.user` gesetzt ist und du die Sprache des Benutzers zurückgeben kannst:\n\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\nDer Delegate läuft für Routen (vor ihrer Middleware), für statische `.html`-Dateien und für WebSocket-Routen. Er wird nicht aufgerufen, wenn die Sprache bereits gesetzt ist, zum Beispiel durch die Option `localize` der eingebauten Session-Autorisierung (siehe [Autorisierung](../../guides/authorization/)). In einer Route kannst du die Sprache auch selbst setzen, bevor du eine View renderst:\n\n```js\nfunction index($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\nInnerhalb einer Aktion gibt `$.language` die Sprache der Anfrage zurück, die die Aktion aufgerufen hat. Dort ist sie schreibgeschützt.\n\n## Views und statische HTML-Dateien\n\nEine View wird beim Kompilieren übersetzt, bevor ihre Befehle laufen, daher enthält `@(...)` nur einfachen Text. Im Release-Modus erhält jede Sprache eine eigene kompilierte Kopie der View. Die Sprache der View ist die Sprache der Anfrage zum Zeitpunkt des Aufrufs von `$.view()`; `@{language}` gibt sie aus. Für `F.view()` setze `view.language` in der Funktion `prepare`; `@{language}` ist dort leer. Der Leitfaden [Views](../../guides/views/) erklärt den Rest.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\nStatische `.html`-Dateien aus `/public/` werden auf die gleiche Weise übersetzt und pro Sprache gecacht, außer Dateien, deren Name `.min`, `-min` oder `@min` enthält.\n\n## Im Code übersetzen\n\n`TRANSLATE(language, text)` ersetzt jedes `@(...)` in einem String und gibt das Ergebnis zurück. Verwende es für Text, den du im Code erstellst, für JSON-Antworten oder Dateien.\n\n```js\nvar title = TRANSLATE($.language, '@(Order) #' + order.number);\n```\n\n`F.resource(language, key)` liest einen Schlüssel eines Wörterbuchs über dessen eigenen Namen, mit demselben Fallback auf `default`. Es gibt einen leeren String zurück, wenn der Schlüssel nicht existiert.\n\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n## Fehlermeldungen\n\nFehler werden beim Senden in die Sprache der Anfrage übersetzt. Eine Meldung in `@(...)` wird wie jeder andere Text übersetzt:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tif (!model.name.trim()) {\n\t\t\t$.invalid('@(The name is required)');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t}\n});\n```\n\nEin Feld, das die Validierung eines Schemas nicht besteht, wird in den Ressourcen über den Namen des Felds gesucht (`name : Enter your name`). Ohne einen solchen Schlüssel lautet die Meldung `The field \"name\" is invalid`. `ErrorBuilder.output(language)` und `toString(language)` übersetzen die Fehler, wenn du selbst mit einem `ErrorBuilder` arbeitest.\n\n## E-Mails und Templates\n\n`MAIL()` nimmt die Sprache nach dem Modell entgegen. Der Betreff und die View werden in diese Sprache übersetzt:\n\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language, function(err) {\n\terr && console.error(err);\n});\n```\n\n`HTMLMAIL(email, subject, body, [language], [callback])` übersetzt den Betreff und den HTML-Inhalt. `TEMPLATE(body, model, $)` übersetzt das Template in `$.language`. Die Leitfäden [Mail](../../guides/mail/) und [Views](../../guides/views/) enthalten die Details.\n\n## Namen von Monaten und Tagen\n\n`date.format(format, [dictionary])` liest die Namen der Monate (`MMMM`, `MMM`) und Tage (`dddd`, `ddd`) aus einem Wörterbuch, mit dem englischen Namen als Schlüssel:\n\n```\n# /resources/sk.resource\nJanuary : január\nMonday  : pondelok\n```\n\n```js\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // pondelok 1. január\n```\n\n## Ressourcen aus dem Code laden\n\n`LOADRESOURCE(name, text)` parst den Text einer Ressourcendatei und speichert ihn als Wörterbuch. Ohne den Text ist das erste Argument eine URL: Das Framework lädt sie herunter und lädt jedes Wörterbuch aus der JSON-Antwort.\n\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte');\nLOADRESOURCE('https://example.com/translations.json');\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:47.498Z"}
{"id":"JaedDbAhT60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/localization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Localización","summary":"Traduce vistas, archivos y mensajes con archivos de recursos, elige el idioma de cada petición y crea diccionarios con total5 translate.","markdown":"---\ntitle: \"Localización\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/localization/\nupdated: 2026-11-16T15:32:47.498Z\n---\n\n# Localización\n\n> Traduce vistas, archivos y mensajes con archivos de recursos, elige el idioma de cada petición y crea diccionarios con total5 translate.\n\nTotal.js traduce el texto que marcas con `@(...)`. El texto sigue siendo legible en tus vistas y en tu código, y el framework lo sustituye por su traducción desde un **archivo de recursos** del idioma actual. El texto sin traducción se queda como está, así que una aplicación funciona antes de que exista ninguna traducción.\n\n```html\n<!-- /views/index.html -->\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n```\n# /resources/sk.resource\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\n```\n\nLa clave de una traducción es `T` seguida de un hash del texto original (`'T' + 'Welcome'.hash(true).toString(36)` es `T1bx8wg2`). No calculas las claves tú mismo: el comando `total5 translate` reúne por ti todos los textos `@(...)` del proyecto en un archivo de recursos.\n\n## Archivos de recursos\n\nUn archivo de recursos es un archivo de texto plano con la extensión `.resource` en la carpeta `/resources/` (también se leen las subcarpetas). El nombre del archivo sin la extensión es el nombre del diccionario, normalmente un código de idioma: `sk.resource` es el diccionario `sk`. Los archivos cuya ruta contiene `-bk` o `_bk` se omiten. Los archivos se cargan cuando arranca la aplicación.\n\nCada línea es una clave, un separador y un valor:\n\n```\n# a comment\n// also a comment\nT1bx8wg2      : Vitajte\nname          : Meno\ntitle = Obchod\n```\n\n- El separador es el primer `:` de la línea, o el primer `=` cuando la línea no tiene `:`. Deja un espacio después del separador: el valor empieza en el segundo carácter después de él.\n- La clave y el valor se recortan, así que puedes alinear los valores con espacios. Un valor puede contener más caracteres `:`.\n- Las líneas vacías y las líneas que empiezan por `#` o `//` se ignoran.\n\nCada diccionario es un objeto plano en `F.resources`. Volver a cargar un diccionario con el mismo nombre lo sustituye por completo; no combina las claves.\n\n### El diccionario por defecto\n\n`default.resource` es el respaldo. Cuando falta una clave en el diccionario del idioma actual, o el idioma no tiene diccionario, la clave se lee de `default`. El texto en `@(...)` sin traducción en ninguno de los dos diccionarios queda sin traducir.\n\n## Crear el diccionario\n\nEjecuta el comando `translate` de la herramienta `total5` en la raíz de tu proyecto:\n\n```bash\ntotal5 translate\ntotal5 translate resources/sk.resource\n```\n\nLee todos los archivos `.js` y `.html` del directorio actual y de sus subcarpetas, encuentra cada texto `@(...)` y escribe el archivo (`translate.resource` cuando no indicas un nombre). Cada línea tiene la clave y el texto original:\n\n```\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\nCopia el archivo en `/resources/` con el nombre de un idioma y traduce los valores.\n\n## Elegir el idioma\n\nEl idioma de una petición es una cadena en `$.language`. Está vacío por defecto, lo que significa el diccionario `default`. Registra con `LOCALIZE()` un delegado que devuelva el idioma de cada petición:\n\n```js\n// /definitions/localize.js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nEl delegado recibe el controlador de la petición. Se ejecuta después de la autorización, así que `$.user` está definido y puedes devolver el idioma del usuario:\n\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\nEl delegado se ejecuta para las rutas (antes de su middleware), para los archivos estáticos `.html` y para las rutas WebSocket. No se llama cuando el idioma ya está definido, por ejemplo por la opción `localize` de la autorización por sesión integrada (consulta [Autorización](../../guides/authorization/)). En una ruta también puedes definir el idioma tú mismo antes de renderizar una vista:\n\n```js\nfunction index($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\nDentro de una acción, `$.language` devuelve el idioma de la petición que llamó a la acción. Ahí es de solo lectura.\n\n## Vistas y archivos HTML estáticos\n\nUna vista se traduce cuando se compila, antes de que se ejecuten sus comandos, así que `@(...)` contiene solo texto plano. En modo release cada idioma tiene su propia copia compilada de la vista. El idioma de la vista es el idioma de la petición en el momento en que llamas a `$.view()`; `@{language}` lo imprime. Para `F.view()` define `view.language` en la función `prepare`; ahí `@{language}` está vacío. La guía [Vistas](../../guides/views/) explica el resto.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\nLos archivos estáticos `.html` de `/public/` se traducen de la misma forma y se guardan en caché por idioma, excepto los archivos cuyo nombre contiene `.min`, `-min` o `@min`.\n\n## Traducir en el código\n\n`TRANSLATE(language, text)` sustituye cada `@(...)` de una cadena y devuelve el resultado. Úsalo para el texto que construyes en el código, respuestas JSON o archivos.\n\n```js\nvar title = TRANSLATE($.language, '@(Order) #' + order.number);\n```\n\n`F.resource(language, key)` lee una clave de un diccionario por su propio nombre, con el mismo respaldo a `default`. Devuelve una cadena vacía cuando la clave no existe.\n\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n## Mensajes de error\n\nLos errores se traducen al idioma de la petición cuando se envían. Un mensaje en `@(...)` se traduce como cualquier otro texto:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tif (!model.name.trim()) {\n\t\t\t$.invalid('@(The name is required)');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t}\n});\n```\n\nUn campo que no supera la validación de un esquema se busca en los recursos por el nombre del campo (`name : Enter your name`). Sin esa clave el mensaje es `The field \"name\" is invalid`. `ErrorBuilder.output(language)` y `toString(language)` traducen los errores cuando trabajas tú mismo con un `ErrorBuilder`.\n\n## Correos electrónicos y plantillas\n\n`MAIL()` recibe el idioma después del modelo. El asunto y la vista se traducen a ese idioma:\n\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language, function(err) {\n\terr && console.error(err);\n});\n```\n\n`HTMLMAIL(email, subject, body, [language], [callback])` traduce el asunto y el cuerpo HTML. `TEMPLATE(body, model, $)` traduce la plantilla a `$.language`. Las guías [Correo](../../guides/mail/) y [Vistas](../../guides/views/) tienen los detalles.\n\n## Nombres de meses y días\n\n`date.format(format, [dictionary])` lee los nombres de los meses (`MMMM`, `MMM`) y de los días (`dddd`, `ddd`) de un diccionario, con el nombre en inglés como clave:\n\n```\n# /resources/sk.resource\nJanuary : január\nMonday  : pondelok\n```\n\n```js\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // pondelok 1. január\n```\n\n## Cargar recursos desde el código\n\n`LOADRESOURCE(name, text)` analiza el texto de un archivo de recursos y lo guarda como diccionario. Sin el texto, el primer argumento es una URL: el framework la descarga y carga cada diccionario de la respuesta JSON.\n\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte');\nLOADRESOURCE('https://example.com/translations.json');\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:47.498Z"}
{"id":"JaedDbAhT60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/localization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Localisation","summary":"Traduis des vues, des fichiers et des messages avec des fichiers de ressources, choisis la langue de chaque requête et crée des dictionnaires avec total5 translate.","markdown":"---\ntitle: Localisation\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/localization/\nupdated: 2026-11-16T15:32:47.498Z\n---\n\n# Localisation\n\n> Traduis des vues, des fichiers et des messages avec des fichiers de ressources, choisis la langue de chaque requête et crée des dictionnaires avec total5 translate.\n\nTotal.js traduit le texte que tu marques avec `@(...)`. Le texte reste lisible dans tes vues et ton code, et le framework le remplace par sa traduction issue d'un **fichier de ressources** de la langue courante. Un texte sans traduction reste tel quel ; une application fonctionne donc avant même qu'une traduction existe.\n\n```html\n<!-- /views/index.html -->\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n```\n# /resources/sk.resource\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\n```\n\nLa clé d'une traduction est `T` suivi d'un hash du texte original (`'T' + 'Welcome'.hash(true).toString(36)` donne `T1bx8wg2`). Tu ne calcules pas les clés toi-même : la commande `total5 translate` rassemble pour toi tous les textes `@(...)` du projet dans un fichier de ressources.\n\n## Fichiers de ressources\n\nUn fichier de ressources est un fichier texte simple avec l'extension `.resource` dans le dossier `/resources/` (les sous-dossiers sont aussi lus). Le nom du fichier sans l'extension est le nom du dictionnaire, généralement un code de langue : `sk.resource` est le dictionnaire `sk`. Les fichiers dont le chemin contient `-bk` ou `_bk` sont ignorés. Les fichiers sont chargés au démarrage de l'application.\n\nChaque ligne contient une clé, un séparateur et une valeur :\n\n```\n# a comment\n// also a comment\nT1bx8wg2      : Vitajte\nname          : Meno\ntitle = Obchod\n```\n\n- Le séparateur est le premier `:` de la ligne, ou le premier `=` lorsque la ligne ne contient pas de `:`. Laisse un espace après le séparateur : la valeur commence au deuxième caractère qui le suit.\n- La clé et la valeur sont débarrassées de leurs espaces ; tu peux donc aligner les valeurs avec des espaces. Une valeur peut contenir d'autres caractères `:`.\n- Les lignes vides et les lignes qui commencent par `#` ou `//` sont ignorées.\n\nChaque dictionnaire est un objet simple dans `F.resources`. Charger à nouveau un dictionnaire du même nom le remplace entièrement ; les clés ne sont pas fusionnées.\n\n### Le dictionnaire par défaut\n\n`default.resource` sert de repli. Lorsqu'une clé manque dans le dictionnaire de la langue courante, ou que la langue n'a pas de dictionnaire, la clé est lue dans `default`. Un texte dans `@(...)` sans traduction dans aucun des deux dictionnaires reste non traduit.\n\n## Créer le dictionnaire\n\nExécute la commande `translate` de l'outil `total5` à la racine de ton projet :\n\n```bash\ntotal5 translate\ntotal5 translate resources/sk.resource\n```\n\nElle lit tous les fichiers `.js` et `.html` du répertoire courant et de ses sous-dossiers, trouve chaque texte `@(...)` et écrit le fichier (`translate.resource` si tu ne donnes pas de nom). Chaque ligne contient la clé et le texte original :\n\n```\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\nCopie le fichier dans `/resources/` sous le nom d'une langue et traduis les valeurs.\n\n## Choisir la langue\n\nLa langue d'une requête est une chaîne dans `$.language`. Elle est vide par défaut, ce qui correspond au dictionnaire `default`. Enregistre avec `LOCALIZE()` un délégué qui renvoie la langue de chaque requête :\n\n```js\n// /definitions/localize.js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nLe délégué reçoit le contrôleur de la requête. Il s'exécute après l'autorisation ; `$.user` est donc défini et tu peux renvoyer la langue de l'utilisateur :\n\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\nLe délégué s'exécute pour les routes (avant leur middleware), pour les fichiers `.html` statiques et pour les routes WebSocket. Il n'est pas appelé lorsque la langue est déjà définie, par exemple par l'option `localize` de l'autorisation par session intégrée (consulte [Autorisation](../../guides/authorization/)). Dans une route, tu peux aussi définir la langue toi-même avant de rendre une vue :\n\n```js\nfunction index($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\nDans une action, `$.language` renvoie la langue de la requête qui a appelé l'action. Elle y est en lecture seule.\n\n## Vues et fichiers HTML statiques\n\nUne vue est traduite lors de sa compilation, avant l'exécution de ses commandes ; `@(...)` ne contient donc que du texte simple. En mode release, chaque langue obtient sa propre copie compilée de la vue. La langue de la vue est celle de la requête au moment où tu appelles `$.view()` ; `@{language}` l'affiche. Pour `F.view()`, définis `view.language` dans la fonction `prepare` ; `@{language}` y est vide. Le guide [Vues](../../guides/views/) explique le reste.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\nLes fichiers `.html` statiques de `/public/` sont traduits de la même façon et mis en cache par langue, sauf les fichiers dont le nom contient `.min`, `-min` ou `@min`.\n\n## Traduire dans le code\n\n`TRANSLATE(language, text)` remplace chaque `@(...)` dans une chaîne et renvoie le résultat. Utilise-la pour du texte construit dans le code, des réponses JSON ou des fichiers.\n\n```js\nvar title = TRANSLATE($.language, '@(Order) #' + order.number);\n```\n\n`F.resource(language, key)` lit une clé d'un dictionnaire par son propre nom, avec le même repli sur `default`. Elle renvoie une chaîne vide lorsque la clé n'existe pas.\n\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n## Messages d'erreur\n\nLes erreurs sont traduites dans la langue de la requête au moment de leur envoi. Un message dans `@(...)` est traduit comme n'importe quel autre texte :\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tif (!model.name.trim()) {\n\t\t\t$.invalid('@(The name is required)');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t}\n});\n```\n\nUn champ qui échoue à la validation d'un schéma est recherché dans les ressources par le nom du champ (`name : Enter your name`). Sans une telle clé, le message est `The field \"name\" is invalid`. `ErrorBuilder.output(language)` et `toString(language)` traduisent les erreurs lorsque tu travailles toi-même avec un `ErrorBuilder`.\n\n## E-mails et templates\n\n`MAIL()` prend la langue après le modèle. Le sujet et la vue sont traduits dans cette langue :\n\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language, function(err) {\n\terr && console.error(err);\n});\n```\n\n`HTMLMAIL(email, subject, body, [language], [callback])` traduit le sujet et le corps HTML. `TEMPLATE(body, model, $)` traduit le template dans `$.language`. Les guides [Mail](../../guides/mail/) et [Vues](../../guides/views/) donnent les détails.\n\n## Noms des mois et des jours\n\n`date.format(format, [dictionary])` lit les noms des mois (`MMMM`, `MMM`) et des jours (`dddd`, `ddd`) dans un dictionnaire, avec le nom anglais comme clé :\n\n```\n# /resources/sk.resource\nJanuary : január\nMonday  : pondelok\n```\n\n```js\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // pondelok 1. január\n```\n\n## Charger des ressources depuis le code\n\n`LOADRESOURCE(name, text)` analyse le texte d'un fichier de ressources et le stocke comme dictionnaire. Sans le texte, le premier argument est une URL : le framework la télécharge et charge chaque dictionnaire de la réponse JSON.\n\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte');\nLOADRESOURCE('https://example.com/translations.json');\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:47.498Z"}
{"id":"JaedDbAhT60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/localization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Localizzazione","summary":"Traduci view, file e messaggi con i file di risorse, scegli la lingua di ogni richiesta e crea dizionari con total5 translate.","markdown":"---\ntitle: Localizzazione\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/localization/\nupdated: 2026-11-16T15:32:47.498Z\n---\n\n# Localizzazione\n\n> Traduci view, file e messaggi con i file di risorse, scegli la lingua di ogni richiesta e crea dizionari con total5 translate.\n\nTotal.js traduce il testo che contrassegni con `@(...)`. Il testo resta leggibile nelle tue view e nel codice, e il framework lo sostituisce con la sua traduzione presa da un **file di risorse** della lingua corrente. Il testo senza traduzione resta com'è, quindi un'applicazione funziona prima ancora che esista una traduzione.\n\n```html\n<!-- /views/index.html -->\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n```\n# /resources/sk.resource\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\n```\n\nLa chiave di una traduzione è `T` seguita da un hash del testo originale (`'T' + 'Welcome'.hash(true).toString(36)` è `T1bx8wg2`). Non calcoli tu le chiavi: il comando `total5 translate` raccoglie per te tutti i testi `@(...)` del progetto in un file di risorse.\n\n## File di risorse\n\nUn file di risorse è un file di testo semplice con estensione `.resource` nella cartella `/resources/` (vengono lette anche le sottocartelle). Il nome del file senza estensione è il nome del dizionario, di solito un codice di lingua: `sk.resource` è il dizionario `sk`. I file il cui percorso contiene `-bk` o `_bk` vengono saltati. I file vengono caricati all'avvio dell'applicazione.\n\nOgni riga è composta da una chiave, un separatore e un valore:\n\n```\n# a comment\n// also a comment\nT1bx8wg2      : Vitajte\nname          : Meno\ntitle = Obchod\n```\n\n- Il separatore è il primo `:` della riga, oppure il primo `=` quando la riga non contiene `:`. Lascia uno spazio dopo il separatore: il valore inizia dal secondo carattere dopo di esso.\n- La chiave e il valore vengono privati degli spazi iniziali e finali, quindi puoi allineare i valori con gli spazi. Un valore può contenere altri caratteri `:`.\n- Le righe vuote e quelle che iniziano con `#` o `//` vengono ignorate.\n\nOgni dizionario è un oggetto semplice in `F.resources`. Caricare di nuovo un dizionario con lo stesso nome lo sostituisce per intero; le chiavi non vengono unite.\n\n### Il dizionario predefinito\n\n`default.resource` è il fallback. Quando una chiave manca nel dizionario della lingua corrente, o la lingua non ha un dizionario, la chiave viene letta da `default`. Il testo in `@(...)` senza traduzione in nessuno dei due dizionari resta non tradotto.\n\n## Creare il dizionario\n\nEsegui il comando `translate` dello strumento `total5` nella radice del tuo progetto:\n\n```bash\ntotal5 translate\ntotal5 translate resources/sk.resource\n```\n\nLegge tutti i file `.js` e `.html` nella directory corrente e nelle sue sottocartelle, trova ogni testo `@(...)` e scrive il file (`translate.resource` quando non indichi un nome). Ogni riga contiene la chiave e il testo originale:\n\n```\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\nCopia il file in `/resources/` con il nome di una lingua e traduci i valori.\n\n## Scegliere la lingua\n\nLa lingua di una richiesta è una stringa in `$.language`. Per impostazione predefinita è vuota, il che significa il dizionario `default`. Registra con `LOCALIZE()` un delegate che restituisce la lingua di ogni richiesta:\n\n```js\n// /definitions/localize.js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nIl delegate riceve il controller della richiesta. Viene eseguito dopo l'autorizzazione, quindi `$.user` è impostato e puoi restituire la lingua dell'utente:\n\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\nIl delegate viene eseguito per le route (prima del loro middleware), per i file `.html` statici e per le route WebSocket. Non viene chiamato quando la lingua è già impostata, per esempio dall'opzione `localize` dell'autorizzazione di sessione integrata (vedi [Autorizzazione](../../guides/authorization/)). In una route puoi anche impostare tu la lingua prima di renderizzare una view:\n\n```js\nfunction index($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\nAll'interno di un'azione, `$.language` restituisce la lingua della richiesta che ha chiamato l'azione. Lì è in sola lettura.\n\n## View e file HTML statici\n\nUna view viene tradotta quando viene compilata, prima che vengano eseguiti i suoi comandi, quindi `@(...)` contiene solo testo semplice. In modalità release ogni lingua ottiene la propria copia compilata della view. La lingua della view è la lingua della richiesta nel momento in cui chiami `$.view()`; `@{language}` la stampa. Per `F.view()` imposta `view.language` nella funzione `prepare`; lì `@{language}` è vuoto. La guida [View](../../guides/views/) spiega il resto.\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\nI file `.html` statici di `/public/` vengono tradotti allo stesso modo e messi in cache per lingua, tranne i file il cui nome contiene `.min`, `-min` o `@min`.\n\n## Tradurre nel codice\n\n`TRANSLATE(language, text)` sostituisce ogni `@(...)` in una stringa e restituisce il risultato. Usala per il testo che costruisci nel codice, per le risposte JSON o per i file.\n\n```js\nvar title = TRANSLATE($.language, '@(Order) #' + order.number);\n```\n\n`F.resource(language, key)` legge una chiave di un dizionario in base al suo nome, con lo stesso fallback su `default`. Restituisce una stringa vuota quando la chiave non esiste.\n\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n## Messaggi di errore\n\nGli errori vengono tradotti nella lingua della richiesta quando vengono inviati. Un messaggio in `@(...)` viene tradotto come qualsiasi altro testo:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tif (!model.name.trim()) {\n\t\t\t$.invalid('@(The name is required)');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t}\n});\n```\n\nUn campo che non supera la validazione di uno schema viene cercato nelle risorse in base al nome del campo (`name : Enter your name`). Senza una chiave di questo tipo il messaggio è `The field \"name\" is invalid`. `ErrorBuilder.output(language)` e `toString(language)` traducono gli errori quando lavori direttamente con un `ErrorBuilder`.\n\n## E-mail e template\n\n`MAIL()` accetta la lingua dopo il modello. L'oggetto e la view vengono tradotti in quella lingua:\n\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language, function(err) {\n\terr && console.error(err);\n});\n```\n\n`HTMLMAIL(email, subject, body, [language], [callback])` traduce l'oggetto e il corpo HTML. `TEMPLATE(body, model, $)` traduce il template in `$.language`. Le guide [Mail](../../guides/mail/) e [View](../../guides/views/) contengono i dettagli.\n\n## Nomi dei mesi e dei giorni\n\n`date.format(format, [dictionary])` legge i nomi dei mesi (`MMMM`, `MMM`) e dei giorni (`dddd`, `ddd`) da un dizionario, con il nome inglese come chiave:\n\n```\n# /resources/sk.resource\nJanuary : január\nMonday  : pondelok\n```\n\n```js\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // pondelok 1. január\n```\n\n## Caricare le risorse dal codice\n\n`LOADRESOURCE(name, text)` analizza il testo di un file di risorse e lo salva come dizionario. Senza testo, il primo argomento è un URL: il framework lo scarica e carica ogni dizionario presente nella risposta JSON.\n\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte');\nLOADRESOURCE('https://example.com/translations.json');\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:47.498Z"}
{"id":"JaedDbAhT60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/localization/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Lokalizácia","summary":"Prekladaj views, súbory a správy pomocou resource súborov, vyber jazyk každej požiadavky a vytváraj slovníky cez total5 translate.","markdown":"---\ntitle: \"Lokalizácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/localization/\nupdated: 2026-11-16T15:32:47.498Z\n---\n\n# Lokalizácia\n\n> Prekladaj views, súbory a správy pomocou resource súborov, vyber jazyk každej požiadavky a vytváraj slovníky cez total5 translate.\n\nTotal.js prekladá text, ktorý označíš `@(...)`. Text zostáva čitateľný vo views aj v kóde a framework ho nahradí prekladom z **resource súboru** aktuálneho jazyka. Text bez prekladu zostane taký, aký je, takže aplikácia funguje ešte predtým, než existuje akýkoľvek preklad.\n\n```html\n<!-- /views/index.html -->\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n```\n# /resources/sk.resource\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\n```\n\nKľúč prekladu je `T` nasledované hashom pôvodného textu (`'T' + 'Welcome'.hash(true).toString(36)` je `T1bx8wg2`). Kľúče nepočítaš sám: príkaz `total5 translate` za teba zozbiera všetky texty `@(...)` projektu do resource súboru.\n\n## Resource súbory\n\nResource súbor je obyčajný textový súbor s príponou `.resource` v priečinku `/resources/` (čítajú sa aj podpriečinky). Názov súboru bez prípony je názov slovníka, zvyčajne kód jazyka: `sk.resource` je slovník `sk`. Súbory, ktorých cesta obsahuje `-bk` alebo `_bk`, sa preskočia. Súbory sa načítajú pri štarte aplikácie.\n\nKaždý riadok je kľúč, oddeľovač a hodnota:\n\n```\n# a comment\n// also a comment\nT1bx8wg2      : Vitajte\nname          : Meno\ntitle = Obchod\n```\n\n- Oddeľovač je prvá `:` v riadku, alebo prvé `=`, keď riadok nemá `:`. Za oddeľovačom nechaj jednu medzeru: hodnota začína druhým znakom za ním.\n- Kľúč aj hodnota sa orežú, takže hodnoty môžeš zarovnať medzerami. Hodnota môže obsahovať ďalšie znaky `:`.\n- Prázdne riadky a riadky, ktoré začínajú na `#` alebo `//`, sa ignorujú.\n\nKaždý slovník je obyčajný objekt v `F.resources`. Opätovné načítanie slovníka s rovnakým názvom ho nahradí celý; kľúče sa nezlučujú.\n\n### Predvolený slovník\n\n`default.resource` je záloha. Keď kľúč v slovníku aktuálneho jazyka chýba alebo jazyk nemá žiadny slovník, kľúč sa prečíta z `default`. Text v `@(...)` bez prekladu v ani jednom slovníku zostane nepreložený.\n\n## Vytvorenie slovníka\n\nV koreňovom priečinku projektu spusti príkaz `translate` nástroja `total5`:\n\n```bash\ntotal5 translate\ntotal5 translate resources/sk.resource\n```\n\nPrečíta všetky súbory `.js` a `.html` v aktuálnom priečinku a jeho podpriečinkoch, nájde každý text `@(...)` a zapíše súbor (`translate.resource`, keď nezadáš názov). Každý riadok obsahuje kľúč a pôvodný text:\n\n```\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\nSkopíruj súbor do `/resources/` pod názvom jazyka a prelož hodnoty.\n\n## Výber jazyka\n\nJazyk požiadavky je reťazec v `$.language`. Predvolene je prázdny, čo znamená slovník `default`. Zaregistruj cez `LOCALIZE()` delegáta, ktorý vráti jazyk pre každú požiadavku:\n\n```js\n// /definitions/localize.js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nDelegát dostane kontrolér požiadavky. Spúšťa sa po autorizácii, takže `$.user` je nastavený a môžeš vrátiť jazyk používateľa:\n\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\nDelegát sa spúšťa pre routy (pred ich middleware), pre statické súbory `.html` a pre WebSocket routy. Nevolá sa, keď je jazyk už nastavený, napríklad voľbou `localize` vstavanej session autorizácie (pozri [Autorizácia](../../guides/authorization/)). V route môžeš jazyk nastaviť aj sám pred vyrenderovaním view:\n\n```js\nfunction index($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\nVnútri akcie vracia `$.language` jazyk požiadavky, ktorá akciu zavolala. Tam je iba na čítanie.\n\n## Views a statické HTML súbory\n\nView sa prekladá pri kompilácii, ešte pred spustením jeho príkazov, takže `@(...)` obsahuje iba obyčajný text. V režime release dostane každý jazyk vlastnú skompilovanú kópiu view. Jazyk view je jazyk požiadavky v čase, keď zavoláš `$.view()`; `@{language}` ho vypíše. Pri `F.view()` nastav `view.language` vo funkcii `prepare`; `@{language}` je tam prázdne. Zvyšok vysvetľuje návod [Views](../../guides/views/).\n\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\nStatické súbory `.html` z `/public/` sa prekladajú rovnako a cachujú sa pre každý jazyk, okrem súborov, ktorých názov obsahuje `.min`, `-min` alebo `@min`.\n\n## Preklad v kóde\n\n`TRANSLATE(language, text)` nahradí každé `@(...)` v reťazci a vráti výsledok. Použi ho pre text, ktorý zostavuješ v kóde, JSON odpovede alebo súbory.\n\n```js\nvar title = TRANSLATE($.language, '@(Order) #' + order.number);\n```\n\n`F.resource(language, key)` prečíta jeden kľúč slovníka podľa jeho vlastného názvu, s rovnakou zálohou na `default`. Keď kľúč neexistuje, vráti prázdny reťazec.\n\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n## Chybové hlásenia\n\nChyby sa pri odosielaní prekladajú do jazyka požiadavky. Hlásenie v `@(...)` sa preloží ako akýkoľvek iný text:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tif (!model.name.trim()) {\n\t\t\t$.invalid('@(The name is required)');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t}\n});\n```\n\nPole, ktoré neprejde validáciou schémy, sa v resources vyhľadá podľa názvu poľa (`name : Enter your name`). Bez takého kľúča je hlásenie `The field \"name\" is invalid`. `ErrorBuilder.output(language)` a `toString(language)` preložia chyby, keď s `ErrorBuilder` pracuješ sám.\n\n## E-maily a šablóny\n\n`MAIL()` berie jazyk za modelom. Predmet aj view sa preložia do tohto jazyka:\n\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language, function(err) {\n\terr && console.error(err);\n});\n```\n\n`HTMLMAIL(email, subject, body, [language], [callback])` preloží predmet a HTML telo. `TEMPLATE(body, model, $)` preloží šablónu do `$.language`. Podrobnosti nájdeš v návodoch [Mail](../../guides/mail/) a [Views](../../guides/views/).\n\n## Názvy mesiacov a dní\n\n`date.format(format, [dictionary])` číta názvy mesiacov (`MMMM`, `MMM`) a dní (`dddd`, `ddd`) zo slovníka, s anglickým názvom ako kľúčom:\n\n```\n# /resources/sk.resource\nJanuary : január\nMonday  : pondelok\n```\n\n```js\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // pondelok 1. január\n```\n\n## Načítanie resources z kódu\n\n`LOADRESOURCE(name, text)` spracuje text resource súboru a uloží ho ako slovník. Bez textu je prvý argument URL: framework ho stiahne a načíta každý slovník z JSON odpovede.\n\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte');\nLOADRESOURCE('https://example.com/translations.json');\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:47.498Z"}
{"id":"JafwtY3Ax61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/http-requests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"HTTP requests","summary":"Call other HTTP services with RESTBuilder, REQUEST(), AJAX() and DOWNLOAD().","markdown":"---\ntitle: HTTP requests\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/http-requests/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# HTTP requests\n\n> Call other HTTP services with RESTBuilder, REQUEST(), AJAX() and DOWNLOAD().\n\nTotal.js has four tools for calling other HTTP services from your application: `RESTBuilder` for REST APIs, `REQUEST()` for full control of a single request, `AJAX()` for a quick JSON call and `DOWNLOAD()` for saving a remote file. `OPENCLIENT()` keeps a WebSocket connection to another service for request-response messages. All of them are global, so you call them in actions, schemas, plugins and definitions without `require()`.\n\n## RESTBuilder\n\n`RESTBuilder` builds a request step by step and parses the response for you. The static helpers create a builder with the method and the data already set:\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\t// response: the parsed JSON body\n\t// output.status, output.headers\n\tconsole.log(err, response);\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).callback(console.log);\n```\n\n`GET()` sends the data as a query string. `POST()`, `PUT()`, `PATCH()` and `DELETE()` send it as a JSON body. You can also start with `RESTBuilder.url(url)` or `RESTBuilder.make(fn)` and set everything with methods:\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.auth('Bearer ' + CONF.apitoken);\n\tbuilder.header('X-Client', 'shop');\n\tbuilder.timeout(5000);\n\tbuilder.json({ name: 'Peter', email: 'peter@example.com' });\n\tbuilder.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\nThe request is sent on the next tick after `callback()` or `stream()`, so the order of the other methods does not matter. `promise()` sends it at once, so call it last.\n\n### The response\n\nThe callback receives `(err, response, output)`. `response` is the body parsed by its `Content-Type`: JSON (also `text/plain` and unknown types that contain JSON), URL-encoded data, or XML (parsed with the HTML parser). An empty body gives an empty object. `output` holds `status`, `headers`, `response` (the raw body), `hostname`, `origin` and the method `output.cookie(name)`.\n\n`err` is set when the connection fails, when the timeout expires, or when the status code is `400` or more. For a status error `err` is an `ErrorBuilder`: with the errors of a Total.js error array (`[{ error: '...' }]`), or with one error whose name is the status code and whose message is the raw response body.\n\n`error(value)` replaces any error with your own value, and `logerror()` prints errors to the console through the framework error handler:\n\n```js\nRESTBuilder.GET('https://api.example.com/stock/')\n\t.logerror()\n\t.error('The stock service is not available')\n\t.callback(function(err, response) {\n\t\t// err === 'The stock service is not available' on any error\n\t});\n```\n\n### Promises\n\n`promise()` returns a promise that resolves with the parsed body and rejects with an `Error`. `callback()` without a function also returns a promise. Pass the `$` of an action to `promise($)` and an error goes straight to `$.invalid()`; `callback($)` passes the whole result to `$.callback()`:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*productid:String, *count:Number',\n\taction: async function($, model) {\n\t\tvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\n\t\t$.callback(order);\n\t}\n});\n```\n\n### Bodies, files and headers\n\n`json(data)`, `urlencoded(data)` and `xml(text)` set the body and its type (a GET request becomes POST). `raw(value, [type])` sends a string as it is, or a buffer with `raw(buffer, 'raw')`. `text(value)` sends plain text and also returns the response body without parsing. `file(name, filename, [buffer|path|url])` adds a file and sends the request as `multipart/form-data`:\n\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('file', 'invoice.pdf', PATH.databases('invoice.pdf'))\n\t.callback(console.log);\n```\n\n`header(name, value)`, `type(contentType)`, `accept(ext)`, `auth(user, [password])`, `cookie(name, value)`, `referrer(url)`, `origin(url)`, `csrf(token)` and `xhr()` set headers. `cook()` keeps the cookies of the response in the builder, so the next request with the same builder sends them back.\n\n### Connection options\n\n`timeout(ms)` (10 seconds by default), `keepalive([val])`, `proxy(url)`, `insecure()` for self-signed certificates, `cert(key, cert, [dhparam])` for client certificates, `unixsocket(socket, path)`, `nodnscache()` and `redirect(false)` control how the request is made. By default the builder caches DNS lookups and follows up to four redirects.\n\n### Streams and progress\n\n`stream(callback)` gives you the response as a stream, without reading the body. `progress(fn)` reports the download percentage when the service sends `Content-Length`:\n\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (err)\n\t\treturn;\n\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### Total.js APIs\n\n`RESTBuilder.API(url, name, [data])` calls an API endpoint of another Total.js application (a route `API /api/ ...`). It sends `{ schema: name, data: data }` as JSON:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(console.log);\n```\n\nThe request stays a `POST`: `get(query)` adds the query to the body (`{ schema, data, query }`), and `compress()` leaves out the keys with `null` or `undefined` values:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes', color: null }).get({ page: 2 }).compress().callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n## REQUEST()\n\n`REQUEST(options, [callback])` is the low-level function used by all the tools above. You describe the whole request in one object. The callback receives `(err, response)`; without a callback it returns a promise.\n\n```js\nREQUEST({\n\turl: 'https://api.example.com/status/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ ping: 1 }),\n\theaders: { 'X-Token': CONF.apitoken },\n\ttimeout: 5000,\n\tkeepalive: true\n}, function(err, response) {\n\t// response.status, response.headers, response.body (a string)\n\tconsole.log(err, response.status, response.body);\n});\n```\n\n`REQUEST()` does not parse the body: `response.body` is a string for text and application types and a `Buffer` for other types. The default timeout is 8 seconds (`timeout: 0` disables it). With `custom: true` the callback receives `response.stream` instead of the body. With `writer: function(req) {}` you write the body yourself and end the request with `req.end()`. The full list of options is in the reference.\n\nAll outgoing requests can go through one proxy with the configuration key `$proxyrequest` (see [Configuration](../configuration/)); requests to `localhost` skip it. Credentials in a URL are sent for you: `https://user:password@host/` as `Authorization: Basic`, and a proxy `http://user:password@host:port` as `Proxy-Authorization: Basic`.\n\n## AJAX()\n\n`AJAX('METHOD url', [data], [callback])` is the shortest way to call a JSON service. `data` is sent as JSON and the response is parsed by its type: JSON, URL-encoded data and XML become objects. For a status of `400` or more the error is the parsed body; the promise turns a Total.js error array into an `Error`.\n\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n\nvar products = await AJAX('GET https://api.example.com/products/');\n```\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` saves a remote file to disk. `Total.download()` is the same function. `response.size` is the number of bytes saved. Check `response.status`, because the body is saved for every status code:\n\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.size, 'bytes to', response.filename);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwtY3Ax61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/http-requests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"HTTP-Anfragen","summary":"Andere HTTP-Dienste mit RESTBuilder, REQUEST(), AJAX() und DOWNLOAD() aufrufen.","markdown":"---\ntitle: HTTP-Anfragen\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/http-requests/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# HTTP-Anfragen\n\n> Andere HTTP-Dienste mit RESTBuilder, REQUEST(), AJAX() und DOWNLOAD() aufrufen.\n\nTotal.js hat vier Werkzeuge, um aus deiner Anwendung andere HTTP-Dienste aufzurufen: `RESTBuilder` für REST-APIs, `REQUEST()` für volle Kontrolle über eine einzelne Anfrage, `AJAX()` für einen schnellen JSON-Aufruf und `DOWNLOAD()` zum Speichern einer entfernten Datei. `OPENCLIENT()` hält eine WebSocket-Verbindung zu einem anderen Dienst für Anfrage-Antwort-Nachrichten. Alle sind global, daher rufst du sie in Aktionen, Schemas, Plugins und Definitionen ohne `require()` auf.\n\n## RESTBuilder\n\n`RESTBuilder` baut eine Anfrage Schritt für Schritt auf und parst die Antwort für dich. Die statischen Helfer erstellen einen Builder, bei dem Methode und Daten bereits gesetzt sind:\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\t// response: the parsed JSON body\n\t// output.status, output.headers\n\tconsole.log(err, response);\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).callback(console.log);\n```\n\n`GET()` sendet die Daten als Query String. `POST()`, `PUT()`, `PATCH()` und `DELETE()` senden sie als JSON-Body. Du kannst auch mit `RESTBuilder.url(url)` oder `RESTBuilder.make(fn)` beginnen und alles mit Methoden setzen:\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.auth('Bearer ' + CONF.apitoken);\n\tbuilder.header('X-Client', 'shop');\n\tbuilder.timeout(5000);\n\tbuilder.json({ name: 'Peter', email: 'peter@example.com' });\n\tbuilder.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\nDie Anfrage wird im nächsten Tick nach `callback()` oder `stream()` gesendet, daher spielt die Reihenfolge der anderen Methoden keine Rolle. `promise()` sendet sie sofort, rufe es also zuletzt auf.\n\n### Die Antwort\n\nDer Callback erhält `(err, response, output)`. `response` ist der anhand seines `Content-Type` geparste Body: JSON (auch `text/plain` und unbekannte Typen, die JSON enthalten), URL-codierte Daten oder XML (mit dem HTML-Parser geparst). Ein leerer Body ergibt ein leeres Objekt. `output` enthält `status`, `headers`, `response` (den rohen Body), `hostname`, `origin` und die Methode `output.cookie(name)`.\n\n`err` ist gesetzt, wenn die Verbindung fehlschlägt, wenn das Timeout abläuft oder wenn der Statuscode `400` oder höher ist. Bei einem Statusfehler ist `err` ein `ErrorBuilder`: mit den Fehlern eines Total.js-Fehler-Arrays (`[{ error: '...' }]`) oder mit einem Fehler, dessen Name der Statuscode und dessen Meldung der rohe Body der Antwort ist.\n\n`error(value)` ersetzt jeden Fehler durch deinen eigenen Wert, und `logerror()` gibt Fehler über den Fehler-Handler des Frameworks in der Konsole aus:\n\n```js\nRESTBuilder.GET('https://api.example.com/stock/')\n\t.logerror()\n\t.error('The stock service is not available')\n\t.callback(function(err, response) {\n\t\t// err === 'The stock service is not available' on any error\n\t});\n```\n\n### Promises\n\n`promise()` gibt eine Promise zurück, die mit dem geparsten Body erfüllt und mit einem `Error` abgelehnt wird. `callback()` ohne Funktion gibt ebenfalls eine Promise zurück. Übergib das `$` einer Aktion an `promise($)`, und ein Fehler geht direkt an `$.invalid()`; `callback($)` übergibt das ganze Ergebnis an `$.callback()`:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*productid:String, *count:Number',\n\taction: async function($, model) {\n\t\tvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\n\t\t$.callback(order);\n\t}\n});\n```\n\n### Bodies, Dateien und Header\n\n`json(data)`, `urlencoded(data)` und `xml(text)` setzen den Body und seinen Typ (eine GET-Anfrage wird zu POST). `raw(value, [type])` sendet einen String unverändert oder einen Buffer mit `raw(buffer, 'raw')`. `text(value)` sendet einfachen Text und gibt außerdem den Body der Antwort ungeparst zurück. `file(name, filename, [buffer|path|url])` fügt eine Datei hinzu und sendet die Anfrage als `multipart/form-data`:\n\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('file', 'invoice.pdf', PATH.databases('invoice.pdf'))\n\t.callback(console.log);\n```\n\n`header(name, value)`, `type(contentType)`, `accept(ext)`, `auth(user, [password])`, `cookie(name, value)`, `referrer(url)`, `origin(url)`, `csrf(token)` und `xhr()` setzen Header. `cook()` behält die Cookies der Antwort im Builder, sodass die nächste Anfrage mit demselben Builder sie zurücksendet.\n\n### Verbindungsoptionen\n\n`timeout(ms)` (standardmäßig 10 Sekunden), `keepalive([val])`, `proxy(url)`, `insecure()` für selbstsignierte Zertifikate, `cert(key, cert, [dhparam])` für Client-Zertifikate, `unixsocket(socket, path)`, `nodnscache()` und `redirect(false)` steuern, wie die Anfrage ausgeführt wird. Standardmäßig speichert der Builder DNS-Abfragen zwischen und folgt bis zu vier Weiterleitungen.\n\n### Streams und Fortschritt\n\n`stream(callback)` gibt dir die Antwort als Stream, ohne den Body zu lesen. `progress(fn)` meldet den Download-Fortschritt in Prozent, wenn der Dienst `Content-Length` sendet:\n\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (err)\n\t\treturn;\n\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### Total.js-APIs\n\n`RESTBuilder.API(url, name, [data])` ruft einen API-Endpunkt einer anderen Total.js-Anwendung auf (eine Route `API /api/ ...`). Es sendet `{ schema: name, data: data }` als JSON:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(console.log);\n```\n\nDie Anfrage bleibt ein `POST`: `get(query)` fügt die Query zum Body hinzu (`{ schema, data, query }`), und `compress()` lässt die Schlüssel mit Werten `null` oder `undefined` weg:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes', color: null }).get({ page: 2 }).compress().callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n## REQUEST()\n\n`REQUEST(options, [callback])` ist die Low-Level-Funktion, die alle obigen Werkzeuge verwenden. Du beschreibst die ganze Anfrage in einem Objekt. Der Callback erhält `(err, response)`; ohne Callback gibt es eine Promise zurück.\n\n```js\nREQUEST({\n\turl: 'https://api.example.com/status/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ ping: 1 }),\n\theaders: { 'X-Token': CONF.apitoken },\n\ttimeout: 5000,\n\tkeepalive: true\n}, function(err, response) {\n\t// response.status, response.headers, response.body (a string)\n\tconsole.log(err, response.status, response.body);\n});\n```\n\n`REQUEST()` parst den Body nicht: `response.body` ist bei Text- und Application-Typen ein String und bei anderen Typen ein `Buffer`. Das Standard-Timeout beträgt 8 Sekunden (`timeout: 0` schaltet es ab). Mit `custom: true` erhält der Callback `response.stream` statt des Bodys. Mit `writer: function(req) {}` schreibst du den Body selbst und beendest die Anfrage mit `req.end()`. Die vollständige Liste der Optionen steht in der Referenz.\n\nAlle ausgehenden Anfragen können mit dem Konfigurationsschlüssel `$proxyrequest` über einen Proxy laufen (siehe [Konfiguration](../configuration/)); Anfragen an `localhost` umgehen ihn. Zugangsdaten in einer URL werden für dich gesendet: `https://user:password@host/` als `Authorization: Basic` und ein Proxy `http://user:password@host:port` als `Proxy-Authorization: Basic`.\n\n## AJAX()\n\n`AJAX('METHOD url', [data], [callback])` ist der kürzeste Weg, einen JSON-Dienst aufzurufen. `data` wird als JSON gesendet, und die Antwort wird anhand ihres Typs geparst: JSON, URL-codierte Daten und XML werden zu Objekten. Bei einem Status von `400` oder mehr ist der Fehler der geparste Body; die Promise macht aus einem Total.js-Fehler-Array einen `Error`.\n\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n\nvar products = await AJAX('GET https://api.example.com/products/');\n```\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` speichert eine entfernte Datei auf der Festplatte. `Total.download()` ist dieselbe Funktion. `response.size` ist die Anzahl der gespeicherten Bytes. Prüfe `response.status`, denn der Body wird bei jedem Statuscode gespeichert:\n\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.size, 'bytes to', response.filename);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwtY3Ax61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/http-requests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Peticiones HTTP","summary":"Llama a otros servicios HTTP con RESTBuilder, REQUEST(), AJAX() y DOWNLOAD().","markdown":"---\ntitle: Peticiones HTTP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/http-requests/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Peticiones HTTP\n\n> Llama a otros servicios HTTP con RESTBuilder, REQUEST(), AJAX() y DOWNLOAD().\n\nTotal.js tiene cuatro herramientas para llamar a otros servicios HTTP desde tu aplicación: `RESTBuilder` para APIs REST, `REQUEST()` para el control total de una sola petición, `AJAX()` para una llamada JSON rápida y `DOWNLOAD()` para guardar un archivo remoto. `OPENCLIENT()` mantiene una conexión WebSocket con otro servicio para mensajes de petición-respuesta. Todas son globales, así que las llamas en acciones, esquemas, plugins y definiciones sin `require()`.\n\n## RESTBuilder\n\n`RESTBuilder` construye una petición paso a paso y parsea la respuesta por ti. Los helpers estáticos crean un builder con el método y los datos ya establecidos:\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\t// response: the parsed JSON body\n\t// output.status, output.headers\n\tconsole.log(err, response);\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).callback(console.log);\n```\n\n`GET()` envía los datos como query string. `POST()`, `PUT()`, `PATCH()` y `DELETE()` los envían como cuerpo JSON. También puedes empezar con `RESTBuilder.url(url)` o `RESTBuilder.make(fn)` y establecerlo todo con métodos:\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.auth('Bearer ' + CONF.apitoken);\n\tbuilder.header('X-Client', 'shop');\n\tbuilder.timeout(5000);\n\tbuilder.json({ name: 'Peter', email: 'peter@example.com' });\n\tbuilder.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\nLa petición se envía en el siguiente tick después de `callback()` o `stream()`, así que el orden de los demás métodos no importa. `promise()` la envía de inmediato, así que llámalo al final.\n\n### La respuesta\n\nEl callback recibe `(err, response, output)`. `response` es el cuerpo parseado según su `Content-Type`: JSON (también `text/plain` y tipos desconocidos que contienen JSON), datos URL-encoded o XML (parseado con el parser de HTML). Un cuerpo vacío da un objeto vacío. `output` contiene `status`, `headers`, `response` (el cuerpo en bruto), `hostname`, `origin` y el método `output.cookie(name)`.\n\n`err` se establece cuando falla la conexión, cuando vence el tiempo de espera o cuando el código de estado es `400` o más. Para un error de estado, `err` es un `ErrorBuilder`: con los errores de un array de errores de Total.js (`[{ error: '...' }]`), o con un error cuyo nombre es el código de estado y cuyo mensaje es el cuerpo en bruto de la respuesta.\n\n`error(value)` sustituye cualquier error por tu propio valor, y `logerror()` imprime los errores en la consola mediante el manejador de errores del framework:\n\n```js\nRESTBuilder.GET('https://api.example.com/stock/')\n\t.logerror()\n\t.error('The stock service is not available')\n\t.callback(function(err, response) {\n\t\t// err === 'The stock service is not available' on any error\n\t});\n```\n\n### Promesas\n\n`promise()` devuelve una promesa que se resuelve con el cuerpo parseado y se rechaza con un `Error`. `callback()` sin función también devuelve una promesa. Pasa el `$` de una acción a `promise($)` y un error va directamente a `$.invalid()`; `callback($)` pasa el resultado completo a `$.callback()`:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*productid:String, *count:Number',\n\taction: async function($, model) {\n\t\tvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\n\t\t$.callback(order);\n\t}\n});\n```\n\n### Cuerpos, archivos y cabeceras\n\n`json(data)`, `urlencoded(data)` y `xml(text)` establecen el cuerpo y su tipo (una petición GET se convierte en POST). `raw(value, [type])` envía un string tal cual, o un buffer con `raw(buffer, 'raw')`. `text(value)` envía texto plano y además devuelve el cuerpo de la respuesta sin parsear. `file(name, filename, [buffer|path|url])` añade un archivo y envía la petición como `multipart/form-data`:\n\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('file', 'invoice.pdf', PATH.databases('invoice.pdf'))\n\t.callback(console.log);\n```\n\n`header(name, value)`, `type(contentType)`, `accept(ext)`, `auth(user, [password])`, `cookie(name, value)`, `referrer(url)`, `origin(url)`, `csrf(token)` y `xhr()` establecen cabeceras. `cook()` guarda las cookies de la respuesta en el builder, así que la siguiente petición con el mismo builder las devuelve.\n\n### Opciones de conexión\n\n`timeout(ms)` (10 segundos por defecto), `keepalive([val])`, `proxy(url)`, `insecure()` para certificados autofirmados, `cert(key, cert, [dhparam])` para certificados de cliente, `unixsocket(socket, path)`, `nodnscache()` y `redirect(false)` controlan cómo se hace la petición. Por defecto el builder guarda en caché las consultas DNS y sigue hasta cuatro redirecciones.\n\n### Streams y progreso\n\n`stream(callback)` te da la respuesta como stream, sin leer el cuerpo. `progress(fn)` informa del porcentaje de descarga cuando el servicio envía `Content-Length`:\n\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (err)\n\t\treturn;\n\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### APIs de Total.js\n\n`RESTBuilder.API(url, name, [data])` llama a un endpoint API de otra aplicación Total.js (una ruta `API /api/ ...`). Envía `{ schema: name, data: data }` como JSON:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(console.log);\n```\n\nLa petición sigue siendo un `POST`: `get(query)` añade el query al cuerpo (`{ schema, data, query }`), y `compress()` omite las claves con valores `null` o `undefined`:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes', color: null }).get({ page: 2 }).compress().callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n## REQUEST()\n\n`REQUEST(options, [callback])` es la función de bajo nivel que usan todas las herramientas anteriores. Describes toda la petición en un objeto. El callback recibe `(err, response)`; sin callback devuelve una promesa.\n\n```js\nREQUEST({\n\turl: 'https://api.example.com/status/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ ping: 1 }),\n\theaders: { 'X-Token': CONF.apitoken },\n\ttimeout: 5000,\n\tkeepalive: true\n}, function(err, response) {\n\t// response.status, response.headers, response.body (a string)\n\tconsole.log(err, response.status, response.body);\n});\n```\n\n`REQUEST()` no parsea el cuerpo: `response.body` es un string para los tipos de texto y de aplicación, y un `Buffer` para los demás tipos. El tiempo de espera por defecto es de 8 segundos (`timeout: 0` lo desactiva). Con `custom: true` el callback recibe `response.stream` en lugar del cuerpo. Con `writer: function(req) {}` escribes tú el cuerpo y terminas la petición con `req.end()`. La lista completa de opciones está en la referencia.\n\nTodas las peticiones salientes pueden pasar por un proxy con la clave de configuración `$proxyrequest` (consulta [Configuración](../configuration/)); las peticiones a `localhost` lo omiten. Las credenciales de una URL se envían por ti: `https://user:password@host/` como `Authorization: Basic`, y un proxy `http://user:password@host:port` como `Proxy-Authorization: Basic`.\n\n## AJAX()\n\n`AJAX('METHOD url', [data], [callback])` es la forma más corta de llamar a un servicio JSON. `data` se envía como JSON y la respuesta se parsea según su tipo: JSON, datos URL-encoded y XML se convierten en objetos. Para un estado de `400` o más, el error es el cuerpo parseado; la promesa convierte un array de errores de Total.js en un `Error`.\n\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n\nvar products = await AJAX('GET https://api.example.com/products/');\n```\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` guarda un archivo remoto en disco. `Total.download()` es la misma función. `response.size` es el número de bytes guardados. Comprueba `response.status`, porque el cuerpo se guarda para cualquier código de estado:\n\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.size, 'bytes to', response.filename);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwtY3Ax61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/http-requests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Requêtes HTTP","summary":"Appelle d'autres services HTTP avec RESTBuilder, REQUEST(), AJAX() et DOWNLOAD().","markdown":"---\ntitle: \"Requêtes HTTP\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/http-requests/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Requêtes HTTP\n\n> Appelle d'autres services HTTP avec RESTBuilder, REQUEST(), AJAX() et DOWNLOAD().\n\nTotal.js propose quatre outils pour appeler d'autres services HTTP depuis ton application : `RESTBuilder` pour les API REST, `REQUEST()` pour un contrôle total d'une requête unique, `AJAX()` pour un appel JSON rapide et `DOWNLOAD()` pour enregistrer un fichier distant. `OPENCLIENT()` maintient une connexion WebSocket vers un autre service pour des messages requête-réponse. Tous sont globaux : tu les appelles dans les actions, les schémas, les plugins et les définitions sans `require()`.\n\n## RESTBuilder\n\n`RESTBuilder` construit une requête étape par étape et analyse la réponse pour toi. Les helpers statiques créent un builder avec la méthode et les données déjà définies :\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\t// response: the parsed JSON body\n\t// output.status, output.headers\n\tconsole.log(err, response);\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).callback(console.log);\n```\n\n`GET()` envoie les données sous forme de query string. `POST()`, `PUT()`, `PATCH()` et `DELETE()` les envoient comme corps JSON. Tu peux aussi commencer avec `RESTBuilder.url(url)` ou `RESTBuilder.make(fn)` et tout définir avec des méthodes :\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.auth('Bearer ' + CONF.apitoken);\n\tbuilder.header('X-Client', 'shop');\n\tbuilder.timeout(5000);\n\tbuilder.json({ name: 'Peter', email: 'peter@example.com' });\n\tbuilder.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\nLa requête est envoyée au tick suivant après `callback()` ou `stream()` : l'ordre des autres méthodes n'a donc pas d'importance. `promise()` l'envoie immédiatement : appelle-la donc en dernier.\n\n### La réponse\n\nLe callback reçoit `(err, response, output)`. `response` est le corps analysé selon son `Content-Type` : JSON (aussi `text/plain` et les types inconnus qui contiennent du JSON), données URL-encoded, ou XML (analysé avec le parseur HTML). Un corps vide donne un objet vide. `output` contient `status`, `headers`, `response` (le corps brut), `hostname`, `origin` et la méthode `output.cookie(name)`.\n\n`err` est défini lorsque la connexion échoue, lorsque le délai d'expiration est dépassé, ou lorsque le code de statut est `400` ou plus. Pour une erreur de statut, `err` est un `ErrorBuilder` : avec les erreurs d'un tableau d'erreurs Total.js (`[{ error: '...' }]`), ou avec une erreur dont le nom est le code de statut et dont le message est le corps brut de la réponse.\n\n`error(value)` remplace toute erreur par ta propre valeur, et `logerror()` affiche les erreurs dans la console via le gestionnaire d'erreurs du framework :\n\n```js\nRESTBuilder.GET('https://api.example.com/stock/')\n\t.logerror()\n\t.error('The stock service is not available')\n\t.callback(function(err, response) {\n\t\t// err === 'The stock service is not available' on any error\n\t});\n```\n\n### Promesses\n\n`promise()` renvoie une promesse résolue avec le corps analysé et rejetée avec une `Error`. `callback()` sans fonction renvoie aussi une promesse. Passe le `$` d'une action à `promise($)` et une erreur va directement à `$.invalid()` ; `callback($)` passe le résultat complet à `$.callback()` :\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*productid:String, *count:Number',\n\taction: async function($, model) {\n\t\tvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\n\t\t$.callback(order);\n\t}\n});\n```\n\n### Corps, fichiers et en-têtes\n\n`json(data)`, `urlencoded(data)` et `xml(text)` définissent le corps et son type (une requête GET devient POST). `raw(value, [type])` envoie une chaîne telle quelle, ou un buffer avec `raw(buffer, 'raw')`. `text(value)` envoie du texte brut et renvoie aussi le corps de la réponse sans l'analyser. `file(name, filename, [buffer|path|url])` ajoute un fichier et envoie la requête en `multipart/form-data` :\n\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('file', 'invoice.pdf', PATH.databases('invoice.pdf'))\n\t.callback(console.log);\n```\n\n`header(name, value)`, `type(contentType)`, `accept(ext)`, `auth(user, [password])`, `cookie(name, value)`, `referrer(url)`, `origin(url)`, `csrf(token)` et `xhr()` définissent des en-têtes. `cook()` conserve les cookies de la réponse dans le builder : la requête suivante avec le même builder les renvoie.\n\n### Options de connexion\n\n`timeout(ms)` (10 secondes par défaut), `keepalive([val])`, `proxy(url)`, `insecure()` pour les certificats auto-signés, `cert(key, cert, [dhparam])` pour les certificats clients, `unixsocket(socket, path)`, `nodnscache()` et `redirect(false)` contrôlent la façon dont la requête est effectuée. Par défaut, le builder met en cache les résolutions DNS et suit jusqu'à quatre redirections.\n\n### Streams et progression\n\n`stream(callback)` te fournit la réponse sous forme de stream, sans lire le corps. `progress(fn)` indique le pourcentage de téléchargement lorsque le service envoie `Content-Length` :\n\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (err)\n\t\treturn;\n\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### API Total.js\n\n`RESTBuilder.API(url, name, [data])` appelle un endpoint d'API d'une autre application Total.js (une route `API /api/ ...`). Il envoie `{ schema: name, data: data }` en JSON :\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(console.log);\n```\n\nLa requête reste un `POST` : `get(query)` ajoute la query au corps (`{ schema, data, query }`), et `compress()` omet les clés dont la valeur est `null` ou `undefined` :\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes', color: null }).get({ page: 2 }).compress().callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n## REQUEST()\n\n`REQUEST(options, [callback])` est la fonction de bas niveau utilisée par tous les outils ci-dessus. Tu décris toute la requête dans un seul objet. Le callback reçoit `(err, response)` ; sans callback, la fonction renvoie une promesse.\n\n```js\nREQUEST({\n\turl: 'https://api.example.com/status/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ ping: 1 }),\n\theaders: { 'X-Token': CONF.apitoken },\n\ttimeout: 5000,\n\tkeepalive: true\n}, function(err, response) {\n\t// response.status, response.headers, response.body (a string)\n\tconsole.log(err, response.status, response.body);\n});\n```\n\n`REQUEST()` n'analyse pas le corps : `response.body` est une chaîne pour les types texte et application, et un `Buffer` pour les autres types. Le délai d'expiration par défaut est de 8 secondes (`timeout: 0` le désactive). Avec `custom: true`, le callback reçoit `response.stream` au lieu du corps. Avec `writer: function(req) {}`, tu écris toi-même le corps et tu termines la requête avec `req.end()`. La liste complète des options se trouve dans la référence.\n\nToutes les requêtes sortantes peuvent passer par un même proxy avec la clé de configuration `$proxyrequest` (voir [Configuration](../configuration/)) ; les requêtes vers `localhost` ne l'utilisent pas. Les identifiants dans une URL sont envoyés pour toi : `https://user:password@host/` comme `Authorization: Basic`, et un proxy `http://user:password@host:port` comme `Proxy-Authorization: Basic`.\n\n## AJAX()\n\n`AJAX('METHOD url', [data], [callback])` est le moyen le plus court d'appeler un service JSON. `data` est envoyé en JSON et la réponse est analysée selon son type : le JSON, les données encodées en URL et le XML deviennent des objets. Pour un statut de `400` ou plus, l'erreur est le corps analysé ; la promesse transforme un tableau d'erreurs Total.js en `Error`.\n\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n\nvar products = await AJAX('GET https://api.example.com/products/');\n```\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` enregistre un fichier distant sur le disque. `Total.download()` est la même fonction. `response.size` est le nombre d'octets enregistrés. Vérifie `response.status`, car le corps est enregistré quel que soit le code de statut :\n\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.size, 'bytes to', response.filename);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwtY3Ax61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/http-requests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Richieste HTTP","summary":"Chiama altri servizi HTTP con RESTBuilder, REQUEST(), AJAX() e DOWNLOAD().","markdown":"---\ntitle: Richieste HTTP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/http-requests/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Richieste HTTP\n\n> Chiama altri servizi HTTP con RESTBuilder, REQUEST(), AJAX() e DOWNLOAD().\n\nTotal.js ha quattro strumenti per chiamare altri servizi HTTP dalla tua applicazione: `RESTBuilder` per le API REST, `REQUEST()` per il pieno controllo di una singola richiesta, `AJAX()` per una chiamata JSON rapida e `DOWNLOAD()` per salvare un file remoto. `OPENCLIENT()` mantiene una connessione WebSocket verso un altro servizio per messaggi di tipo richiesta-risposta. Sono tutti globali, quindi li chiami in azioni, schemi, plugin e definizioni senza `require()`.\n\n## RESTBuilder\n\n`RESTBuilder` costruisce una richiesta passo dopo passo e interpreta la risposta per te. Gli helper statici creano un builder con il metodo e i dati già impostati:\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\t// response: the parsed JSON body\n\t// output.status, output.headers\n\tconsole.log(err, response);\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).callback(console.log);\n```\n\n`GET()` invia i dati come query string. `POST()`, `PUT()`, `PATCH()` e `DELETE()` li inviano come body JSON. Puoi anche partire da `RESTBuilder.url(url)` o `RESTBuilder.make(fn)` e impostare tutto con i metodi:\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.auth('Bearer ' + CONF.apitoken);\n\tbuilder.header('X-Client', 'shop');\n\tbuilder.timeout(5000);\n\tbuilder.json({ name: 'Peter', email: 'peter@example.com' });\n\tbuilder.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\nLa richiesta viene inviata al tick successivo a `callback()` o `stream()`, quindi l'ordine degli altri metodi non conta. `promise()` la invia subito, quindi chiamalo per ultimo.\n\n### La risposta\n\nLa callback riceve `(err, response, output)`. `response` è il body interpretato in base al suo `Content-Type`: JSON (anche `text/plain` e tipi sconosciuti che contengono JSON), dati URL-encoded o XML (interpretato con il parser HTML). Un body vuoto produce un oggetto vuoto. `output` contiene `status`, `headers`, `response` (il body grezzo), `hostname`, `origin` e il metodo `output.cookie(name)`.\n\n`err` viene impostato quando la connessione fallisce, quando scade il timeout o quando il codice di stato è `400` o superiore. Per un errore di stato `err` è un `ErrorBuilder`: con gli errori di un array di errori Total.js (`[{ error: '...' }]`), oppure con un errore il cui nome è il codice di stato e il cui messaggio è il body grezzo della risposta.\n\n`error(value)` sostituisce qualsiasi errore con un tuo valore, e `logerror()` stampa gli errori nella console tramite il gestore degli errori del framework:\n\n```js\nRESTBuilder.GET('https://api.example.com/stock/')\n\t.logerror()\n\t.error('The stock service is not available')\n\t.callback(function(err, response) {\n\t\t// err === 'The stock service is not available' on any error\n\t});\n```\n\n### Promise\n\n`promise()` restituisce una promise che si risolve con il body interpretato e viene rifiutata con un `Error`. Anche `callback()` senza funzione restituisce una promise. Passa il `$` di un'azione a `promise($)` e un errore va direttamente a `$.invalid()`; `callback($)` passa l'intero risultato a `$.callback()`:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*productid:String, *count:Number',\n\taction: async function($, model) {\n\t\tvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\n\t\t$.callback(order);\n\t}\n});\n```\n\n### Body, file e header\n\n`json(data)`, `urlencoded(data)` e `xml(text)` impostano il body e il suo tipo (una richiesta GET diventa POST). `raw(value, [type])` invia una stringa così com'è, oppure un buffer con `raw(buffer, 'raw')`. `text(value)` invia testo semplice e restituisce anche il body della risposta senza interpretarlo. `file(name, filename, [buffer|path|url])` aggiunge un file e invia la richiesta come `multipart/form-data`:\n\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('file', 'invoice.pdf', PATH.databases('invoice.pdf'))\n\t.callback(console.log);\n```\n\n`header(name, value)`, `type(contentType)`, `accept(ext)`, `auth(user, [password])`, `cookie(name, value)`, `referrer(url)`, `origin(url)`, `csrf(token)` e `xhr()` impostano gli header. `cook()` conserva nel builder i cookie della risposta, così la richiesta successiva con lo stesso builder li rimanda indietro.\n\n### Opzioni di connessione\n\n`timeout(ms)` (10 secondi per impostazione predefinita), `keepalive([val])`, `proxy(url)`, `insecure()` per i certificati autofirmati, `cert(key, cert, [dhparam])` per i certificati client, `unixsocket(socket, path)`, `nodnscache()` e `redirect(false)` controllano come viene effettuata la richiesta. Per impostazione predefinita il builder mette in cache le risoluzioni DNS e segue fino a quattro redirect.\n\n### Stream e avanzamento\n\n`stream(callback)` ti dà la risposta come stream, senza leggere il body. `progress(fn)` riporta la percentuale di download quando il servizio invia `Content-Length`:\n\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (err)\n\t\treturn;\n\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### API Total.js\n\n`RESTBuilder.API(url, name, [data])` chiama un endpoint API di un'altra applicazione Total.js (una route `API /api/ ...`). Invia `{ schema: name, data: data }` come JSON:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(console.log);\n```\n\nLa richiesta resta un `POST`: `get(query)` aggiunge la query al body (`{ schema, data, query }`), e `compress()` tralascia le chiavi con valori `null` o `undefined`:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes', color: null }).get({ page: 2 }).compress().callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n## REQUEST()\n\n`REQUEST(options, [callback])` è la funzione di basso livello usata da tutti gli strumenti precedenti. Descrivi l'intera richiesta in un unico oggetto. La callback riceve `(err, response)`; senza callback restituisce una promise.\n\n```js\nREQUEST({\n\turl: 'https://api.example.com/status/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ ping: 1 }),\n\theaders: { 'X-Token': CONF.apitoken },\n\ttimeout: 5000,\n\tkeepalive: true\n}, function(err, response) {\n\t// response.status, response.headers, response.body (a string)\n\tconsole.log(err, response.status, response.body);\n});\n```\n\n`REQUEST()` non interpreta il body: `response.body` è una stringa per i tipi testo e application e un `Buffer` per gli altri tipi. Il timeout predefinito è di 8 secondi (`timeout: 0` lo disattiva). Con `custom: true` la callback riceve `response.stream` invece del body. Con `writer: function(req) {}` scrivi tu il body e termini la richiesta con `req.end()`. L'elenco completo delle opzioni è nel riferimento.\n\nTutte le richieste in uscita possono passare per un unico proxy con la chiave di configurazione `$proxyrequest` (vedi [Configurazione](../configuration/)); le richieste verso `localhost` lo saltano. Le credenziali in un URL vengono inviate al posto tuo: `https://user:password@host/` come `Authorization: Basic`, e un proxy `http://user:password@host:port` come `Proxy-Authorization: Basic`.\n\n## AJAX()\n\n`AJAX('METHOD url', [data], [callback])` è il modo più breve per chiamare un servizio JSON. `data` viene inviato come JSON e la risposta viene interpretata in base al suo tipo: JSON, dati URL-encoded e XML diventano oggetti. Per uno stato `400` o superiore l'errore è il body interpretato; la promise trasforma un array di errori Total.js in un `Error`.\n\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n\nvar products = await AJAX('GET https://api.example.com/products/');\n```\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` salva un file remoto sul disco. `Total.download()` è la stessa funzione. `response.size` è il numero di byte salvati. Controlla `response.status`, perché il body viene salvato per ogni codice di stato:\n\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.size, 'bytes to', response.filename);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwtY3Ax61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/http-requests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"HTTP požiadavky","summary":"Volanie iných HTTP služieb cez RESTBuilder, REQUEST(), AJAX() a DOWNLOAD().","markdown":"---\ntitle: \"HTTP požiadavky\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/http-requests/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# HTTP požiadavky\n\n> Volanie iných HTTP služieb cez RESTBuilder, REQUEST(), AJAX() a DOWNLOAD().\n\nTotal.js má štyri nástroje na volanie iných HTTP služieb z tvojej aplikácie: `RESTBuilder` pre REST API, `REQUEST()` pre úplnú kontrolu nad jednou požiadavkou, `AJAX()` pre rýchle JSON volanie a `DOWNLOAD()` na uloženie vzdialeného súboru. `OPENCLIENT()` udržiava WebSocket spojenie s inou službou pre správy typu požiadavka-odpoveď. Všetky sú globálne, takže ich voláš v akciách, schémach, pluginoch a definíciách bez `require()`.\n\n## RESTBuilder\n\n`RESTBuilder` zostavuje požiadavku krok za krokom a odpoveď spracuje za teba. Statické pomocné funkcie vytvoria builder s už nastavenou metódou a dátami:\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\t// response: the parsed JSON body\n\t// output.status, output.headers\n\tconsole.log(err, response);\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).callback(console.log);\n```\n\n`GET()` odošle dáta ako query string. `POST()`, `PUT()`, `PATCH()` a `DELETE()` ich odošlú ako JSON telo. Môžeš začať aj cez `RESTBuilder.url(url)` alebo `RESTBuilder.make(fn)` a všetko nastaviť metódami:\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.auth('Bearer ' + CONF.apitoken);\n\tbuilder.header('X-Client', 'shop');\n\tbuilder.timeout(5000);\n\tbuilder.json({ name: 'Peter', email: 'peter@example.com' });\n\tbuilder.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\nPožiadavka sa odošle v nasledujúcom ticku po `callback()` alebo `stream()`, takže na poradí ostatných metód nezáleží. `promise()` ju odošle hneď, preto ju volaj ako poslednú.\n\n### Odpoveď\n\nCallback dostane `(err, response, output)`. `response` je telo spracované podľa jeho `Content-Type`: JSON (aj `text/plain` a neznáme typy, ktoré obsahujú JSON), URL-encoded dáta alebo XML (spracované HTML parserom). Prázdne telo dá prázdny objekt. `output` obsahuje `status`, `headers`, `response` (surové telo), `hostname`, `origin` a metódu `output.cookie(name)`.\n\n`err` sa nastaví, keď spojenie zlyhá, keď vyprší časový limit alebo keď je stavový kód `400` či vyšší. Pri chybe stavu je `err` objekt `ErrorBuilder`: s chybami z poľa chýb Total.js (`[{ error: '...' }]`) alebo s jednou chybou, ktorej názov je stavový kód a správa je surové telo odpovede.\n\n`error(value)` nahradí akúkoľvek chybu vlastnou hodnotou a `logerror()` vypisuje chyby do konzoly cez chybový handler frameworku:\n\n```js\nRESTBuilder.GET('https://api.example.com/stock/')\n\t.logerror()\n\t.error('The stock service is not available')\n\t.callback(function(err, response) {\n\t\t// err === 'The stock service is not available' on any error\n\t});\n```\n\n### Promises\n\n`promise()` vracia promise, ktorý sa splní so spracovaným telom a zamietne s `Error`. `callback()` bez funkcie tiež vracia promise. Odovzdaj `$` akcie do `promise($)` a chyba pôjde priamo do `$.invalid()`; `callback($)` odovzdá celý výsledok do `$.callback()`:\n\n```js\nNEWACTION('Orders/create', {\n\tname: 'Create an order',\n\tinput: '*productid:String, *count:Number',\n\taction: async function($, model) {\n\t\tvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\n\t\t$.callback(order);\n\t}\n});\n```\n\n### Telá, súbory a hlavičky\n\n`json(data)`, `urlencoded(data)` a `xml(text)` nastavia telo a jeho typ (GET požiadavka sa zmení na POST). `raw(value, [type])` odošle reťazec tak, ako je, alebo buffer cez `raw(buffer, 'raw')`. `text(value)` odošle čistý text a zároveň vráti telo odpovede bez spracovania. `file(name, filename, [buffer|path|url])` pridá súbor a odošle požiadavku ako `multipart/form-data`:\n\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('file', 'invoice.pdf', PATH.databases('invoice.pdf'))\n\t.callback(console.log);\n```\n\n`header(name, value)`, `type(contentType)`, `accept(ext)`, `auth(user, [password])`, `cookie(name, value)`, `referrer(url)`, `origin(url)`, `csrf(token)` a `xhr()` nastavujú hlavičky. `cook()` uchová cookies odpovede v builderi, takže ďalšia požiadavka s tým istým builderom ich pošle späť.\n\n### Možnosti spojenia\n\n`timeout(ms)` (predvolene 10 sekúnd), `keepalive([val])`, `proxy(url)`, `insecure()` pre self-signed certifikáty, `cert(key, cert, [dhparam])` pre klientske certifikáty, `unixsocket(socket, path)`, `nodnscache()` a `redirect(false)` určujú, ako sa požiadavka vykoná. Predvolene builder ukladá DNS dotazy do cache a nasleduje najviac štyri presmerovania.\n\n### Streamy a priebeh\n\n`stream(callback)` ti dá odpoveď ako stream bez čítania tela. `progress(fn)` hlási percento stiahnutia, keď služba posiela `Content-Length`:\n\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (err)\n\t\treturn;\n\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### Total.js API\n\n`RESTBuilder.API(url, name, [data])` zavolá API endpoint inej Total.js aplikácie (trasa `API /api/ ...`). Odošle `{ schema: name, data: data }` ako JSON:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(console.log);\n```\n\nPožiadavka zostane `POST`: `get(query)` pridá query do tela (`{ schema, data, query }`) a `compress()` vynechá kľúče s hodnotami `null` alebo `undefined`:\n\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes', color: null }).get({ page: 2 }).compress().callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n## REQUEST()\n\n`REQUEST(options, [callback])` je nízkoúrovňová funkcia, ktorú používajú všetky nástroje vyššie. Celú požiadavku opíšeš v jednom objekte. Callback dostane `(err, response)`; bez callbacku vracia promise.\n\n```js\nREQUEST({\n\turl: 'https://api.example.com/status/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ ping: 1 }),\n\theaders: { 'X-Token': CONF.apitoken },\n\ttimeout: 5000,\n\tkeepalive: true\n}, function(err, response) {\n\t// response.status, response.headers, response.body (a string)\n\tconsole.log(err, response.status, response.body);\n});\n```\n\n`REQUEST()` telo nespracúva: `response.body` je reťazec pre textové a aplikačné typy a `Buffer` pre ostatné typy. Predvolený časový limit je 8 sekúnd (`timeout: 0` ho vypne). S `custom: true` dostane callback namiesto tela `response.stream`. S `writer: function(req) {}` zapíšeš telo sám a požiadavku ukončíš cez `req.end()`. Úplný zoznam možností je v referencii.\n\nVšetky odchádzajúce požiadavky môžu ísť cez jednu proxy s konfiguračným kľúčom `$proxyrequest` (pozri [Konfigurácia](../configuration/)); požiadavky na `localhost` ju obchádzajú. Prihlasovacie údaje v URL sa odošlú za teba: `https://user:password@host/` ako `Authorization: Basic` a proxy `http://user:password@host:port` ako `Proxy-Authorization: Basic`.\n\n## AJAX()\n\n`AJAX('METHOD url', [data], [callback])` je najkratší spôsob, ako zavolať JSON službu. `data` sa odošlú ako JSON a odpoveď sa spracuje podľa svojho typu: JSON, URL-encoded dáta a XML sa zmenia na objekty. Pri stave `400` alebo vyššom je chybou spracované telo; promise zmení pole chýb Total.js na `Error`.\n\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n\nvar products = await AJAX('GET https://api.example.com/products/');\n```\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` uloží vzdialený súbor na disk. `Total.download()` je tá istá funkcia. `response.size` je počet uložených bajtov. Skontroluj `response.status`, pretože telo sa uloží pri každom stavovom kóde:\n\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.size, 'bytes to', response.filename);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafqoB1cr61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/openclient/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"OpenClient","summary":"Open a WebSocket connection to another service with OPENCLIENT() and send messages that wait for an answer.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/openclient/\nupdated: 2026-11-16T15:58:11.814Z\n---\n\n# OpenClient\n\n> Open a WebSocket connection to another service with OPENCLIENT() and send messages that wait for an answer.\n\n`OPENCLIENT(url, [id])` opens a WebSocket connection to another service and lets you send messages that wait for an answer. Several clients with the same URL share one connection, which reconnects by itself.\n\n```js\nvar client = OPENCLIENT('https://service.example.com/$client/');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log('Message', msg);\n});\n\nvar result = await client.rpc({ type: 'users' }, 5000);\n```\n\n`rpc()` adds a `callbackid` to the message; the service answers with `{ callbackid, error, response }`. For WebSocket routes in your own application read [WebSockets](../websockets/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:58:11.814Z"}
{"id":"JafqoB1cr61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/openclient/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"OpenClient","summary":"Öffne mit OPENCLIENT() eine WebSocket-Verbindung zu einem anderen Dienst und sende Nachrichten, die auf eine Antwort warten.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/openclient/\nupdated: 2026-11-16T15:58:11.814Z\n---\n\n# OpenClient\n\n> Öffne mit OPENCLIENT() eine WebSocket-Verbindung zu einem anderen Dienst und sende Nachrichten, die auf eine Antwort warten.\n\n`OPENCLIENT(url, [id])` öffnet eine WebSocket-Verbindung zu einem anderen Dienst und ermöglicht dir, Nachrichten zu senden, die auf eine Antwort warten. Mehrere Clients mit derselben URL teilen sich eine Verbindung, die sich selbst neu verbindet.\n\n```js\nvar client = OPENCLIENT('https://service.example.com/$client/');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log('Message', msg);\n});\n\nvar result = await client.rpc({ type: 'users' }, 5000);\n```\n\n`rpc()` fügt der Nachricht eine `callbackid` hinzu; der Dienst antwortet mit `{ callbackid, error, response }`. Für WebSocket-Routes in deiner eigenen Anwendung lies [WebSockets](../websockets/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:58:11.814Z"}
{"id":"JafqoB1cr61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/openclient/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"OpenClient","summary":"Abre una conexión WebSocket con otro servicio con OPENCLIENT() y envía mensajes que esperan respuesta.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/openclient/\nupdated: 2026-11-16T15:58:11.814Z\n---\n\n# OpenClient\n\n> Abre una conexión WebSocket con otro servicio con OPENCLIENT() y envía mensajes que esperan respuesta.\n\n`OPENCLIENT(url, [id])` abre una conexión WebSocket con otro servicio y te permite enviar mensajes que esperan una respuesta. Varios clientes con la misma URL comparten una conexión, que se reconecta sola.\n\n```js\nvar client = OPENCLIENT('https://service.example.com/$client/');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log('Message', msg);\n});\n\nvar result = await client.rpc({ type: 'users' }, 5000);\n```\n\n`rpc()` añade un `callbackid` al mensaje; el servicio responde con `{ callbackid, error, response }`. Para las rutas WebSocket de tu propia aplicación, lee [WebSockets](../websockets/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:58:11.814Z"}
{"id":"JafqoB1cr61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/openclient/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"OpenClient","summary":"Ouvre une connexion WebSocket vers un autre service avec OPENCLIENT() et envoie des messages qui attendent une réponse.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/openclient/\nupdated: 2026-11-16T15:58:11.814Z\n---\n\n# OpenClient\n\n> Ouvre une connexion WebSocket vers un autre service avec OPENCLIENT() et envoie des messages qui attendent une réponse.\n\n`OPENCLIENT(url, [id])` ouvre une connexion WebSocket vers un autre service et te permet d'envoyer des messages qui attendent une réponse. Plusieurs clients avec la même URL partagent une même connexion, qui se reconnecte d'elle-même.\n\n```js\nvar client = OPENCLIENT('https://service.example.com/$client/');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log('Message', msg);\n});\n\nvar result = await client.rpc({ type: 'users' }, 5000);\n```\n\n`rpc()` ajoute un `callbackid` au message ; le service répond avec `{ callbackid, error, response }`. Pour les routes WebSocket de ta propre application, lis [WebSockets](../websockets/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:58:11.814Z"}
{"id":"JafqoB1cr61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/openclient/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"OpenClient","summary":"Apri una connessione WebSocket verso un altro servizio con OPENCLIENT() e invia messaggi che aspettano una risposta.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/openclient/\nupdated: 2026-11-16T15:58:11.814Z\n---\n\n# OpenClient\n\n> Apri una connessione WebSocket verso un altro servizio con OPENCLIENT() e invia messaggi che aspettano una risposta.\n\n`OPENCLIENT(url, [id])` apre una connessione WebSocket verso un altro servizio e ti permette di inviare messaggi che attendono una risposta. Più client con lo stesso URL condividono un'unica connessione, che si riconnette da sola.\n\n```js\nvar client = OPENCLIENT('https://service.example.com/$client/');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log('Message', msg);\n});\n\nvar result = await client.rpc({ type: 'users' }, 5000);\n```\n\n`rpc()` aggiunge un `callbackid` al messaggio; il servizio risponde con `{ callbackid, error, response }`. Per le route WebSocket nella tua applicazione leggi [WebSocket](../websockets/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:58:11.814Z"}
{"id":"JafqoB1cr61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/openclient/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"OpenClient","summary":"Otvor WebSocket spojenie s inou službou pomocou OPENCLIENT() a posielaj správy, ktoré čakajú na odpoveď.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/openclient/\nupdated: 2026-11-16T15:58:11.814Z\n---\n\n# OpenClient\n\n> Otvor WebSocket spojenie s inou službou pomocou OPENCLIENT() a posielaj správy, ktoré čakajú na odpoveď.\n\n`OPENCLIENT(url, [id])` otvorí WebSocket spojenie s inou službou a umožní ti posielať správy, ktoré čakajú na odpoveď. Viac klientov s rovnakou URL zdieľa jedno spojenie, ktoré sa samo znovu pripája.\n\n```js\nvar client = OPENCLIENT('https://service.example.com/$client/');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log('Message', msg);\n});\n\nvar result = await client.rpc({ type: 'users' }, 5000);\n```\n\n`rpc()` pridá do správy `callbackid`; služba odpovie pomocou `{ callbackid, error, response }`. Pre WebSocket route vo vlastnej aplikácii si prečítaj [WebSockety](../websockets/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:58:11.814Z"}
{"id":"JafwuS6Ex61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/mail/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Sending email","summary":"Send e-mail with MAIL(), HTMLMAIL() and LOGMAIL(), configure SMTP, add attachments and build messages with the Mail module.","markdown":"---\ntitle: Sending email\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/mail/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Sending email\n\n> Send e-mail with MAIL(), HTMLMAIL() and LOGMAIL(), configure SMTP, add attachments and build messages with the Mail module.\n\nTotal.js 5 sends e-mail over SMTP with its own client, the `Mail` module. Three global functions cover most needs: `MAIL()` renders a view as the body, `HTMLMAIL()` sends HTML you already have, and `LOGMAIL()` sends a quick text report. Each one returns a **message** object that you can still change before it leaves.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' });\nHTMLMAIL('user@example.com', 'Your order', '<p>Thank you for your order.</p>');\nLOGMAIL('admin@example.com', 'Import finished', { count: 120 });\n```\n\nThe full list of functions, methods and keys is in the reference of [Sending email](../../reference/mail/).\n\n## Configuration\n\nThe SMTP server is set in the `config` file with the `smtp` key (`mail` is an alias). The value is an object; the framework stores it as `CONF.smtp`.\n\n```\nsmtp (json)     : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true ,\"user\":\"info@example.com\",\"password\":\"secret\"}\nmail_from       : info@example.com\nmail_from_name  : My application\n```\n\n| Option | Meaning |\n| --- | --- |\n| `server` | The host name or IP address of the SMTP server (`host`, `hostname`, `smtp` and `url` are read when `server` is missing). An international name is converted to punycode and an IPv4 address to its dotted form |\n| `port` | The port. With `secure: true` it defaults to `465`; otherwise set it (usually `25` or `587`) |\n| `secure` | `true` opens a TLS connection from the start (implicit TLS) |\n| `user`, `password` | The login. The client uses `AUTH LOGIN`, or `AUTH PLAIN` when the server also offers `XOAUTH` and no `token` is set |\n| `token` | An OAuth2 access token, used with `user` when the server offers `XOAUTH2` |\n| `tls` | Extra Node.js TLS options used for the `STARTTLS` upgrade |\n| `timeout` | The connection timeout in milliseconds (default `60000`) |\n| `from`, `name` | The sender address and name used when `mail_from` and `mail_from_name` are not set |\n\nOn a plain connection (for example port `587`) the client upgrades to TLS with `STARTTLS` before it logs in when the server asks for TLS or offers the login only after it. To be sure that the login is always encrypted, use `secure: true` with port `465`.\n\nInstead of one object you can also set the server and the options separately:\n\n```\nmail_smtp          : smtp.example.com\nmail_smtp_options  : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nThe keys `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` and `mail_bcc` are the defaults that `MAIL()`, `HTMLMAIL()` and `LOGMAIL()` put into every message. `mail_reply`, `mail_cc` and `mail_bcc` hold one address each. See [Configuration](../configuration/) for the format of the file.\n\n## MAIL() with a view\n\n`MAIL(email, subject, view, [model], [language], [callback])` renders a view from `/views/` and sends the result. The model is available in the view as `model`, exactly as in [Views](../views/). Start a mail view with `@{layout('')}`: without it the view is rendered into `/views/layout.html`, and `MAIL()` fails if that file does not exist.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' }, function(err) {\n\tif (err)\n\t\tconsole.log('Not sent:', err);\n});\n```\n\n```html\n<!-- views/mail/welcome.html -->\n@{layout('')}\n<h1>Hello @{model.name}</h1>\n<p>Your account is ready.</p>\n```\n\nWith `language`, the view is rendered in that language and a subject that contains `@(...)` is translated as well. See [Localization](../localization/).\n\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language);\n```\n\nThe `email` argument is one address, a comma-separated string of addresses, or an array. Each address becomes a `To:` recipient.\n\n## HTMLMAIL() and LOGMAIL()\n\n`HTMLMAIL(email, subject, body, [language], [callback])` sends HTML from a string. When the body has no `<body>` tag, it is wrapped in a simple HTML document with the subject as the title.\n\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL(email, [subject], body, [callback])` is meant for reports to yourself. The body is shown as preformatted text: a string as it is (it can contain HTML), an object serialized to JSON and HTML-encoded. Without a subject, `CONF.name` is used.\n\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n## Changing the message before it is sent\n\nAll three functions return the message and send it a moment later (on the next turn of the event loop). Until then you can add recipients, attachments or headers:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.cc('accounting@example.com');\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\nmsg.unsubscribe('https://example.com/unsubscribe/?id=123');\n```\n\n`message.manually()` stops the automatic sending. You send the message yourself later with `message.send2()`:\n\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n\n// ... later\nmsg.send2(function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n\n## Attachments\n\n`message.attachment(filename, name, [contentid])` attaches a file from the disk. `name` is the file name the recipient sees, and its extension sets the content type. With a `contentid` the file is an inline part that the HTML refers to as `cid:<contentid>`:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Newsletter', '<img src=\"cid:logo\" /><p>News of the month</p>');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nThe first argument can also be a `Buffer`, for a file you create in memory. `message.attachmentfs(storage, id, [name], [contentid])` attaches a file of a [file storage](../file-storage/); without `name`, the name and the type stored with the file are used:\n\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Your documents', '<p>The files are attached.</p>');\nmsg.attachment(Buffer.from('id;name\\n1;Peter\\n'), 'users.csv');\nmsg.attachmentfs('documents', id);\n```\n\n## Building a message yourself\n\n`Mail.create(subject, body)` returns a new message that nobody sends for you. Set the sender and the recipients, then send it with the configured server (`message.send2()`) or with other SMTP options (`message.send(options)`).\n\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.reply('support@example.com');\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send2();\n```\n\nThe body is HTML by default. Set `msg.type = 'plain'` for a plain-text body. `msg.headers` is an object of extra headers.\n\n`msg.high()` and `msg.low()` set the priority of the message (the header `X-Priority: 1` or `X-Priority: 5`), and `msg.confidential()` adds `Sensitivity: Company-Confidential`. The three methods return the message, so you can chain them:\n\n```js\nHTMLMAIL('boss@example.com', 'Server is down', '<p>The server does not answer.</p>').high().confidential();\n```\n\n`Mail.send(options, messages, [callback])` sends one message or an array of messages over a single connection. `Mail.try(options)` only connects and logs in, which is useful to check SMTP settings:\n\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n## Errors and events\n\nThe callback of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()` (the same as `message.callback()`) is called as `callback(err, message)`. `err` is empty when the message has been handed over to the server. Otherwise it describes the problem:\n\n- the server refuses the message (for example an unknown recipient): the reply line of the server,\n- `CONF.smtp` is set but has no server: `No SMTP server configuration.` Without an `smtp` key `CONF.smtp` is `undefined` and the functions throw a `TypeError`,\n- the server is not a valid host name: `Invalid SMTP server hostname.`,\n- the connection fails or times out.\n\nA refused login also gives the reply line of the server. Reply lines are in upper case.\n\nAn error that reaches a callback is not written to the error log; without a callback, it is logged with `F.error()`.\n\n`Mail` is an event emitter, and the framework emits a global event for every message:\n\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n`Mail.debug = true` prints the whole SMTP conversation to the console.\n\n## Sending through the Total.js API\n\nWith `$tapimail : true` the messages do not go to your SMTP server. They are sent by the Total.js API service (see [APIs](../apis/)) with the token `secret_totalapi`, so you need no SMTP settings:\n\n```\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `message.send2()` use it. The service gets the recipients, the sender, the subject, the body, the type, the priority, the unsubscribe link and the confidential flag; attachments and `msg.headers` are not sent. The callback of the message runs with the answer of the service. `$tapi` must stay `true` (the default).\n\n## Customizing\n\n`DEF.onMail` is the function behind the three globals. Replace it to change how messages are built, for example to add a header to every message:\n\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\nNew methods for all messages can be added with `F.extend('mail', name, fn)`; see [Prototypes](../prototypes/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwuS6Ex61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/mail/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"E-Mails senden","summary":"Sende E-Mails mit MAIL(), HTMLMAIL() und LOGMAIL(), konfiguriere SMTP, füge Anhänge hinzu und erstelle Nachrichten mit dem Modul Mail.","markdown":"---\ntitle: E-Mails senden\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/mail/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# E-Mails senden\n\n> Sende E-Mails mit MAIL(), HTMLMAIL() und LOGMAIL(), konfiguriere SMTP, füge Anhänge hinzu und erstelle Nachrichten mit dem Modul Mail.\n\nTotal.js 5 sendet E-Mails über SMTP mit einem eigenen Client, dem Modul `Mail`. Drei globale Funktionen decken die meisten Bedürfnisse ab: `MAIL()` rendert eine View als Body, `HTMLMAIL()` sendet HTML, das du bereits hast, und `LOGMAIL()` sendet einen schnellen Textbericht. Jede gibt ein **Nachrichten**-Objekt zurück, das du noch ändern kannst, bevor es hinausgeht.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' });\nHTMLMAIL('user@example.com', 'Your order', '<p>Thank you for your order.</p>');\nLOGMAIL('admin@example.com', 'Import finished', { count: 120 });\n```\n\nDie vollständige Liste der Funktionen, Methoden und Schlüssel steht in der Referenz [E-Mails senden](../../reference/mail/).\n\n## Konfiguration\n\nDer SMTP-Server wird in der Datei `config` mit dem Schlüssel `smtp` gesetzt (`mail` ist ein Alias). Der Wert ist ein Objekt; das Framework speichert es als `CONF.smtp`.\n\n```\nsmtp (json)     : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true ,\"user\":\"info@example.com\",\"password\":\"secret\"}\nmail_from       : info@example.com\nmail_from_name  : My application\n```\n\n| Option | Bedeutung |\n| --- | --- |\n| `server` | Der Hostname oder die IP-Adresse des SMTP-Servers (`host`, `hostname`, `smtp` und `url` werden gelesen, wenn `server` fehlt). Ein internationaler Name wird in Punycode umgewandelt und eine IPv4-Adresse in ihre Punktschreibweise |\n| `port` | Der Port. Mit `secure: true` ist der Standard `465`; andernfalls setze ihn (meist `25` oder `587`) |\n| `secure` | `true` öffnet von Anfang an eine TLS-Verbindung (implizites TLS) |\n| `user`, `password` | Die Anmeldung. Der Client verwendet `AUTH LOGIN` oder `AUTH PLAIN`, wenn der Server auch `XOAUTH` anbietet und kein `token` gesetzt ist |\n| `token` | Ein OAuth2-Access-Token, das mit `user` verwendet wird, wenn der Server `XOAUTH2` anbietet |\n| `tls` | Zusätzliche Node.js-TLS-Optionen für das Upgrade mit `STARTTLS` |\n| `timeout` | Das Verbindungs-Timeout in Millisekunden (Standard `60000`) |\n| `from`, `name` | Die Absenderadresse und der Name, wenn `mail_from` und `mail_from_name` nicht gesetzt sind |\n\nBei einer unverschlüsselten Verbindung (zum Beispiel Port `587`) wechselt der Client vor der Anmeldung mit `STARTTLS` zu TLS, wenn der Server TLS verlangt oder die Anmeldung erst danach anbietet. Um sicherzugehen, dass die Anmeldung immer verschlüsselt ist, verwende `secure: true` mit Port `465`.\n\nStatt eines Objekts kannst du Server und Optionen auch getrennt setzen:\n\n```\nmail_smtp          : smtp.example.com\nmail_smtp_options  : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nDie Schlüssel `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` und `mail_bcc` sind die Standardwerte, die `MAIL()`, `HTMLMAIL()` und `LOGMAIL()` in jede Nachricht einsetzen. `mail_reply`, `mail_cc` und `mail_bcc` enthalten je eine Adresse. Siehe [Konfiguration](../configuration/) für das Format der Datei.\n\n## MAIL() mit einer View\n\n`MAIL(email, subject, view, [model], [language], [callback])` rendert eine View aus `/views/` und sendet das Ergebnis. Das Modell ist in der View als `model` verfügbar, genau wie in [Views](../views/). Beginne eine Mail-View mit `@{layout('')}`: Ohne diese Zeile wird die View in `/views/layout.html` gerendert, und `MAIL()` schlägt fehl, wenn diese Datei nicht existiert.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' }, function(err) {\n\tif (err)\n\t\tconsole.log('Not sent:', err);\n});\n```\n\n```html\n<!-- views/mail/welcome.html -->\n@{layout('')}\n<h1>Hello @{model.name}</h1>\n<p>Your account is ready.</p>\n```\n\nMit `language` wird die View in dieser Sprache gerendert, und ein Betreff, der `@(...)` enthält, wird ebenfalls übersetzt. Siehe [Lokalisierung](../localization/).\n\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language);\n```\n\nDas Argument `email` ist eine Adresse, ein kommagetrennter String von Adressen oder ein Array. Jede Adresse wird zu einem Empfänger `To:`.\n\n## HTMLMAIL() und LOGMAIL()\n\n`HTMLMAIL(email, subject, body, [language], [callback])` sendet HTML aus einem String. Hat der Body kein Tag `<body>`, wird er in ein einfaches HTML-Dokument mit dem Betreff als Titel eingeschlossen.\n\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL(email, [subject], body, [callback])` ist für Berichte an dich selbst gedacht. Der Body wird als vorformatierter Text angezeigt: ein String so, wie er ist (er kann HTML enthalten), ein Objekt zu JSON serialisiert und HTML-kodiert. Ohne Betreff wird `CONF.name` verwendet.\n\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n## Die Nachricht vor dem Senden ändern\n\nAlle drei Funktionen geben die Nachricht zurück und senden sie einen Moment später (im nächsten Durchlauf der Event-Loop). Bis dahin kannst du Empfänger, Anhänge oder Header hinzufügen:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.cc('accounting@example.com');\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\nmsg.unsubscribe('https://example.com/unsubscribe/?id=123');\n```\n\n`message.manually()` stoppt das automatische Senden. Du sendest die Nachricht später selbst mit `message.send2()`:\n\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n\n// ... later\nmsg.send2(function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n\n## Anhänge\n\n`message.attachment(filename, name, [contentid])` hängt eine Datei von der Festplatte an. `name` ist der Dateiname, den der Empfänger sieht, und seine Endung bestimmt den Content-Type. Mit einer `contentid` ist die Datei ein Inline-Teil, auf den das HTML als `cid:<contentid>` verweist:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Newsletter', '<img src=\"cid:logo\" /><p>News of the month</p>');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nDas erste Argument kann auch ein `Buffer` sein, für eine Datei, die du im Speicher erzeugst. `message.attachmentfs(storage, id, [name], [contentid])` hängt eine Datei aus einem [Dateispeicher](../file-storage/) an; ohne `name` werden der Name und der Typ verwendet, die mit der Datei gespeichert sind:\n\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Your documents', '<p>The files are attached.</p>');\nmsg.attachment(Buffer.from('id;name\\n1;Peter\\n'), 'users.csv');\nmsg.attachmentfs('documents', id);\n```\n\n## Eine Nachricht selbst erstellen\n\n`Mail.create(subject, body)` gibt eine neue Nachricht zurück, die niemand für dich sendet. Setze den Absender und die Empfänger und sende sie dann mit dem konfigurierten Server (`message.send2()`) oder mit anderen SMTP-Optionen (`message.send(options)`).\n\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.reply('support@example.com');\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send2();\n```\n\nDer Body ist standardmäßig HTML. Setze `msg.type = 'plain'` für einen Body aus reinem Text. `msg.headers` ist ein Objekt mit zusätzlichen Headern.\n\n`msg.high()` und `msg.low()` setzen die Priorität der Nachricht (den Header `X-Priority: 1` oder `X-Priority: 5`), und `msg.confidential()` fügt `Sensitivity: Company-Confidential` hinzu. Die drei Methoden geben die Nachricht zurück, sodass du sie verketten kannst:\n\n```js\nHTMLMAIL('boss@example.com', 'Server is down', '<p>The server does not answer.</p>').high().confidential();\n```\n\n`Mail.send(options, messages, [callback])` sendet eine Nachricht oder ein Array von Nachrichten über eine einzige Verbindung. `Mail.try(options)` verbindet sich nur und meldet sich an, was nützlich ist, um SMTP-Einstellungen zu prüfen:\n\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n## Fehler und Events\n\nDer Callback von `MAIL()`, `HTMLMAIL()` und `LOGMAIL()` (derselbe wie `message.callback()`) wird als `callback(err, message)` aufgerufen. `err` ist leer, wenn die Nachricht an den Server übergeben wurde. Andernfalls beschreibt er das Problem:\n\n- der Server lehnt die Nachricht ab (zum Beispiel ein unbekannter Empfänger): die Antwortzeile des Servers,\n- `CONF.smtp` ist gesetzt, hat aber keinen Server: `No SMTP server configuration.` Ohne einen Schlüssel `smtp` ist `CONF.smtp` gleich `undefined`, und die Funktionen werfen einen `TypeError`,\n- der Server ist kein gültiger Hostname: `Invalid SMTP server hostname.`,\n- die Verbindung schlägt fehl oder läuft ab.\n\nEine abgelehnte Anmeldung liefert ebenfalls die Antwortzeile des Servers. Antwortzeilen sind in Großbuchstaben.\n\nEin Fehler, der einen Callback erreicht, wird nicht ins Fehlerprotokoll geschrieben; ohne Callback wird er mit `F.error()` protokolliert.\n\n`Mail` ist ein Event-Emitter, und das Framework löst für jede Nachricht ein globales Event aus:\n\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n`Mail.debug = true` gibt die ganze SMTP-Kommunikation in der Konsole aus.\n\n## Über die Total.js API senden\n\nMit `$tapimail : true` gehen die Nachrichten nicht an deinen SMTP-Server. Sie werden vom Total.js-API-Dienst (siehe [APIs](../apis/)) mit dem Token `secret_totalapi` gesendet, sodass du keine SMTP-Einstellungen brauchst:\n\n```\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` und `message.send2()` verwenden ihn. Der Dienst erhält die Empfänger, den Absender, den Betreff, den Body, den Typ, die Priorität, den Abmeldelink und das Vertraulichkeitsflag; Anhänge und `msg.headers` werden nicht gesendet. Der Callback der Nachricht läuft mit der Antwort des Dienstes. `$tapi` muss `true` bleiben (der Standard).\n\n## Anpassen\n\n`DEF.onMail` ist die Funktion hinter den drei globalen Funktionen. Ersetze sie, um zu ändern, wie Nachrichten erstellt werden, zum Beispiel um jeder Nachricht einen Header hinzuzufügen:\n\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\nNeue Methoden für alle Nachrichten können mit `F.extend('mail', name, fn)` hinzugefügt werden; siehe [Prototypen](../prototypes/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwuS6Ex61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/mail/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Enviar correo electrónico","summary":"Envía correos electrónicos con MAIL(), HTMLMAIL() y LOGMAIL(), configura SMTP, añade adjuntos y construye mensajes con el módulo Mail.","markdown":"---\ntitle: \"Enviar correo electrónico\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/mail/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Enviar correo electrónico\n\n> Envía correos electrónicos con MAIL(), HTMLMAIL() y LOGMAIL(), configura SMTP, añade adjuntos y construye mensajes con el módulo Mail.\n\nTotal.js 5 envía correos electrónicos por SMTP con su propio cliente, el módulo `Mail`. Tres funciones globales cubren la mayoría de las necesidades: `MAIL()` renderiza una vista como cuerpo, `HTMLMAIL()` envía HTML que ya tienes y `LOGMAIL()` envía un informe de texto rápido. Cada una devuelve un objeto **mensaje** que aún puedes cambiar antes de que salga.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' });\nHTMLMAIL('user@example.com', 'Your order', '<p>Thank you for your order.</p>');\nLOGMAIL('admin@example.com', 'Import finished', { count: 120 });\n```\n\nLa lista completa de funciones, métodos y claves está en la referencia de [Envío de correo](../../reference/mail/).\n\n## Configuración\n\nEl servidor SMTP se establece en el archivo `config` con la clave `smtp` (`mail` es un alias). El valor es un objeto; el framework lo guarda como `CONF.smtp`.\n\n```\nsmtp (json)     : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true ,\"user\":\"info@example.com\",\"password\":\"secret\"}\nmail_from       : info@example.com\nmail_from_name  : My application\n```\n\n| Opción | Significado |\n| --- | --- |\n| `server` | El nombre de host o la dirección IP del servidor SMTP (se leen `host`, `hostname`, `smtp` y `url` cuando falta `server`). Un nombre internacional se convierte a punycode y una dirección IPv4 a su forma con puntos |\n| `port` | El puerto. Con `secure: true` vale por defecto `465`; en otro caso establécelo (normalmente `25` o `587`) |\n| `secure` | `true` abre una conexión TLS desde el principio (TLS implícito) |\n| `user`, `password` | El inicio de sesión. El cliente usa `AUTH LOGIN`, o `AUTH PLAIN` cuando el servidor también ofrece `XOAUTH` y no se ha establecido `token` |\n| `token` | Un token de acceso OAuth2, usado con `user` cuando el servidor ofrece `XOAUTH2` |\n| `tls` | Opciones TLS adicionales de Node.js usadas para el upgrade `STARTTLS` |\n| `timeout` | El tiempo de espera de la conexión en milisegundos (por defecto `60000`) |\n| `from`, `name` | La dirección y el nombre del remitente usados cuando no están establecidos `mail_from` y `mail_from_name` |\n\nEn una conexión sin cifrar (por ejemplo el puerto `587`) el cliente pasa a TLS con `STARTTLS` antes de iniciar sesión cuando el servidor pide TLS u ofrece el inicio de sesión solo después. Para asegurarte de que el inicio de sesión siempre va cifrado, usa `secure: true` con el puerto `465`.\n\nEn lugar de un objeto también puedes establecer el servidor y las opciones por separado:\n\n```\nmail_smtp          : smtp.example.com\nmail_smtp_options  : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nLas claves `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` y `mail_bcc` son los valores por defecto que `MAIL()`, `HTMLMAIL()` y `LOGMAIL()` ponen en cada mensaje. `mail_reply`, `mail_cc` y `mail_bcc` contienen una dirección cada una. Consulta [Configuración](../configuration/) para el formato del archivo.\n\n## MAIL() con una vista\n\n`MAIL(email, subject, view, [model], [language], [callback])` renderiza una vista de `/views/` y envía el resultado. El modelo está disponible en la vista como `model`, exactamente como en [Vistas](../views/). Empieza la vista del correo con `@{layout('')}`: sin esa línea, la vista se renderiza dentro de `/views/layout.html` y `MAIL()` falla si ese archivo no existe.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' }, function(err) {\n\tif (err)\n\t\tconsole.log('Not sent:', err);\n});\n```\n\n```html\n<!-- views/mail/welcome.html -->\n@{layout('')}\n<h1>Hello @{model.name}</h1>\n<p>Your account is ready.</p>\n```\n\nCon `language`, la vista se renderiza en ese idioma y un asunto que contiene `@(...)` también se traduce. Consulta [Localización](../localization/).\n\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language);\n```\n\nEl argumento `email` es una dirección, un string de direcciones separadas por comas o un array. Cada dirección se convierte en un destinatario `To:`.\n\n## HTMLMAIL() y LOGMAIL()\n\n`HTMLMAIL(email, subject, body, [language], [callback])` envía HTML a partir de un string. Cuando el cuerpo no tiene etiqueta `<body>`, se envuelve en un documento HTML sencillo con el asunto como título.\n\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL(email, [subject], body, [callback])` está pensado para informes para ti mismo. El cuerpo se muestra como texto preformateado: un string tal cual (puede contener HTML), un objeto serializado a JSON y codificado en HTML. Sin asunto, se usa `CONF.name`.\n\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n## Cambiar el mensaje antes de enviarlo\n\nLas tres funciones devuelven el mensaje y lo envían un momento después (en el siguiente turno del event loop). Hasta entonces puedes añadir destinatarios, adjuntos o cabeceras:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.cc('accounting@example.com');\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\nmsg.unsubscribe('https://example.com/unsubscribe/?id=123');\n```\n\n`message.manually()` detiene el envío automático. Envías el mensaje tú mismo más tarde con `message.send2()`:\n\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n\n// ... later\nmsg.send2(function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n\n## Adjuntos\n\n`message.attachment(filename, name, [contentid])` adjunta un archivo del disco. `name` es el nombre de archivo que ve el destinatario, y su extensión establece el content type. Con un `contentid` el archivo es una parte en línea a la que el HTML se refiere como `cid:<contentid>`:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Newsletter', '<img src=\"cid:logo\" /><p>News of the month</p>');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nEl primer argumento también puede ser un `Buffer`, para un archivo que creas en memoria. `message.attachmentfs(storage, id, [name], [contentid])` adjunta un archivo de un [almacenamiento de archivos](../file-storage/); sin `name`, se usan el nombre y el tipo guardados con el archivo:\n\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Your documents', '<p>The files are attached.</p>');\nmsg.attachment(Buffer.from('id;name\\n1;Peter\\n'), 'users.csv');\nmsg.attachmentfs('documents', id);\n```\n\n## Construir un mensaje tú mismo\n\n`Mail.create(subject, body)` devuelve un nuevo mensaje que nadie envía por ti. Establece el remitente y los destinatarios, y luego envíalo con el servidor configurado (`message.send2()`) o con otras opciones SMTP (`message.send(options)`).\n\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.reply('support@example.com');\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send2();\n```\n\nEl cuerpo es HTML por defecto. Establece `msg.type = 'plain'` para un cuerpo de texto plano. `msg.headers` es un objeto de cabeceras adicionales.\n\n`msg.high()` y `msg.low()` establecen la prioridad del mensaje (la cabecera `X-Priority: 1` o `X-Priority: 5`), y `msg.confidential()` añade `Sensitivity: Company-Confidential`. Los tres métodos devuelven el mensaje, así que puedes encadenarlos:\n\n```js\nHTMLMAIL('boss@example.com', 'Server is down', '<p>The server does not answer.</p>').high().confidential();\n```\n\n`Mail.send(options, messages, [callback])` envía un mensaje o un array de mensajes por una sola conexión. `Mail.try(options)` solo se conecta e inicia sesión, lo que es útil para comprobar los ajustes SMTP:\n\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n## Errores y eventos\n\nEl callback de `MAIL()`, `HTMLMAIL()` y `LOGMAIL()` (lo mismo que `message.callback()`) se llama como `callback(err, message)`. `err` está vacío cuando el mensaje se ha entregado al servidor. En otro caso describe el problema:\n\n- el servidor rechaza el mensaje (por ejemplo un destinatario desconocido): la línea de respuesta del servidor,\n- `CONF.smtp` está establecido pero no tiene servidor: `No SMTP server configuration.` Sin una clave `smtp`, `CONF.smtp` es `undefined` y las funciones lanzan un `TypeError`,\n- el servidor no es un nombre de host válido: `Invalid SMTP server hostname.`,\n- la conexión falla o agota el tiempo de espera.\n\nUn inicio de sesión rechazado también devuelve la línea de respuesta del servidor. Las líneas de respuesta están en mayúsculas.\n\nUn error que llega a un callback no se escribe en el log de errores; sin callback, se registra con `F.error()`.\n\n`Mail` es un emisor de eventos, y el framework emite un evento global por cada mensaje:\n\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n`Mail.debug = true` imprime en la consola toda la conversación SMTP.\n\n## Enviar a través de la API de Total.js\n\nCon `$tapimail : true` los mensajes no van a tu servidor SMTP. Los envía el servicio Total.js API (consulta [APIs](../apis/)) con el token `secret_totalapi`, así que no necesitas ajustes SMTP:\n\n```\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` y `message.send2()` lo usan. El servicio recibe los destinatarios, el remitente, el asunto, el cuerpo, el tipo, la prioridad, el enlace para darse de baja y el indicador de confidencial; los adjuntos y `msg.headers` no se envían. El callback del mensaje se ejecuta con la respuesta del servicio. `$tapi` debe seguir en `true` (el valor por defecto).\n\n## Personalización\n\n`DEF.onMail` es la función detrás de los tres globales. Sustitúyela para cambiar cómo se construyen los mensajes, por ejemplo para añadir una cabecera a cada mensaje:\n\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\nSe pueden añadir nuevos métodos para todos los mensajes con `F.extend('mail', name, fn)`; consulta [Prototipos](../prototypes/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwuS6Ex61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/mail/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Envoyer des e-mails","summary":"Envoie des e-mails avec MAIL(), HTMLMAIL() et LOGMAIL(), configure SMTP, ajoute des pièces jointes et construis des messages avec le module Mail.","markdown":"---\ntitle: Envoyer des e-mails\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/mail/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Envoyer des e-mails\n\n> Envoie des e-mails avec MAIL(), HTMLMAIL() et LOGMAIL(), configure SMTP, ajoute des pièces jointes et construis des messages avec le module Mail.\n\nTotal.js 5 envoie des e-mails via SMTP avec son propre client, le module `Mail`. Trois fonctions globales couvrent la plupart des besoins : `MAIL()` effectue le rendu d'une vue comme corps, `HTMLMAIL()` envoie du HTML que tu as déjà, et `LOGMAIL()` envoie un rapport texte rapide. Chacune renvoie un objet **message** que tu peux encore modifier avant son départ.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' });\nHTMLMAIL('user@example.com', 'Your order', '<p>Thank you for your order.</p>');\nLOGMAIL('admin@example.com', 'Import finished', { count: 120 });\n```\n\nLa liste complète des fonctions, méthodes et clés se trouve dans la référence [Envoi d'e-mails](../../reference/mail/).\n\n## Configuration\n\nLe serveur SMTP est défini dans le fichier `config` avec la clé `smtp` (`mail` est un alias). La valeur est un objet ; le framework le stocke sous `CONF.smtp`.\n\n```\nsmtp (json)     : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true ,\"user\":\"info@example.com\",\"password\":\"secret\"}\nmail_from       : info@example.com\nmail_from_name  : My application\n```\n\n| Option | Signification |\n| --- | --- |\n| `server` | Le nom d'hôte ou l'adresse IP du serveur SMTP (`host`, `hostname`, `smtp` et `url` sont lus lorsque `server` est absent). Un nom international est converti en punycode et une adresse IPv4 dans sa forme à points |\n| `port` | Le port. Avec `secure: true`, il vaut par défaut `465` ; sinon, définis-le (généralement `25` ou `587`) |\n| `secure` | `true` ouvre une connexion TLS dès le départ (TLS implicite) |\n| `user`, `password` | Le login. Le client utilise `AUTH LOGIN`, ou `AUTH PLAIN` lorsque le serveur propose aussi `XOAUTH` et qu'aucun `token` n'est défini |\n| `token` | Un access token OAuth2, utilisé avec `user` lorsque le serveur propose `XOAUTH2` |\n| `tls` | Options TLS supplémentaires de Node.js utilisées pour l'upgrade `STARTTLS` |\n| `timeout` | Le délai de connexion en millisecondes (par défaut `60000`) |\n| `from`, `name` | L'adresse et le nom de l'expéditeur utilisés lorsque `mail_from` et `mail_from_name` ne sont pas définis |\n\nSur une connexion non chiffrée (par exemple le port `587`), le client passe en TLS avec `STARTTLS` avant de se connecter lorsque le serveur demande TLS ou ne propose le login qu'après celui-ci. Pour être sûr que le login est toujours chiffré, utilise `secure: true` avec le port `465`.\n\nAu lieu d'un seul objet, tu peux aussi définir séparément le serveur et les options :\n\n```\nmail_smtp          : smtp.example.com\nmail_smtp_options  : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nLes clés `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` et `mail_bcc` sont les valeurs par défaut que `MAIL()`, `HTMLMAIL()` et `LOGMAIL()` placent dans chaque message. `mail_reply`, `mail_cc` et `mail_bcc` contiennent chacune une adresse. Voir [Configuration](../configuration/) pour le format du fichier.\n\n## MAIL() avec une vue\n\n`MAIL(email, subject, view, [model], [language], [callback])` effectue le rendu d'une vue de `/views/` et envoie le résultat. Le modèle est disponible dans la vue sous `model`, exactement comme dans [Vues](../views/). Commence une vue d'e-mail par `@{layout('')}` : sans cette ligne, la vue est rendue dans `/views/layout.html` et `MAIL()` échoue si ce fichier n'existe pas.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' }, function(err) {\n\tif (err)\n\t\tconsole.log('Not sent:', err);\n});\n```\n\n```html\n<!-- views/mail/welcome.html -->\n@{layout('')}\n<h1>Hello @{model.name}</h1>\n<p>Your account is ready.</p>\n```\n\nAvec `language`, le rendu de la vue est effectué dans cette langue et un sujet contenant `@(...)` est également traduit. Voir [Localisation](../localization/).\n\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language);\n```\n\nL'argument `email` est une adresse, une chaîne d'adresses séparées par des virgules, ou un tableau. Chaque adresse devient un destinataire `To:`.\n\n## HTMLMAIL() et LOGMAIL()\n\n`HTMLMAIL(email, subject, body, [language], [callback])` envoie du HTML à partir d'une chaîne. Lorsque le corps n'a pas de balise `<body>`, il est enveloppé dans un document HTML simple avec le sujet comme titre.\n\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL(email, [subject], body, [callback])` est destinée aux rapports que tu t'envoies. Le corps est affiché sous forme de texte préformaté : une chaîne telle quelle (elle peut contenir du HTML), un objet sérialisé en JSON et encodé en HTML. Sans sujet, `CONF.name` est utilisé.\n\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n## Modifier le message avant son envoi\n\nLes trois fonctions renvoient le message et l'envoient un instant plus tard (au tour suivant de la boucle d'événements). D'ici là, tu peux ajouter des destinataires, des pièces jointes ou des en-têtes :\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.cc('accounting@example.com');\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\nmsg.unsubscribe('https://example.com/unsubscribe/?id=123');\n```\n\n`message.manually()` arrête l'envoi automatique. Tu envoies toi-même le message plus tard avec `message.send2()` :\n\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n\n// ... later\nmsg.send2(function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n\n## Pièces jointes\n\n`message.attachment(filename, name, [contentid])` joint un fichier du disque. `name` est le nom de fichier que voit le destinataire, et son extension définit le type de contenu. Avec un `contentid`, le fichier est une partie inline que le HTML référence sous la forme `cid:<contentid>` :\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Newsletter', '<img src=\"cid:logo\" /><p>News of the month</p>');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nLe premier argument peut aussi être un `Buffer`, pour un fichier que tu crées en mémoire. `message.attachmentfs(storage, id, [name], [contentid])` joint un fichier d'un [stockage de fichiers](../file-storage/) ; sans `name`, le nom et le type enregistrés avec le fichier sont utilisés :\n\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Your documents', '<p>The files are attached.</p>');\nmsg.attachment(Buffer.from('id;name\\n1;Peter\\n'), 'users.csv');\nmsg.attachmentfs('documents', id);\n```\n\n## Construire un message toi-même\n\n`Mail.create(subject, body)` renvoie un nouveau message que personne n'envoie à ta place. Définis l'expéditeur et les destinataires, puis envoie-le avec le serveur configuré (`message.send2()`) ou avec d'autres options SMTP (`message.send(options)`).\n\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.reply('support@example.com');\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send2();\n```\n\nLe corps est en HTML par défaut. Définis `msg.type = 'plain'` pour un corps en texte brut. `msg.headers` est un objet d'en-têtes supplémentaires.\n\n`msg.high()` et `msg.low()` définissent la priorité du message (l'en-tête `X-Priority: 1` ou `X-Priority: 5`), et `msg.confidential()` ajoute `Sensitivity: Company-Confidential`. Les trois méthodes renvoient le message, tu peux donc les enchaîner :\n\n```js\nHTMLMAIL('boss@example.com', 'Server is down', '<p>The server does not answer.</p>').high().confidential();\n```\n\n`Mail.send(options, messages, [callback])` envoie un message ou un tableau de messages sur une seule connexion. `Mail.try(options)` se contente de se connecter et de s'authentifier, ce qui est utile pour vérifier les paramètres SMTP :\n\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n## Erreurs et événements\n\nLe callback de `MAIL()`, `HTMLMAIL()` et `LOGMAIL()` (le même que `message.callback()`) est appelé sous la forme `callback(err, message)`. `err` est vide lorsque le message a été remis au serveur. Sinon, il décrit le problème :\n\n- le serveur refuse le message (par exemple un destinataire inconnu) : la ligne de réponse du serveur,\n- `CONF.smtp` est défini mais n'a pas de serveur : `No SMTP server configuration.` Sans clé `smtp`, `CONF.smtp` vaut `undefined` et les fonctions lèvent une `TypeError`,\n- le serveur n'est pas un nom d'hôte valide : `Invalid SMTP server hostname.`,\n- la connexion échoue ou expire.\n\nUn login refusé donne aussi la ligne de réponse du serveur. Les lignes de réponse sont en majuscules.\n\nUne erreur qui atteint un callback n'est pas écrite dans le journal des erreurs ; sans callback, elle est journalisée avec `F.error()`.\n\n`Mail` est un émetteur d'événements, et le framework émet un événement global pour chaque message :\n\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n`Mail.debug = true` affiche toute la conversation SMTP dans la console.\n\n## Envoyer via l'API Total.js\n\nAvec `$tapimail : true`, les messages ne passent pas par ton serveur SMTP. Ils sont envoyés par le service Total.js API (voir [APIs](../apis/)) avec le token `secret_totalapi`, tu n'as donc besoin d'aucun réglage SMTP :\n\n```\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` et `message.send2()` l'utilisent. Le service reçoit les destinataires, l'expéditeur, l'objet, le corps, le type, la priorité, le lien de désinscription et l'indicateur de confidentialité ; les pièces jointes et `msg.headers` ne sont pas envoyés. Le callback du message s'exécute avec la réponse du service. `$tapi` doit rester à `true` (la valeur par défaut).\n\n## Personnalisation\n\n`DEF.onMail` est la fonction derrière les trois fonctions globales. Remplace-la pour changer la façon dont les messages sont construits, par exemple pour ajouter un en-tête à chaque message :\n\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\nDe nouvelles méthodes pour tous les messages peuvent être ajoutées avec `F.extend('mail', name, fn)` ; voir [Prototypes](../prototypes/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwuS6Ex61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/mail/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Invio di email","summary":"Invia e-mail con MAIL(), HTMLMAIL() e LOGMAIL(), configura SMTP, aggiungi allegati e costruisci messaggi con il modulo Mail.","markdown":"---\ntitle: Invio di email\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/mail/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Invio di email\n\n> Invia e-mail con MAIL(), HTMLMAIL() e LOGMAIL(), configura SMTP, aggiungi allegati e costruisci messaggi con il modulo Mail.\n\nTotal.js 5 invia e-mail tramite SMTP con un proprio client, il modulo `Mail`. Tre funzioni globali coprono la maggior parte delle esigenze: `MAIL()` renderizza una vista come corpo, `HTMLMAIL()` invia HTML che hai già, e `LOGMAIL()` invia un rapido report testuale. Ognuna restituisce un oggetto **messaggio** che puoi ancora modificare prima che parta.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' });\nHTMLMAIL('user@example.com', 'Your order', '<p>Thank you for your order.</p>');\nLOGMAIL('admin@example.com', 'Import finished', { count: 120 });\n```\n\nL'elenco completo di funzioni, metodi e chiavi è nel riferimento di [Invio di e-mail](../../reference/mail/).\n\n## Configurazione\n\nIl server SMTP si imposta nel file `config` con la chiave `smtp` (`mail` è un alias). Il valore è un oggetto; il framework lo salva come `CONF.smtp`.\n\n```\nsmtp (json)     : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true ,\"user\":\"info@example.com\",\"password\":\"secret\"}\nmail_from       : info@example.com\nmail_from_name  : My application\n```\n\n| Opzione | Significato |\n| --- | --- |\n| `server` | Il nome host o l'indirizzo IP del server SMTP (`host`, `hostname`, `smtp` e `url` vengono letti quando `server` manca). Un nome internazionale viene convertito in punycode e un indirizzo IPv4 nella sua forma puntata |\n| `port` | La porta. Con `secure: true` il predefinito è `465`; altrimenti impostala (di solito `25` o `587`) |\n| `secure` | `true` apre una connessione TLS fin dall'inizio (TLS implicito) |\n| `user`, `password` | Il login. Il client usa `AUTH LOGIN`, oppure `AUTH PLAIN` quando il server offre anche `XOAUTH` e non è impostato nessun `token` |\n| `token` | Un access token OAuth2, usato con `user` quando il server offre `XOAUTH2` |\n| `tls` | Opzioni TLS aggiuntive di Node.js usate per l'upgrade `STARTTLS` |\n| `timeout` | Il timeout di connessione in millisecondi (predefinito `60000`) |\n| `from`, `name` | L'indirizzo e il nome del mittente usati quando `mail_from` e `mail_from_name` non sono impostati |\n\nSu una connessione in chiaro (per esempio la porta `587`) il client passa a TLS con `STARTTLS` prima del login quando il server richiede TLS o offre il login solo dopo. Per essere sicuro che il login sia sempre cifrato, usa `secure: true` con la porta `465`.\n\nInvece di un unico oggetto puoi anche impostare il server e le opzioni separatamente:\n\n```\nmail_smtp          : smtp.example.com\nmail_smtp_options  : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nLe chiavi `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` e `mail_bcc` sono i valori predefiniti che `MAIL()`, `HTMLMAIL()` e `LOGMAIL()` inseriscono in ogni messaggio. `mail_reply`, `mail_cc` e `mail_bcc` contengono un indirizzo ciascuna. Vedi [Configurazione](../configuration/) per il formato del file.\n\n## MAIL() con una vista\n\n`MAIL(email, subject, view, [model], [language], [callback])` renderizza una vista da `/views/` e invia il risultato. Il modello è disponibile nella vista come `model`, esattamente come in [Viste](../views/). Inizia la vista dell'e-mail con `@{layout('')}`: senza questa riga la vista viene renderizzata in `/views/layout.html` e `MAIL()` fallisce se quel file non esiste.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' }, function(err) {\n\tif (err)\n\t\tconsole.log('Not sent:', err);\n});\n```\n\n```html\n<!-- views/mail/welcome.html -->\n@{layout('')}\n<h1>Hello @{model.name}</h1>\n<p>Your account is ready.</p>\n```\n\nCon `language`, la vista viene renderizzata in quella lingua e anche un oggetto che contiene `@(...)` viene tradotto. Vedi [Localizzazione](../localization/).\n\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language);\n```\n\nL'argomento `email` è un indirizzo, una stringa di indirizzi separati da virgole o un array. Ogni indirizzo diventa un destinatario `To:`.\n\n## HTMLMAIL() e LOGMAIL()\n\n`HTMLMAIL(email, subject, body, [language], [callback])` invia HTML da una stringa. Quando il corpo non ha un tag `<body>`, viene racchiuso in un semplice documento HTML con l'oggetto come titolo.\n\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL(email, [subject], body, [callback])` è pensato per i report a te stesso. Il corpo viene mostrato come testo preformattato: una stringa così com'è (può contenere HTML), un oggetto serializzato in JSON e codificato in HTML. Senza oggetto, viene usato `CONF.name`.\n\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n## Modificare il messaggio prima dell'invio\n\nTutte e tre le funzioni restituiscono il messaggio e lo inviano un momento dopo (al giro successivo dell'event loop). Fino ad allora puoi aggiungere destinatari, allegati o header:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.cc('accounting@example.com');\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\nmsg.unsubscribe('https://example.com/unsubscribe/?id=123');\n```\n\n`message.manually()` blocca l'invio automatico. Invii tu il messaggio più tardi con `message.send2()`:\n\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n\n// ... later\nmsg.send2(function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n\n## Allegati\n\n`message.attachment(filename, name, [contentid])` allega un file dal disco. `name` è il nome del file che vede il destinatario, e la sua estensione imposta il content type. Con un `contentid` il file è una parte inline a cui l'HTML fa riferimento come `cid:<contentid>`:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Newsletter', '<img src=\"cid:logo\" /><p>News of the month</p>');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nIl primo argomento può anche essere un `Buffer`, per un file che crei in memoria. `message.attachmentfs(storage, id, [name], [contentid])` allega un file di un [file storage](../file-storage/); senza `name`, vengono usati il nome e il tipo salvati con il file:\n\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Your documents', '<p>The files are attached.</p>');\nmsg.attachment(Buffer.from('id;name\\n1;Peter\\n'), 'users.csv');\nmsg.attachmentfs('documents', id);\n```\n\n## Costruire un messaggio da solo\n\n`Mail.create(subject, body)` restituisce un nuovo messaggio che nessuno invia per te. Imposta il mittente e i destinatari, poi invialo con il server configurato (`message.send2()`) o con altre opzioni SMTP (`message.send(options)`).\n\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.reply('support@example.com');\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send2();\n```\n\nIl corpo è HTML per impostazione predefinita. Imposta `msg.type = 'plain'` per un corpo in testo semplice. `msg.headers` è un oggetto di header aggiuntivi.\n\n`msg.high()` e `msg.low()` impostano la priorità del messaggio (l'header `X-Priority: 1` o `X-Priority: 5`), e `msg.confidential()` aggiunge `Sensitivity: Company-Confidential`. I tre metodi restituiscono il messaggio, quindi puoi concatenarli:\n\n```js\nHTMLMAIL('boss@example.com', 'Server is down', '<p>The server does not answer.</p>').high().confidential();\n```\n\n`Mail.send(options, messages, [callback])` invia un messaggio o un array di messaggi su un'unica connessione. `Mail.try(options)` si limita a collegarsi ed effettuare il login, utile per verificare le impostazioni SMTP:\n\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n## Errori ed eventi\n\nLa callback di `MAIL()`, `HTMLMAIL()` e `LOGMAIL()` (la stessa di `message.callback()`) viene chiamata come `callback(err, message)`. `err` è vuoto quando il messaggio è stato consegnato al server. Altrimenti descrive il problema:\n\n- il server rifiuta il messaggio (per esempio un destinatario sconosciuto): la riga di risposta del server,\n- `CONF.smtp` è impostato ma non ha un server: `No SMTP server configuration.` Senza una chiave `smtp`, `CONF.smtp` è `undefined` e le funzioni lanciano un `TypeError`,\n- il server non è un nome host valido: `Invalid SMTP server hostname.`,\n- la connessione fallisce o va in timeout.\n\nAnche un login rifiutato restituisce la riga di risposta del server. Le righe di risposta sono in maiuscolo.\n\nUn errore che arriva a una callback non viene scritto nel log degli errori; senza callback, viene registrato con `F.error()`.\n\n`Mail` è un event emitter, e il framework emette un evento globale per ogni messaggio:\n\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n`Mail.debug = true` stampa nella console l'intera conversazione SMTP.\n\n## Invio tramite la Total.js API\n\nCon `$tapimail : true` i messaggi non vanno al tuo server SMTP. Li invia il servizio Total.js API (vedi [API](../apis/)) con il token `secret_totalapi`, quindi non ti servono impostazioni SMTP:\n\n```\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` e `message.send2()` lo usano. Il servizio riceve i destinatari, il mittente, l'oggetto, il corpo, il tipo, la priorità, il link di disiscrizione e il flag di riservatezza; gli allegati e `msg.headers` non vengono inviati. La callback del messaggio viene eseguita con la risposta del servizio. `$tapi` deve restare `true` (il valore predefinito).\n\n## Personalizzazione\n\n`DEF.onMail` è la funzione dietro le tre funzioni globali. Sostituiscila per cambiare il modo in cui vengono costruiti i messaggi, per esempio per aggiungere un header a ogni messaggio:\n\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\nSi possono aggiungere nuovi metodi per tutti i messaggi con `F.extend('mail', name, fn)`; vedi [Prototipi](../prototypes/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwuS6Ex61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/mail/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Odosielanie e-mailov","summary":"Posielaj e-maily cez MAIL(), HTMLMAIL() a LOGMAIL(), nastav SMTP, pridávaj prílohy a zostavuj správy pomocou modulu Mail.","markdown":"---\ntitle: Odosielanie e-mailov\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/mail/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Odosielanie e-mailov\n\n> Posielaj e-maily cez MAIL(), HTMLMAIL() a LOGMAIL(), nastav SMTP, pridávaj prílohy a zostavuj správy pomocou modulu Mail.\n\nTotal.js 5 posiela e-maily cez SMTP vlastným klientom, modulom `Mail`. Tri globálne funkcie pokrývajú väčšinu potrieb: `MAIL()` vykreslí pohľad ako telo, `HTMLMAIL()` pošle HTML, ktoré už máš, a `LOGMAIL()` pošle rýchly textový report. Každá vráti objekt **správy**, ktorý môžeš ešte zmeniť, kým odíde.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' });\nHTMLMAIL('user@example.com', 'Your order', '<p>Thank you for your order.</p>');\nLOGMAIL('admin@example.com', 'Import finished', { count: 120 });\n```\n\nÚplný zoznam funkcií, metód a kľúčov je v referencii [Posielanie e-mailov](../../reference/mail/).\n\n## Konfigurácia\n\nSMTP server sa nastavuje v súbore `config` kľúčom `smtp` (`mail` je alias). Hodnota je objekt; framework ho uloží ako `CONF.smtp`.\n\n```\nsmtp (json)     : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true ,\"user\":\"info@example.com\",\"password\":\"secret\"}\nmail_from       : info@example.com\nmail_from_name  : My application\n```\n\n| Voľba | Význam |\n| --- | --- |\n| `server` | Hostname alebo IP adresa SMTP servera (`host`, `hostname`, `smtp` a `url` sa čítajú, keď `server` chýba). Medzinárodný názov sa skonvertuje na punycode a IPv4 adresa na tvar s bodkami |\n| `port` | Port. S `secure: true` je predvolene `465`; inak ho nastav (zvyčajne `25` alebo `587`) |\n| `secure` | `true` otvorí TLS spojenie od začiatku (implicitné TLS) |\n| `user`, `password` | Prihlásenie. Klient používa `AUTH LOGIN`, alebo `AUTH PLAIN`, keď server ponúka aj `XOAUTH` a nie je nastavený `token` |\n| `token` | OAuth2 access token, používa sa s `user`, keď server ponúka `XOAUTH2` |\n| `tls` | Ďalšie TLS voľby Node.js použité pri upgrade cez `STARTTLS` |\n| `timeout` | Časový limit spojenia v milisekundách (predvolene `60000`) |\n| `from`, `name` | Adresa a meno odosielateľa, použité, keď nie sú nastavené `mail_from` a `mail_from_name` |\n\nNa nešifrovanom spojení (napríklad port `587`) klient pred prihlásením prejde na TLS cez `STARTTLS`, keď server žiada TLS alebo ponúka prihlásenie až potom. Ak chceš mať istotu, že prihlásenie je vždy šifrované, použi `secure: true` s portom `465`.\n\nNamiesto jedného objektu môžeš server a voľby nastaviť aj zvlášť:\n\n```\nmail_smtp          : smtp.example.com\nmail_smtp_options  : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nKľúče `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` a `mail_bcc` sú predvolené hodnoty, ktoré `MAIL()`, `HTMLMAIL()` a `LOGMAIL()` vložia do každej správy. `mail_reply`, `mail_cc` a `mail_bcc` obsahujú každý jednu adresu. Formát súboru nájdeš v [Konfigurácia](../configuration/).\n\n## MAIL() s pohľadom\n\n`MAIL(email, subject, view, [model], [language], [callback])` vykreslí pohľad z `/views/` a pošle výsledok. Model je v pohľade dostupný ako `model`, presne ako v [Pohľadoch](../views/). Pohľad e-mailu začni príkazom `@{layout('')}`: bez tohto riadku sa pohľad vykreslí do `/views/layout.html` a `MAIL()` zlyhá, ak tento súbor neexistuje.\n\n```js\nMAIL('user@example.com', 'Welcome', 'mail/welcome', { name: 'Peter' }, function(err) {\n\tif (err)\n\t\tconsole.log('Not sent:', err);\n});\n```\n\n```html\n<!-- views/mail/welcome.html -->\n@{layout('')}\n<h1>Hello @{model.name}</h1>\n<p>Your account is ready.</p>\n```\n\nS `language` sa pohľad vykreslí v tomto jazyku a predmet, ktorý obsahuje `@(...)`, sa tiež preloží. Pozri [Lokalizácia](../localization/).\n\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language);\n```\n\nArgument `email` je jedna adresa, reťazec adries oddelených čiarkami alebo pole. Každá adresa sa stane príjemcom `To:`.\n\n## HTMLMAIL() a LOGMAIL()\n\n`HTMLMAIL(email, subject, body, [language], [callback])` pošle HTML z reťazca. Keď telo nemá tag `<body>`, obalí sa do jednoduchého HTML dokumentu s predmetom ako titulkom.\n\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL(email, [subject], body, [callback])` je určený na reporty pre teba samého. Telo sa zobrazí ako predformátovaný text: reťazec tak, ako je (môže obsahovať HTML), objekt serializovaný do JSON a HTML-enkódovaný. Bez predmetu sa použije `CONF.name`.\n\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n## Zmena správy pred odoslaním\n\nVšetky tri funkcie vrátia správu a pošlú ju o chvíľu neskôr (v ďalšom kole event loopu). Dovtedy môžeš pridať príjemcov, prílohy alebo hlavičky:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.cc('accounting@example.com');\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\nmsg.unsubscribe('https://example.com/unsubscribe/?id=123');\n```\n\n`message.manually()` zastaví automatické odoslanie. Správu potom pošleš sám neskôr cez `message.send2()`:\n\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n\n// ... later\nmsg.send2(function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n\n## Prílohy\n\n`message.attachment(filename, name, [contentid])` pripojí súbor z disku. `name` je názov súboru, ktorý uvidí príjemca, a jeho prípona určí typ obsahu. S `contentid` je súbor inline časť, na ktorú sa HTML odkazuje ako `cid:<contentid>`:\n\n```js\nvar msg = HTMLMAIL('user@example.com', 'Newsletter', '<img src=\"cid:logo\" /><p>News of the month</p>');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nPrvý argument môže byť aj `Buffer`, pre súbor, ktorý vytvoríš v pamäti. `message.attachmentfs(storage, id, [name], [contentid])` pripojí súbor z [úložiska súborov](../file-storage/); bez `name` sa použije názov a typ uložený so súborom:\n\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Your documents', '<p>The files are attached.</p>');\nmsg.attachment(Buffer.from('id;name\\n1;Peter\\n'), 'users.csv');\nmsg.attachmentfs('documents', id);\n```\n\n## Vlastné zostavenie správy\n\n`Mail.create(subject, body)` vráti novú správu, ktorú za teba nikto nepošle. Nastav odosielateľa a príjemcov, potom ju pošli nakonfigurovaným serverom (`message.send2()`) alebo s inými SMTP voľbami (`message.send(options)`).\n\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.reply('support@example.com');\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send2();\n```\n\nTelo je predvolene HTML. Pre telo v čistom texte nastav `msg.type = 'plain'`. `msg.headers` je objekt ďalších hlavičiek.\n\n`msg.high()` a `msg.low()` nastavia prioritu správy (hlavičku `X-Priority: 1` alebo `X-Priority: 5`) a `msg.confidential()` pridá `Sensitivity: Company-Confidential`. Všetky tri metódy vracajú správu, takže ich môžeš reťaziť:\n\n```js\nHTMLMAIL('boss@example.com', 'Server is down', '<p>The server does not answer.</p>').high().confidential();\n```\n\n`Mail.send(options, messages, [callback])` pošle jednu správu alebo pole správ cez jedno spojenie. `Mail.try(options)` sa iba pripojí a prihlási, čo sa hodí na overenie SMTP nastavení:\n\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n## Chyby a udalosti\n\nCallback `MAIL()`, `HTMLMAIL()` a `LOGMAIL()` (to isté ako `message.callback()`) sa volá ako `callback(err, message)`. `err` je prázdne, keď bola správa odovzdaná serveru. Inak opisuje problém:\n\n- server odmietne správu (napríklad neznámy príjemca): riadok odpovede servera,\n- `CONF.smtp` je nastavené, ale nemá server: `No SMTP server configuration.` Bez kľúča `smtp` je `CONF.smtp` `undefined` a funkcie vyhodia `TypeError`,\n- server nie je platný hostname: `Invalid SMTP server hostname.`,\n- spojenie zlyhá alebo vyprší jeho časový limit.\n\nOdmietnuté prihlásenie tiež vráti riadok odpovede servera. Riadky odpovede sú veľkými písmenami.\n\nChyba, ktorá sa dostane do callbacku, sa nezapíše do chybového logu; bez callbacku sa zaznamená cez `F.error()`.\n\n`Mail` je event emitter a framework pre každú správu vyvolá globálnu udalosť:\n\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n`Mail.debug = true` vypíše celú SMTP komunikáciu do konzoly.\n\n## Odosielanie cez Total.js API\n\nS `$tapimail : true` správy nejdú na tvoj SMTP server. Odošle ich služba Total.js API (pozri [API](../apis/)) s tokenom `secret_totalapi`, takže nepotrebuješ žiadne SMTP nastavenia:\n\n```\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n\nPoužívajú ju `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` a `message.send2()`. Služba dostane príjemcov, odosielateľa, predmet, telo, typ, prioritu, odkaz na odhlásenie a príznak dôvernosti; prílohy a `msg.headers` sa neodosielajú. Callback správy sa spustí s odpoveďou služby. `$tapi` musí zostať `true` (predvolené).\n\n## Prispôsobenie\n\n`DEF.onMail` je funkcia, ktorá stojí za tromi globálnymi funkciami. Nahraď ju, ak chceš zmeniť, ako sa správy zostavujú, napríklad pridať hlavičku do každej správy:\n\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\nNové metódy pre všetky správy sa dajú pridať cez `F.extend('mail', name, fn)`; pozri [Prototypy](../prototypes/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"Jafww6Bax61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Scheduling and events","summary":"Crons, global events, the events of the framework, debounced timers, pausing the server and the service timer.","markdown":"---\ntitle: Scheduling and events\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/scheduling-and-events/\nupdated: 2026-11-16T16:36:26.082Z\n---\n\n# Scheduling and events\n\n> Crons, global events, the events of the framework, debounced timers, pausing the server and the service timer.\n\nA Total.js 5 application has one internal timer, the **service timer**, that runs every 5 seconds from the moment the application is loaded. Once a minute it does the housekeeping of the framework, runs the crons registered with `CRON()` and emits the `service` event. The framework also emits global events (`ready`, `exit`, `request`…) that you catch with `ON()`, and you can emit your own events with `EMIT()`.\n\n```js\n// /modules/tasks.js\nexports.install = function() {\n\n\tON('ready', function() {\n\t\tconsole.log('The application is loaded');\n\t});\n\n\tCRON('0 3 * * *', function(date) {\n\t\t// every day at 03:00\n\t\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n\t});\n\n};\n```\n\n## Crons\n\n`CRON(line, fn)` registers a function that runs when the current date matches the cron line. The line has five fields separated by spaces, in this order:\n\n| Field | Values |\n| --- | --- |\n| minute | `0`–`59` |\n| hour | `0`–`23` |\n| day of the month | `1`–`31` |\n| month | `1`–`12` |\n| day of the week | `0`–`6` (`0` is Sunday) or a name: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` |\n\nEach field accepts:\n\n- `*`: any value,\n- a number: `30`,\n- a list: `0,15,30,45`,\n- a range: `8-17` (both ends included),\n- a step: `*/15` is every 15th value from the first value of the field (`0` for minutes and hours, `1` for days and months), `5/20` every 20th value from `5`.\n\nNames of days can be written in full (`monday`): only the first two letters are read.\n\n```js\nCRON('30 8 * * mo-fr', function(date) {\n\t// at 08:30 from Monday to Friday\n});\n\nCRON('0,30 * * * *', function() {\n\t// every half hour\n});\n\nCRON('0 0 1 * *', function() {\n\t// at midnight on the first day of every month\n});\n\nCRON('5/20 8-17 * * mo-fr', function() {\n\t// at minutes 5, 25 and 45 from 08:00 to 17:59 on working days\n});\n```\n\nThe crons are checked once a minute by the service timer, with the date in `NOW`, and `fn` gets that date as its argument. The minutes are counted from the start of the application, not from the start of a wall-clock minute, so a cron runs within the minute it matches, not at its first second. Hours and days follow the time zone of the process, which is `$timezone` from the configuration (default `utc`).\n\n`CRON()` returns an object; call its `remove()` method to stop the cron. All registered crons are in the array `F.crons`.\n\n```js\nvar cron = CRON('* * * * *', function() {\n\tconsole.log('Every minute');\n});\n\n// later\ncron.remove();\n```\n\n## Events\n\n`ON(name, fn)` adds a listener, `ONCE(name, fn)` adds a listener that is removed after its first call, `OFF(name, [fn])` removes one listener or all listeners of the event, and `EMIT(name, [a], [b], ...)` calls the listeners with up to seven arguments. They are global forms of `F.on()`, `F.once()`, `F.off()` and `F.emit()`; inside a listener `this` is `F`.\n\n```js\nON('order.created', function(order) {\n\tMAIL(order.email, 'Thank you', 'mail/order', order);\n});\n\n// anywhere\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\nOne listener can catch several events: join their names with `+`.\n\n```js\nON('ready + service', function() {\n\t// once at the start, then once a minute\n});\n```\n\nA listener of `ready` added after the application is loaded runs at once, so `ON('ready')` is safe in code that loads late (plugins, code run from a cron).\n\n`OFF(name, fn)` needs the same function that was passed to `ON()`; `OFF(name)` removes every listener of `name`, including the ones of the framework, so use it only for your own events.\n\n## Built-in events\n\n| Event | Arguments | When |\n| --- | --- | --- |\n| `ready` | | The application is loaded (all modules, actions, controllers…) |\n| `load` | | Right after `ready` |\n| `service` | `counter` | Once a minute; `counter` is the number of minutes since the start |\n| `exit` | `signal` | The process is stopping |\n| `error` | `obj` | The framework logged an error |\n| `request` | `ctrl` | An HTTP request arrived, before routing |\n| `controller` | `ctrl` | A route was found, before its action runs |\n| `componentator` | `meta` | `COMPONENTATOR()` is about to download components |\n| `flowstream_error` | `meta` | A component of a FlowStream failed |\n| `flowstream` | `instance` | A FlowStream instance was created |\n| `$mail` | `message` | An e-mail is being sent |\n| `$stats` | `stats` | The usage statistics of the process were updated |\n| `$message` | `msg`, `handle` | The process received a message from its parent |\n| `$update` | | Another process of the cluster sent `total:update` |\n\nOther pages describe the events of their area: `$reconfigure` in [Configuration](../../guides/configuration/), `$view` in [Views](../../guides/views/), `websocket_end` in [WebSockets](../../guides/websockets/), and the `@{action}` events in [Actions](../../guides/actions/). `$cors` and `$tms` are used inside the framework.\n\nThe `request` and `controller` events can stop the request: call `ctrl.cancel()` and answer it yourself.\n\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n## Debounced timers\n\n`setTimeout2(id, callback, timeout)` is a `setTimeout()` with a name. When it is called again with the same `id` before the time passes, the previous timer is canceled and a new one starts with the new callback. The callback runs only after `timeout` milliseconds without a new call, which is a debounce. `clearTimeout2(id)` cancels the timer and returns `true` when one was waiting.\n\n```js\nfunction save(doc) {\n\t// many changes in a short time make one write\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nThe fourth argument `limit` stops endless postponing: after `limit` postponements, the next call runs its callback at once and the counting starts again.\n\n```js\nsetTimeout2('search', function() {\n\tsearch(text);\n}, 300, 10);\n```\n\n## Waiting for a stream\n\n`CLEANUP(stream, [callback])` calls `callback` once, when the stream ends, finishes, closes, is aborted or fails, and destroys the stream at that moment. Without a callback it returns a promise.\n\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.write('id;name\\n');\nwriter.end();\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\n## Pausing the server\n\n`PAUSESERVER(name, [enable])` holds all incoming traffic while something is not ready, for example a migration. While at least one name is paused, HTTP requests get the status `503`: browsers see a \"Please wait\" page that lists the paused names and reloads itself after 10 seconds, XHR requests get an error response, and new WebSocket connections are closed. Static files are paused too.\n\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\nWithout `enable` the call toggles the name and returns `true` when it is now paused. The paused names are in the array `F.paused`.\n\n## The service timer\n\nEvery 5 seconds the timer updates `NOW` and cancels HTTP requests that ran out of time. Once a minute it:\n\n- removes expired items of the cache and the bans that expired,\n- every 5 minutes clears `TEMP`,\n- every `$clearcache` minutes (default `10`) clears the internal caches of actions, views, paths, images and templates,\n- every `$tmsclearblocked` minutes (default `60`) clears the list of blocked TMS clients,\n- updates the usage statistics and emits `$stats`,\n- runs the crons and emits `service`.\n\n`$clearcache` and `$tmsclearblocked` are keys of the `config` file; see [Configuration](../../guides/configuration/). For work that repeats in fixed steps, a cron with `*` in a field, or the `service` event with the `counter`, is enough:\n\n```js\nON('service', function(counter) {\n\tif (counter % 5 === 0) {\n\t\t// every 5 minutes\n\t\trefresh();\n\t}\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:26.082Z"}
{"id":"Jafww6Bax61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Zeitplanung und Events","summary":"Crons, globale Events, die Events des Frameworks, entprellte Timer, das Pausieren des Servers und der Service-Timer.","markdown":"---\ntitle: Zeitplanung und Events\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/scheduling-and-events/\nupdated: 2026-11-16T16:36:26.082Z\n---\n\n# Zeitplanung und Events\n\n> Crons, globale Events, die Events des Frameworks, entprellte Timer, das Pausieren des Servers und der Service-Timer.\n\nEine Total.js 5 Anwendung hat einen internen Timer, den **Service-Timer**, der ab dem Laden der Anwendung alle 5 Sekunden läuft. Einmal pro Minute erledigt er die Wartungsarbeiten des Frameworks, führt die mit `CRON()` registrierten Crons aus und löst das Event `service` aus. Das Framework löst außerdem globale Events aus (`ready`, `exit`, `request`…), die du mit `ON()` abfängst, und mit `EMIT()` kannst du eigene Events auslösen.\n\n```js\n// /modules/tasks.js\nexports.install = function() {\n\n\tON('ready', function() {\n\t\tconsole.log('The application is loaded');\n\t});\n\n\tCRON('0 3 * * *', function(date) {\n\t\t// every day at 03:00\n\t\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n\t});\n\n};\n```\n\n## Crons\n\n`CRON(line, fn)` registriert eine Funktion, die läuft, wenn das aktuelle Datum zur Cron-Zeile passt. Die Zeile hat fünf durch Leerzeichen getrennte Felder in dieser Reihenfolge:\n\n| Feld | Werte |\n| --- | --- |\n| Minute | `0`–`59` |\n| Stunde | `0`–`23` |\n| Tag des Monats | `1`–`31` |\n| Monat | `1`–`12` |\n| Wochentag | `0`–`6` (`0` ist Sonntag) oder ein Name: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` |\n\nJedes Feld akzeptiert:\n\n- `*`: jeden Wert,\n- eine Zahl: `30`,\n- eine Liste: `0,15,30,45`,\n- ein Bereich: `8-17` (beide Enden eingeschlossen),\n- eine Schrittweite: `*/15` ist jeder 15. Wert ab dem ersten Wert des Feldes (`0` für Minuten und Stunden, `1` für Tage und Monate), `5/20` jeder 20. Wert ab `5`.\n\nNamen von Tagen kannst du ausschreiben (`monday`): Es werden nur die ersten zwei Buchstaben gelesen.\n\n```js\nCRON('30 8 * * mo-fr', function(date) {\n\t// at 08:30 from Monday to Friday\n});\n\nCRON('0,30 * * * *', function() {\n\t// every half hour\n});\n\nCRON('0 0 1 * *', function() {\n\t// at midnight on the first day of every month\n});\n\nCRON('5/20 8-17 * * mo-fr', function() {\n\t// at minutes 5, 25 and 45 from 08:00 to 17:59 on working days\n});\n```\n\nDie Crons werden einmal pro Minute vom Service-Timer mit dem Datum in `NOW` geprüft, und `fn` bekommt dieses Datum als Argument. Die Minuten werden ab dem Start der Anwendung gezählt, nicht ab dem Beginn einer Minute der Uhrzeit, daher läuft ein Cron innerhalb der passenden Minute, nicht in ihrer ersten Sekunde. Stunden und Tage folgen der Zeitzone des Prozesses, also `$timezone` aus der Konfiguration (Standard `utc`).\n\n`CRON()` gibt ein Objekt zurück; rufe seine Methode `remove()` auf, um den Cron zu stoppen. Alle registrierten Crons stehen im Array `F.crons`.\n\n```js\nvar cron = CRON('* * * * *', function() {\n\tconsole.log('Every minute');\n});\n\n// later\ncron.remove();\n```\n\n## Events\n\n`ON(name, fn)` fügt einen Listener hinzu, `ONCE(name, fn)` fügt einen Listener hinzu, der nach seinem ersten Aufruf entfernt wird, `OFF(name, [fn])` entfernt einen oder alle Listener des Events, und `EMIT(name, [a], [b], ...)` ruft die Listener mit bis zu sieben Argumenten auf. Sie sind globale Formen von `F.on()`, `F.once()`, `F.off()` und `F.emit()`; innerhalb eines Listeners ist `this` gleich `F`.\n\n```js\nON('order.created', function(order) {\n\tMAIL(order.email, 'Thank you', 'mail/order', order);\n});\n\n// anywhere\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\nEin Listener kann mehrere Events abfangen: Verbinde ihre Namen mit `+`.\n\n```js\nON('ready + service', function() {\n\t// once at the start, then once a minute\n});\n```\n\nEin Listener von `ready`, der nach dem Laden der Anwendung hinzugefügt wird, läuft sofort, daher ist `ON('ready')` in spät geladenem Code (Plugins, aus einem Cron ausgeführter Code) sicher.\n\n`OFF(name, fn)` braucht dieselbe Funktion, die an `ON()` übergeben wurde; `OFF(name)` entfernt jeden Listener von `name`, auch die des Frameworks, verwende es daher nur für deine eigenen Events.\n\n## Eingebaute Events\n\n| Event | Argumente | Wann |\n| --- | --- | --- |\n| `ready` | | Die Anwendung ist geladen (alle Module, Aktionen, Controller…) |\n| `load` | | Direkt nach `ready` |\n| `service` | `counter` | Einmal pro Minute; `counter` ist die Anzahl der Minuten seit dem Start |\n| `exit` | `signal` | Der Prozess wird beendet |\n| `error` | `obj` | Das Framework hat einen Fehler protokolliert |\n| `request` | `ctrl` | Eine HTTP-Anfrage ist eingetroffen, vor dem Routing |\n| `controller` | `ctrl` | Eine Route wurde gefunden, bevor ihre Aktion läuft |\n| `componentator` | `meta` | `COMPONENTATOR()` lädt gleich Komponenten herunter |\n| `flowstream_error` | `meta` | Eine Komponente eines FlowStream ist fehlgeschlagen |\n| `flowstream` | `instance` | Eine FlowStream-Instanz wurde erstellt |\n| `$mail` | `message` | Eine E-Mail wird gesendet |\n| `$stats` | `stats` | Die Nutzungsstatistiken des Prozesses wurden aktualisiert |\n| `$message` | `msg`, `handle` | Der Prozess hat eine Nachricht von seinem Elternprozess erhalten |\n| `$update` | | Ein anderer Prozess des Clusters hat `total:update` gesendet |\n\nAndere Seiten beschreiben die Events ihres Bereichs: `$reconfigure` in [Konfiguration](../../guides/configuration/), `$view` in [Views](../../guides/views/), `websocket_end` in [WebSockets](../../guides/websockets/) und die `@{action}`-Events in [Aktionen](../../guides/actions/). `$cors` und `$tms` werden innerhalb des Frameworks verwendet.\n\nDie Events `request` und `controller` können die Anfrage stoppen: Rufe `ctrl.cancel()` auf und beantworte sie selbst.\n\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n## Entprellte Timer\n\n`setTimeout2(id, callback, timeout)` ist ein `setTimeout()` mit einem Namen. Wird es mit derselben `id` erneut aufgerufen, bevor die Zeit abgelaufen ist, wird der vorherige Timer abgebrochen und ein neuer mit dem neuen Callback gestartet. Der Callback läuft erst nach `timeout` Millisekunden ohne neuen Aufruf, also ein Debounce. `clearTimeout2(id)` bricht den Timer ab und gibt `true` zurück, wenn einer gewartet hat.\n\n```js\nfunction save(doc) {\n\t// many changes in a short time make one write\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nDas vierte Argument `limit` verhindert endloses Aufschieben: Nach `limit` Verschiebungen führt der nächste Aufruf seinen Callback sofort aus, und die Zählung beginnt von vorn.\n\n```js\nsetTimeout2('search', function() {\n\tsearch(text);\n}, 300, 10);\n```\n\n## Auf einen Stream warten\n\n`CLEANUP(stream, [callback])` ruft `callback` einmal auf, wenn der Stream endet, fertig ist, geschlossen, abgebrochen wird oder fehlschlägt, und zerstört den Stream in diesem Moment. Ohne Callback gibt es eine Promise zurück.\n\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.write('id;name\\n');\nwriter.end();\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\n## Den Server pausieren\n\n`PAUSESERVER(name, [enable])` hält den gesamten eingehenden Verkehr an, solange etwas nicht bereit ist, zum Beispiel eine Migration. Solange mindestens ein Name pausiert ist, bekommen HTTP-Anfragen den Status `503`: Browser sehen eine Seite „Please wait“, die die pausierten Namen auflistet und sich nach 10 Sekunden neu lädt, XHR-Anfragen bekommen eine Fehlerantwort, und neue WebSocket-Verbindungen werden geschlossen. Auch statische Dateien werden pausiert.\n\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\nOhne `enable` schaltet der Aufruf den Namen um und gibt `true` zurück, wenn er jetzt pausiert ist. Die pausierten Namen stehen im Array `F.paused`.\n\n## Der Service-Timer\n\nAlle 5 Sekunden aktualisiert der Timer `NOW` und bricht HTTP-Anfragen ab, deren Zeit abgelaufen ist. Einmal pro Minute:\n\n- entfernt er abgelaufene Einträge des Caches und abgelaufene Sperren,\n- leert er alle 5 Minuten `TEMP`,\n- leert er alle `$clearcache` Minuten (Standard `10`) die internen Caches von Aktionen, Views, Pfaden, Bildern und Templates,\n- leert er alle `$tmsclearblocked` Minuten (Standard `60`) die Liste der blockierten TMS-Clients,\n- aktualisiert er die Nutzungsstatistiken und löst `$stats` aus,\n- führt er die Crons aus und löst `service` aus.\n\n`$clearcache` und `$tmsclearblocked` sind Schlüssel der Datei `config`; siehe [Konfiguration](../../guides/configuration/). Für Arbeit, die sich in festen Abständen wiederholt, genügt ein Cron mit `*` in einem Feld oder das Event `service` mit dem `counter`:\n\n```js\nON('service', function(counter) {\n\tif (counter % 5 === 0) {\n\t\t// every 5 minutes\n\t\trefresh();\n\t}\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:26.082Z"}
{"id":"Jafww6Bax61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Programación y eventos","summary":"Crons, eventos globales, los eventos del framework, temporizadores con debounce, pausar el servidor y el temporizador de servicio.","markdown":"---\ntitle: \"Programación y eventos\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/scheduling-and-events/\nupdated: 2026-11-16T16:36:26.082Z\n---\n\n# Programación y eventos\n\n> Crons, eventos globales, los eventos del framework, temporizadores con debounce, pausar el servidor y el temporizador de servicio.\n\nUna aplicación Total.js 5 tiene un temporizador interno, el **temporizador de servicio**, que se ejecuta cada 5 segundos desde que se carga la aplicación. Una vez por minuto hace las tareas de mantenimiento del framework, ejecuta los crons registrados con `CRON()` y emite el evento `service`. El framework también emite eventos globales (`ready`, `exit`, `request`…) que capturas con `ON()`, y puedes emitir tus propios eventos con `EMIT()`.\n\n```js\n// /modules/tasks.js\nexports.install = function() {\n\n\tON('ready', function() {\n\t\tconsole.log('The application is loaded');\n\t});\n\n\tCRON('0 3 * * *', function(date) {\n\t\t// every day at 03:00\n\t\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n\t});\n\n};\n```\n\n## Crons\n\n`CRON(line, fn)` registra una función que se ejecuta cuando la fecha actual coincide con la línea cron. La línea tiene cinco campos separados por espacios, en este orden:\n\n| Campo | Valores |\n| --- | --- |\n| minuto | `0`–`59` |\n| hora | `0`–`23` |\n| día del mes | `1`–`31` |\n| mes | `1`–`12` |\n| día de la semana | `0`–`6` (`0` es domingo) o un nombre: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` |\n\nCada campo acepta:\n\n- `*`: cualquier valor,\n- un número: `30`,\n- una lista: `0,15,30,45`,\n- un rango: `8-17` (ambos extremos incluidos),\n- un paso: `*/15` es cada 15.º valor desde el primer valor del campo (`0` para minutos y horas, `1` para días y meses), `5/20` cada 20.º valor desde `5`.\n\nLos nombres de los días se pueden escribir completos (`monday`): solo se leen las dos primeras letras.\n\n```js\nCRON('30 8 * * mo-fr', function(date) {\n\t// at 08:30 from Monday to Friday\n});\n\nCRON('0,30 * * * *', function() {\n\t// every half hour\n});\n\nCRON('0 0 1 * *', function() {\n\t// at midnight on the first day of every month\n});\n\nCRON('5/20 8-17 * * mo-fr', function() {\n\t// at minutes 5, 25 and 45 from 08:00 to 17:59 on working days\n});\n```\n\nEl temporizador de servicio comprueba los crons una vez por minuto, con la fecha de `NOW`, y `fn` recibe esa fecha como argumento. Los minutos se cuentan desde el inicio de la aplicación, no desde el inicio de un minuto del reloj, así que un cron se ejecuta dentro del minuto que coincide, no en su primer segundo. Las horas y los días siguen la zona horaria del proceso, que es `$timezone` de la configuración (por defecto `utc`).\n\n`CRON()` devuelve un objeto; llama a su método `remove()` para detener el cron. Todos los crons registrados están en el array `F.crons`.\n\n```js\nvar cron = CRON('* * * * *', function() {\n\tconsole.log('Every minute');\n});\n\n// later\ncron.remove();\n```\n\n## Eventos\n\n`ON(name, fn)` añade un listener, `ONCE(name, fn)` añade un listener que se elimina tras su primera llamada, `OFF(name, [fn])` elimina un listener o todos los listeners del evento, y `EMIT(name, [a], [b], ...)` llama a los listeners con hasta siete argumentos. Son las formas globales de `F.on()`, `F.once()`, `F.off()` y `F.emit()`; dentro de un listener `this` es `F`.\n\n```js\nON('order.created', function(order) {\n\tMAIL(order.email, 'Thank you', 'mail/order', order);\n});\n\n// anywhere\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\nUn listener puede capturar varios eventos: une sus nombres con `+`.\n\n```js\nON('ready + service', function() {\n\t// once at the start, then once a minute\n});\n```\n\nUn listener de `ready` añadido después de cargar la aplicación se ejecuta de inmediato, así que `ON('ready')` es seguro en código que se carga tarde (plugins, código ejecutado desde un cron).\n\n`OFF(name, fn)` necesita la misma función que se pasó a `ON()`; `OFF(name)` elimina todos los listeners de `name`, incluidos los del framework, así que úsalo solo para tus propios eventos.\n\n## Eventos integrados\n\n| Evento | Argumentos | Cuándo |\n| --- | --- | --- |\n| `ready` | | La aplicación está cargada (todos los módulos, acciones, controladores…) |\n| `load` | | Justo después de `ready` |\n| `service` | `counter` | Una vez por minuto; `counter` es el número de minutos desde el inicio |\n| `exit` | `signal` | El proceso se está deteniendo |\n| `error` | `obj` | El framework registró un error |\n| `request` | `ctrl` | Llegó una petición HTTP, antes del enrutamiento |\n| `controller` | `ctrl` | Se encontró una ruta, antes de que se ejecute su acción |\n| `componentator` | `meta` | `COMPONENTATOR()` está a punto de descargar componentes |\n| `flowstream_error` | `meta` | Falló un componente de un FlowStream |\n| `flowstream` | `instance` | Se creó una instancia de FlowStream |\n| `$mail` | `message` | Se está enviando un e-mail |\n| `$stats` | `stats` | Se actualizaron las estadísticas de uso del proceso |\n| `$message` | `msg`, `handle` | El proceso recibió un mensaje de su padre |\n| `$update` | | Otro proceso del clúster envió `total:update` |\n\nOtras páginas describen los eventos de su área: `$reconfigure` en [Configuración](../../guides/configuration/), `$view` en [Vistas](../../guides/views/), `websocket_end` en [WebSockets](../../guides/websockets/) y los eventos `@{action}` en [Acciones](../../guides/actions/). `$cors` y `$tms` se usan dentro del framework.\n\nLos eventos `request` y `controller` pueden detener la petición: llama a `ctrl.cancel()` y respóndela tú mismo.\n\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n## Temporizadores con debounce\n\n`setTimeout2(id, callback, timeout)` es un `setTimeout()` con nombre. Cuando se vuelve a llamar con el mismo `id` antes de que pase el tiempo, el temporizador anterior se cancela y empieza uno nuevo con el nuevo callback. El callback se ejecuta solo tras `timeout` milisegundos sin una nueva llamada, es decir, un debounce. `clearTimeout2(id)` cancela el temporizador y devuelve `true` cuando había uno esperando.\n\n```js\nfunction save(doc) {\n\t// many changes in a short time make one write\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nEl cuarto argumento `limit` evita que se aplace sin fin: tras `limit` aplazamientos, la siguiente llamada ejecuta su callback de inmediato y el conteo empieza de nuevo.\n\n```js\nsetTimeout2('search', function() {\n\tsearch(text);\n}, 300, 10);\n```\n\n## Esperar a un stream\n\n`CLEANUP(stream, [callback])` llama a `callback` una vez, cuando el stream termina, finaliza, se cierra, se aborta o falla, y destruye el stream en ese momento. Sin callback devuelve una promesa.\n\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.write('id;name\\n');\nwriter.end();\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\n## Pausar el servidor\n\n`PAUSESERVER(name, [enable])` retiene todo el tráfico entrante mientras algo no está listo, por ejemplo una migración. Mientras haya al menos un nombre en pausa, las peticiones HTTP reciben el estado `503`: los navegadores ven una página \"Please wait\" que lista los nombres en pausa y se recarga sola tras 10 segundos, las peticiones XHR reciben una respuesta de error y las nuevas conexiones WebSocket se cierran. Los archivos estáticos también quedan en pausa.\n\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\nSin `enable` la llamada alterna el nombre y devuelve `true` cuando ahora está en pausa. Los nombres en pausa están en el array `F.paused`.\n\n## El temporizador de servicio\n\nCada 5 segundos el temporizador actualiza `NOW` y cancela las peticiones HTTP que agotaron su tiempo. Una vez por minuto:\n\n- elimina los elementos caducados de la caché y los bloqueos que caducaron,\n- cada 5 minutos limpia `TEMP`,\n- cada `$clearcache` minutos (por defecto `10`) limpia las cachés internas de acciones, vistas, rutas de archivos, imágenes y plantillas,\n- cada `$tmsclearblocked` minutos (por defecto `60`) limpia la lista de clientes TMS bloqueados,\n- actualiza las estadísticas de uso y emite `$stats`,\n- ejecuta los crons y emite `service`.\n\n`$clearcache` y `$tmsclearblocked` son claves del archivo `config`; consulta [Configuración](../../guides/configuration/). Para trabajo que se repite en pasos fijos basta con un cron con `*` en un campo, o el evento `service` con el `counter`:\n\n```js\nON('service', function(counter) {\n\tif (counter % 5 === 0) {\n\t\t// every 5 minutes\n\t\trefresh();\n\t}\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:26.082Z"}
{"id":"Jafww6Bax61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Planification et événements","summary":"Crons, événements globaux, événements du framework, timers avec debounce, mise en pause du serveur et timer de service.","markdown":"---\ntitle: \"Planification et événements\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/scheduling-and-events/\nupdated: 2026-11-16T16:36:26.082Z\n---\n\n# Planification et événements\n\n> Crons, événements globaux, événements du framework, timers avec debounce, mise en pause du serveur et timer de service.\n\nUne application Total.js 5 possède un timer interne, le **timer de service**, qui s'exécute toutes les 5 secondes dès le chargement de l'application. Une fois par minute, il effectue la maintenance du framework, exécute les crons enregistrés avec `CRON()` et émet l'événement `service`. Le framework émet aussi des événements globaux (`ready`, `exit`, `request`…) que tu interceptes avec `ON()`, et tu peux émettre tes propres événements avec `EMIT()`.\n\n```js\n// /modules/tasks.js\nexports.install = function() {\n\n\tON('ready', function() {\n\t\tconsole.log('The application is loaded');\n\t});\n\n\tCRON('0 3 * * *', function(date) {\n\t\t// every day at 03:00\n\t\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n\t});\n\n};\n```\n\n## Crons\n\n`CRON(line, fn)` enregistre une fonction qui s'exécute lorsque la date courante correspond à la ligne cron. La ligne comporte cinq champs séparés par des espaces, dans cet ordre :\n\n| Champ | Valeurs |\n| --- | --- |\n| minute | `0`–`59` |\n| heure | `0`–`23` |\n| jour du mois | `1`–`31` |\n| mois | `1`–`12` |\n| jour de la semaine | `0`–`6` (`0` est le dimanche) ou un nom : `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` |\n\nChaque champ accepte :\n\n- `*` : n'importe quelle valeur,\n- un nombre : `30`,\n- une liste : `0,15,30,45`,\n- un intervalle : `8-17` (bornes incluses),\n- un pas : `*/15` correspond à une valeur sur 15 à partir de la première valeur du champ (`0` pour les minutes et les heures, `1` pour les jours et les mois), `5/20` à une valeur sur 20 à partir de `5`.\n\nLes noms des jours peuvent être écrits en entier (`monday`) : seules les deux premières lettres sont lues.\n\n```js\nCRON('30 8 * * mo-fr', function(date) {\n\t// at 08:30 from Monday to Friday\n});\n\nCRON('0,30 * * * *', function() {\n\t// every half hour\n});\n\nCRON('0 0 1 * *', function() {\n\t// at midnight on the first day of every month\n});\n\nCRON('5/20 8-17 * * mo-fr', function() {\n\t// at minutes 5, 25 and 45 from 08:00 to 17:59 on working days\n});\n```\n\nLes crons sont vérifiés une fois par minute par le timer de service, avec la date de `NOW`, et `fn` reçoit cette date en argument. Les minutes sont comptées depuis le démarrage de l'application, et non depuis le début d'une minute de l'horloge : un cron s'exécute donc au cours de la minute à laquelle il correspond, pas à sa première seconde. Les heures et les jours suivent le fuseau horaire du processus, c'est-à-dire `$timezone` de la configuration (par défaut `utc`).\n\n`CRON()` renvoie un objet ; appelle sa méthode `remove()` pour arrêter le cron. Tous les crons enregistrés se trouvent dans le tableau `F.crons`.\n\n```js\nvar cron = CRON('* * * * *', function() {\n\tconsole.log('Every minute');\n});\n\n// later\ncron.remove();\n```\n\n## Événements\n\n`ON(name, fn)` ajoute un écouteur, `ONCE(name, fn)` ajoute un écouteur supprimé après son premier appel, `OFF(name, [fn])` supprime un écouteur ou tous les écouteurs de l'événement, et `EMIT(name, [a], [b], ...)` appelle les écouteurs avec jusqu'à sept arguments. Ce sont les formes globales de `F.on()`, `F.once()`, `F.off()` et `F.emit()` ; dans un écouteur, `this` vaut `F`.\n\n```js\nON('order.created', function(order) {\n\tMAIL(order.email, 'Thank you', 'mail/order', order);\n});\n\n// anywhere\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\nUn écouteur peut intercepter plusieurs événements : joins leurs noms avec `+`.\n\n```js\nON('ready + service', function() {\n\t// once at the start, then once a minute\n});\n```\n\nUn écouteur de `ready` ajouté après le chargement de l'application s'exécute immédiatement : `ON('ready')` est donc sûr dans du code chargé tardivement (plugins, code exécuté depuis un cron).\n\n`OFF(name, fn)` nécessite la même fonction que celle passée à `ON()` ; `OFF(name)` supprime tous les écouteurs de `name`, y compris ceux du framework, utilise-le donc uniquement pour tes propres événements.\n\n## Événements intégrés\n\n| Événement | Arguments | Quand |\n| --- | --- | --- |\n| `ready` | | L'application est chargée (tous les modules, actions, contrôleurs…) |\n| `load` | | Juste après `ready` |\n| `service` | `counter` | Une fois par minute ; `counter` est le nombre de minutes depuis le démarrage |\n| `exit` | `signal` | Le processus s'arrête |\n| `error` | `obj` | Le framework a journalisé une erreur |\n| `request` | `ctrl` | Une requête HTTP est arrivée, avant le routage |\n| `controller` | `ctrl` | Une route a été trouvée, avant l'exécution de son action |\n| `componentator` | `meta` | `COMPONENTATOR()` est sur le point de télécharger des composants |\n| `flowstream_error` | `meta` | Un composant d'un FlowStream a échoué |\n| `flowstream` | `instance` | Une instance FlowStream a été créée |\n| `$mail` | `message` | Un e-mail est en cours d'envoi |\n| `$stats` | `stats` | Les statistiques d'utilisation du processus ont été mises à jour |\n| `$message` | `msg`, `handle` | Le processus a reçu un message de son parent |\n| `$update` | | Un autre processus du cluster a envoyé `total:update` |\n\nD'autres pages décrivent les événements de leur domaine : `$reconfigure` dans [Configuration](../../guides/configuration/), `$view` dans [Vues](../../guides/views/), `websocket_end` dans [WebSockets](../../guides/websockets/), et les événements `@{action}` dans [Actions](../../guides/actions/). `$cors` et `$tms` sont utilisés en interne par le framework.\n\nLes événements `request` et `controller` peuvent arrêter la requête : appelle `ctrl.cancel()` et réponds-y toi-même.\n\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n## Timers avec debounce\n\n`setTimeout2(id, callback, timeout)` est un `setTimeout()` avec un nom. Lorsqu'il est rappelé avec le même `id` avant l'expiration du délai, le timer précédent est annulé et un nouveau démarre avec le nouveau callback. Le callback ne s'exécute qu'après `timeout` millisecondes sans nouvel appel : c'est un debounce. `clearTimeout2(id)` annule le timer et renvoie `true` lorsqu'un timer était en attente.\n\n```js\nfunction save(doc) {\n\t// many changes in a short time make one write\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nLe quatrième argument `limit` arrête les reports sans fin : après `limit` reports, l'appel suivant exécute son callback immédiatement et le comptage recommence.\n\n```js\nsetTimeout2('search', function() {\n\tsearch(text);\n}, 300, 10);\n```\n\n## Attendre un stream\n\n`CLEANUP(stream, [callback])` appelle `callback` une seule fois, lorsque le stream se termine, s'achève, se ferme, est interrompu ou échoue, et détruit le stream à ce moment-là. Sans callback, la fonction renvoie une promesse.\n\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.write('id;name\\n');\nwriter.end();\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\n## Mettre le serveur en pause\n\n`PAUSESERVER(name, [enable])` retient tout le trafic entrant tant que quelque chose n'est pas prêt, par exemple une migration. Tant qu'au moins un nom est en pause, les requêtes HTTP reçoivent le statut `503` : les navigateurs voient une page « Please wait » qui liste les noms en pause et se recharge après 10 secondes, les requêtes XHR reçoivent une réponse d'erreur, et les nouvelles connexions WebSocket sont fermées. Les fichiers statiques sont aussi mis en pause.\n\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\nSans `enable`, l'appel bascule l'état du nom et renvoie `true` lorsqu'il est désormais en pause. Les noms en pause se trouvent dans le tableau `F.paused`.\n\n## Le timer de service\n\nToutes les 5 secondes, le timer met à jour `NOW` et annule les requêtes HTTP dont le délai a expiré. Une fois par minute, il :\n\n- supprime les éléments expirés du cache et les bannissements expirés,\n- toutes les 5 minutes, vide `TEMP`,\n- toutes les `$clearcache` minutes (par défaut `10`), vide les caches internes des actions, des vues, des chemins, des images et des templates,\n- toutes les `$tmsclearblocked` minutes (par défaut `60`), vide la liste des clients TMS bloqués,\n- met à jour les statistiques d'utilisation et émet `$stats`,\n- exécute les crons et émet `service`.\n\n`$clearcache` et `$tmsclearblocked` sont des clés du fichier `config` ; voir [Configuration](../../guides/configuration/). Pour un travail qui se répète à intervalles fixes, un cron avec `*` dans un champ, ou l'événement `service` avec le `counter`, suffit :\n\n```js\nON('service', function(counter) {\n\tif (counter % 5 === 0) {\n\t\t// every 5 minutes\n\t\trefresh();\n\t}\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:26.082Z"}
{"id":"Jafww6Bax61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Pianificazione ed eventi","summary":"Cron, eventi globali, gli eventi del framework, timer con debounce, la sospensione del server e il timer di servizio.","markdown":"---\ntitle: Pianificazione ed eventi\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/scheduling-and-events/\nupdated: 2026-11-16T16:36:26.082Z\n---\n\n# Pianificazione ed eventi\n\n> Cron, eventi globali, gli eventi del framework, timer con debounce, la sospensione del server e il timer di servizio.\n\nUn'applicazione Total.js 5 ha un solo timer interno, il **timer di servizio**, che gira ogni 5 secondi dal momento in cui l'applicazione viene caricata. Una volta al minuto esegue la manutenzione del framework, esegue i cron registrati con `CRON()` ed emette l'evento `service`. Il framework emette anche eventi globali (`ready`, `exit`, `request`…) che intercetti con `ON()`, e puoi emettere i tuoi eventi con `EMIT()`.\n\n```js\n// /modules/tasks.js\nexports.install = function() {\n\n\tON('ready', function() {\n\t\tconsole.log('The application is loaded');\n\t});\n\n\tCRON('0 3 * * *', function(date) {\n\t\t// every day at 03:00\n\t\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n\t});\n\n};\n```\n\n## Cron\n\n`CRON(line, fn)` registra una funzione che viene eseguita quando la data corrente corrisponde alla riga cron. La riga ha cinque campi separati da spazi, in quest'ordine:\n\n| Campo | Valori |\n| --- | --- |\n| minuto | `0`–`59` |\n| ora | `0`–`23` |\n| giorno del mese | `1`–`31` |\n| mese | `1`–`12` |\n| giorno della settimana | `0`–`6` (`0` è domenica) o un nome: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` |\n\nOgni campo accetta:\n\n- `*`: qualsiasi valore,\n- un numero: `30`,\n- un elenco: `0,15,30,45`,\n- un intervallo: `8-17` (estremi inclusi),\n- un passo: `*/15` è ogni 15° valore a partire dal primo valore del campo (`0` per minuti e ore, `1` per giorni e mesi), `5/20` ogni 20° valore a partire da `5`.\n\nI nomi dei giorni si possono scrivere per intero (`monday`): vengono lette solo le prime due lettere.\n\n```js\nCRON('30 8 * * mo-fr', function(date) {\n\t// at 08:30 from Monday to Friday\n});\n\nCRON('0,30 * * * *', function() {\n\t// every half hour\n});\n\nCRON('0 0 1 * *', function() {\n\t// at midnight on the first day of every month\n});\n\nCRON('5/20 8-17 * * mo-fr', function() {\n\t// at minutes 5, 25 and 45 from 08:00 to 17:59 on working days\n});\n```\n\nI cron vengono controllati una volta al minuto dal timer di servizio, con la data in `NOW`, e `fn` riceve quella data come argomento. I minuti si contano dall'avvio dell'applicazione, non dall'inizio di un minuto dell'orologio, quindi un cron viene eseguito entro il minuto che corrisponde, non al suo primo secondo. Ore e giorni seguono il fuso orario del processo, cioè `$timezone` dalla configurazione (predefinito `utc`).\n\n`CRON()` restituisce un oggetto; chiama il suo metodo `remove()` per fermare il cron. Tutti i cron registrati sono nell'array `F.crons`.\n\n```js\nvar cron = CRON('* * * * *', function() {\n\tconsole.log('Every minute');\n});\n\n// later\ncron.remove();\n```\n\n## Eventi\n\n`ON(name, fn)` aggiunge un listener, `ONCE(name, fn)` aggiunge un listener che viene rimosso dopo la prima chiamata, `OFF(name, [fn])` rimuove un listener o tutti i listener dell'evento, ed `EMIT(name, [a], [b], ...)` chiama i listener con un massimo di sette argomenti. Sono le forme globali di `F.on()`, `F.once()`, `F.off()` e `F.emit()`; dentro un listener `this` è `F`.\n\n```js\nON('order.created', function(order) {\n\tMAIL(order.email, 'Thank you', 'mail/order', order);\n});\n\n// anywhere\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\nUn listener può intercettare più eventi: unisci i loro nomi con `+`.\n\n```js\nON('ready + service', function() {\n\t// once at the start, then once a minute\n});\n```\n\nUn listener di `ready` aggiunto dopo il caricamento dell'applicazione viene eseguito subito, quindi `ON('ready')` è sicuro nel codice che si carica tardi (plugin, codice eseguito da un cron).\n\n`OFF(name, fn)` richiede la stessa funzione passata a `ON()`; `OFF(name)` rimuove tutti i listener di `name`, compresi quelli del framework, quindi usalo solo per i tuoi eventi.\n\n## Eventi integrati\n\n| Evento | Argomenti | Quando |\n| --- | --- | --- |\n| `ready` | | L'applicazione è caricata (tutti i moduli, le azioni, i controller…) |\n| `load` | | Subito dopo `ready` |\n| `service` | `counter` | Una volta al minuto; `counter` è il numero di minuti dall'avvio |\n| `exit` | `signal` | Il processo si sta fermando |\n| `error` | `obj` | Il framework ha registrato un errore |\n| `request` | `ctrl` | È arrivata una richiesta HTTP, prima del routing |\n| `controller` | `ctrl` | È stata trovata una route, prima che venga eseguita la sua azione |\n| `componentator` | `meta` | `COMPONENTATOR()` sta per scaricare i componenti |\n| `flowstream_error` | `meta` | Un componente di un FlowStream è fallito |\n| `flowstream` | `instance` | È stata creata un'istanza di FlowStream |\n| `$mail` | `message` | Si sta inviando un'e-mail |\n| `$stats` | `stats` | Le statistiche di utilizzo del processo sono state aggiornate |\n| `$message` | `msg`, `handle` | Il processo ha ricevuto un messaggio dal processo padre |\n| `$update` | | Un altro processo del cluster ha inviato `total:update` |\n\nAltre pagine descrivono gli eventi della loro area: `$reconfigure` in [Configurazione](../../guides/configuration/), `$view` in [Viste](../../guides/views/), `websocket_end` in [WebSocket](../../guides/websockets/) e gli eventi `@{action}` in [Azioni](../../guides/actions/). `$cors` e `$tms` sono usati all'interno del framework.\n\nGli eventi `request` e `controller` possono fermare la richiesta: chiama `ctrl.cancel()` e rispondi tu stesso.\n\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n## Timer con debounce\n\n`setTimeout2(id, callback, timeout)` è un `setTimeout()` con un nome. Quando viene chiamato di nuovo con lo stesso `id` prima che il tempo scada, il timer precedente viene annullato e ne parte uno nuovo con la nuova callback. La callback viene eseguita solo dopo `timeout` millisecondi senza una nuova chiamata: è un debounce. `clearTimeout2(id)` annulla il timer e restituisce `true` quando ce n'era uno in attesa.\n\n```js\nfunction save(doc) {\n\t// many changes in a short time make one write\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nIl quarto argomento `limit` ferma il rinvio infinito: dopo `limit` rinvii, la chiamata successiva esegue subito la sua callback e il conteggio ricomincia.\n\n```js\nsetTimeout2('search', function() {\n\tsearch(text);\n}, 300, 10);\n```\n\n## Attendere uno stream\n\n`CLEANUP(stream, [callback])` chiama `callback` una volta, quando lo stream termina, finisce, si chiude, viene interrotto o fallisce, e in quel momento distrugge lo stream. Senza callback restituisce una promise.\n\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.write('id;name\\n');\nwriter.end();\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\n## Mettere in pausa il server\n\n`PAUSESERVER(name, [enable])` blocca tutto il traffico in ingresso mentre qualcosa non è pronto, per esempio una migrazione. Finché almeno un nome è in pausa, le richieste HTTP ricevono lo stato `503`: i browser vedono una pagina \"Please wait\" che elenca i nomi in pausa e si ricarica da sola dopo 10 secondi, le richieste XHR ricevono una risposta di errore e le nuove connessioni WebSocket vengono chiuse. Anche i file statici vengono messi in pausa.\n\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\nSenza `enable` la chiamata alterna lo stato del nome e restituisce `true` quando ora è in pausa. I nomi in pausa sono nell'array `F.paused`.\n\n## Il timer di servizio\n\nOgni 5 secondi il timer aggiorna `NOW` e annulla le richieste HTTP che hanno esaurito il tempo. Una volta al minuto:\n\n- rimuove gli elementi scaduti della cache e i ban scaduti,\n- ogni 5 minuti svuota `TEMP`,\n- ogni `$clearcache` minuti (predefinito `10`) svuota le cache interne di azioni, viste, percorsi, immagini e template,\n- ogni `$tmsclearblocked` minuti (predefinito `60`) svuota l'elenco dei client TMS bloccati,\n- aggiorna le statistiche di utilizzo ed emette `$stats`,\n- esegue i cron ed emette `service`.\n\n`$clearcache` e `$tmsclearblocked` sono chiavi del file `config`; vedi [Configurazione](../../guides/configuration/). Per un lavoro che si ripete a intervalli fissi basta un cron con `*` in un campo, oppure l'evento `service` con il `counter`:\n\n```js\nON('service', function(counter) {\n\tif (counter % 5 === 0) {\n\t\t// every 5 minutes\n\t\trefresh();\n\t}\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:26.082Z"}
{"id":"Jafww6Bax61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Plánovanie a udalosti","summary":"Crony, globálne udalosti, udalosti frameworku, debounce časovače, pozastavenie servera a servisný časovač.","markdown":"---\ntitle: \"Plánovanie a udalosti\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/scheduling-and-events/\nupdated: 2026-11-16T16:36:26.082Z\n---\n\n# Plánovanie a udalosti\n\n> Crony, globálne udalosti, udalosti frameworku, debounce časovače, pozastavenie servera a servisný časovač.\n\nAplikácia v Total.js 5 má jeden interný časovač, **servisný časovač**, ktorý beží každých 5 sekúnd od chvíle, keď sa aplikácia načíta. Raz za minútu vykoná údržbu frameworku, spustí crony registrované cez `CRON()` a vyvolá udalosť `service`. Framework vyvoláva aj globálne udalosti (`ready`, `exit`, `request`…), ktoré zachytíš cez `ON()`, a vlastné udalosti môžeš vyvolať cez `EMIT()`.\n\n```js\n// /modules/tasks.js\nexports.install = function() {\n\n\tON('ready', function() {\n\t\tconsole.log('The application is loaded');\n\t});\n\n\tCRON('0 3 * * *', function(date) {\n\t\t// every day at 03:00\n\t\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n\t});\n\n};\n```\n\n## Crony\n\n`CRON(line, fn)` registruje funkciu, ktorá sa spustí, keď aktuálny dátum zodpovedá riadku cronu. Riadok má päť polí oddelených medzerami, v tomto poradí:\n\n| Pole | Hodnoty |\n| --- | --- |\n| minúta | `0`–`59` |\n| hodina | `0`–`23` |\n| deň v mesiaci | `1`–`31` |\n| mesiac | `1`–`12` |\n| deň v týždni | `0`–`6` (`0` je nedeľa) alebo názov: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` |\n\nKaždé pole prijíma:\n\n- `*`: ľubovoľná hodnota,\n- číslo: `30`,\n- zoznam: `0,15,30,45`,\n- rozsah: `8-17` (vrátane oboch koncov),\n- krok: `*/15` je každá 15. hodnota od prvej hodnoty poľa (`0` pre minúty a hodiny, `1` pre dni a mesiace), `5/20` každá 20. hodnota od `5`.\n\nNázvy dní môžeš písať celé (`monday`): čítajú sa iba prvé dve písmená.\n\n```js\nCRON('30 8 * * mo-fr', function(date) {\n\t// at 08:30 from Monday to Friday\n});\n\nCRON('0,30 * * * *', function() {\n\t// every half hour\n});\n\nCRON('0 0 1 * *', function() {\n\t// at midnight on the first day of every month\n});\n\nCRON('5/20 8-17 * * mo-fr', function() {\n\t// at minutes 5, 25 and 45 from 08:00 to 17:59 on working days\n});\n```\n\nCrony kontroluje servisný časovač raz za minútu s dátumom v `NOW` a `fn` dostane tento dátum ako argument. Minúty sa počítajú od štartu aplikácie, nie od začiatku minúty na hodinách, takže cron sa spustí v rámci minúty, ktorej zodpovedá, nie v jej prvej sekunde. Hodiny a dni sa riadia časovou zónou procesu, čo je `$timezone` z konfigurácie (predvolene `utc`).\n\n`CRON()` vracia objekt; zavolaj jeho metódu `remove()` a cron sa zastaví. Všetky registrované crony sú v poli `F.crons`.\n\n```js\nvar cron = CRON('* * * * *', function() {\n\tconsole.log('Every minute');\n});\n\n// later\ncron.remove();\n```\n\n## Udalosti\n\n`ON(name, fn)` pridá poslucháča, `ONCE(name, fn)` pridá poslucháča, ktorý sa po prvom volaní odstráni, `OFF(name, [fn])` odstráni jedného poslucháča alebo všetkých poslucháčov udalosti a `EMIT(name, [a], [b], ...)` zavolá poslucháčov s najviac siedmimi argumentmi. Sú to globálne podoby `F.on()`, `F.once()`, `F.off()` a `F.emit()`; vnútri poslucháča je `this` rovné `F`.\n\n```js\nON('order.created', function(order) {\n\tMAIL(order.email, 'Thank you', 'mail/order', order);\n});\n\n// anywhere\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\nJeden poslucháč môže zachytiť viac udalostí: spoj ich názvy znakom `+`.\n\n```js\nON('ready + service', function() {\n\t// once at the start, then once a minute\n});\n```\n\nPoslucháč udalosti `ready` pridaný po načítaní aplikácie sa spustí okamžite, takže `ON('ready')` je bezpečné aj v kóde, ktorý sa načíta neskôr (pluginy, kód spustený z cronu).\n\n`OFF(name, fn)` potrebuje tú istú funkciu, ktorá bola odovzdaná do `ON()`; `OFF(name)` odstráni všetkých poslucháčov `name` vrátane poslucháčov frameworku, preto ho používaj iba pre vlastné udalosti.\n\n## Vstavané udalosti\n\n| Udalosť | Argumenty | Kedy |\n| --- | --- | --- |\n| `ready` | | Aplikácia je načítaná (všetky moduly, akcie, kontroléry…) |\n| `load` | | Hneď po `ready` |\n| `service` | `counter` | Raz za minútu; `counter` je počet minút od štartu |\n| `exit` | `signal` | Proces sa zastavuje |\n| `error` | `obj` | Framework zaznamenal chybu |\n| `request` | `ctrl` | Prišla HTTP požiadavka, pred smerovaním |\n| `controller` | `ctrl` | Našla sa trasa, pred spustením jej akcie |\n| `componentator` | `meta` | `COMPONENTATOR()` sa chystá stiahnuť komponenty |\n| `flowstream_error` | `meta` | Komponent FlowStreamu zlyhal |\n| `flowstream` | `instance` | Vytvorila sa inštancia FlowStreamu |\n| `$mail` | `message` | Odosiela sa e-mail |\n| `$stats` | `stats` | Aktualizovali sa štatistiky využitia procesu |\n| `$message` | `msg`, `handle` | Proces dostal správu od svojho rodiča |\n| `$update` | | Iný proces klastra poslal `total:update` |\n\nĎalšie stránky opisujú udalosti svojej oblasti: `$reconfigure` v [Konfigurácii](../../guides/configuration/), `$view` v [Pohľadoch](../../guides/views/), `websocket_end` vo [WebSocketoch](../../guides/websockets/) a udalosti `@{action}` v [Akciách](../../guides/actions/). `$cors` a `$tms` sa používajú vnútri frameworku.\n\nUdalosti `request` a `controller` môžu požiadavku zastaviť: zavolaj `ctrl.cancel()` a odpovedz na ňu sám.\n\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n## Debounce časovače\n\n`setTimeout2(id, callback, timeout)` je `setTimeout()` s názvom. Keď sa znova zavolá s tým istým `id` skôr, ako čas uplynie, predchádzajúci časovač sa zruší a začne nový s novým callbackom. Callback sa spustí až po `timeout` milisekundách bez nového volania, čo je debounce. `clearTimeout2(id)` zruší časovač a vráti `true`, keď nejaký čakal.\n\n```js\nfunction save(doc) {\n\t// many changes in a short time make one write\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nŠtvrtý argument `limit` zastaví nekonečné odkladanie: po `limit` odloženiach spustí ďalšie volanie svoj callback hneď a počítanie začne odznova.\n\n```js\nsetTimeout2('search', function() {\n\tsearch(text);\n}, 300, 10);\n```\n\n## Čakanie na stream\n\n`CLEANUP(stream, [callback])` zavolá `callback` raz, keď stream skončí, dokončí sa, zatvorí sa, preruší sa alebo zlyhá, a v tej chvíli stream zničí. Bez callbacku vracia promise.\n\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.write('id;name\\n');\nwriter.end();\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\n## Pozastavenie servera\n\n`PAUSESERVER(name, [enable])` zadrží všetku prichádzajúcu prevádzku, kým niečo nie je pripravené, napríklad migrácia. Kým je pozastavený aspoň jeden názov, HTTP požiadavky dostanú stav `503`: prehliadače uvidia stránku „Please wait“, ktorá vypíše pozastavené názvy a po 10 sekundách sa sama obnoví, XHR požiadavky dostanú chybovú odpoveď a nové WebSocket spojenia sa zatvoria. Pozastavené sú aj statické súbory.\n\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\nBez `enable` volanie prepne stav názvu a vráti `true`, keď je teraz pozastavený. Pozastavené názvy sú v poli `F.paused`.\n\n## Servisný časovač\n\nKaždých 5 sekúnd časovač aktualizuje `NOW` a zruší HTTP požiadavky, ktorým vypršal čas. Raz za minútu:\n\n- odstráni expirované položky cache a expirované bany,\n- každých 5 minút vyčistí `TEMP`,\n- každých `$clearcache` minút (predvolene `10`) vyčistí interné cache akcií, pohľadov, ciest, obrázkov a šablón,\n- každých `$tmsclearblocked` minút (predvolene `60`) vyčistí zoznam zablokovaných TMS klientov,\n- aktualizuje štatistiky využitia a vyvolá `$stats`,\n- spustí crony a vyvolá `service`.\n\n`$clearcache` a `$tmsclearblocked` sú kľúče súboru `config`; pozri [Konfigurácia](../../guides/configuration/). Na prácu, ktorá sa opakuje v pevných krokoch, stačí cron so `*` v poli alebo udalosť `service` s `counter`:\n\n```js\nON('service', function(counter) {\n\tif (counter % 5 === 0) {\n\t\t// every 5 minutes\n\t\trefresh();\n\t}\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:26.082Z"}
{"id":"JaqmB51jc60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/file-storage/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"File storage","summary":"Store, read, serve and manage binary files with FILESTORAGE(), including uploaded files.","markdown":"---\ntitle: File storage\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/file-storage/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# File storage\n\n> Store, read, serve and manage binary files with FILESTORAGE(), including uploaded files.\n\nA **file storage** keeps binary files (uploads, documents, images, exports) on the disk under your own identifiers. You never deal with paths: you save a file with an id and read it back with the same id. Each storage is a directory with sub-directories and an index file, and the name, the content type, the size and custom data of every file travel with the file itself.\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save('avatar-100', 'me.jpg', PATH.root('me.jpg'), function(err, meta) {\n\t// meta.name === 'me.jpg', meta.type === 'image/jpeg', meta.width, meta.height\n});\n```\n\n`FILESTORAGE(name)` returns the same instance for the same name during the life of the process, so call it wherever you need it. The full list of methods is in the reference of [File storage](../../reference/file-storage/).\n\n## Where files are stored\n\nA storage named `photos` lives in `/databases/fs-photos/`. Every file is written to `{group}/{id}.file`, where `{group}` is a four-digit directory computed from a hash of the id (`/databases/fs-photos/0417/avatar-100.file`), so large storages do not end up with thousands of files in one directory. The directory is created on the first save.\n\nEach `.file` starts with a 2000-byte header that holds the metadata as JSON, followed by the content. The storage also appends one line per saved file to `files.log`, a NoSQL index used by `browse()`. Change the directory of a storage with `fs.storage(path)`:\n\n```js\nFILESTORAGE('backups').storage('/mnt/disk2/backups/');\n```\n\n## Saving files\n\n`fs.save(id, name, source, [custom], [callback], [expire], [headers])` (alias `insert()`) accepts four kinds of source:\n\n- the path of a file on the disk,\n- a `Buffer`,\n- a readable stream,\n- an `https://` URL, which is downloaded (optional `headers` are sent with the request; a response with status 400 or higher ends with an error).\n\nThe id is up to you; `UID()` gives a unique one. `name` is the original file name: its extension decides the content type, and for JPEG, PNG, GIF and SVG files the width and height are measured during the save. `custom` is any value you want to keep with the file (the owner, a description...). `expire` is a time such as `'1 day'` or `'30 minutes'`: after that time the file can no longer be read. Without a callback the method returns a `Promise`.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a Buffer, with custom data\nfs.save(UID(), 'note.txt', Buffer.from('Hello', 'utf8'), { userid: 'u1' }, function(err, meta) {\n\tconsole.log(meta.id, meta.size, meta.custom.userid);\n});\n\n// From a URL, as a Promise, expires in 7 days\nvar meta = await fs.save('logo', 'logo.png', 'https://www.example.com/logo.png', null, null, '7 days');\n```\n\nThe callback receives the metadata of the saved file:\n\n| Property | Content |\n| --- | --- |\n| `id` | The id of the file |\n| `name` | The file name (without a path, at most 250 characters) |\n| `ext` | The extension, lower case without the dot |\n| `type` | The content type, for example `image/png` |\n| `size` | The size of the content in bytes |\n| `width`, `height` | The dimensions of JPEG, PNG, GIF and SVG images |\n| `custom` | Your custom data, or `null` |\n| `date` | When the file was saved |\n| `expire` | When the file expires, if you set it |\n\nSaving again with an existing id replaces the file. `fs.savejson(id, value, [callback])` is a shortcut that stores a value as `{id}.json`.\n\n## Uploaded files\n\nFiles of a `multipart/form-data` request are in `$.files`, in a route and in an action alike. Each item is an `HttpFile`, and `file.fs(storage, id, [callback])` saves it into a storage with its original file name. The flag `@upload` makes the route accept only multipart requests; a size flag such as `<10MB` raises the size limit of the body.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', upload);\n};\n\nfunction upload($) {\n\n\tvar file = $.files[0];\n\n\tif (!file) {\n\t\t$.invalid('@(Select a file)');\n\t\treturn;\n\t}\n\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n}\n```\n\nSeveral files are saved one after another with `wait()`:\n\n```js\nfunction upload($) {\n\tvar output = [];\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), function(err, meta) {\n\t\t\tmeta && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, () => $.json(output));\n}\n```\n\nThe properties of `HttpFile` and its other methods are described in [Controller](../controller/).\n\n## Reading files\n\n| Method | The callback receives |\n| --- | --- |\n| `fs.read(id, callback)` | `(err, meta)` with a readable stream in `meta.stream` |\n| `fs.readmeta(id, callback)` | `(err, meta)`: only the header, the content is not read |\n| `fs.readbuffer(id, callback)` | `(err, buffer, meta)`: the whole content |\n| `fs.readbase64(id, callback)` | `(err, base64, meta)`: the content as a base64 string |\n| `fs.readjson(id, callback)` | `(err, value, meta)`: the parsed JSON |\n| `fs.image(id, callback)` | `(err, image, meta)`: an image object of [Images](../images/) |\n\nA missing file ends with an error from the file system, an expired one with the error `File is expired`. Except `readjson()`, the methods return a `Promise` without a callback; the promise resolves with the second argument of the callback.\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.read('invoice-2025-001', function(err, meta) {\n\tif (err)\n\t\treturn;\n\tvar writer = F.Fs.createWriteStream(PATH.tmp(meta.name));\n\tmeta.stream.pipe(writer);\n});\n\nvar buffer = await fs.readbuffer('invoice-2025-001');\n```\n\nAlways consume `meta.stream` from `read()`: it holds an open file descriptor until it ends. Pass `true` as the third argument of `read()` when you only need the metadata.\n\n## Serving files over HTTP\n\n`fs.http($, opt)` sends a stored file as the response of a route. It sets the content type, `Last-Modified` and the HTTP cache headers, answers `304` when the browser has the current version, supports `Range` requests (audio and video seeking) and answers `404` when the file does not exist or has expired. `$.filefs(name, id, [download], [check])` of the controller is a shortcut for it.\n\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', file);\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction file($) {\n\tFILESTORAGE('files').http($, { id: $.params.id });\n}\n\nfunction download($) {\n\tFILESTORAGE('files').http($, {\n\t\tid: $.params.id,\n\t\tdownload: true,\n\t\tcheck: meta => meta.custom && meta.custom.public\n\t});\n}\n```\n\nThe options are:\n\n- `id`: the id of the file,\n- `download`: `true` sends the file as an attachment with its stored name, a string sets another name, a function `(name, type)` returns the name,\n- `check`: a function `(meta)`; when it returns `false` the answer is `404`,\n- `image`: a function `(image)` called with `this` as the controller, to transform JPEG, PNG and other images before they are sent,\n- `cache`: a key; with `image`, the transformed image is saved to the temporary directory under this key and reused for the next requests.\n\n```js\nfunction thumbnail($) {\n\tvar id = $.params.id;\n\tFILESTORAGE('photos').http($, {\n\t\tid: id,\n\t\tcache: 'thumb-' + id,\n\t\timage: function(image) {\n\t\t\timage.resize(200, 200);\n\t\t\timage.quality(80);\n\t\t}\n\t});\n}\n```\n\nAn id that ended with `404` once is remembered and answered with `404` until the next periodic clean-up of the framework, so keep ids of removed files unique.\n\n## Managing files\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename('note-1', 'renamed.txt');            // changes the stored name\nfs.copy('note-1', PATH.tmp());                  // writes the content to a directory or a file path\nfs.clone('note-1', 'note-2');                   // a new id with the same content\nfs.remove('note-2', function(err) {});          // deletes the file and its line in the index\n```\n\n`clone(id, [newid], [callback])` creates an id with `UID()` when `newid` is missing, and the callback or the Promise gets the metadata with that id. `copy(id, path)` writes to `path` as a file name when it contains a dot, otherwise into the directory `path` with the stored name.\n\n`fs.clear()` (alias `drop()`) removes all files of the storage and the index; the callback receives the number of removed files.\n\n## Listing files\n\n`fs.browse()` reads the index `files.log` and returns a NoSQL query builder, so you can filter, sort and page the files as in [NoSQL](../nosql/):\n\n```js\nFILESTORAGE('documents').browse().where('ext', 'pdf').sort('date', true).take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n`fs.browse2()` reads the headers of all files on the disk instead of the index, and `fs.stream(onfile, [callback], [workers])` walks the files one by one. `fs.count2()` counts the files on the disk. `fs.rebuild()` writes the index again from the files on the disk, which you need after you copied files into the directory yourself or after `restore()`.\n\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tconsole.log(meta.id, meta.name, meta.size);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n## Backup and restore\n\n`fs.backup(filename, [callback])` writes all files of the storage, each compressed with GZIP, into one text file and returns `{ filename, files, size }`. `fs.restore(filename, [callback])` removes the current files and restores the backup. The index is not part of the backup, so call `rebuild()` after a restore.\n\n```js\nvar fs = FILESTORAGE('documents');\nawait fs.backup(PATH.root('documents.backup'));\n\nfs.restore(PATH.root('documents.backup'), function(err) {\n\tfs.rebuild();\n});\n```\n\nWhile a storage is cleared, restored or its index is rebuilt, its `save()`, `read()`, `readbuffer()`, `copy()` and `clone()` calls wait until the operation ends.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmB51jc60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/file-storage/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Dateispeicher","summary":"Speichere, lies, liefere und verwalte Binärdateien mit FILESTORAGE(), einschließlich hochgeladener Dateien.","markdown":"---\ntitle: Dateispeicher\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/file-storage/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Dateispeicher\n\n> Speichere, lies, liefere und verwalte Binärdateien mit FILESTORAGE(), einschließlich hochgeladener Dateien.\n\nEin **Dateispeicher** bewahrt Binärdateien (Uploads, Dokumente, Bilder, Exporte) auf der Festplatte unter deinen eigenen Kennungen auf. Mit Pfaden hast du nie zu tun: Du speicherst eine Datei mit einer id und liest sie mit derselben id wieder. Jeder Speicher ist ein Verzeichnis mit Unterverzeichnissen und einer Indexdatei, und der Name, der Inhaltstyp, die Größe und eigene Daten jeder Datei reisen mit der Datei selbst.\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save('avatar-100', 'me.jpg', PATH.root('me.jpg'), function(err, meta) {\n\t// meta.name === 'me.jpg', meta.type === 'image/jpeg', meta.width, meta.height\n});\n```\n\n`FILESTORAGE(name)` gibt während der Lebensdauer des Prozesses für denselben Namen dieselbe Instanz zurück, also rufe es auf, wo immer du es brauchst. Die vollständige Liste der Methoden steht in der Referenz zum [Dateispeicher](../../reference/file-storage/).\n\n## Wo die Dateien gespeichert werden\n\nEin Speicher namens `photos` liegt in `/databases/fs-photos/`. Jede Datei wird nach `{group}/{id}.file` geschrieben, wobei `{group}` ein vierstelliges Verzeichnis ist, das aus einem Hash der id berechnet wird (`/databases/fs-photos/0417/avatar-100.file`), sodass große Speicher nicht mit Tausenden von Dateien in einem Verzeichnis enden. Das Verzeichnis wird beim ersten Speichern erstellt.\n\nJede `.file` beginnt mit einem 2000 Byte großen Header, der die Metadaten als JSON enthält, gefolgt vom Inhalt. Der Speicher hängt außerdem für jede gespeicherte Datei eine Zeile an `files.log` an, einen NoSQL-Index, den `browse()` verwendet. Das Verzeichnis eines Speichers änderst du mit `fs.storage(path)`:\n\n```js\nFILESTORAGE('backups').storage('/mnt/disk2/backups/');\n```\n\n## Dateien speichern\n\n`fs.save(id, name, source, [custom], [callback], [expire], [headers])` (Alias `insert()`) akzeptiert vier Arten von Quellen:\n\n- den Pfad einer Datei auf der Festplatte,\n- einen `Buffer`,\n- einen lesbaren Stream,\n- eine `https://`-URL, die heruntergeladen wird (optionale `headers` werden mit der Anfrage gesendet; eine Antwort mit Status 400 oder höher endet mit einem Fehler).\n\nDie id bestimmst du; `UID()` liefert eine eindeutige. `name` ist der ursprüngliche Dateiname: Seine Endung bestimmt den Inhaltstyp, und bei JPEG-, PNG-, GIF- und SVG-Dateien werden Breite und Höhe beim Speichern gemessen. `custom` ist ein beliebiger Wert, den du mit der Datei aufbewahren willst (der Besitzer, eine Beschreibung...). `expire` ist eine Zeitangabe wie `'1 day'` oder `'30 minutes'`: Nach dieser Zeit kann die Datei nicht mehr gelesen werden. Ohne Callback gibt die Methode ein `Promise` zurück.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a Buffer, with custom data\nfs.save(UID(), 'note.txt', Buffer.from('Hello', 'utf8'), { userid: 'u1' }, function(err, meta) {\n\tconsole.log(meta.id, meta.size, meta.custom.userid);\n});\n\n// From a URL, as a Promise, expires in 7 days\nvar meta = await fs.save('logo', 'logo.png', 'https://www.example.com/logo.png', null, null, '7 days');\n```\n\nDer Callback erhält die Metadaten der gespeicherten Datei:\n\n| Eigenschaft | Inhalt |\n| --- | --- |\n| `id` | Die id der Datei |\n| `name` | Der Dateiname (ohne Pfad, höchstens 250 Zeichen) |\n| `ext` | Die Endung, kleingeschrieben und ohne Punkt |\n| `type` | Der Inhaltstyp, zum Beispiel `image/png` |\n| `size` | Die Größe des Inhalts in Bytes |\n| `width`, `height` | Die Abmessungen von JPEG-, PNG-, GIF- und SVG-Bildern |\n| `custom` | Deine eigenen Daten oder `null` |\n| `date` | Wann die Datei gespeichert wurde |\n| `expire` | Wann die Datei abläuft, falls du es gesetzt hast |\n\nErneutes Speichern mit einer vorhandenen id ersetzt die Datei. `fs.savejson(id, value, [callback])` ist eine Abkürzung, die einen Wert als `{id}.json` speichert.\n\n## Hochgeladene Dateien\n\nDie Dateien einer `multipart/form-data`-Anfrage stehen in `$.files`, in einer Route wie in einer Aktion. Jedes Element ist ein `HttpFile`, und `file.fs(storage, id, [callback])` speichert es mit seinem ursprünglichen Dateinamen in einem Speicher. Das Flag `@upload` sorgt dafür, dass die Route nur Multipart-Anfragen annimmt; ein Größen-Flag wie `<10MB` erhöht das Größenlimit des Bodys.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', upload);\n};\n\nfunction upload($) {\n\n\tvar file = $.files[0];\n\n\tif (!file) {\n\t\t$.invalid('@(Select a file)');\n\t\treturn;\n\t}\n\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n}\n```\n\nMehrere Dateien werden mit `wait()` nacheinander gespeichert:\n\n```js\nfunction upload($) {\n\tvar output = [];\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), function(err, meta) {\n\t\t\tmeta && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, () => $.json(output));\n}\n```\n\nDie Eigenschaften von `HttpFile` und seine anderen Methoden sind unter [Controller](../controller/) beschrieben.\n\n## Dateien lesen\n\n| Methode | Der Callback erhält |\n| --- | --- |\n| `fs.read(id, callback)` | `(err, meta)` mit einem lesbaren Stream in `meta.stream` |\n| `fs.readmeta(id, callback)` | `(err, meta)`: nur den Header, der Inhalt wird nicht gelesen |\n| `fs.readbuffer(id, callback)` | `(err, buffer, meta)`: den ganzen Inhalt |\n| `fs.readbase64(id, callback)` | `(err, base64, meta)`: den Inhalt als Base64-String |\n| `fs.readjson(id, callback)` | `(err, value, meta)`: das geparste JSON |\n| `fs.image(id, callback)` | `(err, image, meta)`: ein Bildobjekt aus [Bilder](../images/) |\n\nEine fehlende Datei endet mit einem Fehler des Dateisystems, eine abgelaufene mit dem Fehler `File is expired`. Außer `readjson()` geben die Methoden ohne Callback ein `Promise` zurück; das Promise wird mit dem zweiten Argument des Callbacks aufgelöst.\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.read('invoice-2025-001', function(err, meta) {\n\tif (err)\n\t\treturn;\n\tvar writer = F.Fs.createWriteStream(PATH.tmp(meta.name));\n\tmeta.stream.pipe(writer);\n});\n\nvar buffer = await fs.readbuffer('invoice-2025-001');\n```\n\nLies `meta.stream` aus `read()` immer bis zum Ende: Er hält einen offenen Dateideskriptor, bis er endet. Übergib `true` als drittes Argument von `read()`, wenn du nur die Metadaten brauchst.\n\n## Dateien über HTTP ausliefern\n\n`fs.http($, opt)` sendet eine gespeicherte Datei als Antwort einer Route. Es setzt den Inhaltstyp, `Last-Modified` und die HTTP-Cache-Header, antwortet mit `304`, wenn der Browser die aktuelle Version hat, unterstützt `Range`-Anfragen (Springen in Audio und Video) und antwortet mit `404`, wenn die Datei nicht existiert oder abgelaufen ist. `$.filefs(name, id, [download], [check])` des Controllers ist eine Abkürzung dafür.\n\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', file);\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction file($) {\n\tFILESTORAGE('files').http($, { id: $.params.id });\n}\n\nfunction download($) {\n\tFILESTORAGE('files').http($, {\n\t\tid: $.params.id,\n\t\tdownload: true,\n\t\tcheck: meta => meta.custom && meta.custom.public\n\t});\n}\n```\n\nDie Optionen sind:\n\n- `id`: die id der Datei,\n- `download`: `true` sendet die Datei als Anhang mit ihrem gespeicherten Namen, ein String setzt einen anderen Namen, eine Funktion `(name, type)` gibt den Namen zurück,\n- `check`: eine Funktion `(meta)`; wenn sie `false` zurückgibt, lautet die Antwort `404`,\n- `image`: eine Funktion `(image)`, die mit dem Controller als `this` aufgerufen wird, um JPEG-, PNG- und andere Bilder vor dem Senden zu verändern,\n- `cache`: ein Schlüssel; mit `image` wird das veränderte Bild unter diesem Schlüssel im temporären Verzeichnis gespeichert und für die nächsten Anfragen wiederverwendet.\n\n```js\nfunction thumbnail($) {\n\tvar id = $.params.id;\n\tFILESTORAGE('photos').http($, {\n\t\tid: id,\n\t\tcache: 'thumb-' + id,\n\t\timage: function(image) {\n\t\t\timage.resize(200, 200);\n\t\t\timage.quality(80);\n\t\t}\n\t});\n}\n```\n\nEine id, die einmal mit `404` geendet hat, wird gemerkt und bis zur nächsten regelmäßigen Aufräumrunde des Frameworks mit `404` beantwortet, also halte die ids entfernter Dateien eindeutig.\n\n## Dateien verwalten\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename('note-1', 'renamed.txt');            // changes the stored name\nfs.copy('note-1', PATH.tmp());                  // writes the content to a directory or a file path\nfs.clone('note-1', 'note-2');                   // a new id with the same content\nfs.remove('note-2', function(err) {});          // deletes the file and its line in the index\n```\n\n`clone(id, [newid], [callback])` erzeugt eine id mit `UID()`, wenn `newid` fehlt, und der Callback oder das Promise erhält die Metadaten mit dieser id. `copy(id, path)` schreibt nach `path` als Dateiname, wenn er einen Punkt enthält, andernfalls in das Verzeichnis `path` mit dem gespeicherten Namen.\n\n`fs.clear()` (Alias `drop()`) entfernt alle Dateien des Speichers und den Index; der Callback erhält die Anzahl der entfernten Dateien.\n\n## Dateien auflisten\n\n`fs.browse()` liest den Index `files.log` und gibt einen NoSQL-Query-Builder zurück, sodass du die Dateien wie unter [NoSQL](../nosql/) filtern, sortieren und seitenweise abrufen kannst:\n\n```js\nFILESTORAGE('documents').browse().where('ext', 'pdf').sort('date', true).take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n`fs.browse2()` liest statt des Index die Header aller Dateien auf der Festplatte, und `fs.stream(onfile, [callback], [workers])` geht die Dateien eine nach der anderen durch. `fs.count2()` zählt die Dateien auf der Festplatte. `fs.rebuild()` schreibt den Index aus den Dateien auf der Festplatte neu, was du brauchst, nachdem du selbst Dateien in das Verzeichnis kopiert hast oder nach `restore()`.\n\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tconsole.log(meta.id, meta.name, meta.size);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n## Sichern und wiederherstellen\n\n`fs.backup(filename, [callback])` schreibt alle Dateien des Speichers, jede mit GZIP komprimiert, in eine einzige Textdatei und gibt `{ filename, files, size }` zurück. `fs.restore(filename, [callback])` entfernt die aktuellen Dateien und stellt die Sicherung wieder her. Der Index gehört nicht zur Sicherung, also rufe nach einer Wiederherstellung `rebuild()` auf.\n\n```js\nvar fs = FILESTORAGE('documents');\nawait fs.backup(PATH.root('documents.backup'));\n\nfs.restore(PATH.root('documents.backup'), function(err) {\n\tfs.rebuild();\n});\n```\n\nWährend ein Speicher geleert oder wiederhergestellt oder sein Index neu aufgebaut wird, warten seine Aufrufe von `save()`, `read()`, `readbuffer()`, `copy()` und `clone()`, bis der Vorgang endet.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmB51jc60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/file-storage/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Almacenamiento de archivos","summary":"Guarda, lee, sirve y gestiona archivos binarios con FILESTORAGE(), incluidos los archivos subidos.","markdown":"---\ntitle: Almacenamiento de archivos\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/file-storage/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Almacenamiento de archivos\n\n> Guarda, lee, sirve y gestiona archivos binarios con FILESTORAGE(), incluidos los archivos subidos.\n\nUn **almacenamiento de archivos** guarda archivos binarios (subidas, documentos, imágenes, exportaciones) en el disco bajo tus propios identificadores. Nunca tratas con rutas: guardas un archivo con un id y lo vuelves a leer con el mismo id. Cada almacenamiento es un directorio con subdirectorios y un archivo de índice, y el nombre, el tipo de contenido, el tamaño y los datos personalizados de cada archivo viajan con el propio archivo.\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save('avatar-100', 'me.jpg', PATH.root('me.jpg'), function(err, meta) {\n\t// meta.name === 'me.jpg', meta.type === 'image/jpeg', meta.width, meta.height\n});\n```\n\n`FILESTORAGE(name)` devuelve la misma instancia para el mismo nombre durante toda la vida del proceso, así que llámalo donde lo necesites. La lista completa de métodos está en la referencia de [Almacenamiento de archivos](../../reference/file-storage/).\n\n## Dónde se guardan los archivos\n\nUn almacenamiento llamado `photos` vive en `/databases/fs-photos/`. Cada archivo se escribe en `{group}/{id}.file`, donde `{group}` es un directorio de cuatro dígitos calculado a partir de un hash del id (`/databases/fs-photos/0417/avatar-100.file`), así los almacenamientos grandes no acaban con miles de archivos en un solo directorio. El directorio se crea con el primer guardado.\n\nCada `.file` empieza con una cabecera de 2000 bytes que contiene los metadatos como JSON, seguida del contenido. El almacenamiento también añade una línea por cada archivo guardado a `files.log`, un índice NoSQL que usa `browse()`. Cambia el directorio de un almacenamiento con `fs.storage(path)`:\n\n```js\nFILESTORAGE('backups').storage('/mnt/disk2/backups/');\n```\n\n## Guardar archivos\n\n`fs.save(id, name, source, [custom], [callback], [expire], [headers])` (alias `insert()`) acepta cuatro tipos de origen:\n\n- la ruta de un archivo en el disco,\n- un `Buffer`,\n- un stream de lectura,\n- una URL `https://`, que se descarga (los `headers` opcionales se envían con la petición; una respuesta con estado 400 o superior termina con un error).\n\nEl id lo decides tú; `UID()` te da uno único. `name` es el nombre original del archivo: su extensión decide el tipo de contenido, y para archivos JPEG, PNG, GIF y SVG se miden el ancho y el alto durante el guardado. `custom` es cualquier valor que quieras guardar con el archivo (el propietario, una descripción...). `expire` es un tiempo como `'1 day'` o `'30 minutes'`: pasado ese tiempo el archivo ya no se puede leer. Sin callback el método devuelve una `Promise`.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a Buffer, with custom data\nfs.save(UID(), 'note.txt', Buffer.from('Hello', 'utf8'), { userid: 'u1' }, function(err, meta) {\n\tconsole.log(meta.id, meta.size, meta.custom.userid);\n});\n\n// From a URL, as a Promise, expires in 7 days\nvar meta = await fs.save('logo', 'logo.png', 'https://www.example.com/logo.png', null, null, '7 days');\n```\n\nEl callback recibe los metadatos del archivo guardado:\n\n| Propiedad | Contenido |\n| --- | --- |\n| `id` | El id del archivo |\n| `name` | El nombre del archivo (sin ruta, como máximo 250 caracteres) |\n| `ext` | La extensión, en minúsculas y sin el punto |\n| `type` | El tipo de contenido, por ejemplo `image/png` |\n| `size` | El tamaño del contenido en bytes |\n| `width`, `height` | Las dimensiones de las imágenes JPEG, PNG, GIF y SVG |\n| `custom` | Tus datos personalizados, o `null` |\n| `date` | Cuándo se guardó el archivo |\n| `expire` | Cuándo caduca el archivo, si lo estableciste |\n\nGuardar de nuevo con un id existente sustituye el archivo. `fs.savejson(id, value, [callback])` es un atajo que guarda un valor como `{id}.json`.\n\n## Archivos subidos\n\nLos archivos de una petición `multipart/form-data` están en `$.files`, tanto en una ruta como en una acción. Cada elemento es un `HttpFile`, y `file.fs(storage, id, [callback])` lo guarda en un almacenamiento con su nombre de archivo original. El flag `@upload` hace que la ruta acepte solo peticiones multipart; un flag de tamaño como `<10MB` sube el límite de tamaño del cuerpo.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', upload);\n};\n\nfunction upload($) {\n\n\tvar file = $.files[0];\n\n\tif (!file) {\n\t\t$.invalid('@(Select a file)');\n\t\treturn;\n\t}\n\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n}\n```\n\nVarios archivos se guardan uno tras otro con `wait()`:\n\n```js\nfunction upload($) {\n\tvar output = [];\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), function(err, meta) {\n\t\t\tmeta && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, () => $.json(output));\n}\n```\n\nLas propiedades de `HttpFile` y sus otros métodos se describen en [Controlador](../controller/).\n\n## Leer archivos\n\n| Método | El callback recibe |\n| --- | --- |\n| `fs.read(id, callback)` | `(err, meta)` con un stream de lectura en `meta.stream` |\n| `fs.readmeta(id, callback)` | `(err, meta)`: solo la cabecera, el contenido no se lee |\n| `fs.readbuffer(id, callback)` | `(err, buffer, meta)`: todo el contenido |\n| `fs.readbase64(id, callback)` | `(err, base64, meta)`: el contenido como string en base64 |\n| `fs.readjson(id, callback)` | `(err, value, meta)`: el JSON parseado |\n| `fs.image(id, callback)` | `(err, image, meta)`: un objeto de imagen de [Imágenes](../images/) |\n\nUn archivo que no existe termina con un error del sistema de archivos, uno caducado con el error `File is expired`. Excepto `readjson()`, los métodos devuelven una `Promise` sin callback; la promesa se resuelve con el segundo argumento del callback.\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.read('invoice-2025-001', function(err, meta) {\n\tif (err)\n\t\treturn;\n\tvar writer = F.Fs.createWriteStream(PATH.tmp(meta.name));\n\tmeta.stream.pipe(writer);\n});\n\nvar buffer = await fs.readbuffer('invoice-2025-001');\n```\n\nConsume siempre `meta.stream` de `read()`: mantiene abierto un descriptor de archivo hasta que termina. Pasa `true` como tercer argumento de `read()` cuando solo necesites los metadatos.\n\n## Servir archivos por HTTP\n\n`fs.http($, opt)` envía un archivo guardado como respuesta de una ruta. Establece el tipo de contenido, `Last-Modified` y las cabeceras de caché HTTP, responde `304` cuando el navegador tiene la versión actual, admite peticiones `Range` (para avanzar en audio y vídeo) y responde `404` cuando el archivo no existe o ha caducado. `$.filefs(name, id, [download], [check])` del controlador es un atajo para ello.\n\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', file);\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction file($) {\n\tFILESTORAGE('files').http($, { id: $.params.id });\n}\n\nfunction download($) {\n\tFILESTORAGE('files').http($, {\n\t\tid: $.params.id,\n\t\tdownload: true,\n\t\tcheck: meta => meta.custom && meta.custom.public\n\t});\n}\n```\n\nLas opciones son:\n\n- `id`: el id del archivo,\n- `download`: `true` envía el archivo como adjunto con su nombre guardado, un string establece otro nombre, una función `(name, type)` devuelve el nombre,\n- `check`: una función `(meta)`; cuando devuelve `false` la respuesta es `404`,\n- `image`: una función `(image)` llamada con `this` como el controlador, para transformar imágenes JPEG, PNG y otras antes de enviarlas,\n- `cache`: una clave; con `image`, la imagen transformada se guarda en el directorio temporal bajo esta clave y se reutiliza en las siguientes peticiones.\n\n```js\nfunction thumbnail($) {\n\tvar id = $.params.id;\n\tFILESTORAGE('photos').http($, {\n\t\tid: id,\n\t\tcache: 'thumb-' + id,\n\t\timage: function(image) {\n\t\t\timage.resize(200, 200);\n\t\t\timage.quality(80);\n\t\t}\n\t});\n}\n```\n\nUn id que terminó una vez con `404` se recuerda y se responde con `404` hasta la siguiente limpieza periódica del framework, así que mantén únicos los ids de los archivos eliminados.\n\n## Gestionar archivos\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename('note-1', 'renamed.txt');            // changes the stored name\nfs.copy('note-1', PATH.tmp());                  // writes the content to a directory or a file path\nfs.clone('note-1', 'note-2');                   // a new id with the same content\nfs.remove('note-2', function(err) {});          // deletes the file and its line in the index\n```\n\n`clone(id, [newid], [callback])` crea un id con `UID()` cuando falta `newid`, y el callback o la Promise recibe los metadatos con ese id. `copy(id, path)` escribe en `path` como nombre de archivo cuando contiene un punto; si no, dentro del directorio `path` con el nombre guardado.\n\n`fs.clear()` (alias `drop()`) elimina todos los archivos del almacenamiento y el índice; el callback recibe el número de archivos eliminados.\n\n## Listar archivos\n\n`fs.browse()` lee el índice `files.log` y devuelve un query builder de NoSQL, así puedes filtrar, ordenar y paginar los archivos como en [NoSQL](../nosql/):\n\n```js\nFILESTORAGE('documents').browse().where('ext', 'pdf').sort('date', true).take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n`fs.browse2()` lee las cabeceras de todos los archivos del disco en lugar del índice, y `fs.stream(onfile, [callback], [workers])` recorre los archivos uno a uno. `fs.count2()` cuenta los archivos del disco. `fs.rebuild()` vuelve a escribir el índice a partir de los archivos del disco, algo que necesitas después de copiar tú mismo archivos al directorio o después de `restore()`.\n\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tconsole.log(meta.id, meta.name, meta.size);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n## Copia de seguridad y restauración\n\n`fs.backup(filename, [callback])` escribe todos los archivos del almacenamiento, cada uno comprimido con GZIP, en un solo archivo de texto y devuelve `{ filename, files, size }`. `fs.restore(filename, [callback])` elimina los archivos actuales y restaura la copia de seguridad. El índice no forma parte de la copia de seguridad, así que llama a `rebuild()` después de una restauración.\n\n```js\nvar fs = FILESTORAGE('documents');\nawait fs.backup(PATH.root('documents.backup'));\n\nfs.restore(PATH.root('documents.backup'), function(err) {\n\tfs.rebuild();\n});\n```\n\nMientras se vacía o se restaura un almacenamiento, o se reconstruye su índice, sus llamadas a `save()`, `read()`, `readbuffer()`, `copy()` y `clone()` esperan hasta que termina la operación.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmB51jc60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/file-storage/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Stockage de fichiers","summary":"Stocke, lis, sers et gère des fichiers binaires avec FILESTORAGE(), y compris les fichiers uploadés.","markdown":"---\ntitle: Stockage de fichiers\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/file-storage/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Stockage de fichiers\n\n> Stocke, lis, sers et gère des fichiers binaires avec FILESTORAGE(), y compris les fichiers uploadés.\n\nUn **stockage de fichiers** garde des fichiers binaires (uploads, documents, images, exports) sur le disque sous tes propres identifiants. Tu ne manipules jamais de chemins : tu enregistres un fichier avec un id et tu le relis avec le même id. Chaque stockage est un répertoire avec des sous-répertoires et un fichier d'index, et le nom, le type de contenu, la taille et les données personnalisées de chaque fichier voyagent avec le fichier lui-même.\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save('avatar-100', 'me.jpg', PATH.root('me.jpg'), function(err, meta) {\n\t// meta.name === 'me.jpg', meta.type === 'image/jpeg', meta.width, meta.height\n});\n```\n\n`FILESTORAGE(name)` renvoie la même instance pour le même nom pendant toute la vie du processus, alors appelle-la partout où tu en as besoin. La liste complète des méthodes se trouve dans la référence [Stockage de fichiers](../../reference/file-storage/).\n\n## Où les fichiers sont stockés\n\nUn stockage nommé `photos` se trouve dans `/databases/fs-photos/`. Chaque fichier est écrit dans `{group}/{id}.file`, où `{group}` est un répertoire à quatre chiffres calculé à partir d'un hash de l'id (`/databases/fs-photos/0417/avatar-100.file`) : les gros stockages ne se retrouvent donc pas avec des milliers de fichiers dans un seul répertoire. Le répertoire est créé au premier enregistrement.\n\nChaque `.file` commence par un en-tête de 2000 octets qui contient les métadonnées en JSON, suivi du contenu. Le stockage ajoute aussi une ligne par fichier enregistré à `files.log`, un index NoSQL utilisé par `browse()`. Change le répertoire d'un stockage avec `fs.storage(path)` :\n\n```js\nFILESTORAGE('backups').storage('/mnt/disk2/backups/');\n```\n\n## Enregistrer des fichiers\n\n`fs.save(id, name, source, [custom], [callback], [expire], [headers])` (alias `insert()`) accepte quatre types de source :\n\n- le chemin d'un fichier sur le disque,\n- un `Buffer`,\n- un stream lisible,\n- une URL `https://`, qui est téléchargée (les `headers` facultatifs sont envoyés avec la requête ; une réponse avec un statut 400 ou plus se termine par une erreur).\n\nL'id est à ton choix ; `UID()` t'en donne un unique. `name` est le nom d'origine du fichier : son extension détermine le type de contenu, et pour les fichiers JPEG, PNG, GIF et SVG la largeur et la hauteur sont mesurées pendant l'enregistrement. `custom` est n'importe quelle valeur que tu veux garder avec le fichier (le propriétaire, une description...). `expire` est une durée comme `'1 day'` ou `'30 minutes'` : passé ce délai, le fichier ne peut plus être lu. Sans callback, la méthode renvoie une `Promise`.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a Buffer, with custom data\nfs.save(UID(), 'note.txt', Buffer.from('Hello', 'utf8'), { userid: 'u1' }, function(err, meta) {\n\tconsole.log(meta.id, meta.size, meta.custom.userid);\n});\n\n// From a URL, as a Promise, expires in 7 days\nvar meta = await fs.save('logo', 'logo.png', 'https://www.example.com/logo.png', null, null, '7 days');\n```\n\nLe callback reçoit les métadonnées du fichier enregistré :\n\n| Propriété | Contenu |\n| --- | --- |\n| `id` | L'id du fichier |\n| `name` | Le nom du fichier (sans chemin, 250 caractères au maximum) |\n| `ext` | L'extension, en minuscules et sans le point |\n| `type` | Le type de contenu, par exemple `image/png` |\n| `size` | La taille du contenu en octets |\n| `width`, `height` | Les dimensions des images JPEG, PNG, GIF et SVG |\n| `custom` | Tes données personnalisées, ou `null` |\n| `date` | Le moment où le fichier a été enregistré |\n| `expire` | Le moment où le fichier expire, si tu l'as défini |\n\nEnregistrer à nouveau avec un id existant remplace le fichier. `fs.savejson(id, value, [callback])` est un raccourci qui stocke une valeur sous `{id}.json`.\n\n## Fichiers uploadés\n\nLes fichiers d'une requête `multipart/form-data` se trouvent dans `$.files`, aussi bien dans une route que dans une action. Chaque élément est un `HttpFile`, et `file.fs(storage, id, [callback])` l'enregistre dans un stockage avec son nom de fichier d'origine. Le flag `@upload` fait que la route n'accepte que les requêtes multipart ; un flag de taille comme `<10MB` augmente la limite de taille du corps.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', upload);\n};\n\nfunction upload($) {\n\n\tvar file = $.files[0];\n\n\tif (!file) {\n\t\t$.invalid('@(Select a file)');\n\t\treturn;\n\t}\n\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n}\n```\n\nPlusieurs fichiers sont enregistrés l'un après l'autre avec `wait()` :\n\n```js\nfunction upload($) {\n\tvar output = [];\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), function(err, meta) {\n\t\t\tmeta && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, () => $.json(output));\n}\n```\n\nLes propriétés de `HttpFile` et ses autres méthodes sont décrites dans [Contrôleur](../controller/).\n\n## Lire des fichiers\n\n| Méthode | Le callback reçoit |\n| --- | --- |\n| `fs.read(id, callback)` | `(err, meta)` avec un stream lisible dans `meta.stream` |\n| `fs.readmeta(id, callback)` | `(err, meta)` : seulement l'en-tête, le contenu n'est pas lu |\n| `fs.readbuffer(id, callback)` | `(err, buffer, meta)` : tout le contenu |\n| `fs.readbase64(id, callback)` | `(err, base64, meta)` : le contenu sous forme de chaîne base64 |\n| `fs.readjson(id, callback)` | `(err, value, meta)` : le JSON analysé |\n| `fs.image(id, callback)` | `(err, image, meta)` : un objet image de [Images](../images/) |\n\nUn fichier manquant se termine par une erreur du système de fichiers, un fichier expiré par l'erreur `File is expired`. Sauf `readjson()`, les méthodes renvoient une `Promise` sans callback ; la promise se résout avec le deuxième argument du callback.\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.read('invoice-2025-001', function(err, meta) {\n\tif (err)\n\t\treturn;\n\tvar writer = F.Fs.createWriteStream(PATH.tmp(meta.name));\n\tmeta.stream.pipe(writer);\n});\n\nvar buffer = await fs.readbuffer('invoice-2025-001');\n```\n\nConsomme toujours `meta.stream` de `read()` : il garde un descripteur de fichier ouvert jusqu'à sa fin. Passe `true` comme troisième argument de `read()` quand tu n'as besoin que des métadonnées.\n\n## Servir des fichiers en HTTP\n\n`fs.http($, opt)` envoie un fichier stocké comme réponse d'une route. Elle définit le type de contenu, `Last-Modified` et les en-têtes de cache HTTP, répond `304` quand le navigateur a la version actuelle, prend en charge les requêtes `Range` (navigation dans l'audio et la vidéo) et répond `404` quand le fichier n'existe pas ou a expiré. `$.filefs(name, id, [download], [check])` du contrôleur en est un raccourci.\n\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', file);\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction file($) {\n\tFILESTORAGE('files').http($, { id: $.params.id });\n}\n\nfunction download($) {\n\tFILESTORAGE('files').http($, {\n\t\tid: $.params.id,\n\t\tdownload: true,\n\t\tcheck: meta => meta.custom && meta.custom.public\n\t});\n}\n```\n\nLes options sont :\n\n- `id` : l'id du fichier,\n- `download` : `true` envoie le fichier en pièce jointe avec son nom stocké, une chaîne définit un autre nom, une fonction `(name, type)` renvoie le nom,\n- `check` : une fonction `(meta)` ; quand elle renvoie `false`, la réponse est `404`,\n- `image` : une fonction `(image)` appelée avec `this` comme contrôleur, pour transformer les images JPEG, PNG et autres avant leur envoi,\n- `cache` : une clé ; avec `image`, l'image transformée est enregistrée dans le répertoire temporaire sous cette clé et réutilisée pour les requêtes suivantes.\n\n```js\nfunction thumbnail($) {\n\tvar id = $.params.id;\n\tFILESTORAGE('photos').http($, {\n\t\tid: id,\n\t\tcache: 'thumb-' + id,\n\t\timage: function(image) {\n\t\t\timage.resize(200, 200);\n\t\t\timage.quality(80);\n\t\t}\n\t});\n}\n```\n\nUn id qui a fini une fois en `404` est mémorisé et reçoit la réponse `404` jusqu'au prochain nettoyage périodique du framework, alors garde uniques les ids des fichiers supprimés.\n\n## Gérer les fichiers\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename('note-1', 'renamed.txt');            // changes the stored name\nfs.copy('note-1', PATH.tmp());                  // writes the content to a directory or a file path\nfs.clone('note-1', 'note-2');                   // a new id with the same content\nfs.remove('note-2', function(err) {});          // deletes the file and its line in the index\n```\n\n`clone(id, [newid], [callback])` crée un id avec `UID()` quand `newid` manque, et le callback ou la Promise reçoit les métadonnées avec cet id. `copy(id, path)` écrit dans `path` comme nom de fichier quand il contient un point, sinon dans le répertoire `path` avec le nom stocké.\n\n`fs.clear()` (alias `drop()`) supprime tous les fichiers du stockage et l'index ; le callback reçoit le nombre de fichiers supprimés.\n\n## Lister les fichiers\n\n`fs.browse()` lit l'index `files.log` et renvoie un query builder NoSQL : tu peux donc filtrer, trier et paginer les fichiers comme dans [NoSQL](../nosql/) :\n\n```js\nFILESTORAGE('documents').browse().where('ext', 'pdf').sort('date', true).take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n`fs.browse2()` lit les en-têtes de tous les fichiers sur le disque au lieu de l'index, et `fs.stream(onfile, [callback], [workers])` parcourt les fichiers un par un. `fs.count2()` compte les fichiers sur le disque. `fs.rebuild()` réécrit l'index à partir des fichiers sur le disque, ce dont tu as besoin après avoir copié toi-même des fichiers dans le répertoire ou après `restore()`.\n\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tconsole.log(meta.id, meta.name, meta.size);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n## Sauvegarde et restauration\n\n`fs.backup(filename, [callback])` écrit tous les fichiers du stockage, chacun compressé avec GZIP, dans un seul fichier texte et renvoie `{ filename, files, size }`. `fs.restore(filename, [callback])` supprime les fichiers actuels et restaure la sauvegarde. L'index ne fait pas partie de la sauvegarde, alors appelle `rebuild()` après une restauration.\n\n```js\nvar fs = FILESTORAGE('documents');\nawait fs.backup(PATH.root('documents.backup'));\n\nfs.restore(PATH.root('documents.backup'), function(err) {\n\tfs.rebuild();\n});\n```\n\nPendant qu'un stockage est vidé, restauré ou que son index est reconstruit, ses appels `save()`, `read()`, `readbuffer()`, `copy()` et `clone()` attendent la fin de l'opération.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmB51jc60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/file-storage/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Archivio di file","summary":"Salva, leggi, servi e gestisci file binari con FILESTORAGE(), compresi i file caricati.","markdown":"---\ntitle: Archivio di file\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/file-storage/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Archivio di file\n\n> Salva, leggi, servi e gestisci file binari con FILESTORAGE(), compresi i file caricati.\n\nUn **archivio di file** conserva file binari (upload, documenti, immagini, esportazioni) sul disco con i tuoi identificatori. Non hai mai a che fare con i percorsi: salvi un file con un id e lo rileggi con lo stesso id. Ogni archivio è una directory con sottodirectory e un file di indice, e il nome, il content type, la dimensione e i dati personalizzati di ogni file viaggiano insieme al file stesso.\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save('avatar-100', 'me.jpg', PATH.root('me.jpg'), function(err, meta) {\n\t// meta.name === 'me.jpg', meta.type === 'image/jpeg', meta.width, meta.height\n});\n```\n\n`FILESTORAGE(name)` restituisce la stessa istanza per lo stesso nome per tutta la vita del processo, quindi chiamala ovunque ti serva. L'elenco completo dei metodi è nel riferimento di [Archivio di file](../../reference/file-storage/).\n\n## Dove vengono salvati i file\n\nUn archivio chiamato `photos` si trova in `/databases/fs-photos/`. Ogni file viene scritto in `{group}/{id}.file`, dove `{group}` è una directory di quattro cifre calcolata da un hash dell'id (`/databases/fs-photos/0417/avatar-100.file`), così gli archivi grandi non finiscono con migliaia di file in una sola directory. La directory viene creata al primo salvataggio.\n\nOgni `.file` inizia con un header di 2000 byte che contiene i metadati in JSON, seguito dal contenuto. L'archivio aggiunge anche una riga per ogni file salvato a `files.log`, un indice NoSQL usato da `browse()`. Cambia la directory di un archivio con `fs.storage(path)`:\n\n```js\nFILESTORAGE('backups').storage('/mnt/disk2/backups/');\n```\n\n## Salvare i file\n\n`fs.save(id, name, source, [custom], [callback], [expire], [headers])` (alias `insert()`) accetta quattro tipi di sorgente:\n\n- il percorso di un file sul disco,\n- un `Buffer`,\n- uno stream leggibile,\n- un URL `https://`, che viene scaricato (gli `headers` facoltativi vengono inviati con la richiesta; una risposta con stato 400 o superiore termina con un errore).\n\nL'id lo scegli tu; `UID()` ne fornisce uno univoco. `name` è il nome originale del file: la sua estensione decide il content type, e per i file JPEG, PNG, GIF e SVG larghezza e altezza vengono misurate durante il salvataggio. `custom` è qualsiasi valore che vuoi tenere insieme al file (il proprietario, una descrizione...). `expire` è un tempo come `'1 day'` o `'30 minutes'`: trascorso quel tempo il file non si può più leggere. Senza callback il metodo restituisce una `Promise`.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a Buffer, with custom data\nfs.save(UID(), 'note.txt', Buffer.from('Hello', 'utf8'), { userid: 'u1' }, function(err, meta) {\n\tconsole.log(meta.id, meta.size, meta.custom.userid);\n});\n\n// From a URL, as a Promise, expires in 7 days\nvar meta = await fs.save('logo', 'logo.png', 'https://www.example.com/logo.png', null, null, '7 days');\n```\n\nLa callback riceve i metadati del file salvato:\n\n| Proprietà | Contenuto |\n| --- | --- |\n| `id` | L'id del file |\n| `name` | Il nome del file (senza percorso, al massimo 250 caratteri) |\n| `ext` | L'estensione, in minuscolo e senza il punto |\n| `type` | Il content type, per esempio `image/png` |\n| `size` | La dimensione del contenuto in byte |\n| `width`, `height` | Le dimensioni delle immagini JPEG, PNG, GIF e SVG |\n| `custom` | I tuoi dati personalizzati, oppure `null` |\n| `date` | Quando il file è stato salvato |\n| `expire` | Quando il file scade, se l'hai impostato |\n\nSalvare di nuovo con un id esistente sostituisce il file. `fs.savejson(id, value, [callback])` è una scorciatoia che salva un valore come `{id}.json`.\n\n## File caricati\n\nI file di una richiesta `multipart/form-data` si trovano in `$.files`, sia in una route sia in un'azione. Ogni elemento è un `HttpFile`, e `file.fs(storage, id, [callback])` lo salva in un archivio con il suo nome originale. Il flag `@upload` fa sì che la route accetti solo richieste multipart; un flag di dimensione come `<10MB` alza il limite di dimensione del body.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', upload);\n};\n\nfunction upload($) {\n\n\tvar file = $.files[0];\n\n\tif (!file) {\n\t\t$.invalid('@(Select a file)');\n\t\treturn;\n\t}\n\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n}\n```\n\nPiù file vengono salvati uno dopo l'altro con `wait()`:\n\n```js\nfunction upload($) {\n\tvar output = [];\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), function(err, meta) {\n\t\t\tmeta && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, () => $.json(output));\n}\n```\n\nLe proprietà di `HttpFile` e i suoi altri metodi sono descritti in [Controller](../controller/).\n\n## Leggere i file\n\n| Metodo | La callback riceve |\n| --- | --- |\n| `fs.read(id, callback)` | `(err, meta)` con uno stream leggibile in `meta.stream` |\n| `fs.readmeta(id, callback)` | `(err, meta)`: solo l'header, il contenuto non viene letto |\n| `fs.readbuffer(id, callback)` | `(err, buffer, meta)`: l'intero contenuto |\n| `fs.readbase64(id, callback)` | `(err, base64, meta)`: il contenuto come stringa base64 |\n| `fs.readjson(id, callback)` | `(err, value, meta)`: il JSON interpretato |\n| `fs.image(id, callback)` | `(err, image, meta)`: un oggetto immagine di [Immagini](../images/) |\n\nUn file mancante termina con un errore del file system, uno scaduto con l'errore `File is expired`. Tranne `readjson()`, i metodi restituiscono una `Promise` senza callback; la promise si risolve con il secondo argomento della callback.\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.read('invoice-2025-001', function(err, meta) {\n\tif (err)\n\t\treturn;\n\tvar writer = F.Fs.createWriteStream(PATH.tmp(meta.name));\n\tmeta.stream.pipe(writer);\n});\n\nvar buffer = await fs.readbuffer('invoice-2025-001');\n```\n\nConsuma sempre `meta.stream` di `read()`: tiene aperto un file descriptor finché non termina. Passa `true` come terzo argomento di `read()` quando ti servono solo i metadati.\n\n## Servire i file via HTTP\n\n`fs.http($, opt)` invia un file salvato come risposta di una route. Imposta il content type, `Last-Modified` e gli header di cache HTTP, risponde `304` quando il browser ha la versione attuale, supporta le richieste `Range` (per spostarsi in audio e video) e risponde `404` quando il file non esiste o è scaduto. `$.filefs(name, id, [download], [check])` del controller è una scorciatoia per questo metodo.\n\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', file);\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction file($) {\n\tFILESTORAGE('files').http($, { id: $.params.id });\n}\n\nfunction download($) {\n\tFILESTORAGE('files').http($, {\n\t\tid: $.params.id,\n\t\tdownload: true,\n\t\tcheck: meta => meta.custom && meta.custom.public\n\t});\n}\n```\n\nLe opzioni sono:\n\n- `id`: l'id del file,\n- `download`: `true` invia il file come allegato con il suo nome salvato, una stringa imposta un altro nome, una funzione `(name, type)` restituisce il nome,\n- `check`: una funzione `(meta)`; quando restituisce `false` la risposta è `404`,\n- `image`: una funzione `(image)` chiamata con il controller come `this`, per trasformare le immagini JPEG, PNG e di altri formati prima che vengano inviate,\n- `cache`: una chiave; con `image`, l'immagine trasformata viene salvata nella directory temporanea con questa chiave e riutilizzata per le richieste successive.\n\n```js\nfunction thumbnail($) {\n\tvar id = $.params.id;\n\tFILESTORAGE('photos').http($, {\n\t\tid: id,\n\t\tcache: 'thumb-' + id,\n\t\timage: function(image) {\n\t\t\timage.resize(200, 200);\n\t\t\timage.quality(80);\n\t\t}\n\t});\n}\n```\n\nUn id che una volta ha dato `404` viene ricordato e riceve `404` fino alla successiva pulizia periodica del framework, quindi mantieni univoci gli id dei file rimossi.\n\n## Gestire i file\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename('note-1', 'renamed.txt');            // changes the stored name\nfs.copy('note-1', PATH.tmp());                  // writes the content to a directory or a file path\nfs.clone('note-1', 'note-2');                   // a new id with the same content\nfs.remove('note-2', function(err) {});          // deletes the file and its line in the index\n```\n\n`clone(id, [newid], [callback])` crea un id con `UID()` quando manca `newid`, e la callback o la Promise riceve i metadati con quell'id. `copy(id, path)` scrive in `path` come nome di file quando contiene un punto, altrimenti nella directory `path` con il nome salvato.\n\n`fs.clear()` (alias `drop()`) rimuove tutti i file dell'archivio e l'indice; la callback riceve il numero di file rimossi.\n\n## Elencare i file\n\n`fs.browse()` legge l'indice `files.log` e restituisce un query builder NoSQL, così puoi filtrare, ordinare e paginare i file come in [NoSQL](../nosql/):\n\n```js\nFILESTORAGE('documents').browse().where('ext', 'pdf').sort('date', true).take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n`fs.browse2()` legge gli header di tutti i file sul disco invece dell'indice, e `fs.stream(onfile, [callback], [workers])` scorre i file uno per uno. `fs.count2()` conta i file sul disco. `fs.rebuild()` riscrive l'indice a partire dai file sul disco, cosa che ti serve dopo aver copiato tu stesso dei file nella directory o dopo `restore()`.\n\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tconsole.log(meta.id, meta.name, meta.size);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n## Backup e ripristino\n\n`fs.backup(filename, [callback])` scrive tutti i file dell'archivio, ciascuno compresso con GZIP, in un unico file di testo e restituisce `{ filename, files, size }`. `fs.restore(filename, [callback])` rimuove i file attuali e ripristina il backup. L'indice non fa parte del backup, quindi chiama `rebuild()` dopo un ripristino.\n\n```js\nvar fs = FILESTORAGE('documents');\nawait fs.backup(PATH.root('documents.backup'));\n\nfs.restore(PATH.root('documents.backup'), function(err) {\n\tfs.rebuild();\n});\n```\n\nMentre un archivio viene svuotato, ripristinato o il suo indice viene ricostruito, le sue chiamate `save()`, `read()`, `readbuffer()`, `copy()` e `clone()` aspettano che l'operazione termini.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmB51jc60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/file-storage/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Úložisko súborov","summary":"Ukladaj, čítaj, servíruj a spravuj binárne súbory cez FILESTORAGE(), vrátane nahraných súborov.","markdown":"---\ntitle: \"Úložisko súborov\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/file-storage/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Úložisko súborov\n\n> Ukladaj, čítaj, servíruj a spravuj binárne súbory cez FILESTORAGE(), vrátane nahraných súborov.\n\n**Úložisko súborov** uchováva binárne súbory (nahrané súbory, dokumenty, obrázky, exporty) na disku pod tvojimi vlastnými identifikátormi. S cestami nikdy nepracuješ: súbor uložíš s id a s tým istým id ho prečítaš späť. Každé úložisko je priečinok s podpriečinkami a indexovým súborom a názov, typ obsahu, veľkosť a vlastné dáta každého súboru putujú spolu so samotným súborom.\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save('avatar-100', 'me.jpg', PATH.root('me.jpg'), function(err, meta) {\n\t// meta.name === 'me.jpg', meta.type === 'image/jpeg', meta.width, meta.height\n});\n```\n\n`FILESTORAGE(name)` vráti pre ten istý názov počas života procesu tú istú inštanciu, takže ho volaj všade, kde ho potrebuješ. Úplný zoznam metód je v referencii [Úložisko súborov](../../reference/file-storage/).\n\n## Kde sú súbory uložené\n\nÚložisko s názvom `photos` sa nachádza v `/databases/fs-photos/`. Každý súbor sa zapíše do `{group}/{id}.file`, kde `{group}` je štvorciferný priečinok vypočítaný z hashu id (`/databases/fs-photos/0417/avatar-100.file`), takže veľké úložiská neskončia s tisíckami súborov v jednom priečinku. Priečinok sa vytvorí pri prvom uložení.\n\nKaždý `.file` začína 2000-bajtovou hlavičkou, ktorá obsahuje metadáta ako JSON, a za ňou nasleduje obsah. Úložisko tiež pripojí jeden riadok za každý uložený súbor do `files.log`, NoSQL indexu, ktorý používa `browse()`. Priečinok úložiska zmeníš cez `fs.storage(path)`:\n\n```js\nFILESTORAGE('backups').storage('/mnt/disk2/backups/');\n```\n\n## Ukladanie súborov\n\n`fs.save(id, name, source, [custom], [callback], [expire], [headers])` (alias `insert()`) prijíma štyri druhy zdroja:\n\n- cestu k súboru na disku,\n- `Buffer`,\n- čitateľný stream,\n- URL `https://`, ktorá sa stiahne (voliteľné `headers` sa pošlú s požiadavkou; odpoveď so stavom 400 alebo vyšším skončí chybou).\n\nId je na tebe; `UID()` dá jedinečné. `name` je pôvodný názov súboru: jeho prípona určí typ obsahu a pri súboroch JPEG, PNG, GIF a SVG sa počas ukladania zmeria šírka a výška. `custom` je akákoľvek hodnota, ktorú chceš mať pri súbore (vlastník, popis...). `expire` je čas ako `'1 day'` alebo `'30 minutes'`: po tomto čase sa súbor už nedá prečítať. Bez callbacku metóda vráti `Promise`.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a Buffer, with custom data\nfs.save(UID(), 'note.txt', Buffer.from('Hello', 'utf8'), { userid: 'u1' }, function(err, meta) {\n\tconsole.log(meta.id, meta.size, meta.custom.userid);\n});\n\n// From a URL, as a Promise, expires in 7 days\nvar meta = await fs.save('logo', 'logo.png', 'https://www.example.com/logo.png', null, null, '7 days');\n```\n\nCallback dostane metadáta uloženého súboru:\n\n| Vlastnosť | Obsah |\n| --- | --- |\n| `id` | Id súboru |\n| `name` | Názov súboru (bez cesty, najviac 250 znakov) |\n| `ext` | Prípona, malými písmenami, bez bodky |\n| `type` | Typ obsahu, napríklad `image/png` |\n| `size` | Veľkosť obsahu v bajtoch |\n| `width`, `height` | Rozmery obrázkov JPEG, PNG, GIF a SVG |\n| `custom` | Tvoje vlastné dáta alebo `null` |\n| `date` | Kedy bol súbor uložený |\n| `expire` | Kedy súbor vyprší, ak si to nastavil |\n\nOpätovné uloženie s existujúcim id súbor nahradí. `fs.savejson(id, value, [callback])` je skratka, ktorá uloží hodnotu ako `{id}.json`.\n\n## Nahrané súbory\n\nSúbory požiadavky `multipart/form-data` sú v `$.files`, v trase rovnako ako v akcii. Každá položka je `HttpFile` a `file.fs(storage, id, [callback])` ju uloží do úložiska s jej pôvodným názvom súboru. Flag `@upload` zariadi, že trasa prijme iba multipart požiadavky; flag veľkosti ako `<10MB` zvýši limit veľkosti tela.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', upload);\n};\n\nfunction upload($) {\n\n\tvar file = $.files[0];\n\n\tif (!file) {\n\t\t$.invalid('@(Select a file)');\n\t\treturn;\n\t}\n\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n}\n```\n\nViacero súborov uložíš jeden po druhom cez `wait()`:\n\n```js\nfunction upload($) {\n\tvar output = [];\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), function(err, meta) {\n\t\t\tmeta && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, () => $.json(output));\n}\n```\n\nVlastnosti `HttpFile` a jeho ďalšie metódy sú opísané v [Kontrolér](../controller/).\n\n## Čítanie súborov\n\n| Metóda | Callback dostane |\n| --- | --- |\n| `fs.read(id, callback)` | `(err, meta)` s čitateľným streamom v `meta.stream` |\n| `fs.readmeta(id, callback)` | `(err, meta)`: iba hlavičku, obsah sa nečíta |\n| `fs.readbuffer(id, callback)` | `(err, buffer, meta)`: celý obsah |\n| `fs.readbase64(id, callback)` | `(err, base64, meta)`: obsah ako base64 reťazec |\n| `fs.readjson(id, callback)` | `(err, value, meta)`: sparsovaný JSON |\n| `fs.image(id, callback)` | `(err, image, meta)`: objekt obrázka z [Obrázky](../images/) |\n\nChýbajúci súbor skončí chybou zo súborového systému, súbor po expirácii chybou `File is expired`. Okrem `readjson()` metódy bez callbacku vracajú `Promise`; promise sa vyrieši s druhým argumentom callbacku.\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.read('invoice-2025-001', function(err, meta) {\n\tif (err)\n\t\treturn;\n\tvar writer = F.Fs.createWriteStream(PATH.tmp(meta.name));\n\tmeta.stream.pipe(writer);\n});\n\nvar buffer = await fs.readbuffer('invoice-2025-001');\n```\n\n`meta.stream` z `read()` vždy spotrebuj: drží otvorený deskriptor súboru, kým neskončí. Keď potrebuješ iba metadáta, odovzdaj `true` ako tretí argument `read()`.\n\n## Servírovanie súborov cez HTTP\n\n`fs.http($, opt)` pošle uložený súbor ako odpoveď trasy. Nastaví typ obsahu, `Last-Modified` a hlavičky HTTP cache, odpovie `304`, keď má prehliadač aktuálnu verziu, podporuje požiadavky `Range` (posúvanie v audiu a videu) a odpovie `404`, keď súbor neexistuje alebo vypršal. `$.filefs(name, id, [download], [check])` controllera je jeho skratka.\n\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', file);\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction file($) {\n\tFILESTORAGE('files').http($, { id: $.params.id });\n}\n\nfunction download($) {\n\tFILESTORAGE('files').http($, {\n\t\tid: $.params.id,\n\t\tdownload: true,\n\t\tcheck: meta => meta.custom && meta.custom.public\n\t});\n}\n```\n\nVoľby sú:\n\n- `id`: id súboru,\n- `download`: `true` pošle súbor ako prílohu s jeho uloženým názvom, reťazec nastaví iný názov, funkcia `(name, type)` vráti názov,\n- `check`: funkcia `(meta)`; keď vráti `false`, odpoveď je `404`,\n- `image`: funkcia `(image)` volaná s `this` ako controllerom, na úpravu obrázkov JPEG, PNG a iných pred odoslaním,\n- `cache`: kľúč; s `image` sa upravený obrázok uloží do dočasného priečinka pod týmto kľúčom a použije sa znova pri ďalších požiadavkách.\n\n```js\nfunction thumbnail($) {\n\tvar id = $.params.id;\n\tFILESTORAGE('photos').http($, {\n\t\tid: id,\n\t\tcache: 'thumb-' + id,\n\t\timage: function(image) {\n\t\t\timage.resize(200, 200);\n\t\t\timage.quality(80);\n\t\t}\n\t});\n}\n```\n\nId, ktoré raz skončilo s `404`, si framework zapamätá a odpovedá naň `404` až do ďalšieho pravidelného upratovania frameworku, takže id odstránených súborov drž jedinečné.\n\n## Správa súborov\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename('note-1', 'renamed.txt');            // changes the stored name\nfs.copy('note-1', PATH.tmp());                  // writes the content to a directory or a file path\nfs.clone('note-1', 'note-2');                   // a new id with the same content\nfs.remove('note-2', function(err) {});          // deletes the file and its line in the index\n```\n\n`clone(id, [newid], [callback])` vytvorí id cez `UID()`, keď `newid` chýba, a callback alebo Promise dostane metadáta s týmto id. `copy(id, path)` zapíše do `path` ako názvu súboru, keď obsahuje bodku, inak do priečinka `path` s uloženým názvom.\n\n`fs.clear()` (alias `drop()`) odstráni všetky súbory úložiska aj index; callback dostane počet odstránených súborov.\n\n## Výpis súborov\n\n`fs.browse()` prečíta index `files.log` a vráti NoSQL query builder, takže súbory môžeš filtrovať, triediť a stránkovať ako v [NoSQL](../nosql/):\n\n```js\nFILESTORAGE('documents').browse().where('ext', 'pdf').sort('date', true).take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n`fs.browse2()` namiesto indexu prečíta hlavičky všetkých súborov na disku a `fs.stream(onfile, [callback], [workers])` prechádza súbory jeden po druhom. `fs.count2()` spočíta súbory na disku. `fs.rebuild()` znova zapíše index zo súborov na disku, čo potrebuješ, keď si súbory do priečinka skopíroval sám, alebo po `restore()`.\n\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tconsole.log(meta.id, meta.name, meta.size);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n## Záloha a obnova\n\n`fs.backup(filename, [callback])` zapíše všetky súbory úložiska, každý skomprimovaný cez GZIP, do jedného textového súboru a vráti `{ filename, files, size }`. `fs.restore(filename, [callback])` odstráni aktuálne súbory a obnoví zálohu. Index nie je súčasťou zálohy, takže po obnove zavolaj `rebuild()`.\n\n```js\nvar fs = FILESTORAGE('documents');\nawait fs.backup(PATH.root('documents.backup'));\n\nfs.restore(PATH.root('documents.backup'), function(err) {\n\tfs.rebuild();\n});\n```\n\nKým sa úložisko maže, obnovuje alebo sa znova zostavuje jeho index, jeho volania `save()`, `read()`, `readbuffer()`, `copy()` a `clone()` čakajú, kým operácia neskončí.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwvC98x61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Plugins and components","summary":"Plugins in the plugins/ folder, PLUGINS, UI bundles from COMPONENTATOR(), server components with NEWCOMPONENT(), and NPMINSTALL(), REQUIRE() and IMPORT().","markdown":"---\ntitle: Plugins and components\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/plugins-and-components/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# Plugins and components\n\n> Plugins in the plugins/ folder, PLUGINS, UI bundles from COMPONENTATOR(), server components with NEWCOMPONENT(), and NPMINSTALL(), REQUIRE() and IMPORT().\n\nA **plugin** is a folder in `plugins/` that packs one feature of the application: its own controllers, actions, schemas, public files and views. Total.js loads every plugin at start, together with the files of the application, so a plugin works like a small application inside the main one.\n\nThis page also covers **components**: UI component bundles downloaded from Componentator with `COMPONENTATOR()`, server components compiled with `NEWCOMPONENT()`, and the helpers that load code at run time: `NPMINSTALL()`, `REQUIRE()` and `IMPORT()`. The full list of methods is in the reference [Plugins and components](../../reference/plugins-and-components/).\n\n## Structure of a plugin\n\n```text\nplugins/\n\tshop/\n\t\tindex.js          <- required: the plugin definition\n\t\tcontrollers/      <- routes of the plugin\n\t\tactions/\n\t\tschemas/\n\t\tmodels/\n\t\tdefinitions/\n\t\textensions/\n\t\tmiddleware/\n\t\tpublic/           <- static files, served as /_shop/...\n\t\tviews/            <- views, rendered as #shop/views/...\n```\n\nThe name of the folder is the **id** of the plugin. A folder without an `index.js` file is skipped, together with all its subfolders. Folders whose name contains `-bk` or `_bk` are skipped too, so you can switch a plugin off by renaming `shop` to `shop-bk`.\n\n## index.js\n\n`index.js` is an ordinary Node.js module. Total.js requires it, stores it in `PLUGINS` under the id of the plugin and calls its `install()` function.\n\n```js\n// plugins/shop/index.js\nexports.icon = 'ti ti-shopping-cart';\nexports.name = 'Shop';\nexports.position = 3;\nexports.permissions = [{ id: 'shop', name: 'Shop' }, { id: 'shop_orders', name: 'Orders' }];\nexports.visible = user => user.sa || user.permissions.includes('shop');\n\nexports.install = function() {\n\tROUTE('+API    ?    shop_orders    --> Shop/orders');\n\tON('ready', function() {\n\t\t// the whole application is loaded\n\t});\n};\n```\n\nThe framework itself reads only these properties:\n\n| Property | What Total.js does with it |\n| --- | --- |\n| `exports.install` | Called once, when the plugin is loaded |\n| `exports.id` | Set to the folder name when you do not define it |\n| `exports.name` | Written with the id and the permissions to the source map of the application (debug mode) |\n| `exports.permissions` | An array of strings or objects with `id`; the ids are written to the source map |\n\nAny other property, such as `icon`, `position` or `visible`, is yours: your administration UI reads it from `PLUGINS` to build a menu or to hide items the user may not open.\n\n## Files inside a plugin\n\nThese subfolders of a plugin are loaded exactly like the folders of the same name in the root of the application: every `.js` file is required and its `install()` is called.\n\n| Folder | Content |\n| --- | --- |\n| `controllers/` | Routes, see [Routing](../routing/) |\n| `actions/` | `NEWACTION()` definitions, see [Actions](../actions/) |\n| `schemas/` | Schemas and actions, see [JSON schemas](../json-schemas/) |\n| `models/`, `definitions/`, `extensions/` | Shared code, delegates, prototypes |\n| `middleware/` | `NEWMIDDLEWARE()` definitions, see [Middleware](../middleware/) |\n\nAll plugins and all application files share one global space: a route, an action or a schema declared in a plugin is available everywhere. Use the plugin id as a prefix of names (`Shop/orders`, `/admin/shop/`) to avoid conflicts.\n\n```js\n// plugins/shop/controllers/api.js\nexports.install = function() {\n\tROUTE('+API    ?    shop_products    --> Shop/products');\n\tROUTE('+GET    /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n## Public files, views and templates\n\n- **Public files**: a URL that starts with `/_` and the plugin id is served from the `public/` folder of the plugin. `/_shop/css/shop.css` reads `plugins/shop/public/css/shop.css` (see [Static files](../static-files/)).\n- **Views**: a view name that starts with `#` is relative to the `plugins/` folder: `$.view('#shop/views/index')` renders `plugins/shop/views/index.html` (see [Views](../views/)).\n- **Templates**: `TEMPLATE('#shop/templates/order.html', model)` reads `plugins/shop/templates/order.html`. `.html` is added when the name does not contain it.\n- **Paths**: `PATH.plugins('shop/data.json')` returns the absolute path of a file in the plugins folder.\n\nIn debug mode the `plugins/` folder is watched like `controllers/`: a change of a script restarts the application.\n\n## Configuration of a plugin\n\nA plugin can have a `config` file next to its `index.js`. It has the same format as the main `config` file (see [Configuration](../configuration/)) and is read before the scripts of the application and the plugins run, after the main `config`. Its keys are merged into `CONF`, so a plugin can bring its own defaults, and a key with the same name overrides the value from the main file.\n\n```text\n// plugins/shop/config\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n```js\n// plugins/shop/actions/products.js\nNEWACTION('Shop/products', {\n\taction: function($) {\n\t\tvar take = CONF.shop_pagesize;\n\t\t// ...\n\t\t$.success();\n\t}\n});\n```\n\n## FlowStream in a plugin\n\nWhen a plugin contains an `index.flow` file (a FlowStream export in JSON), Total.js reads it and starts the FlowStream right after the `index.js` of the plugin, before the other files of the plugin; the FlowStream is created asynchronously, so `PLUGINS[id].flowstream` is set once it is ready. The FlowStream gets the plugin id as its id, the plugin `name` (translated) as its name and the plugin folder as its directory. The running instance is stored in `PLUGINS[id].flowstream`. See [FlowStream](../flowstream/).\n\n```js\n// plugins/iot/index.js\nexports.name = 'IoT';\nexports.install = function() {\n\tON('ready', function() {\n\t\tsetTimeout(function() {\n\t\t\tvar flow = PLUGINS.iot.flowstream;\n\t\t\tflow && console.log('IoT FlowStream is running');\n\t\t}, 1000);\n\t});\n};\n```\n\n## PLUGINS\n\n`PLUGINS` is an object with all loaded plugins, by id. Each value is the `module.exports` object of the plugin `index.js`.\n\n```js\n// a menu for an admin panel\nROUTE('+GET /admin/plugins/', function($) {\n\tvar user = $.user;\n\tvar arr = [];\n\tfor (var id in PLUGINS) {\n\t\tvar plugin = PLUGINS[id];\n\t\tif (plugin.visible && !plugin.visible(user))\n\t\t\tcontinue;\n\t\tarr.push({ id: id, name: plugin.name, icon: plugin.icon, position: plugin.position });\n\t}\n\tarr.quicksort('position');\n\t$.json(arr);\n});\n```\n\n## UI components (COMPONENTATOR)\n\n`COMPONENTATOR(name, components, [removeprev], [attrs])` downloads one minified bundle of jComponent UI components from `https://componentator.com` into `public/`. The file is downloaded only when it does not exist yet, so call it in a definition file and keep it in the code.\n\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,aselected,page,viewbox,input,box,validate,loading,notify,message,errorhandler,empty,menu,colorpicker,icons,directory,miniform,preview,datagrid', true);\n```\n\nThe bundle is saved as `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` when `removeprev` is `false`); the hash comes from the list of components, so a different list gives a new file and (with `removeprev`, the default) the old bundle of the same name is deleted. The URL of the file is stored in `REPO[name]`, so a layout can load it:\n\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n## Server components (NEWCOMPONENT)\n\nA server component is an HTML file with a `<script total>` (or `<script node>`) block that holds the server code, optionally with `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` and `<template>` parts for a UI. `NEWCOMPONENT()` compiles it into a component object; you create instances of it and send them data.\n\n```html\n<!-- components/uppercase.html -->\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.config = { prefix: '' };\n\texports.inputs = [{ id: 'input', name: 'Text' }];\n\texports.outputs = [{ id: 'output', name: 'Result' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function(msg) {\n\t\t\tmsg.send('output', config.prefix + String(msg.data).toUpperCase());\n\t\t};\n\t};\n\n</script>\n<readme>\nConverts the text to upper case.\n</readme>\n```\n\n```js\nvar com = await NEWCOMPONENT('uppercase');   // reads components/uppercase.html\ncom.debugger = false;                       // do not print outputs to the console\n\nvar instance = com.create({ prefix: '> ' });\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);      // output > HELLO\n});\n```\n\n`NEWCOMPONENT()` accepts the name of a file in `components/`, the HTML itself, or an `https://` URL. Packages listed in `exports.npm` are installed with `NPMINSTALL()` before `exports.install()` runs. An instance can also emit data on its own with `instance.send(output, data)`, for example from a timer, and report progress with `instance.activity(key, name, value)`. An input with a `schema` (a schema string such as `'name:String, age:Number'`) validates the data: the cleaned data is in `msg.data` and errors in `msg.error`.\n\n## NPM packages and remote modules\n\n- `NPMINSTALL(name, [callback])` installs an NPM package into `CONF.$nodemodules` (the `node_modules` folder of the application) with `npm install`. It does nothing when the package is already there (and has the version from `name@version`).\n- `REQUIRE(name)` loads a module: Node.js built-in modules directly, other packages with `require()` and, when that fails, from `CONF.$nodemodules`.\n- `IMPORT(url, [callback])` downloads a JavaScript file into the temporary folder and requires it. A second call with the same URL in the same process returns the loaded module without downloading. An error page (status `400` or more) or a file that is not a module gives an error.\n\n```js\n// plugins/pdf/index.js\nexports.install = async function() {\n\tawait NPMINSTALL('pdfkit@0.15.0');\n\tvar PDFDocument = REQUIRE('pdfkit');\n\t// ...\n};\n```\n\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, module) {\n\tif (!err)\n\t\tmodule.hello();\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"JafwvC98x61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Plugins und Komponenten","summary":"Plugins im Ordner plugins/, PLUGINS, UI-Bundles aus COMPONENTATOR(), Server-Komponenten mit NEWCOMPONENT() sowie NPMINSTALL(), REQUIRE() und IMPORT().","markdown":"---\ntitle: Plugins und Komponenten\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/plugins-and-components/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# Plugins und Komponenten\n\n> Plugins im Ordner plugins/, PLUGINS, UI-Bundles aus COMPONENTATOR(), Server-Komponenten mit NEWCOMPONENT() sowie NPMINSTALL(), REQUIRE() und IMPORT().\n\nEin **Plugin** ist ein Ordner in `plugins/`, der eine Funktion der Anwendung bündelt: eigene Controller, Aktionen, Schemas, öffentliche Dateien und Views. Total.js lädt jedes Plugin beim Start zusammen mit den Dateien der Anwendung, daher funktioniert ein Plugin wie eine kleine Anwendung innerhalb der Hauptanwendung.\n\nDiese Seite behandelt auch **Komponenten**: UI-Komponenten-Bundles, die mit `COMPONENTATOR()` von Componentator heruntergeladen werden, Server-Komponenten, die mit `NEWCOMPONENT()` kompiliert werden, und die Hilfsfunktionen, die Code zur Laufzeit laden: `NPMINSTALL()`, `REQUIRE()` und `IMPORT()`. Die vollständige Liste der Methoden steht in der Referenz [Plugins und Komponenten](../../reference/plugins-and-components/).\n\n## Aufbau eines Plugins\n\n```text\nplugins/\n\tshop/\n\t\tindex.js          <- required: the plugin definition\n\t\tcontrollers/      <- routes of the plugin\n\t\tactions/\n\t\tschemas/\n\t\tmodels/\n\t\tdefinitions/\n\t\textensions/\n\t\tmiddleware/\n\t\tpublic/           <- static files, served as /_shop/...\n\t\tviews/            <- views, rendered as #shop/views/...\n```\n\nDer Name des Ordners ist die **id** des Plugins. Ein Ordner ohne Datei `index.js` wird übersprungen, zusammen mit all seinen Unterordnern. Ordner, deren Name `-bk` oder `_bk` enthält, werden ebenfalls übersprungen. So kannst du ein Plugin abschalten, indem du `shop` in `shop-bk` umbenennst.\n\n## index.js\n\n`index.js` ist ein gewöhnliches Node.js-Modul. Total.js lädt es per require, speichert es in `PLUGINS` unter der id des Plugins und ruft seine Funktion `install()` auf.\n\n```js\n// plugins/shop/index.js\nexports.icon = 'ti ti-shopping-cart';\nexports.name = 'Shop';\nexports.position = 3;\nexports.permissions = [{ id: 'shop', name: 'Shop' }, { id: 'shop_orders', name: 'Orders' }];\nexports.visible = user => user.sa || user.permissions.includes('shop');\n\nexports.install = function() {\n\tROUTE('+API    ?    shop_orders    --> Shop/orders');\n\tON('ready', function() {\n\t\t// the whole application is loaded\n\t});\n};\n```\n\nDas Framework selbst liest nur diese Eigenschaften:\n\n| Eigenschaft | Was Total.js damit macht |\n| --- | --- |\n| `exports.install` | Wird einmal aufgerufen, wenn das Plugin geladen wird |\n| `exports.id` | Wird auf den Ordnernamen gesetzt, wenn du sie nicht definierst |\n| `exports.name` | Wird mit der id und den Berechtigungen in die Source Map der Anwendung geschrieben (Debug-Modus) |\n| `exports.permissions` | Ein Array von Strings oder Objekten mit `id`; die ids werden in die Source Map geschrieben |\n\nJede andere Eigenschaft, etwa `icon`, `position` oder `visible`, gehört dir: Deine Administrationsoberfläche liest sie aus `PLUGINS`, um ein Menü zu bauen oder Einträge auszublenden, die der Benutzer nicht öffnen darf.\n\n## Dateien in einem Plugin\n\nDiese Unterordner eines Plugins werden genauso geladen wie die gleichnamigen Ordner im Stammverzeichnis der Anwendung: Jede `.js`-Datei wird per require geladen und ihr `install()` aufgerufen.\n\n| Ordner | Inhalt |\n| --- | --- |\n| `controllers/` | Routen, siehe [Routing](../routing/) |\n| `actions/` | `NEWACTION()`-Definitionen, siehe [Aktionen](../actions/) |\n| `schemas/` | Schemas und Aktionen, siehe [JSON-Schemas](../json-schemas/) |\n| `models/`, `definitions/`, `extensions/` | Gemeinsamer Code, Delegates, Prototypen |\n| `middleware/` | `NEWMIDDLEWARE()`-Definitionen, siehe [Middleware](../middleware/) |\n\nAlle Plugins und alle Dateien der Anwendung teilen sich einen globalen Raum: Eine Route, eine Aktion oder ein Schema, das in einem Plugin deklariert ist, ist überall verfügbar. Verwende die id des Plugins als Präfix von Namen (`Shop/orders`, `/admin/shop/`), um Konflikte zu vermeiden.\n\n```js\n// plugins/shop/controllers/api.js\nexports.install = function() {\n\tROUTE('+API    ?    shop_products    --> Shop/products');\n\tROUTE('+GET    /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n## Öffentliche Dateien, Views und Templates\n\n- **Öffentliche Dateien**: Eine URL, die mit `/_` und der id des Plugins beginnt, wird aus dem Ordner `public/` des Plugins ausgeliefert. `/_shop/css/shop.css` liest `plugins/shop/public/css/shop.css` (siehe [Statische Dateien](../static-files/)).\n- **Views**: Ein View-Name, der mit `#` beginnt, ist relativ zum Ordner `plugins/`: `$.view('#shop/views/index')` rendert `plugins/shop/views/index.html` (siehe [Views](../views/)).\n- **Templates**: `TEMPLATE('#shop/templates/order.html', model)` liest `plugins/shop/templates/order.html`. `.html` wird hinzugefügt, wenn der Name es nicht enthält.\n- **Pfade**: `PATH.plugins('shop/data.json')` gibt den absoluten Pfad einer Datei im Ordner plugins zurück.\n\nIm Debug-Modus wird der Ordner `plugins/` wie `controllers/` überwacht: Eine Änderung eines Skripts startet die Anwendung neu.\n\n## Konfiguration eines Plugins\n\nEin Plugin kann neben seiner `index.js` eine Datei `config` haben. Sie hat dasselbe Format wie die Hauptdatei `config` (siehe [Konfiguration](../configuration/)) und wird gelesen, bevor die Skripte der Anwendung und der Plugins laufen, nach der Haupt-`config`. Ihre Schlüssel werden in `CONF` zusammengeführt. So kann ein Plugin eigene Standardwerte mitbringen, und ein Schlüssel mit demselben Namen überschreibt den Wert aus der Hauptdatei.\n\n```text\n// plugins/shop/config\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n```js\n// plugins/shop/actions/products.js\nNEWACTION('Shop/products', {\n\taction: function($) {\n\t\tvar take = CONF.shop_pagesize;\n\t\t// ...\n\t\t$.success();\n\t}\n});\n```\n\n## FlowStream in einem Plugin\n\nWenn ein Plugin eine Datei `index.flow` enthält (ein FlowStream-Export in JSON), liest Total.js sie und startet den FlowStream direkt nach der `index.js` des Plugins, vor den anderen Dateien des Plugins; der FlowStream wird asynchron erstellt, daher wird `PLUGINS[id].flowstream` gesetzt, sobald er bereit ist. Der FlowStream erhält die id des Plugins als seine id, den `name` des Plugins (übersetzt) als seinen Namen und den Plugin-Ordner als sein Verzeichnis. Die laufende Instanz wird in `PLUGINS[id].flowstream` gespeichert. Siehe [FlowStream](../flowstream/).\n\n```js\n// plugins/iot/index.js\nexports.name = 'IoT';\nexports.install = function() {\n\tON('ready', function() {\n\t\tsetTimeout(function() {\n\t\t\tvar flow = PLUGINS.iot.flowstream;\n\t\t\tflow && console.log('IoT FlowStream is running');\n\t\t}, 1000);\n\t});\n};\n```\n\n## PLUGINS\n\n`PLUGINS` ist ein Objekt mit allen geladenen Plugins, nach id. Jeder Wert ist das `module.exports`-Objekt der `index.js` des Plugins.\n\n```js\n// a menu for an admin panel\nROUTE('+GET /admin/plugins/', function($) {\n\tvar user = $.user;\n\tvar arr = [];\n\tfor (var id in PLUGINS) {\n\t\tvar plugin = PLUGINS[id];\n\t\tif (plugin.visible && !plugin.visible(user))\n\t\t\tcontinue;\n\t\tarr.push({ id: id, name: plugin.name, icon: plugin.icon, position: plugin.position });\n\t}\n\tarr.quicksort('position');\n\t$.json(arr);\n});\n```\n\n## UI-Komponenten (COMPONENTATOR)\n\n`COMPONENTATOR(name, components, [removeprev], [attrs])` lädt ein minifiziertes Bundle von jComponent-UI-Komponenten von `https://componentator.com` nach `public/` herunter. Die Datei wird nur heruntergeladen, wenn sie noch nicht existiert. Rufe es daher in einer Definitionsdatei auf und lass es im Code.\n\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,aselected,page,viewbox,input,box,validate,loading,notify,message,errorhandler,empty,menu,colorpicker,icons,directory,miniform,preview,datagrid', true);\n```\n\nDas Bundle wird als `public/ui-<name>-<hash>.min.js` gespeichert (`public/ui-<hash>.min.js`, wenn `removeprev` gleich `false` ist); der Hash ergibt sich aus der Liste der Komponenten. Eine andere Liste ergibt also eine neue Datei, und (mit `removeprev`, dem Standard) wird das alte Bundle mit demselben Namen gelöscht. Die URL der Datei wird in `REPO[name]` gespeichert, sodass ein Layout sie laden kann:\n\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n## Server-Komponenten (NEWCOMPONENT)\n\nEine Server-Komponente ist eine HTML-Datei mit einem Block `<script total>` (oder `<script node>`), der den Server-Code enthält, optional mit den Teilen `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` und `<template>` für eine UI. `NEWCOMPONENT()` kompiliert sie in ein Komponenten-Objekt; du erzeugst Instanzen davon und schickst ihnen Daten.\n\n```html\n<!-- components/uppercase.html -->\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.config = { prefix: '' };\n\texports.inputs = [{ id: 'input', name: 'Text' }];\n\texports.outputs = [{ id: 'output', name: 'Result' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function(msg) {\n\t\t\tmsg.send('output', config.prefix + String(msg.data).toUpperCase());\n\t\t};\n\t};\n\n</script>\n<readme>\nConverts the text to upper case.\n</readme>\n```\n\n```js\nvar com = await NEWCOMPONENT('uppercase');   // reads components/uppercase.html\ncom.debugger = false;                       // do not print outputs to the console\n\nvar instance = com.create({ prefix: '> ' });\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);      // output > HELLO\n});\n```\n\n`NEWCOMPONENT()` akzeptiert den Namen einer Datei in `components/`, das HTML selbst oder eine `https://`-URL. Pakete, die in `exports.npm` aufgeführt sind, werden mit `NPMINSTALL()` installiert, bevor `exports.install()` läuft. Eine Instanz kann mit `instance.send(output, data)` auch selbst Daten senden, zum Beispiel aus einem Timer, und mit `instance.activity(key, name, value)` einen Fortschritt melden. Ein Eingang mit einem `schema` (einem Schema-String wie `'name:String, age:Number'`) validiert die Daten: Die bereinigten Daten stehen in `msg.data` und Fehler in `msg.error`.\n\n## NPM-Pakete und entfernte Module\n\n- `NPMINSTALL(name, [callback])` installiert ein NPM-Paket mit `npm install` in `CONF.$nodemodules` (den Ordner `node_modules` der Anwendung). Es tut nichts, wenn das Paket bereits vorhanden ist (und die Version aus `name@version` hat).\n- `REQUIRE(name)` lädt ein Modul: eingebaute Node.js-Module direkt, andere Pakete mit `require()` und, wenn das fehlschlägt, aus `CONF.$nodemodules`.\n- `IMPORT(url, [callback])` lädt eine JavaScript-Datei in den temporären Ordner herunter und lädt sie per require. Ein zweiter Aufruf mit derselben URL im selben Prozess gibt das geladene Modul zurück, ohne erneut herunterzuladen. Eine Fehlerseite (Status `400` oder mehr) oder eine Datei, die kein Modul ist, führt zu einem Fehler.\n\n```js\n// plugins/pdf/index.js\nexports.install = async function() {\n\tawait NPMINSTALL('pdfkit@0.15.0');\n\tvar PDFDocument = REQUIRE('pdfkit');\n\t// ...\n};\n```\n\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, module) {\n\tif (!err)\n\t\tmodule.hello();\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"JafwvC98x61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Plugins y componentes","summary":"Plugins en la carpeta plugins/, PLUGINS, bundles de UI de COMPONENTATOR(), componentes de servidor con NEWCOMPONENT(), y NPMINSTALL(), REQUIRE() e IMPORT().","markdown":"---\ntitle: Plugins y componentes\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/plugins-and-components/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# Plugins y componentes\n\n> Plugins en la carpeta plugins/, PLUGINS, bundles de UI de COMPONENTATOR(), componentes de servidor con NEWCOMPONENT(), y NPMINSTALL(), REQUIRE() e IMPORT().\n\nUn **plugin** es una carpeta en `plugins/` que empaqueta una funcionalidad de la aplicación: sus propios controladores, acciones, esquemas, archivos públicos y vistas. Total.js carga cada plugin al arrancar, junto con los archivos de la aplicación, así que un plugin funciona como una pequeña aplicación dentro de la principal.\n\nEsta página también trata los **componentes**: bundles de componentes de UI descargados de Componentator con `COMPONENTATOR()`, componentes de servidor compilados con `NEWCOMPONENT()`, y los helpers que cargan código en tiempo de ejecución: `NPMINSTALL()`, `REQUIRE()` e `IMPORT()`. La lista completa de métodos está en la referencia [Plugins y componentes](../../reference/plugins-and-components/).\n\n## Estructura de un plugin\n\n```text\nplugins/\n\tshop/\n\t\tindex.js          <- required: the plugin definition\n\t\tcontrollers/      <- routes of the plugin\n\t\tactions/\n\t\tschemas/\n\t\tmodels/\n\t\tdefinitions/\n\t\textensions/\n\t\tmiddleware/\n\t\tpublic/           <- static files, served as /_shop/...\n\t\tviews/            <- views, rendered as #shop/views/...\n```\n\nEl nombre de la carpeta es el **id** del plugin. Una carpeta sin archivo `index.js` se omite, junto con todas sus subcarpetas. Las carpetas cuyo nombre contiene `-bk` o `_bk` también se omiten, así que puedes desactivar un plugin renombrando `shop` a `shop-bk`.\n\n## index.js\n\n`index.js` es un módulo normal de Node.js. Total.js lo carga con require, lo guarda en `PLUGINS` bajo el id del plugin y llama a su función `install()`.\n\n```js\n// plugins/shop/index.js\nexports.icon = 'ti ti-shopping-cart';\nexports.name = 'Shop';\nexports.position = 3;\nexports.permissions = [{ id: 'shop', name: 'Shop' }, { id: 'shop_orders', name: 'Orders' }];\nexports.visible = user => user.sa || user.permissions.includes('shop');\n\nexports.install = function() {\n\tROUTE('+API    ?    shop_orders    --> Shop/orders');\n\tON('ready', function() {\n\t\t// the whole application is loaded\n\t});\n};\n```\n\nEl framework solo lee estas propiedades:\n\n| Propiedad | Qué hace Total.js con ella |\n| --- | --- |\n| `exports.install` | Se llama una vez, cuando se carga el plugin |\n| `exports.id` | Se establece al nombre de la carpeta si no lo defines |\n| `exports.name` | Se escribe con el id y los permisos en el mapa de fuentes de la aplicación (modo debug) |\n| `exports.permissions` | Un array de strings u objetos con `id`; los ids se escriben en el mapa de fuentes |\n\nCualquier otra propiedad, como `icon`, `position` o `visible`, es tuya: tu UI de administración la lee de `PLUGINS` para construir un menú u ocultar elementos que el usuario no puede abrir.\n\n## Archivos dentro de un plugin\n\nEstas subcarpetas de un plugin se cargan exactamente igual que las carpetas del mismo nombre en la raíz de la aplicación: cada archivo `.js` se carga con require y se llama a su `install()`.\n\n| Carpeta | Contenido |\n| --- | --- |\n| `controllers/` | Rutas, consulta [Enrutamiento](../routing/) |\n| `actions/` | Definiciones `NEWACTION()`, consulta [Acciones](../actions/) |\n| `schemas/` | Esquemas y acciones, consulta [Esquemas JSON](../json-schemas/) |\n| `models/`, `definitions/`, `extensions/` | Código compartido, delegados, prototipos |\n| `middleware/` | Definiciones `NEWMIDDLEWARE()`, consulta [Middleware](../middleware/) |\n\nTodos los plugins y todos los archivos de la aplicación comparten un único espacio global: una ruta, una acción o un esquema declarado en un plugin está disponible en todas partes. Usa el id del plugin como prefijo de los nombres (`Shop/orders`, `/admin/shop/`) para evitar conflictos.\n\n```js\n// plugins/shop/controllers/api.js\nexports.install = function() {\n\tROUTE('+API    ?    shop_products    --> Shop/products');\n\tROUTE('+GET    /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n## Archivos públicos, vistas y plantillas\n\n- **Archivos públicos**: una URL que empieza por `/_` y el id del plugin se sirve desde la carpeta `public/` del plugin. `/_shop/css/shop.css` lee `plugins/shop/public/css/shop.css` (consulta [Archivos estáticos](../static-files/)).\n- **Vistas**: un nombre de vista que empieza por `#` es relativo a la carpeta `plugins/`: `$.view('#shop/views/index')` renderiza `plugins/shop/views/index.html` (consulta [Vistas](../views/)).\n- **Plantillas**: `TEMPLATE('#shop/templates/order.html', model)` lee `plugins/shop/templates/order.html`. Se añade `.html` cuando el nombre no lo contiene.\n- **Rutas de archivo**: `PATH.plugins('shop/data.json')` devuelve la ruta absoluta de un archivo en la carpeta de plugins.\n\nEn modo debug la carpeta `plugins/` se vigila igual que `controllers/`: un cambio en un script reinicia la aplicación.\n\n## Configuración de un plugin\n\nUn plugin puede tener un archivo `config` junto a su `index.js`. Tiene el mismo formato que el archivo `config` principal (consulta [Configuración](../configuration/)) y se lee antes de que se ejecuten los scripts de la aplicación y de los plugins, después del `config` principal. Sus claves se fusionan en `CONF`, así que un plugin puede traer sus propios valores por defecto, y una clave con el mismo nombre sobrescribe el valor del archivo principal.\n\n```text\n// plugins/shop/config\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n```js\n// plugins/shop/actions/products.js\nNEWACTION('Shop/products', {\n\taction: function($) {\n\t\tvar take = CONF.shop_pagesize;\n\t\t// ...\n\t\t$.success();\n\t}\n});\n```\n\n## FlowStream en un plugin\n\nCuando un plugin contiene un archivo `index.flow` (una exportación de FlowStream en JSON), Total.js lo lee e inicia el FlowStream justo después del `index.js` del plugin, antes de los demás archivos del plugin; el FlowStream se crea de forma asíncrona, así que `PLUGINS[id].flowstream` se establece cuando está listo. El FlowStream recibe el id del plugin como su id, el `name` del plugin (traducido) como su nombre y la carpeta del plugin como su directorio. La instancia en ejecución se guarda en `PLUGINS[id].flowstream`. Consulta [FlowStream](../flowstream/).\n\n```js\n// plugins/iot/index.js\nexports.name = 'IoT';\nexports.install = function() {\n\tON('ready', function() {\n\t\tsetTimeout(function() {\n\t\t\tvar flow = PLUGINS.iot.flowstream;\n\t\t\tflow && console.log('IoT FlowStream is running');\n\t\t}, 1000);\n\t});\n};\n```\n\n## PLUGINS\n\n`PLUGINS` es un objeto con todos los plugins cargados, por id. Cada valor es el objeto `module.exports` del `index.js` del plugin.\n\n```js\n// a menu for an admin panel\nROUTE('+GET /admin/plugins/', function($) {\n\tvar user = $.user;\n\tvar arr = [];\n\tfor (var id in PLUGINS) {\n\t\tvar plugin = PLUGINS[id];\n\t\tif (plugin.visible && !plugin.visible(user))\n\t\t\tcontinue;\n\t\tarr.push({ id: id, name: plugin.name, icon: plugin.icon, position: plugin.position });\n\t}\n\tarr.quicksort('position');\n\t$.json(arr);\n});\n```\n\n## Componentes de UI (COMPONENTATOR)\n\n`COMPONENTATOR(name, components, [removeprev], [attrs])` descarga un bundle minificado de componentes de UI de jComponent desde `https://componentator.com` a `public/`. El archivo solo se descarga cuando aún no existe, así que llámalo en un archivo de definición y mantenlo en el código.\n\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,aselected,page,viewbox,input,box,validate,loading,notify,message,errorhandler,empty,menu,colorpicker,icons,directory,miniform,preview,datagrid', true);\n```\n\nEl bundle se guarda como `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` cuando `removeprev` es `false`); el hash proviene de la lista de componentes, así que una lista distinta genera un archivo nuevo y (con `removeprev`, el valor por defecto) se borra el bundle anterior con el mismo nombre. La URL del archivo se guarda en `REPO[name]`, para que una plantilla (layout) pueda cargarlo:\n\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n## Componentes de servidor (NEWCOMPONENT)\n\nUn componente de servidor es un archivo HTML con un bloque `<script total>` (o `<script node>`) que contiene el código del servidor, opcionalmente con partes `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` y `<template>` para una UI. `NEWCOMPONENT()` lo compila en un objeto componente; tú creas instancias de él y les envías datos.\n\n```html\n<!-- components/uppercase.html -->\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.config = { prefix: '' };\n\texports.inputs = [{ id: 'input', name: 'Text' }];\n\texports.outputs = [{ id: 'output', name: 'Result' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function(msg) {\n\t\t\tmsg.send('output', config.prefix + String(msg.data).toUpperCase());\n\t\t};\n\t};\n\n</script>\n<readme>\nConverts the text to upper case.\n</readme>\n```\n\n```js\nvar com = await NEWCOMPONENT('uppercase');   // reads components/uppercase.html\ncom.debugger = false;                       // do not print outputs to the console\n\nvar instance = com.create({ prefix: '> ' });\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);      // output > HELLO\n});\n```\n\n`NEWCOMPONENT()` acepta el nombre de un archivo en `components/`, el propio HTML o una URL `https://`. Los paquetes listados en `exports.npm` se instalan con `NPMINSTALL()` antes de que se ejecute `exports.install()`. Una instancia también puede emitir datos por sí misma con `instance.send(output, data)`, por ejemplo desde un temporizador, e informar del progreso con `instance.activity(key, name, value)`. Una entrada con un `schema` (un string de esquema como `'name:String, age:Number'`) valida los datos: los datos limpios están en `msg.data` y los errores en `msg.error`.\n\n## Paquetes NPM y módulos remotos\n\n- `NPMINSTALL(name, [callback])` instala un paquete NPM en `CONF.$nodemodules` (la carpeta `node_modules` de la aplicación) con `npm install`. No hace nada si el paquete ya está ahí (y tiene la versión de `name@version`).\n- `REQUIRE(name)` carga un módulo: los módulos integrados de Node.js directamente, otros paquetes con `require()` y, si eso falla, desde `CONF.$nodemodules`.\n- `IMPORT(url, [callback])` descarga un archivo JavaScript a la carpeta temporal y lo carga con require. Una segunda llamada con la misma URL en el mismo proceso devuelve el módulo ya cargado sin descargarlo. Una página de error (estado `400` o más) o un archivo que no es un módulo da un error.\n\n```js\n// plugins/pdf/index.js\nexports.install = async function() {\n\tawait NPMINSTALL('pdfkit@0.15.0');\n\tvar PDFDocument = REQUIRE('pdfkit');\n\t// ...\n};\n```\n\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, module) {\n\tif (!err)\n\t\tmodule.hello();\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"JafwvC98x61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Plugins et composants","summary":"Les plugins du dossier plugins/, PLUGINS, les bundles UI de COMPONENTATOR(), les composants serveur avec NEWCOMPONENT(), ainsi que NPMINSTALL(), REQUIRE() et IMPORT().","markdown":"---\ntitle: Plugins et composants\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/plugins-and-components/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# Plugins et composants\n\n> Les plugins du dossier plugins/, PLUGINS, les bundles UI de COMPONENTATOR(), les composants serveur avec NEWCOMPONENT(), ainsi que NPMINSTALL(), REQUIRE() et IMPORT().\n\nUn **plugin** est un dossier dans `plugins/` qui regroupe une fonctionnalité de l'application : ses propres contrôleurs, actions, schémas, fichiers publics et vues. Total.js charge chaque plugin au démarrage, avec les fichiers de l'application, si bien qu'un plugin fonctionne comme une petite application à l'intérieur de l'application principale.\n\nCette page couvre aussi les **composants** : les bundles de composants UI téléchargés depuis Componentator avec `COMPONENTATOR()`, les composants serveur compilés avec `NEWCOMPONENT()`, et les helpers qui chargent du code à l'exécution : `NPMINSTALL()`, `REQUIRE()` et `IMPORT()`. La liste complète des méthodes se trouve dans la référence [Plugins et composants](../../reference/plugins-and-components/).\n\n## Structure d'un plugin\n\n```text\nplugins/\n\tshop/\n\t\tindex.js          <- required: the plugin definition\n\t\tcontrollers/      <- routes of the plugin\n\t\tactions/\n\t\tschemas/\n\t\tmodels/\n\t\tdefinitions/\n\t\textensions/\n\t\tmiddleware/\n\t\tpublic/           <- static files, served as /_shop/...\n\t\tviews/            <- views, rendered as #shop/views/...\n```\n\nLe nom du dossier est l'**id** du plugin. Un dossier sans fichier `index.js` est ignoré, avec tous ses sous-dossiers. Les dossiers dont le nom contient `-bk` ou `_bk` sont ignorés aussi : tu peux donc désactiver un plugin en renommant `shop` en `shop-bk`.\n\n## index.js\n\n`index.js` est un module Node.js ordinaire. Total.js le charge avec require, le stocke dans `PLUGINS` sous l'id du plugin et appelle sa fonction `install()`.\n\n```js\n// plugins/shop/index.js\nexports.icon = 'ti ti-shopping-cart';\nexports.name = 'Shop';\nexports.position = 3;\nexports.permissions = [{ id: 'shop', name: 'Shop' }, { id: 'shop_orders', name: 'Orders' }];\nexports.visible = user => user.sa || user.permissions.includes('shop');\n\nexports.install = function() {\n\tROUTE('+API    ?    shop_orders    --> Shop/orders');\n\tON('ready', function() {\n\t\t// the whole application is loaded\n\t});\n};\n```\n\nLe framework lui-même ne lit que ces propriétés :\n\n| Propriété | Ce que Total.js en fait |\n| --- | --- |\n| `exports.install` | Appelée une fois, au chargement du plugin |\n| `exports.id` | Définie avec le nom du dossier si tu ne la définis pas |\n| `exports.name` | Écrite avec l'id et les permissions dans la source map de l'application (mode debug) |\n| `exports.permissions` | Un tableau de chaînes ou d'objets avec `id` ; les ids sont écrits dans la source map |\n\nToute autre propriété, comme `icon`, `position` ou `visible`, t'appartient : ton interface d'administration la lit depuis `PLUGINS` pour construire un menu ou masquer les éléments que l'utilisateur ne peut pas ouvrir.\n\n## Fichiers à l'intérieur d'un plugin\n\nCes sous-dossiers d'un plugin sont chargés exactement comme les dossiers du même nom à la racine de l'application : chaque fichier `.js` est chargé avec require et son `install()` est appelé.\n\n| Dossier | Contenu |\n| --- | --- |\n| `controllers/` | Routes, voir [Routage](../routing/) |\n| `actions/` | Définitions `NEWACTION()`, voir [Actions](../actions/) |\n| `schemas/` | Schémas et actions, voir [Schémas JSON](../json-schemas/) |\n| `models/`, `definitions/`, `extensions/` | Code partagé, délégués, prototypes |\n| `middleware/` | Définitions `NEWMIDDLEWARE()`, voir [Middleware](../middleware/) |\n\nTous les plugins et tous les fichiers de l'application partagent un même espace global : une route, une action ou un schéma déclaré dans un plugin est disponible partout. Utilise l'id du plugin comme préfixe des noms (`Shop/orders`, `/admin/shop/`) pour éviter les conflits.\n\n```js\n// plugins/shop/controllers/api.js\nexports.install = function() {\n\tROUTE('+API    ?    shop_products    --> Shop/products');\n\tROUTE('+GET    /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n## Fichiers publics, vues et templates\n\n- **Fichiers publics** : une URL qui commence par `/_` et l'id du plugin est servie depuis le dossier `public/` du plugin. `/_shop/css/shop.css` lit `plugins/shop/public/css/shop.css` (voir [Fichiers statiques](../static-files/)).\n- **Vues** : un nom de vue qui commence par `#` est relatif au dossier `plugins/` : `$.view('#shop/views/index')` affiche `plugins/shop/views/index.html` (voir [Vues](../views/)).\n- **Templates** : `TEMPLATE('#shop/templates/order.html', model)` lit `plugins/shop/templates/order.html`. `.html` est ajouté lorsque le nom ne le contient pas.\n- **Chemins** : `PATH.plugins('shop/data.json')` renvoie le chemin absolu d'un fichier dans le dossier des plugins.\n\nEn mode debug, le dossier `plugins/` est surveillé comme `controllers/` : la modification d'un script redémarre l'application.\n\n## Configuration d'un plugin\n\nUn plugin peut avoir un fichier `config` à côté de son `index.js`. Il a le même format que le fichier `config` principal (voir [Configuration](../configuration/)) et il est lu avant l'exécution des scripts de l'application et des plugins, après le `config` principal. Ses clés sont fusionnées dans `CONF` : un plugin peut ainsi apporter ses propres valeurs par défaut, et une clé du même nom remplace la valeur du fichier principal.\n\n```text\n// plugins/shop/config\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n```js\n// plugins/shop/actions/products.js\nNEWACTION('Shop/products', {\n\taction: function($) {\n\t\tvar take = CONF.shop_pagesize;\n\t\t// ...\n\t\t$.success();\n\t}\n});\n```\n\n## FlowStream dans un plugin\n\nQuand un plugin contient un fichier `index.flow` (un export FlowStream en JSON), Total.js le lit et démarre le FlowStream juste après le `index.js` du plugin, avant les autres fichiers du plugin ; le FlowStream est créé de manière asynchrone, donc `PLUGINS[id].flowstream` est défini dès qu'il est prêt. Le FlowStream reçoit l'id du plugin comme id, le `name` du plugin (traduit) comme nom et le dossier du plugin comme répertoire. L'instance en cours d'exécution est stockée dans `PLUGINS[id].flowstream`. Voir [FlowStream](../flowstream/).\n\n```js\n// plugins/iot/index.js\nexports.name = 'IoT';\nexports.install = function() {\n\tON('ready', function() {\n\t\tsetTimeout(function() {\n\t\t\tvar flow = PLUGINS.iot.flowstream;\n\t\t\tflow && console.log('IoT FlowStream is running');\n\t\t}, 1000);\n\t});\n};\n```\n\n## PLUGINS\n\n`PLUGINS` est un objet qui contient tous les plugins chargés, par id. Chaque valeur est l'objet `module.exports` du `index.js` du plugin.\n\n```js\n// a menu for an admin panel\nROUTE('+GET /admin/plugins/', function($) {\n\tvar user = $.user;\n\tvar arr = [];\n\tfor (var id in PLUGINS) {\n\t\tvar plugin = PLUGINS[id];\n\t\tif (plugin.visible && !plugin.visible(user))\n\t\t\tcontinue;\n\t\tarr.push({ id: id, name: plugin.name, icon: plugin.icon, position: plugin.position });\n\t}\n\tarr.quicksort('position');\n\t$.json(arr);\n});\n```\n\n## Composants UI (COMPONENTATOR)\n\n`COMPONENTATOR(name, components, [removeprev], [attrs])` télécharge un bundle minifié de composants UI jComponent depuis `https://componentator.com` dans `public/`. Le fichier n'est téléchargé que s'il n'existe pas encore : appelle-le donc dans un fichier de définition et garde-le dans le code.\n\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,aselected,page,viewbox,input,box,validate,loading,notify,message,errorhandler,empty,menu,colorpicker,icons,directory,miniform,preview,datagrid', true);\n```\n\nLe bundle est enregistré sous `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` lorsque `removeprev` vaut `false`) ; le hash dépend de la liste des composants, donc une autre liste donne un nouveau fichier et (avec `removeprev`, la valeur par défaut) l'ancien bundle du même nom est supprimé. L'URL du fichier est stockée dans `REPO[name]`, afin qu'un layout puisse le charger :\n\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n## Composants serveur (NEWCOMPONENT)\n\nUn composant serveur est un fichier HTML avec un bloc `<script total>` (ou `<script node>`) qui contient le code serveur, éventuellement avec des parties `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` et `<template>` pour une UI. `NEWCOMPONENT()` le compile en un objet composant ; tu en crées des instances et tu leur envoies des données.\n\n```html\n<!-- components/uppercase.html -->\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.config = { prefix: '' };\n\texports.inputs = [{ id: 'input', name: 'Text' }];\n\texports.outputs = [{ id: 'output', name: 'Result' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function(msg) {\n\t\t\tmsg.send('output', config.prefix + String(msg.data).toUpperCase());\n\t\t};\n\t};\n\n</script>\n<readme>\nConverts the text to upper case.\n</readme>\n```\n\n```js\nvar com = await NEWCOMPONENT('uppercase');   // reads components/uppercase.html\ncom.debugger = false;                       // do not print outputs to the console\n\nvar instance = com.create({ prefix: '> ' });\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);      // output > HELLO\n});\n```\n\n`NEWCOMPONENT()` accepte le nom d'un fichier dans `components/`, le HTML lui-même ou une URL `https://`. Les paquets listés dans `exports.npm` sont installés avec `NPMINSTALL()` avant l'exécution de `exports.install()`. Une instance peut aussi émettre des données d'elle-même avec `instance.send(output, data)`, par exemple depuis un timer, et signaler sa progression avec `instance.activity(key, name, value)`. Une entrée avec un `schema` (une chaîne de schéma comme `'name:String, age:Number'`) valide les données : les données nettoyées sont dans `msg.data` et les erreurs dans `msg.error`.\n\n## Paquets NPM et modules distants\n\n- `NPMINSTALL(name, [callback])` installe un paquet NPM dans `CONF.$nodemodules` (le dossier `node_modules` de l'application) avec `npm install`. Il ne fait rien quand le paquet est déjà présent (et a la version de `name@version`).\n- `REQUIRE(name)` charge un module : les modules intégrés de Node.js directement, les autres paquets avec `require()` et, en cas d'échec, depuis `CONF.$nodemodules`.\n- `IMPORT(url, [callback])` télécharge un fichier JavaScript dans le dossier temporaire et le charge avec require. Un second appel avec la même URL dans le même processus renvoie le module chargé sans le télécharger. Une page d'erreur (statut `400` ou plus) ou un fichier qui n'est pas un module donne une erreur.\n\n```js\n// plugins/pdf/index.js\nexports.install = async function() {\n\tawait NPMINSTALL('pdfkit@0.15.0');\n\tvar PDFDocument = REQUIRE('pdfkit');\n\t// ...\n};\n```\n\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, module) {\n\tif (!err)\n\t\tmodule.hello();\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"JafwvC98x61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Plugin e componenti","summary":"Plugin nella cartella plugins/, PLUGINS, bundle UI da COMPONENTATOR(), componenti server con NEWCOMPONENT(), e NPMINSTALL(), REQUIRE() e IMPORT().","markdown":"---\ntitle: Plugin e componenti\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/plugins-and-components/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# Plugin e componenti\n\n> Plugin nella cartella plugins/, PLUGINS, bundle UI da COMPONENTATOR(), componenti server con NEWCOMPONENT(), e NPMINSTALL(), REQUIRE() e IMPORT().\n\nUn **plugin** è una cartella in `plugins/` che racchiude una funzionalità dell'applicazione: i propri controller, azioni, schemi, file pubblici e viste. Total.js carica ogni plugin all'avvio, insieme ai file dell'applicazione, quindi un plugin funziona come una piccola applicazione dentro quella principale.\n\nQuesta pagina tratta anche i **componenti**: bundle di componenti UI scaricati da Componentator con `COMPONENTATOR()`, componenti server compilati con `NEWCOMPONENT()` e gli helper che caricano codice in fase di esecuzione: `NPMINSTALL()`, `REQUIRE()` e `IMPORT()`. L'elenco completo dei metodi è nel riferimento [Plugin e componenti](../../reference/plugins-and-components/).\n\n## Struttura di un plugin\n\n```text\nplugins/\n\tshop/\n\t\tindex.js          <- required: the plugin definition\n\t\tcontrollers/      <- routes of the plugin\n\t\tactions/\n\t\tschemas/\n\t\tmodels/\n\t\tdefinitions/\n\t\textensions/\n\t\tmiddleware/\n\t\tpublic/           <- static files, served as /_shop/...\n\t\tviews/            <- views, rendered as #shop/views/...\n```\n\nIl nome della cartella è l'**id** del plugin. Una cartella senza il file `index.js` viene saltata, insieme a tutte le sue sottocartelle. Vengono saltate anche le cartelle il cui nome contiene `-bk` o `_bk`, quindi puoi disattivare un plugin rinominando `shop` in `shop-bk`.\n\n## index.js\n\n`index.js` è un normale modulo Node.js. Total.js lo carica con require, lo salva in `PLUGINS` sotto l'id del plugin e chiama la sua funzione `install()`.\n\n```js\n// plugins/shop/index.js\nexports.icon = 'ti ti-shopping-cart';\nexports.name = 'Shop';\nexports.position = 3;\nexports.permissions = [{ id: 'shop', name: 'Shop' }, { id: 'shop_orders', name: 'Orders' }];\nexports.visible = user => user.sa || user.permissions.includes('shop');\n\nexports.install = function() {\n\tROUTE('+API    ?    shop_orders    --> Shop/orders');\n\tON('ready', function() {\n\t\t// the whole application is loaded\n\t});\n};\n```\n\nIl framework legge solo queste proprietà:\n\n| Proprietà | Cosa ne fa Total.js |\n| --- | --- |\n| `exports.install` | Chiamata una volta, quando il plugin viene caricato |\n| `exports.id` | Impostata sul nome della cartella se non la definisci |\n| `exports.name` | Scritta con l'id e i permessi nella source map dell'applicazione (modalità debug) |\n| `exports.permissions` | Un array di stringhe o di oggetti con `id`; gli id vengono scritti nella source map |\n\nQualsiasi altra proprietà, come `icon`, `position` o `visible`, è tua: la tua interfaccia di amministrazione la legge da `PLUGINS` per costruire un menu o nascondere le voci che l'utente non può aprire.\n\n## File all'interno di un plugin\n\nQueste sottocartelle di un plugin vengono caricate esattamente come le cartelle con lo stesso nome nella radice dell'applicazione: ogni file `.js` viene caricato con require e viene chiamata la sua `install()`.\n\n| Cartella | Contenuto |\n| --- | --- |\n| `controllers/` | Route, vedi [Routing](../routing/) |\n| `actions/` | Definizioni `NEWACTION()`, vedi [Azioni](../actions/) |\n| `schemas/` | Schemi e azioni, vedi [Schemi JSON](../json-schemas/) |\n| `models/`, `definitions/`, `extensions/` | Codice condiviso, delegate, prototipi |\n| `middleware/` | Definizioni `NEWMIDDLEWARE()`, vedi [Middleware](../middleware/) |\n\nTutti i plugin e tutti i file dell'applicazione condividono un unico spazio globale: una route, un'azione o uno schema dichiarati in un plugin sono disponibili ovunque. Usa l'id del plugin come prefisso dei nomi (`Shop/orders`, `/admin/shop/`) per evitare conflitti.\n\n```js\n// plugins/shop/controllers/api.js\nexports.install = function() {\n\tROUTE('+API    ?    shop_products    --> Shop/products');\n\tROUTE('+GET    /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n## File pubblici, viste e template\n\n- **File pubblici**: un URL che inizia con `/_` e l'id del plugin viene servito dalla cartella `public/` del plugin. `/_shop/css/shop.css` legge `plugins/shop/public/css/shop.css` (vedi [File statici](../static-files/)).\n- **Viste**: un nome di vista che inizia con `#` è relativo alla cartella `plugins/`: `$.view('#shop/views/index')` renderizza `plugins/shop/views/index.html` (vedi [Viste](../views/)).\n- **Template**: `TEMPLATE('#shop/templates/order.html', model)` legge `plugins/shop/templates/order.html`. `.html` viene aggiunto quando il nome non lo contiene.\n- **Percorsi**: `PATH.plugins('shop/data.json')` restituisce il percorso assoluto di un file nella cartella dei plugin.\n\nIn modalità debug la cartella `plugins/` è monitorata come `controllers/`: una modifica a uno script riavvia l'applicazione.\n\n## Configurazione di un plugin\n\nUn plugin può avere un file `config` accanto al suo `index.js`. Ha lo stesso formato del file `config` principale (vedi [Configurazione](../configuration/)) e viene letto prima che vengano eseguiti gli script dell'applicazione e dei plugin, dopo il `config` principale. Le sue chiavi vengono unite in `CONF`, quindi un plugin può portare i propri valori predefiniti, e una chiave con lo stesso nome sovrascrive il valore del file principale.\n\n```text\n// plugins/shop/config\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n```js\n// plugins/shop/actions/products.js\nNEWACTION('Shop/products', {\n\taction: function($) {\n\t\tvar take = CONF.shop_pagesize;\n\t\t// ...\n\t\t$.success();\n\t}\n});\n```\n\n## FlowStream in un plugin\n\nQuando un plugin contiene un file `index.flow` (un export FlowStream in JSON), Total.js lo legge e avvia il FlowStream subito dopo l'`index.js` del plugin, prima degli altri file del plugin; il FlowStream viene creato in modo asincrono, quindi `PLUGINS[id].flowstream` viene impostato quando è pronto. Il FlowStream riceve l'id del plugin come id, il `name` del plugin (tradotto) come nome e la cartella del plugin come directory. L'istanza in esecuzione viene salvata in `PLUGINS[id].flowstream`. Vedi [FlowStream](../flowstream/).\n\n```js\n// plugins/iot/index.js\nexports.name = 'IoT';\nexports.install = function() {\n\tON('ready', function() {\n\t\tsetTimeout(function() {\n\t\t\tvar flow = PLUGINS.iot.flowstream;\n\t\t\tflow && console.log('IoT FlowStream is running');\n\t\t}, 1000);\n\t});\n};\n```\n\n## PLUGINS\n\n`PLUGINS` è un oggetto con tutti i plugin caricati, per id. Ogni valore è l'oggetto `module.exports` dell'`index.js` del plugin.\n\n```js\n// a menu for an admin panel\nROUTE('+GET /admin/plugins/', function($) {\n\tvar user = $.user;\n\tvar arr = [];\n\tfor (var id in PLUGINS) {\n\t\tvar plugin = PLUGINS[id];\n\t\tif (plugin.visible && !plugin.visible(user))\n\t\t\tcontinue;\n\t\tarr.push({ id: id, name: plugin.name, icon: plugin.icon, position: plugin.position });\n\t}\n\tarr.quicksort('position');\n\t$.json(arr);\n});\n```\n\n## Componenti UI (COMPONENTATOR)\n\n`COMPONENTATOR(name, components, [removeprev], [attrs])` scarica un bundle minificato di componenti UI jComponent da `https://componentator.com` in `public/`. Il file viene scaricato solo se non esiste ancora, quindi chiamalo in un file di definizione e lascialo nel codice.\n\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,aselected,page,viewbox,input,box,validate,loading,notify,message,errorhandler,empty,menu,colorpicker,icons,directory,miniform,preview,datagrid', true);\n```\n\nIl bundle viene salvato come `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` quando `removeprev` è `false`); l'hash deriva dall'elenco dei componenti, quindi un elenco diverso produce un nuovo file e (con `removeprev`, il valore predefinito) il vecchio bundle con lo stesso nome viene eliminato. L'URL del file viene salvato in `REPO[name]`, così un layout può caricarlo:\n\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n## Componenti server (NEWCOMPONENT)\n\nUn componente server è un file HTML con un blocco `<script total>` (o `<script node>`) che contiene il codice server, facoltativamente con le parti `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` e `<template>` per una UI. `NEWCOMPONENT()` lo compila in un oggetto componente; ne crei delle istanze e invii loro dei dati.\n\n```html\n<!-- components/uppercase.html -->\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.config = { prefix: '' };\n\texports.inputs = [{ id: 'input', name: 'Text' }];\n\texports.outputs = [{ id: 'output', name: 'Result' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function(msg) {\n\t\t\tmsg.send('output', config.prefix + String(msg.data).toUpperCase());\n\t\t};\n\t};\n\n</script>\n<readme>\nConverts the text to upper case.\n</readme>\n```\n\n```js\nvar com = await NEWCOMPONENT('uppercase');   // reads components/uppercase.html\ncom.debugger = false;                       // do not print outputs to the console\n\nvar instance = com.create({ prefix: '> ' });\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);      // output > HELLO\n});\n```\n\n`NEWCOMPONENT()` accetta il nome di un file in `components/`, l'HTML stesso o un URL `https://`. I pacchetti elencati in `exports.npm` vengono installati con `NPMINSTALL()` prima che venga eseguito `exports.install()`. Un'istanza può anche emettere dati da sola con `instance.send(output, data)`, per esempio da un timer, e segnalare l'avanzamento con `instance.activity(key, name, value)`. Un input con uno `schema` (una stringa di schema come `'name:String, age:Number'`) valida i dati: i dati puliti sono in `msg.data` e gli errori in `msg.error`.\n\n## Pacchetti NPM e moduli remoti\n\n- `NPMINSTALL(name, [callback])` installa un pacchetto NPM in `CONF.$nodemodules` (la cartella `node_modules` dell'applicazione) con `npm install`. Non fa nulla se il pacchetto è già presente (e ha la versione indicata in `name@version`).\n- `REQUIRE(name)` carica un modulo: i moduli integrati di Node.js direttamente, gli altri pacchetti con `require()` e, se questo fallisce, da `CONF.$nodemodules`.\n- `IMPORT(url, [callback])` scarica un file JavaScript nella cartella temporanea e lo carica con require. Una seconda chiamata con lo stesso URL nello stesso processo restituisce il modulo già caricato senza scaricarlo. Una pagina di errore (stato `400` o superiore) o un file che non è un modulo dà un errore.\n\n```js\n// plugins/pdf/index.js\nexports.install = async function() {\n\tawait NPMINSTALL('pdfkit@0.15.0');\n\tvar PDFDocument = REQUIRE('pdfkit');\n\t// ...\n};\n```\n\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, module) {\n\tif (!err)\n\t\tmodule.hello();\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"JafwvC98x61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Pluginy a komponenty","summary":"Pluginy v priečinku plugins/, PLUGINS, UI balíky z COMPONENTATOR(), serverové komponenty s NEWCOMPONENT() a NPMINSTALL(), REQUIRE() a IMPORT().","markdown":"---\ntitle: Pluginy a komponenty\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/plugins-and-components/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# Pluginy a komponenty\n\n> Pluginy v priečinku plugins/, PLUGINS, UI balíky z COMPONENTATOR(), serverové komponenty s NEWCOMPONENT() a NPMINSTALL(), REQUIRE() a IMPORT().\n\n**Plugin** je priečinok v `plugins/`, ktorý zabaľuje jednu funkciu aplikácie: vlastné controllery, akcie, schémy, verejné súbory a view. Total.js načíta každý plugin pri štarte spolu so súbormi aplikácie, takže plugin funguje ako malá aplikácia vnútri hlavnej.\n\nTáto stránka pokrýva aj **komponenty**: balíky UI komponentov stiahnuté z Componentatora cez `COMPONENTATOR()`, serverové komponenty skompilované cez `NEWCOMPONENT()` a pomocné funkcie, ktoré načítajú kód za behu: `NPMINSTALL()`, `REQUIRE()` a `IMPORT()`. Úplný zoznam metód nájdeš v referencii [Pluginy a komponenty](../../reference/plugins-and-components/).\n\n## Štruktúra pluginu\n\n```text\nplugins/\n\tshop/\n\t\tindex.js          <- required: the plugin definition\n\t\tcontrollers/      <- routes of the plugin\n\t\tactions/\n\t\tschemas/\n\t\tmodels/\n\t\tdefinitions/\n\t\textensions/\n\t\tmiddleware/\n\t\tpublic/           <- static files, served as /_shop/...\n\t\tviews/            <- views, rendered as #shop/views/...\n```\n\nNázov priečinka je **id** pluginu. Priečinok bez súboru `index.js` sa preskočí aj so všetkými podpriečinkami. Preskočia sa aj priečinky, ktorých názov obsahuje `-bk` alebo `_bk`, takže plugin vypneš premenovaním `shop` na `shop-bk`.\n\n## index.js\n\n`index.js` je obyčajný modul Node.js. Total.js ho načíta cez require, uloží ho do `PLUGINS` pod id pluginu a zavolá jeho funkciu `install()`.\n\n```js\n// plugins/shop/index.js\nexports.icon = 'ti ti-shopping-cart';\nexports.name = 'Shop';\nexports.position = 3;\nexports.permissions = [{ id: 'shop', name: 'Shop' }, { id: 'shop_orders', name: 'Orders' }];\nexports.visible = user => user.sa || user.permissions.includes('shop');\n\nexports.install = function() {\n\tROUTE('+API    ?    shop_orders    --> Shop/orders');\n\tON('ready', function() {\n\t\t// the whole application is loaded\n\t});\n};\n```\n\nSamotný framework číta iba tieto vlastnosti:\n\n| Vlastnosť | Čo s ňou Total.js robí |\n| --- | --- |\n| `exports.install` | Zavolá sa raz, keď sa plugin načíta |\n| `exports.id` | Nastaví sa na názov priečinka, ak ho nedefinuješ |\n| `exports.name` | Zapíše sa spolu s id a oprávneniami do zdrojovej mapy aplikácie (debug režim) |\n| `exports.permissions` | Pole reťazcov alebo objektov s `id`; id sa zapíšu do zdrojovej mapy |\n\nKaždá iná vlastnosť, napríklad `icon`, `position` alebo `visible`, je tvoja: tvoje administračné UI ju číta z `PLUGINS`, aby zostavilo menu alebo skrylo položky, ktoré používateľ nesmie otvoriť.\n\n## Súbory vnútri pluginu\n\nTieto podpriečinky pluginu sa načítajú presne ako rovnomenné priečinky v koreni aplikácie: každý súbor `.js` sa načíta cez require a zavolá sa jeho `install()`.\n\n| Priečinok | Obsah |\n| --- | --- |\n| `controllers/` | Routy, pozri [Routing](../routing/) |\n| `actions/` | Definície `NEWACTION()`, pozri [Akcie](../actions/) |\n| `schemas/` | Schémy a akcie, pozri [JSON schémy](../json-schemas/) |\n| `models/`, `definitions/`, `extensions/` | Zdieľaný kód, delegáty, prototypy |\n| `middleware/` | Definície `NEWMIDDLEWARE()`, pozri [Middleware](../middleware/) |\n\nVšetky pluginy a všetky súbory aplikácie zdieľajú jeden globálny priestor: routa, akcia alebo schéma deklarovaná v plugine je dostupná všade. Ako prefix názvov používaj id pluginu (`Shop/orders`, `/admin/shop/`), aby si sa vyhol konfliktom.\n\n```js\n// plugins/shop/controllers/api.js\nexports.install = function() {\n\tROUTE('+API    ?    shop_products    --> Shop/products');\n\tROUTE('+GET    /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n## Verejné súbory, view a šablóny\n\n- **Verejné súbory**: URL, ktorá začína `/_` a id pluginu, sa obsluhuje z priečinka `public/` pluginu. `/_shop/css/shop.css` číta `plugins/shop/public/css/shop.css` (pozri [Statické súbory](../static-files/)).\n- **View**: názov view, ktorý začína `#`, je relatívny k priečinku `plugins/`: `$.view('#shop/views/index')` vykreslí `plugins/shop/views/index.html` (pozri [View](../views/)).\n- **Šablóny**: `TEMPLATE('#shop/templates/order.html', model)` číta `plugins/shop/templates/order.html`. `.html` sa pridá, keď ho názov neobsahuje.\n- **Cesty**: `PATH.plugins('shop/data.json')` vráti absolútnu cestu k súboru v priečinku pluginov.\n\nV debug režime sa priečinok `plugins/` sleduje rovnako ako `controllers/`: zmena skriptu reštartuje aplikáciu.\n\n## Konfigurácia pluginu\n\nPlugin môže mať súbor `config` vedľa svojho `index.js`. Má rovnaký formát ako hlavný súbor `config` (pozri [Konfigurácia](../configuration/)) a číta sa pred spustením skriptov aplikácie a pluginov, po hlavnom `config`. Jeho kľúče sa zlúčia do `CONF`, takže plugin si môže priniesť vlastné predvolené hodnoty, a kľúč s rovnakým názvom prepíše hodnotu z hlavného súboru.\n\n```text\n// plugins/shop/config\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n```js\n// plugins/shop/actions/products.js\nNEWACTION('Shop/products', {\n\taction: function($) {\n\t\tvar take = CONF.shop_pagesize;\n\t\t// ...\n\t\t$.success();\n\t}\n});\n```\n\n## FlowStream v plugine\n\nKeď plugin obsahuje súbor `index.flow` (export FlowStreamu v JSON), Total.js ho prečíta a spustí FlowStream hneď po `index.js` pluginu, pred ostatnými súbormi pluginu; FlowStream sa vytvára asynchrónne, takže `PLUGINS[id].flowstream` sa nastaví, keď je pripravený. FlowStream dostane id pluginu ako svoje id, `name` pluginu (preložené) ako svoj názov a priečinok pluginu ako svoj adresár. Bežiaca inštancia je uložená v `PLUGINS[id].flowstream`. Pozri [FlowStream](../flowstream/).\n\n```js\n// plugins/iot/index.js\nexports.name = 'IoT';\nexports.install = function() {\n\tON('ready', function() {\n\t\tsetTimeout(function() {\n\t\t\tvar flow = PLUGINS.iot.flowstream;\n\t\t\tflow && console.log('IoT FlowStream is running');\n\t\t}, 1000);\n\t});\n};\n```\n\n## PLUGINS\n\n`PLUGINS` je objekt so všetkými načítanými pluginmi podľa id. Každá hodnota je objekt `module.exports` z `index.js` pluginu.\n\n```js\n// a menu for an admin panel\nROUTE('+GET /admin/plugins/', function($) {\n\tvar user = $.user;\n\tvar arr = [];\n\tfor (var id in PLUGINS) {\n\t\tvar plugin = PLUGINS[id];\n\t\tif (plugin.visible && !plugin.visible(user))\n\t\t\tcontinue;\n\t\tarr.push({ id: id, name: plugin.name, icon: plugin.icon, position: plugin.position });\n\t}\n\tarr.quicksort('position');\n\t$.json(arr);\n});\n```\n\n## UI komponenty (COMPONENTATOR)\n\n`COMPONENTATOR(name, components, [removeprev], [attrs])` stiahne jeden minifikovaný balík UI komponentov jComponent z `https://componentator.com` do `public/`. Súbor sa stiahne iba vtedy, keď ešte neexistuje, takže ho volaj v definičnom súbore a nechaj ho v kóde.\n\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,aselected,page,viewbox,input,box,validate,loading,notify,message,errorhandler,empty,menu,colorpicker,icons,directory,miniform,preview,datagrid', true);\n```\n\nBalík sa uloží ako `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js`, keď je `removeprev` `false`); hash vzniká zo zoznamu komponentov, takže iný zoznam dá nový súbor a (s `removeprev`, predvolene) sa starý balík s rovnakým názvom zmaže. URL súboru sa uloží do `REPO[name]`, takže ho layout môže načítať:\n\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n## Serverové komponenty (NEWCOMPONENT)\n\nServerový komponent je HTML súbor s blokom `<script total>` (alebo `<script node>`), ktorý obsahuje serverový kód, voliteľne s časťami `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` a `<template>` pre UI. `NEWCOMPONENT()` ho skompiluje do objektu komponentu; vytváraš z neho inštancie a posielaš im dáta.\n\n```html\n<!-- components/uppercase.html -->\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.config = { prefix: '' };\n\texports.inputs = [{ id: 'input', name: 'Text' }];\n\texports.outputs = [{ id: 'output', name: 'Result' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function(msg) {\n\t\t\tmsg.send('output', config.prefix + String(msg.data).toUpperCase());\n\t\t};\n\t};\n\n</script>\n<readme>\nConverts the text to upper case.\n</readme>\n```\n\n```js\nvar com = await NEWCOMPONENT('uppercase');   // reads components/uppercase.html\ncom.debugger = false;                       // do not print outputs to the console\n\nvar instance = com.create({ prefix: '> ' });\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);      // output > HELLO\n});\n```\n\n`NEWCOMPONENT()` prijíma názov súboru v `components/`, samotné HTML alebo URL `https://`. Balíky uvedené v `exports.npm` sa nainštalujú cez `NPMINSTALL()` pred spustením `exports.install()`. Inštancia môže dáta posielať aj sama cez `instance.send(output, data)`, napríklad z časovača, a hlásiť priebeh cez `instance.activity(key, name, value)`. Vstup so `schema` (reťazec schémy, napríklad `'name:String, age:Number'`) dáta validuje: vyčistené dáta sú v `msg.data` a chyby v `msg.error`.\n\n## NPM balíky a vzdialené moduly\n\n- `NPMINSTALL(name, [callback])` nainštaluje NPM balík do `CONF.$nodemodules` (priečinok `node_modules` aplikácie) cez `npm install`. Nerobí nič, ak tam balík už je (a má verziu z `name@version`).\n- `REQUIRE(name)` načíta modul: vstavané moduly Node.js priamo, ostatné balíky cez `require()` a keď to zlyhá, z `CONF.$nodemodules`.\n- `IMPORT(url, [callback])` stiahne JavaScript súbor do dočasného priečinka a načíta ho cez require. Druhé volanie s rovnakou URL v tom istom procese vráti načítaný modul bez sťahovania. Chybová stránka (stav `400` alebo vyšší) alebo súbor, ktorý nie je modul, vráti chybu.\n\n```js\n// plugins/pdf/index.js\nexports.install = async function() {\n\tawait NPMINSTALL('pdfkit@0.15.0');\n\tvar PDFDocument = REQUIRE('pdfkit');\n\t// ...\n};\n```\n\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, module) {\n\tif (!err)\n\t\tmodule.hello();\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"JafwTX7Fx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/flowstream/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"FlowStream","summary":"Visual data flows: loading FlowStreams, components, instances, messages and the Total.js Flow editor.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/flowstream/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# FlowStream\n\n> Visual data flows: loading FlowStreams, components, instances, messages and the Total.js Flow editor.\n\nFlowStream is the engine of visual data flows in Total.js. A flow is a set of **components** (small programs with inputs and outputs), their **instances** placed on a canvas, and the **connections** between them. Messages travel from the outputs of one instance to the inputs of others. The flows are designed in the Total.js Flow editor, which connects to your application through a WebSocket.\n\nThe engine is available as the global `Flow` (and its alias `FlowStream`). Every loaded flow is kept in `Flow.instances[id]`.\n\n## Loading a FlowStream\n\n`Flow.load(schema, [callback])` starts a FlowStream from its schema. The schema is a plain object: the source code of the components, the design (instances and connections) and the variables.\n\n```js\nFlow.load({ id: 'orders', name: 'Orders', components: {}, design: {}, variables: { token: '123' } }, function(err, flowstream) {\n\t// flowstream === Flow.instances.orders\n});\n```\n\n| Key | What it does |\n| --- | --- |\n| `id` | Identifier of the FlowStream (a random id when empty) |\n| `name` | Name shown in the editor (`id` when empty) |\n| `components` | Object: component id → source code of the component |\n| `design` | Object: instance id → `{ component, config, connections, x, y }` |\n| `variables` | Values available as `{name}` in the components |\n| `worker` | `'worker'` runs the flow in a worker thread, any other truthy value in a child process |\n| `memory` | With `worker`: the heap limit of the worker in MB (`--max-old-space-size` for a child process, `resourceLimits` for a worker thread) |\n| `proxypath` | URL path under which the HTTP server of a worker is reachable through the main app |\n| `cloning` | `false` disables cloning of message data between connections |\n| `paused` | `true` loads the flow paused |\n| `readonly` | `true` disables saving |\n| `import` | Comma-separated paths (from the app root) of modules whose `install(flow)` / `init(flow)` run on load |\n| `initscript` | JavaScript code executed with the FlowStream as `instance` |\n| `env` | A value available as `instance.env` in the components |\n\nWhen the application starts, every `*.flow` file in the `/flowstreams/` directory is loaded with `Flow.load()` (files with `-bk` or `_bk` in the name are skipped). A `.flow` file contains the schema as JSON.\n\nLoading a schema with an `id` that is already running reloads the running FlowStream with the new schema.\n\nEach time a FlowStream starts (also after the automatic restart of a worker), the framework emits the global event `flowstream`:\n\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream started:', flowstream.id);\n});\n```\n\nA plugin can contain its own flow: the file `/plugins/{name}/index.flow` is loaded with the plugin. Its `id` is the plugin id and the running FlowStream is stored in `PLUGINS[id].flowstream`. See [Plugins and components](../plugins-and-components/).\n\n## Editing with Total.js Flow\n\nThe editor talks to the FlowStream over a WebSocket. Create a route and pass the connection to `Flow.socket()`:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', socket);\n};\n\nfunction socket($) {\n\t$.autodestroy();\n\tFlow.socket($.params.id, $);\n}\n```\n\nOpen `https://flow.totaljs.com/?socket=` followed by the URL-encoded address of this WebSocket. The editor loads the components and the design, shows the status of the instances and saves every change back to the FlowStream.\n\nThe FlowStream does not write files. About 5 seconds after a change it emits `save` with the whole schema, and you store it yourself:\n\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nFor remote editing, `flowstream.edit([url])` opens a WebSocket client to a proxy (by default `wss://flow.totaljs.com/{id}/`), so the editor can reach a FlowStream that runs behind a firewall.\n\n## Components\n\nA component is text with HTML-like parts. The server code is in `<script total>` (or `<script node>`); `<settings>`, `<body>`, `<style>`, `<readme>` and a plain `<script>` are used by the editor.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-text';\n\texports.group = 'Common';\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\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tdata[config.field] = (data[config.field] || '').toUpperCase();\n\t\t\t$.send('output');\n\t\t};\n\n\t\tinstance.configure = function() {\n\t\t\tconfig = instance.config;\n\t\t};\n\n\t};\n\n</script>\n\n<readme>\nConverts a field to upper case.\n</readme>\n```\n\n`exports.make(instance, config)` runs once for each instance of the component on the canvas. Inside it you assign delegates to the instance: `message` (an incoming message), `configure` (new configuration), `close` (the instance is removed), `variables` (the variables have changed), `trigger` (the trigger button in the editor), `service` (called every minute) and others.\n\n`exports.npm = ['package']` installs the NPM packages before the component is registered. `exports.install` and `exports.uninstall` run when the component is registered and removed.\n\n## Messages\n\nThe `message` delegate receives a message, usually called `$`. `$.data` is the payload, `$.repo` is an object shared by all clones of the message, `$.input` and `$.output` are the ids of the input and the output. `$.send(output, [data])` sends a clone to every instance connected to the output; the clones of the data are deep copies unless the flow has `cloning: false`. `$.send(null)` sends to all outputs; the message ends once, after the clones of all outputs end. A message that is not sent further must be ended with `$.end()`.\n\n```js\ninstance.message = function($) {\n\tif ($.data.price > 100)\n\t\t$.send('expensive');\n\telse\n\t\t$.send('cheap', { price: $.data.price });\n};\n```\n\nThe fourth argument of `$.send()` filters the targets: `$.send('output', null, null, function(from, to, output, input) { return to.component !== 'debug'; })`.\n\nWithout an incoming message, an instance starts a new one with `instance.send(output, data)` (for example from a timer or from `trigger`). `instance.send(null, data)` sends to all outputs. The status of an instance (shown under it in the editor) is set with `instance.status(data)`, errors are reported with `instance.throw(err)`. The flow keeps the last 10 errors in `instance.main.errors`; the reset command of the editor clears them and the flow engine emits `reset`, so an instance can clear its own state too:\n\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\nThe next example starts messages from a timer and shows the time of the last one as the status:\n\n```js\nexports.make = function(instance, config) {\n\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: NOW });\n\t\tinstance.status({ last: NOW });\n\t}, 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n\n};\n```\n\n## Instance data\n\n`instance.config` is the configuration from the editor merged into `exports.config`. `instance.cache` is a plain object for your own runtime data; it is kept in memory for the instance id when the instance is initialized again (for example after its component is updated). Call `instance.save()` after you change `config` from the code: the flow is saved and the editor is redrawn (`instance.save(false)` saves without redrawing).\n\n`instance.repo` is an object stored in the design together with the instance. It survives a reload and a restart, and the editor does not change it.\n\n## Activities\n\nA long task can report its progress to the editor. `instance.activity(key, name, [progress])` creates or updates an activity of the instance; `progress` is a number (percent). Progress `100` or an empty `name` removes the activity.\n\n```js\ninstance.message = function($) {\n\tinstance.activity('import', 'Importing products', 0);\n\timportproducts($.data, function(percentage) {\n\t\tinstance.activity('import', 'Importing products', percentage);\n\t}, function() {\n\t\tinstance.activity('import', 'Importing products', 100);\n\t\t$.send('output');\n\t});\n};\n```\n\n## Variables\n\nThe variables of the flow are replaced in strings with `instance.replace(text)` (or `$.variables(text)` in a message). A `{name}` placeholder takes the value from the variables of the flow, the secrets, `{hostname}` or the given data object.\n\n```js\nvar url = instance.replace('https://api.example.com/orders/?token={token}');\n```\n\n`flowstream.variables(obj)` replaces the variables of a running flow; the instances are notified by their `variables` delegate.\n\n## Controlling a FlowStream from code\n\n`Flow.instances[id]` is the running FlowStream. It works the same for flows in the main process and in workers.\n\n```js\nvar flowstream = Flow.instances.orders;\n\n// Executes the \"trigger\" delegate of an instance\nflowstream.trigger('instanceid', { manual: true });\n\n// Sends data to an instance and waits for the end of the message\nflowstream.send('instanceid', { id: 1 }, function(err, response) {\n\tconsole.log(response.data, response.duration);\n});\n\nflowstream.pause(true);\nflowstream.reconfigure('instanceid', { field: 'title' });\nflowstream.export(function(err, schema) {});\n```\n\nInstance ids can be replaced by `@component` (instances of a component id) or `#name` (instances of a component name).\n\n`Flow.remove(id)` stops a FlowStream and removes it.\n\n## Workers\n\nWith `worker: 'worker'` (a worker thread) or `worker: 'process'` (a child process) the flow runs outside the main process, so a broken component cannot block the application. A worker that exits is started again automatically after a second. `memory: 512` limits the heap of the worker to 512 MB. `flowstream.restart()` or `Flow.restart(id)` ends a worker so that it starts again with the current schema. For a flow in the main process, `instance.main.restart()` (and the restart command of the editor) asks the Total.js process manager to restart the whole application.\n\nWith `proxypath`, the worker runs its own HTTP server on a Unix socket and the main application forwards requests under that path to it. `proxytimeout` sets the timeout of that proxy; it is applied when the schema is loaded again into the running FlowStream.\n\n`flowstream.stats` contains the counters: `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` (messages in the last minute) and `paused`. For a flow in the main process, `online` is the number of editors connected to it. For flows in workers, `Flow.on('stats', function(id, stats) {})` receives the counters every 15 seconds.\n\n## Notifications\n\n`Flow.notify($, id)` passes an HTTP request to the `notify` delegate of an instance. The `id` is `flowid-instanceid`. Register the routes yourself:\n\n```js\nexports.install = function() {\n\tROUTE('GET /notify/{id}/', notify);\n\tROUTE('POST /notify/{id}/ <1MB', notify);\n};\n\nfunction notify($) {\n\tFlow.notify($, $.params.id);\n}\n```\n\n## TMS sources\n\nIn the editor you can add a TMS source (a URL and a token of another Total.js app). The FlowStream connects to it and creates Publish, Subscribe and Call components from the source's schemas, so messages can cross applications. The sources are saved in the `sources` key of the schema. See [Message Service (TMS)](../message-service-and-apis/).\n\n## Testing a component\n\n`Flow.test(name, source, [config], init)` loads a single component in a test flow and gives you a `Test` object:\n\n```js\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER', 'uppercase');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n## The flow5 command\n\nThe `total5` package installs the `flow5` command. It loads one or more schemas from files or HTTPS URLs and starts an HTTP server with the WebSocket route for the editor:\n\n```bash\nflow5 orders.json 8001\n```\n\nChanges made in the editor are written back to the JSON files. See [Command line](../command-line/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwTX7Fx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/flowstream/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"FlowStream","summary":"Visuelle Datenflüsse: FlowStreams laden, Komponenten, Instanzen, Nachrichten und der Editor Total.js Flow.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/flowstream/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# FlowStream\n\n> Visuelle Datenflüsse: FlowStreams laden, Komponenten, Instanzen, Nachrichten und der Editor Total.js Flow.\n\nFlowStream ist die Engine für visuelle Datenflüsse in Total.js. Ein Flow ist eine Menge von **Komponenten** (kleinen Programmen mit Eingängen und Ausgängen), ihren auf einer Arbeitsfläche platzierten **Instanzen** und den **Verbindungen** zwischen ihnen. Nachrichten wandern von den Ausgängen einer Instanz zu den Eingängen anderer. Die Flows werden im Editor Total.js Flow entworfen, der sich über einen WebSocket mit deiner Anwendung verbindet.\n\nDie Engine ist als globales `Flow` verfügbar (und unter seinem Alias `FlowStream`). Jeder geladene Flow wird in `Flow.instances[id]` gehalten.\n\n## Einen FlowStream laden\n\n`Flow.load(schema, [callback])` startet einen FlowStream aus seinem Schema. Das Schema ist ein einfaches Objekt: der Quellcode der Komponenten, das Design (Instanzen und Verbindungen) und die Variablen.\n\n```js\nFlow.load({ id: 'orders', name: 'Orders', components: {}, design: {}, variables: { token: '123' } }, function(err, flowstream) {\n\t// flowstream === Flow.instances.orders\n});\n```\n\n| Schlüssel | Was er bewirkt |\n| --- | --- |\n| `id` | Bezeichner des FlowStreams (eine zufällige id, wenn leer) |\n| `name` | Im Editor angezeigter Name (`id`, wenn leer) |\n| `components` | Objekt: Komponenten-id → Quellcode der Komponente |\n| `design` | Objekt: Instanz-id → `{ component, config, connections, x, y }` |\n| `variables` | Werte, die in den Komponenten als `{name}` verfügbar sind |\n| `worker` | `'worker'` führt den Flow in einem Worker-Thread aus, jeder andere truthy Wert in einem Kindprozess |\n| `memory` | Mit `worker`: das Heap-Limit des Workers in MB (`--max-old-space-size` für einen Kindprozess, `resourceLimits` für einen Worker-Thread) |\n| `proxypath` | URL-Pfad, unter dem der HTTP-Server eines Workers über die Hauptanwendung erreichbar ist |\n| `cloning` | `false` schaltet das Klonen der Nachrichtendaten zwischen Verbindungen ab |\n| `paused` | `true` lädt den Flow pausiert |\n| `readonly` | `true` schaltet das Speichern ab |\n| `import` | Kommagetrennte Pfade (ab dem Stammverzeichnis der Anwendung) von Modulen, deren `install(flow)` / `init(flow)` beim Laden laufen |\n| `initscript` | JavaScript-Code, der mit dem FlowStream als `instance` ausgeführt wird |\n| `env` | Ein Wert, der in den Komponenten als `instance.env` verfügbar ist |\n\nBeim Start der Anwendung wird jede Datei `*.flow` im Verzeichnis `/flowstreams/` mit `Flow.load()` geladen (Dateien mit `-bk` oder `_bk` im Namen werden übersprungen). Eine `.flow`-Datei enthält das Schema als JSON.\n\nWird ein Schema mit einer `id` geladen, die bereits läuft, wird der laufende FlowStream mit dem neuen Schema neu geladen.\n\nJedes Mal, wenn ein FlowStream startet (auch nach dem automatischen Neustart eines Workers), sendet das Framework das globale Event `flowstream`:\n\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream started:', flowstream.id);\n});\n```\n\nEin Plugin kann seinen eigenen Flow enthalten: Die Datei `/plugins/{name}/index.flow` wird mit dem Plugin geladen. Die `id` des Flows ist die id des Plugins, und der laufende FlowStream wird in `PLUGINS[id].flowstream` gespeichert. Siehe [Plugins und Komponenten](../plugins-and-components/).\n\n## Bearbeiten mit Total.js Flow\n\nDer Editor kommuniziert mit dem FlowStream über einen WebSocket. Erstelle eine Route und übergib die Verbindung an `Flow.socket()`:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', socket);\n};\n\nfunction socket($) {\n\t$.autodestroy();\n\tFlow.socket($.params.id, $);\n}\n```\n\nÖffne `https://flow.totaljs.com/?socket=` gefolgt von der URL-kodierten Adresse dieses WebSockets. Der Editor lädt die Komponenten und das Design, zeigt den Status der Instanzen an und speichert jede Änderung zurück in den FlowStream.\n\nDer FlowStream schreibt keine Dateien. Etwa 5 Sekunden nach einer Änderung sendet er `save` mit dem gesamten Schema, und du speicherst es selbst:\n\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nFür die entfernte Bearbeitung öffnet `flowstream.edit([url])` einen WebSocket-Client zu einem Proxy (standardmäßig `wss://flow.totaljs.com/{id}/`), sodass der Editor einen FlowStream erreichen kann, der hinter einer Firewall läuft.\n\n## Komponenten\n\nEine Komponente ist Text mit HTML-ähnlichen Teilen. Der Server-Code steht in `<script total>` (oder `<script node>`); `<settings>`, `<body>`, `<style>`, `<readme>` und ein einfaches `<script>` werden vom Editor verwendet.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-text';\n\texports.group = 'Common';\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\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tdata[config.field] = (data[config.field] || '').toUpperCase();\n\t\t\t$.send('output');\n\t\t};\n\n\t\tinstance.configure = function() {\n\t\t\tconfig = instance.config;\n\t\t};\n\n\t};\n\n</script>\n\n<readme>\nConverts a field to upper case.\n</readme>\n```\n\n`exports.make(instance, config)` läuft einmal für jede Instanz der Komponente auf der Arbeitsfläche. Darin weist du der Instanz Delegates zu: `message` (eine eingehende Nachricht), `configure` (neue Konfiguration), `close` (die Instanz wird entfernt), `variables` (die Variablen haben sich geändert), `trigger` (der Trigger-Button im Editor), `service` (wird jede Minute aufgerufen) und weitere.\n\n`exports.npm = ['package']` installiert die NPM-Pakete, bevor die Komponente registriert wird. `exports.install` und `exports.uninstall` laufen, wenn die Komponente registriert bzw. entfernt wird.\n\n## Nachrichten\n\nDas Delegate `message` empfängt eine Nachricht, meist `$` genannt. `$.data` ist der Payload, `$.repo` ist ein Objekt, das alle Klone der Nachricht teilen, `$.input` und `$.output` sind die ids des Eingangs und des Ausgangs. `$.send(output, [data])` sendet einen Klon an jede Instanz, die mit dem Ausgang verbunden ist; die Klone der Daten sind tiefe Kopien, außer der Flow hat `cloning: false`. `$.send(null)` sendet an alle Ausgänge; die Nachricht endet einmal, nachdem die Klone aller Ausgänge beendet sind. Eine Nachricht, die nicht weitergesendet wird, muss mit `$.end()` beendet werden.\n\n```js\ninstance.message = function($) {\n\tif ($.data.price > 100)\n\t\t$.send('expensive');\n\telse\n\t\t$.send('cheap', { price: $.data.price });\n};\n```\n\nDas vierte Argument von `$.send()` filtert die Ziele: `$.send('output', null, null, function(from, to, output, input) { return to.component !== 'debug'; })`.\n\nOhne eingehende Nachricht startet eine Instanz mit `instance.send(output, data)` eine neue (zum Beispiel aus einem Timer oder aus `trigger`). `instance.send(null, data)` sendet an alle Ausgänge. Der Status einer Instanz (im Editor darunter angezeigt) wird mit `instance.status(data)` gesetzt, Fehler werden mit `instance.throw(err)` gemeldet. Der Flow behält die letzten 10 Fehler in `instance.main.errors`; der Reset-Befehl des Editors löscht sie, und die Flow-Engine sendet `reset`, sodass auch eine Instanz ihren eigenen Zustand löschen kann:\n\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\nDas nächste Beispiel startet Nachrichten aus einem Timer und zeigt die Uhrzeit der letzten als Status an:\n\n```js\nexports.make = function(instance, config) {\n\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: NOW });\n\t\tinstance.status({ last: NOW });\n\t}, 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n\n};\n```\n\n## Instanzdaten\n\n`instance.config` ist die Konfiguration aus dem Editor, zusammengeführt mit `exports.config`. `instance.cache` ist ein einfaches Objekt für deine eigenen Laufzeitdaten; es wird für die Instanz-id im Speicher gehalten, wenn die Instanz erneut initialisiert wird (zum Beispiel nachdem ihre Komponente aktualisiert wurde). Rufe `instance.save()` auf, nachdem du `config` im Code geändert hast: Der Flow wird gespeichert und der Editor neu gezeichnet (`instance.save(false)` speichert ohne Neuzeichnen).\n\n`instance.repo` ist ein Objekt, das zusammen mit der Instanz im Design gespeichert wird. Es übersteht ein Neuladen und einen Neustart, und der Editor ändert es nicht.\n\n## Aktivitäten\n\nEine lange Aufgabe kann ihren Fortschritt an den Editor melden. `instance.activity(key, name, [progress])` erstellt oder aktualisiert eine Aktivität der Instanz; `progress` ist eine Zahl (Prozent). Fortschritt `100` oder ein leerer `name` entfernt die Aktivität.\n\n```js\ninstance.message = function($) {\n\tinstance.activity('import', 'Importing products', 0);\n\timportproducts($.data, function(percentage) {\n\t\tinstance.activity('import', 'Importing products', percentage);\n\t}, function() {\n\t\tinstance.activity('import', 'Importing products', 100);\n\t\t$.send('output');\n\t});\n};\n```\n\n## Variablen\n\nDie Variablen des Flows werden in Strings mit `instance.replace(text)` (oder `$.variables(text)` in einer Nachricht) ersetzt. Ein Platzhalter `{name}` nimmt den Wert aus den Variablen des Flows, den Secrets, `{hostname}` oder dem übergebenen Datenobjekt.\n\n```js\nvar url = instance.replace('https://api.example.com/orders/?token={token}');\n```\n\n`flowstream.variables(obj)` ersetzt die Variablen eines laufenden Flows; die Instanzen werden über ihr Delegate `variables` benachrichtigt.\n\n## Einen FlowStream aus dem Code steuern\n\n`Flow.instances[id]` ist der laufende FlowStream. Er funktioniert gleich für Flows im Hauptprozess und in Workern.\n\n```js\nvar flowstream = Flow.instances.orders;\n\n// Executes the \"trigger\" delegate of an instance\nflowstream.trigger('instanceid', { manual: true });\n\n// Sends data to an instance and waits for the end of the message\nflowstream.send('instanceid', { id: 1 }, function(err, response) {\n\tconsole.log(response.data, response.duration);\n});\n\nflowstream.pause(true);\nflowstream.reconfigure('instanceid', { field: 'title' });\nflowstream.export(function(err, schema) {});\n```\n\nInstanz-ids können durch `@component` (Instanzen einer Komponenten-id) oder `#name` (Instanzen eines Komponentennamens) ersetzt werden.\n\n`Flow.remove(id)` stoppt einen FlowStream und entfernt ihn.\n\n## Worker\n\nMit `worker: 'worker'` (ein Worker-Thread) oder `worker: 'process'` (ein Kindprozess) läuft der Flow außerhalb des Hauptprozesses, sodass eine fehlerhafte Komponente die Anwendung nicht blockieren kann. Ein Worker, der sich beendet, wird nach einer Sekunde automatisch neu gestartet. `memory: 512` begrenzt den Heap des Workers auf 512 MB. `flowstream.restart()` oder `Flow.restart(id)` beendet einen Worker, sodass er mit dem aktuellen Schema neu startet. Bei einem Flow im Hauptprozess bittet `instance.main.restart()` (und der Neustart-Befehl des Editors) den Total.js-Prozessmanager, die gesamte Anwendung neu zu starten.\n\nMit `proxypath` betreibt der Worker seinen eigenen HTTP-Server auf einem Unix-Socket, und die Hauptanwendung leitet Anfragen unter diesem Pfad an ihn weiter. `proxytimeout` setzt den Timeout dieses Proxys; er wird angewendet, wenn das Schema erneut in den laufenden FlowStream geladen wird.\n\n`flowstream.stats` enthält die Zähler: `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` (Nachrichten in der letzten Minute) und `paused`. Bei einem Flow im Hauptprozess ist `online` die Anzahl der mit ihm verbundenen Editoren. Für Flows in Workern empfängt `Flow.on('stats', function(id, stats) {})` die Zähler alle 15 Sekunden.\n\n## Benachrichtigungen\n\n`Flow.notify($, id)` übergibt eine HTTP-Anfrage an das Delegate `notify` einer Instanz. Die `id` ist `flowid-instanceid`. Registriere die Routen selbst:\n\n```js\nexports.install = function() {\n\tROUTE('GET /notify/{id}/', notify);\n\tROUTE('POST /notify/{id}/ <1MB', notify);\n};\n\nfunction notify($) {\n\tFlow.notify($, $.params.id);\n}\n```\n\n## TMS-Quellen\n\nIm Editor kannst du eine TMS-Quelle hinzufügen (eine URL und ein Token einer anderen Total.js-Anwendung). Der FlowStream verbindet sich mit ihr und erzeugt aus den Schemas der Quelle Publish-, Subscribe- und Call-Komponenten, sodass Nachrichten Anwendungsgrenzen überqueren können. Die Quellen werden im Schlüssel `sources` des Schemas gespeichert. Siehe [Message Service (TMS)](../message-service-and-apis/).\n\n## Eine Komponente testen\n\n`Flow.test(name, source, [config], init)` lädt eine einzelne Komponente in einen Test-Flow und gibt dir ein `Test`-Objekt:\n\n```js\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER', 'uppercase');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n## Der Befehl flow5\n\nDas Paket `total5` installiert den Befehl `flow5`. Er lädt ein oder mehrere Schemas aus Dateien oder HTTPS-URLs und startet einen HTTP-Server mit der WebSocket-Route für den Editor:\n\n```bash\nflow5 orders.json 8001\n```\n\nIm Editor gemachte Änderungen werden zurück in die JSON-Dateien geschrieben. Siehe [Kommandozeile](../command-line/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwTX7Fx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/flowstream/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"FlowStream","summary":"Flujos de datos visuales: carga de FlowStreams, componentes, instancias, mensajes y el editor Total.js Flow.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/flowstream/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# FlowStream\n\n> Flujos de datos visuales: carga de FlowStreams, componentes, instancias, mensajes y el editor Total.js Flow.\n\nFlowStream es el motor de los flujos de datos visuales en Total.js. Un flujo es un conjunto de **componentes** (pequeños programas con entradas y salidas), sus **instancias** colocadas en un lienzo y las **conexiones** entre ellas. Los mensajes viajan desde las salidas de una instancia a las entradas de otras. Los flujos se diseñan en el editor Total.js Flow, que se conecta a tu aplicación a través de un WebSocket.\n\nEl motor está disponible como el global `Flow` (y su alias `FlowStream`). Cada flujo cargado se guarda en `Flow.instances[id]`.\n\n## Cargar un FlowStream\n\n`Flow.load(schema, [callback])` inicia un FlowStream a partir de su esquema. El esquema es un objeto simple: el código fuente de los componentes, el diseño (instancias y conexiones) y las variables.\n\n```js\nFlow.load({ id: 'orders', name: 'Orders', components: {}, design: {}, variables: { token: '123' } }, function(err, flowstream) {\n\t// flowstream === Flow.instances.orders\n});\n```\n\n| Clave | Qué hace |\n| --- | --- |\n| `id` | Identificador del FlowStream (un id aleatorio si está vacío) |\n| `name` | Nombre mostrado en el editor (`id` si está vacío) |\n| `components` | Objeto: id del componente → código fuente del componente |\n| `design` | Objeto: id de la instancia → `{ component, config, connections, x, y }` |\n| `variables` | Valores disponibles como `{name}` en los componentes |\n| `worker` | `'worker'` ejecuta el flujo en un hilo worker, cualquier otro valor verdadero en un proceso hijo |\n| `memory` | Con `worker`: el límite del heap del worker en MB (`--max-old-space-size` para un proceso hijo, `resourceLimits` para un hilo worker) |\n| `proxypath` | Ruta URL bajo la que el servidor HTTP de un worker es accesible a través de la aplicación principal |\n| `cloning` | `false` desactiva la clonación de los datos de los mensajes entre conexiones |\n| `paused` | `true` carga el flujo en pausa |\n| `readonly` | `true` desactiva el guardado |\n| `import` | Rutas separadas por comas (desde la raíz de la aplicación) de módulos cuyo `install(flow)` / `init(flow)` se ejecuta al cargar |\n| `initscript` | Código JavaScript ejecutado con el FlowStream como `instance` |\n| `env` | Un valor disponible como `instance.env` en los componentes |\n\nCuando la aplicación arranca, cada archivo `*.flow` del directorio `/flowstreams/` se carga con `Flow.load()` (se omiten los archivos con `-bk` o `_bk` en el nombre). Un archivo `.flow` contiene el esquema como JSON.\n\nCargar un esquema con un `id` que ya está en ejecución recarga el FlowStream en ejecución con el nuevo esquema.\n\nCada vez que un FlowStream arranca (también tras el reinicio automático de un worker), el framework emite el evento global `flowstream`:\n\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream started:', flowstream.id);\n});\n```\n\nUn plugin puede contener su propio flujo: el archivo `/plugins/{name}/index.flow` se carga con el plugin. Su `id` es el id del plugin y el FlowStream en ejecución se guarda en `PLUGINS[id].flowstream`. Consulta [Plugins y componentes](../plugins-and-components/).\n\n## Edición con Total.js Flow\n\nEl editor se comunica con el FlowStream a través de un WebSocket. Crea una ruta y pasa la conexión a `Flow.socket()`:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', socket);\n};\n\nfunction socket($) {\n\t$.autodestroy();\n\tFlow.socket($.params.id, $);\n}\n```\n\nAbre `https://flow.totaljs.com/?socket=` seguido de la dirección de este WebSocket codificada para URL. El editor carga los componentes y el diseño, muestra el estado de las instancias y guarda cada cambio en el FlowStream.\n\nEl FlowStream no escribe archivos. Unos 5 segundos después de un cambio emite `save` con el esquema completo, y lo guardas tú mismo:\n\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nPara la edición remota, `flowstream.edit([url])` abre un cliente WebSocket hacia un proxy (por defecto `wss://flow.totaljs.com/{id}/`), para que el editor pueda llegar a un FlowStream que se ejecuta detrás de un firewall.\n\n## Componentes\n\nUn componente es texto con partes similares a HTML. El código del servidor está en `<script total>` (o `<script node>`); `<settings>`, `<body>`, `<style>`, `<readme>` y un `<script>` simple los usa el editor.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-text';\n\texports.group = 'Common';\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\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tdata[config.field] = (data[config.field] || '').toUpperCase();\n\t\t\t$.send('output');\n\t\t};\n\n\t\tinstance.configure = function() {\n\t\t\tconfig = instance.config;\n\t\t};\n\n\t};\n\n</script>\n\n<readme>\nConverts a field to upper case.\n</readme>\n```\n\n`exports.make(instance, config)` se ejecuta una vez por cada instancia del componente en el lienzo. Dentro asignas delegados a la instancia: `message` (un mensaje entrante), `configure` (nueva configuración), `close` (la instancia se elimina), `variables` (las variables han cambiado), `trigger` (el botón de disparo en el editor), `service` (se llama cada minuto) y otros.\n\n`exports.npm = ['package']` instala los paquetes NPM antes de que se registre el componente. `exports.install` y `exports.uninstall` se ejecutan cuando el componente se registra y se elimina.\n\n## Mensajes\n\nEl delegado `message` recibe un mensaje, normalmente llamado `$`. `$.data` es la carga útil, `$.repo` es un objeto compartido por todos los clones del mensaje, `$.input` y `$.output` son los ids de la entrada y de la salida. `$.send(output, [data])` envía un clon a cada instancia conectada a la salida; los clones de los datos son copias profundas salvo que el flujo tenga `cloning: false`. `$.send(null)` envía a todas las salidas; el mensaje termina una sola vez, cuando terminan los clones de todas las salidas. Un mensaje que no se envía más adelante debe terminarse con `$.end()`.\n\n```js\ninstance.message = function($) {\n\tif ($.data.price > 100)\n\t\t$.send('expensive');\n\telse\n\t\t$.send('cheap', { price: $.data.price });\n};\n```\n\nEl cuarto argumento de `$.send()` filtra los destinos: `$.send('output', null, null, function(from, to, output, input) { return to.component !== 'debug'; })`.\n\nSin un mensaje entrante, una instancia inicia uno nuevo con `instance.send(output, data)` (por ejemplo desde un temporizador o desde `trigger`). `instance.send(null, data)` lo envía a todas las salidas. El estado de una instancia (mostrado debajo de ella en el editor) se establece con `instance.status(data)`, y los errores se notifican con `instance.throw(err)`. El flujo guarda los últimos 10 errores en `instance.main.errors`; el comando de reinicio del editor los borra y el motor del flujo emite `reset`, así una instancia también puede borrar su propio estado:\n\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\nEl siguiente ejemplo inicia mensajes desde un temporizador y muestra la hora del último como estado:\n\n```js\nexports.make = function(instance, config) {\n\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: NOW });\n\t\tinstance.status({ last: NOW });\n\t}, 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n\n};\n```\n\n## Datos de la instancia\n\n`instance.config` es la configuración del editor fusionada en `exports.config`. `instance.cache` es un objeto simple para tus propios datos en tiempo de ejecución; se mantiene en memoria para el id de la instancia cuando la instancia se vuelve a inicializar (por ejemplo después de actualizar su componente). Llama a `instance.save()` después de cambiar `config` desde el código: el flujo se guarda y el editor se redibuja (`instance.save(false)` guarda sin redibujar).\n\n`instance.repo` es un objeto guardado en el diseño junto con la instancia. Sobrevive a una recarga y a un reinicio, y el editor no lo modifica.\n\n## Actividades\n\nUna tarea larga puede informar de su progreso al editor. `instance.activity(key, name, [progress])` crea o actualiza una actividad de la instancia; `progress` es un número (porcentaje). Un progreso `100` o un `name` vacío elimina la actividad.\n\n```js\ninstance.message = function($) {\n\tinstance.activity('import', 'Importing products', 0);\n\timportproducts($.data, function(percentage) {\n\t\tinstance.activity('import', 'Importing products', percentage);\n\t}, function() {\n\t\tinstance.activity('import', 'Importing products', 100);\n\t\t$.send('output');\n\t});\n};\n```\n\n## Variables\n\nLas variables del flujo se sustituyen en strings con `instance.replace(text)` (o `$.variables(text)` en un mensaje). Un marcador `{name}` toma el valor de las variables del flujo, de los secretos, de `{hostname}` o del objeto de datos indicado.\n\n```js\nvar url = instance.replace('https://api.example.com/orders/?token={token}');\n```\n\n`flowstream.variables(obj)` reemplaza las variables de un flujo en ejecución; las instancias reciben el aviso mediante su delegado `variables`.\n\n## Controlar un FlowStream desde el código\n\n`Flow.instances[id]` es el FlowStream en ejecución. Funciona igual para flujos en el proceso principal y en workers.\n\n```js\nvar flowstream = Flow.instances.orders;\n\n// Executes the \"trigger\" delegate of an instance\nflowstream.trigger('instanceid', { manual: true });\n\n// Sends data to an instance and waits for the end of the message\nflowstream.send('instanceid', { id: 1 }, function(err, response) {\n\tconsole.log(response.data, response.duration);\n});\n\nflowstream.pause(true);\nflowstream.reconfigure('instanceid', { field: 'title' });\nflowstream.export(function(err, schema) {});\n```\n\nLos ids de instancia se pueden sustituir por `@component` (instancias de un id de componente) o `#name` (instancias de un nombre de componente).\n\n`Flow.remove(id)` detiene un FlowStream y lo elimina.\n\n## Workers\n\nCon `worker: 'worker'` (un hilo worker) o `worker: 'process'` (un proceso hijo) el flujo se ejecuta fuera del proceso principal, así que un componente defectuoso no puede bloquear la aplicación. Un worker que termina se vuelve a iniciar automáticamente tras un segundo. `memory: 512` limita el heap del worker a 512 MB. `flowstream.restart()` o `Flow.restart(id)` finaliza un worker para que vuelva a arrancar con el esquema actual. Para un flujo en el proceso principal, `instance.main.restart()` (y el comando de reinicio del editor) pide al gestor de procesos de Total.js que reinicie toda la aplicación.\n\nCon `proxypath`, el worker ejecuta su propio servidor HTTP en un socket Unix y la aplicación principal le reenvía las peticiones bajo esa ruta. `proxytimeout` establece el timeout de ese proxy; se aplica cuando el esquema se vuelve a cargar en el FlowStream en ejecución.\n\n`flowstream.stats` contiene los contadores: `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` (mensajes del último minuto) y `paused`. Para un flujo en el proceso principal, `online` es el número de editores conectados a él. Para flujos en workers, `Flow.on('stats', function(id, stats) {})` recibe los contadores cada 15 segundos.\n\n## Notificaciones\n\n`Flow.notify($, id)` pasa una petición HTTP al delegado `notify` de una instancia. El `id` es `flowid-instanceid`. Registra las rutas tú mismo:\n\n```js\nexports.install = function() {\n\tROUTE('GET /notify/{id}/', notify);\n\tROUTE('POST /notify/{id}/ <1MB', notify);\n};\n\nfunction notify($) {\n\tFlow.notify($, $.params.id);\n}\n```\n\n## Fuentes TMS\n\nEn el editor puedes añadir una fuente TMS (una URL y un token de otra aplicación Total.js). El FlowStream se conecta a ella y crea componentes Publish, Subscribe y Call a partir de los esquemas de la fuente, para que los mensajes puedan cruzar entre aplicaciones. Las fuentes se guardan en la clave `sources` del esquema. Consulta [Message Service (TMS)](../message-service-and-apis/).\n\n## Probar un componente\n\n`Flow.test(name, source, [config], init)` carga un único componente en un flujo de prueba y te da un objeto `Test`:\n\n```js\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER', 'uppercase');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n## El comando flow5\n\nEl paquete `total5` instala el comando `flow5`. Carga uno o más esquemas desde archivos o URLs HTTPS e inicia un servidor HTTP con la ruta WebSocket para el editor:\n\n```bash\nflow5 orders.json 8001\n```\n\nLos cambios hechos en el editor se escriben de vuelta en los archivos JSON. Consulta [Línea de comandos](../command-line/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwTX7Fx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/flowstream/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"FlowStream","summary":"Flux de données visuels : chargement des FlowStreams, composants, instances, messages et l'éditeur Total.js Flow.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/flowstream/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# FlowStream\n\n> Flux de données visuels : chargement des FlowStreams, composants, instances, messages et l'éditeur Total.js Flow.\n\nFlowStream est le moteur des flux de données visuels de Total.js. Un flux est un ensemble de **composants** (de petits programmes avec des entrées et des sorties), leurs **instances** placées sur un canevas et les **connexions** entre elles. Les messages circulent des sorties d'une instance vers les entrées des autres. Les flux sont conçus dans l'éditeur Total.js Flow, qui se connecte à ton application par un WebSocket.\n\nLe moteur est disponible via le global `Flow` (et son alias `FlowStream`). Chaque flux chargé est conservé dans `Flow.instances[id]`.\n\n## Charger un FlowStream\n\n`Flow.load(schema, [callback])` démarre un FlowStream à partir de son schéma. Le schéma est un objet simple : le code source des composants, le design (instances et connexions) et les variables.\n\n```js\nFlow.load({ id: 'orders', name: 'Orders', components: {}, design: {}, variables: { token: '123' } }, function(err, flowstream) {\n\t// flowstream === Flow.instances.orders\n});\n```\n\n| Clé | Ce qu'elle fait |\n| --- | --- |\n| `id` | Identifiant du FlowStream (un id aléatoire s'il est vide) |\n| `name` | Nom affiché dans l'éditeur (`id` s'il est vide) |\n| `components` | Objet : id du composant → code source du composant |\n| `design` | Objet : id de l'instance → `{ component, config, connections, x, y }` |\n| `variables` | Valeurs disponibles sous la forme `{name}` dans les composants |\n| `worker` | `'worker'` exécute le flux dans un worker thread, toute autre valeur truthy dans un processus enfant |\n| `memory` | Avec `worker` : la limite du heap du worker en Mo (`--max-old-space-size` pour un processus enfant, `resourceLimits` pour un worker thread) |\n| `proxypath` | Chemin d'URL sous lequel le serveur HTTP d'un worker est accessible via l'application principale |\n| `cloning` | `false` désactive le clonage des données des messages entre les connexions |\n| `paused` | `true` charge le flux en pause |\n| `readonly` | `true` désactive l'enregistrement |\n| `import` | Chemins séparés par des virgules (depuis la racine de l'application) de modules dont `install(flow)` / `init(flow)` s'exécutent au chargement |\n| `initscript` | Code JavaScript exécuté avec le FlowStream comme `instance` |\n| `env` | Une valeur disponible sous `instance.env` dans les composants |\n\nAu démarrage de l'application, chaque fichier `*.flow` du répertoire `/flowstreams/` est chargé avec `Flow.load()` (les fichiers avec `-bk` ou `_bk` dans le nom sont ignorés). Un fichier `.flow` contient le schéma en JSON.\n\nCharger un schéma avec un `id` déjà en cours d'exécution recharge le FlowStream en cours avec le nouveau schéma.\n\nÀ chaque démarrage d'un FlowStream (y compris après le redémarrage automatique d'un worker), le framework émet l'événement global `flowstream` :\n\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream started:', flowstream.id);\n});\n```\n\nUn plugin peut contenir son propre flux : le fichier `/plugins/{name}/index.flow` est chargé avec le plugin. Son `id` est l'id du plugin et le FlowStream en cours d'exécution est stocké dans `PLUGINS[id].flowstream`. Voir [Plugins et composants](../plugins-and-components/).\n\n## Éditer avec Total.js Flow\n\nL'éditeur communique avec le FlowStream par un WebSocket. Crée une route et passe la connexion à `Flow.socket()` :\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', socket);\n};\n\nfunction socket($) {\n\t$.autodestroy();\n\tFlow.socket($.params.id, $);\n}\n```\n\nOuvre `https://flow.totaljs.com/?socket=` suivi de l'adresse encodée en URL de ce WebSocket. L'éditeur charge les composants et le design, affiche l'état des instances et enregistre chaque modification dans le FlowStream.\n\nLe FlowStream n'écrit pas de fichiers. Environ 5 secondes après une modification, il émet `save` avec le schéma complet, et c'est toi qui le stockes :\n\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nPour l'édition à distance, `flowstream.edit([url])` ouvre un client WebSocket vers un proxy (par défaut `wss://flow.totaljs.com/{id}/`), afin que l'éditeur puisse atteindre un FlowStream qui tourne derrière un pare-feu.\n\n## Composants\n\nUn composant est un texte composé de parties de type HTML. Le code serveur se trouve dans `<script total>` (ou `<script node>`) ; `<settings>`, `<body>`, `<style>`, `<readme>` et un `<script>` simple sont utilisés par l'éditeur.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-text';\n\texports.group = 'Common';\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\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tdata[config.field] = (data[config.field] || '').toUpperCase();\n\t\t\t$.send('output');\n\t\t};\n\n\t\tinstance.configure = function() {\n\t\t\tconfig = instance.config;\n\t\t};\n\n\t};\n\n</script>\n\n<readme>\nConverts a field to upper case.\n</readme>\n```\n\n`exports.make(instance, config)` s'exécute une fois pour chaque instance du composant sur le canevas. À l'intérieur, tu assignes des délégués à l'instance : `message` (un message entrant), `configure` (nouvelle configuration), `close` (l'instance est supprimée), `variables` (les variables ont changé), `trigger` (le bouton de déclenchement dans l'éditeur), `service` (appelé chaque minute) et d'autres.\n\n`exports.npm = ['package']` installe les paquets NPM avant l'enregistrement du composant. `exports.install` et `exports.uninstall` s'exécutent quand le composant est enregistré et supprimé.\n\n## Messages\n\nLe délégué `message` reçoit un message, généralement appelé `$`. `$.data` contient les données utiles, `$.repo` est un objet partagé par tous les clones du message, `$.input` et `$.output` sont les ids de l'entrée et de la sortie. `$.send(output, [data])` envoie un clone à chaque instance connectée à la sortie ; les clones des données sont des copies profondes, sauf si le flux a `cloning: false`. `$.send(null)` envoie à toutes les sorties ; le message se termine une seule fois, après la fin des clones de toutes les sorties. Un message qui n'est pas transmis plus loin doit être terminé avec `$.end()`.\n\n```js\ninstance.message = function($) {\n\tif ($.data.price > 100)\n\t\t$.send('expensive');\n\telse\n\t\t$.send('cheap', { price: $.data.price });\n};\n```\n\nLe quatrième argument de `$.send()` filtre les cibles : `$.send('output', null, null, function(from, to, output, input) { return to.component !== 'debug'; })`.\n\nSans message entrant, une instance en démarre un nouveau avec `instance.send(output, data)` (par exemple depuis un timer ou depuis `trigger`). `instance.send(null, data)` envoie à toutes les sorties. L'état d'une instance (affiché sous elle dans l'éditeur) se définit avec `instance.status(data)`, et les erreurs sont signalées avec `instance.throw(err)`. Le flux garde les 10 dernières erreurs dans `instance.main.errors` ; la commande reset de l'éditeur les efface et le moteur de flux émet `reset`, de sorte qu'une instance peut aussi effacer son propre état :\n\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\nL'exemple suivant démarre des messages depuis un timer et affiche l'heure du dernier comme état :\n\n```js\nexports.make = function(instance, config) {\n\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: NOW });\n\t\tinstance.status({ last: NOW });\n\t}, 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n\n};\n```\n\n## Données de l'instance\n\n`instance.config` est la configuration de l'éditeur fusionnée dans `exports.config`. `instance.cache` est un objet simple pour tes propres données d'exécution ; il est conservé en mémoire pour l'id de l'instance lorsque l'instance est réinitialisée (par exemple après la mise à jour de son composant). Appelle `instance.save()` après avoir modifié `config` depuis le code : le flux est enregistré et l'éditeur est redessiné (`instance.save(false)` enregistre sans redessiner).\n\n`instance.repo` est un objet stocké dans le design avec l'instance. Il survit à un rechargement et à un redémarrage, et l'éditeur ne le modifie pas.\n\n## Activités\n\nUne tâche longue peut signaler sa progression à l'éditeur. `instance.activity(key, name, [progress])` crée ou met à jour une activité de l'instance ; `progress` est un nombre (pourcentage). Une progression de `100` ou un `name` vide supprime l'activité.\n\n```js\ninstance.message = function($) {\n\tinstance.activity('import', 'Importing products', 0);\n\timportproducts($.data, function(percentage) {\n\t\tinstance.activity('import', 'Importing products', percentage);\n\t}, function() {\n\t\tinstance.activity('import', 'Importing products', 100);\n\t\t$.send('output');\n\t});\n};\n```\n\n## Variables\n\nLes variables du flux sont remplacées dans les chaînes avec `instance.replace(text)` (ou `$.variables(text)` dans un message). Un placeholder `{name}` prend la valeur dans les variables du flux, les secrets, `{hostname}` ou l'objet de données fourni.\n\n```js\nvar url = instance.replace('https://api.example.com/orders/?token={token}');\n```\n\n`flowstream.variables(obj)` remplace les variables d'un flux en cours d'exécution ; les instances sont notifiées par leur délégué `variables`.\n\n## Contrôler un FlowStream depuis le code\n\n`Flow.instances[id]` est le FlowStream en cours d'exécution. Il fonctionne de la même manière pour les flux du processus principal et ceux des workers.\n\n```js\nvar flowstream = Flow.instances.orders;\n\n// Executes the \"trigger\" delegate of an instance\nflowstream.trigger('instanceid', { manual: true });\n\n// Sends data to an instance and waits for the end of the message\nflowstream.send('instanceid', { id: 1 }, function(err, response) {\n\tconsole.log(response.data, response.duration);\n});\n\nflowstream.pause(true);\nflowstream.reconfigure('instanceid', { field: 'title' });\nflowstream.export(function(err, schema) {});\n```\n\nLes ids d'instance peuvent être remplacés par `@component` (les instances d'un id de composant) ou `#name` (les instances d'un nom de composant).\n\n`Flow.remove(id)` arrête un FlowStream et le supprime.\n\n## Workers\n\nAvec `worker: 'worker'` (un worker thread) ou `worker: 'process'` (un processus enfant), le flux s'exécute hors du processus principal : un composant défaillant ne peut donc pas bloquer l'application. Un worker qui se termine est redémarré automatiquement après une seconde. `memory: 512` limite le heap du worker à 512 Mo. `flowstream.restart()` ou `Flow.restart(id)` termine un worker pour qu'il redémarre avec le schéma actuel. Pour un flux du processus principal, `instance.main.restart()` (et la commande de redémarrage de l'éditeur) demande au gestionnaire de processus de Total.js de redémarrer toute l'application.\n\nAvec `proxypath`, le worker exécute son propre serveur HTTP sur un socket Unix et l'application principale lui transmet les requêtes sous ce chemin. `proxytimeout` définit le timeout de ce proxy ; il est appliqué quand le schéma est rechargé dans le FlowStream en cours d'exécution.\n\n`flowstream.stats` contient les compteurs : `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` (messages de la dernière minute) et `paused`. Pour un flux du processus principal, `online` est le nombre d'éditeurs qui y sont connectés. Pour les flux dans des workers, `Flow.on('stats', function(id, stats) {})` reçoit les compteurs toutes les 15 secondes.\n\n## Notifications\n\n`Flow.notify($, id)` transmet une requête HTTP au délégué `notify` d'une instance. L'`id` est `flowid-instanceid`. Enregistre les routes toi-même :\n\n```js\nexports.install = function() {\n\tROUTE('GET /notify/{id}/', notify);\n\tROUTE('POST /notify/{id}/ <1MB', notify);\n};\n\nfunction notify($) {\n\tFlow.notify($, $.params.id);\n}\n```\n\n## Sources TMS\n\nDans l'éditeur, tu peux ajouter une source TMS (une URL et un token d'une autre application Total.js). Le FlowStream s'y connecte et crée des composants Publish, Subscribe et Call à partir des schémas de la source, afin que les messages puissent passer d'une application à l'autre. Les sources sont enregistrées dans la clé `sources` du schéma. Voir [Message Service (TMS)](../message-service-and-apis/).\n\n## Tester un composant\n\n`Flow.test(name, source, [config], init)` charge un seul composant dans un flux de test et te fournit un objet `Test` :\n\n```js\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER', 'uppercase');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n## La commande flow5\n\nLe paquet `total5` installe la commande `flow5`. Elle charge un ou plusieurs schémas depuis des fichiers ou des URL HTTPS et démarre un serveur HTTP avec la route WebSocket pour l'éditeur :\n\n```bash\nflow5 orders.json 8001\n```\n\nLes modifications faites dans l'éditeur sont réécrites dans les fichiers JSON. Voir [Ligne de commande](../command-line/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwTX7Fx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/flowstream/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"FlowStream","summary":"Flussi di dati visuali: caricamento dei FlowStream, componenti, istanze, messaggi e l'editor Total.js Flow.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/flowstream/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# FlowStream\n\n> Flussi di dati visuali: caricamento dei FlowStream, componenti, istanze, messaggi e l'editor Total.js Flow.\n\nFlowStream è il motore dei flussi di dati visuali in Total.js. Un flusso è un insieme di **componenti** (piccoli programmi con input e output), delle loro **istanze** posizionate su un canvas e delle **connessioni** tra di esse. I messaggi viaggiano dagli output di un'istanza agli input di altre. I flussi si progettano nell'editor Total.js Flow, che si collega alla tua applicazione tramite un WebSocket.\n\nIl motore è disponibile come oggetto globale `Flow` (e il suo alias `FlowStream`). Ogni flusso caricato è conservato in `Flow.instances[id]`.\n\n## Caricare un FlowStream\n\n`Flow.load(schema, [callback])` avvia un FlowStream dal suo schema. Lo schema è un semplice oggetto: il codice sorgente dei componenti, il design (istanze e connessioni) e le variabili.\n\n```js\nFlow.load({ id: 'orders', name: 'Orders', components: {}, design: {}, variables: { token: '123' } }, function(err, flowstream) {\n\t// flowstream === Flow.instances.orders\n});\n```\n\n| Chiave | Cosa fa |\n| --- | --- |\n| `id` | Identificatore del FlowStream (un id casuale se vuoto) |\n| `name` | Nome mostrato nell'editor (`id` se vuoto) |\n| `components` | Oggetto: id del componente → codice sorgente del componente |\n| `design` | Oggetto: id dell'istanza → `{ component, config, connections, x, y }` |\n| `variables` | Valori disponibili come `{name}` nei componenti |\n| `worker` | `'worker'` esegue il flusso in un worker thread, qualsiasi altro valore truthy in un processo figlio |\n| `memory` | Con `worker`: il limite dell'heap del worker in MB (`--max-old-space-size` per un processo figlio, `resourceLimits` per un worker thread) |\n| `proxypath` | Percorso URL con cui il server HTTP di un worker è raggiungibile tramite l'app principale |\n| `cloning` | `false` disattiva la clonazione dei dati dei messaggi tra le connessioni |\n| `paused` | `true` carica il flusso in pausa |\n| `readonly` | `true` disattiva il salvataggio |\n| `import` | Percorsi separati da virgole (dalla radice dell'app) di moduli i cui `install(flow)` / `init(flow)` vengono eseguiti al caricamento |\n| `initscript` | Codice JavaScript eseguito con il FlowStream come `instance` |\n| `env` | Un valore disponibile come `instance.env` nei componenti |\n\nAll'avvio dell'applicazione, ogni file `*.flow` nella directory `/flowstreams/` viene caricato con `Flow.load()` (i file con `-bk` o `_bk` nel nome vengono saltati). Un file `.flow` contiene lo schema in formato JSON.\n\nCaricare uno schema con un `id` già in esecuzione ricarica il FlowStream in esecuzione con il nuovo schema.\n\nOgni volta che un FlowStream si avvia (anche dopo il riavvio automatico di un worker), il framework emette l'evento globale `flowstream`:\n\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream started:', flowstream.id);\n});\n```\n\nUn plugin può contenere un proprio flusso: il file `/plugins/{name}/index.flow` viene caricato con il plugin. Il suo `id` è l'id del plugin e il FlowStream in esecuzione viene salvato in `PLUGINS[id].flowstream`. Vedi [Plugin e componenti](../plugins-and-components/).\n\n## Modificare con Total.js Flow\n\nL'editor comunica con il FlowStream tramite un WebSocket. Crea una route e passa la connessione a `Flow.socket()`:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', socket);\n};\n\nfunction socket($) {\n\t$.autodestroy();\n\tFlow.socket($.params.id, $);\n}\n```\n\nApri `https://flow.totaljs.com/?socket=` seguito dall'indirizzo, codificato per URL, di questo WebSocket. L'editor carica i componenti e il design, mostra lo stato delle istanze e salva ogni modifica nel FlowStream.\n\nIl FlowStream non scrive file. Circa 5 secondi dopo una modifica emette `save` con l'intero schema, e sei tu a salvarlo:\n\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nPer la modifica remota, `flowstream.edit([url])` apre un client WebSocket verso un proxy (per impostazione predefinita `wss://flow.totaljs.com/{id}/`), così l'editor può raggiungere un FlowStream che gira dietro un firewall.\n\n## Componenti\n\nUn componente è un testo con parti simili all'HTML. Il codice server è in `<script total>` (o `<script node>`); `<settings>`, `<body>`, `<style>`, `<readme>` e un semplice `<script>` sono usati dall'editor.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-text';\n\texports.group = 'Common';\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\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tdata[config.field] = (data[config.field] || '').toUpperCase();\n\t\t\t$.send('output');\n\t\t};\n\n\t\tinstance.configure = function() {\n\t\t\tconfig = instance.config;\n\t\t};\n\n\t};\n\n</script>\n\n<readme>\nConverts a field to upper case.\n</readme>\n```\n\n`exports.make(instance, config)` viene eseguito una volta per ogni istanza del componente sul canvas. Al suo interno assegni dei delegate all'istanza: `message` (un messaggio in arrivo), `configure` (nuova configurazione), `close` (l'istanza viene rimossa), `variables` (le variabili sono cambiate), `trigger` (il pulsante trigger nell'editor), `service` (chiamato ogni minuto) e altri.\n\n`exports.npm = ['package']` installa i pacchetti NPM prima che il componente venga registrato. `exports.install` e `exports.uninstall` vengono eseguiti quando il componente viene registrato e rimosso.\n\n## Messaggi\n\nIl delegate `message` riceve un messaggio, di solito chiamato `$`. `$.data` è il payload, `$.repo` è un oggetto condiviso da tutti i cloni del messaggio, `$.input` e `$.output` sono gli id dell'input e dell'output. `$.send(output, [data])` invia un clone a ogni istanza collegata all'output; i cloni dei dati sono copie profonde, a meno che il flusso non abbia `cloning: false`. `$.send(null)` invia a tutti gli output; il messaggio termina una sola volta, dopo che sono terminati i cloni di tutti gli output. Un messaggio che non viene inoltrato deve essere terminato con `$.end()`.\n\n```js\ninstance.message = function($) {\n\tif ($.data.price > 100)\n\t\t$.send('expensive');\n\telse\n\t\t$.send('cheap', { price: $.data.price });\n};\n```\n\nIl quarto argomento di `$.send()` filtra le destinazioni: `$.send('output', null, null, function(from, to, output, input) { return to.component !== 'debug'; })`.\n\nSenza un messaggio in arrivo, un'istanza ne avvia uno nuovo con `instance.send(output, data)` (per esempio da un timer o da `trigger`). `instance.send(null, data)` invia a tutti gli output. Lo stato di un'istanza (mostrato sotto di essa nell'editor) si imposta con `instance.status(data)`, gli errori si segnalano con `instance.throw(err)`. Il flusso conserva gli ultimi 10 errori in `instance.main.errors`; il comando di reset dell'editor li cancella e il motore del flusso emette `reset`, così anche un'istanza può cancellare il proprio stato:\n\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\nL'esempio seguente avvia messaggi da un timer e mostra come stato l'ora dell'ultimo:\n\n```js\nexports.make = function(instance, config) {\n\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: NOW });\n\t\tinstance.status({ last: NOW });\n\t}, 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n\n};\n```\n\n## Dati dell'istanza\n\n`instance.config` è la configurazione dell'editor unita a `exports.config`. `instance.cache` è un semplice oggetto per i tuoi dati di runtime; viene mantenuto in memoria per l'id dell'istanza quando l'istanza viene reinizializzata (per esempio dopo l'aggiornamento del suo componente). Chiama `instance.save()` dopo aver modificato `config` dal codice: il flusso viene salvato e l'editor viene ridisegnato (`instance.save(false)` salva senza ridisegnare).\n\n`instance.repo` è un oggetto salvato nel design insieme all'istanza. Sopravvive a un ricaricamento e a un riavvio, e l'editor non lo modifica.\n\n## Attività\n\nUn'operazione lunga può segnalare il suo avanzamento all'editor. `instance.activity(key, name, [progress])` crea o aggiorna un'attività dell'istanza; `progress` è un numero (percentuale). Un avanzamento `100` o un `name` vuoto rimuove l'attività.\n\n```js\ninstance.message = function($) {\n\tinstance.activity('import', 'Importing products', 0);\n\timportproducts($.data, function(percentage) {\n\t\tinstance.activity('import', 'Importing products', percentage);\n\t}, function() {\n\t\tinstance.activity('import', 'Importing products', 100);\n\t\t$.send('output');\n\t});\n};\n```\n\n## Variabili\n\nLe variabili del flusso vengono sostituite nelle stringhe con `instance.replace(text)` (o `$.variables(text)` in un messaggio). Un segnaposto `{name}` prende il valore dalle variabili del flusso, dai segreti, da `{hostname}` o dall'oggetto dati passato.\n\n```js\nvar url = instance.replace('https://api.example.com/orders/?token={token}');\n```\n\n`flowstream.variables(obj)` sostituisce le variabili di un flusso in esecuzione; le istanze vengono notificate tramite il loro delegate `variables`.\n\n## Controllare un FlowStream dal codice\n\n`Flow.instances[id]` è il FlowStream in esecuzione. Funziona allo stesso modo per i flussi nel processo principale e nei worker.\n\n```js\nvar flowstream = Flow.instances.orders;\n\n// Executes the \"trigger\" delegate of an instance\nflowstream.trigger('instanceid', { manual: true });\n\n// Sends data to an instance and waits for the end of the message\nflowstream.send('instanceid', { id: 1 }, function(err, response) {\n\tconsole.log(response.data, response.duration);\n});\n\nflowstream.pause(true);\nflowstream.reconfigure('instanceid', { field: 'title' });\nflowstream.export(function(err, schema) {});\n```\n\nGli id delle istanze possono essere sostituiti da `@component` (istanze di un id di componente) o `#name` (istanze di un nome di componente).\n\n`Flow.remove(id)` arresta un FlowStream e lo rimuove.\n\n## Worker\n\nCon `worker: 'worker'` (un worker thread) o `worker: 'process'` (un processo figlio) il flusso gira fuori dal processo principale, quindi un componente difettoso non può bloccare l'applicazione. Un worker che termina viene riavviato automaticamente dopo un secondo. `memory: 512` limita l'heap del worker a 512 MB. `flowstream.restart()` o `Flow.restart(id)` termina un worker in modo che riparta con lo schema attuale. Per un flusso nel processo principale, `instance.main.restart()` (e il comando di riavvio dell'editor) chiede al process manager di Total.js di riavviare l'intera applicazione.\n\nCon `proxypath`, il worker esegue un proprio server HTTP su un socket Unix e l'applicazione principale gli inoltra le richieste sotto quel percorso. `proxytimeout` imposta il timeout di quel proxy; viene applicato quando lo schema viene ricaricato nel FlowStream in esecuzione.\n\n`flowstream.stats` contiene i contatori: `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` (messaggi nell'ultimo minuto) e `paused`. Per un flusso nel processo principale, `online` è il numero di editor collegati. Per i flussi nei worker, `Flow.on('stats', function(id, stats) {})` riceve i contatori ogni 15 secondi.\n\n## Notifiche\n\n`Flow.notify($, id)` passa una richiesta HTTP al delegate `notify` di un'istanza. L'`id` è `flowid-instanceid`. Registra tu le route:\n\n```js\nexports.install = function() {\n\tROUTE('GET /notify/{id}/', notify);\n\tROUTE('POST /notify/{id}/ <1MB', notify);\n};\n\nfunction notify($) {\n\tFlow.notify($, $.params.id);\n}\n```\n\n## Sorgenti TMS\n\nNell'editor puoi aggiungere una sorgente TMS (un URL e un token di un'altra app Total.js). Il FlowStream si collega a essa e crea i componenti Publish, Subscribe e Call dagli schemi della sorgente, così i messaggi possono passare da un'applicazione all'altra. Le sorgenti vengono salvate nella chiave `sources` dello schema. Vedi [Message Service (TMS)](../message-service-and-apis/).\n\n## Testare un componente\n\n`Flow.test(name, source, [config], init)` carica un singolo componente in un flusso di test e ti fornisce un oggetto `Test`:\n\n```js\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER', 'uppercase');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n## Il comando flow5\n\nIl pacchetto `total5` installa il comando `flow5`. Carica uno o più schemi da file o da URL HTTPS e avvia un server HTTP con la route WebSocket per l'editor:\n\n```bash\nflow5 orders.json 8001\n```\n\nLe modifiche fatte nell'editor vengono riscritte nei file JSON. Vedi [Riga di comando](../command-line/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwTX7Fx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/flowstream/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"FlowStream","summary":"Vizuálne dátové toky: načítanie FlowStreamov, komponenty, inštancie, správy a editor Total.js Flow.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/flowstream/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# FlowStream\n\n> Vizuálne dátové toky: načítanie FlowStreamov, komponenty, inštancie, správy a editor Total.js Flow.\n\nFlowStream je engine vizuálnych dátových tokov v Total.js. Flow je súbor **komponentov** (malých programov so vstupmi a výstupmi), ich **inštancií** umiestnených na plátne a **spojení** medzi nimi. Správy putujú z výstupov jednej inštancie na vstupy iných. Flowy sa navrhujú v editore Total.js Flow, ktorý sa k tvojej aplikácii pripája cez WebSocket.\n\nEngine je dostupný ako globálny `Flow` (a jeho alias `FlowStream`). Každý načítaný flow je uložený v `Flow.instances[id]`.\n\n## Načítanie FlowStreamu\n\n`Flow.load(schema, [callback])` spustí FlowStream z jeho schémy. Schéma je obyčajný objekt: zdrojový kód komponentov, dizajn (inštancie a spojenia) a premenné.\n\n```js\nFlow.load({ id: 'orders', name: 'Orders', components: {}, design: {}, variables: { token: '123' } }, function(err, flowstream) {\n\t// flowstream === Flow.instances.orders\n});\n```\n\n| Kľúč | Čo robí |\n| --- | --- |\n| `id` | Identifikátor FlowStreamu (náhodné id, ak je prázdny) |\n| `name` | Názov zobrazený v editore (`id`, ak je prázdny) |\n| `components` | Objekt: id komponentu → zdrojový kód komponentu |\n| `design` | Objekt: id inštancie → `{ component, config, connections, x, y }` |\n| `variables` | Hodnoty dostupné ako `{name}` v komponentoch |\n| `worker` | `'worker'` spustí flow vo worker vlákne, akákoľvek iná pravdivá hodnota v podriadenom procese |\n| `memory` | S `worker`: limit haldy workera v MB (`--max-old-space-size` pre podriadený proces, `resourceLimits` pre worker vlákno) |\n| `proxypath` | URL cesta, pod ktorou je HTTP server workera dostupný cez hlavnú aplikáciu |\n| `cloning` | `false` vypne klonovanie dát správ medzi spojeniami |\n| `paused` | `true` načíta flow pozastavený |\n| `readonly` | `true` vypne ukladanie |\n| `import` | Čiarkami oddelené cesty (od koreňa aplikácie) k modulom, ktorých `install(flow)` / `init(flow)` sa spustí pri načítaní |\n| `initscript` | JavaScript kód spustený s FlowStreamom ako `instance` |\n| `env` | Hodnota dostupná ako `instance.env` v komponentoch |\n\nKeď sa aplikácia spustí, každý súbor `*.flow` v adresári `/flowstreams/` sa načíta cez `Flow.load()` (súbory s `-bk` alebo `_bk` v názve sa preskočia). Súbor `.flow` obsahuje schému ako JSON.\n\nNačítanie schémy s `id`, ktoré už beží, znovu načíta bežiaci FlowStream s novou schémou.\n\nPri každom spustení FlowStreamu (aj po automatickom reštarte workera) framework vyšle globálnu udalosť `flowstream`:\n\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream started:', flowstream.id);\n});\n```\n\nPlugin môže obsahovať vlastný flow: súbor `/plugins/{name}/index.flow` sa načíta s pluginom. Jeho `id` je id pluginu a bežiaci FlowStream sa uloží do `PLUGINS[id].flowstream`. Pozri [Pluginy a komponenty](../plugins-and-components/).\n\n## Úpravy v Total.js Flow\n\nEditor komunikuje s FlowStreamom cez WebSocket. Vytvor routu a odovzdaj spojenie do `Flow.socket()`:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', socket);\n};\n\nfunction socket($) {\n\t$.autodestroy();\n\tFlow.socket($.params.id, $);\n}\n```\n\nOtvor `https://flow.totaljs.com/?socket=` a za tým URL-zakódovanú adresu tohto WebSocketu. Editor načíta komponenty a dizajn, zobrazí stav inštancií a každú zmenu uloží späť do FlowStreamu.\n\nFlowStream nezapisuje súbory. Asi 5 sekúnd po zmene vyšle `save` s celou schémou a uložíš ju sám:\n\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nPre vzdialené úpravy `flowstream.edit([url])` otvorí WebSocket klienta k proxy (predvolene `wss://flow.totaljs.com/{id}/`), takže editor sa dostane k FlowStreamu, ktorý beží za firewallom.\n\n## Komponenty\n\nKomponent je text s časťami podobnými HTML. Serverový kód je v `<script total>` (alebo `<script node>`); `<settings>`, `<body>`, `<style>`, `<readme>` a obyčajný `<script>` používa editor.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-text';\n\texports.group = 'Common';\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\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tdata[config.field] = (data[config.field] || '').toUpperCase();\n\t\t\t$.send('output');\n\t\t};\n\n\t\tinstance.configure = function() {\n\t\t\tconfig = instance.config;\n\t\t};\n\n\t};\n\n</script>\n\n<readme>\nConverts a field to upper case.\n</readme>\n```\n\n`exports.make(instance, config)` sa spustí raz pre každú inštanciu komponentu na plátne. Vnútri priraďuješ inštancii delegáty: `message` (prichádzajúca správa), `configure` (nová konfigurácia), `close` (inštancia sa odstraňuje), `variables` (premenné sa zmenili), `trigger` (tlačidlo trigger v editore), `service` (volá sa každú minútu) a ďalšie.\n\n`exports.npm = ['package']` nainštaluje NPM balíky pred registráciou komponentu. `exports.install` a `exports.uninstall` sa spustia, keď sa komponent zaregistruje a odstráni.\n\n## Správy\n\nDelegát `message` dostane správu, zvyčajne nazvanú `$`. `$.data` je payload, `$.repo` je objekt zdieľaný všetkými klonmi správy, `$.input` a `$.output` sú id vstupu a výstupu. `$.send(output, [data])` pošle klon každej inštancii pripojenej k výstupu; klony dát sú hĺbkové kópie, ak flow nemá `cloning: false`. `$.send(null)` pošle na všetky výstupy; správa skončí raz, keď skončia klony všetkých výstupov. Správu, ktorá sa ďalej neposiela, treba ukončiť cez `$.end()`.\n\n```js\ninstance.message = function($) {\n\tif ($.data.price > 100)\n\t\t$.send('expensive');\n\telse\n\t\t$.send('cheap', { price: $.data.price });\n};\n```\n\nŠtvrtý argument `$.send()` filtruje ciele: `$.send('output', null, null, function(from, to, output, input) { return to.component !== 'debug'; })`.\n\nBez prichádzajúcej správy inštancia začne novú cez `instance.send(output, data)` (napríklad z časovača alebo z `trigger`). `instance.send(null, data)` posiela na všetky výstupy. Stav inštancie (zobrazený pod ňou v editore) sa nastavuje cez `instance.status(data)`, chyby sa hlásia cez `instance.throw(err)`. Flow drží posledných 10 chýb v `instance.main.errors`; príkaz reset v editore ich vymaže a flow engine vyšle `reset`, takže inštancia môže vymazať aj svoj vlastný stav:\n\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\nĎalší príklad začína správy z časovača a ako stav zobrazuje čas poslednej z nich:\n\n```js\nexports.make = function(instance, config) {\n\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: NOW });\n\t\tinstance.status({ last: NOW });\n\t}, 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n\n};\n```\n\n## Dáta inštancie\n\n`instance.config` je konfigurácia z editora zlúčená do `exports.config`. `instance.cache` je obyčajný objekt pre tvoje vlastné runtime dáta; uchováva sa v pamäti pre id inštancie, keď sa inštancia znova inicializuje (napríklad po aktualizácii jej komponentu). Po zmene `config` z kódu zavolaj `instance.save()`: flow sa uloží a editor sa prekreslí (`instance.save(false)` uloží bez prekreslenia).\n\n`instance.repo` je objekt uložený v dizajne spolu s inštanciou. Prežije opätovné načítanie aj reštart a editor ho nemení.\n\n## Aktivity\n\nDlhá úloha môže hlásiť svoj priebeh editoru. `instance.activity(key, name, [progress])` vytvorí alebo aktualizuje aktivitu inštancie; `progress` je číslo (percentá). Priebeh `100` alebo prázdny `name` aktivitu odstráni.\n\n```js\ninstance.message = function($) {\n\tinstance.activity('import', 'Importing products', 0);\n\timportproducts($.data, function(percentage) {\n\t\tinstance.activity('import', 'Importing products', percentage);\n\t}, function() {\n\t\tinstance.activity('import', 'Importing products', 100);\n\t\t$.send('output');\n\t});\n};\n```\n\n## Premenné\n\nPremenné flowu sa v reťazcoch nahrádzajú cez `instance.replace(text)` (alebo `$.variables(text)` v správe). Zástupný symbol `{name}` berie hodnotu z premenných flowu, zo secrets, z `{hostname}` alebo z daného dátového objektu.\n\n```js\nvar url = instance.replace('https://api.example.com/orders/?token={token}');\n```\n\n`flowstream.variables(obj)` nahradí premenné bežiaceho flowu; inštancie sú upozornené cez svoj delegát `variables`.\n\n## Ovládanie FlowStreamu z kódu\n\n`Flow.instances[id]` je bežiaci FlowStream. Funguje rovnako pre flowy v hlavnom procese aj vo workeroch.\n\n```js\nvar flowstream = Flow.instances.orders;\n\n// Executes the \"trigger\" delegate of an instance\nflowstream.trigger('instanceid', { manual: true });\n\n// Sends data to an instance and waits for the end of the message\nflowstream.send('instanceid', { id: 1 }, function(err, response) {\n\tconsole.log(response.data, response.duration);\n});\n\nflowstream.pause(true);\nflowstream.reconfigure('instanceid', { field: 'title' });\nflowstream.export(function(err, schema) {});\n```\n\nId inštancií možno nahradiť cez `@component` (inštancie s id komponentu) alebo `#name` (inštancie s názvom komponentu).\n\n`Flow.remove(id)` zastaví FlowStream a odstráni ho.\n\n## Workery\n\nS `worker: 'worker'` (worker vlákno) alebo `worker: 'process'` (podriadený proces) flow beží mimo hlavného procesu, takže pokazený komponent nemôže zablokovať aplikáciu. Worker, ktorý skončí, sa po sekunde automaticky spustí znova. `memory: 512` obmedzí haldu workera na 512 MB. `flowstream.restart()` alebo `Flow.restart(id)` ukončí workera, aby sa spustil znova s aktuálnou schémou. Pre flow v hlavnom procese `instance.main.restart()` (a príkaz reštartu v editore) požiada správcu procesov Total.js o reštart celej aplikácie.\n\nS `proxypath` worker spustí vlastný HTTP server na Unix sockete a hlavná aplikácia mu preposiela požiadavky pod touto cestou. `proxytimeout` nastavuje timeout tejto proxy; aplikuje sa, keď sa schéma znova načíta do bežiaceho FlowStreamu.\n\n`flowstream.stats` obsahuje počítadlá: `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` (správy za poslednú minútu) a `paused`. Pre flow v hlavnom procese je `online` počet editorov, ktoré sú k nemu pripojené. Pre flowy vo workeroch `Flow.on('stats', function(id, stats) {})` dostáva počítadlá každých 15 sekúnd.\n\n## Notifikácie\n\n`Flow.notify($, id)` odovzdá HTTP požiadavku delegátu `notify` inštancie. `id` je `flowid-instanceid`. Routy si zaregistruj sám:\n\n```js\nexports.install = function() {\n\tROUTE('GET /notify/{id}/', notify);\n\tROUTE('POST /notify/{id}/ <1MB', notify);\n};\n\nfunction notify($) {\n\tFlow.notify($, $.params.id);\n}\n```\n\n## Zdroje TMS\n\nV editore môžeš pridať zdroj TMS (URL a token inej Total.js aplikácie). FlowStream sa k nemu pripojí a zo schém zdroja vytvorí komponenty Publish, Subscribe a Call, takže správy môžu prechádzať medzi aplikáciami. Zdroje sa ukladajú v kľúči `sources` schémy. Pozri [Message Service (TMS)](../message-service-and-apis/).\n\n## Testovanie komponentu\n\n`Flow.test(name, source, [config], init)` načíta jeden komponent do testovacieho flowu a dá ti objekt `Test`:\n\n```js\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER', 'uppercase');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n## Príkaz flow5\n\nBalík `total5` inštaluje príkaz `flow5`. Načíta jednu alebo viac schém zo súborov alebo HTTPS URL a spustí HTTP server s WebSocket routou pre editor:\n\n```bash\nflow5 orders.json 8001\n```\n\nZmeny urobené v editore sa zapíšu späť do JSON súborov. Pozri [Príkazový riadok](../command-line/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JacX9h23u60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Message Service (TMS)","summary":"Publish events, receive messages and answer calls over TMS.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/message-service-and-apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# Message Service (TMS)\n\n> Publish events, receive messages and answer calls over TMS.\n\nTotal.js 5 has two small layers for talking to other services:\n\n- **TMS** (Total.js Message Service) opens a WebSocket endpoint in your application. Connected apps receive the events you publish, send you messages and call your procedures. Every message has a name and a JSON schema that validates it.\n- **APIs** give a name to a remote service. You write the code that talks to the service once with `NEWAPI()` and then call it anywhere with `API()`. The built-in `TAPI` service calls Total.js API.\n\n## Enabling TMS\n\nTMS is off by default. Turn it on in the configuration and set a token:\n\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\nThe endpoint is `$tmsurl` (default `/$tms/`) and the maximum message size is `$tmsmaxsize` kB (default `256`). A client must send the token in the `x-token` header. A wrong token closes the connection with code `4001`; an IP address with more than five wrong attempts is refused until the blocked list is cleared, every `$tmsclearblocked` minutes (default `60`). When `secret_tms` changes through `LOADCONFIG()`, all connected clients are disconnected.\n\nAfter the connection opens, the server sends a `meta` message: the name of the app (`CONF.name`) and the lists of publishers, subscribers and calls, each with its JSON schema. The list is sent again (500 ms after the last change) whenever you register or remove a name. A message `{ type: 'ping' }` is answered with `{ type: 'pong' }`.\n\n## Publishing events\n\n`NEWPUBLISH()` declares an event and its schema. `PUBLISH()` sends data to every connected client that subscribed to that event:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\n// anywhere in the app\nPUBLISH('orders_created', { id: order.id, email: order.email, total: order.total });\n```\n\n`PUBLISH()` does nothing when TMS is off, when no client is connected or when the name was not declared with `NEWPUBLISH()`. The server does not validate the data; the receiving `TMSCLIENT()` cleans it with the schema from `meta`. `NEWPUBLISH(name, null)` removes the event.\n\n## Receiving messages\n\n`NEWSUBSCRIBE()` declares a message that clients may send to your app, with its schema. `SUBSCRIBE()` adds a handler for it:\n\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String, email:Email');\n\nSUBSCRIBE('users_updated', function(msg, client) {\n\t// msg.response is the validated data\n\tvar user = msg.response;\n\tconsole.log('From', client.ip, user.id, user.name);\n});\n```\n\nA message that does not pass the schema is dropped. A handler receives the result of the validation (`msg.response` holds the data, `msg.error` is `null`) and the WebSocket client that sent the message. You can pass the handler as the third argument of `NEWSUBSCRIBE()` instead of calling `SUBSCRIBE()`. `UNSUBSCRIBE(name, [handler])` removes one handler, or all handlers of the name.\n\n## Remote calls\n\n`NEWCALL()` declares a procedure that clients can call and wait for its answer:\n\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard', price: 49 });\n});\n```\n\n`next(err, response)` answers the client. An `ErrorBuilder` is sent as its output; any other error becomes `[{ error: '...' }]`. Data that does not pass the schema is answered with the validation errors without running the callback, and an unknown message type is answered with a `404` error. `NEWCALL(name, null)` removes the call.\n\n## Connecting to TMS\n\n`TMSCLIENT()` connects your app to the TMS endpoint of another Total.js app. An `http(s)://` address is changed to `ws(s)://`, and the client reconnects automatically:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\n\tconsole.log('Connected to', meta.name);\n\n\t// Events published by the server with PUBLISH()\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log('New order', order.id);\n\t});\n\n\t// Messages for the server's NEWSUBSCRIBE()\n\tclient.publish('users_updated', { id: user.id, name: user.name });\n\n\t// Procedures declared with NEWCALL()\n\tclient.call('products_detail', { id: '123' }, function(err, product) {\n\t\tconsole.log(err, product);\n\t});\n});\n```\n\nThe callback runs once: with the client when the first `meta` message arrives, or with the close code as `err` when the connection closes before that. The client then fires the `ready` and `meta` events after every (re)connection and keeps the last message in `client.meta`. `client.call()` returns a promise when you omit the callback, fails with `TMS is offline` when the client is not connected and with `408: Timeout` after 10 seconds (or your timeout). Subscriptions you add are sent to the server, so it only pushes the events you want. `client.destroy()` closes the connection and fails the pending calls.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JacX9h23u60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Message Service (TMS)","summary":"Events veröffentlichen, Nachrichten empfangen und Aufrufe über TMS beantworten.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/message-service-and-apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# Message Service (TMS)\n\n> Events veröffentlichen, Nachrichten empfangen und Aufrufe über TMS beantworten.\n\nTotal.js 5 hat zwei kleine Schichten, um mit anderen Diensten zu kommunizieren:\n\n- **TMS** (Total.js Message Service) öffnet einen WebSocket-Endpunkt in deiner Anwendung. Verbundene Anwendungen empfangen die Events, die du veröffentlichst, senden dir Nachrichten und rufen deine Prozeduren auf. Jede Nachricht hat einen Namen und ein JSON-Schema, das sie validiert.\n- **APIs** geben einem entfernten Dienst einen Namen. Du schreibst den Code, der mit dem Dienst spricht, einmal mit `NEWAPI()` und rufst ihn dann überall mit `API()` auf. Der eingebaute Dienst `TAPI` ruft Total.js API auf.\n\n## TMS aktivieren\n\nTMS ist standardmäßig aus. Schalte es in der Konfiguration ein und setze ein Token:\n\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\nDer Endpunkt ist `$tmsurl` (Standard `/$tms/`) und die maximale Nachrichtengröße ist `$tmsmaxsize` kB (Standard `256`). Ein Client muss das Token im Header `x-token` senden. Ein falsches Token schließt die Verbindung mit dem Code `4001`; eine IP-Adresse mit mehr als fünf Fehlversuchen wird abgewiesen, bis die Sperrliste geleert wird, alle `$tmsclearblocked` Minuten (Standard `60`). Wenn sich `secret_tms` über `LOADCONFIG()` ändert, werden alle verbundenen Clients getrennt.\n\nNach dem Öffnen der Verbindung sendet der Server eine Nachricht `meta`: den Namen der Anwendung (`CONF.name`) und die Listen der Publisher, Subscriber und Calls, jeweils mit ihrem JSON-Schema. Die Liste wird erneut gesendet (500 ms nach der letzten Änderung), sobald du einen Namen registrierst oder entfernst. Eine Nachricht `{ type: 'ping' }` wird mit `{ type: 'pong' }` beantwortet.\n\n## Events veröffentlichen\n\n`NEWPUBLISH()` deklariert ein Event und sein Schema. `PUBLISH()` sendet Daten an jeden verbundenen Client, der dieses Event abonniert hat:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\n// anywhere in the app\nPUBLISH('orders_created', { id: order.id, email: order.email, total: order.total });\n```\n\n`PUBLISH()` tut nichts, wenn TMS aus ist, wenn kein Client verbunden ist oder wenn der Name nicht mit `NEWPUBLISH()` deklariert wurde. Der Server validiert die Daten nicht; der empfangende `TMSCLIENT()` bereinigt sie mit dem Schema aus `meta`. `NEWPUBLISH(name, null)` entfernt das Event.\n\n## Nachrichten empfangen\n\n`NEWSUBSCRIBE()` deklariert eine Nachricht, die Clients an deine Anwendung senden dürfen, mit ihrem Schema. `SUBSCRIBE()` fügt einen Handler dafür hinzu:\n\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String, email:Email');\n\nSUBSCRIBE('users_updated', function(msg, client) {\n\t// msg.response is the validated data\n\tvar user = msg.response;\n\tconsole.log('From', client.ip, user.id, user.name);\n});\n```\n\nEine Nachricht, die das Schema nicht besteht, wird verworfen. Ein Handler erhält das Ergebnis der Validierung (`msg.response` enthält die Daten, `msg.error` ist `null`) und den WebSocket-Client, der die Nachricht gesendet hat. Du kannst den Handler als drittes Argument von `NEWSUBSCRIBE()` übergeben, statt `SUBSCRIBE()` aufzurufen. `UNSUBSCRIBE(name, [handler])` entfernt einen Handler oder alle Handler des Namens.\n\n## Entfernte Aufrufe\n\n`NEWCALL()` deklariert eine Prozedur, die Clients aufrufen und auf deren Antwort sie warten können:\n\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard', price: 49 });\n});\n```\n\n`next(err, response)` antwortet dem Client. Ein `ErrorBuilder` wird als seine Ausgabe gesendet; jeder andere Fehler wird zu `[{ error: '...' }]`. Daten, die das Schema nicht bestehen, werden mit den Validierungsfehlern beantwortet, ohne den Callback auszuführen, und ein unbekannter Nachrichtentyp wird mit einem `404`-Fehler beantwortet. `NEWCALL(name, null)` entfernt den Call.\n\n## Mit TMS verbinden\n\n`TMSCLIENT()` verbindet deine Anwendung mit dem TMS-Endpunkt einer anderen Total.js-Anwendung. Eine `http(s)://`-Adresse wird zu `ws(s)://` geändert, und der Client verbindet sich automatisch neu:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\n\tconsole.log('Connected to', meta.name);\n\n\t// Events published by the server with PUBLISH()\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log('New order', order.id);\n\t});\n\n\t// Messages for the server's NEWSUBSCRIBE()\n\tclient.publish('users_updated', { id: user.id, name: user.name });\n\n\t// Procedures declared with NEWCALL()\n\tclient.call('products_detail', { id: '123' }, function(err, product) {\n\t\tconsole.log(err, product);\n\t});\n});\n```\n\nDer Callback läuft einmal: mit dem Client, wenn die erste Nachricht `meta` eintrifft, oder mit dem Close-Code als `err`, wenn die Verbindung vorher geschlossen wird. Danach löst der Client nach jeder (Neu-)Verbindung die Events `ready` und `meta` aus und hält die letzte Nachricht in `client.meta`. `client.call()` gibt ein Promise zurück, wenn du den Callback weglässt, schlägt mit `TMS is offline` fehl, wenn der Client nicht verbunden ist, und mit `408: Timeout` nach 10 Sekunden (oder deinem Timeout). Abonnements, die du hinzufügst, werden an den Server gesendet, sodass er nur die Events pusht, die du willst. `client.destroy()` schließt die Verbindung und lässt die ausstehenden Calls fehlschlagen.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JacX9h23u60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Message Service (TMS)","summary":"Publica eventos, recibe mensajes y responde a llamadas mediante TMS.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/message-service-and-apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# Message Service (TMS)\n\n> Publica eventos, recibe mensajes y responde a llamadas mediante TMS.\n\nTotal.js 5 tiene dos pequeñas capas para comunicarse con otros servicios:\n\n- **TMS** (Total.js Message Service) abre un endpoint WebSocket en tu aplicación. Las aplicaciones conectadas reciben los eventos que publicas, te envían mensajes y llaman a tus procedimientos. Cada mensaje tiene un nombre y un esquema JSON que lo valida.\n- Las **APIs** dan un nombre a un servicio remoto. Escribes una vez el código que se comunica con el servicio con `NEWAPI()` y luego lo llamas desde cualquier lugar con `API()`. El servicio integrado `TAPI` llama a Total.js API.\n\n## Activar TMS\n\nTMS está desactivado por defecto. Actívalo en la configuración y establece un token:\n\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\nEl endpoint es `$tmsurl` (por defecto `/$tms/`) y el tamaño máximo de mensaje es `$tmsmaxsize` kB (por defecto `256`). Un cliente debe enviar el token en la cabecera `x-token`. Un token incorrecto cierra la conexión con el código `4001`; una dirección IP con más de cinco intentos fallidos se rechaza hasta que se vacía la lista de bloqueados, cada `$tmsclearblocked` minutos (por defecto `60`). Cuando `secret_tms` cambia mediante `LOADCONFIG()`, se desconectan todos los clientes conectados.\n\nUna vez abierta la conexión, el servidor envía un mensaje `meta`: el nombre de la aplicación (`CONF.name`) y las listas de publicadores, suscriptores y llamadas, cada uno con su esquema JSON. La lista se vuelve a enviar (500 ms después del último cambio) cada vez que registras o eliminas un nombre. Un mensaje `{ type: 'ping' }` se responde con `{ type: 'pong' }`.\n\n## Publicar eventos\n\n`NEWPUBLISH()` declara un evento y su esquema. `PUBLISH()` envía datos a cada cliente conectado que se suscribió a ese evento:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\n// anywhere in the app\nPUBLISH('orders_created', { id: order.id, email: order.email, total: order.total });\n```\n\n`PUBLISH()` no hace nada cuando TMS está desactivado, cuando no hay ningún cliente conectado o cuando el nombre no se declaró con `NEWPUBLISH()`. El servidor no valida los datos; el `TMSCLIENT()` que los recibe los limpia con el esquema de `meta`. `NEWPUBLISH(name, null)` elimina el evento.\n\n## Recibir mensajes\n\n`NEWSUBSCRIBE()` declara un mensaje que los clientes pueden enviar a tu aplicación, con su esquema. `SUBSCRIBE()` añade un handler para él:\n\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String, email:Email');\n\nSUBSCRIBE('users_updated', function(msg, client) {\n\t// msg.response is the validated data\n\tvar user = msg.response;\n\tconsole.log('From', client.ip, user.id, user.name);\n});\n```\n\nUn mensaje que no supera el esquema se descarta. Un handler recibe el resultado de la validación (`msg.response` contiene los datos, `msg.error` es `null`) y el cliente WebSocket que envió el mensaje. Puedes pasar el handler como tercer argumento de `NEWSUBSCRIBE()` en lugar de llamar a `SUBSCRIBE()`. `UNSUBSCRIBE(name, [handler])` elimina un handler, o todos los handlers del nombre.\n\n## Llamadas remotas\n\n`NEWCALL()` declara un procedimiento que los clientes pueden llamar y esperar su respuesta:\n\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard', price: 49 });\n});\n```\n\n`next(err, response)` responde al cliente. Un `ErrorBuilder` se envía como su salida; cualquier otro error se convierte en `[{ error: '...' }]`. Los datos que no superan el esquema se responden con los errores de validación sin ejecutar el callback, y un tipo de mensaje desconocido se responde con un error `404`. `NEWCALL(name, null)` elimina la llamada.\n\n## Conectarse a TMS\n\n`TMSCLIENT()` conecta tu aplicación al endpoint TMS de otra aplicación Total.js. Una dirección `http(s)://` se cambia a `ws(s)://`, y el cliente se reconecta automáticamente:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\n\tconsole.log('Connected to', meta.name);\n\n\t// Events published by the server with PUBLISH()\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log('New order', order.id);\n\t});\n\n\t// Messages for the server's NEWSUBSCRIBE()\n\tclient.publish('users_updated', { id: user.id, name: user.name });\n\n\t// Procedures declared with NEWCALL()\n\tclient.call('products_detail', { id: '123' }, function(err, product) {\n\t\tconsole.log(err, product);\n\t});\n});\n```\n\nEl callback se ejecuta una vez: con el cliente cuando llega el primer mensaje `meta`, o con el código de cierre como `err` cuando la conexión se cierra antes. Después, el cliente dispara los eventos `ready` y `meta` tras cada (re)conexión y guarda el último mensaje en `client.meta`. `client.call()` devuelve una promesa cuando omites el callback, falla con `TMS is offline` cuando el cliente no está conectado y con `408: Timeout` tras 10 segundos (o tu timeout). Las suscripciones que añades se envían al servidor, para que solo te envíe los eventos que quieres. `client.destroy()` cierra la conexión y hace fallar las llamadas pendientes.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JacX9h23u60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Message Service (TMS)","summary":"Publie des événements, reçois des messages et réponds aux appels via TMS.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/message-service-and-apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# Message Service (TMS)\n\n> Publie des événements, reçois des messages et réponds aux appels via TMS.\n\nTotal.js 5 dispose de deux petites couches pour communiquer avec d'autres services :\n\n- **TMS** (Total.js Message Service) ouvre un endpoint WebSocket dans ton application. Les applications connectées reçoivent les événements que tu publies, t'envoient des messages et appellent tes procédures. Chaque message a un nom et un schéma JSON qui le valide.\n- Les **API** donnent un nom à un service distant. Tu écris une fois le code qui communique avec le service avec `NEWAPI()`, puis tu l'appelles n'importe où avec `API()`. Le service intégré `TAPI` appelle Total.js API.\n\n## Activer TMS\n\nTMS est désactivé par défaut. Active-le dans la configuration et définis un token :\n\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\nL'endpoint est `$tmsurl` (par défaut `/$tms/`) et la taille maximale d'un message est de `$tmsmaxsize` ko (par défaut `256`). Un client doit envoyer le token dans l'en-tête `x-token`. Un token incorrect ferme la connexion avec le code `4001` ; une adresse IP ayant plus de cinq tentatives incorrectes est refusée jusqu'à ce que la liste de blocage soit vidée, toutes les `$tmsclearblocked` minutes (par défaut `60`). Quand `secret_tms` change via `LOADCONFIG()`, tous les clients connectés sont déconnectés.\n\nAprès l'ouverture de la connexion, le serveur envoie un message `meta` : le nom de l'application (`CONF.name`) et les listes des publishers, des subscribers et des appels, chacun avec son schéma JSON. La liste est renvoyée (500 ms après la dernière modification) chaque fois que tu enregistres ou supprimes un nom. Un message `{ type: 'ping' }` reçoit la réponse `{ type: 'pong' }`.\n\n## Publier des événements\n\n`NEWPUBLISH()` déclare un événement et son schéma. `PUBLISH()` envoie des données à chaque client connecté abonné à cet événement :\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\n// anywhere in the app\nPUBLISH('orders_created', { id: order.id, email: order.email, total: order.total });\n```\n\n`PUBLISH()` ne fait rien quand TMS est désactivé, quand aucun client n'est connecté ou quand le nom n'a pas été déclaré avec `NEWPUBLISH()`. Le serveur ne valide pas les données ; le `TMSCLIENT()` qui les reçoit les nettoie avec le schéma de `meta`. `NEWPUBLISH(name, null)` supprime l'événement.\n\n## Recevoir des messages\n\n`NEWSUBSCRIBE()` déclare un message que les clients peuvent envoyer à ton application, avec son schéma. `SUBSCRIBE()` lui ajoute un handler :\n\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String, email:Email');\n\nSUBSCRIBE('users_updated', function(msg, client) {\n\t// msg.response is the validated data\n\tvar user = msg.response;\n\tconsole.log('From', client.ip, user.id, user.name);\n});\n```\n\nUn message qui ne passe pas le schéma est abandonné. Un handler reçoit le résultat de la validation (`msg.response` contient les données, `msg.error` vaut `null`) et le client WebSocket qui a envoyé le message. Tu peux passer le handler comme troisième argument de `NEWSUBSCRIBE()` au lieu d'appeler `SUBSCRIBE()`. `UNSUBSCRIBE(name, [handler])` supprime un handler, ou tous les handlers du nom.\n\n## Appels distants\n\n`NEWCALL()` déclare une procédure que les clients peuvent appeler en attendant sa réponse :\n\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard', price: 49 });\n});\n```\n\n`next(err, response)` répond au client. Un `ErrorBuilder` est envoyé sous forme de sa sortie ; toute autre erreur devient `[{ error: '...' }]`. Les données qui ne passent pas le schéma reçoivent en réponse les erreurs de validation sans exécution du callback, et un type de message inconnu reçoit une erreur `404`. `NEWCALL(name, null)` supprime l'appel.\n\n## Se connecter à TMS\n\n`TMSCLIENT()` connecte ton application à l'endpoint TMS d'une autre application Total.js. Une adresse `http(s)://` est changée en `ws(s)://`, et le client se reconnecte automatiquement :\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\n\tconsole.log('Connected to', meta.name);\n\n\t// Events published by the server with PUBLISH()\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log('New order', order.id);\n\t});\n\n\t// Messages for the server's NEWSUBSCRIBE()\n\tclient.publish('users_updated', { id: user.id, name: user.name });\n\n\t// Procedures declared with NEWCALL()\n\tclient.call('products_detail', { id: '123' }, function(err, product) {\n\t\tconsole.log(err, product);\n\t});\n});\n```\n\nLe callback s'exécute une fois : avec le client quand le premier message `meta` arrive, ou avec le code de fermeture comme `err` si la connexion se ferme avant. Le client déclenche ensuite les événements `ready` et `meta` après chaque (re)connexion et garde le dernier message dans `client.meta`. `client.call()` renvoie une promesse si tu omets le callback, échoue avec `TMS is offline` quand le client n'est pas connecté et avec `408: Timeout` après 10 secondes (ou ton timeout). Les abonnements que tu ajoutes sont envoyés au serveur, afin qu'il ne pousse que les événements souhaités. `client.destroy()` ferme la connexion et fait échouer les appels en attente.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JacX9h23u60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Message Service (TMS)","summary":"Pubblica eventi, ricevi messaggi e rispondi alle chiamate tramite TMS.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/message-service-and-apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# Message Service (TMS)\n\n> Pubblica eventi, ricevi messaggi e rispondi alle chiamate tramite TMS.\n\nTotal.js 5 ha due piccoli livelli per comunicare con altri servizi:\n\n- **TMS** (Total.js Message Service) apre un endpoint WebSocket nella tua applicazione. Le app collegate ricevono gli eventi che pubblichi, ti inviano messaggi e chiamano le tue procedure. Ogni messaggio ha un nome e uno schema JSON che lo valida.\n- Le **API** danno un nome a un servizio remoto. Scrivi una volta con `NEWAPI()` il codice che comunica con il servizio e poi lo chiami ovunque con `API()`. Il servizio integrato `TAPI` chiama Total.js API.\n\n## Attivare TMS\n\nTMS è disattivato per impostazione predefinita. Attivalo nella configurazione e imposta un token:\n\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\nL'endpoint è `$tmsurl` (predefinito `/$tms/`) e la dimensione massima dei messaggi è `$tmsmaxsize` kB (predefinito `256`). Un client deve inviare il token nell'header `x-token`. Un token errato chiude la connessione con il codice `4001`; un indirizzo IP con più di cinque tentativi errati viene rifiutato finché l'elenco dei bloccati non viene svuotato, ogni `$tmsclearblocked` minuti (predefinito `60`). Quando `secret_tms` cambia tramite `LOADCONFIG()`, tutti i client collegati vengono disconnessi.\n\nDopo l'apertura della connessione, il server invia un messaggio `meta`: il nome dell'app (`CONF.name`) e gli elenchi di publisher, subscriber e call, ciascuno con il suo schema JSON. L'elenco viene inviato di nuovo (500 ms dopo l'ultima modifica) ogni volta che registri o rimuovi un nome. A un messaggio `{ type: 'ping' }` si risponde con `{ type: 'pong' }`.\n\n## Pubblicare eventi\n\n`NEWPUBLISH()` dichiara un evento e il suo schema. `PUBLISH()` invia dati a ogni client collegato che si è iscritto a quell'evento:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\n// anywhere in the app\nPUBLISH('orders_created', { id: order.id, email: order.email, total: order.total });\n```\n\n`PUBLISH()` non fa nulla quando TMS è disattivato, quando nessun client è collegato o quando il nome non è stato dichiarato con `NEWPUBLISH()`. Il server non valida i dati; il `TMSCLIENT()` ricevente li ripulisce con lo schema di `meta`. `NEWPUBLISH(name, null)` rimuove l'evento.\n\n## Ricevere messaggi\n\n`NEWSUBSCRIBE()` dichiara un messaggio che i client possono inviare alla tua app, con il suo schema. `SUBSCRIBE()` aggiunge un handler per esso:\n\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String, email:Email');\n\nSUBSCRIBE('users_updated', function(msg, client) {\n\t// msg.response is the validated data\n\tvar user = msg.response;\n\tconsole.log('From', client.ip, user.id, user.name);\n});\n```\n\nUn messaggio che non supera lo schema viene scartato. Un handler riceve il risultato della validazione (`msg.response` contiene i dati, `msg.error` è `null`) e il client WebSocket che ha inviato il messaggio. Puoi passare l'handler come terzo argomento di `NEWSUBSCRIBE()` invece di chiamare `SUBSCRIBE()`. `UNSUBSCRIBE(name, [handler])` rimuove un handler, oppure tutti gli handler del nome.\n\n## Chiamate remote\n\n`NEWCALL()` dichiara una procedura che i client possono chiamare attendendo la sua risposta:\n\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard', price: 49 });\n});\n```\n\n`next(err, response)` risponde al client. Un `ErrorBuilder` viene inviato come suo output; qualsiasi altro errore diventa `[{ error: '...' }]`. Ai dati che non superano lo schema si risponde con gli errori di validazione senza eseguire la callback, e a un tipo di messaggio sconosciuto si risponde con un errore `404`. `NEWCALL(name, null)` rimuove la call.\n\n## Collegarsi a TMS\n\n`TMSCLIENT()` collega la tua app all'endpoint TMS di un'altra app Total.js. Un indirizzo `http(s)://` viene cambiato in `ws(s)://`, e il client si riconnette automaticamente:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\n\tconsole.log('Connected to', meta.name);\n\n\t// Events published by the server with PUBLISH()\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log('New order', order.id);\n\t});\n\n\t// Messages for the server's NEWSUBSCRIBE()\n\tclient.publish('users_updated', { id: user.id, name: user.name });\n\n\t// Procedures declared with NEWCALL()\n\tclient.call('products_detail', { id: '123' }, function(err, product) {\n\t\tconsole.log(err, product);\n\t});\n});\n```\n\nLa callback viene eseguita una volta: con il client quando arriva il primo messaggio `meta`, oppure con il codice di chiusura come `err` quando la connessione si chiude prima. Il client poi emette gli eventi `ready` e `meta` dopo ogni (ri)connessione e conserva l'ultimo messaggio in `client.meta`. `client.call()` restituisce una promise quando ometti la callback, fallisce con `TMS is offline` quando il client non è collegato e con `408: Timeout` dopo 10 secondi (o il tuo timeout). Le iscrizioni che aggiungi vengono inviate al server, così invia solo gli eventi che vuoi. `client.destroy()` chiude la connessione e fa fallire le chiamate in sospeso.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JacX9h23u60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Message Service (TMS)","summary":"Publikovanie udalostí, prijímanie správ a odpovedanie na volania cez TMS.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/message-service-and-apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# Message Service (TMS)\n\n> Publikovanie udalostí, prijímanie správ a odpovedanie na volania cez TMS.\n\nTotal.js 5 má dve malé vrstvy na komunikáciu s inými službami:\n\n- **TMS** (Total.js Message Service) otvorí v tvojej aplikácii WebSocket endpoint. Pripojené aplikácie dostávajú udalosti, ktoré publikuješ, posielajú ti správy a volajú tvoje procedúry. Každá správa má názov a JSON schému, ktorá ju validuje.\n- **API** dávajú vzdialenej službe názov. Kód, ktorý so službou komunikuje, napíšeš raz cez `NEWAPI()` a potom ho voláš kdekoľvek cez `API()`. Vstavaná služba `TAPI` volá Total.js API.\n\n## Zapnutie TMS\n\nTMS je predvolene vypnuté. Zapni ho v konfigurácii a nastav token:\n\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\nEndpoint je `$tmsurl` (predvolene `/$tms/`) a maximálna veľkosť správy je `$tmsmaxsize` kB (predvolene `256`). Klient musí poslať token v hlavičke `x-token`. Zlý token zatvorí spojenie s kódom `4001`; IP adresa s viac ako piatimi zlými pokusmi je odmietaná, kým sa zoznam blokovaných nevyčistí, každých `$tmsclearblocked` minút (predvolene `60`). Keď sa `secret_tms` zmení cez `LOADCONFIG()`, všetci pripojení klienti sa odpoja.\n\nPo otvorení spojenia server pošle správu `meta`: názov aplikácie (`CONF.name`) a zoznamy publisherov, subscriberov a volaní, každý s jeho JSON schémou. Zoznam sa pošle znova (500 ms po poslednej zmene) vždy, keď zaregistruješ alebo odstrániš názov. Na správu `{ type: 'ping' }` sa odpovie `{ type: 'pong' }`.\n\n## Publikovanie udalostí\n\n`NEWPUBLISH()` deklaruje udalosť a jej schému. `PUBLISH()` pošle dáta každému pripojenému klientovi, ktorý sa na túto udalosť prihlásil:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\n// anywhere in the app\nPUBLISH('orders_created', { id: order.id, email: order.email, total: order.total });\n```\n\n`PUBLISH()` nerobí nič, keď je TMS vypnuté, keď nie je pripojený žiadny klient alebo keď názov nebol deklarovaný cez `NEWPUBLISH()`. Server dáta nevaliduje; prijímajúci `TMSCLIENT()` ich vyčistí schémou z `meta`. `NEWPUBLISH(name, null)` udalosť odstráni.\n\n## Prijímanie správ\n\n`NEWSUBSCRIBE()` deklaruje správu, ktorú môžu klienti posielať tvojej aplikácii, s jej schémou. `SUBSCRIBE()` pre ňu pridá handler:\n\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String, email:Email');\n\nSUBSCRIBE('users_updated', function(msg, client) {\n\t// msg.response is the validated data\n\tvar user = msg.response;\n\tconsole.log('From', client.ip, user.id, user.name);\n});\n```\n\nSpráva, ktorá neprejde schémou, sa zahodí. Handler dostane výsledok validácie (`msg.response` obsahuje dáta, `msg.error` je `null`) a WebSocket klienta, ktorý správu poslal. Handler môžeš odovzdať ako tretí argument `NEWSUBSCRIBE()` namiesto volania `SUBSCRIBE()`. `UNSUBSCRIBE(name, [handler])` odstráni jeden handler alebo všetky handlery daného názvu.\n\n## Vzdialené volania\n\n`NEWCALL()` deklaruje procedúru, ktorú môžu klienti zavolať a čakať na jej odpoveď:\n\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard', price: 49 });\n});\n```\n\n`next(err, response)` odpovie klientovi. `ErrorBuilder` sa pošle ako jeho výstup; akákoľvek iná chyba sa stane `[{ error: '...' }]`. Na dáta, ktoré neprejdú schémou, sa odpovie validačnými chybami bez spustenia callbacku a na neznámy typ správy sa odpovie chybou `404`. `NEWCALL(name, null)` volanie odstráni.\n\n## Pripojenie k TMS\n\n`TMSCLIENT()` pripojí tvoju aplikáciu k TMS endpointu inej Total.js aplikácie. Adresa `http(s)://` sa zmení na `ws(s)://` a klient sa automaticky znova pripája:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\n\tconsole.log('Connected to', meta.name);\n\n\t// Events published by the server with PUBLISH()\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log('New order', order.id);\n\t});\n\n\t// Messages for the server's NEWSUBSCRIBE()\n\tclient.publish('users_updated', { id: user.id, name: user.name });\n\n\t// Procedures declared with NEWCALL()\n\tclient.call('products_detail', { id: '123' }, function(err, product) {\n\t\tconsole.log(err, product);\n\t});\n});\n```\n\nCallback sa spustí raz: s klientom, keď príde prvá správa `meta`, alebo s kódom zatvorenia ako `err`, keď sa spojenie zatvorí skôr. Klient potom po každom (opätovnom) pripojení vyvolá udalosti `ready` a `meta` a poslednú správu uchováva v `client.meta`. `client.call()` vráti promise, keď vynecháš callback, zlyhá s `TMS is offline`, keď klient nie je pripojený, a s `408: Timeout` po 10 sekundách (alebo po tvojom timeoute). Odbery, ktoré pridáš, sa pošlú serveru, takže posiela iba udalosti, ktoré chceš. `client.destroy()` zatvorí spojenie a nechá čakajúce volania zlyhať.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JafMt93oH61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"APIs","summary":"Register named APIs with NEWAPI(), call remote services through them with API(), and use the Total.js API service.","markdown":"---\ntitle: APIs\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# APIs\n\n> Register named APIs with NEWAPI(), call remote services through them with API(), and use the Total.js API service.\n\n## Registering an API\n\n`NEWAPI()` registers the code that talks to one service. It receives the options of the call and a `next(err, response)` callback; `this` is the API call:\n\n```js\nNEWAPI('Weather', function(opt, next) {\n\t// opt.schema is the operation, opt.data the payload\n\tvar req = {};\n\treq.url = 'https://api.weather.example/' + opt.schema + '/?q=' + encodeURIComponent(opt.data.city);\n\treq.method = 'GET';\n\treq.type = 'json';\n\treq.callback = function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response && response.body.parseJSON());\n\t};\n\tREQUEST(req);\n});\n```\n\nA name is found in the spelling given to `NEWAPI()` or in lower case, and several names separated by commas share one handler. The name `*` registers a handler for every name that has none. A function alone (or a config object and a function) registers the name `default`, and `NEWAPI(name, null)` removes a handler. `opt.retry()` runs the handler again and increases `opt.retries`.\n\nAn optional `config` object between the name and the handler holds default settings. They are copied into `opt.config` of every call, unless the call sets the same key with `.configure()`:\n\n```js\nNEWAPI('Weather', { region: 'eu', units: 'metric' }, function(opt, next) {\n\t// opt.config.region, opt.config.units\n\tnext(null, { region: opt.config.region });\n});\n\nAPI('Weather', 'current', { city: 'Oslo' }).configure({ units: 'imperial' }).callback(console.log);\n```\n\n## Calling an API\n\n`API(name, schema, data, [$])` runs the handler on the next tick and returns an object whose methods configure the call:\n\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).error('City not found').callback($);\n\t}\n});\n\n// with a promise\nvar forecast = await API('Weather', 'forecast', { city: 'Bratislava' }).promise();\n```\n\n| Method | What it does |\n| --- | --- |\n| `.callback(fn)`, `.pipe(fn)` | Sets `function(err, response)`, or passes the result to `$.callback()` |\n| `.promise([$])` | Returns a promise; with `$` an error goes to `$.invalid()` |\n| `.data(fn)` / `.fail(fn)` | Runs `fn(response)` on success or `fn(err)` on error |\n| `.error(message, [reverse])` | Turns an empty response (or, with `reverse`, any truthy one, an empty array too) into an error |\n| `.output(type)` | Sets `opt.output`, the format the handler should return |\n| `.file(filename, path, [name])` | Adds a file to `opt.files` |\n| `.configure(obj)` | Copies keys into `opt.config` |\n| `.controller($)` | Sets `opt.controller` |\n| `.audit($, message, [type])` | Writes an audit log with `$.audit()` after a successful call |\n| `.debug()` | Prints the error and the response to the console |\n\nA name without a handler (and no `*` handler) fails with `API is not initialized`.\n\n## Total.js API\n\n`TotalAPI(schema, data, [callback])` is a short form of `API('TAPI', schema, data)`. It sends a `POST` request to `https://<$tapiurl>.api.totaljs.com/<schema>/` with your token:\n\n```js\n// /config\ntotalapi       : your-totalapi-token\n\n// code\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n\n// \"operation\" is the name of a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\nThe token is read from `.configure({ token: '...' })`, then `CONF.totalapi`, `CONF.secret_totalapi` or `CONF.$tapisecret`. When `$tapi` is `false`, every operation except `check` fails with `totalapi_inactive`. With `.output()` you choose the format of the response: `json` (default), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream`, or `#storage [id] [filename]`, which saves the response into a [FileStorage](../../guides/file-storage/) and returns the metadata of the saved file. Error responses (status above `200`) fail with the error message sent by Total API.\n\nFor the WebSocket server itself see [WebSockets](../../guides/websockets/), and for outgoing HTTP calls see [HTTP requests](../../guides/http-requests/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JafMt93oH61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"APIs","summary":"Registriere benannte APIs mit NEWAPI(), rufe über sie mit API() entfernte Dienste auf und nutze den Dienst Total.js API.","markdown":"---\ntitle: APIs\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# APIs\n\n> Registriere benannte APIs mit NEWAPI(), rufe über sie mit API() entfernte Dienste auf und nutze den Dienst Total.js API.\n\n## Eine API registrieren\n\n`NEWAPI()` registriert den Code, der mit einem Dienst spricht. Er erhält die Optionen des Aufrufs und einen Callback `next(err, response)`; `this` ist der API-Aufruf:\n\n```js\nNEWAPI('Weather', function(opt, next) {\n\t// opt.schema is the operation, opt.data the payload\n\tvar req = {};\n\treq.url = 'https://api.weather.example/' + opt.schema + '/?q=' + encodeURIComponent(opt.data.city);\n\treq.method = 'GET';\n\treq.type = 'json';\n\treq.callback = function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response && response.body.parseJSON());\n\t};\n\tREQUEST(req);\n});\n```\n\nEin Name wird in der an `NEWAPI()` übergebenen Schreibweise oder in Kleinbuchstaben gefunden, und mehrere durch Kommas getrennte Namen teilen sich einen Handler. Der Name `*` registriert einen Handler für jeden Namen, der keinen hat. Eine Funktion allein (oder ein Konfigurationsobjekt und eine Funktion) registriert den Namen `default`, und `NEWAPI(name, null)` entfernt einen Handler. `opt.retry()` führt den Handler erneut aus und erhöht `opt.retries`.\n\nEin optionales `config`-Objekt zwischen dem Namen und dem Handler enthält Standardeinstellungen. Sie werden in `opt.config` jedes Aufrufs kopiert, außer der Aufruf setzt denselben Schlüssel mit `.configure()`:\n\n```js\nNEWAPI('Weather', { region: 'eu', units: 'metric' }, function(opt, next) {\n\t// opt.config.region, opt.config.units\n\tnext(null, { region: opt.config.region });\n});\n\nAPI('Weather', 'current', { city: 'Oslo' }).configure({ units: 'imperial' }).callback(console.log);\n```\n\n## Eine API aufrufen\n\n`API(name, schema, data, [$])` führt den Handler im nächsten Tick aus und gibt ein Objekt zurück, dessen Methoden den Aufruf konfigurieren:\n\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).error('City not found').callback($);\n\t}\n});\n\n// with a promise\nvar forecast = await API('Weather', 'forecast', { city: 'Bratislava' }).promise();\n```\n\n| Methode | Was sie bewirkt |\n| --- | --- |\n| `.callback(fn)`, `.pipe(fn)` | Setzt `function(err, response)` oder übergibt das Ergebnis an `$.callback()` |\n| `.promise([$])` | Gibt ein Promise zurück; mit `$` geht ein Fehler an `$.invalid()` |\n| `.data(fn)` / `.fail(fn)` | Führt bei Erfolg `fn(response)` oder bei einem Fehler `fn(err)` aus |\n| `.error(message, [reverse])` | Macht aus einer leeren Antwort (oder mit `reverse` aus jeder truthy Antwort, auch einem leeren Array) einen Fehler |\n| `.output(type)` | Setzt `opt.output`, das Format, das der Handler zurückgeben soll |\n| `.file(filename, path, [name])` | Fügt `opt.files` eine Datei hinzu |\n| `.configure(obj)` | Kopiert Schlüssel in `opt.config` |\n| `.controller($)` | Setzt `opt.controller` |\n| `.audit($, message, [type])` | Schreibt nach einem erfolgreichen Aufruf ein Audit-Log mit `$.audit()` |\n| `.debug()` | Gibt den Fehler und die Antwort in der Konsole aus |\n\nEin Name ohne Handler (und ohne `*`-Handler) schlägt mit `API is not initialized` fehl.\n\n## Total.js API\n\n`TotalAPI(schema, data, [callback])` ist eine Kurzform von `API('TAPI', schema, data)`. Es sendet eine `POST`-Anfrage an `https://<$tapiurl>.api.totaljs.com/<schema>/` mit deinem Token:\n\n```js\n// /config\ntotalapi       : your-totalapi-token\n\n// code\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n\n// \"operation\" is the name of a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\nDas Token wird aus `.configure({ token: '...' })` gelesen, danach aus `CONF.totalapi`, `CONF.secret_totalapi` oder `CONF.$tapisecret`. Wenn `$tapi` `false` ist, schlägt jede Operation außer `check` mit `totalapi_inactive` fehl. Mit `.output()` wählst du das Format der Antwort: `json` (Standard), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream` oder `#storage [id] [filename]`, das die Antwort in einem [FileStorage](../../guides/file-storage/) speichert und die Metadaten der gespeicherten Datei zurückgibt. Fehlerantworten (Status über `200`) schlagen mit der von Total API gesendeten Fehlermeldung fehl.\n\nFür den WebSocket-Server selbst siehe [WebSockets](../../guides/websockets/), und für ausgehende HTTP-Aufrufe siehe [HTTP-Anfragen](../../guides/http-requests/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JafMt93oH61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"APIs","summary":"Registra APIs con nombre con NEWAPI(), llama a servicios remotos a través de ellas con API() y usa el servicio Total.js API.","markdown":"---\ntitle: APIs\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# APIs\n\n> Registra APIs con nombre con NEWAPI(), llama a servicios remotos a través de ellas con API() y usa el servicio Total.js API.\n\n## Registrar una API\n\n`NEWAPI()` registra el código que se comunica con un servicio. Recibe las opciones de la llamada y un callback `next(err, response)`; `this` es la llamada a la API:\n\n```js\nNEWAPI('Weather', function(opt, next) {\n\t// opt.schema is the operation, opt.data the payload\n\tvar req = {};\n\treq.url = 'https://api.weather.example/' + opt.schema + '/?q=' + encodeURIComponent(opt.data.city);\n\treq.method = 'GET';\n\treq.type = 'json';\n\treq.callback = function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response && response.body.parseJSON());\n\t};\n\tREQUEST(req);\n});\n```\n\nUn nombre se encuentra con la grafía que se le dio en `NEWAPI()` o en minúsculas, y varios nombres separados por comas comparten un handler. El nombre `*` registra un handler para todos los nombres que no tienen ninguno. Una función sola (o un objeto de configuración y una función) registra el nombre `default`, y `NEWAPI(name, null)` elimina un handler. `opt.retry()` vuelve a ejecutar el handler e incrementa `opt.retries`.\n\nUn objeto `config` opcional entre el nombre y el handler contiene ajustes por defecto. Se copian en `opt.config` de cada llamada, salvo que la llamada establezca la misma clave con `.configure()`:\n\n```js\nNEWAPI('Weather', { region: 'eu', units: 'metric' }, function(opt, next) {\n\t// opt.config.region, opt.config.units\n\tnext(null, { region: opt.config.region });\n});\n\nAPI('Weather', 'current', { city: 'Oslo' }).configure({ units: 'imperial' }).callback(console.log);\n```\n\n## Llamar a una API\n\n`API(name, schema, data, [$])` ejecuta el handler en el siguiente tick y devuelve un objeto cuyos métodos configuran la llamada:\n\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).error('City not found').callback($);\n\t}\n});\n\n// with a promise\nvar forecast = await API('Weather', 'forecast', { city: 'Bratislava' }).promise();\n```\n\n| Método | Qué hace |\n| --- | --- |\n| `.callback(fn)`, `.pipe(fn)` | Establece `function(err, response)`, o pasa el resultado a `$.callback()` |\n| `.promise([$])` | Devuelve una promesa; con `$` un error va a `$.invalid()` |\n| `.data(fn)` / `.fail(fn)` | Ejecuta `fn(response)` en caso de éxito o `fn(err)` en caso de error |\n| `.error(message, [reverse])` | Convierte una respuesta vacía (o, con `reverse`, cualquiera que sea truthy, también un array vacío) en un error |\n| `.output(type)` | Establece `opt.output`, el formato que debe devolver el handler |\n| `.file(filename, path, [name])` | Añade un archivo a `opt.files` |\n| `.configure(obj)` | Copia claves en `opt.config` |\n| `.controller($)` | Establece `opt.controller` |\n| `.audit($, message, [type])` | Escribe un log de auditoría con `$.audit()` tras una llamada correcta |\n| `.debug()` | Imprime el error y la respuesta en la consola |\n\nUn nombre sin handler (y sin handler `*`) falla con `API is not initialized`.\n\n## Total.js API\n\n`TotalAPI(schema, data, [callback])` es una forma abreviada de `API('TAPI', schema, data)`. Envía una petición `POST` a `https://<$tapiurl>.api.totaljs.com/<schema>/` con tu token:\n\n```js\n// /config\ntotalapi       : your-totalapi-token\n\n// code\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n\n// \"operation\" is the name of a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\nEl token se lee de `.configure({ token: '...' })`, y luego de `CONF.totalapi`, `CONF.secret_totalapi` o `CONF.$tapisecret`. Cuando `$tapi` es `false`, todas las operaciones excepto `check` fallan con `totalapi_inactive`. Con `.output()` eliges el formato de la respuesta: `json` (por defecto), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream`, o `#storage [id] [filename]`, que guarda la respuesta en un [FileStorage](../../guides/file-storage/) y devuelve los metadatos del archivo guardado. Las respuestas de error (estado superior a `200`) fallan con el mensaje de error enviado por Total API.\n\nPara el propio servidor WebSocket consulta [WebSockets](../../guides/websockets/), y para las llamadas HTTP salientes consulta [Peticiones HTTP](../../guides/http-requests/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JafMt93oH61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"API","summary":"Enregistre des API nommées avec NEWAPI(), appelle des services distants à travers elles avec API() et utilise le service Total.js API.","markdown":"---\ntitle: API\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# API\n\n> Enregistre des API nommées avec NEWAPI(), appelle des services distants à travers elles avec API() et utilise le service Total.js API.\n\n## Enregistrer une API\n\n`NEWAPI()` enregistre le code qui communique avec un service. Il reçoit les options de l'appel et un callback `next(err, response)` ; `this` est l'appel d'API :\n\n```js\nNEWAPI('Weather', function(opt, next) {\n\t// opt.schema is the operation, opt.data the payload\n\tvar req = {};\n\treq.url = 'https://api.weather.example/' + opt.schema + '/?q=' + encodeURIComponent(opt.data.city);\n\treq.method = 'GET';\n\treq.type = 'json';\n\treq.callback = function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response && response.body.parseJSON());\n\t};\n\tREQUEST(req);\n});\n```\n\nUn nom est trouvé dans l'orthographe donnée à `NEWAPI()` ou en minuscules, et plusieurs noms séparés par des virgules partagent un même handler. Le nom `*` enregistre un handler pour chaque nom qui n'en a pas. Une fonction seule (ou un objet de configuration et une fonction) enregistre le nom `default`, et `NEWAPI(name, null)` supprime un handler. `opt.retry()` exécute à nouveau le handler et incrémente `opt.retries`.\n\nUn objet `config` facultatif entre le nom et le handler contient des réglages par défaut. Ils sont copiés dans `opt.config` de chaque appel, sauf si l'appel définit la même clé avec `.configure()` :\n\n```js\nNEWAPI('Weather', { region: 'eu', units: 'metric' }, function(opt, next) {\n\t// opt.config.region, opt.config.units\n\tnext(null, { region: opt.config.region });\n});\n\nAPI('Weather', 'current', { city: 'Oslo' }).configure({ units: 'imperial' }).callback(console.log);\n```\n\n## Appeler une API\n\n`API(name, schema, data, [$])` exécute le handler au tick suivant et renvoie un objet dont les méthodes configurent l'appel :\n\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).error('City not found').callback($);\n\t}\n});\n\n// with a promise\nvar forecast = await API('Weather', 'forecast', { city: 'Bratislava' }).promise();\n```\n\n| Méthode | Ce qu'elle fait |\n| --- | --- |\n| `.callback(fn)`, `.pipe(fn)` | Définit `function(err, response)`, ou transmet le résultat à `$.callback()` |\n| `.promise([$])` | Renvoie une promesse ; avec `$`, une erreur va à `$.invalid()` |\n| `.data(fn)` / `.fail(fn)` | Exécute `fn(response)` en cas de succès ou `fn(err)` en cas d'erreur |\n| `.error(message, [reverse])` | Transforme une réponse vide (ou, avec `reverse`, toute réponse truthy, y compris un tableau vide) en erreur |\n| `.output(type)` | Définit `opt.output`, le format que le handler doit renvoyer |\n| `.file(filename, path, [name])` | Ajoute un fichier à `opt.files` |\n| `.configure(obj)` | Copie des clés dans `opt.config` |\n| `.controller($)` | Définit `opt.controller` |\n| `.audit($, message, [type])` | Écrit un log d'audit avec `$.audit()` après un appel réussi |\n| `.debug()` | Affiche l'erreur et la réponse dans la console |\n\nUn nom sans handler (et sans handler `*`) échoue avec `API is not initialized`.\n\n## Total.js API\n\n`TotalAPI(schema, data, [callback])` est une forme courte de `API('TAPI', schema, data)`. Elle envoie une requête `POST` à `https://<$tapiurl>.api.totaljs.com/<schema>/` avec ton token :\n\n```js\n// /config\ntotalapi       : your-totalapi-token\n\n// code\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n\n// \"operation\" is the name of a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\nLe token est lu depuis `.configure({ token: '...' })`, puis `CONF.totalapi`, `CONF.secret_totalapi` ou `CONF.$tapisecret`. Quand `$tapi` vaut `false`, toutes les opérations sauf `check` échouent avec `totalapi_inactive`. Avec `.output()`, tu choisis le format de la réponse : `json` (par défaut), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream`, ou `#storage [id] [filename]`, qui enregistre la réponse dans un [FileStorage](../../guides/file-storage/) et renvoie les métadonnées du fichier enregistré. Les réponses d'erreur (statut supérieur à `200`) échouent avec le message d'erreur envoyé par Total API.\n\nPour le serveur WebSocket lui-même, voir [WebSockets](../../guides/websockets/), et pour les appels HTTP sortants, voir [Requêtes HTTP](../../guides/http-requests/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JafMt93oH61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"API","summary":"Registra API con nome con NEWAPI(), chiama servizi remoti tramite esse con API() e usa il servizio Total.js API.","markdown":"---\ntitle: API\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# API\n\n> Registra API con nome con NEWAPI(), chiama servizi remoti tramite esse con API() e usa il servizio Total.js API.\n\n## Registrare un'API\n\n`NEWAPI()` registra il codice che comunica con un servizio. Riceve le opzioni della chiamata e una callback `next(err, response)`; `this` è la chiamata API:\n\n```js\nNEWAPI('Weather', function(opt, next) {\n\t// opt.schema is the operation, opt.data the payload\n\tvar req = {};\n\treq.url = 'https://api.weather.example/' + opt.schema + '/?q=' + encodeURIComponent(opt.data.city);\n\treq.method = 'GET';\n\treq.type = 'json';\n\treq.callback = function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response && response.body.parseJSON());\n\t};\n\tREQUEST(req);\n});\n```\n\nUn nome viene trovato nella grafia data a `NEWAPI()` o in minuscolo, e più nomi separati da virgole condividono un unico handler. Il nome `*` registra un handler per ogni nome che non ne ha uno. Una funzione da sola (o un oggetto di configurazione e una funzione) registra il nome `default`, e `NEWAPI(name, null)` rimuove un handler. `opt.retry()` esegue di nuovo l'handler e incrementa `opt.retries`.\n\nUn oggetto `config` facoltativo tra il nome e l'handler contiene le impostazioni predefinite. Vengono copiate in `opt.config` di ogni chiamata, a meno che la chiamata non imposti la stessa chiave con `.configure()`:\n\n```js\nNEWAPI('Weather', { region: 'eu', units: 'metric' }, function(opt, next) {\n\t// opt.config.region, opt.config.units\n\tnext(null, { region: opt.config.region });\n});\n\nAPI('Weather', 'current', { city: 'Oslo' }).configure({ units: 'imperial' }).callback(console.log);\n```\n\n## Chiamare un'API\n\n`API(name, schema, data, [$])` esegue l'handler al tick successivo e restituisce un oggetto i cui metodi configurano la chiamata:\n\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).error('City not found').callback($);\n\t}\n});\n\n// with a promise\nvar forecast = await API('Weather', 'forecast', { city: 'Bratislava' }).promise();\n```\n\n| Metodo | Cosa fa |\n| --- | --- |\n| `.callback(fn)`, `.pipe(fn)` | Imposta `function(err, response)`, oppure passa il risultato a `$.callback()` |\n| `.promise([$])` | Restituisce una promise; con `$` un errore va a `$.invalid()` |\n| `.data(fn)` / `.fail(fn)` | Esegue `fn(response)` in caso di successo o `fn(err)` in caso di errore |\n| `.error(message, [reverse])` | Trasforma una risposta vuota (o, con `reverse`, qualsiasi risposta truthy, anche un array vuoto) in un errore |\n| `.output(type)` | Imposta `opt.output`, il formato che l'handler deve restituire |\n| `.file(filename, path, [name])` | Aggiunge un file a `opt.files` |\n| `.configure(obj)` | Copia chiavi in `opt.config` |\n| `.controller($)` | Imposta `opt.controller` |\n| `.audit($, message, [type])` | Scrive un log di audit con `$.audit()` dopo una chiamata riuscita |\n| `.debug()` | Stampa l'errore e la risposta nella console |\n\nUn nome senza handler (e senza handler `*`) fallisce con `API is not initialized`.\n\n## Total.js API\n\n`TotalAPI(schema, data, [callback])` è una forma breve di `API('TAPI', schema, data)`. Invia una richiesta `POST` a `https://<$tapiurl>.api.totaljs.com/<schema>/` con il tuo token:\n\n```js\n// /config\ntotalapi       : your-totalapi-token\n\n// code\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n\n// \"operation\" is the name of a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\nIl token viene letto da `.configure({ token: '...' })`, poi da `CONF.totalapi`, `CONF.secret_totalapi` o `CONF.$tapisecret`. Quando `$tapi` è `false`, ogni operazione tranne `check` fallisce con `totalapi_inactive`. Con `.output()` scegli il formato della risposta: `json` (predefinito), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream`, oppure `#storage [id] [filename]`, che salva la risposta in un [FileStorage](../../guides/file-storage/) e restituisce i metadati del file salvato. Le risposte di errore (stato sopra `200`) falliscono con il messaggio di errore inviato da Total API.\n\nPer il server WebSocket vedi [WebSocket](../../guides/websockets/), e per le chiamate HTTP in uscita vedi [Richieste HTTP](../../guides/http-requests/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JafMt93oH61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/apis/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"API","summary":"Zaregistruj pomenované API cez NEWAPI(), volaj cez ne vzdialené služby pomocou API() a používaj službu Total.js API.","markdown":"---\ntitle: API\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/apis/\nupdated: 2026-11-16T15:32:52.498Z\n---\n\n# API\n\n> Zaregistruj pomenované API cez NEWAPI(), volaj cez ne vzdialené služby pomocou API() a používaj službu Total.js API.\n\n## Registrácia API\n\n`NEWAPI()` zaregistruje kód, ktorý komunikuje s jednou službou. Dostane možnosti volania a callback `next(err, response)`; `this` je volanie API:\n\n```js\nNEWAPI('Weather', function(opt, next) {\n\t// opt.schema is the operation, opt.data the payload\n\tvar req = {};\n\treq.url = 'https://api.weather.example/' + opt.schema + '/?q=' + encodeURIComponent(opt.data.city);\n\treq.method = 'GET';\n\treq.type = 'json';\n\treq.callback = function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response && response.body.parseJSON());\n\t};\n\tREQUEST(req);\n});\n```\n\nMeno sa nájde v podobe zadanej do `NEWAPI()` alebo malými písmenami a viac mien oddelených čiarkami zdieľa jeden handler. Meno `*` zaregistruje handler pre každé meno, ktoré žiadny nemá. Samotná funkcia (alebo konfiguračný objekt a funkcia) zaregistruje meno `default` a `NEWAPI(name, null)` handler odstráni. `opt.retry()` spustí handler znova a zvýši `opt.retries`.\n\nVoliteľný objekt `config` medzi názvom a handlerom obsahuje predvolené nastavenia. Skopírujú sa do `opt.config` každého volania, ak volanie nenastaví rovnaký kľúč cez `.configure()`:\n\n```js\nNEWAPI('Weather', { region: 'eu', units: 'metric' }, function(opt, next) {\n\t// opt.config.region, opt.config.units\n\tnext(null, { region: opt.config.region });\n});\n\nAPI('Weather', 'current', { city: 'Oslo' }).configure({ units: 'imperial' }).callback(console.log);\n```\n\n## Volanie API\n\n`API(name, schema, data, [$])` spustí handler v ďalšom ticku a vráti objekt, ktorého metódy volanie konfigurujú:\n\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).error('City not found').callback($);\n\t}\n});\n\n// with a promise\nvar forecast = await API('Weather', 'forecast', { city: 'Bratislava' }).promise();\n```\n\n| Metóda | Čo robí |\n| --- | --- |\n| `.callback(fn)`, `.pipe(fn)` | Nastaví `function(err, response)` alebo odovzdá výsledok do `$.callback()` |\n| `.promise([$])` | Vráti promise; s `$` ide chyba do `$.invalid()` |\n| `.data(fn)` / `.fail(fn)` | Spustí `fn(response)` pri úspechu alebo `fn(err)` pri chybe |\n| `.error(message, [reverse])` | Zmení prázdnu odpoveď (alebo s `reverse` akúkoľvek pravdivú, aj prázdne pole) na chybu |\n| `.output(type)` | Nastaví `opt.output`, formát, ktorý má handler vrátiť |\n| `.file(filename, path, [name])` | Pridá súbor do `opt.files` |\n| `.configure(obj)` | Skopíruje kľúče do `opt.config` |\n| `.controller($)` | Nastaví `opt.controller` |\n| `.audit($, message, [type])` | Po úspešnom volaní zapíše audit log cez `$.audit()` |\n| `.debug()` | Vypíše chybu a odpoveď do konzoly |\n\nNázov bez handlera (a bez handlera `*`) zlyhá s `API is not initialized`.\n\n## Total.js API\n\n`TotalAPI(schema, data, [callback])` je skrátená forma `API('TAPI', schema, data)`. Pošle požiadavku `POST` na `https://<$tapiurl>.api.totaljs.com/<schema>/` s tvojím tokenom:\n\n```js\n// /config\ntotalapi       : your-totalapi-token\n\n// code\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n\n// \"operation\" is the name of a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\nToken sa číta z `.configure({ token: '...' })`, potom z `CONF.totalapi`, `CONF.secret_totalapi` alebo `CONF.$tapisecret`. Keď je `$tapi` `false`, každá operácia okrem `check` zlyhá s `totalapi_inactive`. Cez `.output()` zvolíš formát odpovede: `json` (predvolene), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream` alebo `#storage [id] [filename]`, ktorý odpoveď uloží do [FileStorage](../../guides/file-storage/) a vráti metadáta uloženého súboru. Chybové odpovede (status nad `200`) zlyhajú s chybovou správou, ktorú poslalo Total API.\n\nSamotný WebSocket server nájdeš vo [WebSockety](../../guides/websockets/) a odchádzajúce HTTP volania v [HTTP požiadavky](../../guides/http-requests/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:52.498Z"}
{"id":"JafwvK9Bx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Workers, threads and cluster","summary":"Worker threads, thread pools, cluster mode, shell commands, Python scripts and Python pipelines.","markdown":"---\ntitle: Workers, threads and cluster\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/workers-and-threads/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Workers, threads and cluster\n\n> Worker threads, thread pools, cluster mode, shell commands, Python scripts and Python pipelines.\n\nTotal.js 5 can move work out of the main process in several ways: **worker threads** (`NEWTHREAD()`), **forked processes** (`NEWFORK()`), a **pool** of threads or forks (`NEWTHREADPOOL()`), a **cluster** of HTTP processes (the `cluster` option of the start script) and external programs (`SHELL()` and `PYPELINE()`). Everything here is built on the Node.js modules `worker_threads`, `child_process` and `cluster`, which the framework exposes as `F.Worker`, `F.Child` and `F.Cluster`.\n\n## The `workers/` folder\n\nA worker is a plain script in the `workers/` folder of the application. The name you pass to `NEWTHREAD()` or `NEWFORK()` is the file name without `.js`, so `NEWTHREAD('resize')` runs `workers/resize.js`. A name that starts with `~` is an absolute path: `NEWTHREAD('~/opt/scripts/resize.js')`.\n\n```text\nmyapp/\n├── index.js\n├── controllers/\n└── workers/\n\t└── calc.js\n```\n\n## A worker thread\n\nThe worker script loads the framework and calls `NEWTHREAD()` **without a name**. Inside a worker that returns the worker object `F.worker`, with the data from the main thread and the methods to talk back:\n\n```js\n// workers/calc.js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tvar sum = msg.a + msg.b;\n\tworker.send({ sum: sum, user: worker.data.user });\n};\n```\n\nIn the main application `NEWTHREAD(name, [data])` starts the thread and returns the Node.js `Worker`. `data` is copied into the thread as `worker.data`:\n\n```js\n// controllers/default.js\nexports.install = function() {\n\tROUTE('GET /sum/', sum);\n};\n\nfunction sum($) {\n\tvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\tthread.on('message', function(msg) {\n\t\t$.json(msg);\n\t\tthread.kill();\n\t});\n\tthread.postMessage({ a: 1, b: 2 });\n}\n```\n\nMessages go through the structured clone of Node.js: objects, arrays, strings, numbers, dates and buffers arrive as copies, functions do not. The thread runs with the same working directory as the application, so `PATH.root()` and the other paths point to the application root.\n\n`F.worker` has these members:\n\n| Member | Description |\n| --- | --- |\n| `worker.data` | The `data` passed to `NEWTHREAD(name, data)`, or `{}` |\n| `worker.is` | `true` when the script runs as a worker (the argument `--worker`) |\n| `worker.isfork` | `true` in a process from `NEWFORK()`, `false` in a thread |\n| `worker.message` | Assign a function: it receives every message from the parent |\n| `worker.send(msg)` | Sends a message to the parent (alias `worker.postMessage()`) |\n| `worker.exit([code])` | Ends the process of the worker with the code (default `0`); aliases `kill()` and `close()` |\n| `worker.setTimeout(ms)` | Ends the worker with code `1` after `ms` milliseconds; call it again to restart the countdown |\n\n`setTimeout()` is a watchdog: call it when a job starts, and the worker ends itself if the job takes too long.\n\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\theavyjob(msg, function(err, response) {\n\t\tworker.send({ error: err ? err + '' : null, response: response });\n\t});\n};\n```\n\nOn the main side the returned object is a normal Node.js `Worker` (`on('message')`, `on('error')`, `on('exit')`, `postMessage()`, `terminate()`). The framework adds `kill()` and `exit()`, both of which call `terminate()`.\n\n## A forked process\n\n`NEWFORK(name)` runs the script from `workers/` in a new Node.js process (`child_process.fork()`) instead of a thread. A fork has its own memory and its own event loop, so a crash or a blocking job cannot affect the application. The script calls `NEWFORK()` without a name to get the same `F.worker` object:\n\n```js\n// workers/report.js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn; // internal messages of the framework, e.g. 'total:init'\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nThe returned object is a Node.js `ChildProcess`; the framework adds `postMessage()` (the same as `send()`) and `terminate()`, which kills the process with `SIGKILL`. Messages are serialized as JSON. A fork gets no `data` (`worker.data` is `{}`), so send the input as the first message. The working directory of a fork is the folder of its script, so `PATH.root()` inside a fork points to `workers/`. The framework in the fork sends the string `total:init` to the parent after it starts; skip string messages, as in the example.\n\n## A pool of threads\n\n`NEWTHREADPOOL(name, count, [isfork])` starts `count` threads of the same script at once (or `count` forks when `isfork` is `true`) and lends them to jobs one by one. The workers get no data, so `worker.data` is `{}` and the input goes in the messages. A job gets a free worker and a `release` function; until it calls `release()`, the worker is not given to another job. Jobs that arrive while all workers are busy wait in a queue.\n\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\n`pool.exec()` without a function returns a promise that resolves with the worker; call `worker.release()` when the job is done:\n\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 1 });\n```\n\nBefore a worker goes to the next job, the pool removes all its `message` listeners, so every job attaches its own. The pool is also stored in `F.workers[name]`, and `pool.workers` and `pool.pending` hold the workers and the waiting jobs. `pool.count` is the number of workers. A worker that exits (or crashes) is replaced by a new one, so the pool keeps its size.\n\n## Cluster mode\n\nA cluster runs the HTTP application in several processes that share one port. Set the `cluster` option in the start script to a number of processes, or to `'auto'`:\n\n```js\n// index.js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nThe first process becomes the **master**. It prints a `CLUSTER` header (PID, versions, thread count, mode), starts the first process, waits until it has loaded, starts the others and then calls `options.callback(forks)` if you set it (the other processes may still be loading). Each process loads the whole application and listens on the shared port; Node.js spreads the connections among them. The master itself serves no requests.\n\n| Option | Description |\n| --- | --- |\n| `cluster` | The number of processes, or `'auto'` |\n| `limit` | With `'auto'`: the maximum number of processes |\n| `tz` | The time zone of the processes (`process.env.TZ`), default `'utc'` |\n| `logs` | `'isolated'` prints the cluster header even when the master runs under another process |\n| `callback` | `function(forks)` called in the master after all processes have started |\n\nAll other options (`port`, `ip`, `config`, …) go to `F.http()` in every process. The processes run in release mode when `options.release` is `true` (the official start script sets it with `--release`) or `options.watcher` is `false`. Otherwise they run in debug mode and the master restarts all of them when a source file changes.\n\nWith `'auto'` the master starts one process and pings every process each 5 seconds. When the average answer takes longer than 70 ms it adds a process (up to `limit`); when the processes answer fast again it removes the last one, if it has fewer than two pending requests.\n\nA process that exits is started again after one second. To restart all processes yourself, create an empty file named `restart` in the application directory: the master checks for it every 5 seconds, deletes it and restarts the processes one by one, two seconds apart. The master also writes the statistics of all processes into `<start script>.json` (for example `index.js.json`) about every 50 seconds.\n\nInside a process of the cluster:\n\n```js\nF.isCluster;   // true\nF.isWorker;    // true\nF.id;          // '1', '2', ... the identifier of the process\nF.clusterid;   // the same identifier\n```\n\nThe framework adds `F.clusterid` to the names of its temporary files, so the processes do not overwrite each other's files in `tmp/`.\n\n## Messages between cluster processes\n\nEvery message a process receives arrives as the `$message` event. An object sent to the master with `process.send()` is passed by the master to all ready processes, the sender included. Use it to keep in-memory caches in sync:\n\n```js\n// definitions/sync.js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// anywhere in a request\nfunction update($) {\n\tif (F.isCluster)\n\t\tprocess.send({ type: 'clearcache', from: F.id });\n\telse\n\t\tMAIN.products = null;\n\t$.success();\n}\n```\n\nDo not use the `TYPE` property in your messages and do not send strings that start with `total:`; the framework uses them for its own messages.\n\n## Shell commands\n\n`SHELL(cmd, [callback], [cwd])` runs a command in the system shell with `child_process.exec()`. With a callback you get `(err, stdout)`; without one it returns a promise with the standard output. The command runs in the application directory unless you pass `cwd`, and the config key `$shell` selects another shell (for example `/bin/bash`).\n\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n\nvar files = await SHELL('ls -1', PATH.public());\n```\n\n## Python scripts\n\n`F.python(filename, [callback])` runs a Python script once, in the folder of the script, and gives you its standard output. `F.pipinstall(name, [callback])` installs a Python package with `pip`. Both use the command from the config key `$python` (`python3` by default) and return a promise without a callback:\n\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/report.py'));\nconsole.log(output);\n```\n\nFor a script that keeps running and exchanges messages with the application, use a pipeline.\n\n## Python pipelines\n\n`PYPELINE(name, [options])` starts a `python3` process and talks to it through a Unix socket. `name` is a file in the `pypelines/` folder without `.py` (`PYPELINE('ocr')` runs `pypelines/ocr.py`), an absolute path with `~`, or inline Python code: a name that contains a new line, `;` or a quote is run with `python3 -c`.\n\nThe framework creates the socket in `tmp/` and passes its path to the script as the first argument (`sys.argv[1]`). Every message in both directions is a 4-byte big-endian length followed by the payload. By default the payload is JSON (with `type: 'text'` the `data` event gets a string, with any other `type` a buffer):\n\n```python\n# pypelines/upper.py\nimport sys, socket, struct, json\n\ns = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\ns.connect(sys.argv[1])\n\ndef read(n):\n\tdata = b''\n\twhile len(data) < n:\n\t\tchunk = s.recv(n - len(data))\n\t\tif not chunk:\n\t\t\tsys.exit(0)\n\t\tdata += chunk\n\treturn data\n\nwhile True:\n\tsize = struct.unpack('>I', read(4))[0]\n\tmsg = json.loads(read(size))\n\tout = json.dumps({ 'text': msg['text'].upper() }).encode()\n\ts.sendall(struct.pack('>I', len(out)) + out)\n```\n\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text); // HELLO\n});\n\npy.send({ text: 'hello' });\n```\n\nMessages sent before the script connects wait and go out when it connects. The pipeline emits `open` when the script connects, `data` for every message, and `restart` when it starts the script again. With `autorestart: true` (the default) a script that ends is started again; `py.close()` stops it for good. When the application exits, the framework kills all running Python processes.\n\nThe full list of methods and options is in the reference of [Workers, threads and cluster](../../reference/workers-and-threads/). Scheduled jobs are described in [Scheduling and events](../scheduling-and-events/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwvK9Bx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Worker, Threads und Cluster","summary":"Worker-Threads, Thread-Pools, Cluster-Modus, Shell-Befehle, Python-Skripte und Python-Pipelines.","markdown":"---\ntitle: Worker, Threads und Cluster\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/workers-and-threads/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Worker, Threads und Cluster\n\n> Worker-Threads, Thread-Pools, Cluster-Modus, Shell-Befehle, Python-Skripte und Python-Pipelines.\n\nTotal.js 5 kann Arbeit auf mehrere Arten aus dem Hauptprozess auslagern: **Worker-Threads** (`NEWTHREAD()`), **geforkte Prozesse** (`NEWFORK()`), ein **Pool** von Threads oder Forks (`NEWTHREADPOOL()`), ein **Cluster** von HTTP-Prozessen (die Option `cluster` des Startskripts) und externe Programme (`SHELL()` und `PYPELINE()`). Alles hier baut auf den Node.js-Modulen `worker_threads`, `child_process` und `cluster` auf, die das Framework als `F.Worker`, `F.Child` und `F.Cluster` bereitstellt.\n\n## Der Ordner `workers/`\n\nEin Worker ist ein einfaches Skript im Ordner `workers/` der Anwendung. Der Name, den du an `NEWTHREAD()` oder `NEWFORK()` übergibst, ist der Dateiname ohne `.js`, also führt `NEWTHREAD('resize')` `workers/resize.js` aus. Ein Name, der mit `~` beginnt, ist ein absoluter Pfad: `NEWTHREAD('~/opt/scripts/resize.js')`.\n\n```text\nmyapp/\n├── index.js\n├── controllers/\n└── workers/\n\t└── calc.js\n```\n\n## Ein Worker-Thread\n\nDas Worker-Skript lädt das Framework und ruft `NEWTHREAD()` **ohne Namen** auf. Innerhalb eines Workers gibt das das Worker-Objekt `F.worker` zurück, mit den Daten aus dem Haupt-Thread und den Methoden, um zurückzukommunizieren:\n\n```js\n// workers/calc.js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tvar sum = msg.a + msg.b;\n\tworker.send({ sum: sum, user: worker.data.user });\n};\n```\n\nIn der Hauptanwendung startet `NEWTHREAD(name, [data])` den Thread und gibt den Node.js-`Worker` zurück. `data` wird als `worker.data` in den Thread kopiert:\n\n```js\n// controllers/default.js\nexports.install = function() {\n\tROUTE('GET /sum/', sum);\n};\n\nfunction sum($) {\n\tvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\tthread.on('message', function(msg) {\n\t\t$.json(msg);\n\t\tthread.kill();\n\t});\n\tthread.postMessage({ a: 1, b: 2 });\n}\n```\n\nNachrichten laufen über das Structured Clone von Node.js: Objekte, Arrays, Strings, Zahlen, Datumswerte und Buffer kommen als Kopien an, Funktionen nicht. Der Thread läuft mit demselben Arbeitsverzeichnis wie die Anwendung, daher zeigen `PATH.root()` und die anderen Pfade auf das Stammverzeichnis der Anwendung.\n\n`F.worker` hat diese Mitglieder:\n\n| Mitglied | Beschreibung |\n| --- | --- |\n| `worker.data` | Das an `NEWTHREAD(name, data)` übergebene `data` oder `{}` |\n| `worker.is` | `true`, wenn das Skript als Worker läuft (das Argument `--worker`) |\n| `worker.isfork` | `true` in einem Prozess aus `NEWFORK()`, `false` in einem Thread |\n| `worker.message` | Weise eine Funktion zu: Sie erhält jede Nachricht vom Elternprozess |\n| `worker.send(msg)` | Sendet eine Nachricht an den Elternprozess (Alias `worker.postMessage()`) |\n| `worker.exit([code])` | Beendet den Prozess des Workers mit dem Code (Standard `0`); Aliase `kill()` und `close()` |\n| `worker.setTimeout(ms)` | Beendet den Worker nach `ms` Millisekunden mit dem Code `1`; rufe es erneut auf, um den Countdown neu zu starten |\n\n`setTimeout()` ist ein Watchdog: Rufe es auf, wenn ein Job startet, und der Worker beendet sich selbst, wenn der Job zu lange dauert.\n\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\theavyjob(msg, function(err, response) {\n\t\tworker.send({ error: err ? err + '' : null, response: response });\n\t});\n};\n```\n\nAuf der Hauptseite ist das zurückgegebene Objekt ein normaler Node.js-`Worker` (`on('message')`, `on('error')`, `on('exit')`, `postMessage()`, `terminate()`). Das Framework fügt `kill()` und `exit()` hinzu, die beide `terminate()` aufrufen.\n\n## Ein geforkter Prozess\n\n`NEWFORK(name)` führt das Skript aus `workers/` in einem neuen Node.js-Prozess (`child_process.fork()`) statt in einem Thread aus. Ein Fork hat eigenen Speicher und eine eigene Event-Loop, sodass ein Absturz oder ein blockierender Job die Anwendung nicht beeinträchtigen kann. Das Skript ruft `NEWFORK()` ohne Namen auf, um dasselbe Objekt `F.worker` zu erhalten:\n\n```js\n// workers/report.js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn; // internal messages of the framework, e.g. 'total:init'\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nDas zurückgegebene Objekt ist ein Node.js-`ChildProcess`; das Framework fügt `postMessage()` (dasselbe wie `send()`) und `terminate()` hinzu, das den Prozess mit `SIGKILL` beendet. Nachrichten werden als JSON serialisiert. Ein Fork bekommt kein `data` (`worker.data` ist `{}`), sende die Eingabe also als erste Nachricht. Das Arbeitsverzeichnis eines Forks ist der Ordner seines Skripts, daher zeigt `PATH.root()` innerhalb eines Forks auf `workers/`. Das Framework im Fork sendet nach dem Start den String `total:init` an den Elternprozess; überspringe String-Nachrichten, wie im Beispiel.\n\n## Ein Pool von Threads\n\n`NEWTHREADPOOL(name, count, [isfork])` startet sofort `count` Threads desselben Skripts (oder `count` Forks, wenn `isfork` gleich `true` ist) und leiht sie nacheinander an Jobs aus. Die Worker erhalten keine Daten, daher ist `worker.data` gleich `{}`, und die Eingabe kommt in den Nachrichten. Ein Job erhält einen freien Worker und eine Funktion `release`; bis er `release()` aufruft, wird der Worker keinem anderen Job gegeben. Jobs, die eintreffen, während alle Worker beschäftigt sind, warten in einer Warteschlange.\n\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\n`pool.exec()` ohne Funktion gibt eine Promise zurück, die mit dem Worker erfüllt wird; rufe `worker.release()` auf, wenn der Job erledigt ist:\n\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 1 });\n```\n\nBevor ein Worker zum nächsten Job geht, entfernt der Pool alle seine `message`-Listener, sodass jeder Job seine eigenen anhängt. Der Pool wird außerdem in `F.workers[name]` gespeichert, und `pool.workers` und `pool.pending` enthalten die Worker und die wartenden Jobs. `pool.count` ist die Anzahl der Worker. Ein Worker, der sich beendet (oder abstürzt), wird durch einen neuen ersetzt, sodass der Pool seine Größe behält.\n\n## Cluster-Modus\n\nEin Cluster führt die HTTP-Anwendung in mehreren Prozessen aus, die sich einen Port teilen. Setze die Option `cluster` im Startskript auf eine Anzahl von Prozessen oder auf `'auto'`:\n\n```js\n// index.js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nDer erste Prozess wird zum **Master**. Er gibt einen `CLUSTER`-Header aus (PID, Versionen, Thread-Anzahl, Modus), startet den ersten Prozess, wartet, bis er geladen ist, startet die anderen und ruft dann `options.callback(forks)` auf, falls du es gesetzt hast (die anderen Prozesse laden dann eventuell noch). Jeder Prozess lädt die ganze Anwendung und lauscht auf dem gemeinsamen Port; Node.js verteilt die Verbindungen auf sie. Der Master selbst bedient keine Anfragen.\n\n| Option | Beschreibung |\n| --- | --- |\n| `cluster` | Die Anzahl der Prozesse oder `'auto'` |\n| `limit` | Mit `'auto'`: die maximale Anzahl der Prozesse |\n| `tz` | Die Zeitzone der Prozesse (`process.env.TZ`), Standard `'utc'` |\n| `logs` | `'isolated'` gibt den Cluster-Header auch aus, wenn der Master unter einem anderen Prozess läuft |\n| `callback` | `function(forks)`, die im Master aufgerufen wird, nachdem alle Prozesse gestartet sind |\n\nAlle anderen Optionen (`port`, `ip`, `config`, …) gehen in jedem Prozess an `F.http()`. Die Prozesse laufen im Release-Modus, wenn `options.release` gleich `true` ist (das offizielle Startskript setzt es mit `--release`) oder `options.watcher` gleich `false`. Sonst laufen sie im Debug-Modus, und der Master startet alle neu, wenn sich eine Quelldatei ändert.\n\nMit `'auto'` startet der Master einen Prozess und pingt alle 5 Sekunden jeden Prozess an. Dauert die durchschnittliche Antwort länger als 70 ms, fügt er einen Prozess hinzu (bis zu `limit`); antworten die Prozesse wieder schnell, entfernt er den letzten, wenn dieser weniger als zwei ausstehende Anfragen hat.\n\nEin Prozess, der sich beendet, wird nach einer Sekunde neu gestartet. Um alle Prozesse selbst neu zu starten, erstelle eine leere Datei namens `restart` im Verzeichnis der Anwendung: Der Master prüft alle 5 Sekunden darauf, löscht sie und startet die Prozesse nacheinander neu, im Abstand von zwei Sekunden. Der Master schreibt außerdem etwa alle 50 Sekunden die Statistiken aller Prozesse in `<start script>.json` (zum Beispiel `index.js.json`).\n\nInnerhalb eines Prozesses des Clusters:\n\n```js\nF.isCluster;   // true\nF.isWorker;    // true\nF.id;          // '1', '2', ... the identifier of the process\nF.clusterid;   // the same identifier\n```\n\nDas Framework fügt `F.clusterid` zu den Namen seiner temporären Dateien hinzu, sodass die Prozesse ihre Dateien in `tmp/` nicht gegenseitig überschreiben.\n\n## Nachrichten zwischen Cluster-Prozessen\n\nJede Nachricht, die ein Prozess empfängt, kommt als Event `$message` an. Ein mit `process.send()` an den Master gesendetes Objekt wird vom Master an alle bereiten Prozesse weitergegeben, einschließlich des Absenders. Verwende das, um In-Memory-Caches synchron zu halten:\n\n```js\n// definitions/sync.js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// anywhere in a request\nfunction update($) {\n\tif (F.isCluster)\n\t\tprocess.send({ type: 'clearcache', from: F.id });\n\telse\n\t\tMAIN.products = null;\n\t$.success();\n}\n```\n\nVerwende die Eigenschaft `TYPE` nicht in deinen Nachrichten und sende keine Strings, die mit `total:` beginnen; das Framework verwendet sie für seine eigenen Nachrichten.\n\n## Shell-Befehle\n\n`SHELL(cmd, [callback], [cwd])` führt einen Befehl in der System-Shell mit `child_process.exec()` aus. Mit einem Callback erhältst du `(err, stdout)`; ohne gibt es eine Promise mit der Standardausgabe zurück. Der Befehl läuft im Verzeichnis der Anwendung, sofern du nicht `cwd` übergibst, und der Konfigurationsschlüssel `$shell` wählt eine andere Shell (zum Beispiel `/bin/bash`).\n\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n\nvar files = await SHELL('ls -1', PATH.public());\n```\n\n## Python-Skripte\n\n`F.python(filename, [callback])` führt ein Python-Skript einmal aus, im Ordner des Skripts, und gibt dir seine Standardausgabe. `F.pipinstall(name, [callback])` installiert ein Python-Paket mit `pip`. Beide verwenden den Befehl aus dem Konfigurationsschlüssel `$python` (standardmäßig `python3`) und geben ohne Callback eine Promise zurück:\n\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/report.py'));\nconsole.log(output);\n```\n\nFür ein Skript, das weiterläuft und Nachrichten mit der Anwendung austauscht, verwende eine Pipeline.\n\n## Python-Pipelines\n\n`PYPELINE(name, [options])` startet einen `python3`-Prozess und kommuniziert mit ihm über einen Unix-Socket. `name` ist eine Datei im Ordner `pypelines/` ohne `.py` (`PYPELINE('ocr')` führt `pypelines/ocr.py` aus), ein absoluter Pfad mit `~` oder Inline-Python-Code: Ein Name, der einen Zeilenumbruch, `;` oder ein Anführungszeichen enthält, wird mit `python3 -c` ausgeführt.\n\nDas Framework erstellt den Socket in `tmp/` und übergibt seinen Pfad als erstes Argument an das Skript (`sys.argv[1]`). Jede Nachricht in beide Richtungen besteht aus einer 4-Byte-Länge im Big-Endian-Format, gefolgt von den Nutzdaten. Standardmäßig sind die Nutzdaten JSON (mit `type: 'text'` erhält das Ereignis `data` einen String, mit jedem anderen `type` einen Buffer):\n\n```python\n# pypelines/upper.py\nimport sys, socket, struct, json\n\ns = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\ns.connect(sys.argv[1])\n\ndef read(n):\n\tdata = b''\n\twhile len(data) < n:\n\t\tchunk = s.recv(n - len(data))\n\t\tif not chunk:\n\t\t\tsys.exit(0)\n\t\tdata += chunk\n\treturn data\n\nwhile True:\n\tsize = struct.unpack('>I', read(4))[0]\n\tmsg = json.loads(read(size))\n\tout = json.dumps({ 'text': msg['text'].upper() }).encode()\n\ts.sendall(struct.pack('>I', len(out)) + out)\n```\n\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text); // HELLO\n});\n\npy.send({ text: 'hello' });\n```\n\nNachrichten, die gesendet werden, bevor sich das Skript verbindet, warten und gehen hinaus, sobald es sich verbindet. Die Pipeline löst `open` aus, wenn sich das Skript verbindet, `data` für jede Nachricht und `restart`, wenn sie das Skript erneut startet. Mit `autorestart: true` (dem Standard) wird ein Skript, das endet, erneut gestartet; `py.close()` stoppt es endgültig. Wenn sich die Anwendung beendet, beendet das Framework alle laufenden Python-Prozesse.\n\nDie vollständige Liste der Methoden und Optionen steht in der Referenz [Worker, Threads und Cluster](../../reference/workers-and-threads/). Geplante Jobs werden in [Zeitplanung und Events](../scheduling-and-events/) beschrieben.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwvK9Bx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Workers, hilos y clúster","summary":"Hilos worker, pools de hilos, modo clúster, comandos de shell, scripts de Python y pipelines de Python.","markdown":"---\ntitle: \"Workers, hilos y clúster\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/workers-and-threads/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Workers, hilos y clúster\n\n> Hilos worker, pools de hilos, modo clúster, comandos de shell, scripts de Python y pipelines de Python.\n\nTotal.js 5 puede sacar trabajo del proceso principal de varias formas: **hilos worker** (`NEWTHREAD()`), **procesos bifurcados** (`NEWFORK()`), un **pool** de hilos o forks (`NEWTHREADPOOL()`), un **clúster** de procesos HTTP (la opción `cluster` del script de inicio) y programas externos (`SHELL()` y `PYPELINE()`). Todo esto se basa en los módulos de Node.js `worker_threads`, `child_process` y `cluster`, que el framework expone como `F.Worker`, `F.Child` y `F.Cluster`.\n\n## La carpeta `workers/`\n\nUn worker es un script simple en la carpeta `workers/` de la aplicación. El nombre que pasas a `NEWTHREAD()` o `NEWFORK()` es el nombre del archivo sin `.js`, así que `NEWTHREAD('resize')` ejecuta `workers/resize.js`. Un nombre que empieza por `~` es una ruta absoluta: `NEWTHREAD('~/opt/scripts/resize.js')`.\n\n```text\nmyapp/\n├── index.js\n├── controllers/\n└── workers/\n\t└── calc.js\n```\n\n## Un hilo worker\n\nEl script del worker carga el framework y llama a `NEWTHREAD()` **sin nombre**. Dentro de un worker eso devuelve el objeto worker `F.worker`, con los datos del hilo principal y los métodos para responder:\n\n```js\n// workers/calc.js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tvar sum = msg.a + msg.b;\n\tworker.send({ sum: sum, user: worker.data.user });\n};\n```\n\nEn la aplicación principal `NEWTHREAD(name, [data])` inicia el hilo y devuelve el `Worker` de Node.js. `data` se copia en el hilo como `worker.data`:\n\n```js\n// controllers/default.js\nexports.install = function() {\n\tROUTE('GET /sum/', sum);\n};\n\nfunction sum($) {\n\tvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\tthread.on('message', function(msg) {\n\t\t$.json(msg);\n\t\tthread.kill();\n\t});\n\tthread.postMessage({ a: 1, b: 2 });\n}\n```\n\nLos mensajes pasan por el structured clone de Node.js: objetos, arrays, strings, números, fechas y buffers llegan como copias, las funciones no. El hilo se ejecuta con el mismo directorio de trabajo que la aplicación, así que `PATH.root()` y las demás rutas apuntan a la raíz de la aplicación.\n\n`F.worker` tiene estos miembros:\n\n| Miembro | Descripción |\n| --- | --- |\n| `worker.data` | El `data` pasado a `NEWTHREAD(name, data)`, o `{}` |\n| `worker.is` | `true` cuando el script se ejecuta como worker (el argumento `--worker`) |\n| `worker.isfork` | `true` en un proceso de `NEWFORK()`, `false` en un hilo |\n| `worker.message` | Asígnale una función: recibe cada mensaje del padre |\n| `worker.send(msg)` | Envía un mensaje al padre (alias `worker.postMessage()`) |\n| `worker.exit([code])` | Termina el proceso del worker con el código (por defecto `0`); alias `kill()` y `close()` |\n| `worker.setTimeout(ms)` | Termina el worker con el código `1` tras `ms` milisegundos; llámalo de nuevo para reiniciar la cuenta atrás |\n\n`setTimeout()` es un watchdog: llámalo cuando empiece un trabajo, y el worker se termina solo si el trabajo tarda demasiado.\n\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\theavyjob(msg, function(err, response) {\n\t\tworker.send({ error: err ? err + '' : null, response: response });\n\t});\n};\n```\n\nEn el lado principal el objeto devuelto es un `Worker` normal de Node.js (`on('message')`, `on('error')`, `on('exit')`, `postMessage()`, `terminate()`). El framework añade `kill()` y `exit()`, que llaman ambos a `terminate()`.\n\n## Un proceso bifurcado\n\n`NEWFORK(name)` ejecuta el script de `workers/` en un nuevo proceso de Node.js (`child_process.fork()`) en lugar de un hilo. Un fork tiene su propia memoria y su propio event loop, así que un fallo o un trabajo bloqueante no puede afectar a la aplicación. El script llama a `NEWFORK()` sin nombre para obtener el mismo objeto `F.worker`:\n\n```js\n// workers/report.js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn; // internal messages of the framework, e.g. 'total:init'\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nEl objeto devuelto es un `ChildProcess` de Node.js; el framework añade `postMessage()` (lo mismo que `send()`) y `terminate()`, que mata el proceso con `SIGKILL`. Los mensajes se serializan como JSON. Un fork no recibe `data` (`worker.data` es `{}`), así que envía la entrada como primer mensaje. El directorio de trabajo de un fork es la carpeta de su script, así que `PATH.root()` dentro de un fork apunta a `workers/`. El framework en el fork envía el string `total:init` al padre tras iniciarse; omite los mensajes de tipo string, como en el ejemplo.\n\n## Un pool de hilos\n\n`NEWTHREADPOOL(name, count, [isfork])` inicia a la vez `count` hilos del mismo script (o `count` forks cuando `isfork` es `true`) y los presta a los trabajos uno a uno. Los workers no reciben datos, así que `worker.data` es `{}` y la entrada va en los mensajes. Un trabajo obtiene un worker libre y una función `release`; hasta que llama a `release()`, el worker no se da a otro trabajo. Los trabajos que llegan mientras todos los workers están ocupados esperan en una cola.\n\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\n`pool.exec()` sin función devuelve una promesa que se resuelve con el worker; llama a `worker.release()` cuando el trabajo termine:\n\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 1 });\n```\n\nAntes de que un worker pase al siguiente trabajo, el pool elimina todos sus listeners de `message`, así que cada trabajo añade los suyos. El pool también se guarda en `F.workers[name]`, y `pool.workers` y `pool.pending` contienen los workers y los trabajos en espera. `pool.count` es el número de workers. Un worker que termina (o falla) se sustituye por uno nuevo, así que el pool mantiene su tamaño.\n\n## Modo clúster\n\nUn clúster ejecuta la aplicación HTTP en varios procesos que comparten un puerto. Establece la opción `cluster` del script de inicio en un número de procesos, o en `'auto'`:\n\n```js\n// index.js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nEl primer proceso se convierte en el **master**. Imprime una cabecera `CLUSTER` (PID, versiones, número de hilos, modo), inicia el primer proceso, espera a que se haya cargado, inicia los demás y luego llama a `options.callback(forks)` si lo estableciste (los demás procesos pueden estar cargándose todavía). Cada proceso carga toda la aplicación y escucha en el puerto compartido; Node.js reparte las conexiones entre ellos. El master no atiende peticiones.\n\n| Opción | Descripción |\n| --- | --- |\n| `cluster` | El número de procesos, o `'auto'` |\n| `limit` | Con `'auto'`: el número máximo de procesos |\n| `tz` | La zona horaria de los procesos (`process.env.TZ`), por defecto `'utc'` |\n| `logs` | `'isolated'` imprime la cabecera del clúster incluso cuando el master se ejecuta bajo otro proceso |\n| `callback` | `function(forks)` llamada en el master después de que se hayan iniciado todos los procesos |\n\nTodas las demás opciones (`port`, `ip`, `config`, …) van a `F.http()` en cada proceso. Los procesos se ejecutan en modo release cuando `options.release` es `true` (el script de arranque oficial la activa con `--release`) o `options.watcher` es `false`. Si no, se ejecutan en modo debug y el master los reinicia todos cuando cambia un archivo fuente.\n\nCon `'auto'` el master inicia un proceso y hace ping a cada proceso cada 5 segundos. Cuando la respuesta media tarda más de 70 ms añade un proceso (hasta `limit`); cuando los procesos vuelven a responder rápido elimina el último, si tiene menos de dos peticiones pendientes.\n\nUn proceso que termina se vuelve a iniciar al cabo de un segundo. Para reiniciar tú mismo todos los procesos, crea un archivo vacío llamado `restart` en el directorio de la aplicación: el master lo comprueba cada 5 segundos, lo borra y reinicia los procesos uno a uno, con dos segundos de separación. El master también escribe las estadísticas de todos los procesos en `<start script>.json` (por ejemplo `index.js.json`) aproximadamente cada 50 segundos.\n\nDentro de un proceso del clúster:\n\n```js\nF.isCluster;   // true\nF.isWorker;    // true\nF.id;          // '1', '2', ... the identifier of the process\nF.clusterid;   // the same identifier\n```\n\nEl framework añade `F.clusterid` a los nombres de sus archivos temporales, así los procesos no sobrescriben los archivos de los demás en `tmp/`.\n\n## Mensajes entre procesos del clúster\n\nCada mensaje que recibe un proceso llega como el evento `$message`. Un objeto enviado al master con `process.send()` lo pasa el master a todos los procesos listos, incluido el emisor. Úsalo para mantener sincronizadas las cachés en memoria:\n\n```js\n// definitions/sync.js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// anywhere in a request\nfunction update($) {\n\tif (F.isCluster)\n\t\tprocess.send({ type: 'clearcache', from: F.id });\n\telse\n\t\tMAIN.products = null;\n\t$.success();\n}\n```\n\nNo uses la propiedad `TYPE` en tus mensajes y no envíes strings que empiecen por `total:`; el framework los usa para sus propios mensajes.\n\n## Comandos de shell\n\n`SHELL(cmd, [callback], [cwd])` ejecuta un comando en la shell del sistema con `child_process.exec()`. Con un callback recibes `(err, stdout)`; sin él devuelve una promesa con la salida estándar. El comando se ejecuta en el directorio de la aplicación salvo que pases `cwd`, y la clave de configuración `$shell` selecciona otra shell (por ejemplo `/bin/bash`).\n\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n\nvar files = await SHELL('ls -1', PATH.public());\n```\n\n## Scripts de Python\n\n`F.python(filename, [callback])` ejecuta un script de Python una vez, en la carpeta del script, y te da su salida estándar. `F.pipinstall(name, [callback])` instala un paquete de Python con `pip`. Ambos usan el comando de la clave de configuración `$python` (`python3` por defecto) y devuelven una promesa sin callback:\n\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/report.py'));\nconsole.log(output);\n```\n\nPara un script que sigue ejecutándose e intercambia mensajes con la aplicación, usa un pipeline.\n\n## Pipelines de Python\n\n`PYPELINE(name, [options])` inicia un proceso `python3` y se comunica con él mediante un socket Unix. `name` es un archivo de la carpeta `pypelines/` sin `.py` (`PYPELINE('ocr')` ejecuta `pypelines/ocr.py`), una ruta absoluta con `~`, o código Python en línea: un nombre que contiene un salto de línea, `;` o una comilla se ejecuta con `python3 -c`.\n\nEl framework crea el socket en `tmp/` y pasa su ruta al script como primer argumento (`sys.argv[1]`). Cada mensaje en ambas direcciones es una longitud big-endian de 4 bytes seguida de la carga útil. Por defecto la carga útil es JSON (con `type: 'text'` el evento `data` recibe una cadena y con cualquier otro `type`, un buffer):\n\n```python\n# pypelines/upper.py\nimport sys, socket, struct, json\n\ns = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\ns.connect(sys.argv[1])\n\ndef read(n):\n\tdata = b''\n\twhile len(data) < n:\n\t\tchunk = s.recv(n - len(data))\n\t\tif not chunk:\n\t\t\tsys.exit(0)\n\t\tdata += chunk\n\treturn data\n\nwhile True:\n\tsize = struct.unpack('>I', read(4))[0]\n\tmsg = json.loads(read(size))\n\tout = json.dumps({ 'text': msg['text'].upper() }).encode()\n\ts.sendall(struct.pack('>I', len(out)) + out)\n```\n\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text); // HELLO\n});\n\npy.send({ text: 'hello' });\n```\n\nLos mensajes enviados antes de que el script se conecte esperan y salen cuando se conecta. El pipeline emite `open` cuando el script se conecta, `data` por cada mensaje y `restart` cuando vuelve a iniciar el script. Con `autorestart: true` (el valor por defecto) un script que termina se vuelve a iniciar; `py.close()` lo detiene definitivamente. Cuando la aplicación termina, el framework mata todos los procesos de Python en ejecución.\n\nLa lista completa de métodos y opciones está en la referencia de [Workers, hilos y clúster](../../reference/workers-and-threads/). Las tareas programadas se describen en [Programación y eventos](../scheduling-and-events/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwvK9Bx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Workers, threads et cluster","summary":"Worker threads, pools de threads, mode cluster, commandes shell, scripts Python et pipelines Python.","markdown":"---\ntitle: Workers, threads et cluster\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/workers-and-threads/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Workers, threads et cluster\n\n> Worker threads, pools de threads, mode cluster, commandes shell, scripts Python et pipelines Python.\n\nTotal.js 5 peut déplacer du travail hors du processus principal de plusieurs façons : des **worker threads** (`NEWTHREAD()`), des **processus forkés** (`NEWFORK()`), un **pool** de threads ou de forks (`NEWTHREADPOOL()`), un **cluster** de processus HTTP (l'option `cluster` du script de démarrage) et des programmes externes (`SHELL()` et `PYPELINE()`). Tout cela repose sur les modules Node.js `worker_threads`, `child_process` et `cluster`, que le framework expose sous `F.Worker`, `F.Child` et `F.Cluster`.\n\n## Le dossier `workers/`\n\nUn worker est un simple script du dossier `workers/` de l'application. Le nom que tu passes à `NEWTHREAD()` ou `NEWFORK()` est le nom du fichier sans `.js` : `NEWTHREAD('resize')` exécute donc `workers/resize.js`. Un nom qui commence par `~` est un chemin absolu : `NEWTHREAD('~/opt/scripts/resize.js')`.\n\n```text\nmyapp/\n├── index.js\n├── controllers/\n└── workers/\n\t└── calc.js\n```\n\n## Un worker thread\n\nLe script du worker charge le framework et appelle `NEWTHREAD()` **sans nom**. À l'intérieur d'un worker, cela renvoie l'objet worker `F.worker`, avec les données du thread principal et les méthodes pour lui répondre :\n\n```js\n// workers/calc.js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tvar sum = msg.a + msg.b;\n\tworker.send({ sum: sum, user: worker.data.user });\n};\n```\n\nDans l'application principale, `NEWTHREAD(name, [data])` démarre le thread et renvoie le `Worker` de Node.js. `data` est copié dans le thread sous `worker.data` :\n\n```js\n// controllers/default.js\nexports.install = function() {\n\tROUTE('GET /sum/', sum);\n};\n\nfunction sum($) {\n\tvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\tthread.on('message', function(msg) {\n\t\t$.json(msg);\n\t\tthread.kill();\n\t});\n\tthread.postMessage({ a: 1, b: 2 });\n}\n```\n\nLes messages passent par le structured clone de Node.js : les objets, tableaux, chaînes, nombres, dates et buffers arrivent sous forme de copies, les fonctions non. Le thread s'exécute avec le même répertoire de travail que l'application : `PATH.root()` et les autres chemins pointent donc vers la racine de l'application.\n\n`F.worker` possède ces membres :\n\n| Membre | Description |\n| --- | --- |\n| `worker.data` | Le `data` passé à `NEWTHREAD(name, data)`, ou `{}` |\n| `worker.is` | `true` quand le script s'exécute en tant que worker (l'argument `--worker`) |\n| `worker.isfork` | `true` dans un processus issu de `NEWFORK()`, `false` dans un thread |\n| `worker.message` | Assigne une fonction : elle reçoit chaque message du parent |\n| `worker.send(msg)` | Envoie un message au parent (alias `worker.postMessage()`) |\n| `worker.exit([code])` | Termine le processus du worker avec le code (par défaut `0`) ; alias `kill()` et `close()` |\n| `worker.setTimeout(ms)` | Termine le worker avec le code `1` après `ms` millisecondes ; rappelle-la pour relancer le compte à rebours |\n\n`setTimeout()` est un watchdog : appelle-la au démarrage d'une tâche, et le worker se termine de lui-même si la tâche dure trop longtemps.\n\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\theavyjob(msg, function(err, response) {\n\t\tworker.send({ error: err ? err + '' : null, response: response });\n\t});\n};\n```\n\nCôté principal, l'objet renvoyé est un `Worker` Node.js normal (`on('message')`, `on('error')`, `on('exit')`, `postMessage()`, `terminate()`). Le framework ajoute `kill()` et `exit()`, qui appellent tous deux `terminate()`.\n\n## Un processus forké\n\n`NEWFORK(name)` exécute le script de `workers/` dans un nouveau processus Node.js (`child_process.fork()`) au lieu d'un thread. Un fork a sa propre mémoire et sa propre boucle d'événements : un plantage ou une tâche bloquante ne peut donc pas affecter l'application. Le script appelle `NEWFORK()` sans nom pour obtenir le même objet `F.worker` :\n\n```js\n// workers/report.js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn; // internal messages of the framework, e.g. 'total:init'\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nL'objet renvoyé est un `ChildProcess` Node.js ; le framework ajoute `postMessage()` (identique à `send()`) et `terminate()`, qui tue le processus avec `SIGKILL`. Les messages sont sérialisés en JSON. Un fork ne reçoit pas de `data` (`worker.data` vaut `{}`) : envoie donc l'entrée comme premier message. Le répertoire de travail d'un fork est le dossier de son script : `PATH.root()` dans un fork pointe donc vers `workers/`. Le framework du fork envoie la chaîne `total:init` au parent après son démarrage ; ignore les messages de type chaîne, comme dans l'exemple.\n\n## Un pool de threads\n\n`NEWTHREADPOOL(name, count, [isfork])` démarre d'un coup `count` threads du même script (ou `count` forks lorsque `isfork` vaut `true`) et les prête aux tâches une par une. Les workers ne reçoivent pas de données : `worker.data` vaut donc `{}` et l'entrée passe par les messages. Une tâche obtient un worker libre et une fonction `release` ; tant qu'elle n'appelle pas `release()`, le worker n'est pas donné à une autre tâche. Les tâches qui arrivent alors que tous les workers sont occupés attendent dans une file.\n\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\n`pool.exec()` sans fonction renvoie une promesse résolue avec le worker ; appelle `worker.release()` lorsque la tâche est terminée :\n\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 1 });\n```\n\nAvant qu'un worker passe à la tâche suivante, le pool supprime tous ses écouteurs `message` : chaque tâche attache donc les siens. Le pool est aussi stocké dans `F.workers[name]`, et `pool.workers` et `pool.pending` contiennent les workers et les tâches en attente. `pool.count` est le nombre de workers. Un worker qui se termine (ou plante) est remplacé par un nouveau, le pool garde donc sa taille.\n\n## Mode cluster\n\nUn cluster exécute l'application HTTP dans plusieurs processus qui partagent un même port. Définis l'option `cluster` du script de démarrage avec un nombre de processus, ou avec `'auto'` :\n\n```js\n// index.js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nLe premier processus devient le **master**. Il affiche un en-tête `CLUSTER` (PID, versions, nombre de threads, mode), démarre le premier processus, attend qu'il soit chargé, démarre les autres puis appelle `options.callback(forks)` si tu l'as défini (les autres processus peuvent encore être en cours de chargement). Chaque processus charge toute l'application et écoute sur le port partagé ; Node.js répartit les connexions entre eux. Le master lui-même ne sert aucune requête.\n\n| Option | Description |\n| --- | --- |\n| `cluster` | Le nombre de processus, ou `'auto'` |\n| `limit` | Avec `'auto'` : le nombre maximal de processus |\n| `tz` | Le fuseau horaire des processus (`process.env.TZ`), par défaut `'utc'` |\n| `logs` | `'isolated'` affiche l'en-tête du cluster même lorsque le master s'exécute sous un autre processus |\n| `callback` | `function(forks)` appelée dans le master une fois tous les processus démarrés |\n\nToutes les autres options (`port`, `ip`, `config`, …) sont transmises à `F.http()` dans chaque processus. Les processus s'exécutent en mode release quand `options.release` vaut `true` (le script de démarrage officiel l'active avec `--release`) ou `options.watcher` vaut `false`. Sinon, ils s'exécutent en mode debug et le master les redémarre tous lorsqu'un fichier source change.\n\nAvec `'auto'`, le master démarre un processus et envoie un ping à chaque processus toutes les 5 secondes. Lorsque la réponse moyenne dépasse 70 ms, il ajoute un processus (jusqu'à `limit`) ; lorsque les processus répondent de nouveau rapidement, il supprime le dernier, s'il a moins de deux requêtes en attente.\n\nUn processus qui se termine est redémarré après une seconde. Pour redémarrer toi-même tous les processus, crée un fichier vide nommé `restart` dans le répertoire de l'application : le master le vérifie toutes les 5 secondes, le supprime et redémarre les processus un par un, à deux secondes d'intervalle. Le master écrit aussi les statistiques de tous les processus dans `<start script>.json` (par exemple `index.js.json`) environ toutes les 50 secondes.\n\nÀ l'intérieur d'un processus du cluster :\n\n```js\nF.isCluster;   // true\nF.isWorker;    // true\nF.id;          // '1', '2', ... the identifier of the process\nF.clusterid;   // the same identifier\n```\n\nLe framework ajoute `F.clusterid` aux noms de ses fichiers temporaires, afin que les processus n'écrasent pas les fichiers des autres dans `tmp/`.\n\n## Messages entre les processus du cluster\n\nChaque message reçu par un processus arrive sous forme d'événement `$message`. Un objet envoyé au master avec `process.send()` est transmis par le master à tous les processus prêts, y compris l'expéditeur. Utilise-le pour garder les caches en mémoire synchronisés :\n\n```js\n// definitions/sync.js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// anywhere in a request\nfunction update($) {\n\tif (F.isCluster)\n\t\tprocess.send({ type: 'clearcache', from: F.id });\n\telse\n\t\tMAIN.products = null;\n\t$.success();\n}\n```\n\nN'utilise pas la propriété `TYPE` dans tes messages et n'envoie pas de chaînes commençant par `total:` ; le framework les utilise pour ses propres messages.\n\n## Commandes shell\n\n`SHELL(cmd, [callback], [cwd])` exécute une commande dans le shell du système avec `child_process.exec()`. Avec un callback, tu obtiens `(err, stdout)` ; sans callback, la fonction renvoie une promesse avec la sortie standard. La commande s'exécute dans le répertoire de l'application, sauf si tu passes `cwd`, et la clé de configuration `$shell` sélectionne un autre shell (par exemple `/bin/bash`).\n\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n\nvar files = await SHELL('ls -1', PATH.public());\n```\n\n## Scripts Python\n\n`F.python(filename, [callback])` exécute un script Python une seule fois, dans le dossier du script, et te donne sa sortie standard. `F.pipinstall(name, [callback])` installe un paquet Python avec `pip`. Les deux utilisent la commande de la clé de configuration `$python` (`python3` par défaut) et renvoient une promesse sans callback :\n\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/report.py'));\nconsole.log(output);\n```\n\nPour un script qui reste en cours d'exécution et échange des messages avec l'application, utilise un pipeline.\n\n## Pipelines Python\n\n`PYPELINE(name, [options])` démarre un processus `python3` et communique avec lui via un socket Unix. `name` est un fichier du dossier `pypelines/` sans `.py` (`PYPELINE('ocr')` exécute `pypelines/ocr.py`), un chemin absolu avec `~`, ou du code Python en ligne : un nom qui contient un saut de ligne, `;` ou un guillemet est exécuté avec `python3 -c`.\n\nLe framework crée le socket dans `tmp/` et passe son chemin au script comme premier argument (`sys.argv[1]`). Chaque message, dans les deux sens, est une longueur sur 4 octets en big-endian suivie de la charge utile. Par défaut, la charge utile est du JSON (avec `type: 'text'`, l'événement `data` reçoit une chaîne, avec tout autre `type`, un buffer) :\n\n```python\n# pypelines/upper.py\nimport sys, socket, struct, json\n\ns = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\ns.connect(sys.argv[1])\n\ndef read(n):\n\tdata = b''\n\twhile len(data) < n:\n\t\tchunk = s.recv(n - len(data))\n\t\tif not chunk:\n\t\t\tsys.exit(0)\n\t\tdata += chunk\n\treturn data\n\nwhile True:\n\tsize = struct.unpack('>I', read(4))[0]\n\tmsg = json.loads(read(size))\n\tout = json.dumps({ 'text': msg['text'].upper() }).encode()\n\ts.sendall(struct.pack('>I', len(out)) + out)\n```\n\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text); // HELLO\n});\n\npy.send({ text: 'hello' });\n```\n\nLes messages envoyés avant la connexion du script attendent et partent dès qu'il se connecte. Le pipeline émet `open` lorsque le script se connecte, `data` pour chaque message, et `restart` lorsqu'il redémarre le script. Avec `autorestart: true` (la valeur par défaut), un script qui se termine est redémarré ; `py.close()` l'arrête définitivement. Lorsque l'application se termine, le framework tue tous les processus Python en cours.\n\nLa liste complète des méthodes et options se trouve dans la référence [Workers, threads et cluster](../../reference/workers-and-threads/). Les tâches planifiées sont décrites dans [Planification et événements](../scheduling-and-events/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwvK9Bx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Worker, thread e cluster","summary":"Worker thread, pool di thread, modalità cluster, comandi di shell, script Python e pipeline Python.","markdown":"---\ntitle: Worker, thread e cluster\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/workers-and-threads/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Worker, thread e cluster\n\n> Worker thread, pool di thread, modalità cluster, comandi di shell, script Python e pipeline Python.\n\nTotal.js 5 può spostare il lavoro fuori dal processo principale in diversi modi: **worker thread** (`NEWTHREAD()`), **processi fork** (`NEWFORK()`), un **pool** di thread o fork (`NEWTHREADPOOL()`), un **cluster** di processi HTTP (l'opzione `cluster` dello script di avvio) e programmi esterni (`SHELL()` e `PYPELINE()`). Tutto questo si basa sui moduli Node.js `worker_threads`, `child_process` e `cluster`, che il framework espone come `F.Worker`, `F.Child` e `F.Cluster`.\n\n## La cartella `workers/`\n\nUn worker è un semplice script nella cartella `workers/` dell'applicazione. Il nome che passi a `NEWTHREAD()` o `NEWFORK()` è il nome del file senza `.js`, quindi `NEWTHREAD('resize')` esegue `workers/resize.js`. Un nome che inizia con `~` è un percorso assoluto: `NEWTHREAD('~/opt/scripts/resize.js')`.\n\n```text\nmyapp/\n├── index.js\n├── controllers/\n└── workers/\n\t└── calc.js\n```\n\n## Un worker thread\n\nLo script del worker carica il framework e chiama `NEWTHREAD()` **senza nome**. Dentro un worker questo restituisce l'oggetto worker `F.worker`, con i dati del thread principale e i metodi per rispondere:\n\n```js\n// workers/calc.js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tvar sum = msg.a + msg.b;\n\tworker.send({ sum: sum, user: worker.data.user });\n};\n```\n\nNell'applicazione principale `NEWTHREAD(name, [data])` avvia il thread e restituisce il `Worker` di Node.js. `data` viene copiato nel thread come `worker.data`:\n\n```js\n// controllers/default.js\nexports.install = function() {\n\tROUTE('GET /sum/', sum);\n};\n\nfunction sum($) {\n\tvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\tthread.on('message', function(msg) {\n\t\t$.json(msg);\n\t\tthread.kill();\n\t});\n\tthread.postMessage({ a: 1, b: 2 });\n}\n```\n\nI messaggi passano per lo structured clone di Node.js: oggetti, array, stringhe, numeri, date e buffer arrivano come copie, le funzioni no. Il thread gira con la stessa directory di lavoro dell'applicazione, quindi `PATH.root()` e gli altri percorsi puntano alla radice dell'applicazione.\n\n`F.worker` ha questi membri:\n\n| Membro | Descrizione |\n| --- | --- |\n| `worker.data` | Il `data` passato a `NEWTHREAD(name, data)`, oppure `{}` |\n| `worker.is` | `true` quando lo script viene eseguito come worker (l'argomento `--worker`) |\n| `worker.isfork` | `true` in un processo di `NEWFORK()`, `false` in un thread |\n| `worker.message` | Assegna una funzione: riceve ogni messaggio dal processo padre |\n| `worker.send(msg)` | Invia un messaggio al processo padre (alias `worker.postMessage()`) |\n| `worker.exit([code])` | Termina il processo del worker con il codice (predefinito `0`); alias `kill()` e `close()` |\n| `worker.setTimeout(ms)` | Termina il worker con il codice `1` dopo `ms` millisecondi; chiamalo di nuovo per riavviare il conto alla rovescia |\n\n`setTimeout()` è un watchdog: chiamalo quando inizia un job, e il worker termina da solo se il job dura troppo.\n\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\theavyjob(msg, function(err, response) {\n\t\tworker.send({ error: err ? err + '' : null, response: response });\n\t});\n};\n```\n\nSul lato principale l'oggetto restituito è un normale `Worker` di Node.js (`on('message')`, `on('error')`, `on('exit')`, `postMessage()`, `terminate()`). Il framework aggiunge `kill()` ed `exit()`, che chiamano entrambi `terminate()`.\n\n## Un processo fork\n\n`NEWFORK(name)` esegue lo script di `workers/` in un nuovo processo Node.js (`child_process.fork()`) invece che in un thread. Un fork ha la propria memoria e il proprio event loop, quindi un crash o un job bloccante non possono influire sull'applicazione. Lo script chiama `NEWFORK()` senza nome per ottenere lo stesso oggetto `F.worker`:\n\n```js\n// workers/report.js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn; // internal messages of the framework, e.g. 'total:init'\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nL'oggetto restituito è un `ChildProcess` di Node.js; il framework aggiunge `postMessage()` (lo stesso di `send()`) e `terminate()`, che termina il processo con `SIGKILL`. I messaggi vengono serializzati in JSON. Un fork non riceve `data` (`worker.data` è `{}`), quindi invia l'input come primo messaggio. La directory di lavoro di un fork è la cartella del suo script, quindi `PATH.root()` dentro un fork punta a `workers/`. Il framework nel fork invia la stringa `total:init` al processo padre dopo l'avvio; ignora i messaggi di tipo stringa, come nell'esempio.\n\n## Un pool di thread\n\n`NEWTHREADPOOL(name, count, [isfork])` avvia subito `count` thread dello stesso script (o `count` fork quando `isfork` è `true`) e li presta ai job uno alla volta. I worker non ricevono dati, quindi `worker.data` è `{}` e l'input va nei messaggi. Un job ottiene un worker libero e una funzione `release`; finché non chiama `release()`, il worker non viene dato a un altro job. I job che arrivano mentre tutti i worker sono occupati attendono in una coda.\n\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\n`pool.exec()` senza funzione restituisce una promise che si risolve con il worker; chiama `worker.release()` quando il job è terminato:\n\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 1 });\n```\n\nPrima che un worker passi al job successivo, il pool rimuove tutti i suoi listener `message`, così ogni job collega i propri. Il pool viene salvato anche in `F.workers[name]`, e `pool.workers` e `pool.pending` contengono i worker e i job in attesa. `pool.count` è il numero di worker. Un worker che termina (o va in crash) viene sostituito da uno nuovo, così il pool mantiene la sua dimensione.\n\n## Modalità cluster\n\nUn cluster esegue l'applicazione HTTP in più processi che condividono una porta. Imposta l'opzione `cluster` nello script di avvio a un numero di processi, oppure a `'auto'`:\n\n```js\n// index.js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nIl primo processo diventa il **master**. Stampa un'intestazione `CLUSTER` (PID, versioni, numero di thread, modalità), avvia il primo processo, attende che sia caricato, avvia gli altri e poi chiama `options.callback(forks)` se l'hai impostata (gli altri processi potrebbero essere ancora in caricamento). Ogni processo carica l'intera applicazione e resta in ascolto sulla porta condivisa; Node.js distribuisce le connessioni tra di essi. Il master stesso non serve richieste.\n\n| Opzione | Descrizione |\n| --- | --- |\n| `cluster` | Il numero di processi, oppure `'auto'` |\n| `limit` | Con `'auto'`: il numero massimo di processi |\n| `tz` | Il fuso orario dei processi (`process.env.TZ`), predefinito `'utc'` |\n| `logs` | `'isolated'` stampa l'intestazione del cluster anche quando il master gira sotto un altro processo |\n| `callback` | `function(forks)` chiamata nel master dopo che tutti i processi sono partiti |\n\nTutte le altre opzioni (`port`, `ip`, `config`, …) vanno a `F.http()` in ogni processo. I processi girano in modalità release quando `options.release` è `true` (lo script di avvio ufficiale la attiva con `--release`) o `options.watcher` è `false`. Altrimenti girano in modalità debug e il master li riavvia tutti quando cambia un file sorgente.\n\nCon `'auto'` il master avvia un processo e fa un ping a ogni processo ogni 5 secondi. Quando la risposta media impiega più di 70 ms aggiunge un processo (fino a `limit`); quando i processi tornano a rispondere velocemente rimuove l'ultimo, se ha meno di due richieste in sospeso.\n\nUn processo che termina viene riavviato dopo un secondo. Per riavviare tu stesso tutti i processi, crea un file vuoto chiamato `restart` nella directory dell'applicazione: il master lo controlla ogni 5 secondi, lo elimina e riavvia i processi uno alla volta, a due secondi di distanza. Il master scrive anche le statistiche di tutti i processi in `<start script>.json` (per esempio `index.js.json`) circa ogni 50 secondi.\n\nDentro un processo del cluster:\n\n```js\nF.isCluster;   // true\nF.isWorker;    // true\nF.id;          // '1', '2', ... the identifier of the process\nF.clusterid;   // the same identifier\n```\n\nIl framework aggiunge `F.clusterid` ai nomi dei suoi file temporanei, così i processi non sovrascrivono i file degli altri in `tmp/`.\n\n## Messaggi tra i processi del cluster\n\nOgni messaggio che un processo riceve arriva come evento `$message`. Un oggetto inviato al master con `process.send()` viene passato dal master a tutti i processi pronti, mittente compreso. Usalo per mantenere sincronizzate le cache in memoria:\n\n```js\n// definitions/sync.js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// anywhere in a request\nfunction update($) {\n\tif (F.isCluster)\n\t\tprocess.send({ type: 'clearcache', from: F.id });\n\telse\n\t\tMAIN.products = null;\n\t$.success();\n}\n```\n\nNon usare la proprietà `TYPE` nei tuoi messaggi e non inviare stringhe che iniziano con `total:`; il framework le usa per i propri messaggi.\n\n## Comandi di shell\n\n`SHELL(cmd, [callback], [cwd])` esegue un comando nella shell di sistema con `child_process.exec()`. Con una callback ottieni `(err, stdout)`; senza, restituisce una promise con lo standard output. Il comando viene eseguito nella directory dell'applicazione, a meno che tu non passi `cwd`, e la chiave di configurazione `$shell` seleziona un'altra shell (per esempio `/bin/bash`).\n\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n\nvar files = await SHELL('ls -1', PATH.public());\n```\n\n## Script Python\n\n`F.python(filename, [callback])` esegue uno script Python una volta, nella cartella dello script, e ti restituisce il suo output standard. `F.pipinstall(name, [callback])` installa un pacchetto Python con `pip`. Entrambe usano il comando della chiave di configurazione `$python` (`python3` per impostazione predefinita) e senza callback restituiscono una promise:\n\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/report.py'));\nconsole.log(output);\n```\n\nPer uno script che resta in esecuzione e scambia messaggi con l'applicazione, usa una pipeline.\n\n## Pipeline Python\n\n`PYPELINE(name, [options])` avvia un processo `python3` e comunica con esso tramite un socket Unix. `name` è un file nella cartella `pypelines/` senza `.py` (`PYPELINE('ocr')` esegue `pypelines/ocr.py`), un percorso assoluto con `~`, oppure codice Python inline: un nome che contiene un a capo, `;` o un apice viene eseguito con `python3 -c`.\n\nIl framework crea il socket in `tmp/` e passa il suo percorso allo script come primo argomento (`sys.argv[1]`). Ogni messaggio, in entrambe le direzioni, è una lunghezza di 4 byte big-endian seguita dal payload. Per impostazione predefinita il payload è JSON (con `type: 'text'` l'evento `data` riceve una stringa, con qualsiasi altro `type` un buffer):\n\n```python\n# pypelines/upper.py\nimport sys, socket, struct, json\n\ns = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\ns.connect(sys.argv[1])\n\ndef read(n):\n\tdata = b''\n\twhile len(data) < n:\n\t\tchunk = s.recv(n - len(data))\n\t\tif not chunk:\n\t\t\tsys.exit(0)\n\t\tdata += chunk\n\treturn data\n\nwhile True:\n\tsize = struct.unpack('>I', read(4))[0]\n\tmsg = json.loads(read(size))\n\tout = json.dumps({ 'text': msg['text'].upper() }).encode()\n\ts.sendall(struct.pack('>I', len(out)) + out)\n```\n\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text); // HELLO\n});\n\npy.send({ text: 'hello' });\n```\n\nI messaggi inviati prima che lo script si colleghi restano in attesa e partono quando si collega. La pipeline emette `open` quando lo script si collega, `data` per ogni messaggio e `restart` quando riavvia lo script. Con `autorestart: true` (il predefinito) uno script che termina viene riavviato; `py.close()` lo ferma definitivamente. Quando l'applicazione termina, il framework chiude tutti i processi Python in esecuzione.\n\nL'elenco completo di metodi e opzioni è nel riferimento di [Worker, thread e cluster](../../reference/workers-and-threads/). I job pianificati sono descritti in [Pianificazione ed eventi](../scheduling-and-events/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwvK9Bx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Workery, vlákna a klaster","summary":"Worker vlákna, pooly vlákien, režim klastra, shell príkazy, Python skripty a Python pipeliny.","markdown":"---\ntitle: \"Workery, vlákna a klaster\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/workers-and-threads/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Workery, vlákna a klaster\n\n> Worker vlákna, pooly vlákien, režim klastra, shell príkazy, Python skripty a Python pipeliny.\n\nTotal.js 5 vie presunúť prácu mimo hlavného procesu niekoľkými spôsobmi: **worker vlákna** (`NEWTHREAD()`), **forknuté procesy** (`NEWFORK()`), **pool** vlákien alebo forkov (`NEWTHREADPOOL()`), **klaster** HTTP procesov (voľba `cluster` štartovacieho skriptu) a externé programy (`SHELL()` a `PYPELINE()`). Všetko tu je postavené na Node.js moduloch `worker_threads`, `child_process` a `cluster`, ktoré framework sprístupňuje ako `F.Worker`, `F.Child` a `F.Cluster`.\n\n## Priečinok `workers/`\n\nWorker je obyčajný skript v priečinku `workers/` aplikácie. Názov, ktorý odovzdáš do `NEWTHREAD()` alebo `NEWFORK()`, je názov súboru bez `.js`, takže `NEWTHREAD('resize')` spustí `workers/resize.js`. Názov, ktorý začína `~`, je absolútna cesta: `NEWTHREAD('~/opt/scripts/resize.js')`.\n\n```text\nmyapp/\n├── index.js\n├── controllers/\n└── workers/\n\t└── calc.js\n```\n\n## Worker vlákno\n\nSkript workera načíta framework a zavolá `NEWTHREAD()` **bez názvu**. Vnútri workera to vráti objekt workera `F.worker` s dátami z hlavného vlákna a metódami na odpovedanie:\n\n```js\n// workers/calc.js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tvar sum = msg.a + msg.b;\n\tworker.send({ sum: sum, user: worker.data.user });\n};\n```\n\nV hlavnej aplikácii `NEWTHREAD(name, [data])` spustí vlákno a vráti Node.js `Worker`. `data` sa skopírujú do vlákna ako `worker.data`:\n\n```js\n// controllers/default.js\nexports.install = function() {\n\tROUTE('GET /sum/', sum);\n};\n\nfunction sum($) {\n\tvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\tthread.on('message', function(msg) {\n\t\t$.json(msg);\n\t\tthread.kill();\n\t});\n\tthread.postMessage({ a: 1, b: 2 });\n}\n```\n\nSprávy prechádzajú cez structured clone z Node.js: objekty, polia, reťazce, čísla, dátumy a buffery prídu ako kópie, funkcie nie. Vlákno beží s rovnakým pracovným adresárom ako aplikácia, takže `PATH.root()` a ostatné cesty ukazujú na koreň aplikácie.\n\n`F.worker` má tieto členy:\n\n| Člen | Popis |\n| --- | --- |\n| `worker.data` | `data` odovzdané do `NEWTHREAD(name, data)` alebo `{}` |\n| `worker.is` | `true`, keď skript beží ako worker (argument `--worker`) |\n| `worker.isfork` | `true` v procese z `NEWFORK()`, `false` vo vlákne |\n| `worker.message` | Priraď funkciu: dostane každú správu od rodiča |\n| `worker.send(msg)` | Pošle správu rodičovi (alias `worker.postMessage()`) |\n| `worker.exit([code])` | Ukončí proces workera s kódom (predvolene `0`); aliasy `kill()` a `close()` |\n| `worker.setTimeout(ms)` | Ukončí workera s kódom `1` po `ms` milisekundách; zavolaj znova, aby sa odpočet reštartoval |\n\n`setTimeout()` je watchdog: zavolaj ho, keď úloha začína, a worker sa sám ukončí, ak úloha trvá príliš dlho.\n\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\theavyjob(msg, function(err, response) {\n\t\tworker.send({ error: err ? err + '' : null, response: response });\n\t});\n};\n```\n\nNa strane hlavnej aplikácie je vrátený objekt bežný Node.js `Worker` (`on('message')`, `on('error')`, `on('exit')`, `postMessage()`, `terminate()`). Framework pridáva `kill()` a `exit()`, ktoré obe volajú `terminate()`.\n\n## Forknutý proces\n\n`NEWFORK(name)` spustí skript z `workers/` v novom procese Node.js (`child_process.fork()`) namiesto vlákna. Fork má vlastnú pamäť a vlastný event loop, takže pád alebo blokujúca úloha nemôže ovplyvniť aplikáciu. Skript zavolá `NEWFORK()` bez názvu, aby dostal ten istý objekt `F.worker`:\n\n```js\n// workers/report.js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn; // internal messages of the framework, e.g. 'total:init'\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nVrátený objekt je Node.js `ChildProcess`; framework pridáva `postMessage()` (to isté ako `send()`) a `terminate()`, ktorá zabije proces cez `SIGKILL`. Správy sa serializujú ako JSON. Fork nedostane žiadne `data` (`worker.data` je `{}`), preto vstup pošli ako prvú správu. Pracovný adresár forku je priečinok jeho skriptu, takže `PATH.root()` vnútri forku ukazuje na `workers/`. Framework vo forku po štarte pošle rodičovi reťazec `total:init`; reťazcové správy preskakuj, ako v príklade.\n\n## Pool vlákien\n\n`NEWTHREADPOOL(name, count, [isfork])` spustí naraz `count` vlákien toho istého skriptu (alebo `count` forkov, keď je `isfork` rovné `true`) a požičiava ich úlohám jedno po druhom. Workery nedostanú žiadne dáta, takže `worker.data` je `{}` a vstup ide v správach. Úloha dostane voľného workera a funkciu `release`; kým nezavolá `release()`, worker sa nedá inej úlohe. Úlohy, ktoré prídu, kým sú všetky workery obsadené, čakajú vo fronte.\n\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\n`pool.exec()` bez funkcie vráti promise, ktorý sa splní s workerom; keď je úloha hotová, zavolaj `worker.release()`:\n\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 1 });\n```\n\nPredtým, ako worker prejde na ďalšiu úlohu, pool odstráni všetky jeho poslucháče `message`, takže každá úloha si pripojí vlastný. Pool sa ukladá aj do `F.workers[name]` a `pool.workers` a `pool.pending` obsahujú workery a čakajúce úlohy. `pool.count` je počet workerov. Worker, ktorý skončí (alebo spadne), sa nahradí novým, takže pool si zachová svoju veľkosť.\n\n## Režim klastra\n\nKlaster spúšťa HTTP aplikáciu vo viacerých procesoch, ktoré zdieľajú jeden port. Nastav voľbu `cluster` v štartovacom skripte na počet procesov alebo na `'auto'`:\n\n```js\n// index.js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.limit = 10;\n\nTotal.run(options);\n```\n\nPrvý proces sa stane **masterom**. Vypíše hlavičku `CLUSTER` (PID, verzie, počet vlákien, režim), spustí prvý proces, počká, kým sa načíta, spustí ostatné a potom zavolá `options.callback(forks)`, ak ho nastavíš (ostatné procesy sa môžu ešte načítavať). Každý proces načíta celú aplikáciu a počúva na zdieľanom porte; Node.js medzi ne rozdeľuje spojenia. Samotný master neobsluhuje žiadne požiadavky.\n\n| Voľba | Popis |\n| --- | --- |\n| `cluster` | Počet procesov alebo `'auto'` |\n| `limit` | S `'auto'`: maximálny počet procesov |\n| `tz` | Časová zóna procesov (`process.env.TZ`), predvolene `'utc'` |\n| `logs` | `'isolated'` vypíše hlavičku klastra, aj keď master beží pod iným procesom |\n| `callback` | `function(forks)` volaná v masteri po spustení všetkých procesov |\n\nVšetky ostatné voľby (`port`, `ip`, `config`, …) idú do `F.http()` v každom procese. Procesy bežia v režime release, keď je `options.release` rovné `true` (oficiálny štartovací skript ho zapne cez `--release`) alebo `options.watcher` rovné `false`. Inak bežia v režime debug a master ich všetky reštartuje, keď sa zmení zdrojový súbor.\n\nS `'auto'` master spustí jeden proces a každých 5 sekúnd pingne každý proces. Keď priemerná odpoveď trvá dlhšie ako 70 ms, pridá proces (najviac `limit`); keď procesy znova odpovedajú rýchlo, odstráni posledný, ak má menej ako dve čakajúce požiadavky.\n\nProces, ktorý skončí, sa znova spustí po jednej sekunde. Ak chceš reštartovať všetky procesy sám, vytvor prázdny súbor s názvom `restart` v adresári aplikácie: master ho každých 5 sekúnd kontroluje, zmaže ho a reštartuje procesy jeden po druhom s odstupom dvoch sekúnd. Master tiež zhruba každých 50 sekúnd zapisuje štatistiky všetkých procesov do `<start script>.json` (napríklad `index.js.json`).\n\nVnútri procesu klastra:\n\n```js\nF.isCluster;   // true\nF.isWorker;    // true\nF.id;          // '1', '2', ... the identifier of the process\nF.clusterid;   // the same identifier\n```\n\nFramework pridáva `F.clusterid` do názvov svojich dočasných súborov, takže si procesy navzájom neprepisujú súbory v `tmp/`.\n\n## Správy medzi procesmi klastra\n\nKaždá správa, ktorú proces dostane, príde ako udalosť `$message`. Objekt poslaný masterovi cez `process.send()` master odovzdá všetkým pripraveným procesom vrátane odosielateľa. Použi to na synchronizáciu cache v pamäti:\n\n```js\n// definitions/sync.js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// anywhere in a request\nfunction update($) {\n\tif (F.isCluster)\n\t\tprocess.send({ type: 'clearcache', from: F.id });\n\telse\n\t\tMAIN.products = null;\n\t$.success();\n}\n```\n\nNepoužívaj vlastnosť `TYPE` vo svojich správach a neposielaj reťazce, ktoré začínajú `total:`; framework ich používa pre vlastné správy.\n\n## Shell príkazy\n\n`SHELL(cmd, [callback], [cwd])` spustí príkaz v systémovom shelli cez `child_process.exec()`. S callbackom dostaneš `(err, stdout)`; bez neho vracia promise so štandardným výstupom. Príkaz beží v adresári aplikácie, pokiaľ neodovzdáš `cwd`, a konfiguračný kľúč `$shell` vyberie iný shell (napríklad `/bin/bash`).\n\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n\nvar files = await SHELL('ls -1', PATH.public());\n```\n\n## Python skripty\n\n`F.python(filename, [callback])` spustí Python skript raz, v priečinku skriptu, a dá ti jeho štandardný výstup. `F.pipinstall(name, [callback])` nainštaluje Python balík cez `pip`. Obe používajú príkaz z konfiguračného kľúča `$python` (predvolene `python3`) a bez callbacku vrátia promise:\n\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/report.py'));\nconsole.log(output);\n```\n\nPre skript, ktorý beží ďalej a vymieňa si správy s aplikáciou, použi pipeline.\n\n## Python pipeliny\n\n`PYPELINE(name, [options])` spustí proces `python3` a komunikuje s ním cez Unix socket. `name` je súbor v priečinku `pypelines/` bez `.py` (`PYPELINE('ocr')` spustí `pypelines/ocr.py`), absolútna cesta s `~` alebo inline Python kód: názov, ktorý obsahuje nový riadok, `;` alebo úvodzovku, sa spustí cez `python3 -c`.\n\nFramework vytvorí socket v `tmp/` a jeho cestu odovzdá skriptu ako prvý argument (`sys.argv[1]`). Každá správa v oboch smeroch je 4-bajtová big-endian dĺžka, za ktorou nasleduje obsah. Predvolene je obsah JSON (s `type: 'text'` dostane udalosť `data` reťazec, s iným `type` buffer):\n\n```python\n# pypelines/upper.py\nimport sys, socket, struct, json\n\ns = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\ns.connect(sys.argv[1])\n\ndef read(n):\n\tdata = b''\n\twhile len(data) < n:\n\t\tchunk = s.recv(n - len(data))\n\t\tif not chunk:\n\t\t\tsys.exit(0)\n\t\tdata += chunk\n\treturn data\n\nwhile True:\n\tsize = struct.unpack('>I', read(4))[0]\n\tmsg = json.loads(read(size))\n\tout = json.dumps({ 'text': msg['text'].upper() }).encode()\n\ts.sendall(struct.pack('>I', len(out)) + out)\n```\n\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text); // HELLO\n});\n\npy.send({ text: 'hello' });\n```\n\nSprávy poslané predtým, ako sa skript pripojí, čakajú a odídu, keď sa pripojí. Pipeline vyvolá `open`, keď sa skript pripojí, `data` pre každú správu a `restart`, keď skript spustí znova. S `autorestart: true` (predvolene) sa skript, ktorý skončí, znova spustí; `py.close()` ho zastaví natrvalo. Keď aplikácia končí, framework zabije všetky bežiace Python procesy.\n\nÚplný zoznam metód a volieb je v referencii [Workery, vlákna a klaster](../../reference/workers-and-threads/). Plánované úlohy sú opísané v [Plánovanie a udalosti](../scheduling-and-events/).\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwWSJGx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"MCP server","summary":"Expose actions as tools for AI clients with the built-in MCP endpoint POST /$mcp/ and protect it with Total.mcp.auth; GET /$mcp/client.js gives agents the tools as code.","markdown":"---\ntitle: MCP server\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/mcp-server/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# MCP server\n\n> Expose actions as tools for AI clients with the built-in MCP endpoint POST /$mcp/ and protect it with Total.mcp.auth; GET /$mcp/client.js gives agents the tools as code.\n\nThe **Model Context Protocol** (MCP) lets an AI client, such as an assistant, an agent or an editor, find the tools of a server and call them. Total.js 5 has an MCP server: it turns your actions into tools. Set the configuration key `$mcp` and add `mcp: true` to the actions that the AI may use.\n\n```\n# config\nname     : Tasks\nversion  : 1.0\n$mcp     : true\n```\n\n```js\n// actions/tasks.js\nNEWACTION('Tasks|create', {\n\tsummary: 'Creates a task and returns its ID',\n\tmcp: true,\n\tinput: '*name:String // The name of the task, due:Date // When the task must be done',\n\toutput: 'id:UID',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('tasks').insert(model).callback(() => $.callback({ id: model.id }));\n\t}\n});\n\nNEWACTION('Tasks|remove', {\n\tsummary: 'Removes a task',\n\tmcp: true,\n\tparams: '*id:UID // The ID of the task',\n\taction: function($) {\n\t\tNOSQL('tasks').remove().id($.params.id).callback(function(err, count) {\n\t\t\tif (count)\n\t\t\t\t$.success();\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n```\n\nThe AI client connects to `http://localhost:8000/$mcp/` and sees the tools `Tasks_create` and `Tasks_remove`.\n\n## The endpoint\n\nWith `$mcp : true` the framework creates the route `POST /$mcp/` when the application is ready. Set the key in the `config` file (or in code before the start); without it the URL answers `404`.\n\nThe endpoint speaks JSON-RPC 2.0 over HTTP. Each request is one JSON-RPC message and the answer is one JSON object with `content-type: application/json`. The server keeps no session and sends no stream, so `GET /$mcp/` gives `404`. A request can have up to 10 MB and can take up to 300 seconds. In the settings of an AI client, choose the HTTP transport and enter the URL of the endpoint.\n\n| Method | Answer |\n| --- | --- |\n| `initialize` | The protocol version, `capabilities: { tools: {} }` and `serverInfo` with `CONF.name` and `CONF.version` |\n| `ping` | An empty result |\n| `tools/list` | The list of the tools |\n| `tools/call` | Runs a tool (an action) and returns its response |\n| `server/discover` | The supported version `2026-07-28`, the capabilities and the server info |\n| a notification (a message without `id`) | Status `202` without a body |\n\nAnother method gets the error `-32601` (`Method not found`). A message without `\"jsonrpc\": \"2.0\"` or without a method, or a JSON array (a batch), gets `-32600` (`Invalid Request`).\n\n```js\n// the answer to { \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"initialize\", \"params\": { \"protocolVersion\": \"2025-06-18\" } }\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n`initialize` answers with the version that the client asks for when it is in `Total.mcp.versions` (`2026-07-28`, `2025-11-25`, `2025-06-18`, `2025-03-26`), and with the first one otherwise.\n\n## Actions as tools\n\nEvery action with `mcp: true` is a tool. The list is built again 200 ms after each `NEWACTION()`, so the actions of plugins and of later code are in it too.\n\n- **name**: the name of the action with each character other than a letter, a digit, `_` and `-` replaced by `_`, at most 64 characters. `Tasks|create` is `Tasks_create`.\n- **description**: the `summary` option of the action, or its `name` option.\n- **inputSchema**: an object with up to three keys, `input`, `query` and `params`, made from the schemas of the action. A key is required when its schema has a required field.\n- **outputSchema**: made from the `output` schema, when the action has one.\n\nThe fields are converted to standard JSON Schema. The `//` message of a field is its description, so write messages that tell the AI what to send (a message ends at the next comma, so it can't contain one). `Date` is a string with `format: 'date-time'`, `Email` has `format: 'email'`, an enum keeps its values, and a type that can be `null` (`String2`, `UID`, `JSON` and others) gets the type `['string', 'null']`. Every field of `params` is a string.\n\n```js\n// tools/list, the tool Tasks_remove\n{\n\t\"name\": \"Tasks_remove\",\n\t\"description\": \"Removes a task\",\n\t\"inputSchema\": {\n\t\t\"type\": \"object\",\n\t\t\"properties\": {\n\t\t\t\"params\": {\n\t\t\t\t\"type\": \"object\",\n\t\t\t\t\"description\": \"URL params passed to this action.\",\n\t\t\t\t\"properties\": { \"id\": { \"type\": \"string\", \"description\": \"The ID of the task\" } },\n\t\t\t\t\"additionalProperties\": false,\n\t\t\t\t\"required\": [\"id\"]\n\t\t\t}\n\t\t},\n\t\t\"required\": [\"params\"]\n\t}\n}\n```\n\n`F.actions[name].toAITool()` returns the same definition for one action, and `Total.mcp.tools` holds the whole list.\n\n## Calling a tool\n\nThe AI client sends `tools/call` with the name of the tool and its arguments: `input` (the payload; `data` is accepted too), `query` and `params`.\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_create\", \"arguments\": { \"input\": { \"name\": \"Call Peter\", \"due\": \"2026-11-20\" } } } }\n```\n\nThe framework runs the action with `ACTION()`, so the schemas validate the arguments as for any other call. There is no controller, and the user of the action is the user that `Total.mcp.auth` accepted the request with (see below). With the default function it is `{ id: 'ai', name: 'AI', sa: true }`: the `user: true`, `sa` and `permissions` checks pass, and an action with `user: false` fails with `401`. The `id` from the query string of the endpoint (`/$mcp/?id=...`) is in `$.config.id`.\n\nThe response of the action is sent as text: a string as it is, any other value as JSON. When the response is an object (not an array), it is also in `structuredContent`:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"id\\\":\\\"JafvB11cV61f\\\"}\" }], \"structuredContent\": { \"id\": \"JafvB11cV61f\" } } }\n```\n\nErrors of validation and of `$.invalid()` come back as a result with `isError: true` and the JSON array of the errors as text, so the AI can read them and try again:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 6, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"[{\\\"error\\\":\\\"404: Not Found\\\"}]\" }], \"isError\": true } }\n```\n\nAn unknown tool, or an action without `mcp: true`, gets the error `-32602` (`Unknown tool: name`); arguments that are not an object get `-32602` too. Report errors with `$.invalid()`. An exception thrown in the action (also in an `async` one) is written to the error log, and the client gets a result with `isError: true` and a short message (`Tool execution failed`, or `500: Internal Server Error` for an `async` action), without the details of the exception.\n\n## Authorization\n\nBy default every request is allowed. Anyone who can reach the URL can run the tools, and the tools run as the super admin `{ id: 'ai', name: 'AI', sa: true }`, so protect the endpoint with `Total.mcp.auth`. The function gets `$` with the token from the `Authorization` header (`$.token`, without `Bearer `), `$.headers`, `$.query` and `$.ip`. Call `$.success(user)` to accept the request or `$.invalid()` to refuse it.\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcptoken)\n\t\t$.success({ id: 'mcp' });\n\telse\n\t\t$.invalid();\n};\n```\n\nA refused request gets status `401` and the JSON-RPC error `-32001` (`Unauthorized`). The tools run as the user given to `$.success(user)`, so the `user`, `sa` and `permissions` checks of the actions apply to that user. `$.success()` without a user gives an empty user `{}`.\n\n`Total.mcp.filter` decides which tools each caller may use. It gets the definition of a tool and `$` with the caller in `$.user`, and returns `true` to allow the tool. A tool that is not allowed is not in `tools/list`, and calling it gives `-32602` (`Unknown tool`):\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader' });\n\telse\n\t\t$.invalid();\n};\n\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n## Code mode\n\nEvery tool call goes through the model: the definitions of all tools are sent with each request, and every result comes back into the conversation. With many tools or big results that costs many tokens. In code mode the agent writes a small script that calls the tools, runs it on its side (a shell, a sandbox) and only the output of the script reaches the model.\n\n`GET /$mcp/client.js` returns the tools of the caller as a JavaScript module: one function per tool, with JSDoc that describes the arguments and the result, written from the same schemas as `tools/list`. It is on whenever `$mcp` is on and goes through the same `Total.mcp.auth` and `Total.mcp.filter`, so the file has exactly the tools that the token may use:\n\n```\ncurl -H 'Authorization: Bearer TOKEN' https://app.example.com/$mcp/client.js > client.js\n```\n\n```js\n// /**\n//  * Creates a task and returns its ID\n//  * @param {Object} args\n//  * @param {Object} args.input Payload (request body) passed to this action.\n//  * @param {String} args.input.name The name of the task\n//  * @param {String} [args.input.due] When the task must be done (ISO date)\n//  * @returns {Promise<{ id: ?String }>}\n//  */\n// api.Tasks_create = args => call(\"Tasks_create\", args);\n\nconst api = require('./client.js')('TOKEN');\n\nfor (const name of ['Call Peter', 'Send the offer'])\n\tawait api.Tasks_create({ input: { name } });\n\nconsole.log('2 tasks created');\n```\n\n`require('./client.js')(token, [url])` returns the functions. Each one sends `tools/call` to `POST /$mcp/` with the token, resolves with the output of the tool and throws an `Error` with the message of a tool error. The client needs Node.js 18 or newer and no packages. With `?q=words` the file has only the tools whose name or description contain all the words, so an agent can read just what it needs: `/$mcp/client.js?q=task`.\n\nNothing runs on the server: the script runs where the agent runs, and every call is a normal tool call with the permissions of the token.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwWSJGx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"MCP-Server","summary":"Aktionen über den eingebauten MCP-Endpunkt POST /$mcp/ als Tools für KI-Clients bereitstellen und ihn mit Total.mcp.auth schützen; GET /$mcp/client.js gibt Agenten die Tools als Code.","markdown":"---\ntitle: MCP-Server\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/mcp-server/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# MCP-Server\n\n> Aktionen über den eingebauten MCP-Endpunkt POST /$mcp/ als Tools für KI-Clients bereitstellen und ihn mit Total.mcp.auth schützen; GET /$mcp/client.js gibt Agenten die Tools als Code.\n\nDas **Model Context Protocol** (MCP) lässt einen KI-Client, etwa einen Assistenten, einen Agenten oder einen Editor, die Tools eines Servers finden und aufrufen. Total.js 5 hat einen MCP-Server: Er macht deine Aktionen zu Tools. Setze den Konfigurationsschlüssel `$mcp` und füge `mcp: true` zu den Aktionen hinzu, die die KI verwenden darf.\n\n```\n# config\nname     : Tasks\nversion  : 1.0\n$mcp     : true\n```\n\n```js\n// actions/tasks.js\nNEWACTION('Tasks|create', {\n\tsummary: 'Creates a task and returns its ID',\n\tmcp: true,\n\tinput: '*name:String // The name of the task, due:Date // When the task must be done',\n\toutput: 'id:UID',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('tasks').insert(model).callback(() => $.callback({ id: model.id }));\n\t}\n});\n\nNEWACTION('Tasks|remove', {\n\tsummary: 'Removes a task',\n\tmcp: true,\n\tparams: '*id:UID // The ID of the task',\n\taction: function($) {\n\t\tNOSQL('tasks').remove().id($.params.id).callback(function(err, count) {\n\t\t\tif (count)\n\t\t\t\t$.success();\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n```\n\nDer KI-Client verbindet sich mit `http://localhost:8000/$mcp/` und sieht die Tools `Tasks_create` und `Tasks_remove`.\n\n## Der Endpunkt\n\nMit `$mcp : true` erstellt das Framework die Route `POST /$mcp/`, sobald die Anwendung bereit ist. Setze den Schlüssel in der Datei `config` (oder im Code vor dem Start); ohne ihn antwortet die URL mit `404`.\n\nDer Endpunkt spricht JSON-RPC 2.0 über HTTP. Jede Anfrage ist eine JSON-RPC-Nachricht, und die Antwort ist ein JSON-Objekt mit `content-type: application/json`. Der Server hält keine Session und sendet keinen Stream, daher liefert `GET /$mcp/` `404`. Eine Anfrage darf bis zu 10 MB groß sein und bis zu 300 Sekunden dauern. Wähle in den Einstellungen eines KI-Clients den HTTP-Transport und gib die URL des Endpunkts ein.\n\n| Methode | Antwort |\n| --- | --- |\n| `initialize` | Die Protokollversion, `capabilities: { tools: {} }` und `serverInfo` mit `CONF.name` und `CONF.version` |\n| `ping` | Ein leeres Ergebnis |\n| `tools/list` | Die Liste der Tools |\n| `tools/call` | Führt ein Tool (eine Aktion) aus und gibt seine Antwort zurück |\n| `server/discover` | Die unterstützte Version `2026-07-28`, die Capabilities und die Serverinformationen |\n| eine Notification (eine Nachricht ohne `id`) | Status `202` ohne Body |\n\nEine andere Methode erhält den Fehler `-32601` (`Method not found`). Eine Nachricht ohne `\"jsonrpc\": \"2.0\"` oder ohne Methode oder ein JSON-Array (ein Batch) erhält `-32600` (`Invalid Request`).\n\n```js\n// the answer to { \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"initialize\", \"params\": { \"protocolVersion\": \"2025-06-18\" } }\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n`initialize` antwortet mit der Version, die der Client anfragt, wenn sie in `Total.mcp.versions` steht (`2026-07-28`, `2025-11-25`, `2025-06-18`, `2025-03-26`), und sonst mit der ersten.\n\n## Aktionen als Tools\n\nJede Aktion mit `mcp: true` ist ein Tool. Die Liste wird 200 ms nach jedem `NEWACTION()` neu aufgebaut, daher sind auch die Aktionen von Plugins und von später geladenem Code darin enthalten.\n\n- **name**: der Name der Aktion, in dem jedes Zeichen außer Buchstaben, Ziffern, `_` und `-` durch `_` ersetzt wird, höchstens 64 Zeichen. `Tasks|create` wird zu `Tasks_create`.\n- **description**: die Option `summary` der Aktion oder ihre Option `name`.\n- **inputSchema**: ein Objekt mit bis zu drei Schlüsseln, `input`, `query` und `params`, erzeugt aus den Schemas der Aktion. Ein Schlüssel ist erforderlich, wenn sein Schema ein erforderliches Feld hat.\n- **outputSchema**: erzeugt aus dem Schema `output`, wenn die Aktion eines hat.\n\nDie Felder werden in Standard-JSON-Schema umgewandelt. Die `//`-Meldung eines Feldes ist seine Beschreibung, also schreib Meldungen, die der KI sagen, was sie senden soll (eine Meldung endet am nächsten Komma, daher darf sie keines enthalten). `Date` ist ein String mit `format: 'date-time'`, `Email` hat `format: 'email'`, ein Enum behält seine Werte, und ein Typ, der `null` sein kann (`String2`, `UID`, `JSON` und andere), erhält den Typ `['string', 'null']`. Jedes Feld von `params` ist ein String.\n\n```js\n// tools/list, the tool Tasks_remove\n{\n\t\"name\": \"Tasks_remove\",\n\t\"description\": \"Removes a task\",\n\t\"inputSchema\": {\n\t\t\"type\": \"object\",\n\t\t\"properties\": {\n\t\t\t\"params\": {\n\t\t\t\t\"type\": \"object\",\n\t\t\t\t\"description\": \"URL params passed to this action.\",\n\t\t\t\t\"properties\": { \"id\": { \"type\": \"string\", \"description\": \"The ID of the task\" } },\n\t\t\t\t\"additionalProperties\": false,\n\t\t\t\t\"required\": [\"id\"]\n\t\t\t}\n\t\t},\n\t\t\"required\": [\"params\"]\n\t}\n}\n```\n\n`F.actions[name].toAITool()` gibt dieselbe Definition für eine einzelne Aktion zurück, und `Total.mcp.tools` enthält die ganze Liste.\n\n## Ein Tool aufrufen\n\nDer KI-Client sendet `tools/call` mit dem Namen des Tools und seinen Argumenten: `input` (der Payload; `data` wird ebenfalls akzeptiert), `query` und `params`.\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_create\", \"arguments\": { \"input\": { \"name\": \"Call Peter\", \"due\": \"2026-11-20\" } } } }\n```\n\nDas Framework führt die Aktion mit `ACTION()` aus, daher validieren die Schemas die Argumente wie bei jedem anderen Aufruf. Es gibt keinen Controller, und der Benutzer der Aktion ist der Benutzer, mit dem `Total.mcp.auth` die Anfrage angenommen hat (siehe unten). Mit der Standardfunktion ist das `{ id: 'ai', name: 'AI', sa: true }`: Die Prüfungen `user: true`, `sa` und `permissions` werden bestanden, und eine Aktion mit `user: false` schlägt mit `401` fehl. Die `id` aus dem Query String des Endpunkts (`/$mcp/?id=...`) steht in `$.config.id`.\n\nDie Antwort der Aktion wird als Text gesendet: ein String so, wie er ist, jeder andere Wert als JSON. Wenn die Antwort ein Objekt ist (kein Array), steht sie außerdem in `structuredContent`:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"id\\\":\\\"JafvB11cV61f\\\"}\" }], \"structuredContent\": { \"id\": \"JafvB11cV61f\" } } }\n```\n\nFehler der Validierung und von `$.invalid()` kommen als Ergebnis mit `isError: true` und dem JSON-Array der Fehler als Text zurück, sodass die KI sie lesen und es erneut versuchen kann:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 6, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"[{\\\"error\\\":\\\"404: Not Found\\\"}]\" }], \"isError\": true } }\n```\n\nEin unbekanntes Tool oder eine Aktion ohne `mcp: true` erhält den Fehler `-32602` (`Unknown tool: name`); Argumente, die kein Objekt sind, erhalten ebenfalls `-32602`. Melde Fehler mit `$.invalid()`. Eine in der Aktion geworfene Exception (auch in einer `async`-Aktion) wird ins Fehlerlog geschrieben, und der Client erhält ein Ergebnis mit `isError: true` und einer kurzen Meldung (`Tool execution failed` oder `500: Internal Server Error` bei einer `async`-Aktion), ohne die Details der Exception.\n\n## Autorisierung\n\nStandardmäßig ist jede Anfrage erlaubt. Jeder, der die URL erreicht, kann die Tools ausführen, und die Tools laufen als der Superadmin `{ id: 'ai', name: 'AI', sa: true }`, also schütze den Endpunkt mit `Total.mcp.auth`. Die Funktion erhält `$` mit dem Token aus dem Header `Authorization` (`$.token`, ohne `Bearer `), `$.headers`, `$.query` und `$.ip`. Rufe `$.success(user)` auf, um die Anfrage anzunehmen, oder `$.invalid()`, um sie abzulehnen.\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcptoken)\n\t\t$.success({ id: 'mcp' });\n\telse\n\t\t$.invalid();\n};\n```\n\nEine abgelehnte Anfrage erhält den Status `401` und den JSON-RPC-Fehler `-32001` (`Unauthorized`). Die Tools laufen als der an `$.success(user)` übergebene Benutzer, daher gelten die Prüfungen `user`, `sa` und `permissions` der Aktionen für diesen Benutzer. `$.success()` ohne Benutzer ergibt einen leeren Benutzer `{}`.\n\n`Total.mcp.filter` entscheidet, welche Tools jeder Aufrufer verwenden darf. Die Funktion erhält die Definition eines Tools und `$` mit dem Aufrufer in `$.user` und gibt `true` zurück, um das Tool zu erlauben. Ein nicht erlaubtes Tool steht nicht in `tools/list`, und ein Aufruf davon ergibt `-32602` (`Unknown tool`):\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader' });\n\telse\n\t\t$.invalid();\n};\n\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n## Code Mode\n\nJeder Tool-Aufruf geht über das Modell: Die Definitionen aller Tools werden mit jeder Anfrage gesendet, und jedes Ergebnis kommt in die Unterhaltung zurück. Bei vielen Tools oder großen Ergebnissen kostet das viele Tokens. Im Code Mode schreibt der Agent ein kleines Skript, das die Tools aufruft, führt es auf seiner Seite aus (eine Shell, eine Sandbox), und nur die Ausgabe des Skripts erreicht das Modell.\n\n`GET /$mcp/client.js` gibt die Tools des Aufrufers als JavaScript-Modul zurück: eine Funktion pro Tool, mit JSDoc, das die Argumente und das Ergebnis beschreibt, erzeugt aus denselben Schemas wie `tools/list`. Der Endpunkt ist aktiv, sobald `$mcp` aktiv ist, und läuft durch dieselben `Total.mcp.auth` und `Total.mcp.filter`, sodass die Datei genau die Tools enthält, die das Token verwenden darf:\n\n```\ncurl -H 'Authorization: Bearer TOKEN' https://app.example.com/$mcp/client.js > client.js\n```\n\n```js\n// /**\n//  * Creates a task and returns its ID\n//  * @param {Object} args\n//  * @param {Object} args.input Payload (request body) passed to this action.\n//  * @param {String} args.input.name The name of the task\n//  * @param {String} [args.input.due] When the task must be done (ISO date)\n//  * @returns {Promise<{ id: ?String }>}\n//  */\n// api.Tasks_create = args => call(\"Tasks_create\", args);\n\nconst api = require('./client.js')('TOKEN');\n\nfor (const name of ['Call Peter', 'Send the offer'])\n\tawait api.Tasks_create({ input: { name } });\n\nconsole.log('2 tasks created');\n```\n\n`require('./client.js')(token, [url])` gibt die Funktionen zurück. Jede sendet `tools/call` mit dem Token an `POST /$mcp/`, wird mit der Ausgabe des Tools aufgelöst und wirft einen `Error` mit der Meldung eines Tool-Fehlers. Der Client braucht Node.js 18 oder neuer und keine Pakete. Mit `?q=words` enthält die Datei nur die Tools, deren Name oder Beschreibung alle Wörter enthalten, sodass ein Agent nur liest, was er braucht: `/$mcp/client.js?q=task`.\n\nAuf dem Server läuft nichts: Das Skript läuft dort, wo der Agent läuft, und jeder Aufruf ist ein normaler Tool-Aufruf mit den Berechtigungen des Tokens.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwWSJGx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Servidor MCP","summary":"Expón acciones como herramientas para clientes de IA con el endpoint MCP integrado POST /$mcp/ y protégelo con Total.mcp.auth; GET /$mcp/client.js da a los agentes las herramientas como código.","markdown":"---\ntitle: Servidor MCP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/mcp-server/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Servidor MCP\n\n> Expón acciones como herramientas para clientes de IA con el endpoint MCP integrado POST /$mcp/ y protégelo con Total.mcp.auth; GET /$mcp/client.js da a los agentes las herramientas como código.\n\nEl **Model Context Protocol** (MCP) permite que un cliente de IA, como un asistente, un agente o un editor, encuentre las herramientas de un servidor y las llame. Total.js 5 tiene un servidor MCP: convierte tus acciones en herramientas. Establece la clave de configuración `$mcp` y añade `mcp: true` a las acciones que la IA puede usar.\n\n```\n# config\nname     : Tasks\nversion  : 1.0\n$mcp     : true\n```\n\n```js\n// actions/tasks.js\nNEWACTION('Tasks|create', {\n\tsummary: 'Creates a task and returns its ID',\n\tmcp: true,\n\tinput: '*name:String // The name of the task, due:Date // When the task must be done',\n\toutput: 'id:UID',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('tasks').insert(model).callback(() => $.callback({ id: model.id }));\n\t}\n});\n\nNEWACTION('Tasks|remove', {\n\tsummary: 'Removes a task',\n\tmcp: true,\n\tparams: '*id:UID // The ID of the task',\n\taction: function($) {\n\t\tNOSQL('tasks').remove().id($.params.id).callback(function(err, count) {\n\t\t\tif (count)\n\t\t\t\t$.success();\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n```\n\nEl cliente de IA se conecta a `http://localhost:8000/$mcp/` y ve las herramientas `Tasks_create` y `Tasks_remove`.\n\n## El endpoint\n\nCon `$mcp : true` el framework crea la ruta `POST /$mcp/` cuando la aplicación está lista. Establece la clave en el archivo `config` (o en el código antes del arranque); sin ella la URL responde `404`.\n\nEl endpoint habla JSON-RPC 2.0 sobre HTTP. Cada petición es un mensaje JSON-RPC y la respuesta es un objeto JSON con `content-type: application/json`. El servidor no guarda sesión ni envía stream, así que `GET /$mcp/` da `404`. Una petición puede tener hasta 10 MB y puede durar hasta 300 segundos. En la configuración de un cliente de IA, elige el transporte HTTP e introduce la URL del endpoint.\n\n| Método | Respuesta |\n| --- | --- |\n| `initialize` | La versión del protocolo, `capabilities: { tools: {} }` y `serverInfo` con `CONF.name` y `CONF.version` |\n| `ping` | Un resultado vacío |\n| `tools/list` | La lista de las herramientas |\n| `tools/call` | Ejecuta una herramienta (una acción) y devuelve su respuesta |\n| `server/discover` | La versión admitida `2026-07-28`, las capacidades y la información del servidor |\n| una notificación (un mensaje sin `id`) | Estado `202` sin cuerpo |\n\nOtro método recibe el error `-32601` (`Method not found`). Un mensaje sin `\"jsonrpc\": \"2.0\"` o sin método, o un array JSON (un lote), recibe `-32600` (`Invalid Request`).\n\n```js\n// the answer to { \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"initialize\", \"params\": { \"protocolVersion\": \"2025-06-18\" } }\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n`initialize` responde con la versión que pide el cliente cuando está en `Total.mcp.versions` (`2026-07-28`, `2025-11-25`, `2025-06-18`, `2025-03-26`) y, si no, con la primera.\n\n## Acciones como herramientas\n\nCada acción con `mcp: true` es una herramienta. La lista se vuelve a construir 200 ms después de cada `NEWACTION()`, así que también incluye las acciones de los plugins y del código posterior.\n\n- **name**: el nombre de la acción con cada carácter que no sea una letra, un dígito, `_` o `-` sustituido por `_`, como máximo 64 caracteres. `Tasks|create` es `Tasks_create`.\n- **description**: la opción `summary` de la acción, o su opción `name`.\n- **inputSchema**: un objeto con hasta tres claves, `input`, `query` y `params`, creado a partir de los esquemas de la acción. Una clave es obligatoria cuando su esquema tiene un campo obligatorio.\n- **outputSchema**: creado a partir del esquema `output`, cuando la acción lo tiene.\n\nLos campos se convierten a JSON Schema estándar. El mensaje `//` de un campo es su descripción, así que escribe mensajes que le digan a la IA qué enviar (un mensaje termina en la siguiente coma, así que no puede contener ninguna). `Date` es un string con `format: 'date-time'`, `Email` tiene `format: 'email'`, un enum conserva sus valores, y un tipo que puede ser `null` (`String2`, `UID`, `JSON` y otros) recibe el tipo `['string', 'null']`. Todos los campos de `params` son strings.\n\n```js\n// tools/list, the tool Tasks_remove\n{\n\t\"name\": \"Tasks_remove\",\n\t\"description\": \"Removes a task\",\n\t\"inputSchema\": {\n\t\t\"type\": \"object\",\n\t\t\"properties\": {\n\t\t\t\"params\": {\n\t\t\t\t\"type\": \"object\",\n\t\t\t\t\"description\": \"URL params passed to this action.\",\n\t\t\t\t\"properties\": { \"id\": { \"type\": \"string\", \"description\": \"The ID of the task\" } },\n\t\t\t\t\"additionalProperties\": false,\n\t\t\t\t\"required\": [\"id\"]\n\t\t\t}\n\t\t},\n\t\t\"required\": [\"params\"]\n\t}\n}\n```\n\n`F.actions[name].toAITool()` devuelve la misma definición para una acción, y `Total.mcp.tools` contiene la lista completa.\n\n## Llamar a una herramienta\n\nEl cliente de IA envía `tools/call` con el nombre de la herramienta y sus argumentos: `input` (la carga útil; también se acepta `data`), `query` y `params`.\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_create\", \"arguments\": { \"input\": { \"name\": \"Call Peter\", \"due\": \"2026-11-20\" } } } }\n```\n\nEl framework ejecuta la acción con `ACTION()`, así que los esquemas validan los argumentos como en cualquier otra llamada. No hay controlador, y el usuario de la acción es el usuario con el que `Total.mcp.auth` aceptó la petición (consulta más abajo). Con la función por defecto es `{ id: 'ai', name: 'AI', sa: true }`: las comprobaciones `user: true`, `sa` y `permissions` pasan, y una acción con `user: false` falla con `401`. El `id` del query string del endpoint (`/$mcp/?id=...`) está en `$.config.id`.\n\nLa respuesta de la acción se envía como texto: un string tal cual, cualquier otro valor como JSON. Cuando la respuesta es un objeto (no un array), también está en `structuredContent`:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"id\\\":\\\"JafvB11cV61f\\\"}\" }], \"structuredContent\": { \"id\": \"JafvB11cV61f\" } } }\n```\n\nLos errores de validación y de `$.invalid()` vuelven como un resultado con `isError: true` y el array JSON de los errores como texto, así la IA puede leerlos y volver a intentarlo:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 6, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"[{\\\"error\\\":\\\"404: Not Found\\\"}]\" }], \"isError\": true } }\n```\n\nUna herramienta desconocida, o una acción sin `mcp: true`, recibe el error `-32602` (`Unknown tool: name`); los argumentos que no son un objeto también reciben `-32602`. Notifica los errores con `$.invalid()`. Una excepción lanzada en la acción (también en una `async`) se escribe en el log de errores, y el cliente recibe un resultado con `isError: true` y un mensaje corto (`Tool execution failed`, o `500: Internal Server Error` para una acción `async`), sin los detalles de la excepción.\n\n## Autorización\n\nPor defecto se permite cualquier petición. Cualquiera que pueda llegar a la URL puede ejecutar las herramientas, y las herramientas se ejecutan como el super admin `{ id: 'ai', name: 'AI', sa: true }`, así que protege el endpoint con `Total.mcp.auth`. La función recibe `$` con el token de la cabecera `Authorization` (`$.token`, sin `Bearer `), `$.headers`, `$.query` y `$.ip`. Llama a `$.success(user)` para aceptar la petición o a `$.invalid()` para rechazarla.\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcptoken)\n\t\t$.success({ id: 'mcp' });\n\telse\n\t\t$.invalid();\n};\n```\n\nUna petición rechazada recibe el estado `401` y el error JSON-RPC `-32001` (`Unauthorized`). Las herramientas se ejecutan como el usuario pasado a `$.success(user)`, así que las comprobaciones `user`, `sa` y `permissions` de las acciones se aplican a ese usuario. `$.success()` sin usuario da un usuario vacío `{}`.\n\n`Total.mcp.filter` decide qué herramientas puede usar cada llamante. Recibe la definición de una herramienta y `$` con el llamante en `$.user`, y devuelve `true` para permitir la herramienta. Una herramienta que no está permitida no aparece en `tools/list`, y llamarla da `-32602` (`Unknown tool`):\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader' });\n\telse\n\t\t$.invalid();\n};\n\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n## Modo código\n\nCada llamada a una herramienta pasa por el modelo: las definiciones de todas las herramientas se envían con cada petición, y cada resultado vuelve a la conversación. Con muchas herramientas o resultados grandes, eso cuesta muchos tokens. En el modo código el agente escribe un pequeño script que llama a las herramientas, lo ejecuta en su lado (una shell, un sandbox) y solo la salida del script llega al modelo.\n\n`GET /$mcp/client.js` devuelve las herramientas del llamante como un módulo JavaScript: una función por herramienta, con JSDoc que describe los argumentos y el resultado, escrito a partir de los mismos esquemas que `tools/list`. Está activo siempre que `$mcp` lo está y pasa por los mismos `Total.mcp.auth` y `Total.mcp.filter`, así que el archivo tiene exactamente las herramientas que el token puede usar:\n\n```\ncurl -H 'Authorization: Bearer TOKEN' https://app.example.com/$mcp/client.js > client.js\n```\n\n```js\n// /**\n//  * Creates a task and returns its ID\n//  * @param {Object} args\n//  * @param {Object} args.input Payload (request body) passed to this action.\n//  * @param {String} args.input.name The name of the task\n//  * @param {String} [args.input.due] When the task must be done (ISO date)\n//  * @returns {Promise<{ id: ?String }>}\n//  */\n// api.Tasks_create = args => call(\"Tasks_create\", args);\n\nconst api = require('./client.js')('TOKEN');\n\nfor (const name of ['Call Peter', 'Send the offer'])\n\tawait api.Tasks_create({ input: { name } });\n\nconsole.log('2 tasks created');\n```\n\n`require('./client.js')(token, [url])` devuelve las funciones. Cada una envía `tools/call` a `POST /$mcp/` con el token, se resuelve con la salida de la herramienta y lanza un `Error` con el mensaje de un error de la herramienta. El cliente necesita Node.js 18 o posterior y ningún paquete. Con `?q=words` el archivo solo tiene las herramientas cuyo nombre o descripción contienen todas las palabras, así un agente puede leer solo lo que necesita: `/$mcp/client.js?q=task`.\n\nEn el servidor no se ejecuta nada: el script se ejecuta donde se ejecuta el agente, y cada llamada es una llamada normal a una herramienta con los permisos del token.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwWSJGx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Serveur MCP","summary":"Expose des actions comme outils pour les clients d'IA avec l'endpoint MCP intégré POST /$mcp/ et protège-le avec Total.mcp.auth ; GET /$mcp/client.js donne aux agents les outils sous forme de code.","markdown":"---\ntitle: Serveur MCP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/mcp-server/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Serveur MCP\n\n> Expose des actions comme outils pour les clients d'IA avec l'endpoint MCP intégré POST /$mcp/ et protège-le avec Total.mcp.auth ; GET /$mcp/client.js donne aux agents les outils sous forme de code.\n\nLe **Model Context Protocol** (MCP) permet à un client d'IA, comme un assistant, un agent ou un éditeur, de trouver les outils d'un serveur et de les appeler. Total.js 5 a un serveur MCP : il transforme tes actions en outils. Définis la clé de configuration `$mcp` et ajoute `mcp: true` aux actions que l'IA peut utiliser.\n\n```\n# config\nname     : Tasks\nversion  : 1.0\n$mcp     : true\n```\n\n```js\n// actions/tasks.js\nNEWACTION('Tasks|create', {\n\tsummary: 'Creates a task and returns its ID',\n\tmcp: true,\n\tinput: '*name:String // The name of the task, due:Date // When the task must be done',\n\toutput: 'id:UID',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('tasks').insert(model).callback(() => $.callback({ id: model.id }));\n\t}\n});\n\nNEWACTION('Tasks|remove', {\n\tsummary: 'Removes a task',\n\tmcp: true,\n\tparams: '*id:UID // The ID of the task',\n\taction: function($) {\n\t\tNOSQL('tasks').remove().id($.params.id).callback(function(err, count) {\n\t\t\tif (count)\n\t\t\t\t$.success();\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n```\n\nLe client d'IA se connecte à `http://localhost:8000/$mcp/` et voit les outils `Tasks_create` et `Tasks_remove`.\n\n## L'endpoint\n\nAvec `$mcp : true`, le framework crée la route `POST /$mcp/` quand l'application est prête. Définis la clé dans le fichier `config` (ou dans le code avant le démarrage) ; sans elle, l'URL répond `404`.\n\nL'endpoint parle JSON-RPC 2.0 sur HTTP. Chaque requête est un message JSON-RPC et la réponse est un objet JSON avec `content-type: application/json`. Le serveur ne garde aucune session et n'envoie aucun stream, donc `GET /$mcp/` donne `404`. Une requête peut faire jusqu'à 10 Mo et durer jusqu'à 300 secondes. Dans les réglages d'un client d'IA, choisis le transport HTTP et saisis l'URL de l'endpoint.\n\n| Méthode | Réponse |\n| --- | --- |\n| `initialize` | La version du protocole, `capabilities: { tools: {} }` et `serverInfo` avec `CONF.name` et `CONF.version` |\n| `ping` | Un résultat vide |\n| `tools/list` | La liste des outils |\n| `tools/call` | Exécute un outil (une action) et renvoie sa réponse |\n| `server/discover` | La version prise en charge `2026-07-28`, les capacités et les informations du serveur |\n| une notification (un message sans `id`) | Statut `202` sans corps |\n\nUne autre méthode reçoit l'erreur `-32601` (`Method not found`). Un message sans `\"jsonrpc\": \"2.0\"` ou sans méthode, ou un tableau JSON (un batch), reçoit `-32600` (`Invalid Request`).\n\n```js\n// the answer to { \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"initialize\", \"params\": { \"protocolVersion\": \"2025-06-18\" } }\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n`initialize` répond avec la version que le client demande quand elle se trouve dans `Total.mcp.versions` (`2026-07-28`, `2025-11-25`, `2025-06-18`, `2025-03-26`), et avec la première sinon.\n\n## Les actions comme outils\n\nChaque action avec `mcp: true` est un outil. La liste est reconstruite 200 ms après chaque `NEWACTION()`, donc les actions des plugins et du code chargé plus tard y figurent aussi.\n\n- **name** : le nom de l'action où chaque caractère autre qu'une lettre, un chiffre, `_` et `-` est remplacé par `_`, 64 caractères au maximum. `Tasks|create` devient `Tasks_create`.\n- **description** : l'option `summary` de l'action, ou son option `name`.\n- **inputSchema** : un objet avec jusqu'à trois clés, `input`, `query` et `params`, créé à partir des schémas de l'action. Une clé est obligatoire quand son schéma a un champ obligatoire.\n- **outputSchema** : créé à partir du schéma `output`, quand l'action en a un.\n\nLes champs sont convertis en JSON Schema standard. Le message `//` d'un champ est sa description, donc écris des messages qui disent à l'IA quoi envoyer (un message se termine à la virgule suivante, il ne peut donc pas en contenir). `Date` est une chaîne avec `format: 'date-time'`, `Email` a `format: 'email'`, un enum garde ses valeurs, et un type qui peut valoir `null` (`String2`, `UID`, `JSON` et d'autres) reçoit le type `['string', 'null']`. Chaque champ de `params` est une chaîne.\n\n```js\n// tools/list, the tool Tasks_remove\n{\n\t\"name\": \"Tasks_remove\",\n\t\"description\": \"Removes a task\",\n\t\"inputSchema\": {\n\t\t\"type\": \"object\",\n\t\t\"properties\": {\n\t\t\t\"params\": {\n\t\t\t\t\"type\": \"object\",\n\t\t\t\t\"description\": \"URL params passed to this action.\",\n\t\t\t\t\"properties\": { \"id\": { \"type\": \"string\", \"description\": \"The ID of the task\" } },\n\t\t\t\t\"additionalProperties\": false,\n\t\t\t\t\"required\": [\"id\"]\n\t\t\t}\n\t\t},\n\t\t\"required\": [\"params\"]\n\t}\n}\n```\n\n`F.actions[name].toAITool()` renvoie la même définition pour une seule action, et `Total.mcp.tools` contient la liste complète.\n\n## Appeler un outil\n\nLe client d'IA envoie `tools/call` avec le nom de l'outil et ses arguments : `input` (les données envoyées ; `data` est aussi accepté), `query` et `params`.\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_create\", \"arguments\": { \"input\": { \"name\": \"Call Peter\", \"due\": \"2026-11-20\" } } } }\n```\n\nLe framework exécute l'action avec `ACTION()`, donc les schémas valident les arguments comme pour tout autre appel. Il n'y a pas de contrôleur, et l'utilisateur de l'action est celui avec lequel `Total.mcp.auth` a accepté la requête (voir plus bas). Avec la fonction par défaut, c'est `{ id: 'ai', name: 'AI', sa: true }` : les vérifications `user: true`, `sa` et `permissions` passent, et une action avec `user: false` échoue avec `401`. L'`id` de la query string de l'endpoint (`/$mcp/?id=...`) se trouve dans `$.config.id`.\n\nLa réponse de l'action est envoyée sous forme de texte : une chaîne telle quelle, toute autre valeur en JSON. Quand la réponse est un objet (pas un tableau), elle se trouve aussi dans `structuredContent` :\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"id\\\":\\\"JafvB11cV61f\\\"}\" }], \"structuredContent\": { \"id\": \"JafvB11cV61f\" } } }\n```\n\nLes erreurs de validation et de `$.invalid()` reviennent comme un résultat avec `isError: true` et le tableau JSON des erreurs sous forme de texte, pour que l'IA puisse les lire et réessayer :\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 6, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"[{\\\"error\\\":\\\"404: Not Found\\\"}]\" }], \"isError\": true } }\n```\n\nUn outil inconnu, ou une action sans `mcp: true`, reçoit l'erreur `-32602` (`Unknown tool: name`) ; des arguments qui ne sont pas un objet reçoivent aussi `-32602`. Signale les erreurs avec `$.invalid()`. Une exception levée dans l'action (aussi dans une action `async`) est écrite dans le log des erreurs, et le client reçoit un résultat avec `isError: true` et un court message (`Tool execution failed`, ou `500: Internal Server Error` pour une action `async`), sans les détails de l'exception.\n\n## Autorisation\n\nPar défaut, chaque requête est autorisée. Toute personne qui peut atteindre l'URL peut exécuter les outils, et les outils s'exécutent en tant que super admin `{ id: 'ai', name: 'AI', sa: true }`, alors protège l'endpoint avec `Total.mcp.auth`. La fonction reçoit `$` avec le token de l'en-tête `Authorization` (`$.token`, sans `Bearer `), `$.headers`, `$.query` et `$.ip`. Appelle `$.success(user)` pour accepter la requête ou `$.invalid()` pour la refuser.\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcptoken)\n\t\t$.success({ id: 'mcp' });\n\telse\n\t\t$.invalid();\n};\n```\n\nUne requête refusée reçoit le statut `401` et l'erreur JSON-RPC `-32001` (`Unauthorized`). Les outils s'exécutent avec l'utilisateur donné à `$.success(user)`, donc les vérifications `user`, `sa` et `permissions` des actions s'appliquent à cet utilisateur. `$.success()` sans utilisateur donne un utilisateur vide `{}`.\n\n`Total.mcp.filter` décide quels outils chaque appelant peut utiliser. La fonction reçoit la définition d'un outil et `$` avec l'appelant dans `$.user`, et renvoie `true` pour autoriser l'outil. Un outil non autorisé n'apparaît pas dans `tools/list`, et l'appeler donne `-32602` (`Unknown tool`) :\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader' });\n\telse\n\t\t$.invalid();\n};\n\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n## Mode code\n\nChaque appel d'outil passe par le modèle : les définitions de tous les outils sont envoyées avec chaque requête, et chaque résultat revient dans la conversation. Avec beaucoup d'outils ou de gros résultats, cela coûte beaucoup de tokens. En mode code, l'agent écrit un petit script qui appelle les outils, l'exécute de son côté (un shell, un sandbox), et seule la sortie du script atteint le modèle.\n\n`GET /$mcp/client.js` renvoie les outils de l'appelant sous forme de module JavaScript : une fonction par outil, avec une JSDoc qui décrit les arguments et le résultat, écrite à partir des mêmes schémas que `tools/list`. Il est actif dès que `$mcp` l'est et passe par les mêmes `Total.mcp.auth` et `Total.mcp.filter` : le fichier contient donc exactement les outils que le token peut utiliser :\n\n```\ncurl -H 'Authorization: Bearer TOKEN' https://app.example.com/$mcp/client.js > client.js\n```\n\n```js\n// /**\n//  * Creates a task and returns its ID\n//  * @param {Object} args\n//  * @param {Object} args.input Payload (request body) passed to this action.\n//  * @param {String} args.input.name The name of the task\n//  * @param {String} [args.input.due] When the task must be done (ISO date)\n//  * @returns {Promise<{ id: ?String }>}\n//  */\n// api.Tasks_create = args => call(\"Tasks_create\", args);\n\nconst api = require('./client.js')('TOKEN');\n\nfor (const name of ['Call Peter', 'Send the offer'])\n\tawait api.Tasks_create({ input: { name } });\n\nconsole.log('2 tasks created');\n```\n\n`require('./client.js')(token, [url])` renvoie les fonctions. Chacune envoie `tools/call` à `POST /$mcp/` avec le token, se résout avec la sortie de l'outil et lève une `Error` avec le message d'une erreur de l'outil. Le client a besoin de Node.js 18 ou plus récent, et d'aucun paquet. Avec `?q=words`, le fichier ne contient que les outils dont le nom ou la description contiennent tous les mots, pour qu'un agent puisse lire seulement ce dont il a besoin : `/$mcp/client.js?q=task`.\n\nRien ne s'exécute sur le serveur : le script s'exécute là où l'agent s'exécute, et chaque appel est un appel d'outil normal avec les permissions du token.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwWSJGx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Server MCP","summary":"Esponi le azioni come tool per i client AI con l'endpoint MCP integrato POST /$mcp/ e proteggilo con Total.mcp.auth; GET /$mcp/client.js fornisce agli agenti i tool come codice.","markdown":"---\ntitle: Server MCP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/mcp-server/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Server MCP\n\n> Esponi le azioni come tool per i client AI con l'endpoint MCP integrato POST /$mcp/ e proteggilo con Total.mcp.auth; GET /$mcp/client.js fornisce agli agenti i tool come codice.\n\nIl **Model Context Protocol** (MCP) permette a un client AI, come un assistente, un agente o un editor, di trovare i tool di un server e di chiamarli. Total.js 5 ha un server MCP: trasforma le tue azioni in tool. Imposta la chiave di configurazione `$mcp` e aggiungi `mcp: true` alle azioni che l'AI può usare.\n\n```\n# config\nname     : Tasks\nversion  : 1.0\n$mcp     : true\n```\n\n```js\n// actions/tasks.js\nNEWACTION('Tasks|create', {\n\tsummary: 'Creates a task and returns its ID',\n\tmcp: true,\n\tinput: '*name:String // The name of the task, due:Date // When the task must be done',\n\toutput: 'id:UID',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('tasks').insert(model).callback(() => $.callback({ id: model.id }));\n\t}\n});\n\nNEWACTION('Tasks|remove', {\n\tsummary: 'Removes a task',\n\tmcp: true,\n\tparams: '*id:UID // The ID of the task',\n\taction: function($) {\n\t\tNOSQL('tasks').remove().id($.params.id).callback(function(err, count) {\n\t\t\tif (count)\n\t\t\t\t$.success();\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n```\n\nIl client AI si connette a `http://localhost:8000/$mcp/` e vede i tool `Tasks_create` e `Tasks_remove`.\n\n## L'endpoint\n\nCon `$mcp : true` il framework crea la route `POST /$mcp/` quando l'applicazione è pronta. Imposta la chiave nel file `config` (o nel codice prima dell'avvio); senza di essa l'URL risponde `404`.\n\nL'endpoint parla JSON-RPC 2.0 su HTTP. Ogni richiesta è un messaggio JSON-RPC e la risposta è un oggetto JSON con `content-type: application/json`. Il server non mantiene sessioni e non invia stream, quindi `GET /$mcp/` dà `404`. Una richiesta può essere grande fino a 10 MB e durare fino a 300 secondi. Nelle impostazioni di un client AI, scegli il trasporto HTTP e inserisci l'URL dell'endpoint.\n\n| Metodo | Risposta |\n| --- | --- |\n| `initialize` | La versione del protocollo, `capabilities: { tools: {} }` e `serverInfo` con `CONF.name` e `CONF.version` |\n| `ping` | Un risultato vuoto |\n| `tools/list` | L'elenco dei tool |\n| `tools/call` | Esegue un tool (un'azione) e restituisce la sua risposta |\n| `server/discover` | La versione supportata `2026-07-28`, le capability e le informazioni del server |\n| una notifica (un messaggio senza `id`) | Stato `202` senza body |\n\nUn altro metodo riceve l'errore `-32601` (`Method not found`). Un messaggio senza `\"jsonrpc\": \"2.0\"` o senza metodo, oppure un array JSON (un batch), riceve `-32600` (`Invalid Request`).\n\n```js\n// the answer to { \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"initialize\", \"params\": { \"protocolVersion\": \"2025-06-18\" } }\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n`initialize` risponde con la versione che il client chiede quando è in `Total.mcp.versions` (`2026-07-28`, `2025-11-25`, `2025-06-18`, `2025-03-26`), e altrimenti con la prima.\n\n## Le azioni come tool\n\nOgni azione con `mcp: true` è un tool. L'elenco viene ricostruito 200 ms dopo ogni `NEWACTION()`, quindi contiene anche le azioni dei plugin e del codice caricato dopo.\n\n- **name**: il nome dell'azione con ogni carattere diverso da una lettera, una cifra, `_` e `-` sostituito da `_`, al massimo 64 caratteri. `Tasks|create` diventa `Tasks_create`.\n- **description**: l'opzione `summary` dell'azione, oppure la sua opzione `name`.\n- **inputSchema**: un oggetto con fino a tre chiavi, `input`, `query` e `params`, creato dagli schemi dell'azione. Una chiave è obbligatoria quando il suo schema ha un campo obbligatorio.\n- **outputSchema**: creato dallo schema `output`, quando l'azione ne ha uno.\n\nI campi vengono convertiti in JSON Schema standard. Il messaggio `//` di un campo è la sua descrizione, quindi scrivi messaggi che dicano all'AI cosa inviare (un messaggio finisce alla virgola successiva, quindi non può contenerne una). `Date` è una stringa con `format: 'date-time'`, `Email` ha `format: 'email'`, un enum mantiene i suoi valori e un tipo che può essere `null` (`String2`, `UID`, `JSON` e altri) riceve il tipo `['string', 'null']`. Ogni campo di `params` è una stringa.\n\n```js\n// tools/list, the tool Tasks_remove\n{\n\t\"name\": \"Tasks_remove\",\n\t\"description\": \"Removes a task\",\n\t\"inputSchema\": {\n\t\t\"type\": \"object\",\n\t\t\"properties\": {\n\t\t\t\"params\": {\n\t\t\t\t\"type\": \"object\",\n\t\t\t\t\"description\": \"URL params passed to this action.\",\n\t\t\t\t\"properties\": { \"id\": { \"type\": \"string\", \"description\": \"The ID of the task\" } },\n\t\t\t\t\"additionalProperties\": false,\n\t\t\t\t\"required\": [\"id\"]\n\t\t\t}\n\t\t},\n\t\t\"required\": [\"params\"]\n\t}\n}\n```\n\n`F.actions[name].toAITool()` restituisce la stessa definizione per una sola azione, e `Total.mcp.tools` contiene l'intero elenco.\n\n## Chiamare un tool\n\nIl client AI invia `tools/call` con il nome del tool e i suoi argomenti: `input` (il payload; è accettato anche `data`), `query` e `params`.\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_create\", \"arguments\": { \"input\": { \"name\": \"Call Peter\", \"due\": \"2026-11-20\" } } } }\n```\n\nIl framework esegue l'azione con `ACTION()`, quindi gli schemi validano gli argomenti come per qualsiasi altra chiamata. Non c'è nessun controller, e l'utente dell'azione è l'utente con cui `Total.mcp.auth` ha accettato la richiesta (vedi sotto). Con la funzione predefinita è `{ id: 'ai', name: 'AI', sa: true }`: i controlli `user: true`, `sa` e `permissions` passano, e un'azione con `user: false` fallisce con `401`. L'`id` dalla query string dell'endpoint (`/$mcp/?id=...`) è in `$.config.id`.\n\nLa risposta dell'azione viene inviata come testo: una stringa così com'è, qualsiasi altro valore come JSON. Quando la risposta è un oggetto (non un array), si trova anche in `structuredContent`:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"id\\\":\\\"JafvB11cV61f\\\"}\" }], \"structuredContent\": { \"id\": \"JafvB11cV61f\" } } }\n```\n\nGli errori di validazione e di `$.invalid()` tornano come risultato con `isError: true` e l'array JSON degli errori come testo, così l'AI può leggerli e riprovare:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 6, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"[{\\\"error\\\":\\\"404: Not Found\\\"}]\" }], \"isError\": true } }\n```\n\nUn tool sconosciuto, o un'azione senza `mcp: true`, riceve l'errore `-32602` (`Unknown tool: name`); anche gli argomenti che non sono un oggetto ricevono `-32602`. Segnala gli errori con `$.invalid()`. Un'eccezione lanciata nell'azione (anche in una `async`) viene scritta nel log degli errori, e il client riceve un risultato con `isError: true` e un breve messaggio (`Tool execution failed`, o `500: Internal Server Error` per un'azione `async`), senza i dettagli dell'eccezione.\n\n## Autorizzazione\n\nPer impostazione predefinita ogni richiesta è consentita. Chiunque raggiunga l'URL può eseguire i tool, e i tool vengono eseguiti come il super admin `{ id: 'ai', name: 'AI', sa: true }`, quindi proteggi l'endpoint con `Total.mcp.auth`. La funzione riceve `$` con il token dall'header `Authorization` (`$.token`, senza `Bearer `), `$.headers`, `$.query` e `$.ip`. Chiama `$.success(user)` per accettare la richiesta o `$.invalid()` per rifiutarla.\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcptoken)\n\t\t$.success({ id: 'mcp' });\n\telse\n\t\t$.invalid();\n};\n```\n\nUna richiesta rifiutata riceve lo stato `401` e l'errore JSON-RPC `-32001` (`Unauthorized`). I tool vengono eseguiti come l'utente passato a `$.success(user)`, quindi i controlli `user`, `sa` e `permissions` delle azioni valgono per quell'utente. `$.success()` senza utente dà un utente vuoto `{}`.\n\n`Total.mcp.filter` decide quali tool può usare ogni chiamante. Riceve la definizione di un tool e `$` con il chiamante in `$.user`, e restituisce `true` per consentire il tool. Un tool non consentito non compare in `tools/list`, e chiamarlo dà `-32602` (`Unknown tool`):\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader' });\n\telse\n\t\t$.invalid();\n};\n\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n## Modalità codice\n\nOgni chiamata di tool passa per il modello: le definizioni di tutti i tool vengono inviate con ogni richiesta, e ogni risultato torna nella conversazione. Con molti tool o risultati grandi questo costa molti token. In modalità codice l'agente scrive un piccolo script che chiama i tool, lo esegue dalla sua parte (una shell, una sandbox) e al modello arriva solo l'output dello script.\n\n`GET /$mcp/client.js` restituisce i tool del chiamante come modulo JavaScript: una funzione per tool, con un JSDoc che descrive gli argomenti e il risultato, scritto a partire dagli stessi schemi di `tools/list`. È attivo ogni volta che `$mcp` è attivo e passa per gli stessi `Total.mcp.auth` e `Total.mcp.filter`, quindi il file contiene esattamente i tool che il token può usare:\n\n```\ncurl -H 'Authorization: Bearer TOKEN' https://app.example.com/$mcp/client.js > client.js\n```\n\n```js\n// /**\n//  * Creates a task and returns its ID\n//  * @param {Object} args\n//  * @param {Object} args.input Payload (request body) passed to this action.\n//  * @param {String} args.input.name The name of the task\n//  * @param {String} [args.input.due] When the task must be done (ISO date)\n//  * @returns {Promise<{ id: ?String }>}\n//  */\n// api.Tasks_create = args => call(\"Tasks_create\", args);\n\nconst api = require('./client.js')('TOKEN');\n\nfor (const name of ['Call Peter', 'Send the offer'])\n\tawait api.Tasks_create({ input: { name } });\n\nconsole.log('2 tasks created');\n```\n\n`require('./client.js')(token, [url])` restituisce le funzioni. Ognuna invia `tools/call` a `POST /$mcp/` con il token, si risolve con l'output del tool e lancia un `Error` con il messaggio di un errore del tool. Il client richiede Node.js 18 o successivo e nessun pacchetto. Con `?q=words` il file contiene solo i tool il cui nome o la cui descrizione contengono tutte le parole, così un agente può leggere solo quello che gli serve: `/$mcp/client.js?q=task`.\n\nSul server non viene eseguito nulla: lo script gira dove gira l'agente, e ogni chiamata è una normale chiamata di tool con i permessi del token.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwWSJGx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"MCP server","summary":"Sprístupni akcie ako nástroje pre AI klientov cez vstavaný MCP endpoint POST /$mcp/ a chráň ho cez Total.mcp.auth; GET /$mcp/client.js dá agentom nástroje ako kód.","markdown":"---\ntitle: MCP server\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/mcp-server/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# MCP server\n\n> Sprístupni akcie ako nástroje pre AI klientov cez vstavaný MCP endpoint POST /$mcp/ a chráň ho cez Total.mcp.auth; GET /$mcp/client.js dá agentom nástroje ako kód.\n\n**Model Context Protocol** (MCP) umožňuje AI klientovi, napríklad asistentovi, agentovi alebo editoru, nájsť nástroje servera a volať ich. Total.js 5 má MCP server: z tvojich akcií urobí nástroje. Nastav konfiguračný kľúč `$mcp` a pridaj `mcp: true` k akciám, ktoré môže AI používať.\n\n```\n# config\nname     : Tasks\nversion  : 1.0\n$mcp     : true\n```\n\n```js\n// actions/tasks.js\nNEWACTION('Tasks|create', {\n\tsummary: 'Creates a task and returns its ID',\n\tmcp: true,\n\tinput: '*name:String // The name of the task, due:Date // When the task must be done',\n\toutput: 'id:UID',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('tasks').insert(model).callback(() => $.callback({ id: model.id }));\n\t}\n});\n\nNEWACTION('Tasks|remove', {\n\tsummary: 'Removes a task',\n\tmcp: true,\n\tparams: '*id:UID // The ID of the task',\n\taction: function($) {\n\t\tNOSQL('tasks').remove().id($.params.id).callback(function(err, count) {\n\t\t\tif (count)\n\t\t\t\t$.success();\n\t\t\telse\n\t\t\t\t$.invalid(404);\n\t\t});\n\t}\n});\n```\n\nAI klient sa pripojí na `http://localhost:8000/$mcp/` a uvidí nástroje `Tasks_create` a `Tasks_remove`.\n\n## Endpoint\n\nS `$mcp : true` framework vytvorí routu `POST /$mcp/`, keď je aplikácia pripravená. Kľúč nastav v súbore `config` (alebo v kóde pred štartom); bez neho URL odpovedá `404`.\n\nEndpoint komunikuje cez JSON-RPC 2.0 nad HTTP. Každá požiadavka je jedna JSON-RPC správa a odpoveď je jeden JSON objekt s `content-type: application/json`. Server nedrží žiadnu session a neposiela žiadny stream, takže `GET /$mcp/` vráti `404`. Požiadavka môže mať až 10 MB a môže trvať až 300 sekúnd. V nastaveniach AI klienta vyber HTTP transport a zadaj URL endpointu.\n\n| Metóda | Odpoveď |\n| --- | --- |\n| `initialize` | Verzia protokolu, `capabilities: { tools: {} }` a `serverInfo` s `CONF.name` a `CONF.version` |\n| `ping` | Prázdny výsledok |\n| `tools/list` | Zoznam nástrojov |\n| `tools/call` | Spustí nástroj (akciu) a vráti jeho odpoveď |\n| `server/discover` | Podporovaná verzia `2026-07-28`, schopnosti a informácie o serveri |\n| notifikácia (správa bez `id`) | Stav `202` bez tela |\n\nIná metóda dostane chybu `-32601` (`Method not found`). Správa bez `\"jsonrpc\": \"2.0\"` alebo bez metódy, alebo JSON pole (batch), dostane `-32600` (`Invalid Request`).\n\n```js\n// the answer to { \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"initialize\", \"params\": { \"protocolVersion\": \"2025-06-18\" } }\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n`initialize` odpovie verziou, ktorú klient žiada, keď je v `Total.mcp.versions` (`2026-07-28`, `2025-11-25`, `2025-06-18`, `2025-03-26`), a inak prvou z nich.\n\n## Akcie ako nástroje\n\nKaždá akcia s `mcp: true` je nástroj. Zoznam sa zostaví znova 200 ms po každom `NEWACTION()`, takže sú v ňom aj akcie pluginov a neskoršieho kódu.\n\n- **name**: názov akcie, v ktorom je každý znak okrem písmena, číslice, `_` a `-` nahradený znakom `_`, najviac 64 znakov. `Tasks|create` je `Tasks_create`.\n- **description**: možnosť `summary` akcie alebo jej možnosť `name`.\n- **inputSchema**: objekt s až tromi kľúčmi, `input`, `query` a `params`, vytvorený zo schém akcie. Kľúč je povinný, keď má jeho schéma povinné pole.\n- **outputSchema**: vytvorená zo schémy `output`, keď ju akcia má.\n\nPolia sa konvertujú na štandardnú JSON Schema. Správa `//` poľa je jeho popis, takže píš správy, ktoré AI povedia, čo má poslať (správa končí pri ďalšej čiarke, takže ju nemôže obsahovať). `Date` je reťazec s `format: 'date-time'`, `Email` má `format: 'email'`, enum si ponechá svoje hodnoty a typ, ktorý môže byť `null` (`String2`, `UID`, `JSON` a ďalšie), dostane typ `['string', 'null']`. Každé pole `params` je reťazec.\n\n```js\n// tools/list, the tool Tasks_remove\n{\n\t\"name\": \"Tasks_remove\",\n\t\"description\": \"Removes a task\",\n\t\"inputSchema\": {\n\t\t\"type\": \"object\",\n\t\t\"properties\": {\n\t\t\t\"params\": {\n\t\t\t\t\"type\": \"object\",\n\t\t\t\t\"description\": \"URL params passed to this action.\",\n\t\t\t\t\"properties\": { \"id\": { \"type\": \"string\", \"description\": \"The ID of the task\" } },\n\t\t\t\t\"additionalProperties\": false,\n\t\t\t\t\"required\": [\"id\"]\n\t\t\t}\n\t\t},\n\t\t\"required\": [\"params\"]\n\t}\n}\n```\n\n`F.actions[name].toAITool()` vráti rovnakú definíciu pre jednu akciu a `Total.mcp.tools` drží celý zoznam.\n\n## Volanie nástroja\n\nAI klient pošle `tools/call` s názvom nástroja a jeho argumentmi: `input` (payload; prijíma sa aj `data`), `query` a `params`.\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_create\", \"arguments\": { \"input\": { \"name\": \"Call Peter\", \"due\": \"2026-11-20\" } } } }\n```\n\nFramework spustí akciu cez `ACTION()`, takže schémy validujú argumenty ako pri každom inom volaní. Nie je tu žiadny controller a používateľ akcie je používateľ, s ktorým `Total.mcp.auth` požiadavku prijal (pozri nižšie). S predvolenou funkciou je to `{ id: 'ai', name: 'AI', sa: true }`: kontroly `user: true`, `sa` a `permissions` prejdú a akcia s `user: false` zlyhá s `401`. `id` z query stringu endpointu (`/$mcp/?id=...`) je v `$.config.id`.\n\nOdpoveď akcie sa pošle ako text: reťazec tak, ako je, akákoľvek iná hodnota ako JSON. Keď je odpoveď objekt (nie pole), je aj v `structuredContent`:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 3, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"id\\\":\\\"JafvB11cV61f\\\"}\" }], \"structuredContent\": { \"id\": \"JafvB11cV61f\" } } }\n```\n\nChyby validácie a `$.invalid()` sa vrátia ako výsledok s `isError: true` a JSON poľom chýb ako textom, takže ich AI môže prečítať a skúsiť to znova:\n\n```js\n{ \"jsonrpc\": \"2.0\", \"id\": 6, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"[{\\\"error\\\":\\\"404: Not Found\\\"}]\" }], \"isError\": true } }\n```\n\nNeznámy nástroj alebo akcia bez `mcp: true` dostane chybu `-32602` (`Unknown tool: name`); argumenty, ktoré nie sú objekt, dostanú tiež `-32602`. Chyby hlás cez `$.invalid()`. Výnimka vyhodená v akcii (aj v `async` akcii) sa zapíše do chybového logu a klient dostane výsledok s `isError: true` a krátkou správou (`Tool execution failed` alebo `500: Internal Server Error` pre `async` akciu), bez podrobností výnimky.\n\n## Autorizácia\n\nPredvolene je povolená každá požiadavka. Ktokoľvek, kto sa dostane na URL, môže spúšťať nástroje, a nástroje bežia ako super admin `{ id: 'ai', name: 'AI', sa: true }`, takže endpoint chráň cez `Total.mcp.auth`. Funkcia dostane `$` s tokenom z hlavičky `Authorization` (`$.token`, bez `Bearer `), `$.headers`, `$.query` a `$.ip`. Zavolaj `$.success(user)`, aby si požiadavku prijal, alebo `$.invalid()`, aby si ju odmietol.\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcptoken)\n\t\t$.success({ id: 'mcp' });\n\telse\n\t\t$.invalid();\n};\n```\n\nOdmietnutá požiadavka dostane stav `401` a JSON-RPC chybu `-32001` (`Unauthorized`). Nástroje bežia ako používateľ odovzdaný do `$.success(user)`, takže kontroly `user`, `sa` a `permissions` akcií platia pre tohto používateľa. `$.success()` bez používateľa dá prázdneho používateľa `{}`.\n\n`Total.mcp.filter` rozhoduje, ktoré nástroje smie každý volajúci používať. Dostane definíciu nástroja a `$` s volajúcim v `$.user` a vráti `true`, ak nástroj povolí. Nepovolený nástroj nie je v `tools/list` a jeho volanie dá `-32602` (`Unknown tool`):\n\n```js\n// definitions/mcp.js\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader' });\n\telse\n\t\t$.invalid();\n};\n\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n## Režim kódu\n\nKaždé volanie nástroja ide cez model: definície všetkých nástrojov sa posielajú s každou požiadavkou a každý výsledok sa vracia do konverzácie. Pri veľa nástrojoch alebo veľkých výsledkoch to stojí veľa tokenov. V režime kódu agent napíše malý skript, ktorý volá nástroje, spustí ho na svojej strane (shell, sandbox) a k modelu sa dostane iba výstup skriptu.\n\n`GET /$mcp/client.js` vráti nástroje volajúceho ako JavaScript modul: jednu funkciu na nástroj, s JSDoc, ktorý opisuje argumenty a výsledok, napísaným z tých istých schém ako `tools/list`. Je zapnutý vždy, keď je zapnutý `$mcp`, a prechádza tými istými `Total.mcp.auth` a `Total.mcp.filter`, takže súbor obsahuje presne tie nástroje, ktoré token smie používať:\n\n```\ncurl -H 'Authorization: Bearer TOKEN' https://app.example.com/$mcp/client.js > client.js\n```\n\n```js\n// /**\n//  * Creates a task and returns its ID\n//  * @param {Object} args\n//  * @param {Object} args.input Payload (request body) passed to this action.\n//  * @param {String} args.input.name The name of the task\n//  * @param {String} [args.input.due] When the task must be done (ISO date)\n//  * @returns {Promise<{ id: ?String }>}\n//  */\n// api.Tasks_create = args => call(\"Tasks_create\", args);\n\nconst api = require('./client.js')('TOKEN');\n\nfor (const name of ['Call Peter', 'Send the offer'])\n\tawait api.Tasks_create({ input: { name } });\n\nconsole.log('2 tasks created');\n```\n\n`require('./client.js')(token, [url])` vráti funkcie. Každá pošle `tools/call` na `POST /$mcp/` s tokenom, vyrieši sa s výstupom nástroja a pri chybe nástroja vyhodí `Error` so správou chyby. Klient potrebuje Node.js 18 alebo novší a žiadne balíčky. S `?q=words` súbor obsahuje iba nástroje, ktorých názov alebo popis obsahuje všetky slová, takže agent si môže prečítať iba to, čo potrebuje: `/$mcp/client.js?q=task`.\n\nNa serveri sa nič nespúšťa: skript beží tam, kde beží agent, a každé volanie je bežné volanie nástroja s oprávneniami tokenu.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwwDBdx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/utilities/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Utilities","summary":"The global helpers of Total.js 5: the U/Utils module, identifiers, copies, the in-memory cache, shared objects, PATH, MEMORIZE(), BACKUP() and RESTORE().","markdown":"---\ntitle: Utilities\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/utilities/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Utilities\n\n> The global helpers of Total.js 5: the U/Utils module, identifiers, copies, the in-memory cache, shared objects, PATH, MEMORIZE(), BACKUP() and RESTORE().\n\nTotal.js 5 puts a set of helpers in the global scope as soon as the framework loads. Most of them come from the `Utils` module (`utils.js`), which is also available as the global `U`. Others are shared objects (`MAIN`, `REPO`, `FUNC`, `TEMP`), the in-memory `CACHE`, the `PATH` functions for the application directories, and a few tools for persistent state and archives (`MEMORIZE()`, `BACKUP()`, `RESTORE()`).\n\n```js\nvar id = UID();                       // 'JacVuE1cn61f'\nvar copy = CLONE(model);              // deep copy\nvar url = QUERIFY('/api/products/', { page: 2, q: 'shoe' });\nvar file = PATH.databases('settings.json');\nCACHE.set('stats', data, '10 minutes');\n```\n\nThe full list is in the reference of [Utilities](../../reference/utilities/). The methods added to `String`, `Number`, `Date` and `Array` are on the page [Prototypes](../prototypes/).\n\n## Identifiers and hashes\n\n`UID()` returns a short unique string, made from the time, an internal counter and a random character. It sorts roughly by creation time and is the identifier that Total.js apps use for records. `GUID()` returns a UUID-like string; `GUID(10)` returns 10 random characters. `HASH()` hashes a string: without a type it returns an unsigned 32-bit number, with a type (`'md5'`, `'sha1'`, `'sha256'`, `'sha512'`, `'crc32'`) it returns that hash.\n\n```js\nvar model = {};\nmodel.id = UID();\nmodel.token = GUID(30);\nmodel.checksum = HASH(model.id + model.token, 'sha256');\n```\n\nFor random values, `U.random(max, min)` returns a number in the range, and `U.random_text(n)`, `U.random_string(n)` and `U.random_number(n)` return strings of `n` characters (letters and digits, letters only, digits only).\n\n## Copying and comparing objects\n\n`CLONE()` makes a deep copy: nested objects and arrays are copied, buffers in object properties are duplicated, dates and errors are kept as they are. `COPY()` copies the keys of one object into another; with `false` as the third argument it copies only the keys that the target already has, which is a simple way to update a record with only the fields you allow.\n\n```js\nvar user = { id: 'abc', name: 'Peter', email: 'peter@example.com', admin: true };\nvar form = { name: 'Lucia', email: 'lucia@example.com', admin: false };\n\nvar allowed = { name: '', email: '' };\nCOPY(form, allowed, false);    // { name: 'Lucia', email: 'lucia@example.com' }\nU.extend(user, allowed);       // user.admin stays true\n```\n\n`DIFFARR()` compares two arrays of objects by one property. It tells you what to insert, what to update and what to remove, which is what you need when a form sends the full list of items that belong to a record:\n\n```js\nvar db = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];\nvar form = [{ id: 2, name: 'B2' }, { id: 3, name: 'C' }];\n\nvar diff = DIFFARR('id', db, form);\n// diff.add === [{ id: 3, name: 'C' }]\n// diff.upd === [{ db: { id: 2, name: 'B' }, form: { id: 2, name: 'B2' } }]\n// diff.rem === [1]\n```\n\n`U.get(obj, 'a.b.c')` reads a nested value and returns `undefined` when a part of the path is missing. `U.set(obj, 'a.b.c', value)` writes it and creates the missing objects on the way, and arrays for an index (`U.set(obj, 'items[0].name', 'Pen')` gives `{ items: [{ name: 'Pen' }] }`). `U.sortcomparer('name,price_desc')` returns a compare function for `Array.prototype.sort()`.\n\n## Converting values\n\n`U.parseInt()`, `U.parseFloat()` and `U.parseBoolean()` accept any value (a string from a query string, a number, `null`) and return a number or a boolean, with a default for empty values:\n\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat('12,50');       // 12.5\nvar active = U.parseBoolean('on');       // true\n```\n\n`QUERIFY()` builds a query string from an object. It skips `null`, `undefined` and empty values, writes dates as ISO strings and joins arrays with commas. It also accepts a URL with an HTTP method in front, as `REQUEST()` and `AJAX()` use it:\n\n```js\nQUERIFY({ q: 'red shoes', tags: ['a', 'b'] });   // '?q=red%20shoes&tags=a%2Cb'\nQUERIFY('GET /api/products/', { page: 2 });      // 'GET /api/products/?page=2'\n```\n\n## Hostnames\n\nA host name from a user or from the configuration can be written in many ways that resolve to the same server: `127.1`, `0x7f.0.0.1` and `2130706433` are all `127.0.0.1`, and `münchen.de` is `xn--mnchen-3ya.de`. `U.validhost(host)` accepts only plain ASCII host names and IP addresses in their canonical form. `U.tohost(host)` converts a host name to that form, or returns an empty string when it is not valid:\n\n```js\nU.validhost('example.com');   // true\nU.validhost('127.1');         // false\nU.tohost('münchen.de');       // 'xn--mnchen-3ya.de'\nU.tohost('127.1');            // '127.0.0.1'\nU.tohost('a\\0b.com');         // ''\n```\n\nThe framework uses them for its own connections: `U.connect()` (and so `LDAP()`) and the SMTP server of the mail convert the host first and give an error for an invalid one, and `U.resolve()` checks the host before the DNS query.\n\n## Shared objects\n\n| Global | What it is for |\n| --- | --- |\n| `MAIN` | An empty object for the shared state of your application |\n| `REPO` | An empty object for shared data; also available in views |\n| `FUNC` | An empty object for your own shared functions |\n| `TEMP` | An object for short-lived data; the framework replaces it with an empty object every 5 minutes |\n| `MODS` | The loaded modules from `/modules/`, by their `id` |\n| `NOW` | A `Date` that the framework refreshes every 5 seconds |\n| `NOOP` | An empty function, for callbacks you do not need |\n| `EMPTYOBJECT`, `EMPTYARRAY` | A frozen `{}` and `[]`, for default values that must not change |\n\n`MAIN`, `REPO`, `FUNC` and `MODS` can be read in views too. Use `NOW` where the current second is precise enough (cache keys, expirations, logs); it saves a `new Date()` in hot code.\n\n```js\n// definitions/init.js\nFUNC.slug = function(name) {\n\treturn name.slug();\n};\n\nMAIN.settings = { title: 'My shop' };\n\n// anywhere else\nvar slug = FUNC.slug('Red shoes');\n```\n\n## In-memory cache\n\n`CACHE` keeps values in the memory of the process with an expiration. `set()` stores a value (5 minutes when you omit the expiration), `get()` returns it or a default, and `remove()` and `reset()` delete items. Expired items are removed every minute.\n\n```js\nasync function products($) {\n\tvar items = CACHE.get('products');\n\tif (!items) {\n\t\titems = await DATA.find('nosql/products').promise($);\n\t\tCACHE.set('products', items, '2 minutes');\n\t}\n\t$.callback(items);\n}\n```\n\nThe cache is not shared between threads or cluster instances, and it is empty after a restart. For a result that must survive a restart, see `FILECACHE()` on the page [Caching generated data in a file](#caching-generated-data-in-a-file).\n\n## Caching generated data in a file\n\n`FILECACHE(id, expire, callback, maker)` keeps the result of an expensive task in a file in `tmp/`, so it survives restarts. The `maker` runs only when the file is missing or older than `expire`.\n\n```js\nFILECACHE('sitemap', '1 hour', function(err, response) {\n\tconsole.log(response.length);\n}, function(next) {\n\tDATA.find('nosql/pages').fields('id,url').callback(function(err, response) {\n\t\tnext(err, response);\n\t});\n});\n```\n\n## Persistent state with MEMORIZE()\n\n`MEMORIZE(name)` reads `databases/memorize_{name}.json` and returns its content as an object. Change the object and call `save()`, or use `set(key, value)`: the file is written 10 seconds later (a custom delay is the second argument), so many changes in a row produce one write.\n\n```js\nvar stats = MEMORIZE('stats');\n\nif (!stats.visits)\n\tstats.visits = 0;\n\nfunction visit() {\n\tstats.visits++;\n\tstats.save();\n}\n```\n\n## Paths\n\n`PATH.root()`, `PATH.public()`, `PATH.private()`, `PATH.databases()`, `PATH.temp()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()` and the others return the absolute path of an application directory, joined with the relative path you pass. The directory is created the first time you ask for a path inside it.\n\n```js\nvar filename = PATH.databases('exports/' + UID() + '.csv');\nvar exists = await PATH.exists(filename);\n```\n\n`PATH.exists()`, `PATH.unlink()` and `PATH.rmdir()` cover the common file operations, and `U.ls()` lists a directory recursively. For the other operations, `Total.Fs` is the Node.js module `node:fs` and `Total.FsPromises` is `node:fs/promises`:\n\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\n```\n\n## Archives with BACKUP() and RESTORE()\n\n`BACKUP()` packs files and directories into one text file (each file compressed with gzip), and `RESTORE()` unpacks it into a target directory. Both accept a filter, to leave out paths or (in `RESTORE()`) to rename them.\n\n```js\nawait BACKUP(PATH.temp('site.backup'), PATH.public());\nawait RESTORE(PATH.temp('site.backup'), PATH.root('public-copy'));\n```\n\n## Large data\n\n`U.streamer()` returns a function for the `data` event of a stream and calls you back with each part between two delimiters (or up to a separator), so a large XML or CSV file is processed without loading it whole. `U.chunker()` stores a long list in temporary files, `max` items per file, and reads it back page by page. A new chunker with the same name picks up the pages left on disk with `chunker.load()`.\n\n```js\nvar Fs = require('fs');\nvar chunker = U.chunker('export', 500);\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\n\nstream.on('data', U.streamer('<product>', '</product>', function(value) {\n\tchunker.write(value.parseXML());\n}));\n\nstream.on('end', function() {\n\tchunker.end();\n\tchunker.each(function(items, next) {\n\t\t// 500 products at a time\n\t\tnext();\n\t});\n});\n```\n\nFor the streamed answers of AI chat APIs, `U.aistreamer()` turns the chunks into lines of text. It reads both the server-sent events of OpenAI completions and the JSON lines of Ollama:\n\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n## Promises\n\nMost helpers that take a callback return a promise when you omit it (`PATH.exists()`, `U.ls()`, `U.wait()`, `BACKUP()`, `RESTORE()`). For your own callback-style functions, `PROMISIFY(fn, a, b, c)` calls `fn` with up to three arguments and a callback, and returns a promise:\n\n```js\nvar Fs = require('fs');\n\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwwDBdx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/utilities/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Hilfsmittel","summary":"Die globalen Helfer von Total.js 5: das Modul U/Utils, Kennungen, Kopien, der In-Memory-Cache, gemeinsame Objekte, PATH, MEMORIZE(), BACKUP() und RESTORE().","markdown":"---\ntitle: Hilfsmittel\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/utilities/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Hilfsmittel\n\n> Die globalen Helfer von Total.js 5: das Modul U/Utils, Kennungen, Kopien, der In-Memory-Cache, gemeinsame Objekte, PATH, MEMORIZE(), BACKUP() und RESTORE().\n\nTotal.js 5 stellt eine Reihe von Helfern in den globalen Gültigkeitsbereich, sobald das Framework geladen ist. Die meisten stammen aus dem Modul `Utils` (`utils.js`), das auch als globales `U` verfügbar ist. Andere sind gemeinsame Objekte (`MAIN`, `REPO`, `FUNC`, `TEMP`), der In-Memory-`CACHE`, die `PATH`-Funktionen für die Verzeichnisse der Anwendung und einige Werkzeuge für persistenten Zustand und Archive (`MEMORIZE()`, `BACKUP()`, `RESTORE()`).\n\n```js\nvar id = UID();                       // 'JacVuE1cn61f'\nvar copy = CLONE(model);              // deep copy\nvar url = QUERIFY('/api/products/', { page: 2, q: 'shoe' });\nvar file = PATH.databases('settings.json');\nCACHE.set('stats', data, '10 minutes');\n```\n\nDie vollständige Liste steht in der Referenz [Hilfsfunktionen](../../reference/utilities/). Die zu `String`, `Number`, `Date` und `Array` hinzugefügten Methoden stehen auf der Seite [Prototypen](../prototypes/).\n\n## Bezeichner und Hashes\n\n`UID()` gibt einen kurzen eindeutigen String zurück, gebildet aus der Zeit, einem internen Zähler und einem zufälligen Zeichen. Er sortiert sich ungefähr nach Erstellungszeit und ist der Bezeichner, den Total.js-Anwendungen für Datensätze verwenden. `GUID()` gibt einen UUID-ähnlichen String zurück; `GUID(10)` gibt 10 zufällige Zeichen zurück. `HASH()` hasht einen String: Ohne Typ gibt es eine vorzeichenlose 32-Bit-Zahl zurück, mit einem Typ (`'md5'`, `'sha1'`, `'sha256'`, `'sha512'`, `'crc32'`) diesen Hash.\n\n```js\nvar model = {};\nmodel.id = UID();\nmodel.token = GUID(30);\nmodel.checksum = HASH(model.id + model.token, 'sha256');\n```\n\nFür Zufallswerte gibt `U.random(max, min)` eine Zahl im Bereich zurück, und `U.random_text(n)`, `U.random_string(n)` und `U.random_number(n)` geben Strings mit `n` Zeichen zurück (Buchstaben und Ziffern, nur Buchstaben, nur Ziffern).\n\n## Objekte kopieren und vergleichen\n\n`CLONE()` erstellt eine tiefe Kopie: Verschachtelte Objekte und Arrays werden kopiert, Buffer in Objekteigenschaften dupliziert, Datumswerte und Fehler bleiben, wie sie sind. `COPY()` kopiert die Schlüssel eines Objekts in ein anderes; mit `false` als drittem Argument kopiert es nur die Schlüssel, die das Ziel bereits hat, was eine einfache Möglichkeit ist, einen Datensatz nur mit den erlaubten Feldern zu aktualisieren.\n\n```js\nvar user = { id: 'abc', name: 'Peter', email: 'peter@example.com', admin: true };\nvar form = { name: 'Lucia', email: 'lucia@example.com', admin: false };\n\nvar allowed = { name: '', email: '' };\nCOPY(form, allowed, false);    // { name: 'Lucia', email: 'lucia@example.com' }\nU.extend(user, allowed);       // user.admin stays true\n```\n\n`DIFFARR()` vergleicht zwei Arrays von Objekten anhand einer Eigenschaft. Es sagt dir, was einzufügen, was zu aktualisieren und was zu entfernen ist, also genau das, was du brauchst, wenn ein Formular die vollständige Liste der Einträge sendet, die zu einem Datensatz gehören:\n\n```js\nvar db = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];\nvar form = [{ id: 2, name: 'B2' }, { id: 3, name: 'C' }];\n\nvar diff = DIFFARR('id', db, form);\n// diff.add === [{ id: 3, name: 'C' }]\n// diff.upd === [{ db: { id: 2, name: 'B' }, form: { id: 2, name: 'B2' } }]\n// diff.rem === [1]\n```\n\n`U.get(obj, 'a.b.c')` liest einen verschachtelten Wert und gibt `undefined` zurück, wenn ein Teil des Pfads fehlt. `U.set(obj, 'a.b.c', value)` schreibt ihn und erstellt unterwegs die fehlenden Objekte, und Arrays für einen Index (`U.set(obj, 'items[0].name', 'Pen')` ergibt `{ items: [{ name: 'Pen' }] }`). `U.sortcomparer('name,price_desc')` gibt eine Vergleichsfunktion für `Array.prototype.sort()` zurück.\n\n## Werte umwandeln\n\n`U.parseInt()`, `U.parseFloat()` und `U.parseBoolean()` akzeptieren jeden Wert (einen String aus einem Query String, eine Zahl, `null`) und geben eine Zahl oder einen Boolean zurück, mit einem Standardwert für leere Werte:\n\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat('12,50');       // 12.5\nvar active = U.parseBoolean('on');       // true\n```\n\n`QUERIFY()` baut einen Query String aus einem Objekt. Es überspringt `null`, `undefined` und leere Werte, schreibt Datumswerte als ISO-Strings und verbindet Arrays mit Kommas. Es akzeptiert auch eine URL mit vorangestellter HTTP-Methode, so wie `REQUEST()` und `AJAX()` es verwenden:\n\n```js\nQUERIFY({ q: 'red shoes', tags: ['a', 'b'] });   // '?q=red%20shoes&tags=a%2Cb'\nQUERIFY('GET /api/products/', { page: 2 });      // 'GET /api/products/?page=2'\n```\n\n## Hostnamen\n\nEin Hostname von einem Benutzer oder aus der Konfiguration lässt sich auf viele Arten schreiben, die zum selben Server auflösen: `127.1`, `0x7f.0.0.1` und `2130706433` sind alle `127.0.0.1`, und `münchen.de` ist `xn--mnchen-3ya.de`. `U.validhost(host)` akzeptiert nur reine ASCII-Hostnamen und IP-Adressen in ihrer kanonischen Form. `U.tohost(host)` wandelt einen Hostnamen in diese Form um oder gibt einen leeren String zurück, wenn er nicht gültig ist:\n\n```js\nU.validhost('example.com');   // true\nU.validhost('127.1');         // false\nU.tohost('münchen.de');       // 'xn--mnchen-3ya.de'\nU.tohost('127.1');            // '127.0.0.1'\nU.tohost('a\\0b.com');         // ''\n```\n\nDas Framework verwendet sie für seine eigenen Verbindungen: `U.connect()` (und damit `LDAP()`) und der SMTP-Server der Mail wandeln den Host zuerst um und liefern bei einem ungültigen einen Fehler, und `U.resolve()` prüft den Host vor der DNS-Abfrage.\n\n## Gemeinsame Objekte\n\n| Global | Wofür es gedacht ist |\n| --- | --- |\n| `MAIN` | Ein leeres Objekt für den gemeinsamen Zustand deiner Anwendung |\n| `REPO` | Ein leeres Objekt für gemeinsame Daten; auch in Views verfügbar |\n| `FUNC` | Ein leeres Objekt für deine eigenen gemeinsamen Funktionen |\n| `TEMP` | Ein Objekt für kurzlebige Daten; das Framework ersetzt es alle 5 Minuten durch ein leeres Objekt |\n| `MODS` | Die geladenen Module aus `/modules/`, nach ihrer `id` |\n| `NOW` | Ein `Date`, das das Framework alle 5 Sekunden aktualisiert |\n| `NOOP` | Eine leere Funktion für Callbacks, die du nicht brauchst |\n| `EMPTYOBJECT`, `EMPTYARRAY` | Ein eingefrorenes `{}` und `[]` für Standardwerte, die sich nicht ändern dürfen |\n\n`MAIN`, `REPO`, `FUNC` und `MODS` können auch in Views gelesen werden. Verwende `NOW`, wo die aktuelle Sekunde genau genug ist (Cache-Schlüssel, Ablaufzeiten, Logs); es spart ein `new Date()` in häufig ausgeführtem Code.\n\n```js\n// definitions/init.js\nFUNC.slug = function(name) {\n\treturn name.slug();\n};\n\nMAIN.settings = { title: 'My shop' };\n\n// anywhere else\nvar slug = FUNC.slug('Red shoes');\n```\n\n## In-Memory-Cache\n\n`CACHE` hält Werte im Speicher des Prozesses mit einer Ablaufzeit. `set()` speichert einen Wert (5 Minuten, wenn du die Ablaufzeit weglässt), `get()` gibt ihn oder einen Standardwert zurück, und `remove()` und `reset()` löschen Einträge. Abgelaufene Einträge werden jede Minute entfernt.\n\n```js\nasync function products($) {\n\tvar items = CACHE.get('products');\n\tif (!items) {\n\t\titems = await DATA.find('nosql/products').promise($);\n\t\tCACHE.set('products', items, '2 minutes');\n\t}\n\t$.callback(items);\n}\n```\n\nDer Cache wird nicht zwischen Threads oder Cluster-Instanzen geteilt und ist nach einem Neustart leer. Für ein Ergebnis, das einen Neustart überstehen muss, siehe `FILECACHE()` auf der Seite [Erzeugte Daten in einer Datei zwischenspeichern](#caching-generated-data-in-a-file).\n\n## Erzeugte Daten in einer Datei zwischenspeichern\n\n`FILECACHE(id, expire, callback, maker)` hält das Ergebnis einer aufwendigen Aufgabe in einer Datei in `tmp/`, sodass es Neustarts übersteht. Der `maker` läuft nur, wenn die Datei fehlt oder älter als `expire` ist.\n\n```js\nFILECACHE('sitemap', '1 hour', function(err, response) {\n\tconsole.log(response.length);\n}, function(next) {\n\tDATA.find('nosql/pages').fields('id,url').callback(function(err, response) {\n\t\tnext(err, response);\n\t});\n});\n```\n\n## Persistenter Zustand mit MEMORIZE()\n\n`MEMORIZE(name)` liest `databases/memorize_{name}.json` und gibt den Inhalt als Objekt zurück. Ändere das Objekt und rufe `save()` auf, oder verwende `set(key, value)`: Die Datei wird 10 Sekunden später geschrieben (eine eigene Verzögerung ist das zweite Argument), sodass viele Änderungen hintereinander zu einem Schreibvorgang führen.\n\n```js\nvar stats = MEMORIZE('stats');\n\nif (!stats.visits)\n\tstats.visits = 0;\n\nfunction visit() {\n\tstats.visits++;\n\tstats.save();\n}\n```\n\n## Pfade\n\n`PATH.root()`, `PATH.public()`, `PATH.private()`, `PATH.databases()`, `PATH.temp()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()` und die anderen geben den absoluten Pfad eines Verzeichnisses der Anwendung zurück, verbunden mit dem übergebenen relativen Pfad. Das Verzeichnis wird erstellt, wenn du zum ersten Mal einen Pfad darin abrufst.\n\n```js\nvar filename = PATH.databases('exports/' + UID() + '.csv');\nvar exists = await PATH.exists(filename);\n```\n\n`PATH.exists()`, `PATH.unlink()` und `PATH.rmdir()` decken die gängigen Dateioperationen ab, und `U.ls()` listet ein Verzeichnis rekursiv auf. Für die anderen Operationen ist `Total.Fs` das Node.js-Modul `node:fs` und `Total.FsPromises` ist `node:fs/promises`:\n\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\n```\n\n## Archive mit BACKUP() und RESTORE()\n\n`BACKUP()` packt Dateien und Verzeichnisse in eine Textdatei (jede Datei mit gzip komprimiert), und `RESTORE()` entpackt sie in ein Zielverzeichnis. Beide akzeptieren einen Filter, um Pfade auszulassen oder (in `RESTORE()`) umzubenennen.\n\n```js\nawait BACKUP(PATH.temp('site.backup'), PATH.public());\nawait RESTORE(PATH.temp('site.backup'), PATH.root('public-copy'));\n```\n\n## Große Datenmengen\n\n`U.streamer()` gibt eine Funktion für das Event `data` eines Streams zurück und ruft dich mit jedem Teil zwischen zwei Begrenzern (oder bis zu einem Trennzeichen) zurück, sodass eine große XML- oder CSV-Datei verarbeitet wird, ohne sie ganz zu laden. `U.chunker()` speichert eine lange Liste in temporären Dateien, `max` Einträge pro Datei, und liest sie Seite für Seite zurück. Ein neuer Chunker mit demselben Namen übernimmt mit `chunker.load()` die auf der Festplatte verbliebenen Seiten.\n\n```js\nvar Fs = require('fs');\nvar chunker = U.chunker('export', 500);\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\n\nstream.on('data', U.streamer('<product>', '</product>', function(value) {\n\tchunker.write(value.parseXML());\n}));\n\nstream.on('end', function() {\n\tchunker.end();\n\tchunker.each(function(items, next) {\n\t\t// 500 products at a time\n\t\tnext();\n\t});\n});\n```\n\nFür die gestreamten Antworten von KI-Chat-APIs wandelt `U.aistreamer()` die Chunks in Textzeilen um. Es liest sowohl die Server-Sent Events von OpenAI Completions als auch die JSON-Zeilen von Ollama:\n\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n## Promises\n\nDie meisten Helfer, die einen Callback nehmen, geben eine Promise zurück, wenn du ihn weglässt (`PATH.exists()`, `U.ls()`, `U.wait()`, `BACKUP()`, `RESTORE()`). Für deine eigenen Funktionen im Callback-Stil ruft `PROMISIFY(fn, a, b, c)` `fn` mit bis zu drei Argumenten und einem Callback auf und gibt eine Promise zurück:\n\n```js\nvar Fs = require('fs');\n\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwwDBdx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/utilities/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Utilidades","summary":"Los helpers globales de Total.js 5: el módulo U/Utils, identificadores, copias, la caché en memoria, objetos compartidos, PATH, MEMORIZE(), BACKUP() y RESTORE().","markdown":"---\ntitle: Utilidades\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/utilities/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Utilidades\n\n> Los helpers globales de Total.js 5: el módulo U/Utils, identificadores, copias, la caché en memoria, objetos compartidos, PATH, MEMORIZE(), BACKUP() y RESTORE().\n\nTotal.js 5 coloca un conjunto de helpers en el ámbito global en cuanto se carga el framework. La mayoría vienen del módulo `Utils` (`utils.js`), que también está disponible como el global `U`. Otros son objetos compartidos (`MAIN`, `REPO`, `FUNC`, `TEMP`), la `CACHE` en memoria, las funciones `PATH` para los directorios de la aplicación y algunas herramientas para estado persistente y archivos comprimidos (`MEMORIZE()`, `BACKUP()`, `RESTORE()`).\n\n```js\nvar id = UID();                       // 'JacVuE1cn61f'\nvar copy = CLONE(model);              // deep copy\nvar url = QUERIFY('/api/products/', { page: 2, q: 'shoe' });\nvar file = PATH.databases('settings.json');\nCACHE.set('stats', data, '10 minutes');\n```\n\nLa lista completa está en la referencia de [Utilidades](../../reference/utilities/). Los métodos añadidos a `String`, `Number`, `Date` y `Array` están en la página [Prototipos](../prototypes/).\n\n## Identificadores y hashes\n\n`UID()` devuelve un string corto y único, formado por la hora, un contador interno y un carácter aleatorio. Se ordena aproximadamente por fecha de creación y es el identificador que usan las aplicaciones Total.js para los registros. `GUID()` devuelve un string similar a un UUID; `GUID(10)` devuelve 10 caracteres aleatorios. `HASH()` calcula el hash de un string: sin tipo devuelve un número de 32 bits sin signo, con un tipo (`'md5'`, `'sha1'`, `'sha256'`, `'sha512'`, `'crc32'`) devuelve ese hash.\n\n```js\nvar model = {};\nmodel.id = UID();\nmodel.token = GUID(30);\nmodel.checksum = HASH(model.id + model.token, 'sha256');\n```\n\nPara valores aleatorios, `U.random(max, min)` devuelve un número en el rango, y `U.random_text(n)`, `U.random_string(n)` y `U.random_number(n)` devuelven strings de `n` caracteres (letras y dígitos, solo letras, solo dígitos).\n\n## Copiar y comparar objetos\n\n`CLONE()` hace una copia profunda: los objetos y arrays anidados se copian, los buffers en propiedades de objetos se duplican, y las fechas y errores se mantienen tal cual. `COPY()` copia las claves de un objeto en otro; con `false` como tercer argumento copia solo las claves que el destino ya tiene, una forma sencilla de actualizar un registro solo con los campos que permites.\n\n```js\nvar user = { id: 'abc', name: 'Peter', email: 'peter@example.com', admin: true };\nvar form = { name: 'Lucia', email: 'lucia@example.com', admin: false };\n\nvar allowed = { name: '', email: '' };\nCOPY(form, allowed, false);    // { name: 'Lucia', email: 'lucia@example.com' }\nU.extend(user, allowed);       // user.admin stays true\n```\n\n`DIFFARR()` compara dos arrays de objetos por una propiedad. Te dice qué insertar, qué actualizar y qué eliminar, que es lo que necesitas cuando un formulario envía la lista completa de elementos que pertenecen a un registro:\n\n```js\nvar db = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];\nvar form = [{ id: 2, name: 'B2' }, { id: 3, name: 'C' }];\n\nvar diff = DIFFARR('id', db, form);\n// diff.add === [{ id: 3, name: 'C' }]\n// diff.upd === [{ db: { id: 2, name: 'B' }, form: { id: 2, name: 'B2' } }]\n// diff.rem === [1]\n```\n\n`U.get(obj, 'a.b.c')` lee un valor anidado y devuelve `undefined` cuando falta una parte de la ruta. `U.set(obj, 'a.b.c', value)` lo escribe y crea por el camino los objetos que faltan, y arrays para un índice (`U.set(obj, 'items[0].name', 'Pen')` da `{ items: [{ name: 'Pen' }] }`). `U.sortcomparer('name,price_desc')` devuelve una función de comparación para `Array.prototype.sort()`.\n\n## Convertir valores\n\n`U.parseInt()`, `U.parseFloat()` y `U.parseBoolean()` aceptan cualquier valor (un string de una query string, un número, `null`) y devuelven un número o un booleano, con un valor por defecto para los valores vacíos:\n\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat('12,50');       // 12.5\nvar active = U.parseBoolean('on');       // true\n```\n\n`QUERIFY()` construye una query string a partir de un objeto. Omite los valores `null`, `undefined` y vacíos, escribe las fechas como strings ISO y une los arrays con comas. También acepta una URL con un método HTTP delante, tal como la usan `REQUEST()` y `AJAX()`:\n\n```js\nQUERIFY({ q: 'red shoes', tags: ['a', 'b'] });   // '?q=red%20shoes&tags=a%2Cb'\nQUERIFY('GET /api/products/', { page: 2 });      // 'GET /api/products/?page=2'\n```\n\n## Nombres de host\n\nUn nombre de host de un usuario o de la configuración se puede escribir de muchas formas que llevan al mismo servidor: `127.1`, `0x7f.0.0.1` y `2130706433` son todos `127.0.0.1`, y `münchen.de` es `xn--mnchen-3ya.de`. `U.validhost(host)` acepta solo nombres de host en ASCII simple y direcciones IP en su forma canónica. `U.tohost(host)` convierte un nombre de host a esa forma, o devuelve un string vacío cuando no es válido:\n\n```js\nU.validhost('example.com');   // true\nU.validhost('127.1');         // false\nU.tohost('münchen.de');       // 'xn--mnchen-3ya.de'\nU.tohost('127.1');            // '127.0.0.1'\nU.tohost('a\\0b.com');         // ''\n```\n\nEl framework los usa para sus propias conexiones: `U.connect()` (y por tanto `LDAP()`) y el servidor SMTP del correo convierten primero el host y dan un error si no es válido, y `U.resolve()` comprueba el host antes de la consulta DNS.\n\n## Objetos compartidos\n\n| Global | Para qué sirve |\n| --- | --- |\n| `MAIN` | Un objeto vacío para el estado compartido de tu aplicación |\n| `REPO` | Un objeto vacío para datos compartidos; también disponible en las vistas |\n| `FUNC` | Un objeto vacío para tus propias funciones compartidas |\n| `TEMP` | Un objeto para datos de vida corta; el framework lo sustituye por un objeto vacío cada 5 minutos |\n| `MODS` | Los módulos cargados de `/modules/`, por su `id` |\n| `NOW` | Un `Date` que el framework actualiza cada 5 segundos |\n| `NOOP` | Una función vacía, para callbacks que no necesitas |\n| `EMPTYOBJECT`, `EMPTYARRAY` | Un `{}` y un `[]` congelados, para valores por defecto que no deben cambiar |\n\n`MAIN`, `REPO`, `FUNC` y `MODS` también se pueden leer en las vistas. Usa `NOW` donde el segundo actual es suficientemente preciso (claves de caché, caducidades, logs); ahorra un `new Date()` en código crítico.\n\n```js\n// definitions/init.js\nFUNC.slug = function(name) {\n\treturn name.slug();\n};\n\nMAIN.settings = { title: 'My shop' };\n\n// anywhere else\nvar slug = FUNC.slug('Red shoes');\n```\n\n## Caché en memoria\n\n`CACHE` guarda valores en la memoria del proceso con una caducidad. `set()` guarda un valor (5 minutos cuando omites la caducidad), `get()` lo devuelve o devuelve un valor por defecto, y `remove()` y `reset()` borran elementos. Los elementos caducados se eliminan cada minuto.\n\n```js\nasync function products($) {\n\tvar items = CACHE.get('products');\n\tif (!items) {\n\t\titems = await DATA.find('nosql/products').promise($);\n\t\tCACHE.set('products', items, '2 minutes');\n\t}\n\t$.callback(items);\n}\n```\n\nLa caché no se comparte entre hilos ni instancias del clúster, y queda vacía tras un reinicio. Para un resultado que debe sobrevivir a un reinicio, consulta `FILECACHE()` en la página [Guardar en caché datos generados en un archivo](#caching-generated-data-in-a-file).\n\n## Guardar en caché datos generados en un archivo\n\n`FILECACHE(id, expire, callback, maker)` guarda el resultado de una tarea costosa en un archivo de `tmp/`, para que sobreviva a los reinicios. El `maker` solo se ejecuta cuando el archivo no existe o es más antiguo que `expire`.\n\n```js\nFILECACHE('sitemap', '1 hour', function(err, response) {\n\tconsole.log(response.length);\n}, function(next) {\n\tDATA.find('nosql/pages').fields('id,url').callback(function(err, response) {\n\t\tnext(err, response);\n\t});\n});\n```\n\n## Estado persistente con MEMORIZE()\n\n`MEMORIZE(name)` lee `databases/memorize_{name}.json` y devuelve su contenido como un objeto. Cambia el objeto y llama a `save()`, o usa `set(key, value)`: el archivo se escribe 10 segundos después (un retardo personalizado es el segundo argumento), así que muchos cambios seguidos producen una sola escritura.\n\n```js\nvar stats = MEMORIZE('stats');\n\nif (!stats.visits)\n\tstats.visits = 0;\n\nfunction visit() {\n\tstats.visits++;\n\tstats.save();\n}\n```\n\n## Rutas de archivos\n\n`PATH.root()`, `PATH.public()`, `PATH.private()`, `PATH.databases()`, `PATH.temp()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()` y los demás devuelven la ruta absoluta de un directorio de la aplicación, unida a la ruta relativa que pasas. El directorio se crea la primera vez que pides una ruta dentro de él.\n\n```js\nvar filename = PATH.databases('exports/' + UID() + '.csv');\nvar exists = await PATH.exists(filename);\n```\n\n`PATH.exists()`, `PATH.unlink()` y `PATH.rmdir()` cubren las operaciones de archivos habituales, y `U.ls()` lista un directorio de forma recursiva. Para las demás operaciones, `Total.Fs` es el módulo de Node.js `node:fs` y `Total.FsPromises` es `node:fs/promises`:\n\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\n```\n\n## Archivos con BACKUP() y RESTORE()\n\n`BACKUP()` empaqueta archivos y directorios en un único archivo de texto (cada archivo comprimido con gzip), y `RESTORE()` lo desempaqueta en un directorio de destino. Ambos aceptan un filtro, para excluir rutas o (en `RESTORE()`) para renombrarlas.\n\n```js\nawait BACKUP(PATH.temp('site.backup'), PATH.public());\nawait RESTORE(PATH.temp('site.backup'), PATH.root('public-copy'));\n```\n\n## Datos grandes\n\n`U.streamer()` devuelve una función para el evento `data` de un stream y te llama con cada parte entre dos delimitadores (o hasta un separador), así un archivo XML o CSV grande se procesa sin cargarlo entero. `U.chunker()` guarda una lista larga en archivos temporales, `max` elementos por archivo, y la vuelve a leer página a página. Un nuevo chunker con el mismo nombre recupera las páginas que quedaron en disco con `chunker.load()`.\n\n```js\nvar Fs = require('fs');\nvar chunker = U.chunker('export', 500);\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\n\nstream.on('data', U.streamer('<product>', '</product>', function(value) {\n\tchunker.write(value.parseXML());\n}));\n\nstream.on('end', function() {\n\tchunker.end();\n\tchunker.each(function(items, next) {\n\t\t// 500 products at a time\n\t\tnext();\n\t});\n});\n```\n\nPara las respuestas en streaming de las APIs de chat de IA, `U.aistreamer()` convierte los fragmentos en líneas de texto. Lee tanto los server-sent events de las completions de OpenAI como las líneas JSON de Ollama:\n\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n## Promesas\n\nLa mayoría de los helpers que reciben un callback devuelven una promesa cuando lo omites (`PATH.exists()`, `U.ls()`, `U.wait()`, `BACKUP()`, `RESTORE()`). Para tus propias funciones de estilo callback, `PROMISIFY(fn, a, b, c)` llama a `fn` con hasta tres argumentos y un callback, y devuelve una promesa:\n\n```js\nvar Fs = require('fs');\n\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwwDBdx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/utilities/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Utilitaires","summary":"Les utilitaires globaux de Total.js 5 : le module U/Utils, les identifiants, les copies, le cache en mémoire, les objets partagés, PATH, MEMORIZE(), BACKUP() et RESTORE().","markdown":"---\ntitle: Utilitaires\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/utilities/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Utilitaires\n\n> Les utilitaires globaux de Total.js 5 : le module U/Utils, les identifiants, les copies, le cache en mémoire, les objets partagés, PATH, MEMORIZE(), BACKUP() et RESTORE().\n\nTotal.js 5 place un ensemble de helpers dans la portée globale dès le chargement du framework. La plupart proviennent du module `Utils` (`utils.js`), également disponible sous le nom global `U`. Les autres sont des objets partagés (`MAIN`, `REPO`, `FUNC`, `TEMP`), le `CACHE` en mémoire, les fonctions `PATH` pour les répertoires de l'application, et quelques outils pour l'état persistant et les archives (`MEMORIZE()`, `BACKUP()`, `RESTORE()`).\n\n```js\nvar id = UID();                       // 'JacVuE1cn61f'\nvar copy = CLONE(model);              // deep copy\nvar url = QUERIFY('/api/products/', { page: 2, q: 'shoe' });\nvar file = PATH.databases('settings.json');\nCACHE.set('stats', data, '10 minutes');\n```\n\nLa liste complète se trouve dans la référence [Utilitaires](../../reference/utilities/). Les méthodes ajoutées à `String`, `Number`, `Date` et `Array` sont sur la page [Prototypes](../prototypes/).\n\n## Identifiants et hashes\n\n`UID()` renvoie une courte chaîne unique, construite à partir de l'heure, d'un compteur interne et d'un caractère aléatoire. Elle se trie approximativement par date de création et c'est l'identifiant que les applications Total.js utilisent pour les enregistrements. `GUID()` renvoie une chaîne de type UUID ; `GUID(10)` renvoie 10 caractères aléatoires. `HASH()` calcule le hash d'une chaîne : sans type, elle renvoie un nombre non signé sur 32 bits ; avec un type (`'md5'`, `'sha1'`, `'sha256'`, `'sha512'`, `'crc32'`), elle renvoie ce hash.\n\n```js\nvar model = {};\nmodel.id = UID();\nmodel.token = GUID(30);\nmodel.checksum = HASH(model.id + model.token, 'sha256');\n```\n\nPour les valeurs aléatoires, `U.random(max, min)` renvoie un nombre dans l'intervalle, et `U.random_text(n)`, `U.random_string(n)` et `U.random_number(n)` renvoient des chaînes de `n` caractères (lettres et chiffres, lettres uniquement, chiffres uniquement).\n\n## Copier et comparer des objets\n\n`CLONE()` effectue une copie profonde : les objets et tableaux imbriqués sont copiés, les buffers des propriétés d'objet sont dupliqués, les dates et les erreurs sont conservées telles quelles. `COPY()` copie les clés d'un objet dans un autre ; avec `false` comme troisième argument, elle ne copie que les clés que la cible possède déjà, ce qui est un moyen simple de mettre à jour un enregistrement avec uniquement les champs que tu autorises.\n\n```js\nvar user = { id: 'abc', name: 'Peter', email: 'peter@example.com', admin: true };\nvar form = { name: 'Lucia', email: 'lucia@example.com', admin: false };\n\nvar allowed = { name: '', email: '' };\nCOPY(form, allowed, false);    // { name: 'Lucia', email: 'lucia@example.com' }\nU.extend(user, allowed);       // user.admin stays true\n```\n\n`DIFFARR()` compare deux tableaux d'objets selon une propriété. Elle t'indique ce qu'il faut insérer, mettre à jour et supprimer, ce dont tu as besoin lorsqu'un formulaire envoie la liste complète des éléments appartenant à un enregistrement :\n\n```js\nvar db = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];\nvar form = [{ id: 2, name: 'B2' }, { id: 3, name: 'C' }];\n\nvar diff = DIFFARR('id', db, form);\n// diff.add === [{ id: 3, name: 'C' }]\n// diff.upd === [{ db: { id: 2, name: 'B' }, form: { id: 2, name: 'B2' } }]\n// diff.rem === [1]\n```\n\n`U.get(obj, 'a.b.c')` lit une valeur imbriquée et renvoie `undefined` lorsqu'une partie du chemin manque. `U.set(obj, 'a.b.c', value)` l'écrit et crée au passage les objets manquants, ainsi que des tableaux pour un index (`U.set(obj, 'items[0].name', 'Pen')` donne `{ items: [{ name: 'Pen' }] }`). `U.sortcomparer('name,price_desc')` renvoie une fonction de comparaison pour `Array.prototype.sort()`.\n\n## Convertir des valeurs\n\n`U.parseInt()`, `U.parseFloat()` et `U.parseBoolean()` acceptent n'importe quelle valeur (une chaîne issue d'une query string, un nombre, `null`) et renvoient un nombre ou un booléen, avec une valeur par défaut pour les valeurs vides :\n\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat('12,50');       // 12.5\nvar active = U.parseBoolean('on');       // true\n```\n\n`QUERIFY()` construit une query string à partir d'un objet. Elle ignore `null`, `undefined` et les valeurs vides, écrit les dates sous forme de chaînes ISO et joint les tableaux avec des virgules. Elle accepte aussi une URL précédée d'une méthode HTTP, comme l'utilisent `REQUEST()` et `AJAX()` :\n\n```js\nQUERIFY({ q: 'red shoes', tags: ['a', 'b'] });   // '?q=red%20shoes&tags=a%2Cb'\nQUERIFY('GET /api/products/', { page: 2 });      // 'GET /api/products/?page=2'\n```\n\n## Noms d'hôte\n\nUn nom d'hôte venant d'un utilisateur ou de la configuration peut s'écrire de nombreuses façons qui mènent au même serveur : `127.1`, `0x7f.0.0.1` et `2130706433` sont tous `127.0.0.1`, et `münchen.de` est `xn--mnchen-3ya.de`. `U.validhost(host)` n'accepte que des noms d'hôte en ASCII simple et des adresses IP dans leur forme canonique. `U.tohost(host)` convertit un nom d'hôte dans cette forme, ou renvoie une chaîne vide quand il n'est pas valide :\n\n```js\nU.validhost('example.com');   // true\nU.validhost('127.1');         // false\nU.tohost('münchen.de');       // 'xn--mnchen-3ya.de'\nU.tohost('127.1');            // '127.0.0.1'\nU.tohost('a\\0b.com');         // ''\n```\n\nLe framework les utilise pour ses propres connexions : `U.connect()` (et donc `LDAP()`) et le serveur SMTP des e-mails convertissent d'abord l'hôte et donnent une erreur pour un hôte non valide, et `U.resolve()` vérifie l'hôte avant la requête DNS.\n\n## Objets partagés\n\n| Global | À quoi il sert |\n| --- | --- |\n| `MAIN` | Un objet vide pour l'état partagé de ton application |\n| `REPO` | Un objet vide pour les données partagées ; également disponible dans les vues |\n| `FUNC` | Un objet vide pour tes propres fonctions partagées |\n| `TEMP` | Un objet pour les données éphémères ; le framework le remplace par un objet vide toutes les 5 minutes |\n| `MODS` | Les modules chargés depuis `/modules/`, par leur `id` |\n| `NOW` | Une `Date` que le framework actualise toutes les 5 secondes |\n| `NOOP` | Une fonction vide, pour les callbacks dont tu n'as pas besoin |\n| `EMPTYOBJECT`, `EMPTYARRAY` | Un `{}` et un `[]` gelés, pour les valeurs par défaut qui ne doivent pas changer |\n\n`MAIN`, `REPO`, `FUNC` et `MODS` peuvent aussi être lus dans les vues. Utilise `NOW` lorsque la seconde courante est suffisamment précise (clés de cache, expirations, logs) ; cela évite un `new Date()` dans du code critique.\n\n```js\n// definitions/init.js\nFUNC.slug = function(name) {\n\treturn name.slug();\n};\n\nMAIN.settings = { title: 'My shop' };\n\n// anywhere else\nvar slug = FUNC.slug('Red shoes');\n```\n\n## Cache en mémoire\n\n`CACHE` conserve des valeurs dans la mémoire du processus avec une expiration. `set()` stocke une valeur (5 minutes si tu omets l'expiration), `get()` la renvoie ou renvoie une valeur par défaut, et `remove()` et `reset()` suppriment des éléments. Les éléments expirés sont supprimés chaque minute.\n\n```js\nasync function products($) {\n\tvar items = CACHE.get('products');\n\tif (!items) {\n\t\titems = await DATA.find('nosql/products').promise($);\n\t\tCACHE.set('products', items, '2 minutes');\n\t}\n\t$.callback(items);\n}\n```\n\nLe cache n'est pas partagé entre les threads ni entre les instances du cluster, et il est vide après un redémarrage. Pour un résultat qui doit survivre à un redémarrage, voir `FILECACHE()` sur la page [Mettre en cache des données générées dans un fichier](#caching-generated-data-in-a-file).\n\n## Mettre en cache des données générées dans un fichier\n\n`FILECACHE(id, expire, callback, maker)` conserve le résultat d'une tâche coûteuse dans un fichier de `tmp/`, de sorte qu'il survit aux redémarrages. Le `maker` ne s'exécute que lorsque le fichier est absent ou plus ancien que `expire`.\n\n```js\nFILECACHE('sitemap', '1 hour', function(err, response) {\n\tconsole.log(response.length);\n}, function(next) {\n\tDATA.find('nosql/pages').fields('id,url').callback(function(err, response) {\n\t\tnext(err, response);\n\t});\n});\n```\n\n## État persistant avec MEMORIZE()\n\n`MEMORIZE(name)` lit `databases/memorize_{name}.json` et renvoie son contenu sous forme d'objet. Modifie l'objet et appelle `save()`, ou utilise `set(key, value)` : le fichier est écrit 10 secondes plus tard (un délai personnalisé est le second argument), de sorte que de nombreuses modifications successives ne produisent qu'une seule écriture.\n\n```js\nvar stats = MEMORIZE('stats');\n\nif (!stats.visits)\n\tstats.visits = 0;\n\nfunction visit() {\n\tstats.visits++;\n\tstats.save();\n}\n```\n\n## Chemins\n\n`PATH.root()`, `PATH.public()`, `PATH.private()`, `PATH.databases()`, `PATH.temp()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()` et les autres renvoient le chemin absolu d'un répertoire de l'application, joint au chemin relatif que tu passes. Le répertoire est créé la première fois que tu demandes un chemin à l'intérieur.\n\n```js\nvar filename = PATH.databases('exports/' + UID() + '.csv');\nvar exists = await PATH.exists(filename);\n```\n\n`PATH.exists()`, `PATH.unlink()` et `PATH.rmdir()` couvrent les opérations courantes sur les fichiers, et `U.ls()` liste un répertoire de façon récursive. Pour les autres opérations, `Total.Fs` est le module Node.js `node:fs` et `Total.FsPromises` est `node:fs/promises` :\n\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\n```\n\n## Archives avec BACKUP() et RESTORE()\n\n`BACKUP()` regroupe des fichiers et des répertoires dans un seul fichier texte (chaque fichier compressé avec gzip), et `RESTORE()` le décompresse dans un répertoire cible. Les deux acceptent un filtre, pour exclure des chemins ou (dans `RESTORE()`) pour les renommer.\n\n```js\nawait BACKUP(PATH.temp('site.backup'), PATH.public());\nawait RESTORE(PATH.temp('site.backup'), PATH.root('public-copy'));\n```\n\n## Données volumineuses\n\n`U.streamer()` renvoie une fonction pour l'événement `data` d'un stream et te rappelle avec chaque partie située entre deux délimiteurs (ou jusqu'à un séparateur) : un gros fichier XML ou CSV est ainsi traité sans être chargé en entier. `U.chunker()` stocke une longue liste dans des fichiers temporaires, `max` éléments par fichier, et la relit page par page. Un nouveau chunker du même nom reprend les pages laissées sur le disque avec `chunker.load()`.\n\n```js\nvar Fs = require('fs');\nvar chunker = U.chunker('export', 500);\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\n\nstream.on('data', U.streamer('<product>', '</product>', function(value) {\n\tchunker.write(value.parseXML());\n}));\n\nstream.on('end', function() {\n\tchunker.end();\n\tchunker.each(function(items, next) {\n\t\t// 500 products at a time\n\t\tnext();\n\t});\n});\n```\n\nPour les réponses en stream des API de chat d'IA, `U.aistreamer()` transforme les morceaux en lignes de texte. Elle lit à la fois les server-sent events d'OpenAI completions et les lignes JSON d'Ollama :\n\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n## Promesses\n\nLa plupart des helpers qui acceptent un callback renvoient une promesse lorsque tu l'omets (`PATH.exists()`, `U.ls()`, `U.wait()`, `BACKUP()`, `RESTORE()`). Pour tes propres fonctions de style callback, `PROMISIFY(fn, a, b, c)` appelle `fn` avec jusqu'à trois arguments et un callback, et renvoie une promesse :\n\n```js\nvar Fs = require('fs');\n\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwwDBdx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/utilities/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Utilità","summary":"Gli helper globali di Total.js 5: il modulo U/Utils, identificatori, copie, la cache in memoria, oggetti condivisi, PATH, MEMORIZE(), BACKUP() e RESTORE().","markdown":"---\ntitle: \"Utilità\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/utilities/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Utilità\n\n> Gli helper globali di Total.js 5: il modulo U/Utils, identificatori, copie, la cache in memoria, oggetti condivisi, PATH, MEMORIZE(), BACKUP() e RESTORE().\n\nTotal.js 5 mette un insieme di helper nello scope globale appena il framework si carica. La maggior parte proviene dal modulo `Utils` (`utils.js`), disponibile anche come oggetto globale `U`. Altri sono oggetti condivisi (`MAIN`, `REPO`, `FUNC`, `TEMP`), la `CACHE` in memoria, le funzioni `PATH` per le directory dell'applicazione e alcuni strumenti per lo stato persistente e gli archivi (`MEMORIZE()`, `BACKUP()`, `RESTORE()`).\n\n```js\nvar id = UID();                       // 'JacVuE1cn61f'\nvar copy = CLONE(model);              // deep copy\nvar url = QUERIFY('/api/products/', { page: 2, q: 'shoe' });\nvar file = PATH.databases('settings.json');\nCACHE.set('stats', data, '10 minutes');\n```\n\nL'elenco completo è nel riferimento di [Utility](../../reference/utilities/). I metodi aggiunti a `String`, `Number`, `Date` e `Array` sono nella pagina [Prototipi](../prototypes/).\n\n## Identificatori e hash\n\n`UID()` restituisce una breve stringa univoca, ricavata dal tempo, da un contatore interno e da un carattere casuale. Si ordina approssimativamente per data di creazione ed è l'identificatore che le app Total.js usano per i record. `GUID()` restituisce una stringa simile a un UUID; `GUID(10)` restituisce 10 caratteri casuali. `HASH()` calcola l'hash di una stringa: senza tipo restituisce un numero a 32 bit senza segno, con un tipo (`'md5'`, `'sha1'`, `'sha256'`, `'sha512'`, `'crc32'`) restituisce quell'hash.\n\n```js\nvar model = {};\nmodel.id = UID();\nmodel.token = GUID(30);\nmodel.checksum = HASH(model.id + model.token, 'sha256');\n```\n\nPer i valori casuali, `U.random(max, min)` restituisce un numero nell'intervallo, e `U.random_text(n)`, `U.random_string(n)` e `U.random_number(n)` restituiscono stringhe di `n` caratteri (lettere e cifre, solo lettere, solo cifre).\n\n## Copiare e confrontare oggetti\n\n`CLONE()` crea una copia profonda: gli oggetti e gli array annidati vengono copiati, i buffer nelle proprietà degli oggetti vengono duplicati, date ed errori restano come sono. `COPY()` copia le chiavi di un oggetto in un altro; con `false` come terzo argomento copia solo le chiavi che la destinazione ha già, un modo semplice per aggiornare un record solo con i campi che consenti.\n\n```js\nvar user = { id: 'abc', name: 'Peter', email: 'peter@example.com', admin: true };\nvar form = { name: 'Lucia', email: 'lucia@example.com', admin: false };\n\nvar allowed = { name: '', email: '' };\nCOPY(form, allowed, false);    // { name: 'Lucia', email: 'lucia@example.com' }\nU.extend(user, allowed);       // user.admin stays true\n```\n\n`DIFFARR()` confronta due array di oggetti in base a una proprietà. Ti dice cosa inserire, cosa aggiornare e cosa rimuovere, che è ciò che ti serve quando un form invia l'elenco completo degli elementi che appartengono a un record:\n\n```js\nvar db = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];\nvar form = [{ id: 2, name: 'B2' }, { id: 3, name: 'C' }];\n\nvar diff = DIFFARR('id', db, form);\n// diff.add === [{ id: 3, name: 'C' }]\n// diff.upd === [{ db: { id: 2, name: 'B' }, form: { id: 2, name: 'B2' } }]\n// diff.rem === [1]\n```\n\n`U.get(obj, 'a.b.c')` legge un valore annidato e restituisce `undefined` quando manca una parte del percorso. `U.set(obj, 'a.b.c', value)` lo scrive e crea lungo il percorso gli oggetti mancanti, e gli array per un indice (`U.set(obj, 'items[0].name', 'Pen')` dà `{ items: [{ name: 'Pen' }] }`). `U.sortcomparer('name,price_desc')` restituisce una funzione di confronto per `Array.prototype.sort()`.\n\n## Convertire valori\n\n`U.parseInt()`, `U.parseFloat()` e `U.parseBoolean()` accettano qualsiasi valore (una stringa da una query string, un numero, `null`) e restituiscono un numero o un booleano, con un valore predefinito per i valori vuoti:\n\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat('12,50');       // 12.5\nvar active = U.parseBoolean('on');       // true\n```\n\n`QUERIFY()` costruisce una query string da un oggetto. Salta `null`, `undefined` e i valori vuoti, scrive le date come stringhe ISO e unisce gli array con virgole. Accetta anche un URL preceduto da un metodo HTTP, come lo usano `REQUEST()` e `AJAX()`:\n\n```js\nQUERIFY({ q: 'red shoes', tags: ['a', 'b'] });   // '?q=red%20shoes&tags=a%2Cb'\nQUERIFY('GET /api/products/', { page: 2 });      // 'GET /api/products/?page=2'\n```\n\n## Nomi host\n\nUn nome host che arriva da un utente o dalla configurazione può essere scritto in molti modi che portano allo stesso server: `127.1`, `0x7f.0.0.1` e `2130706433` sono tutti `127.0.0.1`, e `münchen.de` è `xn--mnchen-3ya.de`. `U.validhost(host)` accetta solo nomi host ASCII semplici e indirizzi IP nella loro forma canonica. `U.tohost(host)` converte un nome host in quella forma, oppure restituisce una stringa vuota quando non è valido:\n\n```js\nU.validhost('example.com');   // true\nU.validhost('127.1');         // false\nU.tohost('münchen.de');       // 'xn--mnchen-3ya.de'\nU.tohost('127.1');            // '127.0.0.1'\nU.tohost('a\\0b.com');         // ''\n```\n\nIl framework le usa per le proprie connessioni: `U.connect()` (e quindi `LDAP()`) e il server SMTP della posta convertono prima l'host e danno un errore per uno non valido, e `U.resolve()` controlla l'host prima della query DNS.\n\n## Oggetti condivisi\n\n| Globale | A cosa serve |\n| --- | --- |\n| `MAIN` | Un oggetto vuoto per lo stato condiviso della tua applicazione |\n| `REPO` | Un oggetto vuoto per i dati condivisi; disponibile anche nelle viste |\n| `FUNC` | Un oggetto vuoto per le tue funzioni condivise |\n| `TEMP` | Un oggetto per i dati di breve durata; il framework lo sostituisce con un oggetto vuoto ogni 5 minuti |\n| `MODS` | I moduli caricati da `/modules/`, per il loro `id` |\n| `NOW` | Una `Date` che il framework aggiorna ogni 5 secondi |\n| `NOOP` | Una funzione vuota, per le callback che non ti servono |\n| `EMPTYOBJECT`, `EMPTYARRAY` | Un `{}` e un `[]` congelati, per valori predefiniti che non devono cambiare |\n\n`MAIN`, `REPO`, `FUNC` e `MODS` si possono leggere anche nelle viste. Usa `NOW` dove la precisione al secondo corrente basta (chiavi di cache, scadenze, log); risparmia un `new Date()` nel codice eseguito spesso.\n\n```js\n// definitions/init.js\nFUNC.slug = function(name) {\n\treturn name.slug();\n};\n\nMAIN.settings = { title: 'My shop' };\n\n// anywhere else\nvar slug = FUNC.slug('Red shoes');\n```\n\n## Cache in memoria\n\n`CACHE` conserva valori nella memoria del processo con una scadenza. `set()` salva un valore (5 minuti se ometti la scadenza), `get()` lo restituisce o restituisce un valore predefinito, e `remove()` e `reset()` eliminano elementi. Gli elementi scaduti vengono rimossi ogni minuto.\n\n```js\nasync function products($) {\n\tvar items = CACHE.get('products');\n\tif (!items) {\n\t\titems = await DATA.find('nosql/products').promise($);\n\t\tCACHE.set('products', items, '2 minutes');\n\t}\n\t$.callback(items);\n}\n```\n\nLa cache non è condivisa tra thread o istanze del cluster, ed è vuota dopo un riavvio. Per un risultato che deve sopravvivere a un riavvio, vedi `FILECACHE()` nella pagina [Mettere in cache dati generati in un file](#caching-generated-data-in-a-file).\n\n## Mettere in cache dati generati in un file\n\n`FILECACHE(id, expire, callback, maker)` conserva il risultato di un'operazione costosa in un file in `tmp/`, così sopravvive ai riavvii. Il `maker` viene eseguito solo quando il file manca o è più vecchio di `expire`.\n\n```js\nFILECACHE('sitemap', '1 hour', function(err, response) {\n\tconsole.log(response.length);\n}, function(next) {\n\tDATA.find('nosql/pages').fields('id,url').callback(function(err, response) {\n\t\tnext(err, response);\n\t});\n});\n```\n\n## Stato persistente con MEMORIZE()\n\n`MEMORIZE(name)` legge `databases/memorize_{name}.json` e restituisce il suo contenuto come oggetto. Modifica l'oggetto e chiama `save()`, oppure usa `set(key, value)`: il file viene scritto 10 secondi dopo (un ritardo personalizzato è il secondo argomento), quindi molte modifiche di seguito producono una sola scrittura.\n\n```js\nvar stats = MEMORIZE('stats');\n\nif (!stats.visits)\n\tstats.visits = 0;\n\nfunction visit() {\n\tstats.visits++;\n\tstats.save();\n}\n```\n\n## Percorsi\n\n`PATH.root()`, `PATH.public()`, `PATH.private()`, `PATH.databases()`, `PATH.temp()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()` e gli altri restituiscono il percorso assoluto di una directory dell'applicazione, unito al percorso relativo che passi. La directory viene creata la prima volta che richiedi un percorso al suo interno.\n\n```js\nvar filename = PATH.databases('exports/' + UID() + '.csv');\nvar exists = await PATH.exists(filename);\n```\n\n`PATH.exists()`, `PATH.unlink()` e `PATH.rmdir()` coprono le operazioni comuni sui file, e `U.ls()` elenca una directory in modo ricorsivo. Per le altre operazioni, `Total.Fs` è il modulo Node.js `node:fs` e `Total.FsPromises` è `node:fs/promises`:\n\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\n```\n\n## Archivi con BACKUP() e RESTORE()\n\n`BACKUP()` impacchetta file e directory in un unico file di testo (ogni file compresso con gzip), e `RESTORE()` lo estrae in una directory di destinazione. Entrambi accettano un filtro, per escludere percorsi o (in `RESTORE()`) per rinominarli.\n\n```js\nawait BACKUP(PATH.temp('site.backup'), PATH.public());\nawait RESTORE(PATH.temp('site.backup'), PATH.root('public-copy'));\n```\n\n## Grandi quantità di dati\n\n`U.streamer()` restituisce una funzione per l'evento `data` di uno stream e ti richiama con ogni parte compresa tra due delimitatori (o fino a un separatore), così un grande file XML o CSV viene elaborato senza caricarlo per intero. `U.chunker()` salva un lungo elenco in file temporanei, `max` elementi per file, e lo rilegge pagina per pagina. Un nuovo chunker con lo stesso nome riprende le pagine lasciate sul disco con `chunker.load()`.\n\n```js\nvar Fs = require('fs');\nvar chunker = U.chunker('export', 500);\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\n\nstream.on('data', U.streamer('<product>', '</product>', function(value) {\n\tchunker.write(value.parseXML());\n}));\n\nstream.on('end', function() {\n\tchunker.end();\n\tchunker.each(function(items, next) {\n\t\t// 500 products at a time\n\t\tnext();\n\t});\n});\n```\n\nPer le risposte in streaming delle API di chat AI, `U.aistreamer()` trasforma i chunk in righe di testo. Legge sia i server-sent event delle completion di OpenAI sia le righe JSON di Ollama:\n\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n## Promise\n\nLa maggior parte degli helper che accettano una callback restituisce una promise quando la ometti (`PATH.exists()`, `U.ls()`, `U.wait()`, `BACKUP()`, `RESTORE()`). Per le tue funzioni in stile callback, `PROMISIFY(fn, a, b, c)` chiama `fn` con un massimo di tre argomenti e una callback, e restituisce una promise:\n\n```js\nvar Fs = require('fs');\n\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwwDBdx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/utilities/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Nástroje","summary":"Globálne pomocné nástroje Total.js 5: modul U/Utils, identifikátory, kópie, cache v pamäti, zdieľané objekty, PATH, MEMORIZE(), BACKUP() a RESTORE().","markdown":"---\ntitle: \"Nástroje\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/utilities/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Nástroje\n\n> Globálne pomocné nástroje Total.js 5: modul U/Utils, identifikátory, kópie, cache v pamäti, zdieľané objekty, PATH, MEMORIZE(), BACKUP() a RESTORE().\n\nTotal.js 5 vloží sadu pomocných funkcií do globálneho rozsahu hneď, ako sa framework načíta. Väčšina z nich pochádza z modulu `Utils` (`utils.js`), ktorý je dostupný aj ako globálne `U`. Ďalšie sú zdieľané objekty (`MAIN`, `REPO`, `FUNC`, `TEMP`), `CACHE` v pamäti, funkcie `PATH` pre adresáre aplikácie a niekoľko nástrojov pre trvalý stav a archívy (`MEMORIZE()`, `BACKUP()`, `RESTORE()`).\n\n```js\nvar id = UID();                       // 'JacVuE1cn61f'\nvar copy = CLONE(model);              // deep copy\nvar url = QUERIFY('/api/products/', { page: 2, q: 'shoe' });\nvar file = PATH.databases('settings.json');\nCACHE.set('stats', data, '10 minutes');\n```\n\nÚplný zoznam je v referencii [Utility](../../reference/utilities/). Metódy pridané do `String`, `Number`, `Date` a `Array` sú na stránke [Prototypy](../prototypes/).\n\n## Identifikátory a hashe\n\n`UID()` vráti krátky unikátny reťazec zložený z času, interného počítadla a náhodného znaku. Zoraďuje sa približne podľa času vytvorenia a je to identifikátor, ktorý Total.js aplikácie používajú pre záznamy. `GUID()` vráti reťazec podobný UUID; `GUID(10)` vráti 10 náhodných znakov. `HASH()` zahashuje reťazec: bez typu vráti 32-bitové číslo bez znamienka, s typom (`'md5'`, `'sha1'`, `'sha256'`, `'sha512'`, `'crc32'`) vráti daný hash.\n\n```js\nvar model = {};\nmodel.id = UID();\nmodel.token = GUID(30);\nmodel.checksum = HASH(model.id + model.token, 'sha256');\n```\n\nPre náhodné hodnoty `U.random(max, min)` vráti číslo v rozsahu a `U.random_text(n)`, `U.random_string(n)` a `U.random_number(n)` vrátia reťazce s `n` znakmi (písmená a číslice, iba písmená, iba číslice).\n\n## Kopírovanie a porovnávanie objektov\n\n`CLONE()` vytvorí hlbokú kópiu: vnorené objekty a polia sa skopírujú, buffery vo vlastnostiach objektov sa zduplikujú, dátumy a chyby zostanú tak, ako sú. `COPY()` skopíruje kľúče jedného objektu do iného; s `false` ako tretím argumentom skopíruje iba kľúče, ktoré cieľ už má, čo je jednoduchý spôsob, ako aktualizovať záznam iba poliami, ktoré povolíš.\n\n```js\nvar user = { id: 'abc', name: 'Peter', email: 'peter@example.com', admin: true };\nvar form = { name: 'Lucia', email: 'lucia@example.com', admin: false };\n\nvar allowed = { name: '', email: '' };\nCOPY(form, allowed, false);    // { name: 'Lucia', email: 'lucia@example.com' }\nU.extend(user, allowed);       // user.admin stays true\n```\n\n`DIFFARR()` porovná dve polia objektov podľa jednej vlastnosti. Povie ti, čo vložiť, čo aktualizovať a čo odstrániť, čo potrebuješ, keď formulár posiela úplný zoznam položiek, ktoré patria k záznamu:\n\n```js\nvar db = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];\nvar form = [{ id: 2, name: 'B2' }, { id: 3, name: 'C' }];\n\nvar diff = DIFFARR('id', db, form);\n// diff.add === [{ id: 3, name: 'C' }]\n// diff.upd === [{ db: { id: 2, name: 'B' }, form: { id: 2, name: 'B2' } }]\n// diff.rem === [1]\n```\n\n`U.get(obj, 'a.b.c')` prečíta vnorenú hodnotu a vráti `undefined`, keď časť cesty chýba. `U.set(obj, 'a.b.c', value)` ju zapíše a cestou vytvorí chýbajúce objekty a pre index aj polia (`U.set(obj, 'items[0].name', 'Pen')` dá `{ items: [{ name: 'Pen' }] }`). `U.sortcomparer('name,price_desc')` vráti porovnávaciu funkciu pre `Array.prototype.sort()`.\n\n## Konverzia hodnôt\n\n`U.parseInt()`, `U.parseFloat()` a `U.parseBoolean()` prijmú akúkoľvek hodnotu (reťazec z query stringu, číslo, `null`) a vrátia číslo alebo boolean, s predvolenou hodnotou pre prázdne hodnoty:\n\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat('12,50');       // 12.5\nvar active = U.parseBoolean('on');       // true\n```\n\n`QUERIFY()` zostaví query string z objektu. Preskočí `null`, `undefined` a prázdne hodnoty, dátumy zapíše ako ISO reťazce a polia spojí čiarkami. Prijme aj URL s HTTP metódou na začiatku, ako ju používajú `REQUEST()` a `AJAX()`:\n\n```js\nQUERIFY({ q: 'red shoes', tags: ['a', 'b'] });   // '?q=red%20shoes&tags=a%2Cb'\nQUERIFY('GET /api/products/', { page: 2 });      // 'GET /api/products/?page=2'\n```\n\n## Hostnames\n\nHostname od používateľa alebo z konfigurácie sa dá zapísať mnohými spôsobmi, ktoré vedú na ten istý server: `127.1`, `0x7f.0.0.1` a `2130706433` sú všetky `127.0.0.1` a `münchen.de` je `xn--mnchen-3ya.de`. `U.validhost(host)` prijíma iba čisté ASCII hostnames a IP adresy v ich kanonickom tvare. `U.tohost(host)` skonvertuje hostname na tento tvar, alebo vráti prázdny reťazec, keď nie je platný:\n\n```js\nU.validhost('example.com');   // true\nU.validhost('127.1');         // false\nU.tohost('münchen.de');       // 'xn--mnchen-3ya.de'\nU.tohost('127.1');            // '127.0.0.1'\nU.tohost('a\\0b.com');         // ''\n```\n\nFramework ich používa pre vlastné pripojenia: `U.connect()` (a teda `LDAP()`) a SMTP server pošty najprv skonvertujú hosta a pre neplatného vrátia chybu a `U.resolve()` skontroluje hosta pred DNS dopytom.\n\n## Zdieľané objekty\n\n| Globálny objekt | Na čo slúži |\n| --- | --- |\n| `MAIN` | Prázdny objekt pre zdieľaný stav tvojej aplikácie |\n| `REPO` | Prázdny objekt pre zdieľané dáta; dostupný aj v pohľadoch |\n| `FUNC` | Prázdny objekt pre tvoje vlastné zdieľané funkcie |\n| `TEMP` | Objekt pre krátkodobé dáta; framework ho každých 5 minút nahradí prázdnym objektom |\n| `MODS` | Načítané moduly z `/modules/` podľa ich `id` |\n| `NOW` | `Date`, ktorý framework obnovuje každých 5 sekúnd |\n| `NOOP` | Prázdna funkcia pre callbacky, ktoré nepotrebuješ |\n| `EMPTYOBJECT`, `EMPTYARRAY` | Zmrazené `{}` a `[]` pre predvolené hodnoty, ktoré sa nesmú meniť |\n\n`MAIN`, `REPO`, `FUNC` a `MODS` sa dajú čítať aj v pohľadoch. Používaj `NOW` tam, kde stačí presnosť na sekundu (kľúče cache, expirácie, logy); ušetrí `new Date()` v často volanom kóde.\n\n```js\n// definitions/init.js\nFUNC.slug = function(name) {\n\treturn name.slug();\n};\n\nMAIN.settings = { title: 'My shop' };\n\n// anywhere else\nvar slug = FUNC.slug('Red shoes');\n```\n\n## Cache v pamäti\n\n`CACHE` drží hodnoty v pamäti procesu s expiráciou. `set()` uloží hodnotu (5 minút, keď expiráciu vynecháš), `get()` ju vráti alebo vráti predvolenú hodnotu a `remove()` a `reset()` mažú položky. Expirované položky sa odstraňujú každú minútu.\n\n```js\nasync function products($) {\n\tvar items = CACHE.get('products');\n\tif (!items) {\n\t\titems = await DATA.find('nosql/products').promise($);\n\t\tCACHE.set('products', items, '2 minutes');\n\t}\n\t$.callback(items);\n}\n```\n\nCache sa nezdieľa medzi vláknami ani inštanciami klastra a po reštarte je prázdna. Pre výsledok, ktorý musí prežiť reštart, pozri `FILECACHE()` na stránke [Cachovanie generovaných dát v súbore](#caching-generated-data-in-a-file).\n\n## Cachovanie generovaných dát v súbore\n\n`FILECACHE(id, expire, callback, maker)` uchová výsledok náročnej úlohy v súbore v `tmp/`, takže prežije reštart. `maker` sa spustí len vtedy, keď súbor chýba alebo je starší ako `expire`.\n\n```js\nFILECACHE('sitemap', '1 hour', function(err, response) {\n\tconsole.log(response.length);\n}, function(next) {\n\tDATA.find('nosql/pages').fields('id,url').callback(function(err, response) {\n\t\tnext(err, response);\n\t});\n});\n```\n\n## Trvalý stav cez MEMORIZE()\n\n`MEMORIZE(name)` prečíta `databases/memorize_{name}.json` a vráti jeho obsah ako objekt. Zmeň objekt a zavolaj `save()` alebo použi `set(key, value)`: súbor sa zapíše o 10 sekúnd neskôr (vlastné oneskorenie je druhý argument), takže veľa zmien za sebou vytvorí jeden zápis.\n\n```js\nvar stats = MEMORIZE('stats');\n\nif (!stats.visits)\n\tstats.visits = 0;\n\nfunction visit() {\n\tstats.visits++;\n\tstats.save();\n}\n```\n\n## Cesty\n\n`PATH.root()`, `PATH.public()`, `PATH.private()`, `PATH.databases()`, `PATH.temp()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()` a ďalšie vrátia absolútnu cestu k adresáru aplikácie spojenú s relatívnou cestou, ktorú odovzdáš. Adresár sa vytvorí, keď si prvýkrát požiadaš o cestu v ňom.\n\n```js\nvar filename = PATH.databases('exports/' + UID() + '.csv');\nvar exists = await PATH.exists(filename);\n```\n\n`PATH.exists()`, `PATH.unlink()` a `PATH.rmdir()` pokrývajú bežné operácie so súbormi a `U.ls()` rekurzívne vypíše adresár. Pre ostatné operácie je `Total.Fs` modul Node.js `node:fs` a `Total.FsPromises` je `node:fs/promises`:\n\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\n```\n\n## Archívy cez BACKUP() a RESTORE()\n\n`BACKUP()` zabalí súbory a adresáre do jedného textového súboru (každý súbor komprimovaný cez gzip) a `RESTORE()` ho rozbalí do cieľového adresára. Oba prijímajú filter na vynechanie ciest alebo (v `RESTORE()`) na ich premenovanie.\n\n```js\nawait BACKUP(PATH.temp('site.backup'), PATH.public());\nawait RESTORE(PATH.temp('site.backup'), PATH.root('public-copy'));\n```\n\n## Veľké dáta\n\n`U.streamer()` vráti funkciu pre udalosť `data` streamu a zavolá ťa s každou časťou medzi dvoma oddeľovačmi (alebo až po separátor), takže veľký XML alebo CSV súbor sa spracuje bez načítania celého. `U.chunker()` uloží dlhý zoznam do dočasných súborov, `max` položiek na súbor, a číta ho späť stránku po stránke. Nový chunker s rovnakým názvom prevezme stránky ponechané na disku cez `chunker.load()`.\n\n```js\nvar Fs = require('fs');\nvar chunker = U.chunker('export', 500);\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\n\nstream.on('data', U.streamer('<product>', '</product>', function(value) {\n\tchunker.write(value.parseXML());\n}));\n\nstream.on('end', function() {\n\tchunker.end();\n\tchunker.each(function(items, next) {\n\t\t// 500 products at a time\n\t\tnext();\n\t});\n});\n```\n\nPre streamované odpovede AI chat API `U.aistreamer()` zmení kúsky na riadky textu. Číta server-sent events z OpenAI completions aj JSON riadky z Ollama:\n\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n## Promises\n\nVäčšina pomocných funkcií, ktoré prijímajú callback, vráti promise, keď ho vynecháš (`PATH.exists()`, `U.ls()`, `U.wait()`, `BACKUP()`, `RESTORE()`). Pre tvoje vlastné funkcie v štýle callbackov `PROMISIFY(fn, a, b, c)` zavolá `fn` s najviac tromi argumentmi a callbackom a vráti promise:\n\n```js\nvar Fs = require('fs');\n\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JacXYP3Gt61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/prototypes/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Prototypes","summary":"Methods that Total.js adds to String, Number, Date and Array: formatting, parsing, validation, hashing, dates and array helpers.","markdown":"---\ntitle: Prototypes\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/prototypes/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Prototypes\n\n> Methods that Total.js adds to String, Number, Date and Array: formatting, parsing, validation, hashing, dates and array helpers.\n\nTotal.js 5 adds a set of methods to the built-in prototypes of JavaScript: `String`, `Number`, `Date` and `Array`. They are available in every file of the application (controllers, actions, schemas, definitions, views) as soon as the framework is loaded; you do not import anything.\n\n```js\nvar title = 'Hello World!';\ntitle.slug();                     // hello-world\n'{0} items'.format(5);            // 5 items\n(1234.5).format(2);               // 1 234.50\nnew Date().add('1 day').format('yyyy-MM-dd');\nusers.findItem('id', 5);\n```\n\nThe full list with every argument is in the reference [Prototypes](../../reference/prototypes/). This guide shows the groups and the methods you use most.\n\n## Strings: templates and text\n\n`format()` fills numbered placeholders and `args()` fills named ones. `args()` can encode the values for HTML, JSON or URLs:\n\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n\nvar tpl = '<a href=\"/users/{id}/\">{name}</a>';\ntpl.args({ id: 10, name: '<Peter>' }, 'html');\n// <a href=\"/users/10/\">&lt;Peter&gt;</a>\n```\n\nFor text from users and for URLs:\n\n```js\n'Čaute, svet!'.slug();          // caute-svet\n'<b>Hi</b>'.encode();           // &lt;b&gt;Hi&lt;/b&gt;\n'&lt;b&gt;'.decode();           // <b>\n'<p>Hi</p>'.removeTags();       // Hi\n'A long description'.max(10);   // A long ...\n'hello world'.capitalize();     // Hello World\n'Čučoriedka'.toASCII();         // Cucoriedka\n```\n\n`toKeywords()` and `toSearch()` prepare text for a simple full-text search: they lowercase it, remove diacritics and symbols, and make the matching tolerant (`y` and `i` are the same).\n\n## Strings: parsing\n\nThe `parse*` methods do not throw for bad input: they return a default value, `undefined` or an invalid date instead. Only `parseConfig()` throws for a value that cannot be evaluated when you do not pass `onerr`. This makes them safe for query strings and request bodies.\n\n```js\n'10'.parseInt();                 // 10\n'abc'.parseInt(1);               // 1 (the default)\n'1,5'.parseFloat();              // 1.5\n'on'.parseBoolean();             // true\n'{\"a\":1}'.parseJSON();           // { a: 1 }, or undefined for bad JSON\n'2024-05-01 12:30'.parseDate();  // a Date in UTC\n'01/05/2024'.parseDate('dd/MM/yyyy');\n'5 minutes'.parseDateExpiration(); // now + 5 minutes\n```\n\nStructured text formats have their own parsers:\n\n```js\n'q=total&page=2'.parseEncoded();       // { q: 'total', page: '2' }\n'PORT=8000\\nNAME=\"App\"'.parseEnv();    // { PORT: '8000', NAME: 'App' }\n'count (number) : 10'.parseConfig();   // { count: 10 }\n'a,b\\n1,2'.parseCSV();                 // [{ a: 'a', b: 'b' }, { a: '1', b: '2' }]\nreq.headers['user-agent'].parseUA();   // Windows Chrome\n```\n\n`parseContext()` reads text made of blocks. Each block has header lines between two lines of at least 20 dashes and a body after them; the result is an array of objects with the header keys (lowercased) and `body`:\n\n```js\nvar text = PATH.root('prompts.txt');\nvar blocks = Total.Fs.readFileSync(text, 'utf8').parseContext();\n// [{ name: 'welcome', type: 'prompt', body: '...' }, ...]\n```\n\n`parseCSV()` names the columns by letters (`a`, `b`, `c`, ...), so a file with a header line returns the header as the first object. Read the header, then map the letters to your names:\n\n```js\nvar rows = text.parseCSV(';');\nvar header = rows.shift();\nvar users = rows.map(row => ({ name: row.a, email: row.b }));\n```\n\n## Strings: validation\n\nThe `is*` methods return a boolean. `isEmail()`, `isPhone()`, `isURL()`, `isXSS()` and `isSQLInjection()` use regular expressions stored in `DEF.validators`, so you can replace one of them at startup when your rules are different:\n\n```js\n'info@example.com'.isEmail();     // true\n'+421903123456'.isPhone();        // true\n'https://totaljs.com'.isURL();    // true\nUID().isUID();                    // true (the checksum is checked too)\n'123'.isNumber();                 // true\n'<script>'.isXSS();               // true\n\n// /definitions/validators.js\nDEF.validators.phone = /^\\+?[0-9\\s]{6,20}$/;\n```\n\n## Strings: hashing and encryption\n\n```js\n'text'.hash();               // a fast 32-bit number, for cache keys\n'text'.hash('sha256');       // the same as 'text'.sha256()\n'text'.md5();\n'password'.sha512(CONF.secret);\n\nvar link = '123'.sign('key');    // 123-nzo165\nlink.sign('key', true);          // 123, or null when the text was changed\n\nvar secret = 'user@example.com'.encrypt('key');\nsecret.decrypt('key');           // user@example.com\n\nvar token = '123'.encrypt_uid(); // a short token for public URLs\ntoken.decrypt_uid();             // 123\n```\n\n`encrypt()`, `decrypt()`, `encrypt_uid()` and `decrypt_uid()` use the `secret` configuration key when you do not pass a secret, so all instances of an application with the same configuration can read each other's values.\n\n## Numbers\n\n```js\n(1234567.891).format(2);              // 1 234 567.89\n(1234.5).format(2, ',', '.');         // 1,234.50\n(1.005).round(2);                     // 1.01\n(100).VAT(20);                        // 120\n(100).discount(15);                   // 85\n(5).padLeft(3);                       // 005\n(1536000).filesize();                 // 1.46 MB\n(3).pluralize('no files', '# file', '# files', '# files'); // 3 files\n(5).between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }); // medium\n```\n\n`format()` cuts extra decimals instead of rounding them: round first with `round()` when it matters, for example for prices. `currency()` formats an amount with a function you register in `DEF.currencies`.\n\n## Dates\n\nThe application runs in UTC unless the `$timezone` configuration key says otherwise, so dates are formatted in UTC by default.\n\n```js\nvar now = new Date();\nnow.add('1 day');                    // a new Date, now is not changed\nnow.add('-30 minutes');\nnow.format('yyyy-MM-dd HH:mm');      // 2024-05-01 12:30\nnow.format('dddd, d. MMMM yyyy');    // Wednesday, 1. May 2024\nnow.format();                        // ISO string in UTC\nnow.extend('08:00');                 // the same day at 08:00\nnow.diff(created, 'days');           // days between created and now\nnow.setTimeZone('America/New_York').format('HH:mm'); // the time in New York\n```\n\n## Arrays\n\nThe find methods accept a function, a property name with a value, or a single value:\n\n```js\nvar users = [{ id: 1, name: 'Peter', role: 'admin' }, { id: 2, name: 'Anna', role: 'user' }];\n\nusers.findItem('id', 2);              // { id: 2, ... } or null\nusers.findAll('role', 'admin');       // an array\nusers.findIndex(u => u.name === 'Anna'); // 1\nusers.findValue('id', 1, 'name');     // Peter\nusers = users.remove('id', 1);        // a new array without the item\n\nusers.quicksort('name');              // in place, by name\nusers.quicksort('role,name_desc');    // several columns\nusers.group('role');                  // [{ name: 'admin', items: [...] }, ...]\nall.skip(20).take(10);                // paging\n```\n\n`remove()`, `findAll()`, `take()` and `skip()` return new arrays; `quicksort()` and `random()` change the array itself.\n\nFor asynchronous work over items, `wait()` calls a function for each item and waits for `next()`. The third argument runs several items at the same time:\n\n```js\nfiles.wait(function(file, next) {\n\tFUNC.process(file, next);\n}, function() {\n\tconsole.log('All files are processed');\n}, 3);\n```\n\n`async()` runs an array of functions in sequence and `limit()` processes an array in chunks, which is handy for inserting many rows in batches.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"JacXYP3Gt61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/prototypes/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Prototypen","summary":"Methoden, die Total.js zu String, Number, Date und Array hinzufügt: Formatierung, Parsen, Validierung, Hashing, Datumswerte und Array-Helfer.","markdown":"---\ntitle: Prototypen\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/prototypes/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Prototypen\n\n> Methoden, die Total.js zu String, Number, Date und Array hinzufügt: Formatierung, Parsen, Validierung, Hashing, Datumswerte und Array-Helfer.\n\nTotal.js 5 fügt den eingebauten Prototypen von JavaScript eine Reihe von Methoden hinzu: `String`, `Number`, `Date` und `Array`. Sie sind in jeder Datei der Anwendung verfügbar (Controller, Aktionen, Schemas, Definitionen, Views), sobald das Framework geladen ist; du importierst nichts.\n\n```js\nvar title = 'Hello World!';\ntitle.slug();                     // hello-world\n'{0} items'.format(5);            // 5 items\n(1234.5).format(2);               // 1 234.50\nnew Date().add('1 day').format('yyyy-MM-dd');\nusers.findItem('id', 5);\n```\n\nDie vollständige Liste mit jedem Argument steht in der Referenz [Prototypen](../../reference/prototypes/). Dieser Leitfaden zeigt die Gruppen und die Methoden, die du am häufigsten verwendest.\n\n## Strings: Vorlagen und Text\n\n`format()` füllt nummerierte Platzhalter und `args()` benannte. `args()` kann die Werte für HTML, JSON oder URLs kodieren:\n\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n\nvar tpl = '<a href=\"/users/{id}/\">{name}</a>';\ntpl.args({ id: 10, name: '<Peter>' }, 'html');\n// <a href=\"/users/10/\">&lt;Peter&gt;</a>\n```\n\nFür Text von Benutzern und für URLs:\n\n```js\n'Čaute, svet!'.slug();          // caute-svet\n'<b>Hi</b>'.encode();           // &lt;b&gt;Hi&lt;/b&gt;\n'&lt;b&gt;'.decode();           // <b>\n'<p>Hi</p>'.removeTags();       // Hi\n'A long description'.max(10);   // A long ...\n'hello world'.capitalize();     // Hello World\n'Čučoriedka'.toASCII();         // Cucoriedka\n```\n\n`toKeywords()` und `toSearch()` bereiten Text für eine einfache Volltextsuche vor: Sie schreiben ihn klein, entfernen diakritische Zeichen und Symbole und machen den Abgleich tolerant (`y` und `i` sind gleich).\n\n## Strings: Parsen\n\nDie `parse*`-Methoden werfen bei fehlerhafter Eingabe keine Ausnahme: Sie geben stattdessen einen Standardwert, `undefined` oder ein ungültiges Datum zurück. Nur `parseConfig()` wirft bei einem Wert, der nicht ausgewertet werden kann, wenn du `onerr` nicht übergibst. Das macht sie sicher für Query Strings und Request-Bodys.\n\n```js\n'10'.parseInt();                 // 10\n'abc'.parseInt(1);               // 1 (the default)\n'1,5'.parseFloat();              // 1.5\n'on'.parseBoolean();             // true\n'{\"a\":1}'.parseJSON();           // { a: 1 }, or undefined for bad JSON\n'2024-05-01 12:30'.parseDate();  // a Date in UTC\n'01/05/2024'.parseDate('dd/MM/yyyy');\n'5 minutes'.parseDateExpiration(); // now + 5 minutes\n```\n\nStrukturierte Textformate haben eigene Parser:\n\n```js\n'q=total&page=2'.parseEncoded();       // { q: 'total', page: '2' }\n'PORT=8000\\nNAME=\"App\"'.parseEnv();    // { PORT: '8000', NAME: 'App' }\n'count (number) : 10'.parseConfig();   // { count: 10 }\n'a,b\\n1,2'.parseCSV();                 // [{ a: 'a', b: 'b' }, { a: '1', b: '2' }]\nreq.headers['user-agent'].parseUA();   // Windows Chrome\n```\n\n`parseContext()` liest Text aus Blöcken. Jeder Block hat Header-Zeilen zwischen zwei Zeilen aus mindestens 20 Bindestrichen und danach einen Body; das Ergebnis ist ein Array von Objekten mit den Header-Schlüsseln (kleingeschrieben) und `body`:\n\n```js\nvar text = PATH.root('prompts.txt');\nvar blocks = Total.Fs.readFileSync(text, 'utf8').parseContext();\n// [{ name: 'welcome', type: 'prompt', body: '...' }, ...]\n```\n\n`parseCSV()` benennt die Spalten mit Buchstaben (`a`, `b`, `c`, ...). Eine Datei mit einer Kopfzeile gibt diese daher als erstes Objekt zurück. Lies die Kopfzeile und ordne dann die Buchstaben deinen Namen zu:\n\n```js\nvar rows = text.parseCSV(';');\nvar header = rows.shift();\nvar users = rows.map(row => ({ name: row.a, email: row.b }));\n```\n\n## Strings: Validierung\n\nDie `is*`-Methoden geben einen Boolean zurück. `isEmail()`, `isPhone()`, `isURL()`, `isXSS()` und `isSQLInjection()` verwenden reguläre Ausdrücke, die in `DEF.validators` gespeichert sind. So kannst du einen davon beim Start ersetzen, wenn deine Regeln anders sind:\n\n```js\n'info@example.com'.isEmail();     // true\n'+421903123456'.isPhone();        // true\n'https://totaljs.com'.isURL();    // true\nUID().isUID();                    // true (the checksum is checked too)\n'123'.isNumber();                 // true\n'<script>'.isXSS();               // true\n\n// /definitions/validators.js\nDEF.validators.phone = /^\\+?[0-9\\s]{6,20}$/;\n```\n\n## Strings: Hashing und Verschlüsselung\n\n```js\n'text'.hash();               // a fast 32-bit number, for cache keys\n'text'.hash('sha256');       // the same as 'text'.sha256()\n'text'.md5();\n'password'.sha512(CONF.secret);\n\nvar link = '123'.sign('key');    // 123-nzo165\nlink.sign('key', true);          // 123, or null when the text was changed\n\nvar secret = 'user@example.com'.encrypt('key');\nsecret.decrypt('key');           // user@example.com\n\nvar token = '123'.encrypt_uid(); // a short token for public URLs\ntoken.decrypt_uid();             // 123\n```\n\n`encrypt()`, `decrypt()`, `encrypt_uid()` und `decrypt_uid()` verwenden den Konfigurationsschlüssel `secret`, wenn du kein Secret übergibst. So können alle Instanzen einer Anwendung mit derselben Konfiguration die Werte der anderen lesen.\n\n## Zahlen\n\n```js\n(1234567.891).format(2);              // 1 234 567.89\n(1234.5).format(2, ',', '.');         // 1,234.50\n(1.005).round(2);                     // 1.01\n(100).VAT(20);                        // 120\n(100).discount(15);                   // 85\n(5).padLeft(3);                       // 005\n(1536000).filesize();                 // 1.46 MB\n(3).pluralize('no files', '# file', '# files', '# files'); // 3 files\n(5).between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }); // medium\n```\n\n`format()` schneidet überzählige Dezimalstellen ab, statt sie zu runden: Runde zuerst mit `round()`, wenn es darauf ankommt, zum Beispiel bei Preisen. `currency()` formatiert einen Betrag mit einer Funktion, die du in `DEF.currencies` registrierst.\n\n## Datumswerte\n\nDie Anwendung läuft in UTC, sofern der Konfigurationsschlüssel `$timezone` nichts anderes angibt. Datumswerte werden daher standardmäßig in UTC formatiert.\n\n```js\nvar now = new Date();\nnow.add('1 day');                    // a new Date, now is not changed\nnow.add('-30 minutes');\nnow.format('yyyy-MM-dd HH:mm');      // 2024-05-01 12:30\nnow.format('dddd, d. MMMM yyyy');    // Wednesday, 1. May 2024\nnow.format();                        // ISO string in UTC\nnow.extend('08:00');                 // the same day at 08:00\nnow.diff(created, 'days');           // days between created and now\nnow.setTimeZone('America/New_York').format('HH:mm'); // the time in New York\n```\n\n## Arrays\n\nDie Suchmethoden akzeptieren eine Funktion, einen Eigenschaftsnamen mit einem Wert oder einen einzelnen Wert:\n\n```js\nvar users = [{ id: 1, name: 'Peter', role: 'admin' }, { id: 2, name: 'Anna', role: 'user' }];\n\nusers.findItem('id', 2);              // { id: 2, ... } or null\nusers.findAll('role', 'admin');       // an array\nusers.findIndex(u => u.name === 'Anna'); // 1\nusers.findValue('id', 1, 'name');     // Peter\nusers = users.remove('id', 1);        // a new array without the item\n\nusers.quicksort('name');              // in place, by name\nusers.quicksort('role,name_desc');    // several columns\nusers.group('role');                  // [{ name: 'admin', items: [...] }, ...]\nall.skip(20).take(10);                // paging\n```\n\n`remove()`, `findAll()`, `take()` und `skip()` geben neue Arrays zurück; `quicksort()` und `random()` ändern das Array selbst.\n\nFür asynchrone Arbeit über Elemente ruft `wait()` für jedes Element eine Funktion auf und wartet auf `next()`. Das dritte Argument verarbeitet mehrere Elemente gleichzeitig:\n\n```js\nfiles.wait(function(file, next) {\n\tFUNC.process(file, next);\n}, function() {\n\tconsole.log('All files are processed');\n}, 3);\n```\n\n`async()` führt ein Array von Funktionen nacheinander aus, und `limit()` verarbeitet ein Array in Abschnitten. Das ist praktisch, um viele Zeilen stapelweise einzufügen.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"JacXYP3Gt61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/prototypes/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Prototipos","summary":"Métodos que Total.js añade a String, Number, Date y Array: formato, parseo, validación, hashing, fechas y helpers de arrays.","markdown":"---\ntitle: Prototipos\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/prototypes/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Prototipos\n\n> Métodos que Total.js añade a String, Number, Date y Array: formato, parseo, validación, hashing, fechas y helpers de arrays.\n\nTotal.js 5 añade un conjunto de métodos a los prototipos integrados de JavaScript: `String`, `Number`, `Date` y `Array`. Están disponibles en todos los archivos de la aplicación (controladores, acciones, esquemas, definiciones, vistas) en cuanto se carga el framework; no importas nada.\n\n```js\nvar title = 'Hello World!';\ntitle.slug();                     // hello-world\n'{0} items'.format(5);            // 5 items\n(1234.5).format(2);               // 1 234.50\nnew Date().add('1 day').format('yyyy-MM-dd');\nusers.findItem('id', 5);\n```\n\nLa lista completa con todos los argumentos está en la referencia [Prototipos](../../reference/prototypes/). Esta guía muestra los grupos y los métodos que más usas.\n\n## Strings: plantillas y texto\n\n`format()` rellena marcadores numerados y `args()` rellena los que tienen nombre. `args()` puede codificar los valores para HTML, JSON o URLs:\n\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n\nvar tpl = '<a href=\"/users/{id}/\">{name}</a>';\ntpl.args({ id: 10, name: '<Peter>' }, 'html');\n// <a href=\"/users/10/\">&lt;Peter&gt;</a>\n```\n\nPara texto de los usuarios y para URLs:\n\n```js\n'Čaute, svet!'.slug();          // caute-svet\n'<b>Hi</b>'.encode();           // &lt;b&gt;Hi&lt;/b&gt;\n'&lt;b&gt;'.decode();           // <b>\n'<p>Hi</p>'.removeTags();       // Hi\n'A long description'.max(10);   // A long ...\n'hello world'.capitalize();     // Hello World\n'Čučoriedka'.toASCII();         // Cucoriedka\n```\n\n`toKeywords()` y `toSearch()` preparan el texto para una búsqueda de texto completo sencilla: lo pasan a minúsculas, eliminan los diacríticos y los símbolos, y hacen la coincidencia tolerante (`y` e `i` son lo mismo).\n\n## Strings: parseo\n\nLos métodos `parse*` no lanzan excepciones con una entrada incorrecta: en su lugar devuelven un valor por defecto, `undefined` o una fecha no válida. Solo `parseConfig()` lanza una excepción con un valor que no se puede evaluar cuando no pasas `onerr`. Esto los hace seguros para query strings y cuerpos de peticiones.\n\n```js\n'10'.parseInt();                 // 10\n'abc'.parseInt(1);               // 1 (the default)\n'1,5'.parseFloat();              // 1.5\n'on'.parseBoolean();             // true\n'{\"a\":1}'.parseJSON();           // { a: 1 }, or undefined for bad JSON\n'2024-05-01 12:30'.parseDate();  // a Date in UTC\n'01/05/2024'.parseDate('dd/MM/yyyy');\n'5 minutes'.parseDateExpiration(); // now + 5 minutes\n```\n\nLos formatos de texto estructurado tienen sus propios parsers:\n\n```js\n'q=total&page=2'.parseEncoded();       // { q: 'total', page: '2' }\n'PORT=8000\\nNAME=\"App\"'.parseEnv();    // { PORT: '8000', NAME: 'App' }\n'count (number) : 10'.parseConfig();   // { count: 10 }\n'a,b\\n1,2'.parseCSV();                 // [{ a: 'a', b: 'b' }, { a: '1', b: '2' }]\nreq.headers['user-agent'].parseUA();   // Windows Chrome\n```\n\n`parseContext()` lee texto formado por bloques. Cada bloque tiene líneas de cabecera entre dos líneas de al menos 20 guiones y un cuerpo después de ellas; el resultado es un array de objetos con las claves de la cabecera (en minúsculas) y `body`:\n\n```js\nvar text = PATH.root('prompts.txt');\nvar blocks = Total.Fs.readFileSync(text, 'utf8').parseContext();\n// [{ name: 'welcome', type: 'prompt', body: '...' }, ...]\n```\n\n`parseCSV()` nombra las columnas con letras (`a`, `b`, `c`, ...), así que un archivo con una línea de cabecera devuelve la cabecera como primer objeto. Lee la cabecera y luego asigna las letras a tus nombres:\n\n```js\nvar rows = text.parseCSV(';');\nvar header = rows.shift();\nvar users = rows.map(row => ({ name: row.a, email: row.b }));\n```\n\n## Strings: validación\n\nLos métodos `is*` devuelven un booleano. `isEmail()`, `isPhone()`, `isURL()`, `isXSS()` e `isSQLInjection()` usan expresiones regulares guardadas en `DEF.validators`, así que puedes reemplazar una de ellas al arrancar cuando tus reglas sean distintas:\n\n```js\n'info@example.com'.isEmail();     // true\n'+421903123456'.isPhone();        // true\n'https://totaljs.com'.isURL();    // true\nUID().isUID();                    // true (the checksum is checked too)\n'123'.isNumber();                 // true\n'<script>'.isXSS();               // true\n\n// /definitions/validators.js\nDEF.validators.phone = /^\\+?[0-9\\s]{6,20}$/;\n```\n\n## Strings: hashing y cifrado\n\n```js\n'text'.hash();               // a fast 32-bit number, for cache keys\n'text'.hash('sha256');       // the same as 'text'.sha256()\n'text'.md5();\n'password'.sha512(CONF.secret);\n\nvar link = '123'.sign('key');    // 123-nzo165\nlink.sign('key', true);          // 123, or null when the text was changed\n\nvar secret = 'user@example.com'.encrypt('key');\nsecret.decrypt('key');           // user@example.com\n\nvar token = '123'.encrypt_uid(); // a short token for public URLs\ntoken.decrypt_uid();             // 123\n```\n\n`encrypt()`, `decrypt()`, `encrypt_uid()` y `decrypt_uid()` usan la clave de configuración `secret` cuando no pasas un secreto, así que todas las instancias de una aplicación con la misma configuración pueden leer los valores de las demás.\n\n## Números\n\n```js\n(1234567.891).format(2);              // 1 234 567.89\n(1234.5).format(2, ',', '.');         // 1,234.50\n(1.005).round(2);                     // 1.01\n(100).VAT(20);                        // 120\n(100).discount(15);                   // 85\n(5).padLeft(3);                       // 005\n(1536000).filesize();                 // 1.46 MB\n(3).pluralize('no files', '# file', '# files', '# files'); // 3 files\n(5).between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }); // medium\n```\n\n`format()` corta los decimales sobrantes en lugar de redondearlos: redondea antes con `round()` cuando importe, por ejemplo para precios. `currency()` formatea un importe con una función que registras en `DEF.currencies`.\n\n## Fechas\n\nLa aplicación se ejecuta en UTC salvo que la clave de configuración `$timezone` indique otra cosa, así que las fechas se formatean en UTC por defecto.\n\n```js\nvar now = new Date();\nnow.add('1 day');                    // a new Date, now is not changed\nnow.add('-30 minutes');\nnow.format('yyyy-MM-dd HH:mm');      // 2024-05-01 12:30\nnow.format('dddd, d. MMMM yyyy');    // Wednesday, 1. May 2024\nnow.format();                        // ISO string in UTC\nnow.extend('08:00');                 // the same day at 08:00\nnow.diff(created, 'days');           // days between created and now\nnow.setTimeZone('America/New_York').format('HH:mm'); // the time in New York\n```\n\n## Arrays\n\nLos métodos de búsqueda aceptan una función, un nombre de propiedad con un valor, o un único valor:\n\n```js\nvar users = [{ id: 1, name: 'Peter', role: 'admin' }, { id: 2, name: 'Anna', role: 'user' }];\n\nusers.findItem('id', 2);              // { id: 2, ... } or null\nusers.findAll('role', 'admin');       // an array\nusers.findIndex(u => u.name === 'Anna'); // 1\nusers.findValue('id', 1, 'name');     // Peter\nusers = users.remove('id', 1);        // a new array without the item\n\nusers.quicksort('name');              // in place, by name\nusers.quicksort('role,name_desc');    // several columns\nusers.group('role');                  // [{ name: 'admin', items: [...] }, ...]\nall.skip(20).take(10);                // paging\n```\n\n`remove()`, `findAll()`, `take()` y `skip()` devuelven arrays nuevos; `quicksort()` y `random()` modifican el propio array.\n\nPara trabajo asíncrono sobre elementos, `wait()` llama a una función por cada elemento y espera a `next()`. El tercer argumento procesa varios elementos a la vez:\n\n```js\nfiles.wait(function(file, next) {\n\tFUNC.process(file, next);\n}, function() {\n\tconsole.log('All files are processed');\n}, 3);\n```\n\n`async()` ejecuta un array de funciones en secuencia y `limit()` procesa un array por bloques, lo que resulta práctico para insertar muchas filas por lotes.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"JacXYP3Gt61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/prototypes/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Prototypes","summary":"Les méthodes que Total.js ajoute à String, Number, Date et Array : formatage, analyse, validation, hachage, dates et helpers de tableaux.","markdown":"---\ntitle: Prototypes\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/prototypes/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Prototypes\n\n> Les méthodes que Total.js ajoute à String, Number, Date et Array : formatage, analyse, validation, hachage, dates et helpers de tableaux.\n\nTotal.js 5 ajoute un ensemble de méthodes aux prototypes intégrés de JavaScript : `String`, `Number`, `Date` et `Array`. Elles sont disponibles dans chaque fichier de l'application (contrôleurs, actions, schémas, définitions, vues) dès que le framework est chargé ; tu n'importes rien.\n\n```js\nvar title = 'Hello World!';\ntitle.slug();                     // hello-world\n'{0} items'.format(5);            // 5 items\n(1234.5).format(2);               // 1 234.50\nnew Date().add('1 day').format('yyyy-MM-dd');\nusers.findItem('id', 5);\n```\n\nLa liste complète avec chaque argument se trouve dans la référence [Prototypes](../../reference/prototypes/). Ce guide présente les groupes et les méthodes que tu utilises le plus.\n\n## Chaînes : templates et texte\n\n`format()` remplit les placeholders numérotés et `args()` les placeholders nommés. `args()` peut encoder les valeurs pour le HTML, le JSON ou les URL :\n\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n\nvar tpl = '<a href=\"/users/{id}/\">{name}</a>';\ntpl.args({ id: 10, name: '<Peter>' }, 'html');\n// <a href=\"/users/10/\">&lt;Peter&gt;</a>\n```\n\nPour le texte saisi par les utilisateurs et pour les URL :\n\n```js\n'Čaute, svet!'.slug();          // caute-svet\n'<b>Hi</b>'.encode();           // &lt;b&gt;Hi&lt;/b&gt;\n'&lt;b&gt;'.decode();           // <b>\n'<p>Hi</p>'.removeTags();       // Hi\n'A long description'.max(10);   // A long ...\n'hello world'.capitalize();     // Hello World\n'Čučoriedka'.toASCII();         // Cucoriedka\n```\n\n`toKeywords()` et `toSearch()` préparent du texte pour une recherche plein texte simple : elles le mettent en minuscules, retirent les diacritiques et les symboles, et rendent la correspondance tolérante (`y` et `i` sont identiques).\n\n## Chaînes : analyse\n\nLes méthodes `parse*` ne lèvent pas d'erreur pour une entrée incorrecte : elles renvoient à la place une valeur par défaut, `undefined` ou une date invalide. Seule `parseConfig()` lève une erreur pour une valeur qui ne peut pas être évaluée lorsque tu ne passes pas `onerr`. Elles sont donc sûres pour les query strings et les corps de requête.\n\n```js\n'10'.parseInt();                 // 10\n'abc'.parseInt(1);               // 1 (the default)\n'1,5'.parseFloat();              // 1.5\n'on'.parseBoolean();             // true\n'{\"a\":1}'.parseJSON();           // { a: 1 }, or undefined for bad JSON\n'2024-05-01 12:30'.parseDate();  // a Date in UTC\n'01/05/2024'.parseDate('dd/MM/yyyy');\n'5 minutes'.parseDateExpiration(); // now + 5 minutes\n```\n\nLes formats de texte structuré ont leurs propres parsers :\n\n```js\n'q=total&page=2'.parseEncoded();       // { q: 'total', page: '2' }\n'PORT=8000\\nNAME=\"App\"'.parseEnv();    // { PORT: '8000', NAME: 'App' }\n'count (number) : 10'.parseConfig();   // { count: 10 }\n'a,b\\n1,2'.parseCSV();                 // [{ a: 'a', b: 'b' }, { a: '1', b: '2' }]\nreq.headers['user-agent'].parseUA();   // Windows Chrome\n```\n\n`parseContext()` lit un texte composé de blocs. Chaque bloc a des lignes d'en-tête entre deux lignes d'au moins 20 tirets, suivies d'un corps ; le résultat est un tableau d'objets avec les clés de l'en-tête (en minuscules) et `body` :\n\n```js\nvar text = PATH.root('prompts.txt');\nvar blocks = Total.Fs.readFileSync(text, 'utf8').parseContext();\n// [{ name: 'welcome', type: 'prompt', body: '...' }, ...]\n```\n\n`parseCSV()` nomme les colonnes par des lettres (`a`, `b`, `c`, ...) : un fichier avec une ligne d'en-tête renvoie donc l'en-tête comme premier objet. Lis l'en-tête, puis fais correspondre les lettres à tes noms :\n\n```js\nvar rows = text.parseCSV(';');\nvar header = rows.shift();\nvar users = rows.map(row => ({ name: row.a, email: row.b }));\n```\n\n## Chaînes : validation\n\nLes méthodes `is*` renvoient un booléen. `isEmail()`, `isPhone()`, `isURL()`, `isXSS()` et `isSQLInjection()` utilisent des expressions régulières stockées dans `DEF.validators` : tu peux donc en remplacer une au démarrage si tes règles sont différentes :\n\n```js\n'info@example.com'.isEmail();     // true\n'+421903123456'.isPhone();        // true\n'https://totaljs.com'.isURL();    // true\nUID().isUID();                    // true (the checksum is checked too)\n'123'.isNumber();                 // true\n'<script>'.isXSS();               // true\n\n// /definitions/validators.js\nDEF.validators.phone = /^\\+?[0-9\\s]{6,20}$/;\n```\n\n## Chaînes : hachage et chiffrement\n\n```js\n'text'.hash();               // a fast 32-bit number, for cache keys\n'text'.hash('sha256');       // the same as 'text'.sha256()\n'text'.md5();\n'password'.sha512(CONF.secret);\n\nvar link = '123'.sign('key');    // 123-nzo165\nlink.sign('key', true);          // 123, or null when the text was changed\n\nvar secret = 'user@example.com'.encrypt('key');\nsecret.decrypt('key');           // user@example.com\n\nvar token = '123'.encrypt_uid(); // a short token for public URLs\ntoken.decrypt_uid();             // 123\n```\n\n`encrypt()`, `decrypt()`, `encrypt_uid()` et `decrypt_uid()` utilisent la clé de configuration `secret` quand tu ne passes pas de secret : toutes les instances d'une application ayant la même configuration peuvent ainsi lire les valeurs des autres.\n\n## Nombres\n\n```js\n(1234567.891).format(2);              // 1 234 567.89\n(1234.5).format(2, ',', '.');         // 1,234.50\n(1.005).round(2);                     // 1.01\n(100).VAT(20);                        // 120\n(100).discount(15);                   // 85\n(5).padLeft(3);                       // 005\n(1536000).filesize();                 // 1.46 MB\n(3).pluralize('no files', '# file', '# files', '# files'); // 3 files\n(5).between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }); // medium\n```\n\n`format()` tronque les décimales en trop au lieu de les arrondir : arrondis d'abord avec `round()` quand cela compte, par exemple pour des prix. `currency()` formate un montant avec une fonction que tu enregistres dans `DEF.currencies`.\n\n## Dates\n\nL'application tourne en UTC sauf si la clé de configuration `$timezone` indique autre chose : les dates sont donc formatées en UTC par défaut.\n\n```js\nvar now = new Date();\nnow.add('1 day');                    // a new Date, now is not changed\nnow.add('-30 minutes');\nnow.format('yyyy-MM-dd HH:mm');      // 2024-05-01 12:30\nnow.format('dddd, d. MMMM yyyy');    // Wednesday, 1. May 2024\nnow.format();                        // ISO string in UTC\nnow.extend('08:00');                 // the same day at 08:00\nnow.diff(created, 'days');           // days between created and now\nnow.setTimeZone('America/New_York').format('HH:mm'); // the time in New York\n```\n\n## Tableaux\n\nLes méthodes de recherche acceptent une fonction, un nom de propriété avec une valeur, ou une valeur seule :\n\n```js\nvar users = [{ id: 1, name: 'Peter', role: 'admin' }, { id: 2, name: 'Anna', role: 'user' }];\n\nusers.findItem('id', 2);              // { id: 2, ... } or null\nusers.findAll('role', 'admin');       // an array\nusers.findIndex(u => u.name === 'Anna'); // 1\nusers.findValue('id', 1, 'name');     // Peter\nusers = users.remove('id', 1);        // a new array without the item\n\nusers.quicksort('name');              // in place, by name\nusers.quicksort('role,name_desc');    // several columns\nusers.group('role');                  // [{ name: 'admin', items: [...] }, ...]\nall.skip(20).take(10);                // paging\n```\n\n`remove()`, `findAll()`, `take()` et `skip()` renvoient de nouveaux tableaux ; `quicksort()` et `random()` modifient le tableau lui-même.\n\nPour un traitement asynchrone des éléments, `wait()` appelle une fonction pour chaque élément et attend `next()`. Le troisième argument traite plusieurs éléments en même temps :\n\n```js\nfiles.wait(function(file, next) {\n\tFUNC.process(file, next);\n}, function() {\n\tconsole.log('All files are processed');\n}, 3);\n```\n\n`async()` exécute un tableau de fonctions en séquence et `limit()` traite un tableau par morceaux, ce qui est pratique pour insérer de nombreuses lignes par lots.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"JacXYP3Gt61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/prototypes/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Prototipi","summary":"Metodi che Total.js aggiunge a String, Number, Date e Array: formattazione, parsing, validazione, hashing, date e helper per gli array.","markdown":"---\ntitle: Prototipi\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/prototypes/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Prototipi\n\n> Metodi che Total.js aggiunge a String, Number, Date e Array: formattazione, parsing, validazione, hashing, date e helper per gli array.\n\nTotal.js 5 aggiunge una serie di metodi ai prototipi integrati di JavaScript: `String`, `Number`, `Date` e `Array`. Sono disponibili in ogni file dell'applicazione (controller, azioni, schemi, definizioni, viste) non appena il framework è caricato; non devi importare nulla.\n\n```js\nvar title = 'Hello World!';\ntitle.slug();                     // hello-world\n'{0} items'.format(5);            // 5 items\n(1234.5).format(2);               // 1 234.50\nnew Date().add('1 day').format('yyyy-MM-dd');\nusers.findItem('id', 5);\n```\n\nL'elenco completo con ogni argomento è nel riferimento [Prototipi](../../reference/prototypes/). Questa guida mostra i gruppi e i metodi che userai di più.\n\n## Stringhe: template e testo\n\n`format()` riempie i segnaposto numerati e `args()` quelli con nome. `args()` può codificare i valori per HTML, JSON o URL:\n\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n\nvar tpl = '<a href=\"/users/{id}/\">{name}</a>';\ntpl.args({ id: 10, name: '<Peter>' }, 'html');\n// <a href=\"/users/10/\">&lt;Peter&gt;</a>\n```\n\nPer il testo degli utenti e per gli URL:\n\n```js\n'Čaute, svet!'.slug();          // caute-svet\n'<b>Hi</b>'.encode();           // &lt;b&gt;Hi&lt;/b&gt;\n'&lt;b&gt;'.decode();           // <b>\n'<p>Hi</p>'.removeTags();       // Hi\n'A long description'.max(10);   // A long ...\n'hello world'.capitalize();     // Hello World\n'Čučoriedka'.toASCII();         // Cucoriedka\n```\n\n`toKeywords()` e `toSearch()` preparano il testo per una semplice ricerca full-text: lo convertono in minuscolo, rimuovono i segni diacritici e i simboli, e rendono il confronto tollerante (`y` e `i` sono equivalenti).\n\n## Stringhe: parsing\n\nI metodi `parse*` non generano eccezioni per input non validi: restituiscono invece un valore predefinito, `undefined` o una data non valida. Solo `parseConfig()` genera un'eccezione per un valore che non può essere valutato quando non passi `onerr`. Questo li rende sicuri per query string e body delle richieste.\n\n```js\n'10'.parseInt();                 // 10\n'abc'.parseInt(1);               // 1 (the default)\n'1,5'.parseFloat();              // 1.5\n'on'.parseBoolean();             // true\n'{\"a\":1}'.parseJSON();           // { a: 1 }, or undefined for bad JSON\n'2024-05-01 12:30'.parseDate();  // a Date in UTC\n'01/05/2024'.parseDate('dd/MM/yyyy');\n'5 minutes'.parseDateExpiration(); // now + 5 minutes\n```\n\nI formati di testo strutturati hanno i propri parser:\n\n```js\n'q=total&page=2'.parseEncoded();       // { q: 'total', page: '2' }\n'PORT=8000\\nNAME=\"App\"'.parseEnv();    // { PORT: '8000', NAME: 'App' }\n'count (number) : 10'.parseConfig();   // { count: 10 }\n'a,b\\n1,2'.parseCSV();                 // [{ a: 'a', b: 'b' }, { a: '1', b: '2' }]\nreq.headers['user-agent'].parseUA();   // Windows Chrome\n```\n\n`parseContext()` legge un testo composto da blocchi. Ogni blocco ha righe di intestazione tra due righe di almeno 20 trattini e un corpo dopo di esse; il risultato è un array di oggetti con le chiavi dell'intestazione (in minuscolo) e `body`:\n\n```js\nvar text = PATH.root('prompts.txt');\nvar blocks = Total.Fs.readFileSync(text, 'utf8').parseContext();\n// [{ name: 'welcome', type: 'prompt', body: '...' }, ...]\n```\n\n`parseCSV()` assegna alle colonne delle lettere (`a`, `b`, `c`, ...), quindi un file con una riga di intestazione restituisce l'intestazione come primo oggetto. Leggi l'intestazione, poi associa le lettere ai tuoi nomi:\n\n```js\nvar rows = text.parseCSV(';');\nvar header = rows.shift();\nvar users = rows.map(row => ({ name: row.a, email: row.b }));\n```\n\n## Stringhe: validazione\n\nI metodi `is*` restituiscono un booleano. `isEmail()`, `isPhone()`, `isURL()`, `isXSS()` e `isSQLInjection()` usano espressioni regolari salvate in `DEF.validators`, quindi puoi sostituirne una all'avvio quando le tue regole sono diverse:\n\n```js\n'info@example.com'.isEmail();     // true\n'+421903123456'.isPhone();        // true\n'https://totaljs.com'.isURL();    // true\nUID().isUID();                    // true (the checksum is checked too)\n'123'.isNumber();                 // true\n'<script>'.isXSS();               // true\n\n// /definitions/validators.js\nDEF.validators.phone = /^\\+?[0-9\\s]{6,20}$/;\n```\n\n## Stringhe: hashing e cifratura\n\n```js\n'text'.hash();               // a fast 32-bit number, for cache keys\n'text'.hash('sha256');       // the same as 'text'.sha256()\n'text'.md5();\n'password'.sha512(CONF.secret);\n\nvar link = '123'.sign('key');    // 123-nzo165\nlink.sign('key', true);          // 123, or null when the text was changed\n\nvar secret = 'user@example.com'.encrypt('key');\nsecret.decrypt('key');           // user@example.com\n\nvar token = '123'.encrypt_uid(); // a short token for public URLs\ntoken.decrypt_uid();             // 123\n```\n\n`encrypt()`, `decrypt()`, `encrypt_uid()` e `decrypt_uid()` usano la chiave di configurazione `secret` quando non passi un segreto, così tutte le istanze di un'applicazione con la stessa configurazione possono leggere i valori l'una dell'altra.\n\n## Numeri\n\n```js\n(1234567.891).format(2);              // 1 234 567.89\n(1234.5).format(2, ',', '.');         // 1,234.50\n(1.005).round(2);                     // 1.01\n(100).VAT(20);                        // 120\n(100).discount(15);                   // 85\n(5).padLeft(3);                       // 005\n(1536000).filesize();                 // 1.46 MB\n(3).pluralize('no files', '# file', '# files', '# files'); // 3 files\n(5).between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }); // medium\n```\n\n`format()` tronca i decimali in eccesso invece di arrotondarli: arrotonda prima con `round()` quando conta, per esempio per i prezzi. `currency()` formatta un importo con una funzione che registri in `DEF.currencies`.\n\n## Date\n\nL'applicazione gira in UTC, a meno che la chiave di configurazione `$timezone` non dica altrimenti, quindi le date vengono formattate in UTC per impostazione predefinita.\n\n```js\nvar now = new Date();\nnow.add('1 day');                    // a new Date, now is not changed\nnow.add('-30 minutes');\nnow.format('yyyy-MM-dd HH:mm');      // 2024-05-01 12:30\nnow.format('dddd, d. MMMM yyyy');    // Wednesday, 1. May 2024\nnow.format();                        // ISO string in UTC\nnow.extend('08:00');                 // the same day at 08:00\nnow.diff(created, 'days');           // days between created and now\nnow.setTimeZone('America/New_York').format('HH:mm'); // the time in New York\n```\n\n## Array\n\nI metodi di ricerca accettano una funzione, un nome di proprietà con un valore, oppure un singolo valore:\n\n```js\nvar users = [{ id: 1, name: 'Peter', role: 'admin' }, { id: 2, name: 'Anna', role: 'user' }];\n\nusers.findItem('id', 2);              // { id: 2, ... } or null\nusers.findAll('role', 'admin');       // an array\nusers.findIndex(u => u.name === 'Anna'); // 1\nusers.findValue('id', 1, 'name');     // Peter\nusers = users.remove('id', 1);        // a new array without the item\n\nusers.quicksort('name');              // in place, by name\nusers.quicksort('role,name_desc');    // several columns\nusers.group('role');                  // [{ name: 'admin', items: [...] }, ...]\nall.skip(20).take(10);                // paging\n```\n\n`remove()`, `findAll()`, `take()` e `skip()` restituiscono nuovi array; `quicksort()` e `random()` modificano l'array stesso.\n\nPer il lavoro asincrono sugli elementi, `wait()` chiama una funzione per ogni elemento e attende `next()`. Il terzo argomento elabora più elementi contemporaneamente:\n\n```js\nfiles.wait(function(file, next) {\n\tFUNC.process(file, next);\n}, function() {\n\tconsole.log('All files are processed');\n}, 3);\n```\n\n`async()` esegue in sequenza un array di funzioni e `limit()` elabora un array a blocchi, comodo per inserire molte righe a lotti.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"JacXYP3Gt61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/prototypes/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Prototypy","summary":"Metódy, ktoré Total.js pridáva do String, Number, Date a Array: formátovanie, parsovanie, validácia, hašovanie, dátumy a pomocné funkcie pre polia.","markdown":"---\ntitle: Prototypy\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/prototypes/\nupdated: 2026-11-16T15:32:42.496Z\n---\n\n# Prototypy\n\n> Metódy, ktoré Total.js pridáva do String, Number, Date a Array: formátovanie, parsovanie, validácia, hašovanie, dátumy a pomocné funkcie pre polia.\n\nTotal.js 5 pridáva sadu metód do vstavaných prototypov JavaScriptu: `String`, `Number`, `Date` a `Array`. Sú dostupné v každom súbore aplikácie (controllery, akcie, schémy, definície, view) hneď po načítaní frameworku; nič neimportuješ.\n\n```js\nvar title = 'Hello World!';\ntitle.slug();                     // hello-world\n'{0} items'.format(5);            // 5 items\n(1234.5).format(2);               // 1 234.50\nnew Date().add('1 day').format('yyyy-MM-dd');\nusers.findItem('id', 5);\n```\n\nÚplný zoznam so všetkými argumentmi nájdeš v referencii [Prototypy](../../reference/prototypes/). Tento návod ukazuje skupiny a metódy, ktoré používaš najčastejšie.\n\n## Reťazce: šablóny a text\n\n`format()` vyplní číslované zástupné symboly a `args()` pomenované. `args()` vie hodnoty zakódovať pre HTML, JSON alebo URL:\n\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n\nvar tpl = '<a href=\"/users/{id}/\">{name}</a>';\ntpl.args({ id: 10, name: '<Peter>' }, 'html');\n// <a href=\"/users/10/\">&lt;Peter&gt;</a>\n```\n\nPre text od používateľov a pre URL:\n\n```js\n'Čaute, svet!'.slug();          // caute-svet\n'<b>Hi</b>'.encode();           // &lt;b&gt;Hi&lt;/b&gt;\n'&lt;b&gt;'.decode();           // <b>\n'<p>Hi</p>'.removeTags();       // Hi\n'A long description'.max(10);   // A long ...\n'hello world'.capitalize();     // Hello World\n'Čučoriedka'.toASCII();         // Cucoriedka\n```\n\n`toKeywords()` a `toSearch()` pripravia text pre jednoduché fulltextové vyhľadávanie: prevedú ho na malé písmená, odstránia diakritiku a symboly a urobia porovnávanie tolerantným (`y` a `i` sú to isté).\n\n## Reťazce: parsovanie\n\nMetódy `parse*` pri zlom vstupe nevyhodia výnimku: namiesto toho vrátia predvolenú hodnotu, `undefined` alebo neplatný dátum. Iba `parseConfig()` vyhodí výnimku pre hodnotu, ktorú nemožno vyhodnotiť, keď neodovzdáš `onerr`. Preto sú bezpečné pre query stringy a telá požiadaviek.\n\n```js\n'10'.parseInt();                 // 10\n'abc'.parseInt(1);               // 1 (the default)\n'1,5'.parseFloat();              // 1.5\n'on'.parseBoolean();             // true\n'{\"a\":1}'.parseJSON();           // { a: 1 }, or undefined for bad JSON\n'2024-05-01 12:30'.parseDate();  // a Date in UTC\n'01/05/2024'.parseDate('dd/MM/yyyy');\n'5 minutes'.parseDateExpiration(); // now + 5 minutes\n```\n\nŠtruktúrované textové formáty majú vlastné parsery:\n\n```js\n'q=total&page=2'.parseEncoded();       // { q: 'total', page: '2' }\n'PORT=8000\\nNAME=\"App\"'.parseEnv();    // { PORT: '8000', NAME: 'App' }\n'count (number) : 10'.parseConfig();   // { count: 10 }\n'a,b\\n1,2'.parseCSV();                 // [{ a: 'a', b: 'b' }, { a: '1', b: '2' }]\nreq.headers['user-agent'].parseUA();   // Windows Chrome\n```\n\n`parseContext()` číta text zložený z blokov. Každý blok má riadky hlavičky medzi dvoma riadkami s aspoň 20 pomlčkami a za nimi telo; výsledkom je pole objektov s kľúčmi hlavičky (malými písmenami) a `body`:\n\n```js\nvar text = PATH.root('prompts.txt');\nvar blocks = Total.Fs.readFileSync(text, 'utf8').parseContext();\n// [{ name: 'welcome', type: 'prompt', body: '...' }, ...]\n```\n\n`parseCSV()` pomenúva stĺpce písmenami (`a`, `b`, `c`, ...), takže súbor s riadkom hlavičky vráti hlavičku ako prvý objekt. Prečítaj hlavičku a potom namapuj písmená na svoje názvy:\n\n```js\nvar rows = text.parseCSV(';');\nvar header = rows.shift();\nvar users = rows.map(row => ({ name: row.a, email: row.b }));\n```\n\n## Reťazce: validácia\n\nMetódy `is*` vracajú boolean. `isEmail()`, `isPhone()`, `isURL()`, `isXSS()` a `isSQLInjection()` používajú regulárne výrazy uložené v `DEF.validators`, takže ktorýkoľvek z nich môžeš pri štarte nahradiť, keď máš iné pravidlá:\n\n```js\n'info@example.com'.isEmail();     // true\n'+421903123456'.isPhone();        // true\n'https://totaljs.com'.isURL();    // true\nUID().isUID();                    // true (the checksum is checked too)\n'123'.isNumber();                 // true\n'<script>'.isXSS();               // true\n\n// /definitions/validators.js\nDEF.validators.phone = /^\\+?[0-9\\s]{6,20}$/;\n```\n\n## Reťazce: hašovanie a šifrovanie\n\n```js\n'text'.hash();               // a fast 32-bit number, for cache keys\n'text'.hash('sha256');       // the same as 'text'.sha256()\n'text'.md5();\n'password'.sha512(CONF.secret);\n\nvar link = '123'.sign('key');    // 123-nzo165\nlink.sign('key', true);          // 123, or null when the text was changed\n\nvar secret = 'user@example.com'.encrypt('key');\nsecret.decrypt('key');           // user@example.com\n\nvar token = '123'.encrypt_uid(); // a short token for public URLs\ntoken.decrypt_uid();             // 123\n```\n\n`encrypt()`, `decrypt()`, `encrypt_uid()` a `decrypt_uid()` používajú konfiguračný kľúč `secret`, keď neodovzdáš tajomstvo, takže všetky inštancie aplikácie s rovnakou konfiguráciou si navzájom prečítajú hodnoty.\n\n## Čísla\n\n```js\n(1234567.891).format(2);              // 1 234 567.89\n(1234.5).format(2, ',', '.');         // 1,234.50\n(1.005).round(2);                     // 1.01\n(100).VAT(20);                        // 120\n(100).discount(15);                   // 85\n(5).padLeft(3);                       // 005\n(1536000).filesize();                 // 1.46 MB\n(3).pluralize('no files', '# file', '# files', '# files'); // 3 files\n(5).between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }); // medium\n```\n\n`format()` nadbytočné desatinné miesta odreže namiesto zaokrúhlenia: keď na tom záleží, napríklad pri cenách, najprv zaokrúhli cez `round()`. `currency()` naformátuje sumu funkciou, ktorú zaregistruješ v `DEF.currencies`.\n\n## Dátumy\n\nAplikácia beží v UTC, ak konfiguračný kľúč `$timezone` neurčuje inak, takže dátumy sa predvolene formátujú v UTC.\n\n```js\nvar now = new Date();\nnow.add('1 day');                    // a new Date, now is not changed\nnow.add('-30 minutes');\nnow.format('yyyy-MM-dd HH:mm');      // 2024-05-01 12:30\nnow.format('dddd, d. MMMM yyyy');    // Wednesday, 1. May 2024\nnow.format();                        // ISO string in UTC\nnow.extend('08:00');                 // the same day at 08:00\nnow.diff(created, 'days');           // days between created and now\nnow.setTimeZone('America/New_York').format('HH:mm'); // the time in New York\n```\n\n## Polia\n\nVyhľadávacie metódy prijímajú funkciu, názov vlastnosti s hodnotou alebo jednu hodnotu:\n\n```js\nvar users = [{ id: 1, name: 'Peter', role: 'admin' }, { id: 2, name: 'Anna', role: 'user' }];\n\nusers.findItem('id', 2);              // { id: 2, ... } or null\nusers.findAll('role', 'admin');       // an array\nusers.findIndex(u => u.name === 'Anna'); // 1\nusers.findValue('id', 1, 'name');     // Peter\nusers = users.remove('id', 1);        // a new array without the item\n\nusers.quicksort('name');              // in place, by name\nusers.quicksort('role,name_desc');    // several columns\nusers.group('role');                  // [{ name: 'admin', items: [...] }, ...]\nall.skip(20).take(10);                // paging\n```\n\n`remove()`, `findAll()`, `take()` a `skip()` vracajú nové polia; `quicksort()` a `random()` menia samotné pole.\n\nPre asynchrónnu prácu nad položkami `wait()` zavolá funkciu pre každú položku a čaká na `next()`. Tretí argument spracuje viac položiek naraz:\n\n```js\nfiles.wait(function(file, next) {\n\tFUNC.process(file, next);\n}, function() {\n\tconsole.log('All files are processed');\n}, 3);\n```\n\n`async()` spustí pole funkcií postupne a `limit()` spracuje pole po častiach, čo sa hodí pri vkladaní veľa riadkov v dávkach.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:42.496Z"}
{"id":"JafwT65Ix61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/images/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Images","summary":"Resize, crop, convert, watermark and measure images with GraphicsMagick or ImageMagick.","markdown":"---\ntitle: Images\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/images/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Images\n\n> Resize, crop, convert, watermark and measure images with GraphicsMagick or ImageMagick.\n\nTotal.js processes images with an external program: **GraphicsMagick** (`gm`, the default) or **ImageMagick** (`convert` or `magick`). The framework does not change pixels itself. An `Image` object collects the operations you call and builds one command line from them. The command runs when you call `save()`, `pipe()` or `writer()`.\n\nInstall the program on the server first, for example `brew install graphicsmagick` or `apt-get install graphicsmagick`. The exact reference of every method is in [Images](../../reference/images/).\n\n## Load an image\n\nThe `Image` global is the image module. `Image.load()` (also `F.image()`) creates an image object from a file name, a `Buffer` or a readable stream:\n\n```js\nvar img = Image.load(PATH.public('photos/beach.jpg'));\nimg.resize(800, 600);\nimg.quality(85);\nimg.save(PATH.public('photos/beach-800.jpg'), function(err) {\n\tif (err)\n\t\tconsole.error(err);\n});\n```\n\n```js\n// From a Buffer or a stream\nvar img = Image.load(buffer);\nvar img2 = Image.load(F.Fs.createReadStream('/tmp/upload.png'));\n```\n\nThe type of the image (`img.type`) comes from the extension of the file name. For a `Buffer` or a stream it is `jpg`; change it with `img.output('png')`.\n\nThe methods return the image object, so you can chain them:\n\n```js\nImage.load(filename).resize(200, 200).grayscale().quality(80).save(target, callback);\n```\n\nOther modules give you image objects too: an uploaded file has `file.image()` (see [Controller](../../guides/controller/)), a file storage has `fs.image(id)` (see [File storage](../../guides/file-storage/)), and `$.image(opt)` processes an image and sends it as the response.\n\n## Choose the program\n\nThe configuration key `$imageconverter` sets the program for all images: `gm` (GraphicsMagick, the default), `im` (ImageMagick 6, the `convert` command) or `magick` (ImageMagick 7). See [Configuration](../../guides/configuration/).\n\n```\n$imageconverter : im\n```\n\nThe second argument of `Image.load()` changes it for one image:\n\n```js\nvar img = Image.load(filename, 'magick');\n```\n\n## Resize and crop\n\n| Method | What it does |\n| --- | --- |\n| `resize(w, h, [options])` | Resizes into the box `w`x`h` and keeps the aspect ratio. One side can be empty. `options` is appended to the size (`'!'`, `'^'`, `'>'`, `'<'`), and a size can be a percentage like `'50%'` |\n| `thumbnail(w, h, [options])` | Like `resize()`, but also removes the profiles, for small previews |\n| `scale(w, h, [options])` | A fast resize without filtering |\n| `crop(w, h, [x], [y])` | Cuts a `w`x`h` area at the offset `x`, `y` |\n| `extent(w, h, [x], [y])` | Sets the canvas to `w`x`h`; new area is filled with the background color |\n| `resizecenter(w, h, [color])` | Fills the `w`x`h` box completely and crops the centre |\n| `resizealign(w, h, [align], [color])` | Like `resizecenter()` but crops at the given side |\n| `miniature(w, h, [color])` | Fits the image into `w`x`h` and fills the rest with the color (white) |\n\n```js\n// A square avatar, the face is usually at the top\nImage.load(filename).resizealign(200, 200, 'top').quality(90).save(target);\n\n// The whole photo inside 300x300, with a white border\nImage.load(filename).miniature(300, 300).save(target);\n```\n\n`align(type)` (alias `gravity()`) sets the gravity used by `crop()` and `extent()`. It accepts `'top left'`, `'top'`, `'center'`, `'bottom right'`… and any GraphicsMagick gravity name such as `'NorthEast'`.\n\n## Adjust and transform\n\n```js\nvar img = Image.load(filename);\nimg.rotate(90);           // degrees\nimg.flip();               // vertical mirror\nimg.flop();               // horizontal mirror\nimg.blur(3);\nimg.grayscale();\nimg.sepia();\nimg.normalize();\nimg.colors(16);           // reduce the palette\nimg.bitdepth(8);\nimg.quality(75);          // compression level, 80 when empty\nimg.save(target);\n```\n\n`background(color)` sets the color for new areas (used by `extent()`, `rotate()` and the resize helpers), `fill(color)` sets the fill color, `filter(name)` the resize filter (`'Lanczos'`, `'Hamming'`…; it applies to every resize of the image, in any order of the calls) and `define(value)` passes a coder option such as `'jpeg:extent=200kb'`.\n\n## Watermarks\n\n`watermark(filename, x, y, w, h)` draws another image over the picture. `x` and `y` are measured from the top left corner, and a width and height of 0 keep the size of the watermark:\n\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n## Any other option\n\n`command(key, [value], [priority], [escape])` adds any option of the program. Pass `true` as the third argument to put the value in quotes:\n\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'Holiday 2024', true);\n```\n\nThe operations are sorted by priority before the command is built (the resize filter of `filter()` first, then sizes, gravity, crop, quality, rotation and effects such as `blur()`). `img.cmd(from, to)` returns the command line without running it, which helps when you debug:\n\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n\n`img.clear()` removes all operations, and `img.make(fn)` calls `fn(img)` so you can keep a set of operations in a function.\n\n## Save, pipe and stream\n\n`save([filename], [callback])` writes the result to a file. The format comes from the extension of the target file. Without a file name it overwrites the source file. The callback gets `(err, success)`:\n\n```js\nImage.load(buffer).resize(400).save(PATH.public('upload/photo.jpg'), function(err, success) {\n\t// success === true\n});\n```\n\n`pipe(stream, [type], [options])` sends the result to a writable stream, for example the HTTP response. `type` is the output format (`jpg`, `png`, `gif`, `webp`, `heic`…, otherwise `img.type`); `options` goes to `stream.pipe()`:\n\n```js\nfunction preview($) {\n\tvar img = Image.load(PATH.public('photos/' + $.params.id + '.jpg'));\n\timg.resize(300, 300);\n\t$.res.writeHead(200, { 'content-type': 'image/webp' });\n\timg.pipe($.res, 'webp');\n}\n```\n\n`writer([type])` starts the conversion and returns the readable output stream:\n\n```js\nvar stream = Image.load(buffer).resize(100, 100).writer('png');\nstream.pipe(F.Fs.createWriteStream('/tmp/thumb.png'));\n```\n\nWhen an image has no operations, `save()`, `pipe()` and `writer()` add `minify()`, which removes the profiles and metadata.\n\nFor HTTP responses with a cache, `$.image()` of the controller is shorter (see [Controller](../../guides/controller/)).\n\n## Measure an image\n\nThe module reads the size from the header of the file, without the external program:\n\n```js\nvar size = Image.measure('png', buffer);\n// { width: 800, height: 600 }\n\nImage.load(PATH.public('photos/beach.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n`Image.measure(type, buffer)` understands JPEG, PNG, GIF, WebP, SVG, BMP and PSD (as an extension or a MIME type) and returns `undefined` for other types. For a JPEG whose size marker is not in the buffer (a damaged file or too little data), it returns `null`. The method `img.measure(callback)` reads files with the extensions `.jpg`, `.png`, `.gif` and `.webp`. Uploaded files are measured automatically, see `file.width` and `file.height` in [Controller](../../guides/controller/).\n\n## Post-processing middleware\n\n`Image.middleware(type, fn)` registers a function that returns a transform stream. Every result of that type passes through it (for `save()` only when it has a callback), for example to run an optimizer:\n\n```js\nImage.middleware('png', function() {\n\treturn new MyPngOptimizer(); // a Transform stream\n});\n```\n\nThe type is `img.type`: the extension of the source, or the value of `output()`. For `pipe()` and `writer()` it is the output format.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwT65Ix61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/images/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Bilder","summary":"Bilder mit GraphicsMagick oder ImageMagick skalieren, zuschneiden, konvertieren, mit Wasserzeichen versehen und vermessen.","markdown":"---\ntitle: Bilder\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/images/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Bilder\n\n> Bilder mit GraphicsMagick oder ImageMagick skalieren, zuschneiden, konvertieren, mit Wasserzeichen versehen und vermessen.\n\nTotal.js verarbeitet Bilder mit einem externen Programm: **GraphicsMagick** (`gm`, der Standard) oder **ImageMagick** (`convert` oder `magick`). Das Framework ändert selbst keine Pixel. Ein `Image`-Objekt sammelt die Operationen, die du aufrufst, und baut daraus eine Kommandozeile. Der Befehl läuft, wenn du `save()`, `pipe()` oder `writer()` aufrufst.\n\nInstalliere das Programm zuerst auf dem Server, zum Beispiel `brew install graphicsmagick` oder `apt-get install graphicsmagick`. Die genaue Referenz jeder Methode steht in [Bilder](../../reference/images/).\n\n## Ein Bild laden\n\nDas globale `Image` ist das Bildmodul. `Image.load()` (auch `F.image()`) erstellt ein Bildobjekt aus einem Dateinamen, einem `Buffer` oder einem lesbaren Stream:\n\n```js\nvar img = Image.load(PATH.public('photos/beach.jpg'));\nimg.resize(800, 600);\nimg.quality(85);\nimg.save(PATH.public('photos/beach-800.jpg'), function(err) {\n\tif (err)\n\t\tconsole.error(err);\n});\n```\n\n```js\n// From a Buffer or a stream\nvar img = Image.load(buffer);\nvar img2 = Image.load(F.Fs.createReadStream('/tmp/upload.png'));\n```\n\nDer Typ des Bildes (`img.type`) ergibt sich aus der Endung des Dateinamens. Für einen `Buffer` oder einen Stream ist er `jpg`; ändere ihn mit `img.output('png')`.\n\nDie Methoden geben das Bildobjekt zurück, du kannst sie also verketten:\n\n```js\nImage.load(filename).resize(200, 200).grayscale().quality(80).save(target, callback);\n```\n\nAuch andere Module liefern dir Bildobjekte: Eine hochgeladene Datei hat `file.image()` (siehe [Controller](../../guides/controller/)), ein Dateispeicher hat `fs.image(id)` (siehe [Dateispeicher](../../guides/file-storage/)), und `$.image(opt)` verarbeitet ein Bild und sendet es als Antwort.\n\n## Das Programm wählen\n\nDer Konfigurationsschlüssel `$imageconverter` legt das Programm für alle Bilder fest: `gm` (GraphicsMagick, der Standard), `im` (ImageMagick 6, der Befehl `convert`) oder `magick` (ImageMagick 7). Siehe [Konfiguration](../../guides/configuration/).\n\n```\n$imageconverter : im\n```\n\nDas zweite Argument von `Image.load()` ändert es für ein einzelnes Bild:\n\n```js\nvar img = Image.load(filename, 'magick');\n```\n\n## Skalieren und zuschneiden\n\n| Methode | Was sie bewirkt |\n| --- | --- |\n| `resize(w, h, [options])` | Skaliert in die Box `w`x`h` und behält das Seitenverhältnis. Eine Seite kann leer sein. `options` wird an die Größe angehängt (`'!'`, `'^'`, `'>'`, `'<'`), und eine Größe kann ein Prozentwert wie `'50%'` sein |\n| `thumbnail(w, h, [options])` | Wie `resize()`, entfernt aber auch die Profile, für kleine Vorschauen |\n| `scale(w, h, [options])` | Eine schnelle Skalierung ohne Filterung |\n| `crop(w, h, [x], [y])` | Schneidet einen Bereich `w`x`h` am Versatz `x`, `y` aus |\n| `extent(w, h, [x], [y])` | Setzt die Arbeitsfläche auf `w`x`h`; neue Fläche wird mit der Hintergrundfarbe gefüllt |\n| `resizecenter(w, h, [color])` | Füllt die Box `w`x`h` vollständig und schneidet die Mitte zu |\n| `resizealign(w, h, [align], [color])` | Wie `resizecenter()`, schneidet aber an der angegebenen Seite zu |\n| `miniature(w, h, [color])` | Passt das Bild in `w`x`h` ein und füllt den Rest mit der Farbe (weiß) |\n\n```js\n// A square avatar, the face is usually at the top\nImage.load(filename).resizealign(200, 200, 'top').quality(90).save(target);\n\n// The whole photo inside 300x300, with a white border\nImage.load(filename).miniature(300, 300).save(target);\n```\n\n`align(type)` (Alias `gravity()`) setzt die Ausrichtung (Gravity), die `crop()` und `extent()` verwenden. Es akzeptiert `'top left'`, `'top'`, `'center'`, `'bottom right'`… und jeden Gravity-Namen von GraphicsMagick wie `'NorthEast'`.\n\n## Anpassen und transformieren\n\n```js\nvar img = Image.load(filename);\nimg.rotate(90);           // degrees\nimg.flip();               // vertical mirror\nimg.flop();               // horizontal mirror\nimg.blur(3);\nimg.grayscale();\nimg.sepia();\nimg.normalize();\nimg.colors(16);           // reduce the palette\nimg.bitdepth(8);\nimg.quality(75);          // compression level, 80 when empty\nimg.save(target);\n```\n\n`background(color)` setzt die Farbe für neue Flächen (verwendet von `extent()`, `rotate()` und den Skalierungshelfern), `fill(color)` setzt die Füllfarbe, `filter(name)` den Skalierungsfilter (`'Lanczos'`, `'Hamming'`…; er gilt für jede Skalierung des Bildes, in beliebiger Reihenfolge der Aufrufe), und `define(value)` übergibt eine Coder-Option wie `'jpeg:extent=200kb'`.\n\n## Wasserzeichen\n\n`watermark(filename, x, y, w, h)` zeichnet ein anderes Bild über das Bild. `x` und `y` werden von der oberen linken Ecke aus gemessen, und eine Breite und Höhe von 0 behalten die Größe des Wasserzeichens:\n\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n## Jede andere Option\n\n`command(key, [value], [priority], [escape])` fügt eine beliebige Option des Programms hinzu. Übergib `true` als drittes Argument, um den Wert in Anführungszeichen zu setzen:\n\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'Holiday 2024', true);\n```\n\nDie Operationen werden vor dem Aufbau des Befehls nach Priorität sortiert (zuerst der Skalierungsfilter von `filter()`, dann Größen, Gravity, Zuschnitt, Qualität, Drehung und Effekte wie `blur()`). `img.cmd(from, to)` gibt die Kommandozeile zurück, ohne sie auszuführen, was beim Debuggen hilft:\n\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n\n`img.clear()` entfernt alle Operationen, und `img.make(fn)` ruft `fn(img)` auf, sodass du eine Reihe von Operationen in einer Funktion halten kannst.\n\n## Speichern, pipen und streamen\n\n`save([filename], [callback])` schreibt das Ergebnis in eine Datei. Das Format ergibt sich aus der Endung der Zieldatei. Ohne Dateinamen wird die Quelldatei überschrieben. Der Callback erhält `(err, success)`:\n\n```js\nImage.load(buffer).resize(400).save(PATH.public('upload/photo.jpg'), function(err, success) {\n\t// success === true\n});\n```\n\n`pipe(stream, [type], [options])` sendet das Ergebnis an einen schreibbaren Stream, zum Beispiel die HTTP-Antwort. `type` ist das Ausgabeformat (`jpg`, `png`, `gif`, `webp`, `heic`…, sonst `img.type`); `options` geht an `stream.pipe()`:\n\n```js\nfunction preview($) {\n\tvar img = Image.load(PATH.public('photos/' + $.params.id + '.jpg'));\n\timg.resize(300, 300);\n\t$.res.writeHead(200, { 'content-type': 'image/webp' });\n\timg.pipe($.res, 'webp');\n}\n```\n\n`writer([type])` startet die Konvertierung und gibt den lesbaren Ausgabe-Stream zurück:\n\n```js\nvar stream = Image.load(buffer).resize(100, 100).writer('png');\nstream.pipe(F.Fs.createWriteStream('/tmp/thumb.png'));\n```\n\nHat ein Bild keine Operationen, fügen `save()`, `pipe()` und `writer()` `minify()` hinzu, das die Profile und Metadaten entfernt.\n\nFür HTTP-Antworten mit Cache ist `$.image()` des Controllers kürzer (siehe [Controller](../../guides/controller/)).\n\n## Ein Bild vermessen\n\nDas Modul liest die Größe aus dem Header der Datei, ohne das externe Programm:\n\n```js\nvar size = Image.measure('png', buffer);\n// { width: 800, height: 600 }\n\nImage.load(PATH.public('photos/beach.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n`Image.measure(type, buffer)` versteht JPEG, PNG, GIF, WebP, SVG, BMP und PSD (als Endung oder MIME-Typ) und gibt für andere Typen `undefined` zurück. Für ein JPEG, dessen Größenmarker nicht im Buffer steht (eine beschädigte Datei oder zu wenig Daten), gibt es `null` zurück. Die Methode `img.measure(callback)` liest Dateien mit den Endungen `.jpg`, `.png`, `.gif` und `.webp`. Hochgeladene Dateien werden automatisch vermessen, siehe `file.width` und `file.height` in [Controller](../../guides/controller/).\n\n## Middleware zur Nachbearbeitung\n\n`Image.middleware(type, fn)` registriert eine Funktion, die einen Transform-Stream zurückgibt. Jedes Ergebnis dieses Typs läuft durch ihn hindurch (bei `save()` nur, wenn es einen Callback hat), zum Beispiel um einen Optimierer auszuführen:\n\n```js\nImage.middleware('png', function() {\n\treturn new MyPngOptimizer(); // a Transform stream\n});\n```\n\nDer Typ ist `img.type`: die Endung der Quelle oder der Wert von `output()`. Für `pipe()` und `writer()` ist es das Ausgabeformat.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwT65Ix61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/images/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Imágenes","summary":"Redimensiona, recorta, convierte, añade marcas de agua y mide imágenes con GraphicsMagick o ImageMagick.","markdown":"---\ntitle: \"Imágenes\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/images/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Imágenes\n\n> Redimensiona, recorta, convierte, añade marcas de agua y mide imágenes con GraphicsMagick o ImageMagick.\n\nTotal.js procesa las imágenes con un programa externo: **GraphicsMagick** (`gm`, el valor por defecto) o **ImageMagick** (`convert` o `magick`). El framework no modifica los píxeles por sí mismo. Un objeto `Image` recoge las operaciones que llamas y construye con ellas una línea de comandos. El comando se ejecuta cuando llamas a `save()`, `pipe()` o `writer()`.\n\nInstala primero el programa en el servidor, por ejemplo `brew install graphicsmagick` o `apt-get install graphicsmagick`. La referencia exacta de cada método está en [Imágenes](../../reference/images/).\n\n## Cargar una imagen\n\nEl global `Image` es el módulo de imágenes. `Image.load()` (también `F.image()`) crea un objeto imagen a partir de un nombre de archivo, un `Buffer` o un stream de lectura:\n\n```js\nvar img = Image.load(PATH.public('photos/beach.jpg'));\nimg.resize(800, 600);\nimg.quality(85);\nimg.save(PATH.public('photos/beach-800.jpg'), function(err) {\n\tif (err)\n\t\tconsole.error(err);\n});\n```\n\n```js\n// From a Buffer or a stream\nvar img = Image.load(buffer);\nvar img2 = Image.load(F.Fs.createReadStream('/tmp/upload.png'));\n```\n\nEl tipo de la imagen (`img.type`) sale de la extensión del nombre de archivo. Para un `Buffer` o un stream es `jpg`; cámbialo con `img.output('png')`.\n\nLos métodos devuelven el objeto imagen, así que puedes encadenarlos:\n\n```js\nImage.load(filename).resize(200, 200).grayscale().quality(80).save(target, callback);\n```\n\nOtros módulos también te dan objetos imagen: un archivo subido tiene `file.image()` (consulta [Controlador](../../guides/controller/)), un almacenamiento de archivos tiene `fs.image(id)` (consulta [Almacenamiento de archivos](../../guides/file-storage/)), y `$.image(opt)` procesa una imagen y la envía como respuesta.\n\n## Elegir el programa\n\nLa clave de configuración `$imageconverter` asigna el programa para todas las imágenes: `gm` (GraphicsMagick, el valor por defecto), `im` (ImageMagick 6, el comando `convert`) o `magick` (ImageMagick 7). Consulta [Configuración](../../guides/configuration/).\n\n```\n$imageconverter : im\n```\n\nEl segundo argumento de `Image.load()` lo cambia para una sola imagen:\n\n```js\nvar img = Image.load(filename, 'magick');\n```\n\n## Redimensionar y recortar\n\n| Método | Qué hace |\n| --- | --- |\n| `resize(w, h, [options])` | Redimensiona dentro del recuadro `w`x`h` y mantiene la proporción. Un lado puede quedar vacío. `options` se añade al tamaño (`'!'`, `'^'`, `'>'`, `'<'`), y un tamaño puede ser un porcentaje como `'50%'` |\n| `thumbnail(w, h, [options])` | Como `resize()`, pero además elimina los perfiles, para vistas previas pequeñas |\n| `scale(w, h, [options])` | Un redimensionado rápido sin filtrado |\n| `crop(w, h, [x], [y])` | Recorta un área de `w`x`h` en el desplazamiento `x`, `y` |\n| `extent(w, h, [x], [y])` | Ajusta el lienzo a `w`x`h`; el área nueva se rellena con el color de fondo |\n| `resizecenter(w, h, [color])` | Rellena por completo el recuadro `w`x`h` y recorta el centro |\n| `resizealign(w, h, [align], [color])` | Como `resizecenter()`, pero recorta por el lado indicado |\n| `miniature(w, h, [color])` | Encaja la imagen en `w`x`h` y rellena el resto con el color (blanco) |\n\n```js\n// A square avatar, the face is usually at the top\nImage.load(filename).resizealign(200, 200, 'top').quality(90).save(target);\n\n// The whole photo inside 300x300, with a white border\nImage.load(filename).miniature(300, 300).save(target);\n```\n\n`align(type)` (alias `gravity()`) asigna la gravedad que usan `crop()` y `extent()`. Acepta `'top left'`, `'top'`, `'center'`, `'bottom right'`… y cualquier nombre de gravedad de GraphicsMagick, como `'NorthEast'`.\n\n## Ajustar y transformar\n\n```js\nvar img = Image.load(filename);\nimg.rotate(90);           // degrees\nimg.flip();               // vertical mirror\nimg.flop();               // horizontal mirror\nimg.blur(3);\nimg.grayscale();\nimg.sepia();\nimg.normalize();\nimg.colors(16);           // reduce the palette\nimg.bitdepth(8);\nimg.quality(75);          // compression level, 80 when empty\nimg.save(target);\n```\n\n`background(color)` asigna el color de las áreas nuevas (lo usan `extent()`, `rotate()` y las funciones auxiliares de redimensionado), `fill(color)` asigna el color de relleno, `filter(name)` el filtro de redimensionado (`'Lanczos'`, `'Hamming'`…; se aplica a cada redimensionado de la imagen, en cualquier orden de las llamadas) y `define(value)` pasa una opción del codificador como `'jpeg:extent=200kb'`.\n\n## Marcas de agua\n\n`watermark(filename, x, y, w, h)` dibuja otra imagen sobre la imagen. `x` e `y` se miden desde la esquina superior izquierda, y un ancho y alto de 0 mantienen el tamaño de la marca de agua:\n\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n## Cualquier otra opción\n\n`command(key, [value], [priority], [escape])` añade cualquier opción del programa. Pasa `true` como tercer argumento para poner el valor entre comillas:\n\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'Holiday 2024', true);\n```\n\nLas operaciones se ordenan por prioridad antes de construir el comando (primero el filtro de redimensionado de `filter()`, después los tamaños, la gravedad, el recorte, la calidad, la rotación y los efectos como `blur()`). `img.cmd(from, to)` devuelve la línea de comandos sin ejecutarla, lo que ayuda al depurar:\n\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n\n`img.clear()` elimina todas las operaciones, e `img.make(fn)` llama a `fn(img)` para que puedas guardar un conjunto de operaciones en una función.\n\n## Guardar, pipe y stream\n\n`save([filename], [callback])` escribe el resultado en un archivo. El formato sale de la extensión del archivo de destino. Sin nombre de archivo, sobrescribe el archivo de origen. El callback recibe `(err, success)`:\n\n```js\nImage.load(buffer).resize(400).save(PATH.public('upload/photo.jpg'), function(err, success) {\n\t// success === true\n});\n```\n\n`pipe(stream, [type], [options])` envía el resultado a un stream de escritura, por ejemplo la respuesta HTTP. `type` es el formato de salida (`jpg`, `png`, `gif`, `webp`, `heic`…; si no, `img.type`); `options` va a `stream.pipe()`:\n\n```js\nfunction preview($) {\n\tvar img = Image.load(PATH.public('photos/' + $.params.id + '.jpg'));\n\timg.resize(300, 300);\n\t$.res.writeHead(200, { 'content-type': 'image/webp' });\n\timg.pipe($.res, 'webp');\n}\n```\n\n`writer([type])` inicia la conversión y devuelve el stream de salida de lectura:\n\n```js\nvar stream = Image.load(buffer).resize(100, 100).writer('png');\nstream.pipe(F.Fs.createWriteStream('/tmp/thumb.png'));\n```\n\nCuando una imagen no tiene operaciones, `save()`, `pipe()` y `writer()` añaden `minify()`, que elimina los perfiles y los metadatos.\n\nPara respuestas HTTP con caché, `$.image()` del controlador es más corto (consulta [Controlador](../../guides/controller/)).\n\n## Medir una imagen\n\nEl módulo lee el tamaño de la cabecera del archivo, sin el programa externo:\n\n```js\nvar size = Image.measure('png', buffer);\n// { width: 800, height: 600 }\n\nImage.load(PATH.public('photos/beach.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n`Image.measure(type, buffer)` entiende JPEG, PNG, GIF, WebP, SVG, BMP y PSD (como extensión o como tipo MIME) y devuelve `undefined` para otros tipos. Para un JPEG cuyo marcador de tamaño no está en el buffer (un archivo dañado o demasiado pocos datos), devuelve `null`. El método `img.measure(callback)` lee archivos con las extensiones `.jpg`, `.png`, `.gif` y `.webp`. Los archivos subidos se miden automáticamente; consulta `file.width` y `file.height` en [Controlador](../../guides/controller/).\n\n## Middleware de posprocesado\n\n`Image.middleware(type, fn)` registra una función que devuelve un stream de transformación. Cada resultado de ese tipo pasa por ella (en `save()` solo cuando tiene callback), por ejemplo para ejecutar un optimizador:\n\n```js\nImage.middleware('png', function() {\n\treturn new MyPngOptimizer(); // a Transform stream\n});\n```\n\nEl tipo es `img.type`: la extensión del origen, o el valor de `output()`. Para `pipe()` y `writer()` es el formato de salida.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwT65Ix61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/images/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Images","summary":"Redimensionne, recadre, convertis, filigrane et mesure des images avec GraphicsMagick ou ImageMagick.","markdown":"---\ntitle: Images\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/images/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Images\n\n> Redimensionne, recadre, convertis, filigrane et mesure des images avec GraphicsMagick ou ImageMagick.\n\nTotal.js traite les images avec un programme externe : **GraphicsMagick** (`gm`, par défaut) ou **ImageMagick** (`convert` ou `magick`). Le framework ne modifie pas lui-même les pixels. Un objet `Image` rassemble les opérations que tu appelles et construit à partir d'elles une seule ligne de commande. La commande s'exécute lorsque tu appelles `save()`, `pipe()` ou `writer()`.\n\nInstalle d'abord le programme sur le serveur, par exemple `brew install graphicsmagick` ou `apt-get install graphicsmagick`. La référence exacte de chaque méthode se trouve dans [Images](../../reference/images/).\n\n## Charger une image\n\nLa variable globale `Image` est le module d'images. `Image.load()` (également `F.image()`) crée un objet image à partir d'un nom de fichier, d'un `Buffer` ou d'un flux lisible :\n\n```js\nvar img = Image.load(PATH.public('photos/beach.jpg'));\nimg.resize(800, 600);\nimg.quality(85);\nimg.save(PATH.public('photos/beach-800.jpg'), function(err) {\n\tif (err)\n\t\tconsole.error(err);\n});\n```\n\n```js\n// From a Buffer or a stream\nvar img = Image.load(buffer);\nvar img2 = Image.load(F.Fs.createReadStream('/tmp/upload.png'));\n```\n\nLe type de l'image (`img.type`) provient de l'extension du nom de fichier. Pour un `Buffer` ou un flux, il vaut `jpg` ; change-le avec `img.output('png')`.\n\nLes méthodes renvoient l'objet image, tu peux donc les chaîner :\n\n```js\nImage.load(filename).resize(200, 200).grayscale().quality(80).save(target, callback);\n```\n\nD'autres modules te fournissent aussi des objets image : un fichier envoyé possède `file.image()` (voir [Contrôleur](../../guides/controller/)), un stockage de fichiers possède `fs.image(id)` (voir [Stockage de fichiers](../../guides/file-storage/)), et `$.image(opt)` traite une image et l'envoie comme réponse.\n\n## Choisir le programme\n\nLa clé de configuration `$imageconverter` définit le programme pour toutes les images : `gm` (GraphicsMagick, par défaut), `im` (ImageMagick 6, la commande `convert`) ou `magick` (ImageMagick 7). Voir [Configuration](../../guides/configuration/).\n\n```\n$imageconverter : im\n```\n\nLe deuxième argument de `Image.load()` le change pour une seule image :\n\n```js\nvar img = Image.load(filename, 'magick');\n```\n\n## Redimensionner et recadrer\n\n| Méthode | Ce qu'elle fait |\n| --- | --- |\n| `resize(w, h, [options])` | Redimensionne dans la boîte `w`x`h` en conservant les proportions. Un côté peut être vide. `options` est ajouté à la taille (`'!'`, `'^'`, `'>'`, `'<'`), et une taille peut être un pourcentage comme `'50%'` |\n| `thumbnail(w, h, [options])` | Comme `resize()`, mais retire aussi les profils, pour les petits aperçus |\n| `scale(w, h, [options])` | Un redimensionnement rapide sans filtrage |\n| `crop(w, h, [x], [y])` | Découpe une zone `w`x`h` au décalage `x`, `y` |\n| `extent(w, h, [x], [y])` | Fixe le canevas à `w`x`h` ; la nouvelle zone est remplie avec la couleur de fond |\n| `resizecenter(w, h, [color])` | Remplit entièrement la boîte `w`x`h` et recadre le centre |\n| `resizealign(w, h, [align], [color])` | Comme `resizecenter()`, mais recadre du côté indiqué |\n| `miniature(w, h, [color])` | Fait tenir l'image dans `w`x`h` et remplit le reste avec la couleur (blanc) |\n\n```js\n// A square avatar, the face is usually at the top\nImage.load(filename).resizealign(200, 200, 'top').quality(90).save(target);\n\n// The whole photo inside 300x300, with a white border\nImage.load(filename).miniature(300, 300).save(target);\n```\n\n`align(type)` (alias `gravity()`) définit la gravité utilisée par `crop()` et `extent()`. Elle accepte `'top left'`, `'top'`, `'center'`, `'bottom right'`… ainsi que tout nom de gravité GraphicsMagick comme `'NorthEast'`.\n\n## Ajuster et transformer\n\n```js\nvar img = Image.load(filename);\nimg.rotate(90);           // degrees\nimg.flip();               // vertical mirror\nimg.flop();               // horizontal mirror\nimg.blur(3);\nimg.grayscale();\nimg.sepia();\nimg.normalize();\nimg.colors(16);           // reduce the palette\nimg.bitdepth(8);\nimg.quality(75);          // compression level, 80 when empty\nimg.save(target);\n```\n\n`background(color)` définit la couleur des nouvelles zones (utilisée par `extent()`, `rotate()` et les fonctions de redimensionnement), `fill(color)` définit la couleur de remplissage, `filter(name)` le filtre de redimensionnement (`'Lanczos'`, `'Hamming'`… ; il s'applique à chaque redimensionnement de l'image, quel que soit l'ordre des appels) et `define(value)` transmet une option du codeur comme `'jpeg:extent=200kb'`.\n\n## Filigranes\n\n`watermark(filename, x, y, w, h)` dessine une autre image par-dessus l'image. `x` et `y` sont mesurés depuis le coin supérieur gauche, et une largeur et une hauteur de 0 conservent la taille du filigrane :\n\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n## Toute autre option\n\n`command(key, [value], [priority], [escape])` ajoute n'importe quelle option du programme. Passe `true` comme troisième argument pour mettre la valeur entre guillemets :\n\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'Holiday 2024', true);\n```\n\nLes opérations sont triées par priorité avant la construction de la commande (le filtre de redimensionnement de `filter()` d'abord, puis les tailles, la gravité, le recadrage, la qualité, la rotation et les effets comme `blur()`). `img.cmd(from, to)` renvoie la ligne de commande sans l'exécuter, ce qui aide au débogage :\n\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n\n`img.clear()` retire toutes les opérations, et `img.make(fn)` appelle `fn(img)` afin que tu puisses conserver un ensemble d'opérations dans une fonction.\n\n## Enregistrer, rediriger et diffuser\n\n`save([filename], [callback])` écrit le résultat dans un fichier. Le format provient de l'extension du fichier cible. Sans nom de fichier, elle écrase le fichier source. Le callback reçoit `(err, success)` :\n\n```js\nImage.load(buffer).resize(400).save(PATH.public('upload/photo.jpg'), function(err, success) {\n\t// success === true\n});\n```\n\n`pipe(stream, [type], [options])` envoie le résultat vers un flux inscriptible, par exemple la réponse HTTP. `type` est le format de sortie (`jpg`, `png`, `gif`, `webp`, `heic`…, sinon `img.type`) ; `options` est transmis à `stream.pipe()` :\n\n```js\nfunction preview($) {\n\tvar img = Image.load(PATH.public('photos/' + $.params.id + '.jpg'));\n\timg.resize(300, 300);\n\t$.res.writeHead(200, { 'content-type': 'image/webp' });\n\timg.pipe($.res, 'webp');\n}\n```\n\n`writer([type])` démarre la conversion et renvoie le flux de sortie lisible :\n\n```js\nvar stream = Image.load(buffer).resize(100, 100).writer('png');\nstream.pipe(F.Fs.createWriteStream('/tmp/thumb.png'));\n```\n\nLorsqu'une image n'a aucune opération, `save()`, `pipe()` et `writer()` ajoutent `minify()`, qui retire les profils et les métadonnées.\n\nPour les réponses HTTP avec cache, le `$.image()` du contrôleur est plus court (voir [Contrôleur](../../guides/controller/)).\n\n## Mesurer une image\n\nLe module lit la taille dans l'en-tête du fichier, sans le programme externe :\n\n```js\nvar size = Image.measure('png', buffer);\n// { width: 800, height: 600 }\n\nImage.load(PATH.public('photos/beach.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n`Image.measure(type, buffer)` comprend JPEG, PNG, GIF, WebP, SVG, BMP et PSD (sous forme d'extension ou de type MIME) et renvoie `undefined` pour les autres types. Pour un JPEG dont le marqueur de taille ne se trouve pas dans le buffer (un fichier endommagé ou trop peu de données), il renvoie `null`. La méthode `img.measure(callback)` lit les fichiers ayant les extensions `.jpg`, `.png`, `.gif` et `.webp`. Les fichiers envoyés sont mesurés automatiquement, voir `file.width` et `file.height` dans [Contrôleur](../../guides/controller/).\n\n## Middleware de post-traitement\n\n`Image.middleware(type, fn)` enregistre une fonction qui renvoie un flux de transformation. Chaque résultat de ce type passe par elle (pour `save()` seulement lorsqu'il a un callback), par exemple pour exécuter un optimiseur :\n\n```js\nImage.middleware('png', function() {\n\treturn new MyPngOptimizer(); // a Transform stream\n});\n```\n\nLe type est `img.type` : l'extension de la source, ou la valeur de `output()`. Pour `pipe()` et `writer()`, c'est le format de sortie.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwT65Ix61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/images/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Immagini","summary":"Ridimensiona, ritaglia, converti, applica watermark e misura le immagini con GraphicsMagick o ImageMagick.","markdown":"---\ntitle: Immagini\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/images/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Immagini\n\n> Ridimensiona, ritaglia, converti, applica watermark e misura le immagini con GraphicsMagick o ImageMagick.\n\nTotal.js elabora le immagini con un programma esterno: **GraphicsMagick** (`gm`, il predefinito) o **ImageMagick** (`convert` o `magick`). Il framework non modifica i pixel da sé. Un oggetto `Image` raccoglie le operazioni che chiami e costruisce da esse un'unica riga di comando. Il comando viene eseguito quando chiami `save()`, `pipe()` o `writer()`.\n\nPrima installa il programma sul server, ad esempio `brew install graphicsmagick` o `apt-get install graphicsmagick`. Il riferimento esatto di ogni metodo è in [Immagini](../../reference/images/).\n\n## Caricare un'immagine\n\nL'oggetto globale `Image` è il modulo delle immagini. `Image.load()` (anche `F.image()`) crea un oggetto immagine da un nome di file, un `Buffer` o uno stream leggibile:\n\n```js\nvar img = Image.load(PATH.public('photos/beach.jpg'));\nimg.resize(800, 600);\nimg.quality(85);\nimg.save(PATH.public('photos/beach-800.jpg'), function(err) {\n\tif (err)\n\t\tconsole.error(err);\n});\n```\n\n```js\n// From a Buffer or a stream\nvar img = Image.load(buffer);\nvar img2 = Image.load(F.Fs.createReadStream('/tmp/upload.png'));\n```\n\nIl tipo dell'immagine (`img.type`) deriva dall'estensione del nome del file. Per un `Buffer` o uno stream è `jpg`; cambialo con `img.output('png')`.\n\nI metodi restituiscono l'oggetto immagine, quindi puoi concatenarli:\n\n```js\nImage.load(filename).resize(200, 200).grayscale().quality(80).save(target, callback);\n```\n\nAnche altri moduli ti forniscono oggetti immagine: un file caricato ha `file.image()` (vedi [Controller](../../guides/controller/)), un file storage ha `fs.image(id)` (vedi [File storage](../../guides/file-storage/)), e `$.image(opt)` elabora un'immagine e la invia come risposta.\n\n## Scegliere il programma\n\nLa chiave di configurazione `$imageconverter` imposta il programma per tutte le immagini: `gm` (GraphicsMagick, il predefinito), `im` (ImageMagick 6, il comando `convert`) o `magick` (ImageMagick 7). Vedi [Configurazione](../../guides/configuration/).\n\n```\n$imageconverter : im\n```\n\nIl secondo argomento di `Image.load()` lo cambia per una singola immagine:\n\n```js\nvar img = Image.load(filename, 'magick');\n```\n\n## Ridimensionare e ritagliare\n\n| Metodo | Cosa fa |\n| --- | --- |\n| `resize(w, h, [options])` | Ridimensiona nel riquadro `w`x`h` mantenendo le proporzioni. Un lato può essere vuoto. `options` viene aggiunto alla dimensione (`'!'`, `'^'`, `'>'`, `'<'`), e una dimensione può essere una percentuale come `'50%'` |\n| `thumbnail(w, h, [options])` | Come `resize()`, ma rimuove anche i profili, per piccole anteprime |\n| `scale(w, h, [options])` | Un ridimensionamento veloce senza filtri |\n| `crop(w, h, [x], [y])` | Ritaglia un'area `w`x`h` all'offset `x`, `y` |\n| `extent(w, h, [x], [y])` | Imposta il canvas a `w`x`h`; la nuova area viene riempita con il colore di sfondo |\n| `resizecenter(w, h, [color])` | Riempie completamente il riquadro `w`x`h` e ritaglia il centro |\n| `resizealign(w, h, [align], [color])` | Come `resizecenter()` ma ritaglia sul lato indicato |\n| `miniature(w, h, [color])` | Adatta l'immagine in `w`x`h` e riempie il resto con il colore (bianco) |\n\n```js\n// A square avatar, the face is usually at the top\nImage.load(filename).resizealign(200, 200, 'top').quality(90).save(target);\n\n// The whole photo inside 300x300, with a white border\nImage.load(filename).miniature(300, 300).save(target);\n```\n\n`align(type)` (alias `gravity()`) imposta la gravity usata da `crop()` ed `extent()`. Accetta `'top left'`, `'top'`, `'center'`, `'bottom right'`… e qualsiasi nome di gravity di GraphicsMagick come `'NorthEast'`.\n\n## Regolare e trasformare\n\n```js\nvar img = Image.load(filename);\nimg.rotate(90);           // degrees\nimg.flip();               // vertical mirror\nimg.flop();               // horizontal mirror\nimg.blur(3);\nimg.grayscale();\nimg.sepia();\nimg.normalize();\nimg.colors(16);           // reduce the palette\nimg.bitdepth(8);\nimg.quality(75);          // compression level, 80 when empty\nimg.save(target);\n```\n\n`background(color)` imposta il colore per le nuove aree (usato da `extent()`, `rotate()` e dagli helper di ridimensionamento), `fill(color)` imposta il colore di riempimento, `filter(name)` il filtro di ridimensionamento (`'Lanczos'`, `'Hamming'`…; vale per ogni ridimensionamento dell'immagine, in qualsiasi ordine delle chiamate) e `define(value)` passa un'opzione del coder come `'jpeg:extent=200kb'`.\n\n## Watermark\n\n`watermark(filename, x, y, w, h)` disegna un'altra immagine sopra la foto. `x` e `y` si misurano dall'angolo in alto a sinistra, e una larghezza e un'altezza di 0 mantengono la dimensione del watermark:\n\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n## Qualsiasi altra opzione\n\n`command(key, [value], [priority], [escape])` aggiunge qualsiasi opzione del programma. Passa `true` come terzo argomento per mettere il valore tra virgolette:\n\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'Holiday 2024', true);\n```\n\nLe operazioni vengono ordinate per priorità prima che il comando venga costruito (prima il filtro di ridimensionamento di `filter()`, poi le dimensioni, gravity, ritaglio, qualità, rotazione ed effetti come `blur()`). `img.cmd(from, to)` restituisce la riga di comando senza eseguirla, il che aiuta durante il debug:\n\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n\n`img.clear()` rimuove tutte le operazioni, e `img.make(fn)` chiama `fn(img)` così puoi tenere un insieme di operazioni in una funzione.\n\n## Salvare, pipe e stream\n\n`save([filename], [callback])` scrive il risultato in un file. Il formato deriva dall'estensione del file di destinazione. Senza nome di file sovrascrive il file sorgente. La callback riceve `(err, success)`:\n\n```js\nImage.load(buffer).resize(400).save(PATH.public('upload/photo.jpg'), function(err, success) {\n\t// success === true\n});\n```\n\n`pipe(stream, [type], [options])` invia il risultato a uno stream scrivibile, ad esempio la risposta HTTP. `type` è il formato di output (`jpg`, `png`, `gif`, `webp`, `heic`…, altrimenti `img.type`); `options` va a `stream.pipe()`:\n\n```js\nfunction preview($) {\n\tvar img = Image.load(PATH.public('photos/' + $.params.id + '.jpg'));\n\timg.resize(300, 300);\n\t$.res.writeHead(200, { 'content-type': 'image/webp' });\n\timg.pipe($.res, 'webp');\n}\n```\n\n`writer([type])` avvia la conversione e restituisce lo stream di output leggibile:\n\n```js\nvar stream = Image.load(buffer).resize(100, 100).writer('png');\nstream.pipe(F.Fs.createWriteStream('/tmp/thumb.png'));\n```\n\nQuando un'immagine non ha operazioni, `save()`, `pipe()` e `writer()` aggiungono `minify()`, che rimuove i profili e i metadati.\n\nPer le risposte HTTP con cache, `$.image()` del controller è più breve (vedi [Controller](../../guides/controller/)).\n\n## Misurare un'immagine\n\nIl modulo legge la dimensione dall'header del file, senza il programma esterno:\n\n```js\nvar size = Image.measure('png', buffer);\n// { width: 800, height: 600 }\n\nImage.load(PATH.public('photos/beach.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n`Image.measure(type, buffer)` riconosce JPEG, PNG, GIF, WebP, SVG, BMP e PSD (come estensione o tipo MIME) e restituisce `undefined` per gli altri tipi. Per un JPEG il cui marcatore delle dimensioni non è nel buffer (un file danneggiato o troppo pochi dati), restituisce `null`. Il metodo `img.measure(callback)` legge i file con le estensioni `.jpg`, `.png`, `.gif` e `.webp`. I file caricati vengono misurati automaticamente, vedi `file.width` e `file.height` in [Controller](../../guides/controller/).\n\n## Middleware di post-elaborazione\n\n`Image.middleware(type, fn)` registra una funzione che restituisce uno stream di trasformazione. Ogni risultato di quel tipo passa attraverso di essa (per `save()` solo quando ha una callback), ad esempio per eseguire un ottimizzatore:\n\n```js\nImage.middleware('png', function() {\n\treturn new MyPngOptimizer(); // a Transform stream\n});\n```\n\nIl tipo è `img.type`: l'estensione della sorgente, oppure il valore di `output()`. Per `pipe()` e `writer()` è il formato di output.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwT65Ix61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/images/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Obrázky","summary":"Zmena veľkosti, orezanie, konverzia, vodoznak a meranie obrázkov pomocou GraphicsMagick alebo ImageMagick.","markdown":"---\ntitle: \"Obrázky\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/images/\nupdated: 2026-11-19T16:16:57.153Z\n---\n\n# Obrázky\n\n> Zmena veľkosti, orezanie, konverzia, vodoznak a meranie obrázkov pomocou GraphicsMagick alebo ImageMagick.\n\nTotal.js spracúva obrázky externým programom: **GraphicsMagick** (`gm`, predvolený) alebo **ImageMagick** (`convert` alebo `magick`). Framework sám pixely nemení. Objekt `Image` zbiera operácie, ktoré zavoláš, a zostaví z nich jeden príkazový riadok. Príkaz sa spustí, keď zavoláš `save()`, `pipe()` alebo `writer()`.\n\nNajprv nainštaluj program na server, napríklad `brew install graphicsmagick` alebo `apt-get install graphicsmagick`. Presná referencia každej metódy je v [Obrázky](../../reference/images/).\n\n## Načítanie obrázka\n\nGlobálny `Image` je modul obrázkov. `Image.load()` (aj `F.image()`) vytvorí objekt obrázka z názvu súboru, `Buffer` alebo streamu na čítanie:\n\n```js\nvar img = Image.load(PATH.public('photos/beach.jpg'));\nimg.resize(800, 600);\nimg.quality(85);\nimg.save(PATH.public('photos/beach-800.jpg'), function(err) {\n\tif (err)\n\t\tconsole.error(err);\n});\n```\n\n```js\n// From a Buffer or a stream\nvar img = Image.load(buffer);\nvar img2 = Image.load(F.Fs.createReadStream('/tmp/upload.png'));\n```\n\nTyp obrázka (`img.type`) vychádza z prípony názvu súboru. Pre `Buffer` alebo stream je to `jpg`; zmeň ho pomocou `img.output('png')`.\n\nMetódy vracajú objekt obrázka, takže ich môžeš reťaziť:\n\n```js\nImage.load(filename).resize(200, 200).grayscale().quality(80).save(target, callback);\n```\n\nObjekty obrázkov ti dávajú aj iné moduly: nahratý súbor má `file.image()` (pozri [Kontrolér](../../guides/controller/)), úložisko súborov má `fs.image(id)` (pozri [Úložisko súborov](../../guides/file-storage/)) a `$.image(opt)` spracuje obrázok a pošle ho ako odpoveď.\n\n## Výber programu\n\nKonfiguračný kľúč `$imageconverter` nastaví program pre všetky obrázky: `gm` (GraphicsMagick, predvolený), `im` (ImageMagick 6, príkaz `convert`) alebo `magick` (ImageMagick 7). Pozri [Konfigurácia](../../guides/configuration/).\n\n```\n$imageconverter : im\n```\n\nDruhý argument `Image.load()` ho zmení pre jeden obrázok:\n\n```js\nvar img = Image.load(filename, 'magick');\n```\n\n## Zmena veľkosti a orezanie\n\n| Metóda | Čo robí |\n| --- | --- |\n| `resize(w, h, [options])` | Zmení veľkosť do rámčeka `w`x`h` a zachová pomer strán. Jedna strana môže byť prázdna. `options` sa pripojí k veľkosti (`'!'`, `'^'`, `'>'`, `'<'`) a veľkosť môže byť percento, napríklad `'50%'` |\n| `thumbnail(w, h, [options])` | Ako `resize()`, ale navyše odstráni profily, pre malé náhľady |\n| `scale(w, h, [options])` | Rýchla zmena veľkosti bez filtrovania |\n| `crop(w, h, [x], [y])` | Vyreže oblasť `w`x`h` s posunom `x`, `y` |\n| `extent(w, h, [x], [y])` | Nastaví plátno na `w`x`h`; nová oblasť sa vyplní farbou pozadia |\n| `resizecenter(w, h, [color])` | Úplne vyplní rámček `w`x`h` a oreže stred |\n| `resizealign(w, h, [align], [color])` | Ako `resizecenter()`, ale oreže na zadanej strane |\n| `miniature(w, h, [color])` | Vloží obrázok do `w`x`h` a zvyšok vyplní farbou (biela) |\n\n```js\n// A square avatar, the face is usually at the top\nImage.load(filename).resizealign(200, 200, 'top').quality(90).save(target);\n\n// The whole photo inside 300x300, with a white border\nImage.load(filename).miniature(300, 300).save(target);\n```\n\n`align(type)` (alias `gravity()`) nastaví gravitáciu, ktorú používajú `crop()` a `extent()`. Prijíma `'top left'`, `'top'`, `'center'`, `'bottom right'`… a akýkoľvek názov gravitácie GraphicsMagick, napríklad `'NorthEast'`.\n\n## Úpravy a transformácie\n\n```js\nvar img = Image.load(filename);\nimg.rotate(90);           // degrees\nimg.flip();               // vertical mirror\nimg.flop();               // horizontal mirror\nimg.blur(3);\nimg.grayscale();\nimg.sepia();\nimg.normalize();\nimg.colors(16);           // reduce the palette\nimg.bitdepth(8);\nimg.quality(75);          // compression level, 80 when empty\nimg.save(target);\n```\n\n`background(color)` nastaví farbu pre nové oblasti (používajú ju `extent()`, `rotate()` a pomocníci na zmenu veľkosti), `fill(color)` nastaví farbu výplne, `filter(name)` filter zmeny veľkosti (`'Lanczos'`, `'Hamming'`…; platí pre každú zmenu veľkosti obrázka, v akomkoľvek poradí volaní) a `define(value)` odovzdá voľbu kodéru, napríklad `'jpeg:extent=200kb'`.\n\n## Vodoznaky\n\n`watermark(filename, x, y, w, h)` nakreslí cez obrázok iný obrázok. `x` a `y` sa merajú od ľavého horného rohu a šírka a výška 0 zachovajú veľkosť vodoznaku:\n\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n## Akákoľvek iná voľba\n\n`command(key, [value], [priority], [escape])` pridá akúkoľvek voľbu programu. Odovzdaj `true` ako tretí argument, ak chceš dať hodnotu do úvodzoviek:\n\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'Holiday 2024', true);\n```\n\nOperácie sa pred zostavením príkazu zoradia podľa priority (najprv filter zmeny veľkosti z `filter()`, potom veľkosti, gravitácia, orezanie, kvalita, rotácia a efekty ako `blur()`). `img.cmd(from, to)` vráti príkazový riadok bez jeho spustenia, čo pomáha pri ladení:\n\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n\n`img.clear()` odstráni všetky operácie a `img.make(fn)` zavolá `fn(img)`, takže si môžeš uchovať sadu operácií vo funkcii.\n\n## Uloženie, pipe a stream\n\n`save([filename], [callback])` zapíše výsledok do súboru. Formát vychádza z prípony cieľového súboru. Bez názvu súboru prepíše zdrojový súbor. Callback dostane `(err, success)`:\n\n```js\nImage.load(buffer).resize(400).save(PATH.public('upload/photo.jpg'), function(err, success) {\n\t// success === true\n});\n```\n\n`pipe(stream, [type], [options])` pošle výsledok do streamu na zápis, napríklad do HTTP odpovede. `type` je výstupný formát (`jpg`, `png`, `gif`, `webp`, `heic`…, inak `img.type`); `options` ide do `stream.pipe()`:\n\n```js\nfunction preview($) {\n\tvar img = Image.load(PATH.public('photos/' + $.params.id + '.jpg'));\n\timg.resize(300, 300);\n\t$.res.writeHead(200, { 'content-type': 'image/webp' });\n\timg.pipe($.res, 'webp');\n}\n```\n\n`writer([type])` spustí konverziu a vráti výstupný stream na čítanie:\n\n```js\nvar stream = Image.load(buffer).resize(100, 100).writer('png');\nstream.pipe(F.Fs.createWriteStream('/tmp/thumb.png'));\n```\n\nKeď obrázok nemá žiadne operácie, `save()`, `pipe()` a `writer()` pridajú `minify()`, ktorý odstráni profily a metadáta.\n\nPre HTTP odpovede s cache je kratší `$.image()` kontroléra (pozri [Kontrolér](../../guides/controller/)).\n\n## Meranie obrázka\n\nModul číta veľkosť z hlavičky súboru, bez externého programu:\n\n```js\nvar size = Image.measure('png', buffer);\n// { width: 800, height: 600 }\n\nImage.load(PATH.public('photos/beach.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n`Image.measure(type, buffer)` rozumie formátom JPEG, PNG, GIF, WebP, SVG, BMP a PSD (ako prípona alebo MIME typ) a pre ostatné typy vráti `undefined`. Pre JPEG, ktorého značka veľkosti nie je v bufferi (poškodený súbor alebo príliš málo dát), vráti `null`. Metóda `img.measure(callback)` číta súbory s príponami `.jpg`, `.png`, `.gif` a `.webp`. Nahraté súbory sa merajú automaticky, pozri `file.width` a `file.height` v [Kontrolér](../../guides/controller/).\n\n## Middleware na dodatočné spracovanie\n\n`Image.middleware(type, fn)` zaregistruje funkciu, ktorá vráti transformačný stream. Každý výsledok tohto typu ním prejde (pri `save()` len vtedy, keď má callback), napríklad aby sa spustil optimalizátor:\n\n```js\nImage.middleware('png', function() {\n\treturn new MyPngOptimizer(); // a Transform stream\n});\n```\n\nTyp je `img.type`: prípona zdroja alebo hodnota z `output()`. Pre `pipe()` a `writer()` je to výstupný formát.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:57.153Z"}
{"id":"JafwSd42x61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/ai-models/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"AI models","summary":"Register AI model handlers with NEWAIMODEL() and build chat requests with AIMODEL(): messages, config, callbacks, promises, streaming and tool calls.","markdown":"---\ntitle: AI models\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/ai-models/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# AI models\n\n> Register AI model handlers with NEWAIMODEL() and build chat requests with AIMODEL(): messages, config, callbacks, promises, streaming and tool calls.\n\nTotal.js 5 has a small layer for large language models in the `aimodel.js` module. It does not talk to any AI service by itself. You register a **model handler** with `NEWAIMODEL()` that knows how to call your provider (OpenAI, Ollama, Claude, Gemini or your own server), and the rest of the application builds requests with `AIMODEL()` without caring where the model runs.\n\n```js\n// definitions/ai.js\nNEWAIMODEL('assistant', function(ai, callback) {\n\t// ai.payload.model, ai.payload.messages, ai.config, ai.options.stream\n\tcallback(null, 'Hello from the model');\n});\n\n// anywhere in the application\nAIMODEL('assistant').user('Say hello').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nThe full list of functions, methods and properties is in the reference of [AI models](../../reference/ai-models/).\n\n## Registering a model\n\n`NEWAIMODEL(name, [config], handler)` stores the handler in `F.aimodels` under `name`. The name can contain several names separated by commas; each one gets the same handler and the same config. Registering a name again replaces the previous handler. Put the registrations in a file in `/definitions/` so they exist before the first request.\n\n```js\nNEWAIMODEL('gpt-4o-mini, gpt-4o', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...', temperature: 0.2 }, function(ai, callback) {\n\t// the same handler serves both models\n});\n```\n\nThe handler is called as `handler(ai, callback)`:\n\n- `ai` is the request object created by `AIMODEL()`. The handler reads `ai.payload` (what to send), `ai.config` (how to send it) and `ai.options.stream` (whether the caller wants a stream).\n- `callback(err, response)` ends the request. Whatever you pass as `response` reaches the caller unchanged, so you decide if it is a string, the parsed JSON of the provider or your own object.\n\nThe `config` object of `NEWAIMODEL()` holds defaults. Before the handler runs, every key of it that the request did not set with `ai.configure()` is copied into `ai.config`. This is the place for the URL, the token and default generation settings.\n\n## Building a request\n\n`AIMODEL(name)` returns a new request for the model `name`. Its methods return the request, so you chain them:\n\n| Method | What it does |\n| --- | --- |\n| `system(content, [merge])` | Adds a message with the role `system` |\n| `user(content, [merge])` | Adds a message with the role `user` |\n| `assistant(content, [merge])` | Adds a message with the role `assistant` |\n| `message(role, content, [merge])` | Adds a message with any role |\n| `prompt(content)` | Sets `payload.prompt`, for single-prompt endpoints |\n| `think()` | Sets `payload.think = true` |\n| `configure(obj)` | Copies the keys of `obj` into `ai.config` |\n| `tool(content)` | Adds a tool definition to `payload.tools` |\n\nThe messages are kept in `ai.payload.messages` as `{ role, content }` objects in the order you add them. When `content` is an object, its keys are copied into the message instead, so you can add fields like `images` or `tool_call_id`:\n\n```js\nAIMODEL('assistant')\n\t.system('You are a helpful assistant. Answer briefly.')\n\t.user('What is Total.js?')\n\t.assistant('A Node.js framework.')\n\t.user({ content: 'Describe this picture', images: [base64] })\n\t.configure({ temperature: 0 })\n\t.callback(console.log);\n```\n\n### Merging messages\n\nThe `merge` argument is a separator string. When it is set and a message with the same role already exists, the content is appended to the first such message, joined with the separator, instead of adding a new message. With object content, the keys are copied into that message. This is handy when you build the system instructions in several steps:\n\n```js\nvar ai = AIMODEL('assistant');\nai.system('You are a support agent.');\nai.system('Answer in English.', '\\n');\nai.system('Never share internal links.', '\\n');\n// one system message with three lines\n```\n\n## Running the request\n\nA request does not run when you create it. It runs when you call one of `callback()`, `stream()` or `promise()`. The run is delayed to the next turn of the event loop, so calling `stream()` and then `callback()` in the same chain runs the handler only once with both set.\n\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\tif (err)\n\t\tconsole.log('AI error:', err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n`promise([$])` wraps the callback in a Promise. An error rejects it with an `Error`. When you pass the `$` object of an action or a controller, an error is sent to `$.invalid(err)` instead and the promise does not settle, so the request ends with the error response:\n\n```js\nNEWACTION('Assistant/ask', {\n\tname: 'Ask the assistant',\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar response = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: response });\n\t}\n});\n```\n\nWhen no model with the name is registered, the callback receives the error `'AI model not found.'`.\n\n## Streaming\n\n`stream(fn)` stores `fn` in `ai.options.stream` and starts the request. The framework does not call `fn` itself: it is the handler that reads the answer of the provider piece by piece and calls `ai.options.stream()` with each piece. When the stream ends, the handler calls `callback()` as usual. A request started with `stream()` alone has no callback, so add `callback()` when you need to know the end.\n\n```js\nAIMODEL('assistant')\n\t.user('Write a short poem about Node.js')\n\t.stream(function(text) {\n\t\tprocess.stdout.write(text);\n\t})\n\t.callback(function(err) {\n\t\tconsole.log('\\nDone', err || '');\n\t});\n```\n\n## Tools\n\n`tool(content)` adds a tool definition to `ai.payload.tools`, an array that every request has. The framework does not check the content; the handler sends it to the provider in the format the provider expects. An inline schema can create the common function format for you with `schema.toAITool(name)` (see [JSON schemas](../../guides/json-schemas/#ai-tools)).\n\n```js\nvar weather = {\n\ttype: 'function',\n\tfunction: {\n\t\tname: 'weather',\n\t\tdescription: 'Returns the weather forecast for a city',\n\t\tparameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }\n\t}\n};\n\nAIMODEL('assistant')\n\t.user('What is the weather in Bratislava?')\n\t.tool(weather)\n\t.callback(console.log);\n```\n\nIn the handler, add the tools to the body when there are some:\n\n```js\nif (ai.payload.tools.length)\n\tbody.tools = ai.payload.tools;\n```\n\nWhen the model asks for a tool, run it and send the result back in a new request: add the assistant message with the tool call and a message with the role `tool` using `message('tool', { content: result, tool_call_id: id })`.\n\n## Parsing streams with AIPARSER()\n\n`AIPARSER(provider)` returns a stream parser that understands the streaming formats of the common providers. You write the raw chunks of the response into it and it collects the text, the reasoning (\"thinking\") and the tool calls, and emits events as they arrive.\n\n| Provider | Format |\n| --- | --- |\n| `ollama` | Ollama `/api/chat` and `/api/generate` (and its OpenAI-compatible endpoint) |\n| `openai`, `openai_chat` | OpenAI Chat Completions |\n| `openai_responses` | OpenAI Responses API |\n| `claude`, `anthropic` | Anthropic Messages |\n| `gemini`, `google` | Google Gemini |\n| anything else | A generic parser that reads `content`, `text`, `thinking`, `reasoning`, `message.*` and `tool_calls` |\n\n`parser.write(chunk)` takes a `Buffer`, a string, a `Uint8Array` or an `ArrayBuffer` with raw lines (newline-delimited JSON or server-sent events with `data:`), or an already parsed object. It returns the current output. `parser.end()` processes the rest of the buffer, emits `done` and returns the final output:\n\n```js\n{\n\tcontent: 'The text of the answer',\n\tthinking: 'The reasoning, if the model sends it',\n\ttools: [], // the tool calls: { id, name, arguments }\n\treasoning: 'content' // or 'thinking' or 'tool'\n}\n```\n\nThe events are `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments` and `done`; `*` listens to all of them. Each event object has `type` and the data of the event, for example `delta` (the new piece) and `content` (all text so far). With it, the streaming part of the handler becomes:\n\n```js\nvar parser = AIPARSER('openai');\n\nparser.on('content', function(e) {\n\tai.options.stream(e.delta);\n});\n\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\n\nvar output = parser.end();\ncallback(null, output);\n```\n\nThe parser does not depend on `AIMODEL()`, so you can also use it to read a stream that you requested yourself.\n\n## Tool calls in a stream\n\nThe parser collects the tool calls of every provider in the table above. OpenAI (`openai` and `openai_responses`) and Claude send the arguments of a call as pieces of JSON text; Ollama, Gemini and the generic parser send them whole. The parser joins the pieces of each call, and it keeps calls apart when they arrive in separate chunks: Ollama calls by their `index` (or `function.index`), and generic calls without an id by their arguments (an object is a complete call, a string is a piece of the call at the same position). The parser returns the calls with `parser.end()` in `output.tools`, with the arguments parsed:\n\n```js\nvar parser = AIPARSER('openai');\n\n// recorded server-sent events of an OpenAI Chat Completions stream\nvar chunks = [\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"index\":0,\"id\":\"call_A\",\"type\":\"function\",\"function\":{\"name\":\"weather\",\"arguments\":\"\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\\\"city\\\\\":\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\\\"Bratislava\\\\\"}\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\\n\\n',\n\t'data: [DONE]\\n\\n'\n];\n\nparser.on('tool_start', function(e) {\n\tconsole.log('calling', e.tool.name);\n});\n\nfor (var chunk of chunks)\n\tparser.write(chunk);\n\nvar output = parser.end();\nconsole.log(output.reasoning); // 'tool'\nconsole.log(output.tools);     // [{ id: 'call_A', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\nEach item of `output.tools` is `{ id, name, arguments }`. `id` is the id the provider gives the call (`call_...` for OpenAI, the `call_id` for the Responses API, `toolu_...` for Claude). Gemini calls without an id get `gemini_<candidate>_<part>`, and Ollama and generic calls without an id have `null`. `arguments` is an object when the joined text is valid JSON, the trimmed text when it is not (for example a stream that was cut off) and `{}` when it is empty. When there is at least one call, `output.reasoning` is `tool`.\n\nThree events follow a call while it streams. Each one has `e.tool`, a copy `{ id, name, arguments }` of the call with the arguments parsed so far:\n\n| Event | When |\n| --- | --- |\n| `tool_start` | A new call appears |\n| `tool_update` | More data of a known call arrives (before each further piece of its arguments) |\n| `tool_arguments` | A piece of the arguments arrives: `e.delta` is the piece and `e.arguments` all argument text so far (for providers that send the arguments whole, both are the object) |\n\nWith `openai_responses`, the events in the middle of a call carry the id of the output item (`fc_...`); the `call_id` is back in `e.tool.id` and in the output after the `response.output_item.done` event of the call.\n\nTo answer the model, run the tools and send the results in a new request, as described in the section Tools above. `parser.tools` holds the same calls while the stream runs.\n\n## A complete handler\n\nThis handler calls an OpenAI-compatible Chat Completions endpoint with the global `fetch()` of Node.js. It sends the messages, applies the config and, when the caller asked for a stream, parses the server-sent events with `AIPARSER()`.\n\n```js\nNEWAIMODEL('gpt-4o-mini', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...' }, function(ai, callback) {\n\n\tvar body = {};\n\tbody.model = ai.payload.model;\n\tbody.messages = ai.payload.messages;\n\n\tif (ai.config.temperature != null)\n\t\tbody.temperature = ai.config.temperature;\n\n\tif (ai.payload.tools.length)\n\t\tbody.tools = ai.payload.tools;\n\n\tif (ai.options.stream)\n\t\tbody.stream = true;\n\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + ai.config.token };\n\topt.body = JSON.stringify(body);\n\n\tfetch(ai.config.url, opt).then(async function(res) {\n\n\t\tif (!res.ok) {\n\t\t\tcallback('HTTP ' + res.status + ': ' + (await res.text()));\n\t\t\treturn;\n\t\t}\n\n\t\tif (!ai.options.stream) {\n\t\t\tvar json = await res.json();\n\t\t\tcallback(null, json.choices[0].message.content);\n\t\t\treturn;\n\t\t}\n\n\t\tvar parser = AIPARSER('openai');\n\t\tparser.on('content', function(e) {\n\t\t\tai.options.stream(e.delta);\n\t\t});\n\n\t\tfor await (var chunk of res.body)\n\t\t\tparser.write(Buffer.from(chunk));\n\n\t\tcallback(null, parser.end().content);\n\n\t}).catch(callback);\n});\n```\n\nThe same pattern works for Ollama: point `url` to `http://localhost:11434/api/chat`, read `json.message.content` instead of `json.choices[0].message.content` and use `AIPARSER('ollama')`. Because the handler gets the whole request object, it can also map `ai.payload.think` or `ai.payload.prompt` to the fields your provider expects.\n\n## Tips\n\n- Keep tokens in the [configuration](../../guides/configuration/) and pass them to `NEWAIMODEL()` as config, not in every request.\n- Register one name per use (`summarizer`, `translator`) and decide in the handler which real model it uses. The application code does not change when you switch providers.\n- `ai.payload` is a plain object. A handler can send it almost as it is to providers whose API takes `model` and `messages`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwSd42x61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/ai-models/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"KI-Modelle","summary":"KI-Modell-Handler mit NEWAIMODEL() registrieren und Chat-Anfragen mit AIMODEL() bauen: Nachrichten, Konfiguration, Callbacks, Promises, Streaming und Tool-Aufrufe.","markdown":"---\ntitle: KI-Modelle\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/ai-models/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# KI-Modelle\n\n> KI-Modell-Handler mit NEWAIMODEL() registrieren und Chat-Anfragen mit AIMODEL() bauen: Nachrichten, Konfiguration, Callbacks, Promises, Streaming und Tool-Aufrufe.\n\nTotal.js 5 hat im Modul `aimodel.js` eine kleine Schicht für große Sprachmodelle. Sie spricht selbst mit keinem KI-Dienst. Du registrierst mit `NEWAIMODEL()` einen **Modell-Handler**, der weiß, wie dein Anbieter aufgerufen wird (OpenAI, Ollama, Claude, Gemini oder dein eigener Server), und der Rest der Anwendung baut Anfragen mit `AIMODEL()`, ohne sich darum zu kümmern, wo das Modell läuft.\n\n```js\n// definitions/ai.js\nNEWAIMODEL('assistant', function(ai, callback) {\n\t// ai.payload.model, ai.payload.messages, ai.config, ai.options.stream\n\tcallback(null, 'Hello from the model');\n});\n\n// anywhere in the application\nAIMODEL('assistant').user('Say hello').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nDie vollständige Liste der Funktionen, Methoden und Eigenschaften steht in der Referenz der [KI-Modelle](../../reference/ai-models/).\n\n## Ein Modell registrieren\n\n`NEWAIMODEL(name, [config], handler)` speichert den Handler in `F.aimodels` unter `name`. Der Name kann mehrere durch Kommas getrennte Namen enthalten; jeder erhält denselben Handler und dieselbe Konfiguration. Wird ein Name erneut registriert, ersetzt das den vorherigen Handler. Lege die Registrierungen in eine Datei in `/definitions/`, damit sie vor der ersten Anfrage existieren.\n\n```js\nNEWAIMODEL('gpt-4o-mini, gpt-4o', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...', temperature: 0.2 }, function(ai, callback) {\n\t// the same handler serves both models\n});\n```\n\nDer Handler wird als `handler(ai, callback)` aufgerufen:\n\n- `ai` ist das von `AIMODEL()` erzeugte Anfrageobjekt. Der Handler liest `ai.payload` (was gesendet wird), `ai.config` (wie es gesendet wird) und `ai.options.stream` (ob der Aufrufer einen Stream möchte).\n- `callback(err, response)` beendet die Anfrage. Was du als `response` übergibst, erreicht den Aufrufer unverändert. Du entscheidest also, ob es ein String, das geparste JSON des Anbieters oder dein eigenes Objekt ist.\n\nDas `config`-Objekt von `NEWAIMODEL()` enthält Standardwerte. Bevor der Handler läuft, wird jeder seiner Schlüssel, den die Anfrage nicht mit `ai.configure()` gesetzt hat, in `ai.config` kopiert. Das ist der Ort für die URL, das Token und die Standardeinstellungen der Generierung.\n\n## Eine Anfrage bauen\n\n`AIMODEL(name)` gibt eine neue Anfrage für das Modell `name` zurück. Die Methoden dieser Anfrage geben die Anfrage zurück, daher verkettest du sie:\n\n| Methode | Was sie bewirkt |\n| --- | --- |\n| `system(content, [merge])` | Fügt eine Nachricht mit der Rolle `system` hinzu |\n| `user(content, [merge])` | Fügt eine Nachricht mit der Rolle `user` hinzu |\n| `assistant(content, [merge])` | Fügt eine Nachricht mit der Rolle `assistant` hinzu |\n| `message(role, content, [merge])` | Fügt eine Nachricht mit beliebiger Rolle hinzu |\n| `prompt(content)` | Setzt `payload.prompt`, für Endpunkte mit einem einzelnen Prompt |\n| `think()` | Setzt `payload.think = true` |\n| `configure(obj)` | Kopiert die Schlüssel von `obj` in `ai.config` |\n| `tool(content)` | Fügt `payload.tools` eine Tool-Definition hinzu |\n\nDie Nachrichten werden in `ai.payload.messages` als `{ role, content }`-Objekte in der Reihenfolge gehalten, in der du sie hinzufügst. Wenn `content` ein Objekt ist, werden stattdessen seine Schlüssel in die Nachricht kopiert. So kannst du Felder wie `images` oder `tool_call_id` hinzufügen:\n\n```js\nAIMODEL('assistant')\n\t.system('You are a helpful assistant. Answer briefly.')\n\t.user('What is Total.js?')\n\t.assistant('A Node.js framework.')\n\t.user({ content: 'Describe this picture', images: [base64] })\n\t.configure({ temperature: 0 })\n\t.callback(console.log);\n```\n\n### Nachrichten zusammenführen\n\nDas Argument `merge` ist ein Trennzeichen-String. Wenn es gesetzt ist und bereits eine Nachricht mit derselben Rolle existiert, wird der Inhalt an die erste solche Nachricht angehängt, verbunden mit dem Trennzeichen, statt eine neue Nachricht hinzuzufügen. Bei Objektinhalt werden die Schlüssel in diese Nachricht kopiert. Das ist praktisch, wenn du die Systemanweisungen in mehreren Schritten aufbaust:\n\n```js\nvar ai = AIMODEL('assistant');\nai.system('You are a support agent.');\nai.system('Answer in English.', '\\n');\nai.system('Never share internal links.', '\\n');\n// one system message with three lines\n```\n\n## Die Anfrage ausführen\n\nEine Anfrage läuft nicht, wenn du sie erzeugst. Sie läuft, wenn du `callback()`, `stream()` oder `promise()` aufrufst. Die Ausführung wird auf den nächsten Durchlauf der Event-Loop verschoben, daher führt ein Aufruf von `stream()` und danach `callback()` in derselben Kette den Handler nur einmal aus, mit beidem gesetzt.\n\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\tif (err)\n\t\tconsole.log('AI error:', err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n`promise([$])` verpackt den Callback in ein Promise. Ein Fehler lehnt es mit einem `Error` ab. Wenn du das `$`-Objekt einer Aktion oder eines Controllers übergibst, wird ein Fehler stattdessen an `$.invalid(err)` gesendet und das Promise wird nicht aufgelöst, sodass die Anfrage mit der Fehlerantwort endet:\n\n```js\nNEWACTION('Assistant/ask', {\n\tname: 'Ask the assistant',\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar response = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: response });\n\t}\n});\n```\n\nWenn kein Modell mit dem Namen registriert ist, erhält der Callback den Fehler `'AI model not found.'`.\n\n## Streaming\n\n`stream(fn)` speichert `fn` in `ai.options.stream` und startet die Anfrage. Das Framework ruft `fn` nicht selbst auf: Es ist der Handler, der die Antwort des Anbieters Stück für Stück liest und `ai.options.stream()` mit jedem Stück aufruft. Wenn der Stream endet, ruft der Handler wie üblich `callback()` auf. Eine nur mit `stream()` gestartete Anfrage hat keinen Callback. Füge also `callback()` hinzu, wenn du das Ende wissen musst.\n\n```js\nAIMODEL('assistant')\n\t.user('Write a short poem about Node.js')\n\t.stream(function(text) {\n\t\tprocess.stdout.write(text);\n\t})\n\t.callback(function(err) {\n\t\tconsole.log('\\nDone', err || '');\n\t});\n```\n\n## Tools\n\n`tool(content)` fügt eine Tool-Definition zu `ai.payload.tools` hinzu, einem Array, das jede Anfrage hat. Das Framework prüft den Inhalt nicht; der Handler sendet ihn in dem Format an den Anbieter, das dieser erwartet. Ein Inline-Schema kann mit `schema.toAITool(name)` das übliche Funktionsformat für dich erzeugen (siehe [JSON-Schemas](../../guides/json-schemas/#ai-tools)).\n\n```js\nvar weather = {\n\ttype: 'function',\n\tfunction: {\n\t\tname: 'weather',\n\t\tdescription: 'Returns the weather forecast for a city',\n\t\tparameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }\n\t}\n};\n\nAIMODEL('assistant')\n\t.user('What is the weather in Bratislava?')\n\t.tool(weather)\n\t.callback(console.log);\n```\n\nFüge im Handler die Tools dem Body hinzu, wenn es welche gibt:\n\n```js\nif (ai.payload.tools.length)\n\tbody.tools = ai.payload.tools;\n```\n\nWenn das Modell ein Tool anfordert, führe es aus und sende das Ergebnis in einer neuen Anfrage zurück: Füge die Assistant-Nachricht mit dem Tool-Aufruf hinzu und eine Nachricht mit der Rolle `tool` über `message('tool', { content: result, tool_call_id: id })`.\n\n## Streams mit AIPARSER() parsen\n\n`AIPARSER(provider)` gibt einen Stream-Parser zurück, der die Streaming-Formate der gängigen Anbieter versteht. Du schreibst die rohen Chunks der Antwort hinein, und er sammelt den Text, das Reasoning („Thinking“) und die Tool-Aufrufe und sendet Events, sobald sie eintreffen.\n\n| Anbieter | Format |\n| --- | --- |\n| `ollama` | Ollama `/api/chat` und `/api/generate` (und sein OpenAI-kompatibler Endpunkt) |\n| `openai`, `openai_chat` | OpenAI Chat Completions |\n| `openai_responses` | OpenAI Responses API |\n| `claude`, `anthropic` | Anthropic Messages |\n| `gemini`, `google` | Google Gemini |\n| alles andere | Ein generischer Parser, der `content`, `text`, `thinking`, `reasoning`, `message.*` und `tool_calls` liest |\n\n`parser.write(chunk)` nimmt einen `Buffer`, einen String, ein `Uint8Array` oder einen `ArrayBuffer` mit rohen Zeilen (zeilengetrenntes JSON oder Server-Sent Events mit `data:`) oder ein bereits geparstes Objekt. Es gibt die aktuelle Ausgabe zurück. `parser.end()` verarbeitet den Rest des Puffers, sendet `done` und gibt die endgültige Ausgabe zurück:\n\n```js\n{\n\tcontent: 'The text of the answer',\n\tthinking: 'The reasoning, if the model sends it',\n\ttools: [], // the tool calls: { id, name, arguments }\n\treasoning: 'content' // or 'thinking' or 'tool'\n}\n```\n\nDie Events sind `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments` und `done`; `*` hört auf alle. Jedes Event-Objekt hat `type` und die Daten des Events, zum Beispiel `delta` (das neue Stück) und `content` (der gesamte bisherige Text). Damit wird der Streaming-Teil des Handlers zu:\n\n```js\nvar parser = AIPARSER('openai');\n\nparser.on('content', function(e) {\n\tai.options.stream(e.delta);\n});\n\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\n\nvar output = parser.end();\ncallback(null, output);\n```\n\nDer Parser hängt nicht von `AIMODEL()` ab, daher kannst du ihn auch nutzen, um einen Stream zu lesen, den du selbst angefordert hast.\n\n## Tool-Aufrufe in einem Stream\n\nDer Parser sammelt die Tool-Aufrufe jedes Anbieters aus der Tabelle oben. OpenAI (`openai` und `openai_responses`) und Claude senden die Argumente eines Aufrufs als Stücke von JSON-Text; Ollama, Gemini und der generische Parser senden sie vollständig. Der Parser fügt die Stücke jedes Aufrufs zusammen und hält Aufrufe auseinander, wenn sie in getrennten Chunks ankommen: Ollama-Aufrufe anhand ihres `index` (oder `function.index`) und generische Aufrufe ohne id anhand ihrer Argumente (ein Objekt ist ein vollständiger Aufruf, ein String ist ein Stück des Aufrufs an derselben Position). Der Parser gibt die Aufrufe mit `parser.end()` in `output.tools` zurück, mit geparsten Argumenten:\n\n```js\nvar parser = AIPARSER('openai');\n\n// recorded server-sent events of an OpenAI Chat Completions stream\nvar chunks = [\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"index\":0,\"id\":\"call_A\",\"type\":\"function\",\"function\":{\"name\":\"weather\",\"arguments\":\"\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\\\"city\\\\\":\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\\\"Bratislava\\\\\"}\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\\n\\n',\n\t'data: [DONE]\\n\\n'\n];\n\nparser.on('tool_start', function(e) {\n\tconsole.log('calling', e.tool.name);\n});\n\nfor (var chunk of chunks)\n\tparser.write(chunk);\n\nvar output = parser.end();\nconsole.log(output.reasoning); // 'tool'\nconsole.log(output.tools);     // [{ id: 'call_A', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\nJedes Element von `output.tools` ist `{ id, name, arguments }`. `id` ist die ID, die der Anbieter dem Aufruf gibt (`call_...` bei OpenAI, die `call_id` bei der Responses API, `toolu_...` bei Claude). Gemini-Aufrufe ohne ID erhalten `gemini_<candidate>_<part>`, und Ollama- und generische Aufrufe ohne ID haben `null`. `arguments` ist ein Objekt, wenn der zusammengefügte Text gültiges JSON ist, der getrimmte Text, wenn nicht (zum Beispiel bei einem abgebrochenen Stream), und `{}`, wenn er leer ist. Wenn es mindestens einen Aufruf gibt, ist `output.reasoning` gleich `tool`.\n\nDrei Events begleiten einen Aufruf, während er gestreamt wird. Jedes hat `e.tool`, eine Kopie `{ id, name, arguments }` des Aufrufs mit den bisher geparsten Argumenten:\n\n| Event | Wann |\n| --- | --- |\n| `tool_start` | Ein neuer Aufruf erscheint |\n| `tool_update` | Weitere Daten eines bekannten Aufrufs treffen ein (vor jedem weiteren Stück seiner Argumente) |\n| `tool_arguments` | Ein Stück der Argumente trifft ein: `e.delta` ist das Stück und `e.arguments` der gesamte bisherige Argumenttext (bei Anbietern, die die Argumente vollständig senden, sind beide das Objekt) |\n\nBei `openai_responses` tragen die Events mitten in einem Aufruf die ID des Ausgabeelements (`fc_...`); die `call_id` steht wieder in `e.tool.id` und in der Ausgabe nach dem Event `response.output_item.done` des Aufrufs.\n\nUm dem Modell zu antworten, führe die Tools aus und sende die Ergebnisse in einer neuen Anfrage, wie im Abschnitt Tools oben beschrieben. `parser.tools` enthält dieselben Aufrufe, während der Stream läuft.\n\n## Ein vollständiger Handler\n\nDieser Handler ruft einen OpenAI-kompatiblen Chat-Completions-Endpunkt mit dem globalen `fetch()` von Node.js auf. Er sendet die Nachrichten, wendet die Konfiguration an und parst, wenn der Aufrufer einen Stream angefordert hat, die Server-Sent Events mit `AIPARSER()`.\n\n```js\nNEWAIMODEL('gpt-4o-mini', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...' }, function(ai, callback) {\n\n\tvar body = {};\n\tbody.model = ai.payload.model;\n\tbody.messages = ai.payload.messages;\n\n\tif (ai.config.temperature != null)\n\t\tbody.temperature = ai.config.temperature;\n\n\tif (ai.payload.tools.length)\n\t\tbody.tools = ai.payload.tools;\n\n\tif (ai.options.stream)\n\t\tbody.stream = true;\n\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + ai.config.token };\n\topt.body = JSON.stringify(body);\n\n\tfetch(ai.config.url, opt).then(async function(res) {\n\n\t\tif (!res.ok) {\n\t\t\tcallback('HTTP ' + res.status + ': ' + (await res.text()));\n\t\t\treturn;\n\t\t}\n\n\t\tif (!ai.options.stream) {\n\t\t\tvar json = await res.json();\n\t\t\tcallback(null, json.choices[0].message.content);\n\t\t\treturn;\n\t\t}\n\n\t\tvar parser = AIPARSER('openai');\n\t\tparser.on('content', function(e) {\n\t\t\tai.options.stream(e.delta);\n\t\t});\n\n\t\tfor await (var chunk of res.body)\n\t\t\tparser.write(Buffer.from(chunk));\n\n\t\tcallback(null, parser.end().content);\n\n\t}).catch(callback);\n});\n```\n\nDasselbe Muster funktioniert für Ollama: Richte `url` auf `http://localhost:11434/api/chat`, lies `json.message.content` statt `json.choices[0].message.content` und verwende `AIPARSER('ollama')`. Da der Handler das gesamte Anfrageobjekt erhält, kann er auch `ai.payload.think` oder `ai.payload.prompt` auf die Felder abbilden, die dein Anbieter erwartet.\n\n## Tipps\n\n- Halte Tokens in der [Konfiguration](../../guides/configuration/) und übergib sie `NEWAIMODEL()` als Konfiguration, nicht in jeder Anfrage.\n- Registriere einen Namen pro Verwendungszweck (`summarizer`, `translator`) und entscheide im Handler, welches echte Modell er nutzt. Der Anwendungscode ändert sich nicht, wenn du den Anbieter wechselst.\n- `ai.payload` ist ein einfaches Objekt. Ein Handler kann es fast unverändert an Anbieter senden, deren API `model` und `messages` entgegennimmt.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwSd42x61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/ai-models/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Modelos de IA","summary":"Registra handlers de modelos de IA con NEWAIMODEL() y construye peticiones de chat con AIMODEL(): mensajes, configuración, callbacks, promesas, streaming y llamadas a herramientas.","markdown":"---\ntitle: Modelos de IA\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/ai-models/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Modelos de IA\n\n> Registra handlers de modelos de IA con NEWAIMODEL() y construye peticiones de chat con AIMODEL(): mensajes, configuración, callbacks, promesas, streaming y llamadas a herramientas.\n\nTotal.js 5 tiene una pequeña capa para modelos de lenguaje grandes en el módulo `aimodel.js`. No se comunica por sí misma con ningún servicio de IA. Registras un **handler de modelo** con `NEWAIMODEL()` que sabe cómo llamar a tu proveedor (OpenAI, Ollama, Claude, Gemini o tu propio servidor), y el resto de la aplicación construye peticiones con `AIMODEL()` sin preocuparse de dónde se ejecuta el modelo.\n\n```js\n// definitions/ai.js\nNEWAIMODEL('assistant', function(ai, callback) {\n\t// ai.payload.model, ai.payload.messages, ai.config, ai.options.stream\n\tcallback(null, 'Hello from the model');\n});\n\n// anywhere in the application\nAIMODEL('assistant').user('Say hello').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nLa lista completa de funciones, métodos y propiedades está en la referencia de [Modelos de IA](../../reference/ai-models/).\n\n## Registrar un modelo\n\n`NEWAIMODEL(name, [config], handler)` guarda el handler en `F.aimodels` bajo `name`. El nombre puede contener varios nombres separados por comas; cada uno recibe el mismo handler y la misma configuración. Registrar un nombre otra vez reemplaza el handler anterior. Pon los registros en un archivo de `/definitions/` para que existan antes de la primera petición.\n\n```js\nNEWAIMODEL('gpt-4o-mini, gpt-4o', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...', temperature: 0.2 }, function(ai, callback) {\n\t// the same handler serves both models\n});\n```\n\nEl handler se llama como `handler(ai, callback)`:\n\n- `ai` es el objeto de petición creado por `AIMODEL()`. El handler lee `ai.payload` (qué enviar), `ai.config` (cómo enviarlo) y `ai.options.stream` (si quien llama quiere un stream).\n- `callback(err, response)` termina la petición. Lo que pases como `response` llega sin cambios a quien llama, así que tú decides si es un string, el JSON parseado del proveedor o tu propio objeto.\n\nEl objeto `config` de `NEWAIMODEL()` contiene valores por defecto. Antes de que se ejecute el handler, cada clave suya que la petición no estableció con `ai.configure()` se copia en `ai.config`. Este es el lugar para la URL, el token y los ajustes de generación por defecto.\n\n## Construir una petición\n\n`AIMODEL(name)` devuelve una nueva petición para el modelo `name`. Sus métodos devuelven la petición, así que los encadenas:\n\n| Método | Qué hace |\n| --- | --- |\n| `system(content, [merge])` | Añade un mensaje con el rol `system` |\n| `user(content, [merge])` | Añade un mensaje con el rol `user` |\n| `assistant(content, [merge])` | Añade un mensaje con el rol `assistant` |\n| `message(role, content, [merge])` | Añade un mensaje con cualquier rol |\n| `prompt(content)` | Establece `payload.prompt`, para endpoints de un solo prompt |\n| `think()` | Establece `payload.think = true` |\n| `configure(obj)` | Copia las claves de `obj` en `ai.config` |\n| `tool(content)` | Añade una definición de herramienta a `payload.tools` |\n\nLos mensajes se guardan en `ai.payload.messages` como objetos `{ role, content }` en el orden en que los añades. Cuando `content` es un objeto, sus claves se copian en el mensaje, así que puedes añadir campos como `images` o `tool_call_id`:\n\n```js\nAIMODEL('assistant')\n\t.system('You are a helpful assistant. Answer briefly.')\n\t.user('What is Total.js?')\n\t.assistant('A Node.js framework.')\n\t.user({ content: 'Describe this picture', images: [base64] })\n\t.configure({ temperature: 0 })\n\t.callback(console.log);\n```\n\n### Fusionar mensajes\n\nEl argumento `merge` es un string separador. Cuando está establecido y ya existe un mensaje con el mismo rol, el contenido se añade al primero de esos mensajes, unido con el separador, en lugar de añadir un mensaje nuevo. Con contenido de tipo objeto, las claves se copian en ese mensaje. Es útil cuando construyes las instrucciones del sistema en varios pasos:\n\n```js\nvar ai = AIMODEL('assistant');\nai.system('You are a support agent.');\nai.system('Answer in English.', '\\n');\nai.system('Never share internal links.', '\\n');\n// one system message with three lines\n```\n\n## Ejecutar la petición\n\nUna petición no se ejecuta al crearla. Se ejecuta cuando llamas a `callback()`, `stream()` o `promise()`. La ejecución se aplaza al siguiente ciclo del event loop, así que llamar a `stream()` y luego a `callback()` en la misma cadena ejecuta el handler solo una vez con ambos establecidos.\n\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\tif (err)\n\t\tconsole.log('AI error:', err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n`promise([$])` envuelve el callback en una Promise. Un error la rechaza con un `Error`. Cuando pasas el objeto `$` de una acción o de un controlador, el error se envía a `$.invalid(err)` y la promesa no se resuelve, así que la petición termina con la respuesta de error:\n\n```js\nNEWACTION('Assistant/ask', {\n\tname: 'Ask the assistant',\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar response = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: response });\n\t}\n});\n```\n\nCuando no hay ningún modelo registrado con ese nombre, el callback recibe el error `'AI model not found.'`.\n\n## Streaming\n\n`stream(fn)` guarda `fn` en `ai.options.stream` e inicia la petición. El framework no llama a `fn` por sí mismo: es el handler quien lee la respuesta del proveedor fragmento a fragmento y llama a `ai.options.stream()` con cada fragmento. Cuando el stream termina, el handler llama a `callback()` como siempre. Una petición iniciada solo con `stream()` no tiene callback, así que añade `callback()` cuando necesites saber cuándo termina.\n\n```js\nAIMODEL('assistant')\n\t.user('Write a short poem about Node.js')\n\t.stream(function(text) {\n\t\tprocess.stdout.write(text);\n\t})\n\t.callback(function(err) {\n\t\tconsole.log('\\nDone', err || '');\n\t});\n```\n\n## Herramientas\n\n`tool(content)` añade una definición de herramienta a `ai.payload.tools`, un array que tiene toda petición. El framework no comprueba el contenido; el handler lo envía al proveedor en el formato que este espera. Un esquema en línea puede crear por ti el formato de función común con `schema.toAITool(name)` (consulta [Esquemas JSON](../../guides/json-schemas/#ai-tools)).\n\n```js\nvar weather = {\n\ttype: 'function',\n\tfunction: {\n\t\tname: 'weather',\n\t\tdescription: 'Returns the weather forecast for a city',\n\t\tparameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }\n\t}\n};\n\nAIMODEL('assistant')\n\t.user('What is the weather in Bratislava?')\n\t.tool(weather)\n\t.callback(console.log);\n```\n\nEn el handler, añade las herramientas al cuerpo cuando las haya:\n\n```js\nif (ai.payload.tools.length)\n\tbody.tools = ai.payload.tools;\n```\n\nCuando el modelo pide una herramienta, ejecútala y envía el resultado en una nueva petición: añade el mensaje del asistente con la llamada a la herramienta y un mensaje con el rol `tool` usando `message('tool', { content: result, tool_call_id: id })`.\n\n## Parsear streams con AIPARSER()\n\n`AIPARSER(provider)` devuelve un parser de streams que entiende los formatos de streaming de los proveedores habituales. Escribes en él los fragmentos en bruto de la respuesta y recoge el texto, el razonamiento (\"thinking\") y las llamadas a herramientas, y emite eventos a medida que llegan.\n\n| Proveedor | Formato |\n| --- | --- |\n| `ollama` | Ollama `/api/chat` y `/api/generate` (y su endpoint compatible con OpenAI) |\n| `openai`, `openai_chat` | OpenAI Chat Completions |\n| `openai_responses` | OpenAI Responses API |\n| `claude`, `anthropic` | Anthropic Messages |\n| `gemini`, `google` | Google Gemini |\n| cualquier otro | Un parser genérico que lee `content`, `text`, `thinking`, `reasoning`, `message.*` y `tool_calls` |\n\n`parser.write(chunk)` acepta un `Buffer`, un string, un `Uint8Array` o un `ArrayBuffer` con líneas en bruto (JSON delimitado por saltos de línea o server-sent events con `data:`), o un objeto ya parseado. Devuelve la salida actual. `parser.end()` procesa el resto del buffer, emite `done` y devuelve la salida final:\n\n```js\n{\n\tcontent: 'The text of the answer',\n\tthinking: 'The reasoning, if the model sends it',\n\ttools: [], // the tool calls: { id, name, arguments }\n\treasoning: 'content' // or 'thinking' or 'tool'\n}\n```\n\nLos eventos son `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments` y `done`; `*` escucha todos ellos. Cada objeto de evento tiene `type` y los datos del evento, por ejemplo `delta` (el nuevo fragmento) y `content` (todo el texto hasta el momento). Con él, la parte de streaming del handler queda así:\n\n```js\nvar parser = AIPARSER('openai');\n\nparser.on('content', function(e) {\n\tai.options.stream(e.delta);\n});\n\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\n\nvar output = parser.end();\ncallback(null, output);\n```\n\nEl parser no depende de `AIMODEL()`, así que también puedes usarlo para leer un stream que hayas pedido tú mismo.\n\n## Llamadas a herramientas en un stream\n\nEl parser recoge las llamadas a herramientas de todos los proveedores de la tabla de arriba. OpenAI (`openai` y `openai_responses`) y Claude envían los argumentos de una llamada como fragmentos de texto JSON; Ollama, Gemini y el parser genérico los envían enteros. El parser une los fragmentos de cada llamada, y mantiene separadas las llamadas cuando llegan en fragmentos distintos: las llamadas de Ollama por su `index` (o `function.index`), y las llamadas genéricas sin id por sus argumentos (un objeto es una llamada completa, un string es un fragmento de la llamada en la misma posición). El parser devuelve las llamadas con `parser.end()` en `output.tools`, con los argumentos parseados:\n\n```js\nvar parser = AIPARSER('openai');\n\n// recorded server-sent events of an OpenAI Chat Completions stream\nvar chunks = [\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"index\":0,\"id\":\"call_A\",\"type\":\"function\",\"function\":{\"name\":\"weather\",\"arguments\":\"\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\\\"city\\\\\":\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\\\"Bratislava\\\\\"}\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\\n\\n',\n\t'data: [DONE]\\n\\n'\n];\n\nparser.on('tool_start', function(e) {\n\tconsole.log('calling', e.tool.name);\n});\n\nfor (var chunk of chunks)\n\tparser.write(chunk);\n\nvar output = parser.end();\nconsole.log(output.reasoning); // 'tool'\nconsole.log(output.tools);     // [{ id: 'call_A', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\nCada elemento de `output.tools` es `{ id, name, arguments }`. `id` es el id que el proveedor da a la llamada (`call_...` para OpenAI, el `call_id` para la Responses API, `toolu_...` para Claude). Las llamadas de Gemini sin id reciben `gemini_<candidate>_<part>`, y las llamadas de Ollama y genéricas sin id tienen `null`. `arguments` es un objeto cuando el texto unido es JSON válido, el texto recortado cuando no lo es (por ejemplo un stream que se cortó) y `{}` cuando está vacío. Cuando hay al menos una llamada, `output.reasoning` es `tool`.\n\nTres eventos siguen a una llamada mientras llega por el stream. Cada uno tiene `e.tool`, una copia `{ id, name, arguments }` de la llamada con los argumentos parseados hasta el momento:\n\n| Evento | Cuándo |\n| --- | --- |\n| `tool_start` | Aparece una llamada nueva |\n| `tool_update` | Llegan más datos de una llamada conocida (antes de cada nuevo fragmento de sus argumentos) |\n| `tool_arguments` | Llega un fragmento de los argumentos: `e.delta` es el fragmento y `e.arguments` todo el texto de los argumentos hasta el momento (para los proveedores que envían los argumentos enteros, ambos son el objeto) |\n\nCon `openai_responses`, los eventos en mitad de una llamada llevan el id del elemento de salida (`fc_...`); el `call_id` vuelve a estar en `e.tool.id` y en la salida después del evento `response.output_item.done` de la llamada.\n\nPara responder al modelo, ejecuta las herramientas y envía los resultados en una nueva petición, como se describe en la sección Herramientas de arriba. `parser.tools` contiene las mismas llamadas mientras se ejecuta el stream.\n\n## Un handler completo\n\nEste handler llama a un endpoint de Chat Completions compatible con OpenAI con el `fetch()` global de Node.js. Envía los mensajes, aplica la configuración y, cuando quien llama pidió un stream, parsea los server-sent events con `AIPARSER()`.\n\n```js\nNEWAIMODEL('gpt-4o-mini', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...' }, function(ai, callback) {\n\n\tvar body = {};\n\tbody.model = ai.payload.model;\n\tbody.messages = ai.payload.messages;\n\n\tif (ai.config.temperature != null)\n\t\tbody.temperature = ai.config.temperature;\n\n\tif (ai.payload.tools.length)\n\t\tbody.tools = ai.payload.tools;\n\n\tif (ai.options.stream)\n\t\tbody.stream = true;\n\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + ai.config.token };\n\topt.body = JSON.stringify(body);\n\n\tfetch(ai.config.url, opt).then(async function(res) {\n\n\t\tif (!res.ok) {\n\t\t\tcallback('HTTP ' + res.status + ': ' + (await res.text()));\n\t\t\treturn;\n\t\t}\n\n\t\tif (!ai.options.stream) {\n\t\t\tvar json = await res.json();\n\t\t\tcallback(null, json.choices[0].message.content);\n\t\t\treturn;\n\t\t}\n\n\t\tvar parser = AIPARSER('openai');\n\t\tparser.on('content', function(e) {\n\t\t\tai.options.stream(e.delta);\n\t\t});\n\n\t\tfor await (var chunk of res.body)\n\t\t\tparser.write(Buffer.from(chunk));\n\n\t\tcallback(null, parser.end().content);\n\n\t}).catch(callback);\n});\n```\n\nEl mismo patrón sirve para Ollama: apunta `url` a `http://localhost:11434/api/chat`, lee `json.message.content` en lugar de `json.choices[0].message.content` y usa `AIPARSER('ollama')`. Como el handler recibe el objeto de petición completo, también puede mapear `ai.payload.think` o `ai.payload.prompt` a los campos que espera tu proveedor.\n\n## Consejos\n\n- Guarda los tokens en la [configuración](../../guides/configuration/) y pásalos a `NEWAIMODEL()` como config, no en cada petición.\n- Registra un nombre por uso (`summarizer`, `translator`) y decide en el handler qué modelo real usa. El código de la aplicación no cambia cuando cambias de proveedor.\n- `ai.payload` es un objeto simple. Un handler puede enviarlo casi tal cual a proveedores cuya API acepta `model` y `messages`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwSd42x61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/ai-models/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Modèles d'IA","summary":"Enregistre des handlers de modèles IA avec NEWAIMODEL() et construis des requêtes de chat avec AIMODEL() : messages, configuration, callbacks, promesses, streaming et appels d'outils.","markdown":"---\ntitle: \"Modèles d'IA\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/ai-models/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Modèles d'IA\n\n> Enregistre des handlers de modèles IA avec NEWAIMODEL() et construis des requêtes de chat avec AIMODEL() : messages, configuration, callbacks, promesses, streaming et appels d'outils.\n\nTotal.js 5 dispose d'une petite couche pour les grands modèles de langage dans le module `aimodel.js`. Elle ne communique par elle-même avec aucun service d'IA. Tu enregistres avec `NEWAIMODEL()` un **handler de modèle** qui sait appeler ton fournisseur (OpenAI, Ollama, Claude, Gemini ou ton propre serveur), et le reste de l'application construit les requêtes avec `AIMODEL()` sans se soucier de l'endroit où tourne le modèle.\n\n```js\n// definitions/ai.js\nNEWAIMODEL('assistant', function(ai, callback) {\n\t// ai.payload.model, ai.payload.messages, ai.config, ai.options.stream\n\tcallback(null, 'Hello from the model');\n});\n\n// anywhere in the application\nAIMODEL('assistant').user('Say hello').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nLa liste complète des fonctions, méthodes et propriétés se trouve dans la référence des [Modèles IA](../../reference/ai-models/).\n\n## Enregistrer un modèle\n\n`NEWAIMODEL(name, [config], handler)` stocke le handler dans `F.aimodels` sous `name`. Le nom peut contenir plusieurs noms séparés par des virgules ; chacun reçoit le même handler et la même configuration. Enregistrer à nouveau un nom remplace le handler précédent. Place les enregistrements dans un fichier de `/definitions/` pour qu'ils existent avant la première requête.\n\n```js\nNEWAIMODEL('gpt-4o-mini, gpt-4o', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...', temperature: 0.2 }, function(ai, callback) {\n\t// the same handler serves both models\n});\n```\n\nLe handler est appelé sous la forme `handler(ai, callback)` :\n\n- `ai` est l'objet requête créé par `AIMODEL()`. Le handler lit `ai.payload` (quoi envoyer), `ai.config` (comment l'envoyer) et `ai.options.stream` (si l'appelant veut un stream).\n- `callback(err, response)` termine la requête. Ce que tu passes comme `response` arrive tel quel chez l'appelant : c'est donc toi qui décides s'il s'agit d'une chaîne, du JSON analysé du fournisseur ou de ton propre objet.\n\nL'objet `config` de `NEWAIMODEL()` contient des valeurs par défaut. Avant l'exécution du handler, chacune de ses clés que la requête n'a pas définie avec `ai.configure()` est copiée dans `ai.config`. C'est l'endroit idéal pour l'URL, le token et les paramètres de génération par défaut.\n\n## Construire une requête\n\n`AIMODEL(name)` renvoie une nouvelle requête pour le modèle `name`. Ses méthodes renvoient la requête, tu peux donc les chaîner :\n\n| Méthode | Ce qu'elle fait |\n| --- | --- |\n| `system(content, [merge])` | Ajoute un message avec le rôle `system` |\n| `user(content, [merge])` | Ajoute un message avec le rôle `user` |\n| `assistant(content, [merge])` | Ajoute un message avec le rôle `assistant` |\n| `message(role, content, [merge])` | Ajoute un message avec n'importe quel rôle |\n| `prompt(content)` | Définit `payload.prompt`, pour les endpoints à prompt unique |\n| `think()` | Définit `payload.think = true` |\n| `configure(obj)` | Copie les clés de `obj` dans `ai.config` |\n| `tool(content)` | Ajoute une définition d'outil à `payload.tools` |\n\nLes messages sont conservés dans `ai.payload.messages` sous forme d'objets `{ role, content }`, dans l'ordre où tu les ajoutes. Quand `content` est un objet, ses clés sont copiées dans le message à la place : tu peux ainsi ajouter des champs comme `images` ou `tool_call_id` :\n\n```js\nAIMODEL('assistant')\n\t.system('You are a helpful assistant. Answer briefly.')\n\t.user('What is Total.js?')\n\t.assistant('A Node.js framework.')\n\t.user({ content: 'Describe this picture', images: [base64] })\n\t.configure({ temperature: 0 })\n\t.callback(console.log);\n```\n\n### Fusionner des messages\n\nL'argument `merge` est une chaîne de séparation. Lorsqu'il est défini et qu'un message du même rôle existe déjà, le contenu est ajouté au premier de ces messages, joint avec le séparateur, au lieu d'ajouter un nouveau message. Avec un contenu objet, les clés sont copiées dans ce message. C'est pratique quand tu construis les instructions système en plusieurs étapes :\n\n```js\nvar ai = AIMODEL('assistant');\nai.system('You are a support agent.');\nai.system('Answer in English.', '\\n');\nai.system('Never share internal links.', '\\n');\n// one system message with three lines\n```\n\n## Exécuter la requête\n\nUne requête ne s'exécute pas à sa création. Elle s'exécute quand tu appelles `callback()`, `stream()` ou `promise()`. L'exécution est reportée au tour suivant de l'event loop : appeler `stream()` puis `callback()` dans la même chaîne n'exécute donc le handler qu'une seule fois, avec les deux définis.\n\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\tif (err)\n\t\tconsole.log('AI error:', err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n`promise([$])` enveloppe le callback dans une Promise. Une erreur la rejette avec une `Error`. Si tu passes l'objet `$` d'une action ou d'un contrôleur, l'erreur est envoyée à `$.invalid(err)` à la place et la promesse n'est pas résolue : la requête se termine donc avec la réponse d'erreur :\n\n```js\nNEWACTION('Assistant/ask', {\n\tname: 'Ask the assistant',\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar response = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: response });\n\t}\n});\n```\n\nQuand aucun modèle n'est enregistré sous ce nom, le callback reçoit l'erreur `'AI model not found.'`.\n\n## Streaming\n\n`stream(fn)` stocke `fn` dans `ai.options.stream` et démarre la requête. Le framework n'appelle pas `fn` lui-même : c'est le handler qui lit la réponse du fournisseur morceau par morceau et appelle `ai.options.stream()` avec chaque morceau. À la fin du stream, le handler appelle `callback()` comme d'habitude. Une requête démarrée avec `stream()` seul n'a pas de callback : ajoute donc `callback()` si tu as besoin de connaître la fin.\n\n```js\nAIMODEL('assistant')\n\t.user('Write a short poem about Node.js')\n\t.stream(function(text) {\n\t\tprocess.stdout.write(text);\n\t})\n\t.callback(function(err) {\n\t\tconsole.log('\\nDone', err || '');\n\t});\n```\n\n## Outils\n\n`tool(content)` ajoute une définition d'outil à `ai.payload.tools`, un tableau présent dans chaque requête. Le framework ne vérifie pas le contenu ; le handler l'envoie au fournisseur dans le format attendu par celui-ci. Un schéma en ligne peut créer pour toi le format de fonction courant avec `schema.toAITool(name)` (voir [Schémas JSON](../../guides/json-schemas/#ai-tools)).\n\n```js\nvar weather = {\n\ttype: 'function',\n\tfunction: {\n\t\tname: 'weather',\n\t\tdescription: 'Returns the weather forecast for a city',\n\t\tparameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }\n\t}\n};\n\nAIMODEL('assistant')\n\t.user('What is the weather in Bratislava?')\n\t.tool(weather)\n\t.callback(console.log);\n```\n\nDans le handler, ajoute les outils au corps lorsqu'il y en a :\n\n```js\nif (ai.payload.tools.length)\n\tbody.tools = ai.payload.tools;\n```\n\nQuand le modèle demande un outil, exécute-le et renvoie le résultat dans une nouvelle requête : ajoute le message assistant avec l'appel d'outil et un message avec le rôle `tool` en utilisant `message('tool', { content: result, tool_call_id: id })`.\n\n## Analyser des streams avec AIPARSER()\n\n`AIPARSER(provider)` renvoie un parser de stream qui comprend les formats de streaming des fournisseurs courants. Tu y écris les morceaux bruts de la réponse, et il collecte le texte, le raisonnement (« thinking ») et les appels d'outils, et émet des événements au fur et à mesure.\n\n| Fournisseur | Format |\n| --- | --- |\n| `ollama` | Ollama `/api/chat` et `/api/generate` (et son endpoint compatible OpenAI) |\n| `openai`, `openai_chat` | OpenAI Chat Completions |\n| `openai_responses` | OpenAI Responses API |\n| `claude`, `anthropic` | Anthropic Messages |\n| `gemini`, `google` | Google Gemini |\n| toute autre valeur | Un parser générique qui lit `content`, `text`, `thinking`, `reasoning`, `message.*` et `tool_calls` |\n\n`parser.write(chunk)` accepte un `Buffer`, une chaîne, un `Uint8Array` ou un `ArrayBuffer` avec des lignes brutes (JSON délimité par des retours à la ligne ou server-sent events avec `data:`), ou un objet déjà analysé. Il renvoie la sortie actuelle. `parser.end()` traite le reste du buffer, émet `done` et renvoie la sortie finale :\n\n```js\n{\n\tcontent: 'The text of the answer',\n\tthinking: 'The reasoning, if the model sends it',\n\ttools: [], // the tool calls: { id, name, arguments }\n\treasoning: 'content' // or 'thinking' or 'tool'\n}\n```\n\nLes événements sont `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments` et `done` ; `*` les écoute tous. Chaque objet événement a `type` et les données de l'événement, par exemple `delta` (le nouveau morceau) et `content` (tout le texte jusqu'à présent). Avec lui, la partie streaming du handler devient :\n\n```js\nvar parser = AIPARSER('openai');\n\nparser.on('content', function(e) {\n\tai.options.stream(e.delta);\n});\n\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\n\nvar output = parser.end();\ncallback(null, output);\n```\n\nLe parser ne dépend pas de `AIMODEL()` : tu peux donc aussi l'utiliser pour lire un stream que tu as demandé toi-même.\n\n## Appels d'outils dans un stream\n\nLe parser collecte les appels d'outils de chaque fournisseur du tableau ci-dessus. OpenAI (`openai` et `openai_responses`) et Claude envoient les arguments d'un appel sous forme de morceaux de texte JSON ; Ollama, Gemini et le parser générique les envoient en entier. Le parser assemble les morceaux de chaque appel et garde les appels séparés quand ils arrivent dans des chunks différents : les appels Ollama selon leur `index` (ou `function.index`), et les appels génériques sans id selon leurs arguments (un objet est un appel complet, une chaîne est un morceau de l'appel à la même position). Le parser renvoie les appels avec `parser.end()` dans `output.tools`, avec les arguments analysés :\n\n```js\nvar parser = AIPARSER('openai');\n\n// recorded server-sent events of an OpenAI Chat Completions stream\nvar chunks = [\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"index\":0,\"id\":\"call_A\",\"type\":\"function\",\"function\":{\"name\":\"weather\",\"arguments\":\"\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\\\"city\\\\\":\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\\\"Bratislava\\\\\"}\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\\n\\n',\n\t'data: [DONE]\\n\\n'\n];\n\nparser.on('tool_start', function(e) {\n\tconsole.log('calling', e.tool.name);\n});\n\nfor (var chunk of chunks)\n\tparser.write(chunk);\n\nvar output = parser.end();\nconsole.log(output.reasoning); // 'tool'\nconsole.log(output.tools);     // [{ id: 'call_A', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\nChaque élément de `output.tools` est `{ id, name, arguments }`. `id` est l'id que le fournisseur donne à l'appel (`call_...` pour OpenAI, le `call_id` pour l'API Responses, `toolu_...` pour Claude). Les appels Gemini sans id reçoivent `gemini_<candidate>_<part>`, et les appels Ollama et génériques sans id ont `null`. `arguments` est un objet quand le texte assemblé est du JSON valide, le texte débarrassé des espaces aux extrémités quand il ne l'est pas (par exemple un stream interrompu) et `{}` quand il est vide. Quand il y a au moins un appel, `output.reasoning` vaut `tool`.\n\nTrois événements suivent un appel pendant son streaming. Chacun a `e.tool`, une copie `{ id, name, arguments }` de l'appel avec les arguments analysés jusque-là :\n\n| Événement | Quand |\n| --- | --- |\n| `tool_start` | Un nouvel appel apparaît |\n| `tool_update` | D'autres données d'un appel connu arrivent (avant chaque nouveau morceau de ses arguments) |\n| `tool_arguments` | Un morceau des arguments arrive : `e.delta` est le morceau et `e.arguments` tout le texte des arguments jusque-là (pour les fournisseurs qui envoient les arguments en entier, les deux sont l'objet) |\n\nAvec `openai_responses`, les événements au milieu d'un appel portent l'id de l'élément de sortie (`fc_...`) ; le `call_id` revient dans `e.tool.id` et dans la sortie après l'événement `response.output_item.done` de l'appel.\n\nPour répondre au modèle, exécute les outils et envoie les résultats dans une nouvelle requête, comme décrit dans la section Outils ci-dessus. `parser.tools` contient les mêmes appels pendant que le stream s'exécute.\n\n## Un handler complet\n\nCe handler appelle un endpoint Chat Completions compatible OpenAI avec le `fetch()` global de Node.js. Il envoie les messages, applique la configuration et, quand l'appelant a demandé un stream, analyse les server-sent events avec `AIPARSER()`.\n\n```js\nNEWAIMODEL('gpt-4o-mini', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...' }, function(ai, callback) {\n\n\tvar body = {};\n\tbody.model = ai.payload.model;\n\tbody.messages = ai.payload.messages;\n\n\tif (ai.config.temperature != null)\n\t\tbody.temperature = ai.config.temperature;\n\n\tif (ai.payload.tools.length)\n\t\tbody.tools = ai.payload.tools;\n\n\tif (ai.options.stream)\n\t\tbody.stream = true;\n\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + ai.config.token };\n\topt.body = JSON.stringify(body);\n\n\tfetch(ai.config.url, opt).then(async function(res) {\n\n\t\tif (!res.ok) {\n\t\t\tcallback('HTTP ' + res.status + ': ' + (await res.text()));\n\t\t\treturn;\n\t\t}\n\n\t\tif (!ai.options.stream) {\n\t\t\tvar json = await res.json();\n\t\t\tcallback(null, json.choices[0].message.content);\n\t\t\treturn;\n\t\t}\n\n\t\tvar parser = AIPARSER('openai');\n\t\tparser.on('content', function(e) {\n\t\t\tai.options.stream(e.delta);\n\t\t});\n\n\t\tfor await (var chunk of res.body)\n\t\t\tparser.write(Buffer.from(chunk));\n\n\t\tcallback(null, parser.end().content);\n\n\t}).catch(callback);\n});\n```\n\nLe même principe fonctionne pour Ollama : fais pointer `url` vers `http://localhost:11434/api/chat`, lis `json.message.content` au lieu de `json.choices[0].message.content` et utilise `AIPARSER('ollama')`. Comme le handler reçoit l'objet requête complet, il peut aussi faire correspondre `ai.payload.think` ou `ai.payload.prompt` aux champs attendus par ton fournisseur.\n\n## Conseils\n\n- Garde les tokens dans la [configuration](../../guides/configuration/) et passe-les à `NEWAIMODEL()` comme configuration, pas dans chaque requête.\n- Enregistre un nom par usage (`summarizer`, `translator`) et décide dans le handler quel modèle réel il utilise. Le code de l'application ne change pas quand tu changes de fournisseur.\n- `ai.payload` est un objet simple. Un handler peut l'envoyer presque tel quel aux fournisseurs dont l'API accepte `model` et `messages`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwSd42x61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/ai-models/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Modelli AI","summary":"Registra handler di modelli AI con NEWAIMODEL() e costruisci richieste di chat con AIMODEL(): messaggi, configurazione, callback, promise, streaming e chiamate di tool.","markdown":"---\ntitle: Modelli AI\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/ai-models/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Modelli AI\n\n> Registra handler di modelli AI con NEWAIMODEL() e costruisci richieste di chat con AIMODEL(): messaggi, configurazione, callback, promise, streaming e chiamate di tool.\n\nTotal.js 5 ha un piccolo livello per i modelli linguistici di grandi dimensioni nel modulo `aimodel.js`. Da solo non comunica con nessun servizio AI. Registri un **handler di modello** con `NEWAIMODEL()` che sa come chiamare il tuo provider (OpenAI, Ollama, Claude, Gemini o un tuo server), e il resto dell'applicazione costruisce le richieste con `AIMODEL()` senza preoccuparsi di dove gira il modello.\n\n```js\n// definitions/ai.js\nNEWAIMODEL('assistant', function(ai, callback) {\n\t// ai.payload.model, ai.payload.messages, ai.config, ai.options.stream\n\tcallback(null, 'Hello from the model');\n});\n\n// anywhere in the application\nAIMODEL('assistant').user('Say hello').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nL'elenco completo di funzioni, metodi e proprietà è nel riferimento di [Modelli AI](../../reference/ai-models/).\n\n## Registrare un modello\n\n`NEWAIMODEL(name, [config], handler)` salva l'handler in `F.aimodels` sotto `name`. Il nome può contenere più nomi separati da virgole; ognuno riceve lo stesso handler e la stessa configurazione. Registrare di nuovo un nome sostituisce l'handler precedente. Metti le registrazioni in un file in `/definitions/`, così esistono prima della prima richiesta.\n\n```js\nNEWAIMODEL('gpt-4o-mini, gpt-4o', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...', temperature: 0.2 }, function(ai, callback) {\n\t// the same handler serves both models\n});\n```\n\nL'handler viene chiamato come `handler(ai, callback)`:\n\n- `ai` è l'oggetto richiesta creato da `AIMODEL()`. L'handler legge `ai.payload` (cosa inviare), `ai.config` (come inviarlo) e `ai.options.stream` (se il chiamante vuole uno stream).\n- `callback(err, response)` termina la richiesta. Qualunque cosa passi come `response` arriva invariata al chiamante, quindi decidi tu se è una stringa, il JSON analizzato del provider o un tuo oggetto.\n\nL'oggetto `config` di `NEWAIMODEL()` contiene i valori predefiniti. Prima che l'handler venga eseguito, ogni sua chiave che la richiesta non ha impostato con `ai.configure()` viene copiata in `ai.config`. È il posto giusto per l'URL, il token e le impostazioni di generazione predefinite.\n\n## Costruire una richiesta\n\n`AIMODEL(name)` restituisce una nuova richiesta per il modello `name`. I suoi metodi restituiscono la richiesta, quindi puoi concatenarli:\n\n| Metodo | Cosa fa |\n| --- | --- |\n| `system(content, [merge])` | Aggiunge un messaggio con il ruolo `system` |\n| `user(content, [merge])` | Aggiunge un messaggio con il ruolo `user` |\n| `assistant(content, [merge])` | Aggiunge un messaggio con il ruolo `assistant` |\n| `message(role, content, [merge])` | Aggiunge un messaggio con qualsiasi ruolo |\n| `prompt(content)` | Imposta `payload.prompt`, per endpoint a prompt singolo |\n| `think()` | Imposta `payload.think = true` |\n| `configure(obj)` | Copia le chiavi di `obj` in `ai.config` |\n| `tool(content)` | Aggiunge una definizione di tool a `payload.tools` |\n\nI messaggi sono conservati in `ai.payload.messages` come oggetti `{ role, content }` nell'ordine in cui li aggiungi. Quando `content` è un oggetto, le sue chiavi vengono invece copiate nel messaggio, così puoi aggiungere campi come `images` o `tool_call_id`:\n\n```js\nAIMODEL('assistant')\n\t.system('You are a helpful assistant. Answer briefly.')\n\t.user('What is Total.js?')\n\t.assistant('A Node.js framework.')\n\t.user({ content: 'Describe this picture', images: [base64] })\n\t.configure({ temperature: 0 })\n\t.callback(console.log);\n```\n\n### Unire i messaggi\n\nL'argomento `merge` è una stringa separatrice. Quando è impostato ed esiste già un messaggio con lo stesso ruolo, il contenuto viene accodato al primo di questi messaggi, unito con il separatore, invece di aggiungere un nuovo messaggio. Con un contenuto oggetto, le chiavi vengono copiate in quel messaggio. È comodo quando costruisci le istruzioni di sistema in più passaggi:\n\n```js\nvar ai = AIMODEL('assistant');\nai.system('You are a support agent.');\nai.system('Answer in English.', '\\n');\nai.system('Never share internal links.', '\\n');\n// one system message with three lines\n```\n\n## Eseguire la richiesta\n\nUna richiesta non viene eseguita quando la crei. Viene eseguita quando chiami uno tra `callback()`, `stream()` o `promise()`. L'esecuzione è rimandata al giro successivo dell'event loop, quindi chiamare `stream()` e poi `callback()` nella stessa catena esegue l'handler una sola volta con entrambi impostati.\n\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\tif (err)\n\t\tconsole.log('AI error:', err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n`promise([$])` avvolge la callback in una Promise. Un errore la rifiuta con un `Error`. Quando passi l'oggetto `$` di un'azione o di un controller, l'errore viene invece inviato a `$.invalid(err)` e la promise non si risolve, quindi la richiesta termina con la risposta di errore:\n\n```js\nNEWACTION('Assistant/ask', {\n\tname: 'Ask the assistant',\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar response = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: response });\n\t}\n});\n```\n\nQuando non è registrato nessun modello con quel nome, la callback riceve l'errore `'AI model not found.'`.\n\n## Streaming\n\n`stream(fn)` salva `fn` in `ai.options.stream` e avvia la richiesta. Il framework non chiama `fn` da solo: è l'handler che legge la risposta del provider pezzo per pezzo e chiama `ai.options.stream()` con ogni pezzo. Quando lo stream termina, l'handler chiama `callback()` come al solito. Una richiesta avviata solo con `stream()` non ha callback, quindi aggiungi `callback()` quando devi sapere quando finisce.\n\n```js\nAIMODEL('assistant')\n\t.user('Write a short poem about Node.js')\n\t.stream(function(text) {\n\t\tprocess.stdout.write(text);\n\t})\n\t.callback(function(err) {\n\t\tconsole.log('\\nDone', err || '');\n\t});\n```\n\n## Tool\n\n`tool(content)` aggiunge una definizione di tool a `ai.payload.tools`, un array presente in ogni richiesta. Il framework non verifica il contenuto; l'handler lo invia al provider nel formato che il provider si aspetta. Uno schema inline può creare per te il formato comune delle funzioni con `schema.toAITool(name)` (vedi [Schemi JSON](../../guides/json-schemas/#ai-tools)).\n\n```js\nvar weather = {\n\ttype: 'function',\n\tfunction: {\n\t\tname: 'weather',\n\t\tdescription: 'Returns the weather forecast for a city',\n\t\tparameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }\n\t}\n};\n\nAIMODEL('assistant')\n\t.user('What is the weather in Bratislava?')\n\t.tool(weather)\n\t.callback(console.log);\n```\n\nNell'handler, aggiungi i tool al body quando ce ne sono:\n\n```js\nif (ai.payload.tools.length)\n\tbody.tools = ai.payload.tools;\n```\n\nQuando il modello chiede un tool, eseguilo e rimanda il risultato in una nuova richiesta: aggiungi il messaggio dell'assistant con la chiamata del tool e un messaggio con il ruolo `tool` usando `message('tool', { content: result, tool_call_id: id })`.\n\n## Analizzare gli stream con AIPARSER()\n\n`AIPARSER(provider)` restituisce un parser di stream che comprende i formati di streaming dei provider più comuni. Ci scrivi i chunk grezzi della risposta e lui raccoglie il testo, il ragionamento (\"thinking\") e le chiamate di tool, ed emette eventi man mano che arrivano.\n\n| Provider | Formato |\n| --- | --- |\n| `ollama` | Ollama `/api/chat` e `/api/generate` (e il suo endpoint compatibile con OpenAI) |\n| `openai`, `openai_chat` | OpenAI Chat Completions |\n| `openai_responses` | OpenAI Responses API |\n| `claude`, `anthropic` | Anthropic Messages |\n| `gemini`, `google` | Google Gemini |\n| qualsiasi altro | Un parser generico che legge `content`, `text`, `thinking`, `reasoning`, `message.*` e `tool_calls` |\n\n`parser.write(chunk)` accetta un `Buffer`, una stringa, un `Uint8Array` o un `ArrayBuffer` con righe grezze (JSON delimitato da a capo o server-sent events con `data:`), oppure un oggetto già analizzato. Restituisce l'output attuale. `parser.end()` elabora il resto del buffer, emette `done` e restituisce l'output finale:\n\n```js\n{\n\tcontent: 'The text of the answer',\n\tthinking: 'The reasoning, if the model sends it',\n\ttools: [], // the tool calls: { id, name, arguments }\n\treasoning: 'content' // or 'thinking' or 'tool'\n}\n```\n\nGli eventi sono `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments` e `done`; `*` li ascolta tutti. Ogni oggetto evento ha `type` e i dati dell'evento, per esempio `delta` (il nuovo pezzo) e `content` (tutto il testo finora). Con il parser, la parte di streaming dell'handler diventa:\n\n```js\nvar parser = AIPARSER('openai');\n\nparser.on('content', function(e) {\n\tai.options.stream(e.delta);\n});\n\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\n\nvar output = parser.end();\ncallback(null, output);\n```\n\nIl parser non dipende da `AIMODEL()`, quindi puoi usarlo anche per leggere uno stream che hai richiesto tu stesso.\n\n## Chiamate di tool in uno stream\n\nIl parser raccoglie le chiamate di tool di ogni provider della tabella sopra. OpenAI (`openai` e `openai_responses`) e Claude inviano gli argomenti di una chiamata come pezzi di testo JSON; Ollama, Gemini e il parser generico li inviano interi. Il parser unisce i pezzi di ogni chiamata e tiene separate le chiamate quando arrivano in chunk diversi: le chiamate di Ollama in base al loro `index` (o `function.index`), e le chiamate generiche senza id in base ai loro argomenti (un oggetto è una chiamata completa, una stringa è un pezzo della chiamata nella stessa posizione). Il parser restituisce le chiamate con `parser.end()` in `output.tools`, con gli argomenti interpretati:\n\n```js\nvar parser = AIPARSER('openai');\n\n// recorded server-sent events of an OpenAI Chat Completions stream\nvar chunks = [\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"index\":0,\"id\":\"call_A\",\"type\":\"function\",\"function\":{\"name\":\"weather\",\"arguments\":\"\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\\\"city\\\\\":\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\\\"Bratislava\\\\\"}\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\\n\\n',\n\t'data: [DONE]\\n\\n'\n];\n\nparser.on('tool_start', function(e) {\n\tconsole.log('calling', e.tool.name);\n});\n\nfor (var chunk of chunks)\n\tparser.write(chunk);\n\nvar output = parser.end();\nconsole.log(output.reasoning); // 'tool'\nconsole.log(output.tools);     // [{ id: 'call_A', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\nOgni elemento di `output.tools` è `{ id, name, arguments }`. `id` è l'id che il provider dà alla chiamata (`call_...` per OpenAI, il `call_id` per la Responses API, `toolu_...` per Claude). Le chiamate di Gemini senza id ricevono `gemini_<candidate>_<part>`, e le chiamate di Ollama e generiche senza id hanno `null`. `arguments` è un oggetto quando il testo unito è JSON valido, il testo ripulito dagli spazi quando non lo è (per esempio uno stream interrotto) e `{}` quando è vuoto. Quando c'è almeno una chiamata, `output.reasoning` è `tool`.\n\nTre eventi seguono una chiamata mentre arriva in streaming. Ognuno ha `e.tool`, una copia `{ id, name, arguments }` della chiamata con gli argomenti interpretati fino a quel momento:\n\n| Evento | Quando |\n| --- | --- |\n| `tool_start` | Compare una nuova chiamata |\n| `tool_update` | Arrivano altri dati di una chiamata nota (prima di ogni ulteriore pezzo dei suoi argomenti) |\n| `tool_arguments` | Arriva un pezzo degli argomenti: `e.delta` è il pezzo e `e.arguments` tutto il testo degli argomenti fino a quel momento (per i provider che inviano gli argomenti interi, entrambi sono l'oggetto) |\n\nCon `openai_responses`, gli eventi a metà di una chiamata portano l'id dell'elemento di output (`fc_...`); il `call_id` torna in `e.tool.id` e nell'output dopo l'evento `response.output_item.done` della chiamata.\n\nPer rispondere al modello, esegui i tool e invia i risultati in una nuova richiesta, come descritto nella sezione Tool sopra. `parser.tools` contiene le stesse chiamate mentre lo stream è in corso.\n\n## Un handler completo\n\nQuesto handler chiama un endpoint Chat Completions compatibile con OpenAI con il `fetch()` globale di Node.js. Invia i messaggi, applica la configurazione e, quando il chiamante ha chiesto uno stream, analizza i server-sent events con `AIPARSER()`.\n\n```js\nNEWAIMODEL('gpt-4o-mini', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...' }, function(ai, callback) {\n\n\tvar body = {};\n\tbody.model = ai.payload.model;\n\tbody.messages = ai.payload.messages;\n\n\tif (ai.config.temperature != null)\n\t\tbody.temperature = ai.config.temperature;\n\n\tif (ai.payload.tools.length)\n\t\tbody.tools = ai.payload.tools;\n\n\tif (ai.options.stream)\n\t\tbody.stream = true;\n\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + ai.config.token };\n\topt.body = JSON.stringify(body);\n\n\tfetch(ai.config.url, opt).then(async function(res) {\n\n\t\tif (!res.ok) {\n\t\t\tcallback('HTTP ' + res.status + ': ' + (await res.text()));\n\t\t\treturn;\n\t\t}\n\n\t\tif (!ai.options.stream) {\n\t\t\tvar json = await res.json();\n\t\t\tcallback(null, json.choices[0].message.content);\n\t\t\treturn;\n\t\t}\n\n\t\tvar parser = AIPARSER('openai');\n\t\tparser.on('content', function(e) {\n\t\t\tai.options.stream(e.delta);\n\t\t});\n\n\t\tfor await (var chunk of res.body)\n\t\t\tparser.write(Buffer.from(chunk));\n\n\t\tcallback(null, parser.end().content);\n\n\t}).catch(callback);\n});\n```\n\nLo stesso schema funziona per Ollama: punta `url` a `http://localhost:11434/api/chat`, leggi `json.message.content` invece di `json.choices[0].message.content` e usa `AIPARSER('ollama')`. Poiché l'handler riceve l'intero oggetto richiesta, può anche mappare `ai.payload.think` o `ai.payload.prompt` sui campi che il tuo provider si aspetta.\n\n## Suggerimenti\n\n- Tieni i token nella [configurazione](../../guides/configuration/) e passali a `NEWAIMODEL()` come config, non in ogni richiesta.\n- Registra un nome per ogni uso (`summarizer`, `translator`) e decidi nell'handler quale modello reale usare. Il codice dell'applicazione non cambia quando cambi provider.\n- `ai.payload` è un semplice oggetto. Un handler può inviarlo quasi così com'è ai provider la cui API accetta `model` e `messages`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwSd42x61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/ai-models/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"AI modely","summary":"Registrácia handlerov AI modelov cez NEWAIMODEL() a zostavovanie chat požiadaviek cez AIMODEL(): správy, konfigurácia, callbacky, promisy, streamovanie a volania nástrojov.","markdown":"---\ntitle: AI modely\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/ai-models/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# AI modely\n\n> Registrácia handlerov AI modelov cez NEWAIMODEL() a zostavovanie chat požiadaviek cez AIMODEL(): správy, konfigurácia, callbacky, promisy, streamovanie a volania nástrojov.\n\nTotal.js 5 má v module `aimodel.js` malú vrstvu pre veľké jazykové modely. Sama nekomunikuje so žiadnou AI službou. Zaregistruješ **handler modelu** cez `NEWAIMODEL()`, ktorý vie zavolať tvojho poskytovateľa (OpenAI, Ollama, Claude, Gemini alebo vlastný server), a zvyšok aplikácie zostavuje požiadavky cez `AIMODEL()` bez ohľadu na to, kde model beží.\n\n```js\n// definitions/ai.js\nNEWAIMODEL('assistant', function(ai, callback) {\n\t// ai.payload.model, ai.payload.messages, ai.config, ai.options.stream\n\tcallback(null, 'Hello from the model');\n});\n\n// anywhere in the application\nAIMODEL('assistant').user('Say hello').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nÚplný zoznam funkcií, metód a vlastností nájdeš v referencii [AI modely](../../reference/ai-models/).\n\n## Registrácia modelu\n\n`NEWAIMODEL(name, [config], handler)` uloží handler do `F.aimodels` pod `name`. Názov môže obsahovať viac názvov oddelených čiarkami; každý dostane rovnaký handler a rovnakú konfiguráciu. Opätovná registrácia názvu nahradí predchádzajúci handler. Registrácie daj do súboru v `/definitions/`, aby existovali pred prvou požiadavkou.\n\n```js\nNEWAIMODEL('gpt-4o-mini, gpt-4o', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...', temperature: 0.2 }, function(ai, callback) {\n\t// the same handler serves both models\n});\n```\n\nHandler sa volá ako `handler(ai, callback)`:\n\n- `ai` je objekt požiadavky vytvorený cez `AIMODEL()`. Handler číta `ai.payload` (čo poslať), `ai.config` (ako to poslať) a `ai.options.stream` (či volajúci chce stream).\n- `callback(err, response)` ukončí požiadavku. Čokoľvek odovzdáš ako `response`, dostane sa k volajúcemu nezmenené, takže ty rozhoduješ, či je to reťazec, sparsovaný JSON poskytovateľa alebo vlastný objekt.\n\nObjekt `config` v `NEWAIMODEL()` obsahuje predvolené hodnoty. Pred spustením handlera sa každý jeho kľúč, ktorý požiadavka nenastavila cez `ai.configure()`, skopíruje do `ai.config`. To je miesto pre URL, token a predvolené nastavenia generovania.\n\n## Zostavenie požiadavky\n\n`AIMODEL(name)` vráti novú požiadavku pre model `name`. Jej metódy vracajú požiadavku, takže ich reťazíš:\n\n| Metóda | Čo robí |\n| --- | --- |\n| `system(content, [merge])` | Pridá správu s rolou `system` |\n| `user(content, [merge])` | Pridá správu s rolou `user` |\n| `assistant(content, [merge])` | Pridá správu s rolou `assistant` |\n| `message(role, content, [merge])` | Pridá správu s ľubovoľnou rolou |\n| `prompt(content)` | Nastaví `payload.prompt` pre endpointy s jedným promptom |\n| `think()` | Nastaví `payload.think = true` |\n| `configure(obj)` | Skopíruje kľúče `obj` do `ai.config` |\n| `tool(content)` | Pridá definíciu nástroja do `payload.tools` |\n\nSprávy sa uchovávajú v `ai.payload.messages` ako objekty `{ role, content }` v poradí, v akom ich pridáš. Keď je `content` objekt, do správy sa namiesto toho skopírujú jeho kľúče, takže môžeš pridať polia ako `images` alebo `tool_call_id`:\n\n```js\nAIMODEL('assistant')\n\t.system('You are a helpful assistant. Answer briefly.')\n\t.user('What is Total.js?')\n\t.assistant('A Node.js framework.')\n\t.user({ content: 'Describe this picture', images: [base64] })\n\t.configure({ temperature: 0 })\n\t.callback(console.log);\n```\n\n### Zlučovanie správ\n\nArgument `merge` je reťazec oddeľovača. Keď je nastavený a správa s rovnakou rolou už existuje, obsah sa pripojí k prvej takej správe, spojený oddeľovačom, namiesto pridania novej správy. Pri objektovom obsahu sa kľúče skopírujú do tejto správy. Hodí sa to, keď systémové inštrukcie zostavuješ v niekoľkých krokoch:\n\n```js\nvar ai = AIMODEL('assistant');\nai.system('You are a support agent.');\nai.system('Answer in English.', '\\n');\nai.system('Never share internal links.', '\\n');\n// one system message with three lines\n```\n\n## Spustenie požiadavky\n\nPožiadavka sa nespustí pri vytvorení. Spustí sa, keď zavoláš jednu z metód `callback()`, `stream()` alebo `promise()`. Spustenie sa odloží na ďalšie kolo event loopu, takže zavolanie `stream()` a potom `callback()` v tom istom reťazci spustí handler iba raz s oboma nastavenými.\n\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\tif (err)\n\t\tconsole.log('AI error:', err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n`promise([$])` zabalí callback do Promise. Chyba ho zamietne s `Error`. Keď odovzdáš objekt `$` akcie alebo controllera, chyba sa namiesto toho pošle do `$.invalid(err)` a promise sa nevyrieši, takže požiadavka skončí chybovou odpoveďou:\n\n```js\nNEWACTION('Assistant/ask', {\n\tname: 'Ask the assistant',\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar response = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: response });\n\t}\n});\n```\n\nKeď nie je zaregistrovaný žiadny model s daným názvom, callback dostane chybu `'AI model not found.'`.\n\n## Streamovanie\n\n`stream(fn)` uloží `fn` do `ai.options.stream` a spustí požiadavku. Framework `fn` sám nevolá: je to handler, kto číta odpoveď poskytovateľa po častiach a s každou časťou volá `ai.options.stream()`. Keď stream skončí, handler zavolá `callback()` ako zvyčajne. Požiadavka spustená iba cez `stream()` nemá callback, takže pridaj `callback()`, keď potrebuješ vedieť o konci.\n\n```js\nAIMODEL('assistant')\n\t.user('Write a short poem about Node.js')\n\t.stream(function(text) {\n\t\tprocess.stdout.write(text);\n\t})\n\t.callback(function(err) {\n\t\tconsole.log('\\nDone', err || '');\n\t});\n```\n\n## Nástroje\n\n`tool(content)` pridá definíciu nástroja do `ai.payload.tools`, poľa, ktoré má každá požiadavka. Framework obsah nekontroluje; handler ho pošle poskytovateľovi vo formáte, ktorý poskytovateľ očakáva. Inline schéma ti môže vytvoriť bežný formát funkcie cez `schema.toAITool(name)` (pozri [JSON schémy](../../guides/json-schemas/#ai-tools)).\n\n```js\nvar weather = {\n\ttype: 'function',\n\tfunction: {\n\t\tname: 'weather',\n\t\tdescription: 'Returns the weather forecast for a city',\n\t\tparameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }\n\t}\n};\n\nAIMODEL('assistant')\n\t.user('What is the weather in Bratislava?')\n\t.tool(weather)\n\t.callback(console.log);\n```\n\nV handleri pridaj nástroje do tela, keď nejaké sú:\n\n```js\nif (ai.payload.tools.length)\n\tbody.tools = ai.payload.tools;\n```\n\nKeď model požiada o nástroj, spusti ho a pošli výsledok späť v novej požiadavke: pridaj správu assistant s volaním nástroja a správu s rolou `tool` cez `message('tool', { content: result, tool_call_id: id })`.\n\n## Parsovanie streamov cez AIPARSER()\n\n`AIPARSER(provider)` vráti stream parser, ktorý rozumie streamovacím formátom bežných poskytovateľov. Zapisuješ doň surové časti odpovede a on zbiera text, uvažovanie („thinking“) a volania nástrojov a vysiela udalosti, ako prichádzajú.\n\n| Poskytovateľ | Formát |\n| --- | --- |\n| `ollama` | Ollama `/api/chat` a `/api/generate` (a jeho endpoint kompatibilný s OpenAI) |\n| `openai`, `openai_chat` | OpenAI Chat Completions |\n| `openai_responses` | OpenAI Responses API |\n| `claude`, `anthropic` | Anthropic Messages |\n| `gemini`, `google` | Google Gemini |\n| čokoľvek iné | Všeobecný parser, ktorý číta `content`, `text`, `thinking`, `reasoning`, `message.*` a `tool_calls` |\n\n`parser.write(chunk)` prijíma `Buffer`, reťazec, `Uint8Array` alebo `ArrayBuffer` so surovými riadkami (JSON oddelený novými riadkami alebo server-sent events s `data:`), alebo už sparsovaný objekt. Vráti aktuálny výstup. `parser.end()` spracuje zvyšok buffera, vyšle `done` a vráti konečný výstup:\n\n```js\n{\n\tcontent: 'The text of the answer',\n\tthinking: 'The reasoning, if the model sends it',\n\ttools: [], // the tool calls: { id, name, arguments }\n\treasoning: 'content' // or 'thinking' or 'tool'\n}\n```\n\nUdalosti sú `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments` a `done`; `*` počúva všetky. Každý objekt udalosti má `type` a dáta udalosti, napríklad `delta` (nová časť) a `content` (celý doterajší text). Vďaka nemu sa streamovacia časť handlera zmení na:\n\n```js\nvar parser = AIPARSER('openai');\n\nparser.on('content', function(e) {\n\tai.options.stream(e.delta);\n});\n\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\n\nvar output = parser.end();\ncallback(null, output);\n```\n\nParser nezávisí od `AIMODEL()`, takže ho môžeš použiť aj na čítanie streamu, ktorý si vyžiadal sám.\n\n## Volania nástrojov v streame\n\nParser zbiera volania nástrojov každého poskytovateľa z tabuľky vyššie. OpenAI (`openai` a `openai_responses`) a Claude posielajú argumenty volania ako kúsky JSON textu; Ollama, Gemini a generický parser ich posielajú celé. Parser spojí kúsky každého volania a drží volania oddelene, keď prídu v samostatných chunkoch: volania Ollama podľa ich `index` (alebo `function.index`) a generické volania bez id podľa ich argumentov (objekt je celé volanie, reťazec je kúsok volania na tej istej pozícii). Parser vráti volania cez `parser.end()` v `output.tools` so sparsovanými argumentmi:\n\n```js\nvar parser = AIPARSER('openai');\n\n// recorded server-sent events of an OpenAI Chat Completions stream\nvar chunks = [\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"tool_calls\":[{\"index\":0,\"id\":\"call_A\",\"type\":\"function\",\"function\":{\"name\":\"weather\",\"arguments\":\"\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\\\"city\\\\\":\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\\\"Bratislava\\\\\"}\"}}]}}]}\\n\\n',\n\t'data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\\n\\n',\n\t'data: [DONE]\\n\\n'\n];\n\nparser.on('tool_start', function(e) {\n\tconsole.log('calling', e.tool.name);\n});\n\nfor (var chunk of chunks)\n\tparser.write(chunk);\n\nvar output = parser.end();\nconsole.log(output.reasoning); // 'tool'\nconsole.log(output.tools);     // [{ id: 'call_A', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\nKaždá položka `output.tools` je `{ id, name, arguments }`. `id` je id, ktoré volaniu dá poskytovateľ (`call_...` pre OpenAI, `call_id` pre Responses API, `toolu_...` pre Claude). Volania Gemini bez id dostanú `gemini_<candidate>_<part>` a volania Ollama a generické volania bez id majú `null`. `arguments` je objekt, keď je spojený text platný JSON, orezaný text, keď nie je (napríklad stream, ktorý bol prerušený), a `{}`, keď je prázdny. Keď existuje aspoň jedno volanie, `output.reasoning` je `tool`.\n\nVolanie počas streamovania sledujú tri udalosti. Každá má `e.tool`, kópiu `{ id, name, arguments }` volania s doteraz sparsovanými argumentmi:\n\n| Udalosť | Kedy |\n| --- | --- |\n| `tool_start` | Objaví sa nové volanie |\n| `tool_update` | Prídu ďalšie dáta známeho volania (pred každým ďalším kúskom jeho argumentov) |\n| `tool_arguments` | Príde kúsok argumentov: `e.delta` je kúsok a `e.arguments` celý doterajší text argumentov (pri poskytovateľoch, ktorí posielajú argumenty celé, sú obe objekt) |\n\nS `openai_responses` nesú udalosti uprostred volania id výstupnej položky (`fc_...`); `call_id` je späť v `e.tool.id` a vo výstupe po udalosti `response.output_item.done` volania.\n\nAby si modelu odpovedal, spusti nástroje a pošli výsledky v novej požiadavke, ako je opísané v sekcii Nástroje vyššie. `parser.tools` drží tie isté volania, kým stream beží.\n\n## Kompletný handler\n\nTento handler volá endpoint Chat Completions kompatibilný s OpenAI cez globálny `fetch()` z Node.js. Pošle správy, aplikuje konfiguráciu a keď volajúci požiadal o stream, sparsuje server-sent events cez `AIPARSER()`.\n\n```js\nNEWAIMODEL('gpt-4o-mini', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...' }, function(ai, callback) {\n\n\tvar body = {};\n\tbody.model = ai.payload.model;\n\tbody.messages = ai.payload.messages;\n\n\tif (ai.config.temperature != null)\n\t\tbody.temperature = ai.config.temperature;\n\n\tif (ai.payload.tools.length)\n\t\tbody.tools = ai.payload.tools;\n\n\tif (ai.options.stream)\n\t\tbody.stream = true;\n\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + ai.config.token };\n\topt.body = JSON.stringify(body);\n\n\tfetch(ai.config.url, opt).then(async function(res) {\n\n\t\tif (!res.ok) {\n\t\t\tcallback('HTTP ' + res.status + ': ' + (await res.text()));\n\t\t\treturn;\n\t\t}\n\n\t\tif (!ai.options.stream) {\n\t\t\tvar json = await res.json();\n\t\t\tcallback(null, json.choices[0].message.content);\n\t\t\treturn;\n\t\t}\n\n\t\tvar parser = AIPARSER('openai');\n\t\tparser.on('content', function(e) {\n\t\t\tai.options.stream(e.delta);\n\t\t});\n\n\t\tfor await (var chunk of res.body)\n\t\t\tparser.write(Buffer.from(chunk));\n\n\t\tcallback(null, parser.end().content);\n\n\t}).catch(callback);\n});\n```\n\nRovnaký vzor funguje pre Ollama: nastav `url` na `http://localhost:11434/api/chat`, čítaj `json.message.content` namiesto `json.choices[0].message.content` a použi `AIPARSER('ollama')`. Keďže handler dostane celý objekt požiadavky, môže tiež namapovať `ai.payload.think` alebo `ai.payload.prompt` na polia, ktoré tvoj poskytovateľ očakáva.\n\n## Tipy\n\n- Tokeny drž v [konfigurácii](../../guides/configuration/) a odovzdávaj ich do `NEWAIMODEL()` ako konfiguráciu, nie v každej požiadavke.\n- Zaregistruj jeden názov na jedno použitie (`summarizer`, `translator`) a v handleri rozhodni, ktorý skutočný model použije. Kód aplikácie sa pri zmene poskytovateľa nemení.\n- `ai.payload` je obyčajný objekt. Handler ho môže poslať takmer bez zmeny poskytovateľom, ktorých API prijíma `model` a `messages`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwwlDnx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/proxy/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Proxy","summary":"Forward requests with PROXY(), and publish an app of a private network through a public Total.js app with PROXYSERVER() and PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/proxy/\nupdated: 2026-11-16T16:36:31.083Z\n---\n\n# Proxy\n\n> Forward requests with PROXY(), and publish an app of a private network through a public Total.js app with PROXYSERVER() and PROXYCLIENT().\n\n`PROXY(path, target)` forwards requests to another HTTP server or a Unix socket. It is part of the routing and described in [Routing](../routing/#proxies).\n\n### Publishing a local app through a public server\n\n`PROXYSERVER()` and `PROXYCLIENT()` make an app running on your computer (or in a private network) reachable through a public Total.js app. The public app runs the server part, the private machine runs the client part, and the two talk over one binary WebSocket that the client opens. Every HTTP request that arrives at the server is sent through the WebSocket to the client, the client calls the local app and sends the response back.\n\n```js\n// The public app\nPROXYSERVER('/', '/$proxy/');\n```\n\n```js\n// The private machine (any Total.js app, or a small script)\nPROXYCLIENT('https://public.example.com/$proxy/', '127.0.0.1:8000');\n```\n\n`PROXYSERVER(endpoint, socketendpoint)` forwards all requests that start with `endpoint` and listens for the client at `socketendpoint`. Only one client can be connected; until it connects, requests get `400` with `Not yet available.`. The local request gets the header `x-proxy: Total.js` and the `host` of the local app. When the request to the local app fails (the app does not run or closes the connection), the visitor gets an empty response with the status `200`. Both functions write their activity to the console; pass your own function as the last argument to log elsewhere.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:31.083Z"}
{"id":"JafwwlDnx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/proxy/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Proxy","summary":"Leite Requests mit PROXY() weiter und mache eine App aus einem privaten Netz über eine öffentliche Total.js-App mit PROXYSERVER() und PROXYCLIENT() erreichbar.","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/proxy/\nupdated: 2026-11-16T16:36:31.083Z\n---\n\n# Proxy\n\n> Leite Requests mit PROXY() weiter und mache eine App aus einem privaten Netz über eine öffentliche Total.js-App mit PROXYSERVER() und PROXYCLIENT() erreichbar.\n\n`PROXY(path, target)` leitet Anfragen an einen anderen HTTP-Server oder einen Unix-Socket weiter. Es ist Teil des Routings und in [Routing](../routing/#proxies) beschrieben.\n\n### Eine lokale Anwendung über einen öffentlichen Server veröffentlichen\n\n`PROXYSERVER()` und `PROXYCLIENT()` machen eine Anwendung, die auf deinem Computer (oder in einem privaten Netzwerk) läuft, über eine öffentliche Total.js-Anwendung erreichbar. Die öffentliche Anwendung führt den Serverteil aus, der private Rechner den Clientteil, und beide kommunizieren über einen binären WebSocket, den der Client öffnet. Jede HTTP-Anfrage, die beim Server eintrifft, wird über den WebSocket an den Client gesendet; der Client ruft die lokale Anwendung auf und sendet die Antwort zurück.\n\n```js\n// The public app\nPROXYSERVER('/', '/$proxy/');\n```\n\n```js\n// The private machine (any Total.js app, or a small script)\nPROXYCLIENT('https://public.example.com/$proxy/', '127.0.0.1:8000');\n```\n\n`PROXYSERVER(endpoint, socketendpoint)` leitet alle Anfragen weiter, die mit `endpoint` beginnen, und wartet unter `socketendpoint` auf den Client. Nur ein Client kann verbunden sein; bis er sich verbindet, erhalten Anfragen `400` mit `Not yet available.`. Die lokale Anfrage erhält den Header `x-proxy: Total.js` und den `host` der lokalen Anwendung. Wenn die Anfrage an die lokale Anwendung fehlschlägt (die Anwendung läuft nicht oder schließt die Verbindung), erhält der Besucher eine leere Antwort mit dem Status `200`. Beide Funktionen schreiben ihre Aktivität in die Konsole; übergib als letztes Argument eine eigene Funktion, um woanders zu loggen.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:31.083Z"}
{"id":"JafwwlDnx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/proxy/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Proxy","summary":"Reenvía peticiones con PROXY() y publica una app de una red privada a través de una app Total.js pública con PROXYSERVER() y PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/proxy/\nupdated: 2026-11-16T16:36:31.083Z\n---\n\n# Proxy\n\n> Reenvía peticiones con PROXY() y publica una app de una red privada a través de una app Total.js pública con PROXYSERVER() y PROXYCLIENT().\n\n`PROXY(path, target)` reenvía peticiones a otro servidor HTTP o a un socket Unix. Forma parte del enrutamiento y se describe en [Enrutamiento](../routing/#proxies).\n\n### Publicar una aplicación local a través de un servidor público\n\n`PROXYSERVER()` y `PROXYCLIENT()` hacen accesible una aplicación que se ejecuta en tu ordenador (o en una red privada) a través de una aplicación pública de Total.js. La aplicación pública ejecuta la parte del servidor, la máquina privada ejecuta la parte del cliente, y ambas se comunican por un único WebSocket binario que abre el cliente. Cada petición HTTP que llega al servidor se envía por el WebSocket al cliente; el cliente llama a la aplicación local y devuelve la respuesta.\n\n```js\n// The public app\nPROXYSERVER('/', '/$proxy/');\n```\n\n```js\n// The private machine (any Total.js app, or a small script)\nPROXYCLIENT('https://public.example.com/$proxy/', '127.0.0.1:8000');\n```\n\n`PROXYSERVER(endpoint, socketendpoint)` reenvía todas las peticiones que empiezan por `endpoint` y espera al cliente en `socketendpoint`. Solo puede haber un cliente conectado; hasta que se conecta, las peticiones reciben `400` con `Not yet available.`. La petición local recibe la cabecera `x-proxy: Total.js` y el `host` de la aplicación local. Cuando la petición a la aplicación local falla (la aplicación no se está ejecutando o cierra la conexión), el visitante recibe una respuesta vacía con el estado `200`. Ambas funciones escriben su actividad en la consola; pasa tu propia función como último argumento para registrarla en otro lugar.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:31.083Z"}
{"id":"JafwwlDnx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/proxy/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Proxy","summary":"Transmets des requêtes avec PROXY() et publie une app d'un réseau privé à travers une app Total.js publique avec PROXYSERVER() et PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/proxy/\nupdated: 2026-11-16T16:36:31.083Z\n---\n\n# Proxy\n\n> Transmets des requêtes avec PROXY() et publie une app d'un réseau privé à travers une app Total.js publique avec PROXYSERVER() et PROXYCLIENT().\n\n`PROXY(path, target)` transmet les requêtes à un autre serveur HTTP ou à un socket Unix. Il fait partie du routage et est décrit dans [Routage](../routing/#proxies).\n\n### Publier une application locale via un serveur public\n\n`PROXYSERVER()` et `PROXYCLIENT()` rendent une application qui tourne sur ton ordinateur (ou dans un réseau privé) accessible via une application Total.js publique. L'application publique exécute la partie serveur, la machine privée exécute la partie client, et les deux communiquent par un seul WebSocket binaire ouvert par le client. Chaque requête HTTP qui arrive au serveur est envoyée par le WebSocket au client ; le client appelle l'application locale et renvoie la réponse.\n\n```js\n// The public app\nPROXYSERVER('/', '/$proxy/');\n```\n\n```js\n// The private machine (any Total.js app, or a small script)\nPROXYCLIENT('https://public.example.com/$proxy/', '127.0.0.1:8000');\n```\n\n`PROXYSERVER(endpoint, socketendpoint)` transmet toutes les requêtes qui commencent par `endpoint` et attend le client sur `socketendpoint`. Un seul client peut être connecté ; tant qu'il n'est pas connecté, les requêtes reçoivent `400` avec `Not yet available.`. La requête locale reçoit l'en-tête `x-proxy: Total.js` et le `host` de l'application locale. Quand la requête vers l'application locale échoue (l'application ne tourne pas ou ferme la connexion), le visiteur reçoit une réponse vide avec le statut `200`. Les deux fonctions écrivent leur activité dans la console ; passe ta propre fonction comme dernier argument pour journaliser ailleurs.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:31.083Z"}
{"id":"JafwwlDnx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/proxy/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Proxy","summary":"Inoltra le richieste con PROXY() e pubblica un'app di una rete privata tramite un'app Total.js pubblica con PROXYSERVER() e PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/proxy/\nupdated: 2026-11-16T16:36:31.083Z\n---\n\n# Proxy\n\n> Inoltra le richieste con PROXY() e pubblica un'app di una rete privata tramite un'app Total.js pubblica con PROXYSERVER() e PROXYCLIENT().\n\n`PROXY(path, target)` inoltra le richieste a un altro server HTTP o a un socket Unix. Fa parte del routing ed è descritto in [Routing](../routing/#proxies).\n\n### Pubblicare un'app locale tramite un server pubblico\n\n`PROXYSERVER()` e `PROXYCLIENT()` rendono un'app in esecuzione sul tuo computer (o in una rete privata) raggiungibile tramite un'app Total.js pubblica. L'app pubblica esegue la parte server, la macchina privata esegue la parte client, e le due comunicano tramite un unico WebSocket binario aperto dal client. Ogni richiesta HTTP che arriva al server viene inviata attraverso il WebSocket al client, il client chiama l'app locale e rimanda indietro la risposta.\n\n```js\n// The public app\nPROXYSERVER('/', '/$proxy/');\n```\n\n```js\n// The private machine (any Total.js app, or a small script)\nPROXYCLIENT('https://public.example.com/$proxy/', '127.0.0.1:8000');\n```\n\n`PROXYSERVER(endpoint, socketendpoint)` inoltra tutte le richieste che iniziano con `endpoint` e attende il client su `socketendpoint`. Può essere collegato un solo client; finché non si collega, le richieste ricevono `400` con `Not yet available.`. La richiesta locale riceve l'header `x-proxy: Total.js` e l'`host` dell'app locale. Quando la richiesta all'app locale fallisce (l'app non è in esecuzione o chiude la connessione), il visitatore riceve una risposta vuota con lo stato `200`. Entrambe le funzioni scrivono la loro attività nella console; passa una tua funzione come ultimo argomento per registrarla altrove.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:31.083Z"}
{"id":"JafwwlDnx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/proxy/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Proxy","summary":"Preposielaj požiadavky cez PROXY() a sprístupni aplikáciu zo súkromnej siete cez verejnú aplikáciu Total.js pomocou PROXYSERVER() a PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/proxy/\nupdated: 2026-11-16T16:36:31.083Z\n---\n\n# Proxy\n\n> Preposielaj požiadavky cez PROXY() a sprístupni aplikáciu zo súkromnej siete cez verejnú aplikáciu Total.js pomocou PROXYSERVER() a PROXYCLIENT().\n\n`PROXY(path, target)` preposiela požiadavky na iný HTTP server alebo Unix socket. Je súčasťou routingu a je opísaná v [Routing](../routing/#proxies).\n\n### Zverejnenie lokálnej aplikácie cez verejný server\n\n`PROXYSERVER()` a `PROXYCLIENT()` sprístupnia aplikáciu bežiacu na tvojom počítači (alebo v privátnej sieti) cez verejnú Total.js aplikáciu. Verejná aplikácia spúšťa serverovú časť, privátny stroj klientsku časť a obe komunikujú cez jeden binárny WebSocket, ktorý otvorí klient. Každá HTTP požiadavka, ktorá príde na server, sa cez WebSocket pošle klientovi, klient zavolá lokálnu aplikáciu a pošle odpoveď späť.\n\n```js\n// The public app\nPROXYSERVER('/', '/$proxy/');\n```\n\n```js\n// The private machine (any Total.js app, or a small script)\nPROXYCLIENT('https://public.example.com/$proxy/', '127.0.0.1:8000');\n```\n\n`PROXYSERVER(endpoint, socketendpoint)` preposiela všetky požiadavky, ktoré začínajú `endpoint`, a čaká na klienta na `socketendpoint`. Pripojený môže byť iba jeden klient; kým sa nepripojí, požiadavky dostávajú `400` s `Not yet available.`. Lokálna požiadavka dostane hlavičku `x-proxy: Total.js` a `host` lokálnej aplikácie. Keď požiadavka na lokálnu aplikáciu zlyhá (aplikácia nebeží alebo zatvorí spojenie), návštevník dostane prázdnu odpoveď so stavom `200`. Obe funkcie zapisujú svoju činnosť do konzoly; ak chceš logovať inam, odovzdaj ako posledný argument vlastnú funkciu.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:31.083Z"}
{"id":"Jafwuh6Mx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/ldap/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"LDAP","summary":"Read users and groups from an LDAP server such as Active Directory with LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/ldap/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# LDAP\n\n> Read users and groups from an LDAP server such as Active Directory with LDAP().\n\n`LDAP(options, [callback])` reads users or groups from an LDAP server such as Active Directory. It binds with a user and a password, runs one search and returns the entries. Without a callback it returns a promise.\n\n```js\nvar users = await LDAP({\n\tldap: { host: 'ad.example.com', port: 389 },\n\tuser: 'CN=reader,CN=Users,DC=example,DC=com',\n\tpassword: CONF.ldap_password,\n\tdn: 'CN=Users,DC=example,DC=com',\n\ttype: 'person'\n});\n\n// [{ cn: 'Peter', mail: 'peter@example.com', memberOf: ['CN=Admins,...', ...], ... }]\n```\n\nEach entry is an object with the attributes of the entry. A single value is a string, several values are an array of strings, and `objectGUID` and `objectSid` are hex strings. `type` is the `objectClass` to search for (`person`, `group`...).\n\nTo read one account, use `type: 'profile'` with `login` (the `sAMAccountName`); the result is one object or `null`. Without `dn` the function binds as `user` and returns the entry of that user, which is a simple way to check a login:\n\n```js\nvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n```\n\n`ldap.secure: true` connects with TLS (set the port, usually `636`) and `ldap.timeout` limits the connection time in milliseconds. `noauth: true` skips the bind.\n\nAttributes are text by default. The `attributes` option tells how to read the others, for example a photo:\n\n```js\nvar profile = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'peter@example.com',\n\tpassword: password,\n\tattributes: { thumbnailPhoto: 'buffer', employeeNumber: 'number', whenCreated: 'date' }\n});\n```\n\nThe types are `string`, `number`, `date`, `buffer` (or `binary`) and the encodings `hex`, `base64`, `ascii` and `utf8`.\n\nA refused bind (a wrong user or password) is an error: the text of the server, or `LDAP bind error 49` when the server sends no text. The error is a string:\n\n```js\ntry {\n\tvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n} catch (err) {\n\t// 'LDAP bind error 49' or the text of the server\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"Jafwuh6Mx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/ldap/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"LDAP","summary":"Lies Benutzer und Gruppen aus einem LDAP-Server wie Active Directory mit LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/ldap/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# LDAP\n\n> Lies Benutzer und Gruppen aus einem LDAP-Server wie Active Directory mit LDAP().\n\n`LDAP(options, [callback])` liest Benutzer oder Gruppen von einem LDAP-Server wie Active Directory. Es bindet sich mit einem Benutzer und einem Passwort, führt eine Suche aus und gibt die Einträge zurück. Ohne Callback gibt es ein Promise zurück.\n\n```js\nvar users = await LDAP({\n\tldap: { host: 'ad.example.com', port: 389 },\n\tuser: 'CN=reader,CN=Users,DC=example,DC=com',\n\tpassword: CONF.ldap_password,\n\tdn: 'CN=Users,DC=example,DC=com',\n\ttype: 'person'\n});\n\n// [{ cn: 'Peter', mail: 'peter@example.com', memberOf: ['CN=Admins,...', ...], ... }]\n```\n\nJeder Eintrag ist ein Objekt mit den Attributen des Eintrags. Ein einzelner Wert ist ein String, mehrere Werte sind ein Array von Strings, und `objectGUID` und `objectSid` sind Hex-Strings. `type` ist die zu suchende `objectClass` (`person`, `group`...).\n\nUm ein einzelnes Konto zu lesen, verwende `type: 'profile'` mit `login` (dem `sAMAccountName`); das Ergebnis ist ein Objekt oder `null`. Ohne `dn` bindet sich die Funktion als `user` und gibt den Eintrag dieses Benutzers zurück. Das ist eine einfache Möglichkeit, eine Anmeldung zu prüfen:\n\n```js\nvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n```\n\n`ldap.secure: true` verbindet sich mit TLS (setze den Port, meist `636`), und `ldap.timeout` begrenzt die Verbindungszeit in Millisekunden. `noauth: true` überspringt das Binden.\n\nAttribute sind standardmäßig Text. Die Option `attributes` gibt an, wie die anderen gelesen werden, zum Beispiel ein Foto:\n\n```js\nvar profile = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'peter@example.com',\n\tpassword: password,\n\tattributes: { thumbnailPhoto: 'buffer', employeeNumber: 'number', whenCreated: 'date' }\n});\n```\n\nDie Typen sind `string`, `number`, `date`, `buffer` (oder `binary`) und die Kodierungen `hex`, `base64`, `ascii` und `utf8`.\n\nEine abgelehnte Bind-Anfrage (ein falscher Benutzer oder ein falsches Passwort) ist ein Fehler: der Text des Servers oder `LDAP bind error 49`, wenn der Server keinen Text sendet. Der Fehler ist ein String:\n\n```js\ntry {\n\tvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n} catch (err) {\n\t// 'LDAP bind error 49' or the text of the server\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"Jafwuh6Mx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/ldap/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"LDAP","summary":"Lee usuarios y grupos de un servidor LDAP como Active Directory con LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/ldap/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# LDAP\n\n> Lee usuarios y grupos de un servidor LDAP como Active Directory con LDAP().\n\n`LDAP(options, [callback])` lee usuarios o grupos de un servidor LDAP como Active Directory. Se autentica (bind) con un usuario y una contraseña, ejecuta una búsqueda y devuelve las entradas. Sin callback devuelve una promesa.\n\n```js\nvar users = await LDAP({\n\tldap: { host: 'ad.example.com', port: 389 },\n\tuser: 'CN=reader,CN=Users,DC=example,DC=com',\n\tpassword: CONF.ldap_password,\n\tdn: 'CN=Users,DC=example,DC=com',\n\ttype: 'person'\n});\n\n// [{ cn: 'Peter', mail: 'peter@example.com', memberOf: ['CN=Admins,...', ...], ... }]\n```\n\nCada entrada es un objeto con los atributos de la entrada. Un valor único es un string, varios valores son un array de strings, y `objectGUID` y `objectSid` son strings hexadecimales. `type` es el `objectClass` que se busca (`person`, `group`...).\n\nPara leer una cuenta, usa `type: 'profile'` con `login` (el `sAMAccountName`); el resultado es un objeto o `null`. Sin `dn` la función se autentica como `user` y devuelve la entrada de ese usuario, lo que es una forma sencilla de comprobar un inicio de sesión:\n\n```js\nvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n```\n\n`ldap.secure: true` se conecta con TLS (indica el puerto, normalmente `636`) y `ldap.timeout` limita el tiempo de conexión en milisegundos. `noauth: true` omite la autenticación (bind).\n\nLos atributos son texto por defecto. La opción `attributes` indica cómo leer los demás, por ejemplo una foto:\n\n```js\nvar profile = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'peter@example.com',\n\tpassword: password,\n\tattributes: { thumbnailPhoto: 'buffer', employeeNumber: 'number', whenCreated: 'date' }\n});\n```\n\nLos tipos son `string`, `number`, `date`, `buffer` (o `binary`) y las codificaciones `hex`, `base64`, `ascii` y `utf8`.\n\nUn bind rechazado (un usuario o una contraseña incorrectos) es un error: el texto del servidor, o `LDAP bind error 49` cuando el servidor no envía texto. El error es un string:\n\n```js\ntry {\n\tvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n} catch (err) {\n\t// 'LDAP bind error 49' or the text of the server\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"Jafwuh6Mx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/ldap/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"LDAP","summary":"Lis des utilisateurs et des groupes depuis un serveur LDAP comme Active Directory avec LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/ldap/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# LDAP\n\n> Lis des utilisateurs et des groupes depuis un serveur LDAP comme Active Directory avec LDAP().\n\n`LDAP(options, [callback])` lit des utilisateurs ou des groupes depuis un serveur LDAP comme Active Directory. Il effectue un bind avec un utilisateur et un mot de passe, exécute une recherche et renvoie les entrées. Sans callback, il renvoie une promesse.\n\n```js\nvar users = await LDAP({\n\tldap: { host: 'ad.example.com', port: 389 },\n\tuser: 'CN=reader,CN=Users,DC=example,DC=com',\n\tpassword: CONF.ldap_password,\n\tdn: 'CN=Users,DC=example,DC=com',\n\ttype: 'person'\n});\n\n// [{ cn: 'Peter', mail: 'peter@example.com', memberOf: ['CN=Admins,...', ...], ... }]\n```\n\nChaque entrée est un objet avec les attributs de l'entrée. Une valeur unique est une chaîne, plusieurs valeurs forment un tableau de chaînes, et `objectGUID` et `objectSid` sont des chaînes hexadécimales. `type` est l'`objectClass` à rechercher (`person`, `group`...).\n\nPour lire un seul compte, utilise `type: 'profile'` avec `login` (le `sAMAccountName`) ; le résultat est un objet ou `null`. Sans `dn`, la fonction effectue le bind en tant que `user` et renvoie l'entrée de cet utilisateur, ce qui est un moyen simple de vérifier une connexion :\n\n```js\nvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n```\n\n`ldap.secure: true` se connecte avec TLS (définis le port, généralement `636`) et `ldap.timeout` limite le temps de connexion en millisecondes. `noauth: true` ignore le bind.\n\nLes attributs sont du texte par défaut. L'option `attributes` indique comment lire les autres, par exemple une photo :\n\n```js\nvar profile = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'peter@example.com',\n\tpassword: password,\n\tattributes: { thumbnailPhoto: 'buffer', employeeNumber: 'number', whenCreated: 'date' }\n});\n```\n\nLes types sont `string`, `number`, `date`, `buffer` (ou `binary`) et les encodages `hex`, `base64`, `ascii` et `utf8`.\n\nUn bind refusé (un mauvais utilisateur ou mot de passe) est une erreur : le texte du serveur, ou `LDAP bind error 49` quand le serveur n'envoie aucun texte. L'erreur est une chaîne :\n\n```js\ntry {\n\tvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n} catch (err) {\n\t// 'LDAP bind error 49' or the text of the server\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"Jafwuh6Mx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/ldap/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"LDAP","summary":"Leggi utenti e gruppi da un server LDAP come Active Directory con LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/ldap/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# LDAP\n\n> Leggi utenti e gruppi da un server LDAP come Active Directory con LDAP().\n\n`LDAP(options, [callback])` legge utenti o gruppi da un server LDAP come Active Directory. Esegue il bind con un utente e una password, esegue una ricerca e restituisce le voci. Senza callback restituisce una promise.\n\n```js\nvar users = await LDAP({\n\tldap: { host: 'ad.example.com', port: 389 },\n\tuser: 'CN=reader,CN=Users,DC=example,DC=com',\n\tpassword: CONF.ldap_password,\n\tdn: 'CN=Users,DC=example,DC=com',\n\ttype: 'person'\n});\n\n// [{ cn: 'Peter', mail: 'peter@example.com', memberOf: ['CN=Admins,...', ...], ... }]\n```\n\nOgni voce è un oggetto con gli attributi della voce. Un singolo valore è una stringa, più valori sono un array di stringhe, e `objectGUID` e `objectSid` sono stringhe esadecimali. `type` è l'`objectClass` da cercare (`person`, `group`...).\n\nPer leggere un account, usa `type: 'profile'` con `login` (il `sAMAccountName`); il risultato è un oggetto o `null`. Senza `dn` la funzione esegue il bind come `user` e restituisce la voce di quell'utente, un modo semplice per verificare un login:\n\n```js\nvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n```\n\n`ldap.secure: true` si connette con TLS (imposta la porta, di solito `636`) e `ldap.timeout` limita il tempo di connessione in millisecondi. `noauth: true` salta il bind.\n\nGli attributi sono testo per impostazione predefinita. L'opzione `attributes` indica come leggere gli altri, per esempio una foto:\n\n```js\nvar profile = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'peter@example.com',\n\tpassword: password,\n\tattributes: { thumbnailPhoto: 'buffer', employeeNumber: 'number', whenCreated: 'date' }\n});\n```\n\nI tipi sono `string`, `number`, `date`, `buffer` (o `binary`) e le codifiche `hex`, `base64`, `ascii` e `utf8`.\n\nUn bind rifiutato (utente o password sbagliati) è un errore: il testo del server, oppure `LDAP bind error 49` quando il server non invia alcun testo. L'errore è una stringa:\n\n```js\ntry {\n\tvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n} catch (err) {\n\t// 'LDAP bind error 49' or the text of the server\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"Jafwuh6Mx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/ldap/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"LDAP","summary":"Čítaj používateľov a skupiny z LDAP servera, napríklad Active Directory, pomocou LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/ldap/\nupdated: 2026-11-16T16:36:21.082Z\n---\n\n# LDAP\n\n> Čítaj používateľov a skupiny z LDAP servera, napríklad Active Directory, pomocou LDAP().\n\n`LDAP(options, [callback])` číta používateľov alebo skupiny z LDAP servera, napríklad Active Directory. Prihlási sa (bind) používateľom a heslom, spustí jedno vyhľadávanie a vráti záznamy. Bez callbacku vráti promise.\n\n```js\nvar users = await LDAP({\n\tldap: { host: 'ad.example.com', port: 389 },\n\tuser: 'CN=reader,CN=Users,DC=example,DC=com',\n\tpassword: CONF.ldap_password,\n\tdn: 'CN=Users,DC=example,DC=com',\n\ttype: 'person'\n});\n\n// [{ cn: 'Peter', mail: 'peter@example.com', memberOf: ['CN=Admins,...', ...], ... }]\n```\n\nKaždý záznam je objekt s atribútmi záznamu. Jedna hodnota je reťazec, viac hodnôt je pole reťazcov a `objectGUID` a `objectSid` sú hex reťazce. `type` je `objectClass`, ktorú hľadáš (`person`, `group`...).\n\nNa prečítanie jedného účtu použi `type: 'profile'` s `login` (`sAMAccountName`); výsledkom je jeden objekt alebo `null`. Bez `dn` sa funkcia prihlási ako `user` a vráti záznam tohto používateľa, čo je jednoduchý spôsob, ako overiť prihlásenie:\n\n```js\nvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n```\n\n`ldap.secure: true` sa pripojí cez TLS (nastav port, zvyčajne `636`) a `ldap.timeout` obmedzí čas pripojenia v milisekundách. `noauth: true` preskočí bind.\n\nAtribúty sú predvolene text. Možnosť `attributes` určuje, ako čítať ostatné, napríklad fotku:\n\n```js\nvar profile = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'peter@example.com',\n\tpassword: password,\n\tattributes: { thumbnailPhoto: 'buffer', employeeNumber: 'number', whenCreated: 'date' }\n});\n```\n\nTypy sú `string`, `number`, `date`, `buffer` (alebo `binary`) a kódovania `hex`, `base64`, `ascii` a `utf8`.\n\nOdmietnutý bind (nesprávny používateľ alebo heslo) je chyba: text servera, alebo `LDAP bind error 49`, keď server nepošle žiadny text. Chyba je reťazec:\n\n```js\ntry {\n\tvar profile = await LDAP({ ldap: { host: 'ad.example.com' }, user: 'peter@example.com', password: password });\n} catch (err) {\n\t// 'LDAP bind error 49' or the text of the server\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T16:36:21.082Z"}
{"id":"JafiLh3r660f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/markdown/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Markdown","summary":"Convert Markdown to HTML with String.prototype.markdown(), and the Markdown syntax it supports.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/markdown/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Markdown\n\n> Convert Markdown to HTML with String.prototype.markdown(), and the Markdown syntax it supports.\n\n`String.prototype.markdown([options])` converts Markdown to HTML. The output is wrapped in `<div class=\"markdown markdown-container\">` and every block has the class `markdown-line`, so you can style it.\n\n```js\nvar html = '# Hello\\n\\nSome **bold** text with a [link](https://www.totaljs.com).'.markdown();\n```\n\nBesides the usual headings (`#` to `#####`), `**bold**`, `*italic*`, `__bold__`, `_underline_`, `~~strike~~`, inline code, code blocks, lists (nested with tabs, tasks with `[ ]` and `[x]`), tables with alignment, `> quotes`, `---` lines, links and images, it supports a few extensions:\n\n| Syntax | Output |\n| --- | --- |\n| `:check:` or `:ti ti-user:` | An icon `<i class=\"ti ti-check\">` |\n| `{keyword}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` and a line `#1: text` | A footnote and its text |\n| `< text` | A `<section>` |\n| `::: Title` … `:::` | A block that can be expanded |\n| `![+alt](url)`, `![-alt](url)` | An image without `img-responsive`, a gallery image |\n\nHeadings get an `id` made from their text (turn it off with `bookmarks: false`, or add `prefix`). Each feature can be turned off: `{ tables: false, images: false, code: false }` and so on. `wrap: false` removes the outer `<div>`, `linetag` changes the `<p>` of paragraphs, and `html(text, type)` lets you change the text of each block.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiLh3r660f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/markdown/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Markdown","summary":"Wandle Markdown mit String.prototype.markdown() in HTML um, und die Markdown-Syntax, die es unterstützt.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/markdown/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Markdown\n\n> Wandle Markdown mit String.prototype.markdown() in HTML um, und die Markdown-Syntax, die es unterstützt.\n\n`String.prototype.markdown([options])` wandelt Markdown in HTML um. Die Ausgabe ist in `<div class=\"markdown markdown-container\">` eingeschlossen, und jeder Block hat die Klasse `markdown-line`, sodass du ihn gestalten kannst.\n\n```js\nvar html = '# Hello\\n\\nSome **bold** text with a [link](https://www.totaljs.com).'.markdown();\n```\n\nNeben den üblichen Überschriften (`#` bis `#####`), `**bold**`, `*italic*`, `__bold__`, `_underline_`, `~~strike~~`, Inline-Code, Codeblöcken, Listen (mit Tabs verschachtelt, Aufgaben mit `[ ]` und `[x]`), Tabellen mit Ausrichtung, `> quotes`, `---`-Linien, Links und Bildern unterstützt es einige Erweiterungen:\n\n| Syntax | Ausgabe |\n| --- | --- |\n| `:check:` oder `:ti ti-user:` | Ein Icon `<i class=\"ti ti-check\">` |\n| `{keyword}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` und eine Zeile `#1: text` | Eine Fußnote und ihr Text |\n| `< text` | Ein `<section>` |\n| `::: Title` … `:::` | Ein Block, der aufgeklappt werden kann |\n| `![+alt](url)`, `![-alt](url)` | Ein Bild ohne `img-responsive`, ein Galeriebild |\n\nÜberschriften erhalten eine `id`, die aus ihrem Text gebildet wird (schalte das mit `bookmarks: false` aus oder füge `prefix` hinzu). Jede Funktion kann ausgeschaltet werden: `{ tables: false, images: false, code: false }` und so weiter. `wrap: false` entfernt das äußere `<div>`, `linetag` ändert das `<p>` von Absätzen, und mit `html(text, type)` kannst du den Text jedes Blocks ändern.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiLh3r660f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/markdown/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Markdown","summary":"Convierte Markdown en HTML con String.prototype.markdown() y la sintaxis de Markdown que admite.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/markdown/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Markdown\n\n> Convierte Markdown en HTML con String.prototype.markdown() y la sintaxis de Markdown que admite.\n\n`String.prototype.markdown([options])` convierte Markdown en HTML. La salida se envuelve en `<div class=\"markdown markdown-container\">` y cada bloque tiene la clase `markdown-line`, para que puedas darle estilo.\n\n```js\nvar html = '# Hello\\n\\nSome **bold** text with a [link](https://www.totaljs.com).'.markdown();\n```\n\nAdemás de los encabezados habituales (`#` a `#####`), `**bold**`, `*italic*`, `__bold__`, `_underline_`, `~~strike~~`, código en línea, bloques de código, listas (anidadas con tabuladores, tareas con `[ ]` y `[x]`), tablas con alineación, `> quotes`, líneas `---`, enlaces e imágenes, admite algunas extensiones:\n\n| Sintaxis | Salida |\n| --- | --- |\n| `:check:` o `:ti ti-user:` | Un icono `<i class=\"ti ti-check\">` |\n| `{keyword}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` y una línea `#1: text` | Una nota al pie y su texto |\n| `< text` | Una `<section>` |\n| `::: Title` … `:::` | Un bloque que se puede desplegar |\n| `![+alt](url)`, `![-alt](url)` | Una imagen sin `img-responsive`, una imagen de galería |\n\nLos encabezados reciben un `id` creado a partir de su texto (desactívalo con `bookmarks: false`, o añade `prefix`). Cada característica se puede desactivar: `{ tables: false, images: false, code: false }` y así sucesivamente. `wrap: false` elimina el `<div>` exterior, `linetag` cambia el `<p>` de los párrafos, y `html(text, type)` te permite cambiar el texto de cada bloque.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiLh3r660f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/markdown/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Markdown","summary":"Convertis du Markdown en HTML avec String.prototype.markdown(), et la syntaxe Markdown qu'il prend en charge.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/markdown/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Markdown\n\n> Convertis du Markdown en HTML avec String.prototype.markdown(), et la syntaxe Markdown qu'il prend en charge.\n\n`String.prototype.markdown([options])` convertit du Markdown en HTML. La sortie est enveloppée dans `<div class=\"markdown markdown-container\">` et chaque bloc a la classe `markdown-line`, ce qui te permet de la styliser.\n\n```js\nvar html = '# Hello\\n\\nSome **bold** text with a [link](https://www.totaljs.com).'.markdown();\n```\n\nEn plus des éléments habituels, titres (`#` à `#####`), `**bold**`, `*italic*`, `__bold__`, `_underline_`, `~~strike~~`, code en ligne, blocs de code, listes (imbriquées avec des tabulations, tâches avec `[ ]` et `[x]`), tableaux avec alignement, `> quotes`, lignes `---`, liens et images, il prend en charge quelques extensions :\n\n| Syntaxe | Résultat |\n| --- | --- |\n| `:check:` ou `:ti ti-user:` | Une icône `<i class=\"ti ti-check\">` |\n| `{keyword}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` et une ligne `#1: text` | Une note de bas de page et son texte |\n| `< text` | Une `<section>` |\n| `::: Title` … `:::` | Un bloc dépliable |\n| `![+alt](url)`, `![-alt](url)` | Une image sans `img-responsive`, une image de galerie |\n\nLes titres reçoivent un `id` construit à partir de leur texte (désactive-le avec `bookmarks: false`, ou ajoute `prefix`). Chaque fonctionnalité peut être désactivée : `{ tables: false, images: false, code: false }` et ainsi de suite. `wrap: false` supprime le `<div>` extérieur, `linetag` change le `<p>` des paragraphes, et `html(text, type)` te permet de modifier le texte de chaque bloc.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiLh3r660f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/markdown/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Markdown","summary":"Converti Markdown in HTML con String.prototype.markdown() e la sintassi Markdown che supporta.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/markdown/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Markdown\n\n> Converti Markdown in HTML con String.prototype.markdown() e la sintassi Markdown che supporta.\n\n`String.prototype.markdown([options])` converte Markdown in HTML. L'output è racchiuso in `<div class=\"markdown markdown-container\">` e ogni blocco ha la classe `markdown-line`, così puoi applicarvi degli stili.\n\n```js\nvar html = '# Hello\\n\\nSome **bold** text with a [link](https://www.totaljs.com).'.markdown();\n```\n\nOltre ai consueti titoli (da `#` a `#####`), `**bold**`, `*italic*`, `__bold__`, `_underline_`, `~~strike~~`, codice inline, blocchi di codice, elenchi (annidati con tabulazioni, attività con `[ ]` e `[x]`), tabelle con allineamento, `> quotes`, linee `---`, link e immagini, supporta alcune estensioni:\n\n| Sintassi | Output |\n| --- | --- |\n| `:check:` o `:ti ti-user:` | Un'icona `<i class=\"ti ti-check\">` |\n| `{keyword}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` e una riga `#1: text` | Una nota a piè di pagina e il suo testo |\n| `< text` | Una `<section>` |\n| `::: Title` … `:::` | Un blocco espandibile |\n| `![+alt](url)`, `![-alt](url)` | Un'immagine senza `img-responsive`, un'immagine di galleria |\n\nI titoli ricevono un `id` ricavato dal loro testo (disattivalo con `bookmarks: false`, o aggiungi `prefix`). Ogni funzionalità può essere disattivata: `{ tables: false, images: false, code: false }` e così via. `wrap: false` rimuove il `<div>` esterno, `linetag` cambia il `<p>` dei paragrafi e `html(text, type)` ti permette di modificare il testo di ogni blocco.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiLh3r660f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/markdown/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Markdown","summary":"Preveď Markdown na HTML pomocou String.prototype.markdown() a syntax Markdownu, ktorú podporuje.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/markdown/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Markdown\n\n> Preveď Markdown na HTML pomocou String.prototype.markdown() a syntax Markdownu, ktorú podporuje.\n\n`String.prototype.markdown([options])` prevedie Markdown na HTML. Výstup je zabalený v `<div class=\"markdown markdown-container\">` a každý blok má triedu `markdown-line`, takže ho môžeš naštýlovať.\n\n```js\nvar html = '# Hello\\n\\nSome **bold** text with a [link](https://www.totaljs.com).'.markdown();\n```\n\nOkrem bežných nadpisov (`#` až `#####`), `**bold**`, `*italic*`, `__bold__`, `_underline_`, `~~strike~~`, inline kódu, blokov kódu, zoznamov (vnorených pomocou tabulátorov, úloh s `[ ]` a `[x]`), tabuliek so zarovnaním, `> quotes`, čiar `---`, odkazov a obrázkov podporuje niekoľko rozšírení:\n\n| Syntax | Výstup |\n| --- | --- |\n| `:check:` alebo `:ti ti-user:` | Ikona `<i class=\"ti ti-check\">` |\n| `{keyword}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` a riadok `#1: text` | Poznámka pod čiarou a jej text |\n| `< text` | `<section>` |\n| `::: Title` … `:::` | Blok, ktorý sa dá rozbaliť |\n| `![+alt](url)`, `![-alt](url)` | Obrázok bez `img-responsive`, obrázok galérie |\n\nNadpisy dostanú `id` vytvorené z ich textu (vypneš to pomocou `bookmarks: false` alebo pridáš `prefix`). Každú funkciu môžeš vypnúť: `{ tables: false, images: false, code: false }` a tak ďalej. `wrap: false` odstráni vonkajší `<div>`, `linetag` zmení `<p>` odsekov a `html(text, type)` ti umožní zmeniť text každého bloku.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JaqmBC1nc60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/html-parser/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"HTML and XML parser","summary":"Parse HTML and XML on the server into a tree of elements that you can search and change.","markdown":"---\ntitle: HTML and XML parser\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/html-parser/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# HTML and XML parser\n\n> Parse HTML and XML on the server into a tree of elements that you can search and change.\n\n`String.prototype.parseHTML([trim])` parses HTML into a tree of elements that you can search and change, a small DOM on the server. `parseXML2()` does the same for XML (tag names keep their prefixes, such as `soap:Body`).\n\n```js\nvar dom = '<div class=\"list\"><p id=\"a\">Hello <b>world</b></p><p data-id=\"2\">Bye</p></div>'.parseHTML();\n\ndom.find('p').length;                     // 2\ndom.find('div > p[data-id=\"2\"]').text();  // 'Bye'\n\nvar p = dom.find('#a')[0];\np.aclass('big').css('color', 'red').attr('title', 'Greeting');\np.find('b')[0].remove();\n\ndom.html(); // '<div class=\"list\"><p id=\"a\" class=\"big\" style=\"color:red\" title=\"Greeting\">Hello </p>...'\n```\n\n`find()` accepts tag names, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (the attribute exists), descendants (`div p`), children (`div > p`) and several selectors separated by commas. It returns an array of elements with the same methods for all of them (`aclass()`, `rclass()`, `attr()`, `find()`, `html()`, `text()`...). Each element has `tagName` (upper case), `attrs`, `children` and `parentNode`; text is in nodes with `tagName` `TEXT` and `textContent`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmBC1nc60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/html-parser/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"HTML- und XML-Parser","summary":"Parse HTML und XML auf dem Server in einen Baum von Elementen, den du durchsuchen und ändern kannst.","markdown":"---\ntitle: HTML- und XML-Parser\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/html-parser/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# HTML- und XML-Parser\n\n> Parse HTML und XML auf dem Server in einen Baum von Elementen, den du durchsuchen und ändern kannst.\n\n`String.prototype.parseHTML([trim])` parst HTML in einen Baum von Elementen, den du durchsuchen und ändern kannst, ein kleines DOM auf dem Server. `parseXML2()` macht dasselbe für XML (Tag-Namen behalten ihre Präfixe, etwa `soap:Body`).\n\n```js\nvar dom = '<div class=\"list\"><p id=\"a\">Hello <b>world</b></p><p data-id=\"2\">Bye</p></div>'.parseHTML();\n\ndom.find('p').length;                     // 2\ndom.find('div > p[data-id=\"2\"]').text();  // 'Bye'\n\nvar p = dom.find('#a')[0];\np.aclass('big').css('color', 'red').attr('title', 'Greeting');\np.find('b')[0].remove();\n\ndom.html(); // '<div class=\"list\"><p id=\"a\" class=\"big\" style=\"color:red\" title=\"Greeting\">Hello </p>...'\n```\n\n`find()` akzeptiert Tag-Namen, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (das Attribut existiert), Nachfahren (`div p`), Kinder (`div > p`) und mehrere durch Kommas getrennte Selektoren. Es gibt ein Array von Elementen zurück, mit denselben Methoden für alle (`aclass()`, `rclass()`, `attr()`, `find()`, `html()`, `text()`...). Jedes Element hat `tagName` (in Großbuchstaben), `attrs`, `children` und `parentNode`; Text steht in Knoten mit `tagName` `TEXT` und `textContent`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmBC1nc60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/html-parser/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Parser de HTML y XML","summary":"Analiza HTML y XML en el servidor en un árbol de elementos que puedes buscar y modificar.","markdown":"---\ntitle: Parser de HTML y XML\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/html-parser/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Parser de HTML y XML\n\n> Analiza HTML y XML en el servidor en un árbol de elementos que puedes buscar y modificar.\n\n`String.prototype.parseHTML([trim])` analiza HTML en un árbol de elementos que puedes buscar y modificar, un pequeño DOM en el servidor. `parseXML2()` hace lo mismo con XML (los nombres de las etiquetas conservan sus prefijos, como `soap:Body`).\n\n```js\nvar dom = '<div class=\"list\"><p id=\"a\">Hello <b>world</b></p><p data-id=\"2\">Bye</p></div>'.parseHTML();\n\ndom.find('p').length;                     // 2\ndom.find('div > p[data-id=\"2\"]').text();  // 'Bye'\n\nvar p = dom.find('#a')[0];\np.aclass('big').css('color', 'red').attr('title', 'Greeting');\np.find('b')[0].remove();\n\ndom.html(); // '<div class=\"list\"><p id=\"a\" class=\"big\" style=\"color:red\" title=\"Greeting\">Hello </p>...'\n```\n\n`find()` acepta nombres de etiquetas, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (el atributo existe), descendientes (`div p`), hijos (`div > p`) y varios selectores separados por comas. Devuelve un array de elementos con los mismos métodos para todos ellos (`aclass()`, `rclass()`, `attr()`, `find()`, `html()`, `text()`...). Cada elemento tiene `tagName` (en mayúsculas), `attrs`, `children` y `parentNode`; el texto está en nodos con `tagName` `TEXT` y `textContent`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmBC1nc60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/html-parser/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Parseur HTML et XML","summary":"Analyse du HTML et du XML sur le serveur en un arbre d'éléments que tu peux parcourir et modifier.","markdown":"---\ntitle: Parseur HTML et XML\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/html-parser/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Parseur HTML et XML\n\n> Analyse du HTML et du XML sur le serveur en un arbre d'éléments que tu peux parcourir et modifier.\n\n`String.prototype.parseHTML([trim])` analyse du HTML en un arbre d'éléments que tu peux parcourir et modifier, un petit DOM sur le serveur. `parseXML2()` fait la même chose pour le XML (les noms de balises gardent leurs préfixes, comme `soap:Body`).\n\n```js\nvar dom = '<div class=\"list\"><p id=\"a\">Hello <b>world</b></p><p data-id=\"2\">Bye</p></div>'.parseHTML();\n\ndom.find('p').length;                     // 2\ndom.find('div > p[data-id=\"2\"]').text();  // 'Bye'\n\nvar p = dom.find('#a')[0];\np.aclass('big').css('color', 'red').attr('title', 'Greeting');\np.find('b')[0].remove();\n\ndom.html(); // '<div class=\"list\"><p id=\"a\" class=\"big\" style=\"color:red\" title=\"Greeting\">Hello </p>...'\n```\n\n`find()` accepte des noms de balises, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (l'attribut existe), des descendants (`div p`), des enfants (`div > p`) et plusieurs sélecteurs séparés par des virgules. Elle renvoie un tableau d'éléments avec les mêmes méthodes pour tous (`aclass()`, `rclass()`, `attr()`, `find()`, `html()`, `text()`...). Chaque élément a `tagName` (en majuscules), `attrs`, `children` et `parentNode` ; le texte se trouve dans des nœuds avec `tagName` `TEXT` et `textContent`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmBC1nc60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/html-parser/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Parser HTML e XML","summary":"Analizza HTML e XML sul server in un albero di elementi che puoi cercare e modificare.","markdown":"---\ntitle: Parser HTML e XML\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/html-parser/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Parser HTML e XML\n\n> Analizza HTML e XML sul server in un albero di elementi che puoi cercare e modificare.\n\n`String.prototype.parseHTML([trim])` analizza l'HTML in un albero di elementi che puoi cercare e modificare, un piccolo DOM sul server. `parseXML2()` fa lo stesso per l'XML (i nomi dei tag mantengono i loro prefissi, come `soap:Body`).\n\n```js\nvar dom = '<div class=\"list\"><p id=\"a\">Hello <b>world</b></p><p data-id=\"2\">Bye</p></div>'.parseHTML();\n\ndom.find('p').length;                     // 2\ndom.find('div > p[data-id=\"2\"]').text();  // 'Bye'\n\nvar p = dom.find('#a')[0];\np.aclass('big').css('color', 'red').attr('title', 'Greeting');\np.find('b')[0].remove();\n\ndom.html(); // '<div class=\"list\"><p id=\"a\" class=\"big\" style=\"color:red\" title=\"Greeting\">Hello </p>...'\n```\n\n`find()` accetta nomi di tag, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (l'attributo esiste), discendenti (`div p`), figli (`div > p`) e più selettori separati da virgole. Restituisce un array di elementi con gli stessi metodi per tutti (`aclass()`, `rclass()`, `attr()`, `find()`, `html()`, `text()`...). Ogni elemento ha `tagName` (in maiuscolo), `attrs`, `children` e `parentNode`; il testo si trova nei nodi con `tagName` `TEXT` e `textContent`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmBC1nc60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/html-parser/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"HTML a XML parser","summary":"Parsuj HTML a XML na serveri do stromu prvkov, ktorý môžeš prehľadávať a meniť.","markdown":"---\ntitle: HTML a XML parser\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/html-parser/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# HTML a XML parser\n\n> Parsuj HTML a XML na serveri do stromu prvkov, ktorý môžeš prehľadávať a meniť.\n\n`String.prototype.parseHTML([trim])` sparsuje HTML do stromu prvkov, ktorý môžeš prehľadávať a meniť, malého DOM na serveri. `parseXML2()` robí to isté pre XML (názvy tagov si ponechajú prefixy, napríklad `soap:Body`).\n\n```js\nvar dom = '<div class=\"list\"><p id=\"a\">Hello <b>world</b></p><p data-id=\"2\">Bye</p></div>'.parseHTML();\n\ndom.find('p').length;                     // 2\ndom.find('div > p[data-id=\"2\"]').text();  // 'Bye'\n\nvar p = dom.find('#a')[0];\np.aclass('big').css('color', 'red').attr('title', 'Greeting');\np.find('b')[0].remove();\n\ndom.html(); // '<div class=\"list\"><p id=\"a\" class=\"big\" style=\"color:red\" title=\"Greeting\">Hello </p>...'\n```\n\n`find()` prijíma názvy tagov, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (atribút existuje), potomkov (`div p`), priame deti (`div > p`) a viacero selektorov oddelených čiarkami. Vráti pole prvkov s rovnakými metódami pre všetky (`aclass()`, `rclass()`, `attr()`, `find()`, `html()`, `text()`...). Každý prvok má `tagName` (veľkými písmenami), `attrs`, `children` a `parentNode`; text je v uzloch s `tagName` `TEXT` a `textContent`.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafiYZ3OK61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/macros/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/macros/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Macros\n\n> Compile a small rule language into a function with NEWMACRO(), for rules that users write.\n\n`NEWMACRO(code)` compiles a small rule language into a function. It is meant for rules that users write in an admin, such as prices or discounts. The function receives a model and an object with helpers.\n\n```js\nvar rule = NEWMACRO([\n\t'#total = price * count',\n\t'IF #total > 1000 AND country == \"SK\"',\n\t'\tRETURN discount(#total)',\n\t'FI',\n\t'RETURN #total'\n].join('\\n'));\n\nrule({ price: 600, count: 2, country: 'SK' }, { discount: function(value) { return value * 0.8; } }); // 960\n```\n\nA macro has `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `NULL` and the values `TRUE`, `FALSE`, `YES`, `NO`. Words are properties of the model, `#name` is a temporary variable and `name(...)` calls a helper. Keywords can be in any case, but properties and helpers are read in lower case. `NEWMACRO(code, true)` returns the generated JavaScript instead of a function, and `NEWMACRO(code, false, true)` makes an async function that awaits the helpers.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiYZ3OK61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/macros/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/macros/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Makros\n\n> Kompiliere mit NEWMACRO() eine kleine Regelsprache in eine Funktion, für Regeln, die Benutzer schreiben.\n\n`NEWMACRO(code)` kompiliert eine kleine Regelsprache zu einer Funktion. Sie ist für Regeln gedacht, die Benutzer in einem Admin schreiben, etwa Preise oder Rabatte. Die Funktion erhält ein Modell und ein Objekt mit Hilfsfunktionen.\n\n```js\nvar rule = NEWMACRO([\n\t'#total = price * count',\n\t'IF #total > 1000 AND country == \"SK\"',\n\t'\tRETURN discount(#total)',\n\t'FI',\n\t'RETURN #total'\n].join('\\n'));\n\nrule({ price: 600, count: 2, country: 'SK' }, { discount: function(value) { return value * 0.8; } }); // 960\n```\n\nEin Makro hat `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `NULL` und die Werte `TRUE`, `FALSE`, `YES`, `NO`. Wörter sind Eigenschaften des Modells, `#name` ist eine temporäre Variable und `name(...)` ruft eine Hilfsfunktion auf. Schlüsselwörter können beliebig groß oder klein geschrieben sein, aber Eigenschaften und Hilfsfunktionen werden in Kleinbuchstaben gelesen. `NEWMACRO(code, true)` gibt das erzeugte JavaScript statt einer Funktion zurück, und `NEWMACRO(code, false, true)` erzeugt eine asynchrone Funktion, die auf die Hilfsfunktionen wartet.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiYZ3OK61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/macros/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/macros/\nupdated: 2026-11-16T15:32:27.494Z\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(code)` compila un pequeño lenguaje de reglas en una función. Está pensado para reglas que los usuarios escriben en un panel de administración, como precios o descuentos. La función recibe un modelo y un objeto con helpers.\n\n```js\nvar rule = NEWMACRO([\n\t'#total = price * count',\n\t'IF #total > 1000 AND country == \"SK\"',\n\t'\tRETURN discount(#total)',\n\t'FI',\n\t'RETURN #total'\n].join('\\n'));\n\nrule({ price: 600, count: 2, country: 'SK' }, { discount: function(value) { return value * 0.8; } }); // 960\n```\n\nUna macro tiene `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `NULL` y los valores `TRUE`, `FALSE`, `YES`, `NO`. Las palabras son propiedades del modelo, `#name` es una variable temporal y `name(...)` llama a un helper. Las palabras clave pueden estar en mayúsculas o minúsculas, pero las propiedades y los helpers se leen en minúsculas. `NEWMACRO(code, true)` devuelve el JavaScript generado en lugar de una función, y `NEWMACRO(code, false, true)` crea una función async que espera (await) a los helpers.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiYZ3OK61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/macros/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/macros/\nupdated: 2026-11-16T15:32:27.494Z\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(code)` compile un petit langage de règles en une fonction. Il est destiné aux règles que les utilisateurs écrivent dans une administration, comme des prix ou des remises. La fonction reçoit un modèle et un objet de helpers.\n\n```js\nvar rule = NEWMACRO([\n\t'#total = price * count',\n\t'IF #total > 1000 AND country == \"SK\"',\n\t'\tRETURN discount(#total)',\n\t'FI',\n\t'RETURN #total'\n].join('\\n'));\n\nrule({ price: 600, count: 2, country: 'SK' }, { discount: function(value) { return value * 0.8; } }); // 960\n```\n\nUne macro dispose de `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `NULL` et des valeurs `TRUE`, `FALSE`, `YES`, `NO`. Les mots sont des propriétés du modèle, `#name` est une variable temporaire et `name(...)` appelle un helper. Les mots-clés peuvent être écrits dans n'importe quelle casse, mais les propriétés et les helpers sont lus en minuscules. `NEWMACRO(code, true)` renvoie le JavaScript généré au lieu d'une fonction, et `NEWMACRO(code, false, true)` crée une fonction async qui attend les helpers.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiYZ3OK61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/macros/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/macros/\nupdated: 2026-11-16T15:32:27.494Z\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(code)` compila un piccolo linguaggio di regole in una funzione. È pensato per regole che gli utenti scrivono in un pannello di amministrazione, come prezzi o sconti. La funzione riceve un modello e un oggetto con gli helper.\n\n```js\nvar rule = NEWMACRO([\n\t'#total = price * count',\n\t'IF #total > 1000 AND country == \"SK\"',\n\t'\tRETURN discount(#total)',\n\t'FI',\n\t'RETURN #total'\n].join('\\n'));\n\nrule({ price: 600, count: 2, country: 'SK' }, { discount: function(value) { return value * 0.8; } }); // 960\n```\n\nUna macro ha `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `NULL` e i valori `TRUE`, `FALSE`, `YES`, `NO`. Le parole sono proprietà del modello, `#name` è una variabile temporanea e `name(...)` chiama un helper. Le parole chiave possono essere maiuscole o minuscole, ma proprietà e helper vengono letti in minuscolo. `NEWMACRO(code, true)` restituisce il JavaScript generato invece di una funzione, e `NEWMACRO(code, false, true)` crea una funzione async che attende gli helper.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"JafiYZ3OK61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/macros/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/macros/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Makrá\n\n> Skompiluj malý jazyk pravidiel do funkcie pomocou NEWMACRO(), pre pravidlá, ktoré píšu používatelia.\n\n`NEWMACRO(code)` skompiluje malý jazyk pravidiel do funkcie. Je určený pre pravidlá, ktoré používatelia píšu v administrácii, napríklad ceny alebo zľavy. Funkcia dostane model a objekt s pomocnými funkciami.\n\n```js\nvar rule = NEWMACRO([\n\t'#total = price * count',\n\t'IF #total > 1000 AND country == \"SK\"',\n\t'\tRETURN discount(#total)',\n\t'FI',\n\t'RETURN #total'\n].join('\\n'));\n\nrule({ price: 600, count: 2, country: 'SK' }, { discount: function(value) { return value * 0.8; } }); // 960\n```\n\nMakro má `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `NULL` a hodnoty `TRUE`, `FALSE`, `YES`, `NO`. Slová sú vlastnosti modelu, `#name` je dočasná premenná a `name(...)` volá pomocnú funkciu. Kľúčové slová môžu byť v ľubovoľnej veľkosti písmen, ale vlastnosti a pomocné funkcie sa čítajú malými písmenami. `NEWMACRO(code, true)` vráti vygenerovaný JavaScript namiesto funkcie a `NEWMACRO(code, false, true)` vytvorí asynchrónnu funkciu, ktorá na pomocné funkcie čaká pomocou await.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"Jafics4SK61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/tangular/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Tangular","summary":"The Tangular template engine: compile and render templates and register helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/tangular/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Tangular\n\n> The Tangular template engine: compile and render templates and register helpers.\n\nTangular is the template engine used by `TEMPLATE()`, by audit messages and by the CMS. It is available as the global `Tangular`. The commands (`{{ value }}`, `{{ if }}`, `{{ foreach }}` and helpers) are described in [Views](../views/#templates).\n\n```js\nvar template = Tangular.compile('<h1>{{ name }}</h1>{{ foreach item in items }}<p>{{ item.price | format(2) }}</p>{{ end }}');\nvar html = template({ name: 'Order', items: [{ price: 10 }] });\n```\n\nThe compiled function is `template(model, [repository], [helpers])`: names in the template are read from the model, `$` is the repository. Values are HTML-encoded unless you use `| raw`. `Tangular.register(name, fn)` adds a helper for all templates.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"Jafics4SK61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/tangular/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Tangular","summary":"Die Template-Engine Tangular: Templates kompilieren und rendern und Helfer registrieren.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/tangular/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Tangular\n\n> Die Template-Engine Tangular: Templates kompilieren und rendern und Helfer registrieren.\n\nTangular ist die Template-Engine, die von `TEMPLATE()`, von Audit-Meldungen und vom CMS verwendet wird. Sie ist als globales `Tangular` verfügbar. Die Befehle (`{{ value }}`, `{{ if }}`, `{{ foreach }}` und Hilfsfunktionen) sind in [Views](../views/#templates) beschrieben.\n\n```js\nvar template = Tangular.compile('<h1>{{ name }}</h1>{{ foreach item in items }}<p>{{ item.price | format(2) }}</p>{{ end }}');\nvar html = template({ name: 'Order', items: [{ price: 10 }] });\n```\n\nDie kompilierte Funktion ist `template(model, [repository], [helpers])`: Namen im Template werden aus dem Modell gelesen, `$` ist das Repository. Werte werden HTML-kodiert, außer du verwendest `| raw`. `Tangular.register(name, fn)` fügt eine Hilfsfunktion für alle Templates hinzu.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"Jafics4SK61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/tangular/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Tangular","summary":"El motor de plantillas Tangular: compila y renderiza plantillas y registra helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/tangular/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Tangular\n\n> El motor de plantillas Tangular: compila y renderiza plantillas y registra helpers.\n\nTangular es el motor de plantillas que usan `TEMPLATE()`, los mensajes de auditoría y el CMS. Está disponible como la global `Tangular`. Los comandos (`{{ value }}`, `{{ if }}`, `{{ foreach }}` y los helpers) se describen en [Vistas](../views/#templates).\n\n```js\nvar template = Tangular.compile('<h1>{{ name }}</h1>{{ foreach item in items }}<p>{{ item.price | format(2) }}</p>{{ end }}');\nvar html = template({ name: 'Order', items: [{ price: 10 }] });\n```\n\nLa función compilada es `template(model, [repository], [helpers])`: los nombres de la plantilla se leen del modelo, y `$` es el repositorio. Los valores se codifican en HTML salvo que uses `| raw`. `Tangular.register(name, fn)` añade un helper para todas las plantillas.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"Jafics4SK61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/tangular/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Tangular","summary":"Le moteur de templates Tangular : compile et rends des templates et enregistre des helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/tangular/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Tangular\n\n> Le moteur de templates Tangular : compile et rends des templates et enregistre des helpers.\n\nTangular est le moteur de templates utilisé par `TEMPLATE()`, par les messages d'audit et par le CMS. Il est disponible via la variable globale `Tangular`. Les commandes (`{{ value }}`, `{{ if }}`, `{{ foreach }}` et les helpers) sont décrites dans [Vues](../views/#templates).\n\n```js\nvar template = Tangular.compile('<h1>{{ name }}</h1>{{ foreach item in items }}<p>{{ item.price | format(2) }}</p>{{ end }}');\nvar html = template({ name: 'Order', items: [{ price: 10 }] });\n```\n\nLa fonction compilée est `template(model, [repository], [helpers])` : les noms du template sont lus dans le modèle, `$` est le repository. Les valeurs sont encodées en HTML, sauf si tu utilises `| raw`. `Tangular.register(name, fn)` ajoute un helper pour tous les templates.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"Jafics4SK61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/tangular/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Tangular","summary":"Il motore di template Tangular: compila e renderizza i template e registra gli helper.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/tangular/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Tangular\n\n> Il motore di template Tangular: compila e renderizza i template e registra gli helper.\n\nTangular è il motore di template usato da `TEMPLATE()`, dai messaggi di audit e dal CMS. È disponibile come variabile globale `Tangular`. I comandi (`{{ value }}`, `{{ if }}`, `{{ foreach }}` e gli helper) sono descritti in [View](../views/#templates).\n\n```js\nvar template = Tangular.compile('<h1>{{ name }}</h1>{{ foreach item in items }}<p>{{ item.price | format(2) }}</p>{{ end }}');\nvar html = template({ name: 'Order', items: [{ price: 10 }] });\n```\n\nLa funzione compilata è `template(model, [repository], [helpers])`: i nomi nel template vengono letti dal modello, `$` è il repository. I valori vengono codificati in HTML a meno che non usi `| raw`. `Tangular.register(name, fn)` aggiunge un helper per tutti i template.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"Jafics4SK61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/tangular/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Tangular","summary":"Šablónovací engine Tangular: kompiluj a vykresľuj šablóny a registruj helpery.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/tangular/\nupdated: 2026-11-16T15:32:27.494Z\n---\n\n# Tangular\n\n> Šablónovací engine Tangular: kompiluj a vykresľuj šablóny a registruj helpery.\n\nTangular je šablónovací engine, ktorý používa `TEMPLATE()`, auditné správy a CMS. Je dostupný ako globálny `Tangular`. Príkazy (`{{ value }}`, `{{ if }}`, `{{ foreach }}` a pomocné funkcie) sú opísané vo [Views](../views/#templates).\n\n```js\nvar template = Tangular.compile('<h1>{{ name }}</h1>{{ foreach item in items }}<p>{{ item.price | format(2) }}</p>{{ end }}');\nvar html = template({ name: 'Order', items: [{ price: 10 }] });\n```\n\nSkompilovaná funkcia je `template(model, [repository], [helpers])`: názvy v šablóne sa čítajú z modelu, `$` je repository. Hodnoty sa kódujú pre HTML, pokiaľ nepoužiješ `| raw`. `Tangular.register(name, fn)` pridá pomocnú funkciu pre všetky šablóny.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:27.494Z"}
{"id":"Jafim93VY60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/minification/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Minification","summary":"Minify JavaScript, CSS and HTML from your code with the minificators of U.","markdown":"---\ntitle: Minification\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/minification/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Minification\n\n> Minify JavaScript, CSS and HTML from your code with the minificators of U.\n\nThe framework minifies static `.js`, `.css` and `.html` files and merged files (see [Static files](../static-files/)). The same minificators are in `U`:\n\n```js\nU.minify_css('.box {\\n\\t.title { margin: 0 0 0 0; color: #FFFFFF; }\\n}');  // '.box .title{margin:0;color:#FFF}'\nU.minify_js('function sum(a, b) {\\n\\t// adds\\n\\treturn a + b;\\n}');        // 'function sum(a,b){return a+b}'\nU.minify_html(html);\n```\n\nThe CSS minificator also compiles nested rules (a rule that contains only other rules) and variables written as `$name: value;`. `MERGE()` joins several files into one URL and is described in [Static files](../static-files/).\n\nThe HTML minificator removes comments (but not conditional comments) and collapses runs of spaces between words. Line breaks and indentation between tags are kept. Inline `<script>` and `<style>` are minified when `$minifyjs` and `$minifycss` are on.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"Jafim93VY60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/minification/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Minifizierung","summary":"Minifiziere JavaScript, CSS und HTML aus deinem Code mit den Minifiern von U.","markdown":"---\ntitle: Minifizierung\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/minification/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Minifizierung\n\n> Minifiziere JavaScript, CSS und HTML aus deinem Code mit den Minifiern von U.\n\nDas Framework minifiziert statische `.js`-, `.css`- und `.html`-Dateien sowie zusammengeführte Dateien (siehe [Statische Dateien](../static-files/)). Dieselben Minifier stehen in `U`:\n\n```js\nU.minify_css('.box {\\n\\t.title { margin: 0 0 0 0; color: #FFFFFF; }\\n}');  // '.box .title{margin:0;color:#FFF}'\nU.minify_js('function sum(a, b) {\\n\\t// adds\\n\\treturn a + b;\\n}');        // 'function sum(a,b){return a+b}'\nU.minify_html(html);\n```\n\nDer CSS-Minifier kompiliert auch verschachtelte Regeln (eine Regel, die nur andere Regeln enthält) und Variablen, die als `$name: value;` geschrieben sind. `MERGE()` fasst mehrere Dateien unter einer URL zusammen und ist in [Statische Dateien](../static-files/) beschrieben.\n\nDer HTML-Minifier entfernt Kommentare (aber keine bedingten Kommentare) und fasst Folgen von Leerzeichen zwischen Wörtern zusammen. Zeilenumbrüche und Einrückungen zwischen Tags bleiben erhalten. Eingebettete `<script>` und `<style>` werden minifiziert, wenn `$minifyjs` und `$minifycss` aktiv sind.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"Jafim93VY60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/minification/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Minificación","summary":"Minifica JavaScript, CSS y HTML desde tu código con los minificadores de U.","markdown":"---\ntitle: \"Minificación\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/minification/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Minificación\n\n> Minifica JavaScript, CSS y HTML desde tu código con los minificadores de U.\n\nEl framework minifica los archivos estáticos `.js`, `.css` y `.html` y los archivos combinados (consulta [Archivos estáticos](../static-files/)). Los mismos minificadores están en `U`:\n\n```js\nU.minify_css('.box {\\n\\t.title { margin: 0 0 0 0; color: #FFFFFF; }\\n}');  // '.box .title{margin:0;color:#FFF}'\nU.minify_js('function sum(a, b) {\\n\\t// adds\\n\\treturn a + b;\\n}');        // 'function sum(a,b){return a+b}'\nU.minify_html(html);\n```\n\nEl minificador de CSS también compila reglas anidadas (una regla que solo contiene otras reglas) y variables escritas como `$name: value;`. `MERGE()` une varios archivos en una URL y se describe en [Archivos estáticos](../static-files/).\n\nEl minificador de HTML elimina los comentarios (pero no los comentarios condicionales) y colapsa las secuencias de espacios entre palabras. Se conservan los saltos de línea y la sangría entre etiquetas. Los `<script>` y `<style>` en línea se minifican cuando `$minifyjs` y `$minifycss` están activados.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"Jafim93VY60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/minification/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Minification","summary":"Minifie du JavaScript, du CSS et du HTML depuis ton code avec les minificateurs de U.","markdown":"---\ntitle: Minification\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/minification/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Minification\n\n> Minifie du JavaScript, du CSS et du HTML depuis ton code avec les minificateurs de U.\n\nLe framework minifie les fichiers statiques `.js`, `.css` et `.html` ainsi que les fichiers fusionnés (voir [Fichiers statiques](../static-files/)). Les mêmes minificateurs se trouvent dans `U` :\n\n```js\nU.minify_css('.box {\\n\\t.title { margin: 0 0 0 0; color: #FFFFFF; }\\n}');  // '.box .title{margin:0;color:#FFF}'\nU.minify_js('function sum(a, b) {\\n\\t// adds\\n\\treturn a + b;\\n}');        // 'function sum(a,b){return a+b}'\nU.minify_html(html);\n```\n\nLe minificateur CSS compile aussi les règles imbriquées (une règle qui ne contient que d'autres règles) et les variables écrites sous la forme `$name: value;`. `MERGE()` joint plusieurs fichiers en une seule URL et est décrit dans [Fichiers statiques](../static-files/).\n\nLe minificateur HTML retire les commentaires (mais pas les commentaires conditionnels) et réduit les suites d'espaces entre les mots. Les retours à la ligne et l'indentation entre les balises sont conservés. Les `<script>` et `<style>` inline sont minifiés quand `$minifyjs` et `$minifycss` sont activés.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"Jafim93VY60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/minification/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Minificazione","summary":"Minifica JavaScript, CSS e HTML dal tuo codice con i minificatori di U.","markdown":"---\ntitle: Minificazione\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/minification/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Minificazione\n\n> Minifica JavaScript, CSS e HTML dal tuo codice con i minificatori di U.\n\nIl framework minifica i file statici `.js`, `.css` e `.html` e i file uniti (vedi [File statici](../static-files/)). Gli stessi minificatori sono in `U`:\n\n```js\nU.minify_css('.box {\\n\\t.title { margin: 0 0 0 0; color: #FFFFFF; }\\n}');  // '.box .title{margin:0;color:#FFF}'\nU.minify_js('function sum(a, b) {\\n\\t// adds\\n\\treturn a + b;\\n}');        // 'function sum(a,b){return a+b}'\nU.minify_html(html);\n```\n\nIl minificatore CSS compila anche le regole annidate (una regola che contiene solo altre regole) e le variabili scritte come `$name: value;`. `MERGE()` unisce più file in un unico URL ed è descritto in [File statici](../static-files/).\n\nIl minificatore HTML rimuove i commenti (ma non i commenti condizionali) e riduce le sequenze di spazi tra le parole. Le interruzioni di riga e l'indentazione tra i tag vengono mantenute. `<script>` e `<style>` inline vengono minificati quando `$minifyjs` e `$minifycss` sono attivi.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"Jafim93VY60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/minification/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Minifikácia","summary":"Minifikuj JavaScript, CSS a HTML zo svojho kódu pomocou minifikátorov z U.","markdown":"---\ntitle: \"Minifikácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/minification/\nupdated: 2026-11-16T15:48:48.957Z\n---\n\n# Minifikácia\n\n> Minifikuj JavaScript, CSS a HTML zo svojho kódu pomocou minifikátorov z U.\n\nFramework minifikuje statické súbory `.js`, `.css` a `.html` a zlúčené súbory (pozri [Statické súbory](../static-files/)). Tie isté minifikátory sú v `U`:\n\n```js\nU.minify_css('.box {\\n\\t.title { margin: 0 0 0 0; color: #FFFFFF; }\\n}');  // '.box .title{margin:0;color:#FFF}'\nU.minify_js('function sum(a, b) {\\n\\t// adds\\n\\treturn a + b;\\n}');        // 'function sum(a,b){return a+b}'\nU.minify_html(html);\n```\n\nCSS minifikátor tiež kompiluje vnorené pravidlá (pravidlo, ktoré obsahuje iba iné pravidlá) a premenné zapísané ako `$name: value;`. `MERGE()` spojí viac súborov do jednej URL a je opísaný v [Statické súbory](../static-files/).\n\nHTML minifikátor odstráni komentáre (ale nie podmienené komentáre) a zlúči viacnásobné medzery medzi slovami. Zalomenia riadkov a odsadenie medzi tagmi sa zachovajú. Inline `<script>` a `<style>` sa minifikujú, keď sú zapnuté `$minifyjs` a `$minifycss`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:48:48.957Z"}
{"id":"JafipJ1o861f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/cms/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/cms/\nupdated: 2026-11-16T15:32:37.496Z\n---\n\n# CMS compiler\n\n> Compile pages made with the Total.js CMS editor and render them with their widgets.\n\n`F.TCMS` compiles pages made with the Total.js CMS editor. A page is HTML where every widget is an element with `data-cms=\"<widgetid>__<config>\"`. `F.TCMS.compile(html, widgets)` prepares the page once, and `render()` makes the HTML for each request: it calls `render(opt, next)` of every widget and fills the navigation templates.\n\n```js\nvar widgets = [{\n\tid: 'hello',\n\tcss: '.hello { color: red; }',\n\trender: function(opt, next) {\n\t\tnext('<b>Hello ' + opt.config.name + '</b>');\n\t}\n}];\n\nvar page = F.TCMS.compile(html, widgets);\npage.importcss();\n\nvar output = await page.render({\n\turl: '/about/',\n\tnavigation: function(id) {\n\t\treturn [{ url: '/', name: 'Home' }];\n\t}\n});\n```\n\nA `<script type=\"text/navigation\" id=\"main\">` in the page is a Tangular template; its `value` is what `navigation(id)` returns, where `id` is the `id` attribute (a navigation with only a `name` attribute gets a hash of the name). A `<script type=\"text/breadcrumb\">` gets `opt.breadcrumb`. Elements with the class `CMS_trash` or `CMS_editor` are removed. The CSS and JS of the widgets are minified and joined into `page.css` and `page.js`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JafipJ1o861f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/cms/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/cms/\nupdated: 2026-11-16T15:32:37.496Z\n---\n\n# CMS-Compiler\n\n> Kompiliere Seiten aus dem CMS-Editor von Total.js und rendere sie mit ihren Widgets.\n\n`F.TCMS` kompiliert Seiten, die mit dem Total.js-CMS-Editor erstellt wurden. Eine Seite ist HTML, in dem jedes Widget ein Element mit `data-cms=\"<widgetid>__<config>\"` ist. `F.TCMS.compile(html, widgets)` bereitet die Seite einmal vor, und `render()` erzeugt das HTML für jede Anfrage: Es ruft `render(opt, next)` jedes Widgets auf und füllt die Navigations-Templates.\n\n```js\nvar widgets = [{\n\tid: 'hello',\n\tcss: '.hello { color: red; }',\n\trender: function(opt, next) {\n\t\tnext('<b>Hello ' + opt.config.name + '</b>');\n\t}\n}];\n\nvar page = F.TCMS.compile(html, widgets);\npage.importcss();\n\nvar output = await page.render({\n\turl: '/about/',\n\tnavigation: function(id) {\n\t\treturn [{ url: '/', name: 'Home' }];\n\t}\n});\n```\n\nEin `<script type=\"text/navigation\" id=\"main\">` in der Seite ist ein Tangular-Template; sein `value` ist das, was `navigation(id)` zurückgibt, wobei `id` das Attribut `id` ist (eine Navigation nur mit einem Attribut `name` erhält einen Hash des Namens). Ein `<script type=\"text/breadcrumb\">` erhält `opt.breadcrumb`. Elemente mit der Klasse `CMS_trash` oder `CMS_editor` werden entfernt. Das CSS und JS der Widgets wird minifiziert und zu `page.css` und `page.js` zusammengefügt.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JafipJ1o861f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/cms/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Compilador del CMS","summary":"Compila páginas hechas con el editor del CMS de Total.js y renderízalas con sus widgets.","markdown":"---\ntitle: Compilador del CMS\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/cms/\nupdated: 2026-11-16T15:32:37.496Z\n---\n\n# Compilador del CMS\n\n> Compila páginas hechas con el editor del CMS de Total.js y renderízalas con sus widgets.\n\n`F.TCMS` compila páginas hechas con el editor de Total.js CMS. Una página es HTML donde cada widget es un elemento con `data-cms=\"<widgetid>__<config>\"`. `F.TCMS.compile(html, widgets)` prepara la página una vez, y `render()` genera el HTML para cada petición: llama a `render(opt, next)` de cada widget y rellena las plantillas de navegación.\n\n```js\nvar widgets = [{\n\tid: 'hello',\n\tcss: '.hello { color: red; }',\n\trender: function(opt, next) {\n\t\tnext('<b>Hello ' + opt.config.name + '</b>');\n\t}\n}];\n\nvar page = F.TCMS.compile(html, widgets);\npage.importcss();\n\nvar output = await page.render({\n\turl: '/about/',\n\tnavigation: function(id) {\n\t\treturn [{ url: '/', name: 'Home' }];\n\t}\n});\n```\n\nUn `<script type=\"text/navigation\" id=\"main\">` en la página es una plantilla Tangular; su `value` es lo que devuelve `navigation(id)`, donde `id` es el atributo `id` (una navegación con solo un atributo `name` recibe un hash del nombre). Un `<script type=\"text/breadcrumb\">` recibe `opt.breadcrumb`. Se eliminan los elementos con la clase `CMS_trash` o `CMS_editor`. El CSS y el JS de los widgets se minifican y se unen en `page.css` y `page.js`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JafipJ1o861f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/cms/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/cms/\nupdated: 2026-11-16T15:32:37.496Z\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`F.TCMS` compile les pages créées avec l'éditeur de Total.js CMS. Une page est du HTML où chaque widget est un élément avec `data-cms=\"<widgetid>__<config>\"`. `F.TCMS.compile(html, widgets)` prépare la page une fois, et `render()` produit le HTML pour chaque requête : elle appelle `render(opt, next)` de chaque widget et remplit les templates de navigation.\n\n```js\nvar widgets = [{\n\tid: 'hello',\n\tcss: '.hello { color: red; }',\n\trender: function(opt, next) {\n\t\tnext('<b>Hello ' + opt.config.name + '</b>');\n\t}\n}];\n\nvar page = F.TCMS.compile(html, widgets);\npage.importcss();\n\nvar output = await page.render({\n\turl: '/about/',\n\tnavigation: function(id) {\n\t\treturn [{ url: '/', name: 'Home' }];\n\t}\n});\n```\n\nUn `<script type=\"text/navigation\" id=\"main\">` dans la page est un template Tangular ; sa `value` est ce que renvoie `navigation(id)`, où `id` est l'attribut `id` (une navigation ayant seulement un attribut `name` reçoit un hash du nom). Un `<script type=\"text/breadcrumb\">` reçoit `opt.breadcrumb`. Les éléments ayant la classe `CMS_trash` ou `CMS_editor` sont supprimés. Le CSS et le JS des widgets sont minifiés et joints dans `page.css` et `page.js`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JafipJ1o861f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/cms/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/cms/\nupdated: 2026-11-16T15:32:37.496Z\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`F.TCMS` compila le pagine create con l'editor di Total.js CMS. Una pagina è HTML in cui ogni widget è un elemento con `data-cms=\"<widgetid>__<config>\"`. `F.TCMS.compile(html, widgets)` prepara la pagina una volta, e `render()` produce l'HTML per ogni richiesta: chiama `render(opt, next)` di ogni widget e riempie i template di navigazione.\n\n```js\nvar widgets = [{\n\tid: 'hello',\n\tcss: '.hello { color: red; }',\n\trender: function(opt, next) {\n\t\tnext('<b>Hello ' + opt.config.name + '</b>');\n\t}\n}];\n\nvar page = F.TCMS.compile(html, widgets);\npage.importcss();\n\nvar output = await page.render({\n\turl: '/about/',\n\tnavigation: function(id) {\n\t\treturn [{ url: '/', name: 'Home' }];\n\t}\n});\n```\n\nUno `<script type=\"text/navigation\" id=\"main\">` nella pagina è un template Tangular; il suo `value` è ciò che restituisce `navigation(id)`, dove `id` è l'attributo `id` (una navigazione con solo un attributo `name` riceve un hash del nome). Uno `<script type=\"text/breadcrumb\">` riceve `opt.breadcrumb`. Gli elementi con la classe `CMS_trash` o `CMS_editor` vengono rimossi. Il CSS e il JS dei widget vengono minificati e uniti in `page.css` e `page.js`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JafipJ1o861f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/cms/","project":"total-js-v5","version":"0-0-20","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 V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/cms/\nupdated: 2026-11-16T15:32:37.496Z\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`F.TCMS` kompiluje stránky vytvorené v editore Total.js CMS. Stránka je HTML, kde je každý widget element s `data-cms=\"<widgetid>__<config>\"`. `F.TCMS.compile(html, widgets)` pripraví stránku raz a `render()` vytvorí HTML pre každú požiadavku: zavolá `render(opt, next)` každého widgetu a vyplní šablóny navigácie.\n\n```js\nvar widgets = [{\n\tid: 'hello',\n\tcss: '.hello { color: red; }',\n\trender: function(opt, next) {\n\t\tnext('<b>Hello ' + opt.config.name + '</b>');\n\t}\n}];\n\nvar page = F.TCMS.compile(html, widgets);\npage.importcss();\n\nvar output = await page.render({\n\turl: '/about/',\n\tnavigation: function(id) {\n\t\treturn [{ url: '/', name: 'Home' }];\n\t}\n});\n```\n\n`<script type=\"text/navigation\" id=\"main\">` na stránke je šablóna Tangular; jej `value` je to, čo vráti `navigation(id)`, kde `id` je atribút `id` (navigácia iba s atribútom `name` dostane hash názvu). `<script type=\"text/breadcrumb\">` dostane `opt.breadcrumb`. Elementy s triedou `CMS_trash` alebo `CMS_editor` sa odstránia. CSS a JS widgetov sa minifikujú a spoja do `page.css` a `page.js`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:32:37.496Z"}
{"id":"JaqmAy1fc60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/application-structure/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Application structure and modes","summary":"The start script, the folders and their loading order, debug and release mode, bundles, remote editing, modules and statistics.","markdown":"---\ntitle: Application structure and modes\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/application-structure/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Application structure and modes\n\n> The start script, the folders and their loading order, debug and release mode, bundles, remote editing, modules and statistics.\n\nA Total.js 5 application is a folder with a start script, a few plain files and folders with JavaScript files. The framework scans the folders in a fixed order when it starts, so a file only needs to be in the right folder to be loaded. How to install `total5` and create the first project is in the guide [Installation](../../guides/installation/).\n\n## The start script\n\nThe start script (usually `index.js`) is the file that you run with `node`. It loads `total5` and calls `F.run()` with the start options:\n\n```js\nrequire('total5');\n\nvar options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'Total.js' };\n// options.cluster = 'auto';\n\nF.run(options);\n```\n\n`F.run()` starts the application in **debug** mode with a watcher. With `options.watcher = false` it starts in **release** mode. Both modes are explained below; every option is in the [reference](../../reference/application-structure/).\n\nThe root of the application is the current working directory of the process (`F.directory`), so start the script from the folder of the application: `cd /www/app && node index.js`. When the script loads `total5`, the framework also changes the working directory of the process (`process.cwd()`) to the folder of the start script, except inside worker threads.\n\n## Folders and the loading order\n\n`LOAD()` (called by `F.http()` and `F.run()`) reads the application in this order:\n\n1. `.env`: environment variables\n2. `config`: the configuration (see [Configuration](../../guides/configuration/))\n3. `version`: the first line becomes `CONF.version` as a number\n4. `resources/*.resource`: dictionaries (see [Localization](../../guides/localization/))\n5. `jsonschemas/*.json` and `jsonschemas/*.txt`: JSON schemas, named after the file\n6. the JavaScript files of `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers` and `middleware`, in this order\n7. `plugins/`: every plugin folder: its `index.js`, then the JavaScript files of its `extensions`, `controllers`, `actions`, `schemas`, `models`, `definitions` and `middleware` folders (see [Plugins and components](../../guides/plugins-and-components/)). A folder without `index.js` is skipped. A `config` file in the plugin folder is read like the main `config`, before the JavaScript files are loaded. An `index.flow` file in the plugin folder is loaded as a FlowStream of the plugin (`PLUGINS.<id>.flowstream`)\n8. `flowstreams/*.flow`: the FlowStream engine loads the flows (see [FlowStream](../../guides/flowstream/))\n9. the framework statistics and the service timer\n\nThe folders are read recursively. Files with `-bk` or `_bk` in the name are skipped, which is handy for keeping a backup copy of a file next to the original. Each JavaScript file is loaded with `require()`, and when it exports an `install()` function, the framework calls it:\n\n```js\n// controllers/api.js\nexports.install = function() {\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n```\n\nWhen everything is loaded, `F.isLoaded` is `true`, the number of files and the time are in `F.stats.compiled` and `F.stats.compilation`, and the events `ready` and `load` are emitted (see [Scheduling and events](../../guides/scheduling-and-events/)).\n\nOther folders are used while the application runs, not loaded: `public` ([static files](../../guides/static-files/)), `views` ([Views](../../guides/views/)), `databases`, `tmp`, `logs`, `templates`, `private`. `F.dir()` sets their paths, and a `$dir...` configuration key moves one.\n\n### Loading only some parts\n\n`LOAD()` accepts a list of parts (the names are in the reference), so a background process can load only what it needs, without the HTTP server:\n\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\t// the application is ready, without the web server\n});\n```\n\n## Debug mode and the watcher\n\nIn debug mode (`F.run()` without `watcher: false`) two processes run. The first one is the **watcher**: it starts the application in a child process and watches the files. When a file changes, it prints a line and restarts the child:\n\n```\n--- UPD --- [ 2025-03-01 10:15:22 ] --------> /controllers/api.js\n```\n\n`ADD`, `UPD` and `REM` mark added, updated and removed files, and `RES` a restart asked by the application itself with `F.restart()`.\n\nThe watcher reads these folders: `controllers`, `definitions`, `extensions`, `modules`, `models`, `schemas`, `actions`, `resources`, `source`, `workers`, `middleware`, `bundles`, `transforms`, `startup` and `plugins`, plus the folders in `options.watch`. Inside them it reacts to files with the extensions `.js`, `.ts`, `.py`, `.resource`, `.package`, `.bundle`, `.build`, `.url` and `.html`, and to files named `config` (for example `plugins/<name>/config`), but not to files inside a `public` folder. In the root folder it watches the files `config` and `version` and files ending with `.ts`, `.py` or `.resource` (other `.js` files in the root are ignored, and so is the start script). The `public` and `views` folders are not watched (except with bundles or live reload, see below). A file that is still being written (its size keeps growing between two checks, for example a slow copy over the network) is checked again in the next round, so the application restarts only when the file is complete.\n\nThe watcher polls the files every few seconds. In debug mode `DEBUG` is `true` in the application process, and the console prints the start information (`F.console()`) after the first start.\n\nThe watcher writes its PID into `<script>.pid` (`index.pid`); deleting the file stops the watcher and the application within a few seconds. When the application process ends by itself, the watcher ends too. `options.inspector` starts the child with `--inspect=<port>`.\n\n### Live reload\n\nWith `options.livereload` set to the hostname of your application, the watcher connects to the Total.js live reload service (`wss://livereload.totaljs.com/?hostname=...`) and sends the name of every changed `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` or `.resource` file there, including changes in `public` and `views`. Other files in the watched folders are not watched in this mode.\n\n## Release mode\n\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nIn release mode the application runs in the same process, without the watcher, and `DEBUG` is `false`. Started with the `--watcher` argument (`node index.js --watcher`), the process becomes a watcher for release mode: it prints `RELEASE PID`, starts the application in a child process, writes `<script>.pid`, restarts the application when it ends and stops when the PID file is deleted. It does not watch the files.\n\n### Service mode\n\n`options.servicemode` loads the application without the HTTP server: `true` loads everything, a string such as `'config,modules,actions'` loads only these parts (the names of `LOAD()`). It works in both modes.\n\n### Cluster\n\n`options.cluster` starts the application in several Node.js cluster threads that share the port: a number, or `'auto'`, which starts with one thread and adds threads (up to `options.limit`) when the threads answer slowly. In debug mode the watcher restarts all threads when a file changes; the cluster runs without a watcher when `options.release` is `true`. More about threads is in [Workers and threads](../../guides/workers-and-threads/).\n\n## Bundles\n\nA bundle is one `.bundle` file with the files of an application or of a part of it (a module, a plugin, an admin). You create it with the `total5 bundle` command (see [Command line](../../guides/command-line/)) and place it into the `bundles` folder of another application.\n\nWhen `bundles` contains files, `LOAD()` builds the application in the hidden folder `.src` and runs it from there (`F.isBundle` is `true` and `F.directory` points to `.src`):\n\n1. Every `bundles/<name>.url` file contains a URL; the bundle is downloaded into `bundles/<name>.bundle`.\n2. The files of the previous build (listed in `.src/bundle.json`) are removed.\n3. Every `.bundle` file (except `-bk` and `_bk` copies) is extracted into `.src`. A file of `/updates/` is skipped when it, or its `_bk` copy, already exists in `.src`; a file of `/startup/` or `/databases/` is skipped when it already exists there.\n4. The files of the application itself are copied over the extracted ones, so your own files win. The folders `tmp`, `bundles`, `logs`, `node_modules`, hidden files and folders in the root and the PID files are skipped.\n5. The list of files is written to `.src/bundle.json`.\n\nThe `config` files, `sitemap`, `versions`, `workflows`, `dependencies` and `.resource` files are merged (each copy is appended), so several bundles can add keys to the same `config`. A file whose name starts with `--` (`/controllers/--api.js`) is appended to the file without the dashes.\n\nA `.bundleignore` file in the root lists paths that are not copied, one per line: a folder (`/docs/`), a file (`/readme.md`) or the files with one extension in a folder (`/public/*.map`).\n\n```\n/docs/\n/readme.md\n/public/*.map\n```\n\nWith the configuration key `bundling` set to `'shallow'`, the build is skipped when `.src/bundle.json` exists and the application runs from the existing `.src`. Bundles are extracted before the `config` file is read, so set the key in the start options: `F.run({ config: { bundling: 'shallow' } })`.\n\nA file named `bundles.debug` in the root skips the build and runs the application directly from `.src`. It is for editing an extracted application in place: the debug watcher then watches `.src`.\n\nWith bundles, the debug watcher watches every file: changes in `public` and `views` are copied into `.src` without a restart, other changes rebuild `.src` and restart.\n\n## Remote editing\n\nThe Total.js Code Editor can edit the files of a running application. The application connects to the editor with a WebSocket, so it works behind a firewall without an open port:\n\n```js\nrequire('total5');\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\nThe URL comes from the editor (`http` is changed to `ws`). The client reconnects every 10 seconds when the connection is lost, also after the answers `404 project not found` and `409 project is already open`.\n\nThe editor can browse, load, save, create, rename, remove, upload and download files, read and clear the logs and, in debug mode, restart the application. It can also run a file on the server (`exec`): a `.js` file with Node.js, a `.sh` file with `sh`, or with a command that the editor sends; the output comes back to the editor. Saved files are written into the folder of the application, so in debug mode the watcher restarts the application after each change.\n\nIn debug mode the editor client runs in the watcher process. In release mode it runs in the watcher process when the application is started with `--watcher`. `F.remote(url, [directory])` starts the same client from your own code, and `total5 edit <url>` starts it for the current folder without running the application.\n\n### Remote editing by an AI agent\n\n`editmcp` does the same for an AI agent. The application connects to an MCP edit proxy, and the agent works on the files through the MCP tools of the proxy:\n\n```js\nrequire('total5');\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nThe proxy is a Total.js application with `$mcp : true` and one WebSocket route:\n\n```js\nconst editmcp = require('total5/edit-mcp');\nROUTE('SOCKET /$mcp/', $ => editmcp.proxy($));\n```\n\nThe agent connects to the MCP endpoint of the proxy with the same id, `https://proxy.example.com/$mcp/?id=myproject`, and gets the tools `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` and `App_restart`. The proxy sends each call to the connected application, where it runs; when no application with that id is connected the answer is `App is offline.`. Paths are relative to the application root. Each `App_write` saves the written content as a numbered revision in the folder `revisions/`, and `App_restore` returns the content of an earlier revision.\n\n`App_shell` runs any shell command on the computer of the application, so protect the endpoint of the proxy with `Total.mcp.auth` (see [MCP server](../mcp-server/)). Like `edit`, the client runs in the watcher process.\n\n## Modules and MODS\n\nA file in `modules` is a module: a piece of code that the rest of the application uses. The framework registers it in `MODS` (`F.modules`) under `exports.id`, or under the file name when `id` is missing, and then calls `install()`:\n\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.install = function() {\n\tROUTE('GET /counter/', function($) {\n\t\t$.json({ count: exports.increment() });\n\t});\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// anywhere after the start\nMODS.counter.increment();\n```\n\nPlugins are registered in `PLUGINS` in the same way (see [Plugins and components](../../guides/plugins-and-components/)).\n\n## IMPORT() and REQUIRE()\n\n`REQUIRE(name)` loads a Node.js module or an NPM package and also looks into `CONF.$nodemodules`. `IMPORT(url)` downloads a JavaScript file into the temporary folder and loads it, once per process:\n\n```js\nvar Fs = REQUIRE('fs');\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\n```\n\n## Framework statistics\n\n`F.stats` holds counters for the whole life of the process: requests by method and type, responses by type and HTTP code, transferred data, `compilation` and `compiled` from the start, and `error`.\n\nOnce a minute the service timer computes the usage statistics of the process into `F.consumption` and emits `ON('$stats', stats)`. The first statistics are computed 5 seconds after the application is loaded. When `CONF.$stats` is `true` (the default), they are also written into `<script>.json` next to the start script (`index.js.json`), so a monitoring tool can read them without asking the application:\n\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory usage:', stats.memory, 'MB');\n});\n```\n\nThe fields (memory, requests, errors, per-minute counters ...) are listed in the reference of `F.consumption`. `overload` counts the hours in which the usage was above 80 %, the memory above 600 MB or more than 1000 requests were pending. `uptime` is the number of minutes since the start.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmAy1fc60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/application-structure/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Anwendungsstruktur und Modi","summary":"Das Startskript, die Ordner und ihre Ladereihenfolge, Debug- und Release-Modus, Bundles, Remote-Bearbeitung, Module und Statistiken.","markdown":"---\ntitle: Anwendungsstruktur und Modi\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/application-structure/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Anwendungsstruktur und Modi\n\n> Das Startskript, die Ordner und ihre Ladereihenfolge, Debug- und Release-Modus, Bundles, Remote-Bearbeitung, Module und Statistiken.\n\nEine Total.js-5-Anwendung ist ein Ordner mit einem Startskript, ein paar einfachen Dateien und Ordnern mit JavaScript-Dateien. Das Framework durchsucht die Ordner beim Start in einer festen Reihenfolge, eine Datei muss also nur im richtigen Ordner liegen, um geladen zu werden. Wie du `total5` installierst und das erste Projekt erstellst, steht in der Anleitung [Installation](../../guides/installation/).\n\n## Das Startskript\n\nDas Startskript (meist `index.js`) ist die Datei, die du mit `node` ausführst. Es lädt `total5` und ruft `F.run()` mit den Startoptionen auf:\n\n```js\nrequire('total5');\n\nvar options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'Total.js' };\n// options.cluster = 'auto';\n\nF.run(options);\n```\n\n`F.run()` startet die Anwendung im **Debug**-Modus mit einem Watcher. Mit `options.watcher = false` startet sie im **Release**-Modus. Beide Modi werden unten erklärt; jede Option steht in der [Referenz](../../reference/application-structure/).\n\nDas Stammverzeichnis der Anwendung ist das aktuelle Arbeitsverzeichnis des Prozesses (`F.directory`), also starte das Skript aus dem Ordner der Anwendung: `cd /www/app && node index.js`. Wenn das Skript `total5` lädt, ändert das Framework außerdem das Arbeitsverzeichnis des Prozesses (`process.cwd()`) auf den Ordner des Startskripts, außer in Worker-Threads.\n\n## Ordner und die Ladereihenfolge\n\n`LOAD()` (aufgerufen von `F.http()` und `F.run()`) liest die Anwendung in dieser Reihenfolge:\n\n1. `.env`: Umgebungsvariablen\n2. `config`: die Konfiguration (siehe [Konfiguration](../../guides/configuration/))\n3. `version`: die erste Zeile wird als Zahl zu `CONF.version`\n4. `resources/*.resource`: Wörterbücher (siehe [Lokalisierung](../../guides/localization/))\n5. `jsonschemas/*.json` und `jsonschemas/*.txt`: JSON-Schemas, benannt nach der Datei\n6. die JavaScript-Dateien von `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers` und `middleware`, in dieser Reihenfolge\n7. `plugins/`: jeder Plugin-Ordner: seine `index.js`, dann die JavaScript-Dateien seiner Ordner `extensions`, `controllers`, `actions`, `schemas`, `models`, `definitions` und `middleware` (siehe [Plugins und Komponenten](../../guides/plugins-and-components/)). Ein Ordner ohne `index.js` wird übersprungen. Eine `config`-Datei im Plugin-Ordner wird wie die Haupt-`config` gelesen, bevor die JavaScript-Dateien geladen werden. Eine Datei `index.flow` im Plugin-Ordner wird als FlowStream des Plugins geladen (`PLUGINS.<id>.flowstream`)\n8. `flowstreams/*.flow`: Die FlowStream-Engine lädt die Flows (siehe [FlowStream](../../guides/flowstream/))\n9. die Framework-Statistiken und der Service-Timer\n\nDie Ordner werden rekursiv gelesen. Dateien mit `-bk` oder `_bk` im Namen werden übersprungen, was praktisch ist, um eine Sicherungskopie einer Datei neben dem Original aufzubewahren. Jede JavaScript-Datei wird mit `require()` geladen, und wenn sie eine Funktion `install()` exportiert, ruft das Framework sie auf:\n\n```js\n// controllers/api.js\nexports.install = function() {\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n```\n\nWenn alles geladen ist, ist `F.isLoaded` gleich `true`, die Anzahl der Dateien und die Zeit stehen in `F.stats.compiled` und `F.stats.compilation`, und die Events `ready` und `load` werden ausgelöst (siehe [Zeitplanung und Events](../../guides/scheduling-and-events/)).\n\nAndere Ordner werden während der Laufzeit der Anwendung verwendet, nicht geladen: `public` ([statische Dateien](../../guides/static-files/)), `views` ([Views](../../guides/views/)), `databases`, `tmp`, `logs`, `templates`, `private`. `F.dir()` setzt ihre Pfade, und ein Konfigurationsschlüssel `$dir...` verschiebt einen davon.\n\n### Nur einige Teile laden\n\n`LOAD()` akzeptiert eine Liste von Teilen (die Namen stehen in der Referenz), sodass ein Hintergrundprozess nur das laden kann, was er braucht, ohne den HTTP-Server:\n\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\t// the application is ready, without the web server\n});\n```\n\n## Debug-Modus und der Watcher\n\nIm Debug-Modus (`F.run()` ohne `watcher: false`) laufen zwei Prozesse. Der erste ist der **Watcher**: Er startet die Anwendung in einem Kindprozess und überwacht die Dateien. Wenn sich eine Datei ändert, gibt er eine Zeile aus und startet das Kind neu:\n\n```\n--- UPD --- [ 2025-03-01 10:15:22 ] --------> /controllers/api.js\n```\n\n`ADD`, `UPD` und `REM` markieren hinzugefügte, aktualisierte und entfernte Dateien, und `RES` einen Neustart, den die Anwendung selbst mit `F.restart()` angefordert hat.\n\nDer Watcher liest diese Ordner: `controllers`, `definitions`, `extensions`, `modules`, `models`, `schemas`, `actions`, `resources`, `source`, `workers`, `middleware`, `bundles`, `transforms`, `startup` und `plugins`, dazu die Ordner in `options.watch`. Darin reagiert er auf Dateien mit den Endungen `.js`, `.ts`, `.py`, `.resource`, `.package`, `.bundle`, `.build`, `.url` und `.html` und auf Dateien namens `config` (zum Beispiel `plugins/<name>/config`), aber nicht auf Dateien in einem `public`-Ordner. Im Stammordner überwacht er die Dateien `config` und `version` und Dateien, die auf `.ts`, `.py` oder `.resource` enden (andere `.js`-Dateien im Stammordner werden ignoriert, ebenso das Startskript). Die Ordner `public` und `views` werden nicht überwacht (außer mit Bundles oder Live Reload, siehe unten). Eine Datei, die noch geschrieben wird (ihre Größe wächst zwischen zwei Prüfungen weiter, zum Beispiel bei einer langsamen Kopie über das Netzwerk), wird in der nächsten Runde erneut geprüft, sodass die Anwendung erst neu startet, wenn die Datei vollständig ist.\n\nDer Watcher fragt die Dateien alle paar Sekunden ab. Im Debug-Modus ist `DEBUG` im Anwendungsprozess `true`, und die Konsole gibt nach dem ersten Start die Startinformationen aus (`F.console()`).\n\nDer Watcher schreibt seine PID in `<script>.pid` (`index.pid`); wenn du die Datei löschst, beenden sich der Watcher und die Anwendung innerhalb weniger Sekunden. Wenn der Anwendungsprozess von selbst endet, endet auch der Watcher. `options.inspector` startet das Kind mit `--inspect=<port>`.\n\n### Live Reload\n\nWenn `options.livereload` auf den Hostnamen deiner Anwendung gesetzt ist, verbindet sich der Watcher mit dem Live-Reload-Dienst von Total.js (`wss://livereload.totaljs.com/?hostname=...`) und sendet dorthin den Namen jeder geänderten Datei mit `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` oder `.resource`, einschließlich Änderungen in `public` und `views`. Andere Dateien in den überwachten Ordnern werden in diesem Modus nicht überwacht.\n\n## Release-Modus\n\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nIm Release-Modus läuft die Anwendung im selben Prozess, ohne den Watcher, und `DEBUG` ist `false`. Mit dem Argument `--watcher` gestartet (`node index.js --watcher`), wird der Prozess zu einem Watcher für den Release-Modus: Er gibt `RELEASE PID` aus, startet die Anwendung in einem Kindprozess, schreibt `<script>.pid`, startet die Anwendung neu, wenn sie endet, und beendet sich, wenn die PID-Datei gelöscht wird. Die Dateien überwacht er nicht.\n\n### Service-Modus\n\n`options.servicemode` lädt die Anwendung ohne den HTTP-Server: `true` lädt alles, ein String wie `'config,modules,actions'` lädt nur diese Teile (die Namen von `LOAD()`). Das funktioniert in beiden Modi.\n\n### Cluster\n\n`options.cluster` startet die Anwendung in mehreren Node.js-Cluster-Threads, die sich den Port teilen: eine Zahl oder `'auto'`, das mit einem Thread beginnt und Threads hinzufügt (bis zu `options.limit`), wenn die Threads langsam antworten. Im Debug-Modus startet der Watcher alle Threads neu, wenn sich eine Datei ändert; der Cluster läuft ohne Watcher, wenn `options.release` `true` ist. Mehr über Threads steht unter [Worker, Threads und Cluster](../../guides/workers-and-threads/).\n\n## Bundles\n\nEin Bundle ist eine einzelne `.bundle`-Datei mit den Dateien einer Anwendung oder eines Teils davon (ein Modul, ein Plugin, ein Admin). Du erstellst es mit dem Befehl `total5 bundle` (siehe [Kommandozeile](../../guides/command-line/)) und legst es in den Ordner `bundles` einer anderen Anwendung.\n\nWenn `bundles` Dateien enthält, baut `LOAD()` die Anwendung im versteckten Ordner `.src` und führt sie von dort aus (`F.isBundle` ist `true` und `F.directory` zeigt auf `.src`):\n\n1. Jede Datei `bundles/<name>.url` enthält eine URL; das Bundle wird nach `bundles/<name>.bundle` heruntergeladen.\n2. Die Dateien des vorherigen Builds (aufgelistet in `.src/bundle.json`) werden entfernt.\n3. Jede `.bundle`-Datei (außer Kopien mit `-bk` und `_bk`) wird nach `.src` entpackt. Eine Datei aus `/updates/` wird übersprungen, wenn sie oder ihre `_bk`-Kopie bereits in `.src` existiert; eine Datei aus `/startup/` oder `/databases/` wird übersprungen, wenn sie dort bereits existiert.\n4. Die Dateien der Anwendung selbst werden über die entpackten kopiert, sodass deine eigenen Dateien gewinnen. Die Ordner `tmp`, `bundles`, `logs`, `node_modules`, versteckte Dateien und Ordner im Stammverzeichnis und die PID-Dateien werden übersprungen.\n5. Die Liste der Dateien wird in `.src/bundle.json` geschrieben.\n\nDie `config`-Dateien, `sitemap`, `versions`, `workflows`, `dependencies` und `.resource`-Dateien werden zusammengeführt (jede Kopie wird angehängt), sodass mehrere Bundles Schlüssel zur selben `config` hinzufügen können. Eine Datei, deren Name mit `--` beginnt (`/controllers/--api.js`), wird an die Datei ohne die Bindestriche angehängt.\n\nEine Datei `.bundleignore` im Stammverzeichnis listet Pfade auf, die nicht kopiert werden, einen pro Zeile: einen Ordner (`/docs/`), eine Datei (`/readme.md`) oder die Dateien mit einer Endung in einem Ordner (`/public/*.map`).\n\n```\n/docs/\n/readme.md\n/public/*.map\n```\n\nWenn der Konfigurationsschlüssel `bundling` auf `'shallow'` gesetzt ist, wird der Build übersprungen, sobald `.src/bundle.json` existiert, und die Anwendung läuft aus dem vorhandenen `.src`. Bundles werden entpackt, bevor die Datei `config` gelesen wird, also setze den Schlüssel in den Startoptionen: `F.run({ config: { bundling: 'shallow' } })`.\n\nEine Datei namens `bundles.debug` im Stammverzeichnis überspringt den Build und führt die Anwendung direkt aus `.src` aus. Sie ist dafür gedacht, eine entpackte Anwendung an Ort und Stelle zu bearbeiten: Der Debug-Watcher überwacht dann `.src`.\n\nMit Bundles überwacht der Debug-Watcher jede Datei: Änderungen in `public` und `views` werden ohne Neustart nach `.src` kopiert, andere Änderungen bauen `.src` neu und starten neu.\n\n## Remote-Bearbeitung\n\nDer Total.js Code Editor kann die Dateien einer laufenden Anwendung bearbeiten. Die Anwendung verbindet sich über einen WebSocket mit dem Editor, daher funktioniert das hinter einer Firewall ohne offenen Port:\n\n```js\nrequire('total5');\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\nDie URL kommt vom Editor (`http` wird zu `ws` geändert). Der Client verbindet sich alle 10 Sekunden neu, wenn die Verbindung verloren geht, auch nach den Antworten `404 project not found` und `409 project is already open`.\n\nDer Editor kann Dateien durchsuchen, laden, speichern, erstellen, umbenennen, entfernen, hochladen und herunterladen, die Logs lesen und leeren und im Debug-Modus die Anwendung neu starten. Er kann außerdem eine Datei auf dem Server ausführen (`exec`): eine `.js`-Datei mit Node.js, eine `.sh`-Datei mit `sh` oder mit einem Befehl, den der Editor sendet; die Ausgabe kommt zum Editor zurück. Gespeicherte Dateien werden in den Ordner der Anwendung geschrieben, daher startet der Watcher im Debug-Modus die Anwendung nach jeder Änderung neu.\n\nIm Debug-Modus läuft der Editor-Client im Watcher-Prozess. Im Release-Modus läuft er im Watcher-Prozess, wenn die Anwendung mit `--watcher` gestartet wird. `F.remote(url, [directory])` startet denselben Client aus deinem eigenen Code, und `total5 edit <url>` startet ihn für den aktuellen Ordner, ohne die Anwendung auszuführen.\n\n### Remote-Bearbeitung durch einen KI-Agenten\n\n`editmcp` macht dasselbe für einen KI-Agenten. Die Anwendung verbindet sich mit einem MCP-Bearbeitungsproxy, und der Agent arbeitet über die MCP-Tools des Proxys an den Dateien:\n\n```js\nrequire('total5');\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nDer Proxy ist eine Total.js-Anwendung mit `$mcp : true` und einer WebSocket-Route:\n\n```js\nconst editmcp = require('total5/edit-mcp');\nROUTE('SOCKET /$mcp/', $ => editmcp.proxy($));\n```\n\nDer Agent verbindet sich mit derselben id mit dem MCP-Endpunkt des Proxys, `https://proxy.example.com/$mcp/?id=myproject`, und erhält die Tools `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` und `App_restart`. Der Proxy schickt jeden Aufruf an die verbundene Anwendung, wo er ausgeführt wird; wenn keine Anwendung mit dieser id verbunden ist, lautet die Antwort `App is offline.`. Pfade sind relativ zum Stammverzeichnis der Anwendung. Jedes `App_write` speichert den geschriebenen Inhalt als nummerierte Revision im Ordner `revisions/`, und `App_restore` gibt den Inhalt einer früheren Revision zurück.\n\n`App_shell` führt jeden beliebigen Shell-Befehl auf dem Computer der Anwendung aus, also schütze den Endpunkt des Proxys mit `Total.mcp.auth` (siehe [MCP-Server](../mcp-server/)). Wie bei `edit` läuft der Client im Watcher-Prozess.\n\n## Module und MODS\n\nEine Datei in `modules` ist ein Modul: ein Stück Code, das der Rest der Anwendung verwendet. Das Framework registriert es in `MODS` (`F.modules`) unter `exports.id`, oder unter dem Dateinamen, wenn `id` fehlt, und ruft dann `install()` auf:\n\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.install = function() {\n\tROUTE('GET /counter/', function($) {\n\t\t$.json({ count: exports.increment() });\n\t});\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// anywhere after the start\nMODS.counter.increment();\n```\n\nPlugins werden auf die gleiche Weise in `PLUGINS` registriert (siehe [Plugins und Komponenten](../../guides/plugins-and-components/)).\n\n## IMPORT() und REQUIRE()\n\n`REQUIRE(name)` lädt ein Node.js-Modul oder ein NPM-Paket und sucht auch in `CONF.$nodemodules`. `IMPORT(url)` lädt eine JavaScript-Datei in den temporären Ordner herunter und lädt sie, einmal pro Prozess:\n\n```js\nvar Fs = REQUIRE('fs');\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\n```\n\n## Framework-Statistiken\n\n`F.stats` enthält Zähler für die gesamte Lebensdauer des Prozesses: Anfragen nach Methode und Typ, Antworten nach Typ und HTTP-Code, übertragene Daten, `compilation` und `compiled` vom Start sowie `error`.\n\nEinmal pro Minute berechnet der Service-Timer die Nutzungsstatistiken des Prozesses in `F.consumption` und löst `ON('$stats', stats)` aus. Die ersten Statistiken werden 5 Sekunden nach dem Laden der Anwendung berechnet. Wenn `CONF.$stats` `true` ist (der Standard), werden sie außerdem in `<script>.json` neben dem Startskript geschrieben (`index.js.json`), sodass ein Überwachungstool sie lesen kann, ohne die Anwendung zu fragen:\n\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory usage:', stats.memory, 'MB');\n});\n```\n\nDie Felder (Speicher, Anfragen, Fehler, Zähler pro Minute ...) sind in der Referenz von `F.consumption` aufgelistet. `overload` zählt die Stunden, in denen die Auslastung über 80 % lag, der Speicher über 600 MB lag oder mehr als 1000 Anfragen ausstanden. `uptime` ist die Anzahl der Minuten seit dem Start.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmAy1fc60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/application-structure/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Estructura de la aplicación y modos","summary":"El script de arranque, las carpetas y su orden de carga, el modo debug y release, los bundles, la edición remota, los módulos y las estadísticas.","markdown":"---\ntitle: \"Estructura de la aplicación y modos\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/application-structure/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Estructura de la aplicación y modos\n\n> El script de arranque, las carpetas y su orden de carga, el modo debug y release, los bundles, la edición remota, los módulos y las estadísticas.\n\nUna aplicación Total.js 5 es una carpeta con un script de arranque, unos pocos archivos simples y carpetas con archivos JavaScript. El framework recorre las carpetas en un orden fijo al arrancar, así que a un archivo le basta con estar en la carpeta correcta para cargarse. Cómo instalar `total5` y crear el primer proyecto está en la guía [Instalación](../../guides/installation/).\n\n## El script de arranque\n\nEl script de arranque (normalmente `index.js`) es el archivo que ejecutas con `node`. Carga `total5` y llama a `F.run()` con las opciones de arranque:\n\n```js\nrequire('total5');\n\nvar options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'Total.js' };\n// options.cluster = 'auto';\n\nF.run(options);\n```\n\n`F.run()` arranca la aplicación en modo **debug** con un watcher. Con `options.watcher = false` arranca en modo **release**. Los dos modos se explican más abajo; todas las opciones están en la [referencia](../../reference/application-structure/).\n\nLa raíz de la aplicación es el directorio de trabajo actual del proceso (`F.directory`), así que arranca el script desde la carpeta de la aplicación: `cd /www/app && node index.js`. Cuando el script carga `total5`, el framework también cambia el directorio de trabajo del proceso (`process.cwd()`) a la carpeta del script de arranque, excepto dentro de los worker threads.\n\n## Las carpetas y el orden de carga\n\n`LOAD()` (lo llaman `F.http()` y `F.run()`) lee la aplicación en este orden:\n\n1. `.env`: variables de entorno\n2. `config`: la configuración (consulta [Configuración](../../guides/configuration/))\n3. `version`: la primera línea se convierte en `CONF.version` como número\n4. `resources/*.resource`: diccionarios (consulta [Localización](../../guides/localization/))\n5. `jsonschemas/*.json` y `jsonschemas/*.txt`: esquemas JSON, con el nombre del archivo\n6. los archivos JavaScript de `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers` y `middleware`, en este orden\n7. `plugins/`: cada carpeta de plugin: su `index.js`, y después los archivos JavaScript de sus carpetas `extensions`, `controllers`, `actions`, `schemas`, `models`, `definitions` y `middleware` (consulta [Plugins y componentes](../../guides/plugins-and-components/)). Una carpeta sin `index.js` se omite. Un archivo `config` en la carpeta del plugin se lee como el `config` principal, antes de cargar los archivos JavaScript. Un archivo `index.flow` en la carpeta del plugin se carga como un FlowStream del plugin (`PLUGINS.<id>.flowstream`)\n8. `flowstreams/*.flow`: el motor de FlowStream carga los flujos (consulta [FlowStream](../../guides/flowstream/))\n9. las estadísticas del framework y el temporizador del servicio\n\nLas carpetas se leen de forma recursiva. Los archivos con `-bk` o `_bk` en el nombre se omiten, lo que viene bien para guardar una copia de seguridad de un archivo junto al original. Cada archivo JavaScript se carga con `require()`, y cuando exporta una función `install()`, el framework la llama:\n\n```js\n// controllers/api.js\nexports.install = function() {\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n```\n\nCuando todo está cargado, `F.isLoaded` es `true`, el número de archivos y el tiempo están en `F.stats.compiled` y `F.stats.compilation`, y se emiten los eventos `ready` y `load` (consulta [Programación y eventos](../../guides/scheduling-and-events/)).\n\nOtras carpetas se usan mientras la aplicación se ejecuta, no se cargan: `public` ([archivos estáticos](../../guides/static-files/)), `views` ([Vistas](../../guides/views/)), `databases`, `tmp`, `logs`, `templates`, `private`. `F.dir()` establece sus rutas, y una clave de configuración `$dir...` mueve una de ellas.\n\n### Cargar solo algunas partes\n\n`LOAD()` acepta una lista de partes (los nombres están en la referencia), así un proceso en segundo plano puede cargar solo lo que necesita, sin el servidor HTTP:\n\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\t// the application is ready, without the web server\n});\n```\n\n## El modo debug y el watcher\n\nEn modo debug (`F.run()` sin `watcher: false`) se ejecutan dos procesos. El primero es el **watcher**: arranca la aplicación en un proceso hijo y vigila los archivos. Cuando un archivo cambia, imprime una línea y reinicia el hijo:\n\n```\n--- UPD --- [ 2025-03-01 10:15:22 ] --------> /controllers/api.js\n```\n\n`ADD`, `UPD` y `REM` marcan archivos añadidos, actualizados y eliminados, y `RES` un reinicio que pide la propia aplicación con `F.restart()`.\n\nEl watcher lee estas carpetas: `controllers`, `definitions`, `extensions`, `modules`, `models`, `schemas`, `actions`, `resources`, `source`, `workers`, `middleware`, `bundles`, `transforms`, `startup` y `plugins`, además de las carpetas de `options.watch`. Dentro de ellas reacciona a los archivos con las extensiones `.js`, `.ts`, `.py`, `.resource`, `.package`, `.bundle`, `.build`, `.url` y `.html`, y a los archivos llamados `config` (por ejemplo `plugins/<name>/config`), pero no a los archivos de dentro de una carpeta `public`. En la carpeta raíz vigila los archivos `config` y `version` y los archivos que terminan en `.ts`, `.py` o `.resource` (los demás archivos `.js` de la raíz se ignoran, y también el script de arranque). Las carpetas `public` y `views` no se vigilan (excepto con bundles o live reload, consulta más abajo). Un archivo que todavía se está escribiendo (su tamaño sigue creciendo entre dos comprobaciones, por ejemplo una copia lenta por la red) se vuelve a comprobar en la siguiente ronda, así la aplicación solo se reinicia cuando el archivo está completo.\n\nEl watcher consulta los archivos cada pocos segundos. En modo debug `DEBUG` es `true` en el proceso de la aplicación, y la consola imprime la información de arranque (`F.console()`) después del primer arranque.\n\nEl watcher escribe su PID en `<script>.pid` (`index.pid`); borrar el archivo detiene el watcher y la aplicación en pocos segundos. Cuando el proceso de la aplicación termina por sí mismo, el watcher también termina. `options.inspector` arranca el hijo con `--inspect=<port>`.\n\n### Live reload\n\nCon `options.livereload` establecido al nombre de host de tu aplicación, el watcher se conecta al servicio de live reload de Total.js (`wss://livereload.totaljs.com/?hostname=...`) y le envía el nombre de cada archivo `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` o `.resource` que cambia, incluidos los cambios en `public` y `views`. En este modo no se vigilan los demás archivos de las carpetas vigiladas.\n\n## El modo release\n\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nEn modo release la aplicación se ejecuta en el mismo proceso, sin el watcher, y `DEBUG` es `false`. Arrancado con el argumento `--watcher` (`node index.js --watcher`), el proceso se convierte en un watcher para el modo release: imprime `RELEASE PID`, arranca la aplicación en un proceso hijo, escribe `<script>.pid`, reinicia la aplicación cuando termina y se detiene cuando se borra el archivo PID. No vigila los archivos.\n\n### Modo servicio\n\n`options.servicemode` carga la aplicación sin el servidor HTTP: `true` lo carga todo, un string como `'config,modules,actions'` carga solo esas partes (los nombres de `LOAD()`). Funciona en los dos modos.\n\n### Clúster\n\n`options.cluster` arranca la aplicación en varios hilos de clúster de Node.js que comparten el puerto: un número, o `'auto'`, que empieza con un hilo y añade hilos (hasta `options.limit`) cuando los hilos responden lentamente. En modo debug el watcher reinicia todos los hilos cuando cambia un archivo; el clúster se ejecuta sin watcher cuando `options.release` es `true`. Hay más sobre los hilos en [Workers, hilos y clúster](../../guides/workers-and-threads/).\n\n## Bundles\n\nUn bundle es un único archivo `.bundle` con los archivos de una aplicación o de una parte de ella (un módulo, un plugin, un admin). Lo creas con el comando `total5 bundle` (consulta [Línea de comandos](../../guides/command-line/)) y lo pones en la carpeta `bundles` de otra aplicación.\n\nCuando `bundles` contiene archivos, `LOAD()` construye la aplicación en la carpeta oculta `.src` y la ejecuta desde ahí (`F.isBundle` es `true` y `F.directory` apunta a `.src`):\n\n1. Cada archivo `bundles/<name>.url` contiene una URL; el bundle se descarga en `bundles/<name>.bundle`.\n2. Se eliminan los archivos de la construcción anterior (listados en `.src/bundle.json`).\n3. Cada archivo `.bundle` (excepto las copias `-bk` y `_bk`) se extrae en `.src`. Un archivo de `/updates/` se omite cuando él, o su copia `_bk`, ya existe en `.src`; un archivo de `/startup/` o `/databases/` se omite cuando ya existe allí.\n4. Los archivos de la propia aplicación se copian sobre los extraídos, así ganan tus propios archivos. Se omiten las carpetas `tmp`, `bundles`, `logs`, `node_modules`, los archivos y carpetas ocultos de la raíz y los archivos PID.\n5. La lista de archivos se escribe en `.src/bundle.json`.\n\nLos archivos `config`, `sitemap`, `versions`, `workflows`, `dependencies` y `.resource` se fusionan (cada copia se añade al final), así varios bundles pueden añadir claves al mismo `config`. Un archivo cuyo nombre empieza por `--` (`/controllers/--api.js`) se añade al final del archivo sin los guiones.\n\nUn archivo `.bundleignore` en la raíz lista las rutas que no se copian, una por línea: una carpeta (`/docs/`), un archivo (`/readme.md`) o los archivos con una extensión dentro de una carpeta (`/public/*.map`).\n\n```\n/docs/\n/readme.md\n/public/*.map\n```\n\nCon la clave de configuración `bundling` establecida a `'shallow'`, la construcción se omite cuando existe `.src/bundle.json` y la aplicación se ejecuta desde el `.src` existente. Los bundles se extraen antes de leer el archivo `config`, así que establece la clave en las opciones de arranque: `F.run({ config: { bundling: 'shallow' } })`.\n\nUn archivo llamado `bundles.debug` en la raíz omite la construcción y ejecuta la aplicación directamente desde `.src`. Sirve para editar en su sitio una aplicación extraída: el watcher de debug vigila entonces `.src`.\n\nCon bundles, el watcher de debug vigila todos los archivos: los cambios en `public` y `views` se copian a `.src` sin reinicio, los demás cambios reconstruyen `.src` y reinician.\n\n## Edición remota\n\nEl Total.js Code Editor puede editar los archivos de una aplicación en ejecución. La aplicación se conecta al editor con un WebSocket, así que funciona detrás de un firewall sin un puerto abierto:\n\n```js\nrequire('total5');\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\nLa URL viene del editor (`http` se cambia por `ws`). El cliente se reconecta cada 10 segundos cuando se pierde la conexión, también después de las respuestas `404 project not found` y `409 project is already open`.\n\nEl editor puede explorar, cargar, guardar, crear, renombrar, eliminar, subir y descargar archivos, leer y vaciar los logs y, en modo debug, reiniciar la aplicación. También puede ejecutar un archivo en el servidor (`exec`): un archivo `.js` con Node.js, un archivo `.sh` con `sh`, o con un comando que envía el editor; la salida vuelve al editor. Los archivos guardados se escriben en la carpeta de la aplicación, así que en modo debug el watcher reinicia la aplicación después de cada cambio.\n\nEn modo debug el cliente del editor se ejecuta en el proceso del watcher. En modo release se ejecuta en el proceso del watcher cuando la aplicación se arranca con `--watcher`. `F.remote(url, [directory])` arranca el mismo cliente desde tu propio código, y `total5 edit <url>` lo arranca para la carpeta actual sin ejecutar la aplicación.\n\n### Edición remota por un agente de IA\n\n`editmcp` hace lo mismo para un agente de IA. La aplicación se conecta a un proxy de edición MCP, y el agente trabaja sobre los archivos con las herramientas MCP del proxy:\n\n```js\nrequire('total5');\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nEl proxy es una aplicación Total.js con `$mcp : true` y una ruta WebSocket:\n\n```js\nconst editmcp = require('total5/edit-mcp');\nROUTE('SOCKET /$mcp/', $ => editmcp.proxy($));\n```\n\nEl agente se conecta al endpoint MCP del proxy con el mismo id, `https://proxy.example.com/$mcp/?id=myproject`, y recibe las herramientas `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` y `App_restart`. El proxy envía cada llamada a la aplicación conectada, donde se ejecuta; cuando no hay ninguna aplicación conectada con ese id, la respuesta es `App is offline.`. Las rutas son relativas a la raíz de la aplicación. Cada `App_write` guarda el contenido escrito como una revisión numerada en la carpeta `revisions/`, y `App_restore` devuelve el contenido de una revisión anterior.\n\n`App_shell` ejecuta cualquier comando de shell en el ordenador de la aplicación, así que protege el endpoint del proxy con `Total.mcp.auth` (consulta [Servidor MCP](../mcp-server/)). Igual que con `edit`, el cliente se ejecuta en el proceso del watcher.\n\n## Módulos y MODS\n\nUn archivo de `modules` es un módulo: un trozo de código que usa el resto de la aplicación. El framework lo registra en `MODS` (`F.modules`) bajo `exports.id`, o bajo el nombre del archivo cuando falta `id`, y después llama a `install()`:\n\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.install = function() {\n\tROUTE('GET /counter/', function($) {\n\t\t$.json({ count: exports.increment() });\n\t});\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// anywhere after the start\nMODS.counter.increment();\n```\n\nLos plugins se registran en `PLUGINS` de la misma forma (consulta [Plugins y componentes](../../guides/plugins-and-components/)).\n\n## IMPORT() y REQUIRE()\n\n`REQUIRE(name)` carga un módulo de Node.js o un paquete de NPM y también busca en `CONF.$nodemodules`. `IMPORT(url)` descarga un archivo JavaScript en la carpeta temporal y lo carga, una vez por proceso:\n\n```js\nvar Fs = REQUIRE('fs');\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\n```\n\n## Estadísticas del framework\n\n`F.stats` contiene contadores de toda la vida del proceso: peticiones por método y tipo, respuestas por tipo y código HTTP, datos transferidos, `compilation` y `compiled` desde el arranque, y `error`.\n\nUna vez por minuto el temporizador del servicio calcula las estadísticas de uso del proceso en `F.consumption` y emite `ON('$stats', stats)`. Las primeras estadísticas se calculan 5 segundos después de cargar la aplicación. Cuando `CONF.$stats` es `true` (por defecto), también se escriben en `<script>.json` junto al script de arranque (`index.js.json`), así una herramienta de monitorización puede leerlas sin preguntar a la aplicación:\n\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory usage:', stats.memory, 'MB');\n});\n```\n\nLos campos (memoria, peticiones, errores, contadores por minuto ...) están en la referencia de `F.consumption`. `overload` cuenta las horas en las que el uso superó el 80 %, la memoria superó los 600 MB o había más de 1000 peticiones pendientes. `uptime` es el número de minutos desde el arranque.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmAy1fc60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/application-structure/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Structure de l'application et modes","summary":"Le script de démarrage, les dossiers et leur ordre de chargement, les modes debug et release, les bundles, l'édition à distance, les modules et les statistiques.","markdown":"---\ntitle: \"Structure de l'application et modes\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/application-structure/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Structure de l'application et modes\n\n> Le script de démarrage, les dossiers et leur ordre de chargement, les modes debug et release, les bundles, l'édition à distance, les modules et les statistiques.\n\nUne application Total.js 5 est un dossier avec un script de démarrage, quelques fichiers simples et des dossiers contenant des fichiers JavaScript. Au démarrage, le framework parcourt les dossiers dans un ordre fixe : il suffit donc qu'un fichier soit dans le bon dossier pour être chargé. La façon d'installer `total5` et de créer le premier projet est expliquée dans le guide [Installation](../../guides/installation/).\n\n## Le script de démarrage\n\nLe script de démarrage (généralement `index.js`) est le fichier que tu exécutes avec `node`. Il charge `total5` et appelle `F.run()` avec les options de démarrage :\n\n```js\nrequire('total5');\n\nvar options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'Total.js' };\n// options.cluster = 'auto';\n\nF.run(options);\n```\n\n`F.run()` démarre l'application en mode **debug** avec un watcher. Avec `options.watcher = false`, elle démarre en mode **release**. Les deux modes sont expliqués plus bas ; toutes les options se trouvent dans la [référence](../../reference/application-structure/).\n\nLa racine de l'application est le répertoire de travail courant du processus (`F.directory`), alors lance le script depuis le dossier de l'application : `cd /www/app && node index.js`. Quand le script charge `total5`, le framework change aussi le répertoire de travail du processus (`process.cwd()`) pour le dossier du script de démarrage, sauf dans les worker threads.\n\n## Les dossiers et l'ordre de chargement\n\n`LOAD()` (appelée par `F.http()` et `F.run()`) lit l'application dans cet ordre :\n\n1. `.env` : les variables d'environnement\n2. `config` : la configuration (voir [Configuration](../../guides/configuration/))\n3. `version` : la première ligne devient `CONF.version`, sous forme de nombre\n4. `resources/*.resource` : les dictionnaires (voir [Localisation](../../guides/localization/))\n5. `jsonschemas/*.json` et `jsonschemas/*.txt` : les schémas JSON, nommés d'après le fichier\n6. les fichiers JavaScript de `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers` et `middleware`, dans cet ordre\n7. `plugins/` : chaque dossier de plugin : son `index.js`, puis les fichiers JavaScript de ses dossiers `extensions`, `controllers`, `actions`, `schemas`, `models`, `definitions` et `middleware` (voir [Plugins et composants](../../guides/plugins-and-components/)). Un dossier sans `index.js` est ignoré. Un fichier `config` dans le dossier du plugin est lu comme le `config` principal, avant le chargement des fichiers JavaScript. Un fichier `index.flow` dans le dossier du plugin est chargé comme FlowStream du plugin (`PLUGINS.<id>.flowstream`)\n8. `flowstreams/*.flow` : le moteur FlowStream charge les flux (voir [FlowStream](../../guides/flowstream/))\n9. les statistiques du framework et le timer de service\n\nLes dossiers sont lus de façon récursive. Les fichiers avec `-bk` ou `_bk` dans le nom sont ignorés, ce qui est pratique pour garder une copie de sauvegarde d'un fichier à côté de l'original. Chaque fichier JavaScript est chargé avec `require()`, et quand il exporte une fonction `install()`, le framework l'appelle :\n\n```js\n// controllers/api.js\nexports.install = function() {\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n```\n\nQuand tout est chargé, `F.isLoaded` vaut `true`, le nombre de fichiers et le temps se trouvent dans `F.stats.compiled` et `F.stats.compilation`, et les événements `ready` et `load` sont émis (voir [Planification et événements](../../guides/scheduling-and-events/)).\n\nD'autres dossiers sont utilisés pendant que l'application tourne, sans être chargés : `public` ([fichiers statiques](../../guides/static-files/)), `views` ([Vues](../../guides/views/)), `databases`, `tmp`, `logs`, `templates`, `private`. `F.dir()` définit leurs chemins, et une clé de configuration `$dir...` en déplace un.\n\n### Charger seulement certaines parties\n\n`LOAD()` accepte une liste de parties (les noms sont dans la référence), pour qu'un processus en arrière-plan puisse charger seulement ce dont il a besoin, sans le serveur HTTP :\n\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\t// the application is ready, without the web server\n});\n```\n\n## Le mode debug et le watcher\n\nEn mode debug (`F.run()` sans `watcher: false`), deux processus tournent. Le premier est le **watcher** : il démarre l'application dans un processus enfant et surveille les fichiers. Quand un fichier change, il affiche une ligne et redémarre l'enfant :\n\n```\n--- UPD --- [ 2025-03-01 10:15:22 ] --------> /controllers/api.js\n```\n\n`ADD`, `UPD` et `REM` marquent les fichiers ajoutés, modifiés et supprimés, et `RES` un redémarrage demandé par l'application elle-même avec `F.restart()`.\n\nLe watcher lit ces dossiers : `controllers`, `definitions`, `extensions`, `modules`, `models`, `schemas`, `actions`, `resources`, `source`, `workers`, `middleware`, `bundles`, `transforms`, `startup` et `plugins`, plus les dossiers de `options.watch`. À l'intérieur, il réagit aux fichiers avec les extensions `.js`, `.ts`, `.py`, `.resource`, `.package`, `.bundle`, `.build`, `.url` et `.html`, et aux fichiers nommés `config` (par exemple `plugins/<name>/config`), mais pas aux fichiers situés dans un dossier `public`. Dans le dossier racine, il surveille les fichiers `config` et `version` et les fichiers qui se terminent par `.ts`, `.py` ou `.resource` (les autres fichiers `.js` de la racine sont ignorés, tout comme le script de démarrage). Les dossiers `public` et `views` ne sont pas surveillés (sauf avec les bundles ou le live reload, voir plus bas). Un fichier qui est encore en cours d'écriture (sa taille continue d'augmenter entre deux vérifications, par exemple lors d'une copie lente sur le réseau) est vérifié à nouveau au tour suivant : l'application ne redémarre donc que lorsque le fichier est complet.\n\nLe watcher interroge les fichiers toutes les quelques secondes. En mode debug, `DEBUG` vaut `true` dans le processus de l'application, et la console affiche les informations de démarrage (`F.console()`) après le premier démarrage.\n\nLe watcher écrit son PID dans `<script>.pid` (`index.pid`) ; supprimer ce fichier arrête le watcher et l'application en quelques secondes. Quand le processus de l'application se termine de lui-même, le watcher se termine aussi. `options.inspector` démarre l'enfant avec `--inspect=<port>`.\n\n### Live reload\n\nAvec `options.livereload` défini sur le nom d'hôte de ton application, le watcher se connecte au service de live reload de Total.js (`wss://livereload.totaljs.com/?hostname=...`) et y envoie le nom de chaque fichier `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` ou `.resource` modifié, y compris les changements dans `public` et `views`. Les autres fichiers des dossiers surveillés ne sont pas surveillés dans ce mode.\n\n## Le mode release\n\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nEn mode release, l'application tourne dans le même processus, sans le watcher, et `DEBUG` vaut `false`. Démarré avec l'argument `--watcher` (`node index.js --watcher`), le processus devient un watcher pour le mode release : il affiche `RELEASE PID`, démarre l'application dans un processus enfant, écrit `<script>.pid`, redémarre l'application quand elle se termine et s'arrête quand le fichier PID est supprimé. Il ne surveille pas les fichiers.\n\n### Le mode service\n\n`options.servicemode` charge l'application sans le serveur HTTP : `true` charge tout, une chaîne comme `'config,modules,actions'` charge seulement ces parties (les noms de `LOAD()`). Il fonctionne dans les deux modes.\n\n### Cluster\n\n`options.cluster` démarre l'application dans plusieurs threads du cluster Node.js qui partagent le port : un nombre, ou `'auto'`, qui démarre avec un thread et en ajoute (jusqu'à `options.limit`) quand les threads répondent lentement. En mode debug, le watcher redémarre tous les threads quand un fichier change ; le cluster tourne sans watcher quand `options.release` vaut `true`. Tu trouveras plus d'informations sur les threads dans [Workers et threads](../../guides/workers-and-threads/).\n\n## Les bundles\n\nUn bundle est un fichier `.bundle` unique qui contient les fichiers d'une application ou d'une partie de celle-ci (un module, un plugin, une administration). Tu le crées avec la commande `total5 bundle` (voir [Ligne de commande](../../guides/command-line/)) et tu le places dans le dossier `bundles` d'une autre application.\n\nQuand `bundles` contient des fichiers, `LOAD()` construit l'application dans le dossier caché `.src` et l'exécute depuis celui-ci (`F.isBundle` vaut `true` et `F.directory` pointe vers `.src`) :\n\n1. Chaque fichier `bundles/<name>.url` contient une URL ; le bundle est téléchargé dans `bundles/<name>.bundle`.\n2. Les fichiers de la construction précédente (listés dans `.src/bundle.json`) sont supprimés.\n3. Chaque fichier `.bundle` (sauf les copies `-bk` et `_bk`) est extrait dans `.src`. Un fichier de `/updates/` est ignoré quand lui-même, ou sa copie `_bk`, existe déjà dans `.src` ; un fichier de `/startup/` ou de `/databases/` est ignoré quand il y existe déjà.\n4. Les fichiers de l'application elle-même sont copiés par-dessus les fichiers extraits : ce sont donc tes propres fichiers qui l'emportent. Les dossiers `tmp`, `bundles`, `logs`, `node_modules`, les fichiers et dossiers cachés de la racine et les fichiers PID sont ignorés.\n5. La liste des fichiers est écrite dans `.src/bundle.json`.\n\nLes fichiers `config`, `sitemap`, `versions`, `workflows`, `dependencies` et `.resource` sont fusionnés (chaque copie est ajoutée à la suite), pour que plusieurs bundles puissent ajouter des clés au même `config`. Un fichier dont le nom commence par `--` (`/controllers/--api.js`) est ajouté à la suite du fichier sans les tirets.\n\nUn fichier `.bundleignore` à la racine liste les chemins qui ne sont pas copiés, un par ligne : un dossier (`/docs/`), un fichier (`/readme.md`) ou les fichiers d'une extension dans un dossier (`/public/*.map`).\n\n```\n/docs/\n/readme.md\n/public/*.map\n```\n\nAvec la clé de configuration `bundling` définie sur `'shallow'`, la construction est ignorée quand `.src/bundle.json` existe, et l'application tourne à partir du `.src` existant. Les bundles sont extraits avant la lecture du fichier `config`, alors définis la clé dans les options de démarrage : `F.run({ config: { bundling: 'shallow' } })`.\n\nUn fichier nommé `bundles.debug` à la racine saute la construction et exécute l'application directement depuis `.src`. Il sert à modifier sur place une application extraite : le watcher de debug surveille alors `.src`.\n\nAvec les bundles, le watcher de debug surveille tous les fichiers : les changements dans `public` et `views` sont copiés dans `.src` sans redémarrage, les autres changements reconstruisent `.src` et redémarrent l'application.\n\n## L'édition à distance\n\nLe Total.js Code Editor peut modifier les fichiers d'une application en cours d'exécution. L'application se connecte à l'éditeur avec un WebSocket : cela fonctionne donc derrière un pare-feu, sans port ouvert :\n\n```js\nrequire('total5');\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\nL'URL vient de l'éditeur (`http` est changé en `ws`). Le client se reconnecte toutes les 10 secondes quand la connexion est perdue, y compris après les réponses `404 project not found` et `409 project is already open`.\n\nL'éditeur peut parcourir, charger, enregistrer, créer, renommer, supprimer, envoyer et télécharger des fichiers, lire et vider les logs et, en mode debug, redémarrer l'application. Il peut aussi exécuter un fichier sur le serveur (`exec`) : un fichier `.js` avec Node.js, un fichier `.sh` avec `sh`, ou avec une commande que l'éditeur envoie ; la sortie revient à l'éditeur. Les fichiers enregistrés sont écrits dans le dossier de l'application : en mode debug, le watcher redémarre donc l'application après chaque changement.\n\nEn mode debug, le client de l'éditeur tourne dans le processus du watcher. En mode release, il tourne dans le processus du watcher quand l'application est démarrée avec `--watcher`. `F.remote(url, [directory])` démarre le même client depuis ton propre code, et `total5 edit <url>` le démarre pour le dossier courant sans exécuter l'application.\n\n### L'édition à distance par un agent d'IA\n\n`editmcp` fait la même chose pour un agent d'IA. L'application se connecte à un proxy d'édition MCP, et l'agent travaille sur les fichiers avec les outils MCP du proxy :\n\n```js\nrequire('total5');\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nLe proxy est une application Total.js avec `$mcp : true` et une route WebSocket :\n\n```js\nconst editmcp = require('total5/edit-mcp');\nROUTE('SOCKET /$mcp/', $ => editmcp.proxy($));\n```\n\nL'agent se connecte à l'endpoint MCP du proxy avec le même id, `https://proxy.example.com/$mcp/?id=myproject`, et reçoit les outils `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` et `App_restart`. Le proxy envoie chaque appel à l'application connectée, où il s'exécute ; quand aucune application avec cet id n'est connectée, la réponse est `App is offline.`. Les chemins sont relatifs à la racine de l'application. Chaque `App_write` enregistre le contenu écrit comme révision numérotée dans le dossier `revisions/`, et `App_restore` renvoie le contenu d'une révision antérieure.\n\n`App_shell` exécute n'importe quelle commande shell sur l'ordinateur de l'application, alors protège l'endpoint du proxy avec `Total.mcp.auth` (voir [Serveur MCP](../mcp-server/)). Comme pour `edit`, le client tourne dans le processus du watcher.\n\n## Les modules et MODS\n\nUn fichier de `modules` est un module : un morceau de code que le reste de l'application utilise. Le framework l'enregistre dans `MODS` (`F.modules`) sous `exports.id`, ou sous le nom du fichier quand `id` manque, puis appelle `install()` :\n\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.install = function() {\n\tROUTE('GET /counter/', function($) {\n\t\t$.json({ count: exports.increment() });\n\t});\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// anywhere after the start\nMODS.counter.increment();\n```\n\nLes plugins sont enregistrés dans `PLUGINS` de la même façon (voir [Plugins et composants](../../guides/plugins-and-components/)).\n\n## IMPORT() et REQUIRE()\n\n`REQUIRE(name)` charge un module Node.js ou un paquet NPM et cherche aussi dans `CONF.$nodemodules`. `IMPORT(url)` télécharge un fichier JavaScript dans le dossier temporaire et le charge, une fois par processus :\n\n```js\nvar Fs = REQUIRE('fs');\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\n```\n\n## Les statistiques du framework\n\n`F.stats` contient des compteurs pour toute la durée de vie du processus : les requêtes par méthode et par type, les réponses par type et par code HTTP, les données transférées, `compilation` et `compiled` depuis le démarrage, et `error`.\n\nUne fois par minute, le timer de service calcule les statistiques d'utilisation du processus dans `F.consumption` et émet `ON('$stats', stats)`. Les premières statistiques sont calculées 5 secondes après le chargement de l'application. Quand `CONF.$stats` vaut `true` (la valeur par défaut), elles sont aussi écrites dans `<script>.json` à côté du script de démarrage (`index.js.json`), pour qu'un outil de supervision puisse les lire sans interroger l'application :\n\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory usage:', stats.memory, 'MB');\n});\n```\n\nLes champs (mémoire, requêtes, erreurs, compteurs par minute...) sont listés dans la référence de `F.consumption`. `overload` compte les heures pendant lesquelles l'utilisation était supérieure à 80 %, la mémoire supérieure à 600 MB ou plus de 1000 requêtes en attente. `uptime` est le nombre de minutes depuis le démarrage.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmAy1fc60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/application-structure/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Struttura dell'applicazione e modalità","summary":"Lo script di avvio, le cartelle e il loro ordine di caricamento, modalità debug e release, bundle, modifica remota, moduli e statistiche.","markdown":"---\ntitle: \"Struttura dell'applicazione e modalità\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/application-structure/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Struttura dell'applicazione e modalità\n\n> Lo script di avvio, le cartelle e il loro ordine di caricamento, modalità debug e release, bundle, modifica remota, moduli e statistiche.\n\nUn'applicazione Total.js 5 è una cartella con uno script di avvio, alcuni file semplici e cartelle con file JavaScript. All'avvio il framework scansiona le cartelle in un ordine fisso, quindi basta che un file sia nella cartella giusta per essere caricato. Come installare `total5` e creare il primo progetto è spiegato nella guida [Installazione](../../guides/installation/).\n\n## Lo script di avvio\n\nLo script di avvio (di solito `index.js`) è il file che esegui con `node`. Carica `total5` e chiama `F.run()` con le opzioni di avvio:\n\n```js\nrequire('total5');\n\nvar options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'Total.js' };\n// options.cluster = 'auto';\n\nF.run(options);\n```\n\n`F.run()` avvia l'applicazione in modalità **debug** con un watcher. Con `options.watcher = false` la avvia in modalità **release**. Entrambe le modalità sono spiegate qui sotto; tutte le opzioni sono nel [riferimento](../../reference/application-structure/).\n\nLa radice dell'applicazione è la directory di lavoro corrente del processo (`F.directory`), quindi avvia lo script dalla cartella dell'applicazione: `cd /www/app && node index.js`. Quando lo script carica `total5`, il framework cambia anche la directory di lavoro del processo (`process.cwd()`) nella cartella dello script di avvio, tranne che nei worker thread.\n\n## Le cartelle e l'ordine di caricamento\n\n`LOAD()` (chiamata da `F.http()` e `F.run()`) legge l'applicazione in questo ordine:\n\n1. `.env`: le variabili d'ambiente\n2. `config`: la configurazione (vedi [Configurazione](../../guides/configuration/))\n3. `version`: la prima riga diventa `CONF.version` come numero\n4. `resources/*.resource`: i dizionari (vedi [Localizzazione](../../guides/localization/))\n5. `jsonschemas/*.json` e `jsonschemas/*.txt`: gli schemi JSON, con il nome del file\n6. i file JavaScript di `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers` e `middleware`, in questo ordine\n7. `plugins/`: ogni cartella di plugin: il suo `index.js`, poi i file JavaScript delle sue cartelle `extensions`, `controllers`, `actions`, `schemas`, `models`, `definitions` e `middleware` (vedi [Plugin e componenti](../../guides/plugins-and-components/)). Una cartella senza `index.js` viene saltata. Un file `config` nella cartella del plugin viene letto come il `config` principale, prima che vengano caricati i file JavaScript. Un file `index.flow` nella cartella del plugin viene caricato come FlowStream del plugin (`PLUGINS.<id>.flowstream`)\n8. `flowstreams/*.flow`: il motore FlowStream carica i flussi (vedi [FlowStream](../../guides/flowstream/))\n9. le statistiche del framework e il timer di servizio\n\nLe cartelle vengono lette in modo ricorsivo. I file con `-bk` o `_bk` nel nome vengono saltati, il che è comodo per tenere una copia di backup di un file accanto all'originale. Ogni file JavaScript viene caricato con `require()`, e quando esporta una funzione `install()`, il framework la chiama:\n\n```js\n// controllers/api.js\nexports.install = function() {\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n```\n\nQuando tutto è caricato, `F.isLoaded` è `true`, il numero di file e il tempo sono in `F.stats.compiled` e `F.stats.compilation`, e vengono emessi gli eventi `ready` e `load` (vedi [Pianificazione ed eventi](../../guides/scheduling-and-events/)).\n\nAltre cartelle vengono usate mentre l'applicazione gira, non caricate: `public` ([file statici](../../guides/static-files/)), `views` ([Viste](../../guides/views/)), `databases`, `tmp`, `logs`, `templates`, `private`. `F.dir()` imposta i loro percorsi, e una chiave di configurazione `$dir...` ne sposta una.\n\n### Caricare solo alcune parti\n\n`LOAD()` accetta un elenco di parti (i nomi sono nel riferimento), così un processo in background può caricare solo ciò che gli serve, senza il server HTTP:\n\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\t// the application is ready, without the web server\n});\n```\n\n## Modalità debug e il watcher\n\nIn modalità debug (`F.run()` senza `watcher: false`) girano due processi. Il primo è il **watcher**: avvia l'applicazione in un processo figlio e controlla i file. Quando un file cambia, stampa una riga e riavvia il processo figlio:\n\n```\n--- UPD --- [ 2025-03-01 10:15:22 ] --------> /controllers/api.js\n```\n\n`ADD`, `UPD` e `REM` indicano i file aggiunti, aggiornati e rimossi, e `RES` un riavvio chiesto dall'applicazione stessa con `F.restart()`.\n\nIl watcher legge queste cartelle: `controllers`, `definitions`, `extensions`, `modules`, `models`, `schemas`, `actions`, `resources`, `source`, `workers`, `middleware`, `bundles`, `transforms`, `startup` e `plugins`, più le cartelle in `options.watch`. Al loro interno reagisce ai file con le estensioni `.js`, `.ts`, `.py`, `.resource`, `.package`, `.bundle`, `.build`, `.url` e `.html`, e ai file chiamati `config` (per esempio `plugins/<name>/config`), ma non ai file dentro una cartella `public`. Nella cartella radice controlla i file `config` e `version` e i file che finiscono con `.ts`, `.py` o `.resource` (gli altri file `.js` nella radice vengono ignorati, e anche lo script di avvio). Le cartelle `public` e `views` non vengono controllate (tranne con i bundle o con il live reload, vedi sotto). Un file che è ancora in scrittura (la sua dimensione continua a crescere tra due controlli, per esempio una copia lenta in rete) viene ricontrollato al giro successivo, così l'applicazione si riavvia solo quando il file è completo.\n\nIl watcher controlla i file a intervalli di pochi secondi. In modalità debug `DEBUG` è `true` nel processo dell'applicazione, e la console stampa le informazioni di avvio (`F.console()`) dopo il primo avvio.\n\nIl watcher scrive il suo PID in `<script>.pid` (`index.pid`); se elimini il file, il watcher e l'applicazione si fermano entro pochi secondi. Quando il processo dell'applicazione termina da solo, termina anche il watcher. `options.inspector` avvia il processo figlio con `--inspect=<port>`.\n\n### Live reload\n\nCon `options.livereload` impostato sul nome host della tua applicazione, il watcher si collega al servizio di live reload di Total.js (`wss://livereload.totaljs.com/?hostname=...`) e gli invia il nome di ogni file `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` o `.resource` modificato, comprese le modifiche in `public` e `views`. In questa modalità gli altri file delle cartelle controllate non vengono controllati.\n\n## Modalità release\n\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nIn modalità release l'applicazione gira nello stesso processo, senza il watcher, e `DEBUG` è `false`. Avviato con l'argomento `--watcher` (`node index.js --watcher`), il processo diventa un watcher per la modalità release: stampa `RELEASE PID`, avvia l'applicazione in un processo figlio, scrive `<script>.pid`, riavvia l'applicazione quando termina e si ferma quando il file PID viene eliminato. Non controlla i file.\n\n### Modalità servizio\n\n`options.servicemode` carica l'applicazione senza il server HTTP: `true` carica tutto, una stringa come `'config,modules,actions'` carica solo queste parti (i nomi di `LOAD()`). Funziona in entrambe le modalità.\n\n### Cluster\n\n`options.cluster` avvia l'applicazione in più thread del cluster di Node.js che condividono la porta: un numero, oppure `'auto'`, che parte con un thread e aggiunge thread (fino a `options.limit`) quando i thread rispondono lentamente. In modalità debug il watcher riavvia tutti i thread quando un file cambia; il cluster gira senza watcher quando `options.release` è `true`. Trovi di più sui thread in [Worker e thread](../../guides/workers-and-threads/).\n\n## Bundle\n\nUn bundle è un unico file `.bundle` con i file di un'applicazione o di una sua parte (un modulo, un plugin, un pannello di amministrazione). Lo crei con il comando `total5 bundle` (vedi [Riga di comando](../../guides/command-line/)) e lo metti nella cartella `bundles` di un'altra applicazione.\n\nQuando `bundles` contiene dei file, `LOAD()` costruisce l'applicazione nella cartella nascosta `.src` e la esegue da lì (`F.isBundle` è `true` e `F.directory` punta a `.src`):\n\n1. Ogni file `bundles/<name>.url` contiene un URL; il bundle viene scaricato in `bundles/<name>.bundle`.\n2. I file della build precedente (elencati in `.src/bundle.json`) vengono rimossi.\n3. Ogni file `.bundle` (tranne le copie `-bk` e `_bk`) viene estratto in `.src`. Un file di `/updates/` viene saltato quando esiste già in `.src`, lui o la sua copia `_bk`; un file di `/startup/` o `/databases/` viene saltato quando esiste già lì.\n4. I file dell'applicazione stessa vengono copiati sopra quelli estratti, così vincono i tuoi file. Vengono saltate le cartelle `tmp`, `bundles`, `logs`, `node_modules`, i file e le cartelle nascosti nella radice e i file PID.\n5. L'elenco dei file viene scritto in `.src/bundle.json`.\n\nI file `config`, `sitemap`, `versions`, `workflows`, `dependencies` e i file `.resource` vengono uniti (ogni copia viene aggiunta in coda), così più bundle possono aggiungere chiavi allo stesso `config`. Un file il cui nome inizia con `--` (`/controllers/--api.js`) viene aggiunto in coda al file senza i trattini.\n\nUn file `.bundleignore` nella radice elenca i percorsi che non vengono copiati, uno per riga: una cartella (`/docs/`), un file (`/readme.md`) o i file con una certa estensione in una cartella (`/public/*.map`).\n\n```\n/docs/\n/readme.md\n/public/*.map\n```\n\nCon la chiave di configurazione `bundling` impostata a `'shallow'`, la build viene saltata quando esiste `.src/bundle.json` e l'applicazione gira dalla `.src` esistente. I bundle vengono estratti prima che venga letto il file `config`, quindi imposta la chiave nelle opzioni di avvio: `F.run({ config: { bundling: 'shallow' } })`.\n\nUn file chiamato `bundles.debug` nella radice salta la build ed esegue l'applicazione direttamente da `.src`. Serve per modificare sul posto un'applicazione estratta: il watcher di debug controlla allora `.src`.\n\nCon i bundle, il watcher di debug controlla ogni file: le modifiche in `public` e `views` vengono copiate in `.src` senza riavvio, le altre modifiche ricostruiscono `.src` e riavviano.\n\n## Modifica remota\n\nIl Total.js Code Editor può modificare i file di un'applicazione in esecuzione. L'applicazione si collega all'editor con un WebSocket, quindi funziona anche dietro un firewall senza una porta aperta:\n\n```js\nrequire('total5');\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\nL'URL arriva dall'editor (`http` viene cambiato in `ws`). Il client si ricollega ogni 10 secondi quando la connessione si interrompe, anche dopo le risposte `404 project not found` e `409 project is already open`.\n\nL'editor può sfogliare, caricare, salvare, creare, rinominare, rimuovere, caricare sul server e scaricare file, leggere e svuotare i log e, in modalità debug, riavviare l'applicazione. Può anche eseguire un file sul server (`exec`): un file `.js` con Node.js, un file `.sh` con `sh`, oppure con un comando che invia l'editor; l'output torna all'editor. I file salvati vengono scritti nella cartella dell'applicazione, quindi in modalità debug il watcher riavvia l'applicazione dopo ogni modifica.\n\nIn modalità debug il client dell'editor gira nel processo del watcher. In modalità release gira nel processo del watcher quando l'applicazione viene avviata con `--watcher`. `F.remote(url, [directory])` avvia lo stesso client dal tuo codice, e `total5 edit <url>` lo avvia per la cartella corrente senza eseguire l'applicazione.\n\n### Modifica remota da parte di un agente AI\n\n`editmcp` fa lo stesso per un agente AI. L'applicazione si collega a un proxy di modifica MCP, e l'agente lavora sui file tramite i tool MCP del proxy:\n\n```js\nrequire('total5');\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nIl proxy è un'applicazione Total.js con `$mcp : true` e una route WebSocket:\n\n```js\nconst editmcp = require('total5/edit-mcp');\nROUTE('SOCKET /$mcp/', $ => editmcp.proxy($));\n```\n\nL'agente si collega all'endpoint MCP del proxy con lo stesso id, `https://proxy.example.com/$mcp/?id=myproject`, e riceve i tool `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` e `App_restart`. Il proxy invia ogni chiamata all'applicazione collegata, dove viene eseguita; quando non è collegata nessuna applicazione con quell'id, la risposta è `App is offline.`. I percorsi sono relativi alla radice dell'applicazione. Ogni `App_write` salva il contenuto scritto come revisione numerata nella cartella `revisions/`, e `App_restore` restituisce il contenuto di una revisione precedente.\n\n`App_shell` esegue qualsiasi comando di shell sul computer dell'applicazione, quindi proteggi l'endpoint del proxy con `Total.mcp.auth` (vedi [Server MCP](../mcp-server/)). Come con `edit`, il client gira nel processo del watcher.\n\n## Moduli e MODS\n\nUn file in `modules` è un modulo: un pezzo di codice che il resto dell'applicazione usa. Il framework lo registra in `MODS` (`F.modules`) con `exports.id`, o con il nome del file quando `id` manca, e poi chiama `install()`:\n\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.install = function() {\n\tROUTE('GET /counter/', function($) {\n\t\t$.json({ count: exports.increment() });\n\t});\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// anywhere after the start\nMODS.counter.increment();\n```\n\nI plugin vengono registrati in `PLUGINS` allo stesso modo (vedi [Plugin e componenti](../../guides/plugins-and-components/)).\n\n## IMPORT() e REQUIRE()\n\n`REQUIRE(name)` carica un modulo di Node.js o un pacchetto NPM e cerca anche in `CONF.$nodemodules`. `IMPORT(url)` scarica un file JavaScript nella cartella temporanea e lo carica, una volta per processo:\n\n```js\nvar Fs = REQUIRE('fs');\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\n```\n\n## Statistiche del framework\n\n`F.stats` contiene contatori per tutta la vita del processo: richieste per metodo e tipo, risposte per tipo e codice HTTP, dati trasferiti, `compilation` e `compiled` dall'avvio, ed `error`.\n\nUna volta al minuto il timer di servizio calcola le statistiche di utilizzo del processo in `F.consumption` ed emette `ON('$stats', stats)`. Le prime statistiche vengono calcolate 5 secondi dopo il caricamento dell'applicazione. Quando `CONF.$stats` è `true` (il valore predefinito), vengono scritte anche in `<script>.json` accanto allo script di avvio (`index.js.json`), così uno strumento di monitoraggio può leggerle senza interrogare l'applicazione:\n\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory usage:', stats.memory, 'MB');\n});\n```\n\nI campi (memoria, richieste, errori, contatori al minuto ...) sono elencati nel riferimento di `F.consumption`. `overload` conta le ore in cui l'utilizzo era sopra l'80 %, la memoria sopra 600 MB o più di 1000 richieste erano in attesa. `uptime` è il numero di minuti dall'avvio.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JaqmAy1fc60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/application-structure/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Štruktúra aplikácie a režimy","summary":"Štartovací skript, priečinky a poradie ich načítania, režim debug a release, bundly, vzdialená úprava, moduly a štatistiky.","markdown":"---\ntitle: \"Štruktúra aplikácie a režimy\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/application-structure/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# Štruktúra aplikácie a režimy\n\n> Štartovací skript, priečinky a poradie ich načítania, režim debug a release, bundly, vzdialená úprava, moduly a štatistiky.\n\nAplikácia Total.js 5 je priečinok so štartovacím skriptom, niekoľkými obyčajnými súbormi a priečinkami s JavaScript súbormi. Framework pri štarte prechádza priečinky v pevnom poradí, takže súbor sa načíta už len tým, že je v správnom priečinku. Ako nainštalovať `total5` a vytvoriť prvý projekt, nájdeš v návode [Inštalácia](../../guides/installation/).\n\n## Štartovací skript\n\nŠtartovací skript (zvyčajne `index.js`) je súbor, ktorý spúšťaš cez `node`. Načíta `total5` a zavolá `F.run()` so štartovacími voľbami:\n\n```js\nrequire('total5');\n\nvar options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'Total.js' };\n// options.cluster = 'auto';\n\nF.run(options);\n```\n\n`F.run()` spustí aplikáciu v režime **debug** s watcherom. S `options.watcher = false` ju spustí v režime **release**. Oba režimy sú vysvetlené nižšie; všetky voľby sú v [referencii](../../reference/application-structure/).\n\nKoreň aplikácie je aktuálny pracovný priečinok procesu (`F.directory`), takže skript spúšťaj z priečinka aplikácie: `cd /www/app && node index.js`. Keď skript načíta `total5`, framework zmení aj pracovný priečinok procesu (`process.cwd()`) na priečinok štartovacieho skriptu, okrem worker vlákien.\n\n## Priečinky a poradie načítania\n\n`LOAD()` (volá ho `F.http()` aj `F.run()`) načíta aplikáciu v tomto poradí:\n\n1. `.env`: premenné prostredia\n2. `config`: konfigurácia (pozri [Konfigurácia](../../guides/configuration/))\n3. `version`: prvý riadok sa stane `CONF.version` ako číslo\n4. `resources/*.resource`: slovníky (pozri [Lokalizácia](../../guides/localization/))\n5. `jsonschemas/*.json` a `jsonschemas/*.txt`: JSON schémy pomenované podľa súboru\n6. JavaScript súbory z `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers` a `middleware`, v tomto poradí\n7. `plugins/`: každý priečinok pluginu: jeho `index.js`, potom JavaScript súbory z jeho priečinkov `extensions`, `controllers`, `actions`, `schemas`, `models`, `definitions` a `middleware` (pozri [Pluginy a komponenty](../../guides/plugins-and-components/)). Priečinok bez `index.js` sa preskočí. Súbor `config` v priečinku pluginu sa načíta ako hlavný `config`, ešte pred JavaScript súbormi. Súbor `index.flow` v priečinku pluginu sa načíta ako FlowStream pluginu (`PLUGINS.<id>.flowstream`)\n8. `flowstreams/*.flow`: engine FlowStream načíta flowy (pozri [FlowStream](../../guides/flowstream/))\n9. štatistiky frameworku a servisný časovač\n\nPriečinky sa čítajú rekurzívne. Súbory s `-bk` alebo `_bk` v názve sa preskočia, čo sa hodí, keď si chceš nechať záložnú kópiu súboru vedľa originálu. Každý JavaScript súbor sa načíta cez `require()` a keď exportuje funkciu `install()`, framework ju zavolá:\n\n```js\n// controllers/api.js\nexports.install = function() {\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n```\n\nKeď je všetko načítané, `F.isLoaded` je `true`, počet súborov a čas sú v `F.stats.compiled` a `F.stats.compilation` a vyšlú sa udalosti `ready` a `load` (pozri [Plánovanie a udalosti](../../guides/scheduling-and-events/)).\n\nOstatné priečinky sa používajú počas behu aplikácie, nenačítavajú sa: `public` ([statické súbory](../../guides/static-files/)), `views` ([Views](../../guides/views/)), `databases`, `tmp`, `logs`, `templates`, `private`. `F.dir()` nastaví ich cesty a konfiguračný kľúč `$dir...` niektorý z nich presunie.\n\n### Načítanie iba niektorých častí\n\n`LOAD()` prijíma zoznam častí (názvy sú v referencii), takže proces na pozadí môže načítať iba to, čo potrebuje, bez HTTP servera:\n\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\t// the application is ready, without the web server\n});\n```\n\n## Režim debug a watcher\n\nV režime debug (`F.run()` bez `watcher: false`) bežia dva procesy. Prvý je **watcher**: spustí aplikáciu v podriadenom procese a sleduje súbory. Keď sa súbor zmení, vypíše riadok a podriadený proces reštartuje:\n\n```\n--- UPD --- [ 2025-03-01 10:15:22 ] --------> /controllers/api.js\n```\n\n`ADD`, `UPD` a `REM` označujú pridané, upravené a odstránené súbory a `RES` reštart, o ktorý požiadala samotná aplikácia cez `F.restart()`.\n\nWatcher číta tieto priečinky: `controllers`, `definitions`, `extensions`, `modules`, `models`, `schemas`, `actions`, `resources`, `source`, `workers`, `middleware`, `bundles`, `transforms`, `startup` a `plugins`, plus priečinky v `options.watch`. V nich reaguje na súbory s príponami `.js`, `.ts`, `.py`, `.resource`, `.package`, `.bundle`, `.build`, `.url` a `.html` a na súbory s názvom `config` (napríklad `plugins/<name>/config`), ale nie na súbory v priečinku `public`. V koreňovom priečinku sleduje súbory `config` a `version` a súbory končiace na `.ts`, `.py` alebo `.resource` (ostatné `.js` súbory v koreni sa ignorujú, rovnako aj štartovací skript). Priečinky `public` a `views` sa nesledujú (okrem bundlov alebo live reloadu, pozri nižšie). Súbor, ktorý sa ešte zapisuje (jeho veľkosť medzi dvoma kontrolami stále rastie, napríklad pri pomalom kopírovaní cez sieť), sa skontroluje znova v ďalšom kole, takže aplikácia sa reštartuje až vtedy, keď je súbor kompletný.\n\nWatcher kontroluje súbory každých pár sekúnd. V režime debug je `DEBUG` v procese aplikácie `true` a konzola po prvom štarte vypíše štartovacie informácie (`F.console()`).\n\nWatcher zapíše svoje PID do `<script>.pid` (`index.pid`); keď súbor zmažeš, watcher aj aplikácia sa do pár sekúnd zastavia. Keď proces aplikácie skončí sám, skončí aj watcher. `options.inspector` spustí podriadený proces s `--inspect=<port>`.\n\n### Live reload\n\nKeď nastavíš `options.livereload` na hostname svojej aplikácie, watcher sa pripojí k službe live reload od Total.js (`wss://livereload.totaljs.com/?hostname=...`) a pošle tam názov každého zmeneného súboru `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` alebo `.resource`, vrátane zmien v `public` a `views`. Ostatné súbory v sledovaných priečinkoch sa v tomto režime nesledujú.\n\n## Režim release\n\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nV režime release beží aplikácia v tom istom procese, bez watchera, a `DEBUG` je `false`. Keď ho spustíš s argumentom `--watcher` (`node index.js --watcher`), proces sa stane watcherom pre režim release: vypíše `RELEASE PID`, spustí aplikáciu v podriadenom procese, zapíše `<script>.pid`, reštartuje aplikáciu, keď skončí, a zastaví sa, keď zmažeš PID súbor. Súbory nesleduje.\n\n### Servisný režim\n\n`options.servicemode` načíta aplikáciu bez HTTP servera: `true` načíta všetko, reťazec ako `'config,modules,actions'` načíta iba tieto časti (názvy z `LOAD()`). Funguje v oboch režimoch.\n\n### Klaster\n\n`options.cluster` spustí aplikáciu vo viacerých vláknach Node.js klastra, ktoré zdieľajú port: číslo, alebo `'auto'`, ktoré začne s jedným vláknom a pridáva vlákna (až do `options.limit`), keď vlákna odpovedajú pomaly. V režime debug watcher reštartuje všetky vlákna, keď sa zmení súbor; klaster beží bez watchera, keď je `options.release` `true`. Viac o vláknach nájdeš v [Workery, vlákna a klaster](../../guides/workers-and-threads/).\n\n## Bundly\n\nBundle je jeden súbor `.bundle` so súbormi aplikácie alebo jej časti (modulu, pluginu, administrácie). Vytvoríš ho príkazom `total5 bundle` (pozri [Príkazový riadok](../../guides/command-line/)) a vložíš do priečinka `bundles` inej aplikácie.\n\nKeď `bundles` obsahuje súbory, `LOAD()` zostaví aplikáciu v skrytom priečinku `.src` a spustí ju odtiaľ (`F.isBundle` je `true` a `F.directory` ukazuje na `.src`):\n\n1. Každý súbor `bundles/<name>.url` obsahuje URL; bundle sa stiahne do `bundles/<name>.bundle`.\n2. Súbory predchádzajúceho zostavenia (uvedené v `.src/bundle.json`) sa odstránia.\n3. Každý súbor `.bundle` (okrem kópií `-bk` a `_bk`) sa rozbalí do `.src`. Súbor z `/updates/` sa preskočí, keď on alebo jeho kópia `_bk` už v `.src` existuje; súbor z `/startup/` alebo `/databases/` sa preskočí, keď tam už existuje.\n4. Súbory samotnej aplikácie sa skopírujú cez rozbalené, takže tvoje vlastné súbory majú prednosť. Priečinky `tmp`, `bundles`, `logs`, `node_modules`, skryté súbory a priečinky v koreni a PID súbory sa preskočia.\n5. Zoznam súborov sa zapíše do `.src/bundle.json`.\n\nSúbory `config`, `sitemap`, `versions`, `workflows`, `dependencies` a súbory `.resource` sa zlúčia (každá kópia sa pripojí), takže viacero bundlov môže pridať kľúče do toho istého `config`. Súbor, ktorého názov začína na `--` (`/controllers/--api.js`), sa pripojí k súboru bez pomlčiek.\n\nSúbor `.bundleignore` v koreni obsahuje cesty, ktoré sa nekopírujú, jednu na riadok: priečinok (`/docs/`), súbor (`/readme.md`) alebo súbory s jednou príponou v priečinku (`/public/*.map`).\n\n```\n/docs/\n/readme.md\n/public/*.map\n```\n\nKeď je konfiguračný kľúč `bundling` nastavený na `'shallow'`, zostavenie sa preskočí, ak existuje `.src/bundle.json`, a aplikácia beží z existujúceho `.src`. Bundly sa rozbaľujú pred načítaním súboru `config`, takže kľúč nastav v štartovacích voľbách: `F.run({ config: { bundling: 'shallow' } })`.\n\nSúbor s názvom `bundles.debug` v koreni preskočí zostavenie a spustí aplikáciu priamo z `.src`. Slúži na úpravu rozbalenej aplikácie na mieste: watcher v režime debug potom sleduje `.src`.\n\nS bundlami watcher v režime debug sleduje každý súbor: zmeny v `public` a `views` sa skopírujú do `.src` bez reštartu, ostatné zmeny znova zostavia `.src` a reštartujú aplikáciu.\n\n## Vzdialená úprava\n\nTotal.js Code Editor dokáže upravovať súbory bežiacej aplikácie. Aplikácia sa k editoru pripojí cez WebSocket, takže to funguje aj za firewallom bez otvoreného portu:\n\n```js\nrequire('total5');\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\nURL dostaneš z editora (`http` sa zmení na `ws`). Keď sa spojenie stratí, klient sa každých 10 sekúnd pripojí znova, aj po odpovediach `404 project not found` a `409 project is already open`.\n\nEditor môže prehliadať, načítavať, ukladať, vytvárať, premenovávať, odstraňovať, nahrávať a sťahovať súbory, čítať a mazať logy a v režime debug reštartovať aplikáciu. Môže aj spustiť súbor na serveri (`exec`): súbor `.js` cez Node.js, súbor `.sh` cez `sh` alebo príkazom, ktorý editor pošle; výstup sa vráti do editora. Uložené súbory sa zapíšu do priečinka aplikácie, takže v režime debug watcher po každej zmene aplikáciu reštartuje.\n\nV režime debug beží klient editora v procese watchera. V režime release beží v procese watchera, keď je aplikácia spustená s `--watcher`. `F.remote(url, [directory])` spustí ten istý klient z tvojho vlastného kódu a `total5 edit <url>` ho spustí pre aktuálny priečinok bez spustenia aplikácie.\n\n### Vzdialená úprava AI agentom\n\n`editmcp` robí to isté pre AI agenta. Aplikácia sa pripojí k MCP edit proxy a agent pracuje so súbormi cez MCP nástroje proxy:\n\n```js\nrequire('total5');\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nProxy je Total.js aplikácia s `$mcp : true` a jednou WebSocket trasou:\n\n```js\nconst editmcp = require('total5/edit-mcp');\nROUTE('SOCKET /$mcp/', $ => editmcp.proxy($));\n```\n\nAgent sa pripojí k MCP endpointu proxy s tým istým id, `https://proxy.example.com/$mcp/?id=myproject`, a dostane nástroje `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` a `App_restart`. Proxy pošle každé volanie pripojenej aplikácii, kde sa vykoná; keď nie je pripojená žiadna aplikácia s týmto id, odpoveď je `App is offline.`. Cesty sú relatívne ku koreňu aplikácie. Každý `App_write` uloží zapísaný obsah ako očíslovanú revíziu do priečinka `revisions/` a `App_restore` vráti obsah staršej revízie.\n\n`App_shell` spustí akýkoľvek shell príkaz na počítači aplikácie, takže endpoint proxy chráň cez `Total.mcp.auth` (pozri [MCP server](../mcp-server/)). Rovnako ako pri `edit` beží klient v procese watchera.\n\n## Moduly a MODS\n\nSúbor v `modules` je modul: kúsok kódu, ktorý používa zvyšok aplikácie. Framework ho zaregistruje v `MODS` (`F.modules`) pod `exports.id`, alebo pod názvom súboru, keď `id` chýba, a potom zavolá `install()`:\n\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.install = function() {\n\tROUTE('GET /counter/', function($) {\n\t\t$.json({ count: exports.increment() });\n\t});\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// anywhere after the start\nMODS.counter.increment();\n```\n\nPluginy sa registrujú v `PLUGINS` rovnakým spôsobom (pozri [Pluginy a komponenty](../../guides/plugins-and-components/)).\n\n## IMPORT() a REQUIRE()\n\n`REQUIRE(name)` načíta modul Node.js alebo NPM balíček a hľadá aj v `CONF.$nodemodules`. `IMPORT(url)` stiahne JavaScript súbor do dočasného priečinka a načíta ho, raz za proces:\n\n```js\nvar Fs = REQUIRE('fs');\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\n```\n\n## Štatistiky frameworku\n\n`F.stats` obsahuje počítadlá za celý život procesu: požiadavky podľa metódy a typu, odpovede podľa typu a HTTP kódu, prenesené dáta, `compilation` a `compiled` zo štartu a `error`.\n\nRaz za minútu servisný časovač vypočíta štatistiky využitia procesu do `F.consumption` a vyšle `ON('$stats', stats)`. Prvé štatistiky sa vypočítajú 5 sekúnd po načítaní aplikácie. Keď je `CONF.$stats` `true` (predvolené), zapíšu sa aj do `<script>.json` vedľa štartovacieho skriptu (`index.js.json`), takže ich monitorovací nástroj môže čítať bez toho, aby sa pýtal aplikácie:\n\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory usage:', stats.memory, 'MB');\n});\n```\n\nPolia (pamäť, požiadavky, chyby, počítadlá za minútu ...) sú uvedené v referencii `F.consumption`. `overload` počíta hodiny, v ktorých bolo využitie nad 80 %, pamäť nad 600 MB alebo čakalo viac ako 1000 požiadaviek. `uptime` je počet minút od štartu.\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JafwTt97x60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Unit tests","summary":"Write unit tests with the Test runner of total5/test: test groups, results, fake actions and how to run them with total5 test.","markdown":"---\ntitle: Unit tests\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/unit-tests/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Unit tests\n\n> Write unit tests with the Test runner of total5/test: test groups, results, fake actions and how to run them with total5 test.\n\n`total5` contains a small test runner. `require('total5/test')` loads the framework (when it is not loaded yet) and creates the global object `Test`. You add test groups with `Test.push()`, check results with `Test.print()` and start them with `Test.run()`:\n\n```js\n// tests/run.js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nThe groups run one by one; each one gets `next` and must call it. `Test.print(message)` prints `[OK]`. With a second argument it prints `[FAIL]`, throws the error and ends the process with exit code 1, so the first failure stops the run and a CI job fails. When all groups are done, `Test.run()` prints the number of checks and the time and ends the process with exit code 0, or calls your callback instead.\n\nTo test routes, start the server with `F.http()` and wait for `ON('ready')`. Routes answer a moment later, so wait about 500 ms more before the first request. Then send requests with `RESTBuilder` (see [HTTP requests](../../guides/http-requests/)) from the test groups.\n\n## Running tests with total5 test\n\nThe command `total5 test` runs the test scripts of a project without a script of your own that loads them. Put the scripts into the `tests` directory of the project:\n\n```\ntests/\n\tconfig\n\tinit.js\n\torders.js\n\tstrings.js\n```\n\n```bash\ncd ~/projects/shop\ntotal5 test                  # all scripts\ntotal5 test strings          # tests/strings.js\ntotal5 test strings orders   # two scripts, in this order\n```\n\nThe command:\n\n1. takes the `tests` directory of the current directory, or the current directory when it has no `tests` directory,\n2. loads the `config` file of that directory into `CONF`, in the format of the [configuration](../../guides/configuration/) file,\n3. creates `Test` and loads `init.js` when it exists,\n4. loads the scripts named in the arguments in their order or, without names, every `.js` file of the directory except `init.js`, in alphabetical order,\n5. calls `Test.run()`.\n\nThe names can also be separated with commas (`total5 test strings,orders`) and the `.js` extension is optional. A name without a file prints `ERROR: the test \"name\" not found (path)` and ends with exit code 1. The scripts do not need `require('total5/test')`, `Test` is already global:\n\n```js\n// tests/strings.js\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('config', CONF.name === 'Shop tests' ? null : 'Unexpected name');\n\tnext();\n});\n```\n\nThe process ends with exit code 0 when all groups are done, and with exit code 1 when a check fails or when the run stops before the end (for example a group that never calls `next`).\n\n`total5 test` uses the `total5` package installed in the project (in `node_modules` of the current directory or of a parent directory), so it works from the `tests` directory too; without one it uses the package the command belongs to. The root of the application (`PATH.root()`) is the current directory, so run the command from the root of the project when the tests load parts of the application.\n\nThe command does not start the application. Load what the tests need in `init.js`: it is loaded before the scripts, so a group it adds runs first. `LOAD()` is asynchronous, so call it inside a group and continue with `next` when it is done:\n\n```js\n// tests/init.js\nTest.push('Init', function(next) {\n\tLOAD('actions', next);\n});\n```\n\n## Fake actions\n\n`Test.fake(name, action)` replaces an action for the test. `action` is the same object as in `NEWACTION()`; the original action is kept aside. `Test.restore()` puts all original actions back and removes the fakes of names that had no action. Use it to keep a test away from e-mails, payments or other services. With these actions:\n\n```js\n// actions/orders.js\nNEWACTION('Orders/create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tACTION('Mail/send', { to: 'shop@example.com', subject: 'Order ' + model.name }).callback(function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback({ name: model.name, mail: response });\n\t\t});\n\t}\n});\n\nNEWACTION('Mail/send', {\n\tinput: '*to:Email,*subject:String',\n\taction: function($, model) {\n\t\t// sends the e-mail\n\t\t$.callback('sent');\n\t}\n});\n```\n\nthe test of `Orders/create` replaces `Mail/send`:\n\n```js\n// tests/orders.js\nTest.push('Orders', async function(next) {\n\n\tvar sent = [];\n\n\t// no e-mail goes out during the test\n\tTest.fake('Mail/send', {\n\t\tinput: '*to:Email,*subject:String',\n\t\taction: function($, model) {\n\t\t\tsent.push(model.subject);\n\t\t\t$.callback('fake');\n\t\t}\n\t});\n\n\tvar response = await ACTION('Orders/create', { name: 'A100' }).promise();\n\tTest.print('Orders/create', response.mail === 'fake' ? null : 'The fake was not used');\n\tTest.print('Mail/send', sent[0] === 'Order A100' ? null : 'No e-mail');\n\n\tTest.restore();\n\tnext();\n});\n```\n\nWhen an action is faked more times before `Test.restore()`, the last fake is used and the restore puts back the original from before the first fake.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JafwTt97x60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Unit-Tests","summary":"Schreibe Unit-Tests mit dem Test-Runner von total5/test: Testgruppen, Ergebnisse, Fake-Aktionen und wie du sie mit total5 test ausführst.","markdown":"---\ntitle: Unit-Tests\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/unit-tests/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Unit-Tests\n\n> Schreibe Unit-Tests mit dem Test-Runner von total5/test: Testgruppen, Ergebnisse, Fake-Aktionen und wie du sie mit total5 test ausführst.\n\n`total5` enthält einen kleinen Test-Runner. `require('total5/test')` lädt das Framework (wenn es noch nicht geladen ist) und erzeugt das globale Objekt `Test`. Du fügst Testgruppen mit `Test.push()` hinzu, prüfst Ergebnisse mit `Test.print()` und startest sie mit `Test.run()`:\n\n```js\n// tests/run.js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nDie Gruppen laufen nacheinander; jede erhält `next` und muss es aufrufen. `Test.print(message)` gibt `[OK]` aus. Mit einem zweiten Argument gibt es `[FAIL]` aus, wirft den Fehler und beendet den Prozess mit Exit-Code 1, sodass der erste Fehlschlag den Lauf stoppt und ein CI-Job fehlschlägt. Wenn alle Gruppen fertig sind, gibt `Test.run()` die Anzahl der Prüfungen und die Zeit aus und beendet den Prozess mit Exit-Code 0 oder ruft stattdessen deinen Callback auf.\n\nUm Routen zu testen, starte den Server mit `F.http()` und warte auf `ON('ready')`. Die Routen antworten erst einen Moment später, warte also vor der ersten Anfrage noch etwa 500 ms. Sende dann aus den Testgruppen Anfragen mit `RESTBuilder` (siehe [HTTP-Anfragen](../../guides/http-requests/)).\n\n## Tests mit total5 test ausführen\n\nDer Befehl `total5 test` führt die Testskripte eines Projekts aus, ohne dass du ein eigenes Skript zum Laden schreiben musst. Lege die Skripte in das Verzeichnis `tests` des Projekts:\n\n```\ntests/\n\tconfig\n\tinit.js\n\torders.js\n\tstrings.js\n```\n\n```bash\ncd ~/projects/shop\ntotal5 test                  # all scripts\ntotal5 test strings          # tests/strings.js\ntotal5 test strings orders   # two scripts, in this order\n```\n\nDer Befehl:\n\n1. nimmt das Verzeichnis `tests` des aktuellen Verzeichnisses oder das aktuelle Verzeichnis, wenn es kein Verzeichnis `tests` hat,\n2. lädt die Datei `config` dieses Verzeichnisses in `CONF`, im Format der [Konfigurationsdatei](../../guides/configuration/),\n3. erstellt `Test` und lädt `init.js`, wenn es existiert,\n4. lädt die in den Argumenten genannten Skripte in ihrer Reihenfolge oder, ohne Namen, jede `.js`-Datei des Verzeichnisses außer `init.js` in alphabetischer Reihenfolge,\n5. ruft `Test.run()` auf.\n\nDie Namen können auch durch Kommas getrennt werden (`total5 test strings,orders`), und die Endung `.js` ist optional. Ein Name ohne Datei gibt `ERROR: the test \"name\" not found (path)` aus und endet mit Exit-Code 1. Die Skripte brauchen kein `require('total5/test')`, `Test` ist bereits global:\n\n```js\n// tests/strings.js\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('config', CONF.name === 'Shop tests' ? null : 'Unexpected name');\n\tnext();\n});\n```\n\nDer Prozess endet mit Exit-Code 0, wenn alle Gruppen fertig sind, und mit Exit-Code 1, wenn eine Prüfung fehlschlägt oder der Lauf vor dem Ende stoppt (zum Beispiel bei einer Gruppe, die nie `next` aufruft).\n\n`total5 test` verwendet das im Projekt installierte Paket `total5` (in `node_modules` des aktuellen Verzeichnisses oder eines übergeordneten Verzeichnisses), daher funktioniert es auch aus dem Verzeichnis `tests`; ohne eines verwendet es das Paket, zu dem der Befehl gehört. Die Wurzel der Anwendung (`PATH.root()`) ist das aktuelle Verzeichnis, also führe den Befehl aus der Wurzel des Projekts aus, wenn die Tests Teile der Anwendung laden.\n\nDer Befehl startet die Anwendung nicht. Lade das, was die Tests brauchen, in `init.js`: Es wird vor den Skripten geladen, daher läuft eine Gruppe, die es hinzufügt, zuerst. `LOAD()` ist asynchron, also rufe es innerhalb einer Gruppe auf und mach mit `next` weiter, wenn es fertig ist:\n\n```js\n// tests/init.js\nTest.push('Init', function(next) {\n\tLOAD('actions', next);\n});\n```\n\n## Fake-Aktionen\n\n`Test.fake(name, action)` ersetzt eine Aktion für den Test. `action` ist dasselbe Objekt wie in `NEWACTION()`; die ursprüngliche Aktion wird beiseitegelegt. `Test.restore()` stellt alle ursprünglichen Aktionen wieder her und entfernt die Fakes von Namen, die keine Aktion hatten. Verwende es, um einen Test von E-Mails, Zahlungen oder anderen Diensten fernzuhalten. Mit diesen Aktionen:\n\n```js\n// actions/orders.js\nNEWACTION('Orders/create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tACTION('Mail/send', { to: 'shop@example.com', subject: 'Order ' + model.name }).callback(function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback({ name: model.name, mail: response });\n\t\t});\n\t}\n});\n\nNEWACTION('Mail/send', {\n\tinput: '*to:Email,*subject:String',\n\taction: function($, model) {\n\t\t// sends the e-mail\n\t\t$.callback('sent');\n\t}\n});\n```\n\nersetzt der Test von `Orders/create` die Aktion `Mail/send`:\n\n```js\n// tests/orders.js\nTest.push('Orders', async function(next) {\n\n\tvar sent = [];\n\n\t// no e-mail goes out during the test\n\tTest.fake('Mail/send', {\n\t\tinput: '*to:Email,*subject:String',\n\t\taction: function($, model) {\n\t\t\tsent.push(model.subject);\n\t\t\t$.callback('fake');\n\t\t}\n\t});\n\n\tvar response = await ACTION('Orders/create', { name: 'A100' }).promise();\n\tTest.print('Orders/create', response.mail === 'fake' ? null : 'The fake was not used');\n\tTest.print('Mail/send', sent[0] === 'Order A100' ? null : 'No e-mail');\n\n\tTest.restore();\n\tnext();\n});\n```\n\nWenn eine Aktion vor `Test.restore()` mehrmals gefakt wird, wird der letzte Fake verwendet, und die Wiederherstellung setzt das Original von vor dem ersten Fake zurück.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JafwTt97x60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Tests unitarios","summary":"Escribe tests unitarios con el ejecutor Test de total5/test: grupos de tests, resultados, acciones falsas y cómo ejecutarlos con total5 test.","markdown":"---\ntitle: Tests unitarios\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/unit-tests/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Tests unitarios\n\n> Escribe tests unitarios con el ejecutor Test de total5/test: grupos de tests, resultados, acciones falsas y cómo ejecutarlos con total5 test.\n\n`total5` contiene un pequeño ejecutor de tests. `require('total5/test')` carga el framework (si aún no está cargado) y crea el objeto global `Test`. Añades grupos de tests con `Test.push()`, compruebas resultados con `Test.print()` y los inicias con `Test.run()`:\n\n```js\n// tests/run.js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nLos grupos se ejecutan uno a uno; cada uno recibe `next` y debe llamarlo. `Test.print(message)` imprime `[OK]`. Con un segundo argumento imprime `[FAIL]`, lanza el error y termina el proceso con el código de salida 1, así que el primer fallo detiene la ejecución y un job de CI falla. Cuando todos los grupos han terminado, `Test.run()` imprime el número de comprobaciones y el tiempo y termina el proceso con el código de salida 0, o llama a tu callback en su lugar.\n\nPara probar rutas, inicia el servidor con `F.http()` y espera a `ON('ready')`. Las rutas responden un momento después, así que espera unos 500 ms más antes de la primera petición. Luego envía peticiones con `RESTBuilder` (consulta [Peticiones HTTP](../../guides/http-requests/)) desde los grupos de tests.\n\n## Ejecutar tests con total5 test\n\nEl comando `total5 test` ejecuta los scripts de test de un proyecto sin un script propio que los cargue. Pon los scripts en el directorio `tests` del proyecto:\n\n```\ntests/\n\tconfig\n\tinit.js\n\torders.js\n\tstrings.js\n```\n\n```bash\ncd ~/projects/shop\ntotal5 test                  # all scripts\ntotal5 test strings          # tests/strings.js\ntotal5 test strings orders   # two scripts, in this order\n```\n\nEl comando:\n\n1. toma el directorio `tests` del directorio actual, o el directorio actual cuando no tiene directorio `tests`,\n2. carga el archivo `config` de ese directorio en `CONF`, en el formato del archivo de [configuración](../../guides/configuration/),\n3. crea `Test` y carga `init.js` cuando existe,\n4. carga los scripts indicados en los argumentos en su orden o, sin nombres, todos los archivos `.js` del directorio excepto `init.js`, en orden alfabético,\n5. llama a `Test.run()`.\n\nLos nombres también se pueden separar con comas (`total5 test strings,orders`) y la extensión `.js` es opcional. Un nombre sin archivo imprime `ERROR: the test \"name\" not found (path)` y termina con el código de salida 1. Los scripts no necesitan `require('total5/test')`, `Test` ya es global:\n\n```js\n// tests/strings.js\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('config', CONF.name === 'Shop tests' ? null : 'Unexpected name');\n\tnext();\n});\n```\n\nEl proceso termina con el código de salida 0 cuando todos los grupos han terminado, y con el código de salida 1 cuando falla una comprobación o cuando la ejecución se detiene antes del final (por ejemplo un grupo que nunca llama a `next`).\n\n`total5 test` usa el paquete `total5` instalado en el proyecto (en `node_modules` del directorio actual o de un directorio padre), así que también funciona desde el directorio `tests`; si no lo hay, usa el paquete al que pertenece el comando. La raíz de la aplicación (`PATH.root()`) es el directorio actual, así que ejecuta el comando desde la raíz del proyecto cuando los tests cargan partes de la aplicación.\n\nEl comando no arranca la aplicación. Carga lo que necesitan los tests en `init.js`: se carga antes que los scripts, así que un grupo que añade se ejecuta primero. `LOAD()` es asíncrono, así que llámalo dentro de un grupo y continúa con `next` cuando termine:\n\n```js\n// tests/init.js\nTest.push('Init', function(next) {\n\tLOAD('actions', next);\n});\n```\n\n## Acciones falsas\n\n`Test.fake(name, action)` sustituye una acción para el test. `action` es el mismo objeto que en `NEWACTION()`; la acción original se guarda aparte. `Test.restore()` vuelve a poner todas las acciones originales y elimina las falsas de nombres que no tenían acción. Úsalo para mantener un test alejado de e-mails, pagos u otros servicios. Con estas acciones:\n\n```js\n// actions/orders.js\nNEWACTION('Orders/create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tACTION('Mail/send', { to: 'shop@example.com', subject: 'Order ' + model.name }).callback(function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback({ name: model.name, mail: response });\n\t\t});\n\t}\n});\n\nNEWACTION('Mail/send', {\n\tinput: '*to:Email,*subject:String',\n\taction: function($, model) {\n\t\t// sends the e-mail\n\t\t$.callback('sent');\n\t}\n});\n```\n\nel test de `Orders/create` sustituye `Mail/send`:\n\n```js\n// tests/orders.js\nTest.push('Orders', async function(next) {\n\n\tvar sent = [];\n\n\t// no e-mail goes out during the test\n\tTest.fake('Mail/send', {\n\t\tinput: '*to:Email,*subject:String',\n\t\taction: function($, model) {\n\t\t\tsent.push(model.subject);\n\t\t\t$.callback('fake');\n\t\t}\n\t});\n\n\tvar response = await ACTION('Orders/create', { name: 'A100' }).promise();\n\tTest.print('Orders/create', response.mail === 'fake' ? null : 'The fake was not used');\n\tTest.print('Mail/send', sent[0] === 'Order A100' ? null : 'No e-mail');\n\n\tTest.restore();\n\tnext();\n});\n```\n\nCuando una acción se falsea varias veces antes de `Test.restore()`, se usa la última falsa y la restauración vuelve a poner la original de antes de la primera.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JafwTt97x60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Tests unitaires","summary":"Écris des tests unitaires avec l'exécuteur Test de total5/test : groupes de tests, résultats, fausses actions et comment les lancer avec total5 test.","markdown":"---\ntitle: Tests unitaires\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/unit-tests/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Tests unitaires\n\n> Écris des tests unitaires avec l'exécuteur Test de total5/test : groupes de tests, résultats, fausses actions et comment les lancer avec total5 test.\n\n`total5` contient un petit exécuteur de tests. `require('total5/test')` charge le framework (s'il n'est pas encore chargé) et crée l'objet global `Test`. Tu ajoutes des groupes de tests avec `Test.push()`, vérifies les résultats avec `Test.print()` et les lances avec `Test.run()` :\n\n```js\n// tests/run.js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nLes groupes s'exécutent l'un après l'autre ; chacun reçoit `next` et doit l'appeler. `Test.print(message)` affiche `[OK]`. Avec un second argument, il affiche `[FAIL]`, lève l'erreur et termine le processus avec le code de sortie 1 : le premier échec arrête donc l'exécution et un job de CI échoue. Quand tous les groupes sont terminés, `Test.run()` affiche le nombre de vérifications et la durée et termine le processus avec le code de sortie 0, ou appelle ton callback à la place.\n\nPour tester des routes, démarre le serveur avec `F.http()` et attends `ON('ready')`. Les routes répondent un instant plus tard : attends donc encore environ 500 ms avant la première requête. Envoie ensuite des requêtes avec `RESTBuilder` (voir [Requêtes HTTP](../../guides/http-requests/)) depuis les groupes de tests.\n\n## Lancer les tests avec total5 test\n\nLa commande `total5 test` lance les scripts de test d'un projet sans script à toi pour les charger. Place les scripts dans le répertoire `tests` du projet :\n\n```\ntests/\n\tconfig\n\tinit.js\n\torders.js\n\tstrings.js\n```\n\n```bash\ncd ~/projects/shop\ntotal5 test                  # all scripts\ntotal5 test strings          # tests/strings.js\ntotal5 test strings orders   # two scripts, in this order\n```\n\nLa commande :\n\n1. prend le répertoire `tests` du répertoire courant, ou le répertoire courant quand il n'a pas de répertoire `tests`,\n2. charge le fichier `config` de ce répertoire dans `CONF`, au format du fichier de [configuration](../../guides/configuration/),\n3. crée `Test` et charge `init.js` s'il existe,\n4. charge les scripts nommés dans les arguments dans leur ordre ou, sans noms, chaque fichier `.js` du répertoire sauf `init.js`, dans l'ordre alphabétique,\n5. appelle `Test.run()`.\n\nLes noms peuvent aussi être séparés par des virgules (`total5 test strings,orders`) et l'extension `.js` est facultative. Un nom sans fichier affiche `ERROR: the test \"name\" not found (path)` et se termine avec le code de sortie 1. Les scripts n'ont pas besoin de `require('total5/test')`, `Test` est déjà global :\n\n```js\n// tests/strings.js\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('config', CONF.name === 'Shop tests' ? null : 'Unexpected name');\n\tnext();\n});\n```\n\nLe processus se termine avec le code de sortie 0 quand tous les groupes sont terminés, et avec le code de sortie 1 quand une vérification échoue ou quand l'exécution s'arrête avant la fin (par exemple un groupe qui n'appelle jamais `next`).\n\n`total5 test` utilise le paquet `total5` installé dans le projet (dans `node_modules` du répertoire courant ou d'un répertoire parent), donc il fonctionne aussi depuis le répertoire `tests` ; sans lui, il utilise le paquet auquel appartient la commande. La racine de l'application (`PATH.root()`) est le répertoire courant, donc lance la commande depuis la racine du projet quand les tests chargent des parties de l'application.\n\nLa commande ne démarre pas l'application. Charge ce dont les tests ont besoin dans `init.js` : il est chargé avant les scripts, donc un groupe qu'il ajoute s'exécute en premier. `LOAD()` est asynchrone, donc appelle-la dans un groupe et continue avec `next` quand elle a terminé :\n\n```js\n// tests/init.js\nTest.push('Init', function(next) {\n\tLOAD('actions', next);\n});\n```\n\n## Fausses actions\n\n`Test.fake(name, action)` remplace une action pour le test. `action` est le même objet que dans `NEWACTION()` ; l'action d'origine est mise de côté. `Test.restore()` remet toutes les actions d'origine et supprime les fausses actions des noms qui n'avaient pas d'action. Utilise-la pour tenir un test à l'écart des e-mails, des paiements ou d'autres services. Avec ces actions :\n\n```js\n// actions/orders.js\nNEWACTION('Orders/create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tACTION('Mail/send', { to: 'shop@example.com', subject: 'Order ' + model.name }).callback(function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback({ name: model.name, mail: response });\n\t\t});\n\t}\n});\n\nNEWACTION('Mail/send', {\n\tinput: '*to:Email,*subject:String',\n\taction: function($, model) {\n\t\t// sends the e-mail\n\t\t$.callback('sent');\n\t}\n});\n```\n\nle test de `Orders/create` remplace `Mail/send` :\n\n```js\n// tests/orders.js\nTest.push('Orders', async function(next) {\n\n\tvar sent = [];\n\n\t// no e-mail goes out during the test\n\tTest.fake('Mail/send', {\n\t\tinput: '*to:Email,*subject:String',\n\t\taction: function($, model) {\n\t\t\tsent.push(model.subject);\n\t\t\t$.callback('fake');\n\t\t}\n\t});\n\n\tvar response = await ACTION('Orders/create', { name: 'A100' }).promise();\n\tTest.print('Orders/create', response.mail === 'fake' ? null : 'The fake was not used');\n\tTest.print('Mail/send', sent[0] === 'Order A100' ? null : 'No e-mail');\n\n\tTest.restore();\n\tnext();\n});\n```\n\nQuand une action est remplacée plusieurs fois avant `Test.restore()`, la dernière fausse action est utilisée et la restauration remet l'action d'origine d'avant le premier remplacement.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JafwTt97x60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Test unitari","summary":"Scrivi test unitari con il test runner di total5/test: gruppi di test, risultati, azioni finte e come eseguirli con total5 test.","markdown":"---\ntitle: Test unitari\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/unit-tests/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Test unitari\n\n> Scrivi test unitari con il test runner di total5/test: gruppi di test, risultati, azioni finte e come eseguirli con total5 test.\n\n`total5` contiene un piccolo test runner. `require('total5/test')` carica il framework (se non è ancora caricato) e crea l'oggetto globale `Test`. Aggiungi gruppi di test con `Test.push()`, verifichi i risultati con `Test.print()` e li avvii con `Test.run()`:\n\n```js\n// tests/run.js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nI gruppi vengono eseguiti uno alla volta; ognuno riceve `next` e deve chiamarlo. `Test.print(message)` stampa `[OK]`. Con un secondo argomento stampa `[FAIL]`, lancia l'errore e termina il processo con exit code 1, quindi il primo fallimento ferma l'esecuzione e un job di CI fallisce. Quando tutti i gruppi sono terminati, `Test.run()` stampa il numero di verifiche e il tempo e termina il processo con exit code 0, oppure chiama invece la tua callback.\n\nPer testare le route, avvia il server con `F.http()` e attendi `ON('ready')`. Le route rispondono un momento dopo, quindi attendi circa altri 500 ms prima della prima richiesta. Poi invia richieste con `RESTBuilder` (vedi [Richieste HTTP](../../guides/http-requests/)) dai gruppi di test.\n\n## Eseguire i test con total5 test\n\nIl comando `total5 test` esegue gli script di test di un progetto senza uno script tuo che li carichi. Metti gli script nella directory `tests` del progetto:\n\n```\ntests/\n\tconfig\n\tinit.js\n\torders.js\n\tstrings.js\n```\n\n```bash\ncd ~/projects/shop\ntotal5 test                  # all scripts\ntotal5 test strings          # tests/strings.js\ntotal5 test strings orders   # two scripts, in this order\n```\n\nIl comando:\n\n1. prende la directory `tests` della directory corrente, oppure la directory corrente quando non ha una directory `tests`,\n2. carica il file `config` di quella directory in `CONF`, nel formato del file di [configurazione](../../guides/configuration/),\n3. crea `Test` e carica `init.js` quando esiste,\n4. carica gli script indicati negli argomenti nel loro ordine oppure, senza nomi, ogni file `.js` della directory tranne `init.js`, in ordine alfabetico,\n5. chiama `Test.run()`.\n\nI nomi possono anche essere separati da virgole (`total5 test strings,orders`) e l'estensione `.js` è facoltativa. Un nome senza file stampa `ERROR: the test \"name\" not found (path)` e termina con exit code 1. Gli script non hanno bisogno di `require('total5/test')`, `Test` è già globale:\n\n```js\n// tests/strings.js\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('config', CONF.name === 'Shop tests' ? null : 'Unexpected name');\n\tnext();\n});\n```\n\nIl processo termina con exit code 0 quando tutti i gruppi sono completati, e con exit code 1 quando un controllo fallisce o quando l'esecuzione si ferma prima della fine (per esempio un gruppo che non chiama mai `next`).\n\n`total5 test` usa il pacchetto `total5` installato nel progetto (in `node_modules` della directory corrente o di una directory superiore), quindi funziona anche dalla directory `tests`; senza di esso usa il pacchetto a cui appartiene il comando. La radice dell'applicazione (`PATH.root()`) è la directory corrente, quindi esegui il comando dalla radice del progetto quando i test caricano parti dell'applicazione.\n\nIl comando non avvia l'applicazione. Carica ciò che serve ai test in `init.js`: viene caricato prima degli script, quindi un gruppo che aggiunge viene eseguito per primo. `LOAD()` è asincrona, quindi chiamala dentro un gruppo e continua con `next` quando ha finito:\n\n```js\n// tests/init.js\nTest.push('Init', function(next) {\n\tLOAD('actions', next);\n});\n```\n\n## Azioni finte\n\n`Test.fake(name, action)` sostituisce un'azione per il test. `action` è lo stesso oggetto di `NEWACTION()`; l'azione originale viene messa da parte. `Test.restore()` rimette tutte le azioni originali e rimuove le azioni finte dei nomi che non avevano un'azione. Usalo per tenere un test lontano da e-mail, pagamenti o altri servizi. Con queste azioni:\n\n```js\n// actions/orders.js\nNEWACTION('Orders/create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tACTION('Mail/send', { to: 'shop@example.com', subject: 'Order ' + model.name }).callback(function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback({ name: model.name, mail: response });\n\t\t});\n\t}\n});\n\nNEWACTION('Mail/send', {\n\tinput: '*to:Email,*subject:String',\n\taction: function($, model) {\n\t\t// sends the e-mail\n\t\t$.callback('sent');\n\t}\n});\n```\n\nil test di `Orders/create` sostituisce `Mail/send`:\n\n```js\n// tests/orders.js\nTest.push('Orders', async function(next) {\n\n\tvar sent = [];\n\n\t// no e-mail goes out during the test\n\tTest.fake('Mail/send', {\n\t\tinput: '*to:Email,*subject:String',\n\t\taction: function($, model) {\n\t\t\tsent.push(model.subject);\n\t\t\t$.callback('fake');\n\t\t}\n\t});\n\n\tvar response = await ACTION('Orders/create', { name: 'A100' }).promise();\n\tTest.print('Orders/create', response.mail === 'fake' ? null : 'The fake was not used');\n\tTest.print('Mail/send', sent[0] === 'Order A100' ? null : 'No e-mail');\n\n\tTest.restore();\n\tnext();\n});\n```\n\nQuando un'azione viene sostituita più volte prima di `Test.restore()`, viene usata l'ultima azione finta e il ripristino rimette l'originale di prima della prima sostituzione.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JafwTt97x60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Unit testy","summary":"Píš unit testy so spúšťačom Test z total5/test: skupiny testov, výsledky, falošné akcie a ako ich spustiť cez total5 test.","markdown":"---\ntitle: Unit testy\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/unit-tests/\nupdated: 2026-11-18T15:27:34.798Z\n---\n\n# Unit testy\n\n> Píš unit testy so spúšťačom Test z total5/test: skupiny testov, výsledky, falošné akcie a ako ich spustiť cez total5 test.\n\n`total5` obsahuje malý spúšťač testov. `require('total5/test')` načíta framework (ak ešte nie je načítaný) a vytvorí globálny objekt `Test`. Skupiny testov pridávaš cez `Test.push()`, výsledky kontroluješ cez `Test.print()` a spúšťaš ich cez `Test.run()`:\n\n```js\n// tests/run.js\nrequire('total5/test');\n\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('capitalize()', 'total'.capitalize() === 'Total' ? null : 'Unexpected value');\n\tnext();\n});\n\nTest.run();\n```\n\nSkupiny bežia jedna po druhej; každá dostane `next` a musí ho zavolať. `Test.print(message)` vypíše `[OK]`. S druhým argumentom vypíše `[FAIL]`, vyhodí chybu a ukončí proces s návratovým kódom 1, takže prvé zlyhanie zastaví beh a CI úloha zlyhá. Keď sú všetky skupiny hotové, `Test.run()` vypíše počet kontrol a čas a ukončí proces s návratovým kódom 0, alebo namiesto toho zavolá tvoj callback.\n\nNa testovanie rout spusti server cez `F.http()` a počkaj na `ON('ready')`. Routy odpovedajú až o chvíľu neskôr, preto pred prvou požiadavkou počkaj ešte asi 500 ms. Potom zo skupín testov posielaj požiadavky cez `RESTBuilder` (pozri [HTTP požiadavky](../../guides/http-requests/)).\n\n## Spúšťanie testov cez total5 test\n\nPríkaz `total5 test` spustí testovacie skripty projektu bez vlastného skriptu, ktorý by ich načítal. Skripty daj do adresára `tests` projektu:\n\n```\ntests/\n\tconfig\n\tinit.js\n\torders.js\n\tstrings.js\n```\n\n```bash\ncd ~/projects/shop\ntotal5 test                  # all scripts\ntotal5 test strings          # tests/strings.js\ntotal5 test strings orders   # two scripts, in this order\n```\n\nPríkaz:\n\n1. vezme adresár `tests` aktuálneho adresára, alebo aktuálny adresár, keď nemá adresár `tests`,\n2. načíta súbor `config` tohto adresára do `CONF` vo formáte súboru [konfigurácie](../../guides/configuration/),\n3. vytvorí `Test` a načíta `init.js`, keď existuje,\n4. načíta skripty pomenované v argumentoch v ich poradí, alebo bez názvov každý súbor `.js` adresára okrem `init.js` v abecednom poradí,\n5. zavolá `Test.run()`.\n\nNázvy môžu byť oddelené aj čiarkami (`total5 test strings,orders`) a prípona `.js` je voliteľná. Názov bez súboru vypíše `ERROR: the test \"name\" not found (path)` a skončí s exit kódom 1. Skripty nepotrebujú `require('total5/test')`, `Test` je už globálny:\n\n```js\n// tests/strings.js\nTest.push('Strings', function(next) {\n\tTest.print('slug()', 'Hello World'.slug() === 'hello-world' ? null : 'Unexpected slug');\n\tTest.print('config', CONF.name === 'Shop tests' ? null : 'Unexpected name');\n\tnext();\n});\n```\n\nProces skončí s exit kódom 0, keď sú všetky skupiny hotové, a s exit kódom 1, keď kontrola zlyhá alebo keď sa beh zastaví pred koncom (napríklad skupina, ktorá nikdy nezavolá `next`).\n\n`total5 test` používa balík `total5` nainštalovaný v projekte (v `node_modules` aktuálneho adresára alebo nadradeného adresára), takže funguje aj z adresára `tests`; bez neho použije balík, ku ktorému príkaz patrí. Koreň aplikácie (`PATH.root()`) je aktuálny adresár, takže príkaz spúšťaj z koreňa projektu, keď testy načítavajú časti aplikácie.\n\nPríkaz nespúšťa aplikáciu. Čo testy potrebujú, načítaj v `init.js`: načíta sa pred skriptami, takže skupina, ktorú pridá, beží ako prvá. `LOAD()` je asynchrónne, takže ho zavolaj vnútri skupiny a pokračuj cez `next`, keď je hotové:\n\n```js\n// tests/init.js\nTest.push('Init', function(next) {\n\tLOAD('actions', next);\n});\n```\n\n## Falošné akcie\n\n`Test.fake(name, action)` nahradí akciu pre test. `action` je ten istý objekt ako v `NEWACTION()`; pôvodná akcia sa odloží bokom. `Test.restore()` vráti všetky pôvodné akcie späť a odstráni falošné akcie názvov, ktoré žiadnu akciu nemali. Použi ho, aby test nesiahal na e-maily, platby alebo iné služby. S týmito akciami:\n\n```js\n// actions/orders.js\nNEWACTION('Orders/create', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tACTION('Mail/send', { to: 'shop@example.com', subject: 'Order ' + model.name }).callback(function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback({ name: model.name, mail: response });\n\t\t});\n\t}\n});\n\nNEWACTION('Mail/send', {\n\tinput: '*to:Email,*subject:String',\n\taction: function($, model) {\n\t\t// sends the e-mail\n\t\t$.callback('sent');\n\t}\n});\n```\n\ntest `Orders/create` nahradí `Mail/send`:\n\n```js\n// tests/orders.js\nTest.push('Orders', async function(next) {\n\n\tvar sent = [];\n\n\t// no e-mail goes out during the test\n\tTest.fake('Mail/send', {\n\t\tinput: '*to:Email,*subject:String',\n\t\taction: function($, model) {\n\t\t\tsent.push(model.subject);\n\t\t\t$.callback('fake');\n\t\t}\n\t});\n\n\tvar response = await ACTION('Orders/create', { name: 'A100' }).promise();\n\tTest.print('Orders/create', response.mail === 'fake' ? null : 'The fake was not used');\n\tTest.print('Mail/send', sent[0] === 'Order A100' ? null : 'No e-mail');\n\n\tTest.restore();\n\tnext();\n});\n```\n\nKeď sa akcia pred `Test.restore()` nahradí viackrát, použije sa posledná falošná akcia a obnovenie vráti pôvodnú akciu spred prvého nahradenia.\n","entries":[],"license":"MIT","updated":"2026-11-18T15:27:34.798Z"}
{"id":"JafwUC9Wx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/guides/command-line/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"en","title":"Command line (total5)","summary":"The total5 and flow5 programs: a static web server, translations, minifying, bundles, remote editing, a proxy client, tests and running flows.","markdown":"---\ntitle: Command line (total5)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/guides/command-line/\nupdated: 2026-11-16T16:33:35.963Z\n---\n\n# Command line (total5)\n\n> The total5 and flow5 programs: a static web server, translations, minifying, bundles, remote editing, a proxy client, tests and running flows.\n\nThe `total5` package installs two programs: **`total5`**, a toolbox for the directory you are in, and **`flow5`**, which runs FlowStream schemas without an application. Install the package globally to have both on your `PATH` (see [Installation](../../guides/installation/)):\n\n```bash\nnpm install -g total5\n```\n\nEach `total5` command prints a header with its name, does its work and, for the short tasks, ends with a `[Done]` line with the time it took:\n\n```bash\n$ total5 minify /www/app/public/app.js\n* Total.js v5: [Minify]\n----------------------------------------\nFilename  : /www/app/public/app.js\nOutput    : /www/app/public/app.min.js\n----------------------------------------\n[Done]: 1.2ms\n```\n\n## Command syntax\n\n```bash\ntotal5 <command> [arguments]\n```\n\n- The first word is the command. Two or more dashes in front of it are removed, so `total5 --help` is the same as `total5 help`.\n- The words after it are the arguments, in order. Double quotes inside them are removed and spaces at the ends are trimmed.\n- A number as the command (`total5 8000`) starts the web server on that port.\n- `total5` with no command shows the help.\n- A word the program does not know prints only the header and does nothing.\n\n## The help\n\n`total5` or `total5 help` lists the commands:\n\n| Command | What it does |\n| --- | --- |\n| `translate <filename>` | Makes a resource file from the `@(...)` texts of the current directory |\n| `minify <filename>` | Minifies a `.js`, `.css` or `.html` file |\n| `bundle <filename>` | Packs the current directory into a `.bundle` file |\n| `extract <filename>` | Unpacks a bundle into the current directory |\n| `edit <url>` | Opens the current directory for remote editing in the Total.js Code Editor |\n| `proxy <endpoint> <port>` | Connects a local port to a remote Total.js proxy server |\n| `test [names]` | Runs the tests of the current directory or of its `tests` directory |\n| `<port>` | Starts a web server for the current directory |\n\n## A web server for a directory\n\nA number as the command starts a static web server for the current directory. `total5 server [port]` does the same, and the port is `8000` when you leave it out.\n\n```bash\ncd ~/projects/landing\ntotal5 8000\n# http://0.0.0.0:8000/\n```\n\n- Files are served from the current directory. Minification and source maps are off, so you get the files exactly as they are on disk.\n- A URL of a directory shows a listing of its subdirectories and files with their sizes. Click a file (`index.html` too) to open it.\n- The application folders (`controllers/`, `config`, …) are not loaded: it is only a file server.\n\nStop it with `Ctrl+C`.\n\n## Translations\n\n`total5 translate <filename>` reads every `.js` and `.html` file of the current directory and its subdirectories, finds the texts marked with `@(...)` and writes them into the resource file you name. Give the full path of the file:\n\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n```\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\nEach key is `T` plus a hash of the text, the same key the view engine uses when it looks up a translation. Copy the file into `resources/` under a language name and translate the texts after the colon. See [Localization](../../guides/localization/).\n\n## Minifying a file\n\n`total5 minify <filename>` minifies one file and writes the result next to it with `.min` before the extension. Give the full path of the file:\n\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"     # public/js/app.min.js\ntotal5 minify \"$PWD/public/css/site.css\"  # public/css/site.min.css\ntotal5 minify \"$PWD/views/index.html\"     # views/index.min.html\n```\n\nThe extension chooses the minifier: JavaScript, CSS or HTML. The HTML minifier removes comments, shortens runs of spaces inside the markup and minifies inline `<script>` and `<style>` blocks; it keeps the line breaks and the indentation between tags. A file with another extension is copied without change. These are the same minifiers the framework uses for static files (see [Utilities](../../guides/utilities/)).\n\n## Bundles\n\nA bundle is one file that holds a whole application. The framework unpacks the `.bundle` files of the `bundles/` folder when it starts (see [Application structure](../../guides/application-structure/)).\n\n`total5 bundle <filename>` packs the current directory. Give the full path of the bundle and keep it outside the directory you pack:\n\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop     # ~/backups/shop.bundle\n```\n\n`.bundle` is added to the name when it is missing. The bundle leaves out the files that belong to the machine, not to the application: `index.js`, `debug.js`, `release.js` with their `.json` and `.pid` files, `bundle.json`, `package.json`, `readme.md`, `license.txt` and the folders `bundles/`, `tmp/`, `.src/` and `.git/`.\n\n`total5 extract <filename>` unpacks a bundle into the current directory. Give the full path of the bundle:\n\n```bash\nmkdir ~/projects/shop-copy && cd ~/projects/shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n## Remote editing\n\n`total5 edit <url>` connects the current directory to the **Total.js Code Editor**. The editor gives you the URL of the project; the program opens a WebSocket to it (`http` becomes `ws`, `https` becomes `wss`) and answers the requests of the editor: it lists, reads, saves, creates, renames and removes files, uploads and downloads them, reads log files and runs scripts.\n\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n# > Total.js Code Editor: Welcome to \"Code (1.0)\"\n# > Project: \"shop\"\n```\n\nThe connection reconnects every 10 seconds when it drops. The program keeps running until you stop it. Without a URL it stops with the error `Invalid URL address`.\n\n## Proxy client\n\n`total5 proxy <endpoint> <port>` makes a local port reachable through a remote Total.js proxy server, an application that calls `PROXYSERVER()`. The program connects to the server with a WebSocket and forwards each request it receives to the local port:\n\n```bash\ntotal5 8000 &\ntotal5 proxy wss://proxy.example.com/ 8000\ntotal5 proxy wss://proxy.example.com/ 192.168.1.20:8000\n```\n\nThe second argument is a port on `127.0.0.1` or an `ip:port` pair. Each request is printed with its method, the IP address of the visitor and the URL. Without both arguments the program prints how to call it.\n\n## Running tests\n\n`total5 test` runs the test scripts of the `tests` directory of the current directory, or of the current directory when it has no `tests` directory. It loads the `config` file and `init.js` of that directory first, then the scripts you name, or all `.js` files when you name none:\n\n```bash\ncd ~/projects/shop\ntotal5 test\ntotal5 test strings orders\n```\n\nIt uses the `total5` package installed in the project, also when you run it from a subdirectory. A failed check ends the program with exit code 1, so a CI job fails. See [Unit tests](../../guides/unit-tests/).\n\n## Running flows with flow5\n\n`flow5` loads FlowStream schemas and runs them with a small HTTP server, without an application (see [FlowStream](../../guides/flowstream/)):\n\n```bash\nflow5 \"$PWD/flowschema.json\"\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\nflow5 https://example.com/flowschema.json\n```\n\n- Every argument that is a number is the port (`8000` by default). The other arguments are files, with their full path, or `https://` addresses of schemas.\n- A file holds one schema (an object with `components` and `design`) or an object of several schemas under their ids.\n- For each flow it prints a link that opens the flow in the Flow editor at `flow.totaljs.com`, connected to your machine.\n- When you save a flow in the editor, the program writes it back into its file. Give every schema an `id`, and in a file with several flows use the id as the key.\n\n```\n[Total.js v5 Flow Engine]\n|--- http://127.0.0.1:8000\n|--- Orders: https://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n\nThe server has two routes: `GET` and `POST /notify/{id}/` for notifications to the flows, and the WebSocket `/flowstreams/{id}/` for the editor. `flow5` with no arguments prints its help.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:33:35.963Z"}
{"id":"JafwUC9Wx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/command-line/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"de","title":"Kommandozeile (total5)","summary":"Die Programme total5 und flow5: ein statischer Webserver, Übersetzungen, Minifizierung, Bundles, entfernte Bearbeitung, ein Proxy-Client, Tests und das Ausführen von Flows.","markdown":"---\ntitle: Kommandozeile (total5)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/guides/command-line/\nupdated: 2026-11-16T16:33:35.963Z\n---\n\n# Kommandozeile (total5)\n\n> Die Programme total5 und flow5: ein statischer Webserver, Übersetzungen, Minifizierung, Bundles, entfernte Bearbeitung, ein Proxy-Client, Tests und das Ausführen von Flows.\n\nDas Paket `total5` installiert zwei Programme: **`total5`**, einen Werkzeugkasten für das Verzeichnis, in dem du dich befindest, und **`flow5`**, das FlowStream-Schemas ohne Anwendung ausführt. Installiere das Paket global, damit beide in deinem `PATH` liegen (siehe [Installation](../../guides/installation/)):\n\n```bash\nnpm install -g total5\n```\n\nJeder `total5`-Befehl gibt einen Header mit seinem Namen aus, erledigt seine Arbeit und endet bei den kurzen Aufgaben mit einer Zeile `[Done]` mit der benötigten Zeit:\n\n```bash\n$ total5 minify /www/app/public/app.js\n* Total.js v5: [Minify]\n----------------------------------------\nFilename  : /www/app/public/app.js\nOutput    : /www/app/public/app.min.js\n----------------------------------------\n[Done]: 1.2ms\n```\n\n## Befehlssyntax\n\n```bash\ntotal5 <command> [arguments]\n```\n\n- Das erste Wort ist der Befehl. Zwei oder mehr Bindestriche davor werden entfernt, daher ist `total5 --help` dasselbe wie `total5 help`.\n- Die Wörter danach sind die Argumente, in Reihenfolge. Doppelte Anführungszeichen darin werden entfernt und Leerzeichen an den Enden abgeschnitten.\n- Eine Zahl als Befehl (`total5 8000`) startet den Webserver auf diesem Port.\n- `total5` ohne Befehl zeigt die Hilfe.\n- Ein Wort, das das Programm nicht kennt, gibt nur den Header aus und tut nichts.\n\n## Die Hilfe\n\n`total5` oder `total5 help` listet die Befehle auf:\n\n| Befehl | Was er bewirkt |\n| --- | --- |\n| `translate <filename>` | Erstellt eine Ressourcendatei aus den `@(...)`-Texten des aktuellen Verzeichnisses |\n| `minify <filename>` | Minifiziert eine `.js`-, `.css`- oder `.html`-Datei |\n| `bundle <filename>` | Packt das aktuelle Verzeichnis in eine `.bundle`-Datei |\n| `extract <filename>` | Entpackt ein Bundle in das aktuelle Verzeichnis |\n| `edit <url>` | Öffnet das aktuelle Verzeichnis zur entfernten Bearbeitung im Total.js Code Editor |\n| `proxy <endpoint> <port>` | Verbindet einen lokalen Port mit einem entfernten Total.js-Proxy-Server |\n| `test [names]` | Führt die Tests des aktuellen Verzeichnisses oder seines Verzeichnisses `tests` aus |\n| `<port>` | Startet einen Webserver für das aktuelle Verzeichnis |\n\n## Ein Webserver für ein Verzeichnis\n\nEine Zahl als Befehl startet einen statischen Webserver für das aktuelle Verzeichnis. `total5 server [port]` macht dasselbe, und der Port ist `8000`, wenn du ihn weglässt.\n\n```bash\ncd ~/projects/landing\ntotal5 8000\n# http://0.0.0.0:8000/\n```\n\n- Dateien werden aus dem aktuellen Verzeichnis ausgeliefert. Minifizierung und Source Maps sind aus, sodass du die Dateien genau so erhältst, wie sie auf der Festplatte liegen.\n- Die URL eines Verzeichnisses zeigt eine Auflistung seiner Unterverzeichnisse und Dateien mit ihren Größen. Klicke auf eine Datei (auch `index.html`), um sie zu öffnen.\n- Die Ordner der Anwendung (`controllers/`, `config`, …) werden nicht geladen: Es ist nur ein Dateiserver.\n\nStoppe ihn mit `Ctrl+C`.\n\n## Übersetzungen\n\n`total5 translate <filename>` liest jede `.js`- und `.html`-Datei des aktuellen Verzeichnisses und seiner Unterverzeichnisse, findet die mit `@(...)` markierten Texte und schreibt sie in die angegebene Ressourcendatei. Gib den vollständigen Pfad der Datei an:\n\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n```\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\nJeder Schlüssel ist `T` plus ein Hash des Textes, derselbe Schlüssel, den die View-Engine beim Nachschlagen einer Übersetzung verwendet. Kopiere die Datei unter einem Sprachnamen nach `resources/` und übersetze die Texte nach dem Doppelpunkt. Siehe [Lokalisierung](../../guides/localization/).\n\n## Eine Datei minifizieren\n\n`total5 minify <filename>` minifiziert eine Datei und schreibt das Ergebnis daneben, mit `.min` vor der Endung. Gib den vollständigen Pfad der Datei an:\n\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"     # public/js/app.min.js\ntotal5 minify \"$PWD/public/css/site.css\"  # public/css/site.min.css\ntotal5 minify \"$PWD/views/index.html\"     # views/index.min.html\n```\n\nDie Endung bestimmt den Minifier: JavaScript, CSS oder HTML. Der HTML-Minifier entfernt Kommentare, verkürzt Folgen von Leerzeichen im Markup und minifiziert eingebettete `<script>`- und `<style>`-Blöcke; Zeilenumbrüche und Einrückungen zwischen Tags bleiben erhalten. Eine Datei mit einer anderen Endung wird unverändert kopiert. Es sind dieselben Minifier, die das Framework für statische Dateien verwendet (siehe [Hilfsfunktionen](../../guides/utilities/)).\n\n## Bundles\n\nEin Bundle ist eine Datei, die eine ganze Anwendung enthält. Das Framework entpackt beim Start die `.bundle`-Dateien des Ordners `bundles/` (siehe [Anwendungsstruktur](../../guides/application-structure/)).\n\n`total5 bundle <filename>` packt das aktuelle Verzeichnis. Gib den vollständigen Pfad des Bundles an und lege es außerhalb des Verzeichnisses ab, das du packst:\n\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop     # ~/backups/shop.bundle\n```\n\n`.bundle` wird an den Namen angehängt, wenn es fehlt. Das Bundle lässt die Dateien weg, die zum Rechner gehören, nicht zur Anwendung: `index.js`, `debug.js`, `release.js` mit ihren `.json`- und `.pid`-Dateien, `bundle.json`, `package.json`, `readme.md`, `license.txt` und die Ordner `bundles/`, `tmp/`, `.src/` und `.git/`.\n\n`total5 extract <filename>` entpackt ein Bundle in das aktuelle Verzeichnis. Gib den vollständigen Pfad des Bundles an:\n\n```bash\nmkdir ~/projects/shop-copy && cd ~/projects/shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n## Entfernte Bearbeitung\n\n`total5 edit <url>` verbindet das aktuelle Verzeichnis mit dem **Total.js Code Editor**. Der Editor gibt dir die URL des Projekts; das Programm öffnet einen WebSocket dorthin (`http` wird zu `ws`, `https` zu `wss`) und beantwortet die Anfragen des Editors: Es listet, liest, speichert, erstellt, benennt um und entfernt Dateien, lädt sie hoch und herunter, liest Logdateien und führt Skripte aus.\n\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n# > Total.js Code Editor: Welcome to \"Code (1.0)\"\n# > Project: \"shop\"\n```\n\nBricht die Verbindung ab, wird sie alle 10 Sekunden neu aufgebaut. Das Programm läuft weiter, bis du es stoppst. Ohne URL bricht es mit dem Fehler `Invalid URL address` ab.\n\n## Proxy-Client\n\n`total5 proxy <endpoint> <port>` macht einen lokalen Port über einen entfernten Total.js-Proxy-Server erreichbar, eine Anwendung, die `PROXYSERVER()` aufruft. Das Programm verbindet sich per WebSocket mit dem Server und leitet jede empfangene Anfrage an den lokalen Port weiter:\n\n```bash\ntotal5 8000 &\ntotal5 proxy wss://proxy.example.com/ 8000\ntotal5 proxy wss://proxy.example.com/ 192.168.1.20:8000\n```\n\nDas zweite Argument ist ein Port auf `127.0.0.1` oder ein Paar `ip:port`. Jede Anfrage wird mit ihrer Methode, der IP-Adresse des Besuchers und der URL ausgegeben. Ohne beide Argumente gibt das Programm aus, wie es aufgerufen wird.\n\n## Tests ausführen\n\n`total5 test` führt die Testskripte des Verzeichnisses `tests` des aktuellen Verzeichnisses aus oder die des aktuellen Verzeichnisses, wenn es kein Verzeichnis `tests` hat. Es lädt zuerst die Datei `config` und `init.js` dieses Verzeichnisses, dann die Skripte, die du nennst, oder alle `.js`-Dateien, wenn du keine nennst:\n\n```bash\ncd ~/projects/shop\ntotal5 test\ntotal5 test strings orders\n```\n\nEs verwendet das im Projekt installierte Paket `total5`, auch wenn du es aus einem Unterverzeichnis ausführst. Eine fehlgeschlagene Prüfung beendet das Programm mit Exit-Code 1, sodass ein CI-Job fehlschlägt. Siehe [Unit-Tests](../../guides/unit-tests/).\n\n## Flows mit flow5 ausführen\n\n`flow5` lädt FlowStream-Schemas und führt sie mit einem kleinen HTTP-Server aus, ohne Anwendung (siehe [FlowStream](../../guides/flowstream/)):\n\n```bash\nflow5 \"$PWD/flowschema.json\"\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\nflow5 https://example.com/flowschema.json\n```\n\n- Jedes Argument, das eine Zahl ist, ist der Port (standardmäßig `8000`). Die anderen Argumente sind Dateien mit ihrem vollständigen Pfad oder `https://`-Adressen von Schemas.\n- Eine Datei enthält ein Schema (ein Objekt mit `components` und `design`) oder ein Objekt mit mehreren Schemas unter ihren ids.\n- Für jeden Flow gibt es einen Link aus, der den Flow im Flow-Editor auf `flow.totaljs.com` öffnet, verbunden mit deinem Rechner.\n- Wenn du einen Flow im Editor speicherst, schreibt das Programm ihn zurück in seine Datei. Gib jedem Schema eine `id` und verwende in einer Datei mit mehreren Flows die id als Schlüssel.\n\n```\n[Total.js v5 Flow Engine]\n|--- http://127.0.0.1:8000\n|--- Orders: https://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n\nDer Server hat zwei Routen: `GET` und `POST /notify/{id}/` für Benachrichtigungen an die Flows sowie den WebSocket `/flowstreams/{id}/` für den Editor. `flow5` ohne Argumente gibt seine Hilfe aus.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:33:35.963Z"}
{"id":"JafwUC9Wx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/command-line/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"es","title":"Línea de comandos (total5)","summary":"Los programas total5 y flow5: un servidor web estático, traducciones, minificación, bundles, edición remota, un cliente proxy, tests y la ejecución de flujos.","markdown":"---\ntitle: \"Línea de comandos (total5)\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/guides/command-line/\nupdated: 2026-11-16T16:33:35.963Z\n---\n\n# Línea de comandos (total5)\n\n> Los programas total5 y flow5: un servidor web estático, traducciones, minificación, bundles, edición remota, un cliente proxy, tests y la ejecución de flujos.\n\nEl paquete `total5` instala dos programas: **`total5`**, una caja de herramientas para el directorio en el que estás, y **`flow5`**, que ejecuta esquemas de FlowStream sin una aplicación. Instala el paquete de forma global para tener ambos en tu `PATH` (consulta [Instalación](../../guides/installation/)):\n\n```bash\nnpm install -g total5\n```\n\nCada comando de `total5` imprime una cabecera con su nombre, hace su trabajo y, para las tareas cortas, termina con una línea `[Done]` con el tiempo que tardó:\n\n```bash\n$ total5 minify /www/app/public/app.js\n* Total.js v5: [Minify]\n----------------------------------------\nFilename  : /www/app/public/app.js\nOutput    : /www/app/public/app.min.js\n----------------------------------------\n[Done]: 1.2ms\n```\n\n## Sintaxis de los comandos\n\n```bash\ntotal5 <command> [arguments]\n```\n\n- La primera palabra es el comando. Se eliminan dos o más guiones delante de ella, así que `total5 --help` es lo mismo que `total5 help`.\n- Las palabras siguientes son los argumentos, en orden. Se eliminan las comillas dobles que contengan y se recortan los espacios de los extremos.\n- Un número como comando (`total5 8000`) inicia el servidor web en ese puerto.\n- `total5` sin comando muestra la ayuda.\n- Una palabra que el programa no conoce imprime solo la cabecera y no hace nada.\n\n## La ayuda\n\n`total5` o `total5 help` lista los comandos:\n\n| Comando | Qué hace |\n| --- | --- |\n| `translate <filename>` | Crea un archivo de recursos a partir de los textos `@(...)` del directorio actual |\n| `minify <filename>` | Minifica un archivo `.js`, `.css` o `.html` |\n| `bundle <filename>` | Empaqueta el directorio actual en un archivo `.bundle` |\n| `extract <filename>` | Desempaqueta un bundle en el directorio actual |\n| `edit <url>` | Abre el directorio actual para edición remota en el Total.js Code Editor |\n| `proxy <endpoint> <port>` | Conecta un puerto local a un servidor proxy remoto de Total.js |\n| `test [names]` | Ejecuta los tests del directorio actual o de su directorio `tests` |\n| `<port>` | Inicia un servidor web para el directorio actual |\n\n## Un servidor web para un directorio\n\nUn número como comando inicia un servidor web estático para el directorio actual. `total5 server [port]` hace lo mismo, y el puerto es `8000` si lo omites.\n\n```bash\ncd ~/projects/landing\ntotal5 8000\n# http://0.0.0.0:8000/\n```\n\n- Los archivos se sirven desde el directorio actual. La minificación y los source maps están desactivados, así que obtienes los archivos exactamente como están en el disco.\n- La URL de un directorio muestra un listado de sus subdirectorios y archivos con sus tamaños. Haz clic en un archivo (también `index.html`) para abrirlo.\n- Las carpetas de la aplicación (`controllers/`, `config`, …) no se cargan: es solo un servidor de archivos.\n\nDetenlo con `Ctrl+C`.\n\n## Traducciones\n\n`total5 translate <filename>` lee cada archivo `.js` y `.html` del directorio actual y de sus subdirectorios, encuentra los textos marcados con `@(...)` y los escribe en el archivo de recursos que indiques. Indica la ruta completa del archivo:\n\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n```\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\nCada clave es `T` más un hash del texto, la misma clave que usa el motor de vistas cuando busca una traducción. Copia el archivo en `resources/` con el nombre de un idioma y traduce los textos que van después de los dos puntos. Consulta [Localización](../../guides/localization/).\n\n## Minificar un archivo\n\n`total5 minify <filename>` minifica un archivo y escribe el resultado a su lado con `.min` antes de la extensión. Indica la ruta completa del archivo:\n\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"     # public/js/app.min.js\ntotal5 minify \"$PWD/public/css/site.css\"  # public/css/site.min.css\ntotal5 minify \"$PWD/views/index.html\"     # views/index.min.html\n```\n\nLa extensión elige el minificador: JavaScript, CSS o HTML. El minificador de HTML elimina los comentarios, acorta las secuencias de espacios dentro del marcado y minifica los bloques `<script>` y `<style>` en línea; conserva los saltos de línea y la sangría entre etiquetas. Un archivo con otra extensión se copia sin cambios. Son los mismos minificadores que el framework usa para los archivos estáticos (consulta [Utilidades](../../guides/utilities/)).\n\n## Bundles\n\nUn bundle es un único archivo que contiene una aplicación entera. El framework desempaqueta los archivos `.bundle` de la carpeta `bundles/` al arrancar (consulta [Estructura de la aplicación](../../guides/application-structure/)).\n\n`total5 bundle <filename>` empaqueta el directorio actual. Indica la ruta completa del bundle y guárdalo fuera del directorio que empaquetas:\n\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop     # ~/backups/shop.bundle\n```\n\nSe añade `.bundle` al nombre si falta. El bundle excluye los archivos que pertenecen a la máquina, no a la aplicación: `index.js`, `debug.js`, `release.js` con sus archivos `.json` y `.pid`, `bundle.json`, `package.json`, `readme.md`, `license.txt` y las carpetas `bundles/`, `tmp/`, `.src/` y `.git/`.\n\n`total5 extract <filename>` desempaqueta un bundle en el directorio actual. Indica la ruta completa del bundle:\n\n```bash\nmkdir ~/projects/shop-copy && cd ~/projects/shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n## Edición remota\n\n`total5 edit <url>` conecta el directorio actual al **Total.js Code Editor**. El editor te da la URL del proyecto; el programa abre un WebSocket hacia ella (`http` pasa a `ws`, `https` pasa a `wss`) y responde a las peticiones del editor: lista, lee, guarda, crea, renombra y elimina archivos, los sube y los descarga, lee archivos de log y ejecuta scripts.\n\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n# > Total.js Code Editor: Welcome to \"Code (1.0)\"\n# > Project: \"shop\"\n```\n\nLa conexión se restablece cada 10 segundos cuando se cae. El programa sigue en ejecución hasta que lo detienes. Sin URL se detiene con el error `Invalid URL address`.\n\n## Cliente proxy\n\n`total5 proxy <endpoint> <port>` hace accesible un puerto local a través de un servidor proxy remoto de Total.js, una aplicación que llama a `PROXYSERVER()`. El programa se conecta al servidor con un WebSocket y reenvía al puerto local cada petición que recibe:\n\n```bash\ntotal5 8000 &\ntotal5 proxy wss://proxy.example.com/ 8000\ntotal5 proxy wss://proxy.example.com/ 192.168.1.20:8000\n```\n\nEl segundo argumento es un puerto en `127.0.0.1` o un par `ip:port`. Cada petición se imprime con su método, la dirección IP del visitante y la URL. Sin ambos argumentos el programa imprime cómo llamarlo.\n\n## Ejecutar tests\n\n`total5 test` ejecuta los scripts de test del directorio `tests` del directorio actual, o del directorio actual cuando no tiene directorio `tests`. Primero carga el archivo `config` y `init.js` de ese directorio, después los scripts que indiques, o todos los archivos `.js` cuando no indicas ninguno:\n\n```bash\ncd ~/projects/shop\ntotal5 test\ntotal5 test strings orders\n```\n\nUsa el paquete `total5` instalado en el proyecto, también cuando lo ejecutas desde un subdirectorio. Una comprobación fallida termina el programa con el código de salida 1, así que falla un job de CI. Consulta [Tests unitarios](../../guides/unit-tests/).\n\n## Ejecutar flujos con flow5\n\n`flow5` carga esquemas de FlowStream y los ejecuta con un pequeño servidor HTTP, sin una aplicación (consulta [FlowStream](../../guides/flowstream/)):\n\n```bash\nflow5 \"$PWD/flowschema.json\"\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\nflow5 https://example.com/flowschema.json\n```\n\n- Cada argumento que es un número es el puerto (`8000` por defecto). Los demás argumentos son archivos, con su ruta completa, o direcciones `https://` de esquemas.\n- Un archivo contiene un esquema (un objeto con `components` y `design`) o un objeto con varios esquemas bajo sus ids.\n- Para cada flujo imprime un enlace que abre el flujo en el editor Flow en `flow.totaljs.com`, conectado a tu máquina.\n- Cuando guardas un flujo en el editor, el programa lo escribe de vuelta en su archivo. Da a cada esquema un `id` y, en un archivo con varios flujos, usa el id como clave.\n\n```\n[Total.js v5 Flow Engine]\n|--- http://127.0.0.1:8000\n|--- Orders: https://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n\nEl servidor tiene dos rutas: `GET` y `POST /notify/{id}/` para las notificaciones a los flujos, y el WebSocket `/flowstreams/{id}/` para el editor. `flow5` sin argumentos imprime su ayuda.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:33:35.963Z"}
{"id":"JafwUC9Wx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/command-line/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"fr","title":"Ligne de commande (total5)","summary":"Les programmes total5 et flow5 : un serveur web statique, les traductions, la minification, les bundles, l'édition à distance, un client proxy, les tests et l'exécution de flux.","markdown":"---\ntitle: Ligne de commande (total5)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/guides/command-line/\nupdated: 2026-11-16T16:33:35.963Z\n---\n\n# Ligne de commande (total5)\n\n> Les programmes total5 et flow5 : un serveur web statique, les traductions, la minification, les bundles, l'édition à distance, un client proxy, les tests et l'exécution de flux.\n\nLe paquet `total5` installe deux programmes : **`total5`**, une boîte à outils pour le répertoire dans lequel tu te trouves, et **`flow5`**, qui exécute des schémas FlowStream sans application. Installe le paquet globalement pour avoir les deux dans ton `PATH` (voir [Installation](../../guides/installation/)) :\n\n```bash\nnpm install -g total5\n```\n\nChaque commande `total5` affiche un en-tête avec son nom, fait son travail et, pour les tâches courtes, se termine par une ligne `[Done]` avec la durée :\n\n```bash\n$ total5 minify /www/app/public/app.js\n* Total.js v5: [Minify]\n----------------------------------------\nFilename  : /www/app/public/app.js\nOutput    : /www/app/public/app.min.js\n----------------------------------------\n[Done]: 1.2ms\n```\n\n## Syntaxe des commandes\n\n```bash\ntotal5 <command> [arguments]\n```\n\n- Le premier mot est la commande. Deux tirets ou plus placés devant sont retirés : `total5 --help` équivaut donc à `total5 help`.\n- Les mots qui suivent sont les arguments, dans l'ordre. Les guillemets doubles qu'ils contiennent sont retirés et les espaces aux extrémités sont supprimés.\n- Un nombre comme commande (`total5 8000`) démarre le serveur web sur ce port.\n- `total5` sans commande affiche l'aide.\n- Un mot que le programme ne connaît pas n'affiche que l'en-tête et ne fait rien.\n\n## L'aide\n\n`total5` ou `total5 help` liste les commandes :\n\n| Commande | Ce qu'elle fait |\n| --- | --- |\n| `translate <filename>` | Crée un fichier de ressources à partir des textes `@(...)` du répertoire courant |\n| `minify <filename>` | Minifie un fichier `.js`, `.css` ou `.html` |\n| `bundle <filename>` | Regroupe le répertoire courant dans un fichier `.bundle` |\n| `extract <filename>` | Décompresse un bundle dans le répertoire courant |\n| `edit <url>` | Ouvre le répertoire courant pour l'édition à distance dans le Total.js Code Editor |\n| `proxy <endpoint> <port>` | Connecte un port local à un serveur proxy Total.js distant |\n| `test [names]` | Lance les tests du répertoire courant ou de son répertoire `tests` |\n| `<port>` | Démarre un serveur web pour le répertoire courant |\n\n## Un serveur web pour un répertoire\n\nUn nombre comme commande démarre un serveur web statique pour le répertoire courant. `total5 server [port]` fait de même, et le port est `8000` si tu l'omets.\n\n```bash\ncd ~/projects/landing\ntotal5 8000\n# http://0.0.0.0:8000/\n```\n\n- Les fichiers sont servis depuis le répertoire courant. La minification et les source maps sont désactivées : tu obtiens donc les fichiers exactement tels qu'ils sont sur le disque.\n- L'URL d'un répertoire affiche la liste de ses sous-répertoires et fichiers avec leurs tailles. Clique sur un fichier (`index.html` aussi) pour l'ouvrir.\n- Les dossiers de l'application (`controllers/`, `config`, …) ne sont pas chargés : c'est uniquement un serveur de fichiers.\n\nArrête-le avec `Ctrl+C`.\n\n## Traductions\n\n`total5 translate <filename>` lit chaque fichier `.js` et `.html` du répertoire courant et de ses sous-répertoires, trouve les textes marqués avec `@(...)` et les écrit dans le fichier de ressources que tu indiques. Indique le chemin complet du fichier :\n\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n```\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\nChaque clé est `T` suivi d'un hash du texte, la même clé que celle utilisée par le moteur de vues lorsqu'il cherche une traduction. Copie le fichier dans `resources/` sous un nom de langue et traduis les textes après les deux-points. Voir [Localisation](../../guides/localization/).\n\n## Minifier un fichier\n\n`total5 minify <filename>` minifie un fichier et écrit le résultat à côté de lui avec `.min` avant l'extension. Indique le chemin complet du fichier :\n\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"     # public/js/app.min.js\ntotal5 minify \"$PWD/public/css/site.css\"  # public/css/site.min.css\ntotal5 minify \"$PWD/views/index.html\"     # views/index.min.html\n```\n\nL'extension détermine le minificateur : JavaScript, CSS ou HTML. Le minificateur HTML retire les commentaires, réduit les suites d'espaces dans le balisage et minifie les blocs `<script>` et `<style>` inline ; il conserve les retours à la ligne et l'indentation entre les balises. Un fichier avec une autre extension est copié sans modification. Ce sont les mêmes minificateurs que ceux utilisés par le framework pour les fichiers statiques (voir [Utilitaires](../../guides/utilities/)).\n\n## Bundles\n\nUn bundle est un fichier unique qui contient toute une application. Le framework décompresse les fichiers `.bundle` du dossier `bundles/` au démarrage (voir [Structure de l'application](../../guides/application-structure/)).\n\n`total5 bundle <filename>` regroupe le répertoire courant. Indique le chemin complet du bundle et garde-le hors du répertoire que tu regroupes :\n\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop     # ~/backups/shop.bundle\n```\n\n`.bundle` est ajouté au nom s'il manque. Le bundle exclut les fichiers qui appartiennent à la machine et non à l'application : `index.js`, `debug.js`, `release.js` avec leurs fichiers `.json` et `.pid`, `bundle.json`, `package.json`, `readme.md`, `license.txt` et les dossiers `bundles/`, `tmp/`, `.src/` et `.git/`.\n\n`total5 extract <filename>` décompresse un bundle dans le répertoire courant. Indique le chemin complet du bundle :\n\n```bash\nmkdir ~/projects/shop-copy && cd ~/projects/shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n## Édition à distance\n\n`total5 edit <url>` connecte le répertoire courant au **Total.js Code Editor**. L'éditeur te donne l'URL du projet ; le programme ouvre un WebSocket vers celle-ci (`http` devient `ws`, `https` devient `wss`) et répond aux requêtes de l'éditeur : il liste, lit, enregistre, crée, renomme et supprime des fichiers, les envoie et les télécharge, lit les fichiers de log et exécute des scripts.\n\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n# > Total.js Code Editor: Welcome to \"Code (1.0)\"\n# > Project: \"shop\"\n```\n\nLa connexion se rétablit toutes les 10 secondes lorsqu'elle tombe. Le programme continue de tourner jusqu'à ce que tu l'arrêtes. Sans URL, il s'arrête avec l'erreur `Invalid URL address`.\n\n## Client proxy\n\n`total5 proxy <endpoint> <port>` rend un port local accessible via un serveur proxy Total.js distant, une application qui appelle `PROXYSERVER()`. Le programme se connecte au serveur par un WebSocket et transmet chaque requête reçue au port local :\n\n```bash\ntotal5 8000 &\ntotal5 proxy wss://proxy.example.com/ 8000\ntotal5 proxy wss://proxy.example.com/ 192.168.1.20:8000\n```\n\nLe second argument est un port sur `127.0.0.1` ou une paire `ip:port`. Chaque requête est affichée avec sa méthode, l'adresse IP du visiteur et l'URL. Sans les deux arguments, le programme affiche comment l'appeler.\n\n## Lancer les tests\n\n`total5 test` lance les scripts de test du répertoire `tests` du répertoire courant, ou du répertoire courant quand il n'a pas de répertoire `tests`. Il charge d'abord le fichier `config` et `init.js` de ce répertoire, puis les scripts que tu nommes, ou tous les fichiers `.js` quand tu n'en nommes aucun :\n\n```bash\ncd ~/projects/shop\ntotal5 test\ntotal5 test strings orders\n```\n\nIl utilise le paquet `total5` installé dans le projet, même quand tu le lances depuis un sous-répertoire. Une vérification qui échoue termine le programme avec le code de sortie 1, donc un job de CI échoue. Voir [Tests unitaires](../../guides/unit-tests/).\n\n## Exécuter des flux avec flow5\n\n`flow5` charge des schémas FlowStream et les exécute avec un petit serveur HTTP, sans application (voir [FlowStream](../../guides/flowstream/)) :\n\n```bash\nflow5 \"$PWD/flowschema.json\"\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\nflow5 https://example.com/flowschema.json\n```\n\n- Chaque argument qui est un nombre est le port (`8000` par défaut). Les autres arguments sont des fichiers, avec leur chemin complet, ou des adresses `https://` de schémas.\n- Un fichier contient un schéma (un objet avec `components` et `design`) ou un objet de plusieurs schémas sous leurs ids.\n- Pour chaque flux, il affiche un lien qui ouvre le flux dans l'éditeur Flow sur `flow.totaljs.com`, connecté à ta machine.\n- Quand tu enregistres un flux dans l'éditeur, le programme le réécrit dans son fichier. Donne un `id` à chaque schéma et, dans un fichier contenant plusieurs flux, utilise l'id comme clé.\n\n```\n[Total.js v5 Flow Engine]\n|--- http://127.0.0.1:8000\n|--- Orders: https://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n\nLe serveur a deux routes : `GET` et `POST /notify/{id}/` pour les notifications aux flux, et le WebSocket `/flowstreams/{id}/` pour l'éditeur. `flow5` sans arguments affiche son aide.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:33:35.963Z"}
{"id":"JafwUC9Wx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/command-line/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"it","title":"Riga di comando (total5)","summary":"I programmi total5 e flow5: un web server statico, traduzioni, minificazione, bundle, modifica remota, un client proxy, test ed esecuzione di flussi.","markdown":"---\ntitle: Riga di comando (total5)\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/guides/command-line/\nupdated: 2026-11-16T16:33:35.963Z\n---\n\n# Riga di comando (total5)\n\n> I programmi total5 e flow5: un web server statico, traduzioni, minificazione, bundle, modifica remota, un client proxy, test ed esecuzione di flussi.\n\nIl pacchetto `total5` installa due programmi: **`total5`**, una cassetta degli attrezzi per la directory in cui ti trovi, e **`flow5`**, che esegue schemi FlowStream senza un'applicazione. Installa il pacchetto globalmente per averli entrambi nel tuo `PATH` (vedi [Installazione](../../guides/installation/)):\n\n```bash\nnpm install -g total5\n```\n\nOgni comando `total5` stampa un'intestazione con il suo nome, esegue il proprio lavoro e, per le operazioni brevi, termina con una riga `[Done]` con il tempo impiegato:\n\n```bash\n$ total5 minify /www/app/public/app.js\n* Total.js v5: [Minify]\n----------------------------------------\nFilename  : /www/app/public/app.js\nOutput    : /www/app/public/app.min.js\n----------------------------------------\n[Done]: 1.2ms\n```\n\n## Sintassi dei comandi\n\n```bash\ntotal5 <command> [arguments]\n```\n\n- La prima parola è il comando. Due o più trattini davanti vengono rimossi, quindi `total5 --help` equivale a `total5 help`.\n- Le parole successive sono gli argomenti, in ordine. Le virgolette doppie al loro interno vengono rimosse e gli spazi alle estremità vengono eliminati.\n- Un numero come comando (`total5 8000`) avvia il web server su quella porta.\n- `total5` senza comando mostra l'aiuto.\n- Una parola che il programma non conosce stampa solo l'intestazione e non fa nulla.\n\n## L'aiuto\n\n`total5` o `total5 help` elenca i comandi:\n\n| Comando | Cosa fa |\n| --- | --- |\n| `translate <filename>` | Crea un file di risorse dai testi `@(...)` della directory corrente |\n| `minify <filename>` | Minifica un file `.js`, `.css` o `.html` |\n| `bundle <filename>` | Impacchetta la directory corrente in un file `.bundle` |\n| `extract <filename>` | Estrae un bundle nella directory corrente |\n| `edit <url>` | Apre la directory corrente per la modifica remota nel Total.js Code Editor |\n| `proxy <endpoint> <port>` | Collega una porta locale a un proxy server Total.js remoto |\n| `test [names]` | Esegue i test della directory corrente o della sua directory `tests` |\n| `<port>` | Avvia un web server per la directory corrente |\n\n## Un web server per una directory\n\nUn numero come comando avvia un web server statico per la directory corrente. `total5 server [port]` fa lo stesso, e la porta è `8000` se la ometti.\n\n```bash\ncd ~/projects/landing\ntotal5 8000\n# http://0.0.0.0:8000/\n```\n\n- I file vengono serviti dalla directory corrente. Minificazione e source map sono disattivate, quindi ottieni i file esattamente come sono sul disco.\n- L'URL di una directory mostra un elenco delle sue sottodirectory e dei suoi file con le relative dimensioni. Fai clic su un file (anche `index.html`) per aprirlo.\n- Le cartelle dell'applicazione (`controllers/`, `config`, …) non vengono caricate: è solo un file server.\n\nFermalo con `Ctrl+C`.\n\n## Traduzioni\n\n`total5 translate <filename>` legge ogni file `.js` e `.html` della directory corrente e delle sue sottodirectory, trova i testi contrassegnati con `@(...)` e li scrive nel file di risorse che indichi. Indica il percorso completo del file:\n\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n```\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\nOgni chiave è `T` più un hash del testo, la stessa chiave che il motore delle viste usa quando cerca una traduzione. Copia il file in `resources/` con il nome di una lingua e traduci i testi dopo i due punti. Vedi [Localizzazione](../../guides/localization/).\n\n## Minificare un file\n\n`total5 minify <filename>` minifica un file e scrive il risultato accanto a esso con `.min` prima dell'estensione. Indica il percorso completo del file:\n\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"     # public/js/app.min.js\ntotal5 minify \"$PWD/public/css/site.css\"  # public/css/site.min.css\ntotal5 minify \"$PWD/views/index.html\"     # views/index.min.html\n```\n\nL'estensione determina il minificatore: JavaScript, CSS o HTML. Il minificatore HTML rimuove i commenti, riduce le sequenze di spazi all'interno del markup e minifica i blocchi `<script>` e `<style>` inline; mantiene le interruzioni di riga e l'indentazione tra i tag. Un file con un'altra estensione viene copiato senza modifiche. Sono gli stessi minificatori che il framework usa per i file statici (vedi [Utilità](../../guides/utilities/)).\n\n## Bundle\n\nUn bundle è un unico file che contiene un'intera applicazione. Il framework estrae i file `.bundle` della cartella `bundles/` all'avvio (vedi [Struttura dell'applicazione](../../guides/application-structure/)).\n\n`total5 bundle <filename>` impacchetta la directory corrente. Indica il percorso completo del bundle e tienilo fuori dalla directory che impacchetti:\n\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop     # ~/backups/shop.bundle\n```\n\n`.bundle` viene aggiunto al nome se manca. Il bundle esclude i file che appartengono alla macchina, non all'applicazione: `index.js`, `debug.js`, `release.js` con i loro file `.json` e `.pid`, `bundle.json`, `package.json`, `readme.md`, `license.txt` e le cartelle `bundles/`, `tmp/`, `.src/` e `.git/`.\n\n`total5 extract <filename>` estrae un bundle nella directory corrente. Indica il percorso completo del bundle:\n\n```bash\nmkdir ~/projects/shop-copy && cd ~/projects/shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n## Modifica remota\n\n`total5 edit <url>` collega la directory corrente al **Total.js Code Editor**. L'editor ti fornisce l'URL del progetto; il programma apre un WebSocket verso di esso (`http` diventa `ws`, `https` diventa `wss`) e risponde alle richieste dell'editor: elenca, legge, salva, crea, rinomina e rimuove file, li carica e li scarica, legge i file di log ed esegue script.\n\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n# > Total.js Code Editor: Welcome to \"Code (1.0)\"\n# > Project: \"shop\"\n```\n\nQuando la connessione cade, si riconnette ogni 10 secondi. Il programma resta in esecuzione finché non lo fermi. Senza un URL si ferma con l'errore `Invalid URL address`.\n\n## Client proxy\n\n`total5 proxy <endpoint> <port>` rende una porta locale raggiungibile tramite un proxy server Total.js remoto, un'applicazione che chiama `PROXYSERVER()`. Il programma si collega al server con un WebSocket e inoltra alla porta locale ogni richiesta che riceve:\n\n```bash\ntotal5 8000 &\ntotal5 proxy wss://proxy.example.com/ 8000\ntotal5 proxy wss://proxy.example.com/ 192.168.1.20:8000\n```\n\nIl secondo argomento è una porta su `127.0.0.1` o una coppia `ip:port`. Ogni richiesta viene stampata con il suo metodo, l'indirizzo IP del visitatore e l'URL. Senza entrambi gli argomenti il programma stampa come chiamarlo.\n\n## Eseguire i test\n\n`total5 test` esegue gli script di test della directory `tests` della directory corrente, oppure della directory corrente quando non ha una directory `tests`. Prima carica il file `config` e `init.js` di quella directory, poi gli script che indichi, oppure tutti i file `.js` quando non ne indichi nessuno:\n\n```bash\ncd ~/projects/shop\ntotal5 test\ntotal5 test strings orders\n```\n\nUsa il pacchetto `total5` installato nel progetto, anche quando lo esegui da una sottodirectory. Un controllo fallito termina il programma con exit code 1, così un job di CI fallisce. Vedi [Test unitari](../../guides/unit-tests/).\n\n## Eseguire flussi con flow5\n\n`flow5` carica schemi FlowStream e li esegue con un piccolo server HTTP, senza un'applicazione (vedi [FlowStream](../../guides/flowstream/)):\n\n```bash\nflow5 \"$PWD/flowschema.json\"\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\nflow5 https://example.com/flowschema.json\n```\n\n- Ogni argomento numerico è la porta (`8000` per impostazione predefinita). Gli altri argomenti sono file, con il loro percorso completo, o indirizzi `https://` di schemi.\n- Un file contiene uno schema (un oggetto con `components` e `design`) oppure un oggetto con più schemi sotto i rispettivi id.\n- Per ogni flusso stampa un link che apre il flusso nell'editor Flow su `flow.totaljs.com`, collegato alla tua macchina.\n- Quando salvi un flusso nell'editor, il programma lo riscrive nel suo file. Dai a ogni schema un `id` e, in un file con più flussi, usa l'id come chiave.\n\n```\n[Total.js v5 Flow Engine]\n|--- http://127.0.0.1:8000\n|--- Orders: https://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n\nIl server ha due route: `GET` e `POST /notify/{id}/` per le notifiche ai flussi, e il WebSocket `/flowstreams/{id}/` per l'editor. `flow5` senza argomenti stampa il suo aiuto.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:33:35.963Z"}
{"id":"JafwUC9Wx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/command-line/","project":"total-js-v5","version":"0-0-20","section":"guides","language":"sk","title":"Príkazový riadok (total5)","summary":"Programy total5 a flow5: statický webový server, preklady, minifikácia, bundly, vzdialené úpravy, proxy klient, testy a spúšťanie flowov.","markdown":"---\ntitle: \"Príkazový riadok (total5)\"\nproject: Total.js V5\nversion: 0.0.20\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/guides/command-line/\nupdated: 2026-11-16T16:33:35.963Z\n---\n\n# Príkazový riadok (total5)\n\n> Programy total5 a flow5: statický webový server, preklady, minifikácia, bundly, vzdialené úpravy, proxy klient, testy a spúšťanie flowov.\n\nBalík `total5` inštaluje dva programy: **`total5`**, súpravu nástrojov pre adresár, v ktorom si, a **`flow5`**, ktorý spúšťa schémy FlowStream bez aplikácie. Nainštaluj balík globálne, aby si mal oba vo svojom `PATH` (pozri [Inštalácia](../../guides/installation/)):\n\n```bash\nnpm install -g total5\n```\n\nKaždý príkaz `total5` vypíše hlavičku so svojím názvom, urobí svoju prácu a pri krátkych úlohách skončí riadkom `[Done]` s časom, ktorý trvala:\n\n```bash\n$ total5 minify /www/app/public/app.js\n* Total.js v5: [Minify]\n----------------------------------------\nFilename  : /www/app/public/app.js\nOutput    : /www/app/public/app.min.js\n----------------------------------------\n[Done]: 1.2ms\n```\n\n## Syntax príkazov\n\n```bash\ntotal5 <command> [arguments]\n```\n\n- Prvé slovo je príkaz. Dve alebo viac pomlčiek pred ním sa odstránia, takže `total5 --help` je to isté ako `total5 help`.\n- Slová za ním sú argumenty v poradí. Dvojité úvodzovky v nich sa odstránia a medzery na koncoch sa orežú.\n- Číslo ako príkaz (`total5 8000`) spustí webový server na tomto porte.\n- `total5` bez príkazu zobrazí pomoc.\n- Slovo, ktoré program nepozná, vypíše iba hlavičku a nič neurobí.\n\n## Pomoc\n\n`total5` alebo `total5 help` vypíše zoznam príkazov:\n\n| Príkaz | Čo robí |\n| --- | --- |\n| `translate <filename>` | Vytvorí súbor zdrojov z textov `@(...)` aktuálneho adresára |\n| `minify <filename>` | Minifikuje súbor `.js`, `.css` alebo `.html` |\n| `bundle <filename>` | Zabalí aktuálny adresár do súboru `.bundle` |\n| `extract <filename>` | Rozbalí bundle do aktuálneho adresára |\n| `edit <url>` | Otvorí aktuálny adresár na vzdialené úpravy v Total.js Code Editore |\n| `proxy <endpoint> <port>` | Pripojí lokálny port k vzdialenému proxy serveru Total.js |\n| `test [names]` | Spustí testy aktuálneho adresára alebo jeho adresára `tests` |\n| `<port>` | Spustí webový server pre aktuálny adresár |\n\n## Webový server pre adresár\n\nČíslo ako príkaz spustí statický webový server pre aktuálny adresár. `total5 server [port]` robí to isté a port je `8000`, keď ho vynecháš.\n\n```bash\ncd ~/projects/landing\ntotal5 8000\n# http://0.0.0.0:8000/\n```\n\n- Súbory sa obsluhujú z aktuálneho adresára. Minifikácia a source mapy sú vypnuté, takže dostaneš súbory presne tak, ako sú na disku.\n- URL adresára zobrazí výpis jeho podadresárov a súborov s ich veľkosťami. Kliknutím na súbor (aj `index.html`) ho otvoríš.\n- Priečinky aplikácie (`controllers/`, `config`, …) sa nenačítajú: je to iba súborový server.\n\nZastavíš ho cez `Ctrl+C`.\n\n## Preklady\n\n`total5 translate <filename>` prečíta každý súbor `.js` a `.html` aktuálneho adresára a jeho podadresárov, nájde texty označené `@(...)` a zapíše ich do súboru zdrojov, ktorý zadáš. Zadaj úplnú cestu k súboru:\n\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n```\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\nKaždý kľúč je `T` plus hash textu, ten istý kľúč, ktorý používa view engine pri hľadaní prekladu. Skopíruj súbor do `resources/` pod názvom jazyka a prelož texty za dvojbodkou. Pozri [Lokalizácia](../../guides/localization/).\n\n## Minifikácia súboru\n\n`total5 minify <filename>` minifikuje jeden súbor a výsledok zapíše vedľa neho s `.min` pred príponou. Zadaj úplnú cestu k súboru:\n\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"     # public/js/app.min.js\ntotal5 minify \"$PWD/public/css/site.css\"  # public/css/site.min.css\ntotal5 minify \"$PWD/views/index.html\"     # views/index.min.html\n```\n\nPrípona určí minifikátor: JavaScript, CSS alebo HTML. HTML minifikátor odstráni komentáre, skráti viacnásobné medzery v markupe a minifikuje inline bloky `<script>` a `<style>`; zalomenia riadkov a odsadenie medzi tagmi zachová. Súbor s inou príponou sa skopíruje bez zmeny. Sú to tie isté minifikátory, ktoré framework používa pre statické súbory (pozri [Utility](../../guides/utilities/)).\n\n## Bundly\n\nBundle je jeden súbor, ktorý obsahuje celú aplikáciu. Framework pri štarte rozbalí súbory `.bundle` z priečinka `bundles/` (pozri [Štruktúra aplikácie](../../guides/application-structure/)).\n\n`total5 bundle <filename>` zabalí aktuálny adresár. Zadaj úplnú cestu k bundlu a drž ho mimo adresára, ktorý balíš:\n\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop     # ~/backups/shop.bundle\n```\n\n`.bundle` sa k názvu doplní, keď chýba. Bundle vynechá súbory, ktoré patria stroju, nie aplikácii: `index.js`, `debug.js`, `release.js` s ich súbormi `.json` a `.pid`, `bundle.json`, `package.json`, `readme.md`, `license.txt` a priečinky `bundles/`, `tmp/`, `.src/` a `.git/`.\n\n`total5 extract <filename>` rozbalí bundle do aktuálneho adresára. Zadaj úplnú cestu k bundlu:\n\n```bash\nmkdir ~/projects/shop-copy && cd ~/projects/shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n## Vzdialené úpravy\n\n`total5 edit <url>` pripojí aktuálny adresár k **Total.js Code Editoru**. Editor ti dá URL projektu; program k nej otvorí WebSocket (`http` sa zmení na `ws`, `https` na `wss`) a odpovedá na požiadavky editora: vypisuje, číta, ukladá, vytvára, premenúva a odstraňuje súbory, nahráva a sťahuje ich, číta log súbory a spúšťa skripty.\n\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n# > Total.js Code Editor: Welcome to \"Code (1.0)\"\n# > Project: \"shop\"\n```\n\nPri výpadku sa spojenie obnovuje každých 10 sekúnd. Program beží, kým ho nezastavíš. Bez URL skončí s chybou `Invalid URL address`.\n\n## Proxy klient\n\n`total5 proxy <endpoint> <port>` sprístupní lokálny port cez vzdialený proxy server Total.js, aplikáciu, ktorá volá `PROXYSERVER()`. Program sa k serveru pripojí cez WebSocket a každú prijatú požiadavku prepošle na lokálny port:\n\n```bash\ntotal5 8000 &\ntotal5 proxy wss://proxy.example.com/ 8000\ntotal5 proxy wss://proxy.example.com/ 192.168.1.20:8000\n```\n\nDruhý argument je port na `127.0.0.1` alebo dvojica `ip:port`. Každá požiadavka sa vypíše s metódou, IP adresou návštevníka a URL. Bez oboch argumentov program vypíše, ako ho zavolať.\n\n## Spúšťanie testov\n\n`total5 test` spustí testovacie skripty adresára `tests` aktuálneho adresára, alebo aktuálneho adresára, keď nemá adresár `tests`. Najprv načíta súbor `config` a `init.js` tohto adresára, potom skripty, ktoré pomenuješ, alebo všetky súbory `.js`, keď nepomenuješ žiadny:\n\n```bash\ncd ~/projects/shop\ntotal5 test\ntotal5 test strings orders\n```\n\nPoužíva balík `total5` nainštalovaný v projekte, aj keď ho spustíš z podadresára. Neúspešná kontrola ukončí program s exit kódom 1, takže CI job zlyhá. Pozri [Unit testy](../../guides/unit-tests/).\n\n## Spúšťanie flowov cez flow5\n\n`flow5` načíta schémy FlowStream a spustí ich s malým HTTP serverom, bez aplikácie (pozri [FlowStream](../../guides/flowstream/)):\n\n```bash\nflow5 \"$PWD/flowschema.json\"\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\nflow5 https://example.com/flowschema.json\n```\n\n- Každý argument, ktorý je číslo, je port (predvolene `8000`). Ostatné argumenty sú súbory s úplnou cestou alebo adresy schém `https://`.\n- Súbor obsahuje jednu schému (objekt s `components` a `design`) alebo objekt viacerých schém pod ich id.\n- Pre každý flow vypíše odkaz, ktorý otvorí flow v editore Flow na `flow.totaljs.com` pripojený k tvojmu počítaču.\n- Keď flow v editore uložíš, program ho zapíše späť do jeho súboru. Daj každej schéme `id` a v súbore s viacerými flowmi použi id ako kľúč.\n\n```\n[Total.js v5 Flow Engine]\n|--- http://127.0.0.1:8000\n|--- Orders: https://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n\nServer má dve routy: `GET` a `POST /notify/{id}/` pre notifikácie flowom a WebSocket `/flowstreams/{id}/` pre editor. `flow5` bez argumentov vypíše svoju pomoc.\n","entries":[],"license":"MIT","updated":"2026-11-16T16:33:35.963Z"}
{"id":"JaedEABfT60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/routing/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Routing","summary":"ROUTE() syntax, flags, the route object, CORS(), PROXY() and the routing configuration.","markdown":"---\ntitle: Routing\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/routing/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Routing\n\n> ROUTE() syntax, flags, the route object, CORS(), PROXY() and the routing configuration.\n\nEvery part of the `ROUTE()` string (method prefixes, parameters, flags, actions and API endpoints), the route object, `CORS()`, `PROXY()` and the configuration keys of routing. The guide [Routing](../../guides/routing/) explains them with examples; this page is the exact reference.\n\n## API\n\n### ROUTE(url, [action], [size])\n\nType: `method`\n\nDeclares a route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The method, the path and the flags, for example `+POST /api/orders/ @json <1MB`. |\n| `action` | `Function|String` | no |  | A function called with the controller, or the name of a view. Without it, a view named after the first path segment is rendered (`index` for `/`). |\n| `size` | `Number` | no | `CONF.$httpmaxsize` | The maximum body size in bytes. It can be the second argument when there is no action. |\n\nReturns: `Route` The route object.\n\n`url` is one string: the method (with an optional `+` or `-` prefix), the path and optional flags, actions after `-->` and API endpoints after `?`. The routes are sorted 100 ms after the last `ROUTE()` call. A path that starts with `#` declares an error route. The global `ROUTE` is the same function as `F.route`.\n\nExample: A page and a JSON endpoint\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n\nfunction index($) {\n\t$.view('index');\n}\n```\n\nExample: A view without code\n```js\nexports.install = function() {\n\tROUTE('GET /contact/', 'contact');\n\tROUTE('GET /about/');\n};\n```\n\n### ROUTE('+METHOD /path/', action)\n\nType: `type`\n\nThe route is only for signed-in users.\n\nThe `AUTH()` delegate must return a user; without `AUTH()` the prefix is not checked and the route serves everybody. When the user is not signed in and no other route of the URL accepts visitors, the answer is `401`. The user is in `$.user`.\n\nExample: An account page\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', function($) {\n\t\t$.json($.user);\n\t});\n};\n```\n\n### ROUTE('-METHOD /path/', action)\n\nType: `type`\n\nThe route is only for visitors who are not signed in.\n\nUse it with a `+` route of the same URL to show different content to signed-in users and to visitors. A signed-in user who reaches only a `-` route gets `401`.\n\nExample: Login or account\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n};\n```\n\n### ROUTE('GET /path/{name}/', action)\n\nType: `type`\n\nA dynamic segment of the path.\n\nThe value of the segment is stored in `$.params` under its name, as a string with the case of the request URL. A parameter takes a whole segment. A route with parameters matches only URLs with the same number of segments.\n\nExample: Two parameters\n```js\nexports.install = function() {\n\tROUTE('GET /blog/{year}/{slug}/', function($) {\n\t\t$.json({ year: $.params.year, slug: $.params.slug });\n\t});\n};\n```\n\n### ROUTE('GET /path/*', action)\n\nType: `type`\n\nMatches the path and everything below it.\n\nA wildcard route has a lower priority than fixed and dynamic routes, so it catches only the URLs that no other route takes.\n\nExample: A catch-all for a section\n```js\nexports.install = function() {\n\tROUTE('GET /app/*', 'app');\n};\n```\n\n### ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])\n\nType: `type`\n\nDeclares one endpoint of the API route.\n\nThe `?` is replaced with `CONF.$api` (default `/api/`, without `CONF.$root` added again). All endpoints share one `POST` route. The request body is `{ schema: \"endpoint/param?query\", data: {...} }`: `$.params` is filled from the path parts of `schema`, `$.query` from the part after `?`, and `data` becomes the body. `+API` and `-API` check the user for each endpoint. A missing parameter is an error for `params.<name>`; an unknown endpoint, or a body without `schema`, gets `400`. The timeout flag applies to the endpoint and the largest size flag to the shared route.\n\nExample: Endpoints\n```js\nexports.install = function() {\n\tROUTE('API ? tasks_list --> Tasks/list');\n\tROUTE('+API ? tasks_read/{id} --> Tasks/read');\n\tROUTE('+API ? tasks_save <5MB --> Tasks/save');\n};\n```\n\nExample: A function instead of actions\n```js\nexports.install = function() {\n\tROUTE('API ? ping', function($) {\n\t\t$.success();\n\t});\n};\n```\n\nExample: Client\n```js\nAJAX('POST /api/', { schema: 'tasks_read/42', data: null }, function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')\n\nType: `type`\n\nRuns actions instead of a function.\n\nThe names after `-->` are actions declared with `NEWACTION()`, separated by spaces or commas. The request body is the payload, and `$.params`, `$.query` and `$.user` are passed on. The result is sent as the response and an error with `$.invalid()`. With several actions, mark the one whose result is the response with `(response)`; a single action is the response.\n\nExample: One action\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/ --> Users/list');\n};\n```\n\nExample: Insert and read back\n```js\nexports.install = function() {\n\tROUTE('+POST /api/users/ --> Users/insert Users/read (response)');\n};\n```\n\n### ROUTE('METHOD /path/ <10MB', action)\n\nType: `type`\n\nSets the maximum size of the request body.\n\nUnits: `b` (bytes), `kB` (kilobytes, 1024 bytes), `MB` (megabytes) and `GB` (gigabytes); the unit is required. A larger body is answered with `431`. Without the flag the limit is `CONF.$httpmaxsize` kB (`CONF.$wsmaxsize` kB for `SOCKET` routes).\n\nExample: Uploads up to 50 MB\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <50MB', upload);\n};\n```\n\n### ROUTE('METHOD /path/ <30s', action)\n\nType: `type`\n\nSets the timeout of the request.\n\nUnits: `s` (seconds), `m` (minutes) and `h` (hours). When the action does not answer in time, the request ends with `503`. Without the flag the timeout is `CONF.$httptimeout` seconds. The timeout is checked every 5 seconds.\n\nExample: A long export\n```js\nexports.install = function() {\n\tROUTE('GET /export/ <10m', exportdata);\n};\n```\n\n### ROUTE('METHOD /path/ #name', action)\n\nType: `type`\n\nRuns a middleware before the action.\n\nThe name must be registered with `MIDDLEWARE(name, fn)`. Several `#names` run in the order written; an unknown name is skipped. Middleware names contain letters, digits and `_`.\n\nExample: Two middleware\n```js\nMIDDLEWARE('cors_api', function($, next) {\n\t$.response.headers['x-api'] = '1';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/stats/ #cors_api #nocache', stats);\n};\n```\n\n### ROUTE('METHOD /path/ @json', action)\n\nType: `type`\n\nThe route matches only when the request body is JSON (`application/json` or `text/json`).\n\nIf the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.\n\nExample: Usage\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/ @json', orders);\n};\n```\n\n### ROUTE('METHOD /path/ @xml', action)\n\nType: `type`\n\nThe route matches only when the request body is XML (`application/xml` or `text/xml`).\n\nIf the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.\n\nExample: Usage\n```js\nexports.install = function() {\n\tROUTE('POST /feed/ @xml', feed);\n};\n```\n\n### ROUTE('METHOD /path/ @upload', action)\n\nType: `type`\n\nThe route matches only when the request body is `multipart/form-data`.\n\nIf the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.\n\nExample: Usage\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', function($) {\n\t\t$.json($.files.map(f => f.filename));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @xhr', action)\n\nType: `type`\n\nThe route matches only when the request has the header `X-Requested-With: XMLHttpRequest`.\n\nIf the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.\n\nExample: Usage\n```js\nexports.install = function() {\n\tROUTE('GET /partials/menu/ @xhr', 'partials/menu');\n};\n```\n\n### ROUTE('METHOD /path/ @mobile', action)\n\nType: `type`\n\nThe route matches only when the client is a mobile device.\n\nIf the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.\n\nExample: Usage\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /m/ @mobile', 'mobile');\n};\n```\n\n### ROUTE('METHOD /path/ @robot', action)\n\nType: `type`\n\nThe route matches only when the client is a crawler.\n\nIf the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.\n\nExample: Usage\n```js\nexports.install = function() {\n\tROUTE('GET /prerender/ @robot', 'static');\n};\n```\n\n### ROUTE('METHOD /path/ @referrer', action)\n\nType: `type`\n\nThe route matches only when the `Referer` header contains the host of the request; `@referer` is the same flag.\n\nIf the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.\n\nExample: Usage\n```js\nexports.install = function() {\n\tROUTE('GET /download/ @referrer', download);\n};\n```\n\n### ROUTE('METHOD /path/ @debug', action)\n\nType: `type`\n\nThe route matches only when the application runs in debug mode.\n\nIf the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.\n\nExample: Usage\n```js\nexports.install = function() {\n\tROUTE('GET /dev/routes/ @debug', function($) {\n\t\t$.json(F.routes.routes.map(r => r.method + ' ' + r.url2));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @release', action)\n\nType: `type`\n\nThe route matches only when the application runs in release mode.\n\nIf the request does not meet the condition, the router tries the next route with the same method and path. Each flag lowers the priority of the route by one, so a route with fewer flags is checked first.\n\nExample: Usage\n```js\nexports.install = function() {\n\tROUTE('GET /status/ @release', status);\n};\n```\n\n### ROUTE('FILE /path/pattern', action)\n\nType: `type`\n\nHandles requests for static files with your code.\n\nFile routes are checked for URLs with an extension. Patterns: a fixed file (`/robots.txt`), extensions in a folder (`/docs/*.md|txt`), every file in a folder (`/downloads/*`) and an extension anywhere (`*.webp`). The action receives the controller; answer with `$.file()`, `$.image()`, `$.plain()` or `$.resume()` (serves the file from `/public/`). A request that no route takes is served from `/public/` when its extension is in `CONF.$httpfiles`, or gets `404`.\n\nExample: Generated robots.txt\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', function($) {\n\t\t$.plain('User-agent: *\\nDisallow: /admin/');\n\t});\n};\n```\n\nExample: Files from a private folder\n```js\nexports.install = function() {\n\tROUTE('FILE /files/*.pdf|docx', function($) {\n\t\t$.file(PATH.databases($.split[1]), true);\n\t});\n};\n```\n\n### ROUTE('SOCKET /path/ [flags]', action)\n\nType: `type`\n\nDeclares a WebSocket endpoint.\n\n`WEBSOCKET` is the same method. The path, `+`/`-`, `{params}`, `#middleware` and the size flag work as in HTTP routes; the default message size is `CONF.$wsmaxsize` kB. See [WebSockets](../../guides/websockets/).\n\nExample: Chat\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /chat/{room}/ <1MB', chat);\n};\n```\n\n### ROUTE('#code', action)\n\nType: `type`\n\nReplaces the default error page for a status code.\n\nWhen the framework answers with that code (for example `404`, `401`, `431` or `503`), it calls your action with the controller instead of rendering the built-in error page.\n\nExample: Custom 404\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n### Route\n\nType: `class`\n\nThe object that ROUTE() returns.\n\nIt describes a parsed route. You read its properties or call `remove()`; do not change them after the routes are sorted. The controller of a request has its route in `$.route`.\n\nExample: Inspect a route\n```js\nvar route = ROUTE('+POST /api/orders/ @json <2MB', create);\nconsole.log(route.method, route.auth, route.size, route.flags);\n```\n\n### route.method\n\nType: `property`\n\nThe HTTP method in upper case, without `+` or `-`.\n\nReturns: `String`\n\n`API` routes have `POST`. `FILE` and `SOCKET` routes keep their method name.\n\n### route.url\n\nType: `property`\n\nThe path split into lower-case segments.\n\nReturns: `Array`\n\nParameter segments keep their `{name}` form. The path as written (with `CONF.$root`) is in `route.url2`.\n\n### route.params\n\nType: `property`\n\nThe dynamic parameters of the path.\n\nReturns: `Array`\n\nEach item has `name` and `index`, the position of the segment in the path.\n\n### route.flags\n\nType: `property`\n\nThe `@` flags of the route as an object.\n\nReturns: `Object`\n\nFor example `@json @xhr` gives `{ json: 1, xhr: 1 }`.\n\n### route.middleware\n\nType: `property`\n\nThe names of the middleware that run before the action.\n\nReturns: `Array`\n\nThe `#name` flags in their order. `MIDDLEWARE(name, fn, assign)` can add names to existing routes.\n\n### route.auth\n\nType: `property`\n\nThe authorization of the route.\n\nReturns: `Number`\n\n`0` for everybody, `1` for signed-in users (`+`), `2` for visitors who are not signed in (`-`). The shared route of the API has `0`; each endpoint keeps its own value.\n\n### route.size\n\nType: `property`\n\nThe maximum body size in bytes.\n\nReturns: `Number`\n\nSet by the size flag or the `size` argument; otherwise `CONF.$httpmaxsize * 1024` (`CONF.$wsmaxsize * 1024` for `SOCKET` routes).\n\n### route.timeout\n\nType: `property`\n\nThe timeout in seconds, or `0`.\n\nReturns: `Number`\n\n`0` means the request uses `CONF.$httptimeout`.\n\n### route.priority\n\nType: `property`\n\nThe order in which routes with the same method and path are checked.\n\nReturns: `Number`\n\nIt starts at `100`, each `@` flag lowers it by one and a wildcard by 50. Higher values are checked first.\n\n### route.type\n\nType: `property`\n\nThe kind of route.\n\nReturns: `String`\n\n`route`, `file` or `websocket`.\n\n### route.remove()\n\nType: `method`\n\nRemoves the route.\n\nReturns: `undefined`\n\nUnregisters the route and sorts the routing table again. It works for HTTP routes, API endpoints (the shared `POST` route of the API is removed with its last endpoint), `FILE` routes and `SOCKET` routes, whose open connections are closed.\n\nExample: A temporary route\n```js\nvar route = ROUTE('GET /maintenance/', function($) {\n\t$.plain('Back soon');\n});\n\nsetTimeout(function() {\n\troute.remove();\n}, 60000);\n```\n\n### CORS([origins])\n\nType: `method`\n\nSets the origins allowed for cross-origin requests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `origins` | `String` | no | `'*'` | The allowed origins, `*`, or `+origins` to add. |\n\nReturns: `undefined`\n\nWithout an argument, every origin is allowed (`*`). Otherwise give full origins separated by commas, `;` or `|`. An item that starts with `*` allows every origin that contains the rest. A value that starts with `+` adds origins to the current list. Requests from the same host always pass. An allowed request gets `Access-Control-Allow-Origin` (the origin), `-Credentials: true`, `-Methods`, `-Headers` and `-Expose-Headers` (`*`), and `OPTIONS` is answered at once. Other origins get `400` with `Invalid origin (CORS)`.\n\nExample: Allow two apps\n```js\nCORS('https://app.example.com,https://admin.example.com');\n```\n\nExample: Add one and allow subdomains\n```js\nCORS('+https://partner.com');\nCORS('+*example.org');\n```\n\nExample: Any origin\n```js\nCORS();\n```\n\n### PROXY(path, [target])\n\nType: `method`\n\nForwards requests under a path to another server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | The beginning of the request path, for example `/cdn/`. |\n| `target` | `String|Function` | no |  | The target URL, a Unix socket path, or `function($)`. |\n\nReturns: `Proxy` The proxy object with chainable methods, or nothing when you remove a proxy.\n\nProxies are checked before routes, for every method and for WebSocket upgrades. `path` should end with `/` and gets `CONF.$root`. `target` is an `http://`/`https://` URL, a Unix socket path, or a function that receives the controller and answers itself. The forwarded request keeps the headers (without `Host`) and gets `X-Forwarded-For`, `X-Forwarded-URL` and `X-Forwarded-Host`. When the target fails, the client gets `503`. `PROXY(path)` without a target removes the proxy for that path.\n\nExample: Forward to a service\n```js\nPROXY('/search/', 'http://127.0.0.1:9200').copy('replace');\n```\n\nExample: Unix socket\n```js\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nExample: Own handler\n```js\nPROXY('/ping/', function($) {\n\t$.plain('pong');\n});\n```\n\n### proxy.copy(type)\n\nType: `method`\n\nSets how the request path is copied to the target.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `none`, `replace` or `extend`. |\n\nReturns: `Proxy` The proxy.\n\n`none` (default): the target URL with the query string of the request. `replace`: the target with the part of the path after the proxy path (when the target URL has its own path, `replace` works like `extend`). `extend`: the target path, plus the rest of the request path, plus the query strings of the request and of the target.\n\nExample: Keep sub-paths\n```js\n// GET /cl/something/?q=1 --> https://example.com/something/?q=1\nPROXY('/cl/', 'https://example.com').copy('extend');\n```\n\n### proxy.before(callback)\n\nType: `method`\n\nChanges the outgoing request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(uri, $)`. |\n\nReturns: `Proxy` The proxy.\n\n`callback(uri, $)` runs before the request is sent. `uri` holds the Node.js request options (`path`, `headers`, `method`...).\n\nExample: Add a token\n```js\nPROXY('/api2/', 'https://internal.example.com').before(function(uri, $) {\n\turi.headers['x-token'] = CONF.internal_token;\n});\n```\n\n### proxy.after(callback)\n\nType: `method`\n\nReads the response of the target.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(response)`. |\n\nReturns: `Proxy` The proxy.\n\n`callback(response)` gets the Node.js response before it is sent to the client; you can change `response.headers`.\n\nExample: Remove a header\n```js\nPROXY('/cdn/', 'https://cdn.example.com').after(function(response) {\n\tdelete response.headers['set-cookie'];\n});\n```\n\n### proxy.check(callback)\n\nType: `method`\n\nDecides for each request whether the proxy is used.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)` returning a boolean. |\n\nReturns: `Proxy` The proxy.\n\n`callback($)` returns `true` to forward the request. Otherwise the request goes to the routes.\n\nExample: Only GET\n```js\nPROXY('/files/', 'http://127.0.0.1:8001').check($ => $.method === 'GET');\n```\n\n### proxy.timeout(ms)\n\nType: `method`\n\nSets the timeout of the forwarded request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes |  | The timeout in milliseconds. |\n\nReturns: `Proxy` The proxy.\n\nIn milliseconds. Without it (or with `0`) the proxy uses `CONF.$proxytimeout` seconds.\n\nExample: 30 seconds\n```js\nPROXY('/reports/', 'http://127.0.0.1:8002').timeout(30000);\n```\n\n### proxy.remove()\n\nType: `method`\n\nRemoves the proxy.\n\nReturns: `undefined`\n\nRequests under its path go to the routes again. `PROXY(path)` without a target does the same.\n\nExample: Remove\n```js\nvar proxy = PROXY('/old/', 'http://127.0.0.1:8003');\nproxy.remove();\n```\n\n### $api : /api/\n\nType: `config`\n\nThe path that `?` stands for in API routes.\n\nReturns: `String`\n\nDefault `/api/`. When `$root` is set, it is added in front.\n\nExample: /config\n```js\n$api : /rpc/\n```\n\n### $root : /app/\n\nType: `config`\n\nA path prefix for all routes.\n\nReturns: `String`\n\nEvery route, proxy and `$api` path is prefixed with it, for example when the app runs under `/app/` behind a web server. Default empty.\n\nExample: /config\n```js\n$root : /admin/\n```\n\n### $cors : https://app.example.com\n\nType: `config`\n\nThe origins allowed for cross-origin requests.\n\nReturns: `String`\n\nThe same value as `CORS()` takes: `*`, or origins separated by commas, with `*domain` items for partial matches. Default empty (cross-origin requests are not checked).\n\nExample: /config\n```js\n$cors : https://app.example.com, *example.org\n```\n\n### $httpmaxsize : 256\n\nType: `config`\n\nThe default maximum body size of HTTP routes, in kB.\n\nReturns: `Number`\n\nDefault `256`. A route overrides it with a size flag.\n\nExample: /config\n```js\n$httpmaxsize : 1024\n```\n\n### $httptimeout : 5\n\nType: `config`\n\nThe default timeout of HTTP requests, in seconds.\n\nReturns: `Number`\n\nDefault `5`. A route overrides it with a timeout flag.\n\nExample: /config\n```js\n$httptimeout : 15\n```\n\n### $proxytimeout : 5\n\nType: `config`\n\nThe default timeout of `PROXY()` requests, in seconds.\n\nReturns: `Number`\n\nDefault `5`. `proxy.timeout()` overrides it for one proxy.\n\nExample: /config\n```js\n$proxytimeout : 30\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [size])","since":"","deprecated":false},{"type":"type","name":"+ flag","signature":"ROUTE('+METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"- flag","signature":"ROUTE('-METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"{param}","signature":"ROUTE('GET /path/{name}/', action)","since":"","deprecated":false},{"type":"type","name":"* wildcard","signature":"ROUTE('GET /path/*', action)","since":"","deprecated":false},{"type":"type","name":"API ?","signature":"ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])","since":"","deprecated":false},{"type":"type","name":"--> actions","signature":"ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')","since":"","deprecated":false},{"type":"type","name":"<size","signature":"ROUTE('METHOD /path/ <10MB', action)","since":"","deprecated":false},{"type":"type","name":"<timeout","signature":"ROUTE('METHOD /path/ <30s', action)","since":"","deprecated":false},{"type":"type","name":"#middleware","signature":"ROUTE('METHOD /path/ #name', action)","since":"","deprecated":false},{"type":"type","name":"@json","signature":"ROUTE('METHOD /path/ @json', action)","since":"","deprecated":false},{"type":"type","name":"@xml","signature":"ROUTE('METHOD /path/ @xml', action)","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('METHOD /path/ @upload', action)","since":"","deprecated":false},{"type":"type","name":"@xhr","signature":"ROUTE('METHOD /path/ @xhr', action)","since":"","deprecated":false},{"type":"type","name":"@mobile","signature":"ROUTE('METHOD /path/ @mobile', action)","since":"","deprecated":false},{"type":"type","name":"@robot","signature":"ROUTE('METHOD /path/ @robot', action)","since":"","deprecated":false},{"type":"type","name":"@referrer","signature":"ROUTE('METHOD /path/ @referrer', action)","since":"","deprecated":false},{"type":"type","name":"@debug","signature":"ROUTE('METHOD /path/ @debug', action)","since":"","deprecated":false},{"type":"type","name":"@release","signature":"ROUTE('METHOD /path/ @release', action)","since":"","deprecated":false},{"type":"type","name":"FILE","signature":"ROUTE('FILE /path/pattern', action)","since":"","deprecated":false},{"type":"type","name":"SOCKET","signature":"ROUTE('SOCKET /path/ [flags]', action)","since":"","deprecated":false},{"type":"type","name":"#code","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"class","name":"Route","signature":"Route","since":"","deprecated":false},{"type":"property","name":"route.method","signature":"route.method","since":"","deprecated":false},{"type":"property","name":"route.url","signature":"route.url","since":"","deprecated":false},{"type":"property","name":"route.params","signature":"route.params","since":"","deprecated":false},{"type":"property","name":"route.flags","signature":"route.flags","since":"","deprecated":false},{"type":"property","name":"route.middleware","signature":"route.middleware","since":"","deprecated":false},{"type":"property","name":"route.auth","signature":"route.auth","since":"","deprecated":false},{"type":"property","name":"route.size","signature":"route.size","since":"","deprecated":false},{"type":"property","name":"route.timeout","signature":"route.timeout","since":"","deprecated":false},{"type":"property","name":"route.priority","signature":"route.priority","since":"","deprecated":false},{"type":"property","name":"route.type","signature":"route.type","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([origins])","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(path, [target])","since":"","deprecated":false},{"type":"method","name":"proxy.copy()","signature":"proxy.copy(type)","since":"","deprecated":false},{"type":"method","name":"proxy.before()","signature":"proxy.before(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.after()","signature":"proxy.after(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.check()","signature":"proxy.check(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.timeout()","signature":"proxy.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"proxy.remove()","signature":"proxy.remove()","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : /api/","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root : /app/","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : https://app.example.com","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : 5","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : 5","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JaedEABfT60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/routing/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Routing","summary":"Syntax von ROUTE(), Flags, das Routenobjekt, CORS(), PROXY() und die Konfiguration des Routings.","markdown":"---\ntitle: Routing\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/routing/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Routing\n\n> Syntax von ROUTE(), Flags, das Routenobjekt, CORS(), PROXY() und die Konfiguration des Routings.\n\nJeder Teil des Strings von `ROUTE()` (Präfixe der Methode, Parameter, Flags, Aktionen und API-Endpunkte), das Routenobjekt, `CORS()`, `PROXY()` und die Konfigurationsschlüssel des Routings. Die Anleitung [Routing](../../guides/routing/) erklärt sie mit Beispielen; diese Seite ist die genaue Referenz.\n\n## API\n\n### ROUTE(url, [action], [size])\n\nType: `method`\n\nDeklariert eine Route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Methode, der Pfad und die Flags, zum Beispiel `+POST /api/orders/ @json <1MB`. |\n| `action` | `Function|String` | no |  | Eine Funktion, die mit dem Controller aufgerufen wird, oder der Name einer View. Ohne sie wird eine View gerendert, die nach dem ersten Segment des Pfads benannt ist (`index` für `/`). |\n| `size` | `Number` | no | `CONF.$httpmaxsize` | Die maximale Größe des Bodys in Bytes. Sie kann das zweite Argument sein, wenn es keine Aktion gibt. |\n\nReturns: `Route` Das Routenobjekt.\n\n`url` ist ein String: die Methode (mit optionalem Präfix `+` oder `-`), der Pfad und optionale Flags, Aktionen nach `-->` und API-Endpunkte nach `?`. Die Routen werden 100 ms nach dem letzten Aufruf von `ROUTE()` sortiert. Ein Pfad, der mit `#` beginnt, deklariert eine Fehler-Route. Das globale `ROUTE` ist dieselbe Funktion wie `F.route`.\n\nExample: Eine Seite und ein JSON-Endpunkt\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n\nfunction index($) {\n\t$.view('index');\n}\n```\n\nExample: Eine View ohne Code\n```js\nexports.install = function() {\n\tROUTE('GET /contact/', 'contact');\n\tROUTE('GET /about/');\n};\n```\n\n### ROUTE('+METHOD /path/', action)\n\nType: `type`\n\nDie Route ist nur für angemeldete Benutzer.\n\nDer Delegate `AUTH()` muss einen Benutzer zurückgeben; ohne `AUTH()` wird das Präfix nicht geprüft, und die Route bedient alle. Wenn der Benutzer nicht angemeldet ist und keine andere Route der URL Besucher akzeptiert, lautet die Antwort `401`. Der Benutzer steht in `$.user`.\n\nExample: Eine Kontoseite\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', function($) {\n\t\t$.json($.user);\n\t});\n};\n```\n\n### ROUTE('-METHOD /path/', action)\n\nType: `type`\n\nDie Route ist nur für Besucher, die nicht angemeldet sind.\n\nVerwende sie zusammen mit einer `+`-Route derselben URL, um angemeldeten Benutzern und Besuchern unterschiedliche Inhalte zu zeigen. Ein angemeldeter Benutzer, der nur eine `-`-Route erreicht, erhält `401`.\n\nExample: Anmeldung oder Konto\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n};\n```\n\n### ROUTE('GET /path/{name}/', action)\n\nType: `type`\n\nEin dynamisches Segment des Pfads.\n\nDer Wert des Segments wird in `$.params` unter seinem Namen gespeichert, als String mit der Groß- und Kleinschreibung der URL der Anfrage. Ein Parameter belegt ein ganzes Segment. Eine Route mit Parametern passt nur auf URLs mit derselben Anzahl an Segmenten.\n\nExample: Zwei Parameter\n```js\nexports.install = function() {\n\tROUTE('GET /blog/{year}/{slug}/', function($) {\n\t\t$.json({ year: $.params.year, slug: $.params.slug });\n\t});\n};\n```\n\n### ROUTE('GET /path/*', action)\n\nType: `type`\n\nPasst auf den Pfad und alles darunter.\n\nEine Platzhalter-Route hat eine niedrigere Priorität als feste und dynamische Routen, sodass sie nur die URLs abfängt, die keine andere Route übernimmt.\n\nExample: Ein Catch-all für einen Bereich\n```js\nexports.install = function() {\n\tROUTE('GET /app/*', 'app');\n};\n```\n\n### ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])\n\nType: `type`\n\nDeklariert einen Endpunkt der API-Route.\n\nDas `?` wird durch `CONF.$api` ersetzt (Standard `/api/`, ohne dass `CONF.$root` erneut hinzugefügt wird). Alle Endpunkte teilen sich eine `POST`-Route. Der Body der Anfrage ist `{ schema: \"endpoint/param?query\", data: {...} }`: `$.params` wird aus den Teilen des Pfads von `schema` gefüllt, `$.query` aus dem Teil nach `?`, und `data` wird zum Body. `+API` und `-API` prüfen den Benutzer für jeden Endpunkt. Ein fehlender Parameter ist ein Fehler für `params.<name>`; ein unbekannter Endpunkt oder ein Body ohne `schema` erhält `400`. Das Timeout-Flag gilt für den Endpunkt und das größte Größen-Flag für die gemeinsame Route.\n\nExample: Endpunkte\n```js\nexports.install = function() {\n\tROUTE('API ? tasks_list --> Tasks/list');\n\tROUTE('+API ? tasks_read/{id} --> Tasks/read');\n\tROUTE('+API ? tasks_save <5MB --> Tasks/save');\n};\n```\n\nExample: Eine Funktion statt Aktionen\n```js\nexports.install = function() {\n\tROUTE('API ? ping', function($) {\n\t\t$.success();\n\t});\n};\n```\n\nExample: Client\n```js\nAJAX('POST /api/', { schema: 'tasks_read/42', data: null }, function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')\n\nType: `type`\n\nFührt Aktionen statt einer Funktion aus.\n\nDie Namen nach `-->` sind mit `NEWACTION()` deklarierte Aktionen, getrennt durch Leerzeichen oder Kommas. Der Body der Anfrage ist der Payload, und `$.params`, `$.query` und `$.user` werden weitergegeben. Das Ergebnis wird als Antwort gesendet und ein Fehler mit `$.invalid()`. Bei mehreren Aktionen markierst du die, deren Ergebnis die Antwort ist, mit `(response)`; eine einzelne Aktion ist die Antwort.\n\nExample: Eine Aktion\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/ --> Users/list');\n};\n```\n\nExample: Einfügen und zurücklesen\n```js\nexports.install = function() {\n\tROUTE('+POST /api/users/ --> Users/insert Users/read (response)');\n};\n```\n\n### ROUTE('METHOD /path/ <10MB', action)\n\nType: `type`\n\nSetzt die maximale Größe des Bodys der Anfrage.\n\nEinheiten: `b` (Bytes), `kB` (Kilobytes, 1024 Bytes), `MB` (Megabytes) und `GB` (Gigabytes); die Einheit ist erforderlich. Ein größerer Body wird mit `431` beantwortet. Ohne das Flag ist das Limit `CONF.$httpmaxsize` kB (`CONF.$wsmaxsize` kB bei `SOCKET`-Routen).\n\nExample: Uploads bis 50 MB\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <50MB', upload);\n};\n```\n\n### ROUTE('METHOD /path/ <30s', action)\n\nType: `type`\n\nSetzt das Timeout der Anfrage.\n\nEinheiten: `s` (Sekunden), `m` (Minuten) und `h` (Stunden). Wenn die Aktion nicht rechtzeitig antwortet, endet die Anfrage mit `503`. Ohne das Flag ist das Timeout `CONF.$httptimeout` Sekunden. Das Timeout wird alle 5 Sekunden geprüft.\n\nExample: Ein langer Export\n```js\nexports.install = function() {\n\tROUTE('GET /export/ <10m', exportdata);\n};\n```\n\n### ROUTE('METHOD /path/ #name', action)\n\nType: `type`\n\nFührt eine Middleware vor der Aktion aus.\n\nDer Name muss mit `MIDDLEWARE(name, fn)` registriert sein. Mehrere `#names` laufen in der geschriebenen Reihenfolge; ein unbekannter Name wird übersprungen. Middleware-Namen enthalten Buchstaben, Ziffern und `_`.\n\nExample: Zwei Middleware\n```js\nMIDDLEWARE('cors_api', function($, next) {\n\t$.response.headers['x-api'] = '1';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/stats/ #cors_api #nocache', stats);\n};\n```\n\n### ROUTE('METHOD /path/ @json', action)\n\nType: `type`\n\nDie Route passt nur, wenn der Body der Anfrage JSON ist (`application/json` oder `text/json`).\n\nErfüllt die Anfrage die Bedingung nicht, versucht der Router die nächste Route mit derselben Methode und demselben Pfad. Jedes Flag senkt die Priorität der Route um eins, sodass eine Route mit weniger Flags zuerst geprüft wird.\n\nExample: Verwendung\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/ @json', orders);\n};\n```\n\n### ROUTE('METHOD /path/ @xml', action)\n\nType: `type`\n\nDie Route passt nur, wenn der Body der Anfrage XML ist (`application/xml` oder `text/xml`).\n\nErfüllt die Anfrage die Bedingung nicht, versucht der Router die nächste Route mit derselben Methode und demselben Pfad. Jedes Flag senkt die Priorität der Route um eins, sodass eine Route mit weniger Flags zuerst geprüft wird.\n\nExample: Verwendung\n```js\nexports.install = function() {\n\tROUTE('POST /feed/ @xml', feed);\n};\n```\n\n### ROUTE('METHOD /path/ @upload', action)\n\nType: `type`\n\nDie Route passt nur, wenn der Body der Anfrage `multipart/form-data` ist.\n\nErfüllt die Anfrage die Bedingung nicht, versucht der Router die nächste Route mit derselben Methode und demselben Pfad. Jedes Flag senkt die Priorität der Route um eins, sodass eine Route mit weniger Flags zuerst geprüft wird.\n\nExample: Verwendung\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', function($) {\n\t\t$.json($.files.map(f => f.filename));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @xhr', action)\n\nType: `type`\n\nDie Route passt nur, wenn die Anfrage den Header `X-Requested-With: XMLHttpRequest` hat.\n\nErfüllt die Anfrage die Bedingung nicht, versucht der Router die nächste Route mit derselben Methode und demselben Pfad. Jedes Flag senkt die Priorität der Route um eins, sodass eine Route mit weniger Flags zuerst geprüft wird.\n\nExample: Verwendung\n```js\nexports.install = function() {\n\tROUTE('GET /partials/menu/ @xhr', 'partials/menu');\n};\n```\n\n### ROUTE('METHOD /path/ @mobile', action)\n\nType: `type`\n\nDie Route passt nur, wenn der Client ein Mobilgerät ist.\n\nErfüllt die Anfrage die Bedingung nicht, versucht der Router die nächste Route mit derselben Methode und demselben Pfad. Jedes Flag senkt die Priorität der Route um eins, sodass eine Route mit weniger Flags zuerst geprüft wird.\n\nExample: Verwendung\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /m/ @mobile', 'mobile');\n};\n```\n\n### ROUTE('METHOD /path/ @robot', action)\n\nType: `type`\n\nDie Route passt nur, wenn der Client ein Crawler ist.\n\nErfüllt die Anfrage die Bedingung nicht, versucht der Router die nächste Route mit derselben Methode und demselben Pfad. Jedes Flag senkt die Priorität der Route um eins, sodass eine Route mit weniger Flags zuerst geprüft wird.\n\nExample: Verwendung\n```js\nexports.install = function() {\n\tROUTE('GET /prerender/ @robot', 'static');\n};\n```\n\n### ROUTE('METHOD /path/ @referrer', action)\n\nType: `type`\n\nDie Route passt nur, wenn der Header `Referer` den Host der Anfrage enthält; `@referer` ist dasselbe Flag.\n\nErfüllt die Anfrage die Bedingung nicht, versucht der Router die nächste Route mit derselben Methode und demselben Pfad. Jedes Flag senkt die Priorität der Route um eins, sodass eine Route mit weniger Flags zuerst geprüft wird.\n\nExample: Verwendung\n```js\nexports.install = function() {\n\tROUTE('GET /download/ @referrer', download);\n};\n```\n\n### ROUTE('METHOD /path/ @debug', action)\n\nType: `type`\n\nDie Route passt nur, wenn die Anwendung im Debug-Modus läuft.\n\nErfüllt die Anfrage die Bedingung nicht, versucht der Router die nächste Route mit derselben Methode und demselben Pfad. Jedes Flag senkt die Priorität der Route um eins, sodass eine Route mit weniger Flags zuerst geprüft wird.\n\nExample: Verwendung\n```js\nexports.install = function() {\n\tROUTE('GET /dev/routes/ @debug', function($) {\n\t\t$.json(F.routes.routes.map(r => r.method + ' ' + r.url2));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @release', action)\n\nType: `type`\n\nDie Route passt nur, wenn die Anwendung im Release-Modus läuft.\n\nErfüllt die Anfrage die Bedingung nicht, versucht der Router die nächste Route mit derselben Methode und demselben Pfad. Jedes Flag senkt die Priorität der Route um eins, sodass eine Route mit weniger Flags zuerst geprüft wird.\n\nExample: Verwendung\n```js\nexports.install = function() {\n\tROUTE('GET /status/ @release', status);\n};\n```\n\n### ROUTE('FILE /path/pattern', action)\n\nType: `type`\n\nBehandelt Anfragen nach statischen Dateien mit deinem Code.\n\nDatei-Routen werden für URLs mit einer Endung geprüft. Muster: eine feste Datei (`/robots.txt`), Endungen in einem Ordner (`/docs/*.md|txt`), jede Datei in einem Ordner (`/downloads/*`) und eine Endung an beliebiger Stelle (`*.webp`). Die Aktion erhält den Controller; antworte mit `$.file()`, `$.image()`, `$.plain()` oder `$.resume()` (liefert die Datei aus `/public/` aus). Eine Anfrage, die keine Route übernimmt, wird aus `/public/` ausgeliefert, wenn ihre Endung in `CONF.$httpfiles` steht, oder erhält `404`.\n\nExample: Erzeugte robots.txt\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', function($) {\n\t\t$.plain('User-agent: *\\nDisallow: /admin/');\n\t});\n};\n```\n\nExample: Dateien aus einem privaten Ordner\n```js\nexports.install = function() {\n\tROUTE('FILE /files/*.pdf|docx', function($) {\n\t\t$.file(PATH.databases($.split[1]), true);\n\t});\n};\n```\n\n### ROUTE('SOCKET /path/ [flags]', action)\n\nType: `type`\n\nDeklariert einen WebSocket-Endpunkt.\n\n`WEBSOCKET` ist dieselbe Methode. Der Pfad, `+`/`-`, `{params}`, `#middleware` und das Größen-Flag funktionieren wie bei HTTP-Routen; die Standardgröße einer Nachricht ist `CONF.$wsmaxsize` kB. Siehe [WebSockets](../../guides/websockets/).\n\nExample: Chat\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /chat/{room}/ <1MB', chat);\n};\n```\n\n### ROUTE('#code', action)\n\nType: `type`\n\nErsetzt die Standard-Fehlerseite für einen Statuscode.\n\nWenn das Framework mit diesem Code antwortet (zum Beispiel `404`, `401`, `431` oder `503`), ruft es deine Aktion mit dem Controller auf, statt die eingebaute Fehlerseite zu rendern.\n\nExample: Eigene 404-Seite\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n### Route\n\nType: `class`\n\nDas Objekt, das ROUTE() zurückgibt.\n\nEs beschreibt eine geparste Route. Du liest seine Eigenschaften oder rufst `remove()` auf; ändere sie nicht, nachdem die Routen sortiert sind. Der Controller einer Anfrage hat seine Route in `$.route`.\n\nExample: Eine Route untersuchen\n```js\nvar route = ROUTE('+POST /api/orders/ @json <2MB', create);\nconsole.log(route.method, route.auth, route.size, route.flags);\n```\n\n### route.method\n\nType: `property`\n\nDie HTTP-Methode in Großbuchstaben, ohne `+` oder `-`.\n\nReturns: `String`\n\n`API`-Routen haben `POST`. `FILE`- und `SOCKET`-Routen behalten ihren Methodennamen.\n\n### route.url\n\nType: `property`\n\nDer Pfad, in kleingeschriebene Segmente aufgeteilt.\n\nReturns: `Array`\n\nParameter-Segmente behalten ihre Form `{name}`. Der Pfad, wie er geschrieben wurde (mit `CONF.$root`), steht in `route.url2`.\n\n### route.params\n\nType: `property`\n\nDie dynamischen Parameter des Pfads.\n\nReturns: `Array`\n\nJedes Element hat `name` und `index`, die Position des Segments im Pfad.\n\n### route.flags\n\nType: `property`\n\nDie `@`-Flags der Route als Objekt.\n\nReturns: `Object`\n\nZum Beispiel ergibt `@json @xhr` `{ json: 1, xhr: 1 }`.\n\n### route.middleware\n\nType: `property`\n\nDie Namen der Middleware, die vor der Aktion laufen.\n\nReturns: `Array`\n\nDie `#name`-Flags in ihrer Reihenfolge. `MIDDLEWARE(name, fn, assign)` kann bestehenden Routen Namen hinzufügen.\n\n### route.auth\n\nType: `property`\n\nDie Autorisierung der Route.\n\nReturns: `Number`\n\n`0` für alle, `1` für angemeldete Benutzer (`+`), `2` für Besucher, die nicht angemeldet sind (`-`). Die gemeinsame Route der API hat `0`; jeder Endpunkt behält seinen eigenen Wert.\n\n### route.size\n\nType: `property`\n\nDie maximale Größe des Bodys in Bytes.\n\nReturns: `Number`\n\nGesetzt durch das Größen-Flag oder das Argument `size`; sonst `CONF.$httpmaxsize * 1024` (`CONF.$wsmaxsize * 1024` bei `SOCKET`-Routen).\n\n### route.timeout\n\nType: `property`\n\nDas Timeout in Sekunden oder `0`.\n\nReturns: `Number`\n\n`0` bedeutet, dass die Anfrage `CONF.$httptimeout` verwendet.\n\n### route.priority\n\nType: `property`\n\nDie Reihenfolge, in der Routen mit derselben Methode und demselben Pfad geprüft werden.\n\nReturns: `Number`\n\nSie beginnt bei `100`, jedes `@`-Flag senkt sie um eins und ein Platzhalter um 50. Höhere Werte werden zuerst geprüft.\n\n### route.type\n\nType: `property`\n\nDie Art der Route.\n\nReturns: `String`\n\n`route`, `file` oder `websocket`.\n\n### route.remove()\n\nType: `method`\n\nEntfernt die Route.\n\nReturns: `undefined`\n\nMeldet die Route ab und sortiert die Routing-Tabelle neu. Es funktioniert für HTTP-Routen, API-Endpunkte (die gemeinsame `POST`-Route der API wird mit ihrem letzten Endpunkt entfernt), `FILE`-Routen und `SOCKET`-Routen, deren offene Verbindungen geschlossen werden.\n\nExample: Eine temporäre Route\n```js\nvar route = ROUTE('GET /maintenance/', function($) {\n\t$.plain('Back soon');\n});\n\nsetTimeout(function() {\n\troute.remove();\n}, 60000);\n```\n\n### CORS([origins])\n\nType: `method`\n\nSetzt die Origins, die für Cross-Origin-Anfragen erlaubt sind.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `origins` | `String` | no | `'*'` | Die erlaubten Origins, `*` oder `+origins` zum Hinzufügen. |\n\nReturns: `undefined`\n\nOhne Argument ist jeder Origin erlaubt (`*`). Andernfalls gib vollständige Origins an, getrennt durch Kommas, `;` oder `|`. Ein Element, das mit `*` beginnt, erlaubt jeden Origin, der den Rest enthält. Ein Wert, der mit `+` beginnt, fügt der aktuellen Liste Origins hinzu. Anfragen vom selben Host sind immer erlaubt. Eine erlaubte Anfrage erhält `Access-Control-Allow-Origin` (den Origin), `-Credentials: true`, `-Methods`, `-Headers` und `-Expose-Headers` (`*`), und `OPTIONS` wird sofort beantwortet. Andere Origins erhalten `400` mit `Invalid origin (CORS)`.\n\nExample: Zwei Apps erlauben\n```js\nCORS('https://app.example.com,https://admin.example.com');\n```\n\nExample: Einen hinzufügen und Subdomains erlauben\n```js\nCORS('+https://partner.com');\nCORS('+*example.org');\n```\n\nExample: Beliebiger Origin\n```js\nCORS();\n```\n\n### PROXY(path, [target])\n\nType: `method`\n\nLeitet Requests unter einem Pfad an einen anderen Server weiter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Der Anfang des Pfads der Anfrage, zum Beispiel `/cdn/`. |\n| `target` | `String|Function` | no |  | Die Ziel-URL, ein Pfad zu einem Unix-Socket oder `function($)`. |\n\nReturns: `Proxy` Das Proxy-Objekt mit verkettbaren Methoden oder nichts, wenn du einen Proxy entfernst.\n\nProxys werden vor den Routen geprüft, für jede Methode und für WebSocket-Upgrades. `path` sollte mit `/` enden und erhält `CONF.$root`. `target` ist eine `http://`/`https://`-URL, ein Pfad zu einem Unix-Socket oder eine Funktion, die den Controller erhält und selbst antwortet. Die weitergeleitete Anfrage behält die Header (ohne `Host`) und erhält `X-Forwarded-For`, `X-Forwarded-URL` und `X-Forwarded-Host`. Wenn das Ziel fehlschlägt, erhält der Client `503`. `PROXY(path)` ohne Ziel entfernt den Proxy für diesen Pfad.\n\nExample: An einen Dienst weiterleiten\n```js\nPROXY('/search/', 'http://127.0.0.1:9200').copy('replace');\n```\n\nExample: Unix-Socket\n```js\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nExample: Eigener Handler\n```js\nPROXY('/ping/', function($) {\n\t$.plain('pong');\n});\n```\n\n### proxy.copy(type)\n\nType: `method`\n\nLegt fest, wie der Pfad der Anfrage auf das Ziel übertragen wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `none`, `replace` oder `extend`. |\n\nReturns: `Proxy` Der Proxy.\n\n`none` (Standard): die Ziel-URL mit dem Query String der Anfrage. `replace`: das Ziel mit dem Teil des Pfads nach dem Proxy-Pfad (wenn die Ziel-URL einen eigenen Pfad hat, funktioniert `replace` wie `extend`). `extend`: der Pfad des Ziels plus der Rest des Pfads der Anfrage plus die Query Strings der Anfrage und des Ziels.\n\nExample: Unterpfade beibehalten\n```js\n// GET /cl/something/?q=1 --> https://example.com/something/?q=1\nPROXY('/cl/', 'https://example.com').copy('extend');\n```\n\n### proxy.before(callback)\n\nType: `method`\n\nÄndert die ausgehende Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(uri, $)`. |\n\nReturns: `Proxy` Der Proxy.\n\n`callback(uri, $)` läuft, bevor die Anfrage gesendet wird. `uri` enthält die Request-Optionen von Node.js (`path`, `headers`, `method`...).\n\nExample: Ein Token hinzufügen\n```js\nPROXY('/api2/', 'https://internal.example.com').before(function(uri, $) {\n\turi.headers['x-token'] = CONF.internal_token;\n});\n```\n\n### proxy.after(callback)\n\nType: `method`\n\nLiest die Antwort des Ziels.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(response)`. |\n\nReturns: `Proxy` Der Proxy.\n\n`callback(response)` erhält die Node.js-Antwort, bevor sie an den Client gesendet wird; du kannst `response.headers` ändern.\n\nExample: Einen Header entfernen\n```js\nPROXY('/cdn/', 'https://cdn.example.com').after(function(response) {\n\tdelete response.headers['set-cookie'];\n});\n```\n\n### proxy.check(callback)\n\nType: `method`\n\nEntscheidet für jede Anfrage, ob der Proxy verwendet wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)`, die einen Boolean zurückgibt. |\n\nReturns: `Proxy` Der Proxy.\n\n`callback($)` gibt `true` zurück, um die Anfrage weiterzuleiten. Andernfalls geht die Anfrage an die Routen.\n\nExample: Nur GET\n```js\nPROXY('/files/', 'http://127.0.0.1:8001').check($ => $.method === 'GET');\n```\n\n### proxy.timeout(ms)\n\nType: `method`\n\nSetzt das Timeout der weitergeleiteten Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes |  | Das Timeout in Millisekunden. |\n\nReturns: `Proxy` Der Proxy.\n\nIn Millisekunden. Ohne es (oder mit `0`) verwendet der Proxy `CONF.$proxytimeout` Sekunden.\n\nExample: 30 Sekunden\n```js\nPROXY('/reports/', 'http://127.0.0.1:8002').timeout(30000);\n```\n\n### proxy.remove()\n\nType: `method`\n\nEntfernt den Proxy.\n\nReturns: `undefined`\n\nAnfragen unter seinem Pfad gehen wieder an die Routen. `PROXY(path)` ohne Ziel bewirkt dasselbe.\n\nExample: Entfernen\n```js\nvar proxy = PROXY('/old/', 'http://127.0.0.1:8003');\nproxy.remove();\n```\n\n### $api : /api/\n\nType: `config`\n\nDer Pfad, für den `?` in API-Routen steht.\n\nReturns: `String`\n\nStandard `/api/`. Wenn `$root` gesetzt ist, wird es vorangestellt.\n\nExample: /config\n```js\n$api : /rpc/\n```\n\n### $root : /app/\n\nType: `config`\n\nEin Pfadpräfix für alle Routen.\n\nReturns: `String`\n\nJedem Pfad von Routen, Proxys und `$api` wird es vorangestellt, zum Beispiel wenn die App hinter einem Webserver unter `/app/` läuft. Standard leer.\n\nExample: /config\n```js\n$root : /admin/\n```\n\n### $cors : https://app.example.com\n\nType: `config`\n\nDie Origins, die für Cross-Origin-Anfragen erlaubt sind.\n\nReturns: `String`\n\nDerselbe Wert, den `CORS()` annimmt: `*` oder durch Kommas getrennte Origins, mit `*domain`-Elementen für Teilübereinstimmungen. Standard leer (Cross-Origin-Anfragen werden nicht geprüft).\n\nExample: /config\n```js\n$cors : https://app.example.com, *example.org\n```\n\n### $httpmaxsize : 256\n\nType: `config`\n\nDie standardmäßige maximale Größe des Bodys von HTTP-Routen, in kB.\n\nReturns: `Number`\n\nStandard `256`. Eine Route überschreibt sie mit einem Größen-Flag.\n\nExample: /config\n```js\n$httpmaxsize : 1024\n```\n\n### $httptimeout : 5\n\nType: `config`\n\nDas standardmäßige Timeout von HTTP-Anfragen, in Sekunden.\n\nReturns: `Number`\n\nStandard `5`. Eine Route überschreibt es mit einem Timeout-Flag.\n\nExample: /config\n```js\n$httptimeout : 15\n```\n\n### $proxytimeout : 5\n\nType: `config`\n\nDas standardmäßige Timeout von `PROXY()`-Anfragen, in Sekunden.\n\nReturns: `Number`\n\nStandard `5`. `proxy.timeout()` überschreibt es für einen Proxy.\n\nExample: /config\n```js\n$proxytimeout : 30\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [size])","since":"","deprecated":false},{"type":"type","name":"+ flag","signature":"ROUTE('+METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"- flag","signature":"ROUTE('-METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"{param}","signature":"ROUTE('GET /path/{name}/', action)","since":"","deprecated":false},{"type":"type","name":"* wildcard","signature":"ROUTE('GET /path/*', action)","since":"","deprecated":false},{"type":"type","name":"API ?","signature":"ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])","since":"","deprecated":false},{"type":"type","name":"--> actions","signature":"ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')","since":"","deprecated":false},{"type":"type","name":"<size","signature":"ROUTE('METHOD /path/ <10MB', action)","since":"","deprecated":false},{"type":"type","name":"<timeout","signature":"ROUTE('METHOD /path/ <30s', action)","since":"","deprecated":false},{"type":"type","name":"#middleware","signature":"ROUTE('METHOD /path/ #name', action)","since":"","deprecated":false},{"type":"type","name":"@json","signature":"ROUTE('METHOD /path/ @json', action)","since":"","deprecated":false},{"type":"type","name":"@xml","signature":"ROUTE('METHOD /path/ @xml', action)","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('METHOD /path/ @upload', action)","since":"","deprecated":false},{"type":"type","name":"@xhr","signature":"ROUTE('METHOD /path/ @xhr', action)","since":"","deprecated":false},{"type":"type","name":"@mobile","signature":"ROUTE('METHOD /path/ @mobile', action)","since":"","deprecated":false},{"type":"type","name":"@robot","signature":"ROUTE('METHOD /path/ @robot', action)","since":"","deprecated":false},{"type":"type","name":"@referrer","signature":"ROUTE('METHOD /path/ @referrer', action)","since":"","deprecated":false},{"type":"type","name":"@debug","signature":"ROUTE('METHOD /path/ @debug', action)","since":"","deprecated":false},{"type":"type","name":"@release","signature":"ROUTE('METHOD /path/ @release', action)","since":"","deprecated":false},{"type":"type","name":"FILE","signature":"ROUTE('FILE /path/pattern', action)","since":"","deprecated":false},{"type":"type","name":"SOCKET","signature":"ROUTE('SOCKET /path/ [flags]', action)","since":"","deprecated":false},{"type":"type","name":"#code","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"class","name":"Route","signature":"Route","since":"","deprecated":false},{"type":"property","name":"route.method","signature":"route.method","since":"","deprecated":false},{"type":"property","name":"route.url","signature":"route.url","since":"","deprecated":false},{"type":"property","name":"route.params","signature":"route.params","since":"","deprecated":false},{"type":"property","name":"route.flags","signature":"route.flags","since":"","deprecated":false},{"type":"property","name":"route.middleware","signature":"route.middleware","since":"","deprecated":false},{"type":"property","name":"route.auth","signature":"route.auth","since":"","deprecated":false},{"type":"property","name":"route.size","signature":"route.size","since":"","deprecated":false},{"type":"property","name":"route.timeout","signature":"route.timeout","since":"","deprecated":false},{"type":"property","name":"route.priority","signature":"route.priority","since":"","deprecated":false},{"type":"property","name":"route.type","signature":"route.type","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([origins])","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(path, [target])","since":"","deprecated":false},{"type":"method","name":"proxy.copy()","signature":"proxy.copy(type)","since":"","deprecated":false},{"type":"method","name":"proxy.before()","signature":"proxy.before(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.after()","signature":"proxy.after(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.check()","signature":"proxy.check(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.timeout()","signature":"proxy.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"proxy.remove()","signature":"proxy.remove()","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : /api/","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root : /app/","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : https://app.example.com","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : 5","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : 5","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JaedEABfT60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/routing/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Enrutamiento","summary":"Sintaxis de ROUTE(), flags, el objeto de la ruta, CORS(), PROXY() y la configuración del enrutamiento.","markdown":"---\ntitle: Enrutamiento\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/routing/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Enrutamiento\n\n> Sintaxis de ROUTE(), flags, el objeto de la ruta, CORS(), PROXY() y la configuración del enrutamiento.\n\nCada parte de la cadena de `ROUTE()` (prefijos del método, parámetros, flags, acciones y endpoints de API), el objeto de la ruta, `CORS()`, `PROXY()` y las claves de configuración del enrutamiento. La guía [Enrutamiento](../../guides/routing/) los explica con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### ROUTE(url, [action], [size])\n\nType: `method`\n\nDeclara una ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | El método, la ruta y los flags, por ejemplo `+POST /api/orders/ @json <1MB`. |\n| `action` | `Function|String` | no |  | Una función que se llama con el controlador, o el nombre de una vista. Sin ella, se renderiza una vista con el nombre del primer segmento de la ruta (`index` para `/`). |\n| `size` | `Number` | no | `CONF.$httpmaxsize` | El tamaño máximo del cuerpo en bytes. Puede ser el segundo argumento cuando no hay acción. |\n\nReturns: `Route` El objeto de la ruta.\n\n`url` es una sola cadena: el método (con un prefijo opcional `+` o `-`), la ruta y flags opcionales, las acciones después de `-->` y los endpoints de API después de `?`. Las rutas se ordenan 100 ms después de la última llamada a `ROUTE()`. Una ruta que empieza por `#` declara una ruta de error. La función global `ROUTE` es la misma función que `F.route`.\n\nExample: Una página y un endpoint JSON\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n\nfunction index($) {\n\t$.view('index');\n}\n```\n\nExample: Una vista sin código\n```js\nexports.install = function() {\n\tROUTE('GET /contact/', 'contact');\n\tROUTE('GET /about/');\n};\n```\n\n### ROUTE('+METHOD /path/', action)\n\nType: `type`\n\nLa ruta es solo para usuarios con sesión iniciada.\n\nEl delegado `AUTH()` debe devolver un usuario; sin `AUTH()` el prefijo no se comprueba y la ruta atiende a todo el mundo. Cuando el usuario no tiene la sesión iniciada y ninguna otra ruta de la URL acepta visitantes, la respuesta es `401`. El usuario está en `$.user`.\n\nExample: Una página de cuenta\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', function($) {\n\t\t$.json($.user);\n\t});\n};\n```\n\n### ROUTE('-METHOD /path/', action)\n\nType: `type`\n\nLa ruta es solo para visitantes sin sesión iniciada.\n\nÚsala con una ruta `+` de la misma URL para mostrar contenido distinto a los usuarios con sesión iniciada y a los visitantes. Un usuario con sesión iniciada que solo llega a una ruta `-` recibe `401`.\n\nExample: Inicio de sesión o cuenta\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n};\n```\n\n### ROUTE('GET /path/{name}/', action)\n\nType: `type`\n\nUn segmento dinámico de la ruta.\n\nEl valor del segmento se guarda en `$.params` con su nombre, como cadena con las mayúsculas y minúsculas de la URL de la petición. Un parámetro ocupa un segmento entero. Una ruta con parámetros solo coincide con URL que tienen el mismo número de segmentos.\n\nExample: Dos parámetros\n```js\nexports.install = function() {\n\tROUTE('GET /blog/{year}/{slug}/', function($) {\n\t\t$.json({ year: $.params.year, slug: $.params.slug });\n\t});\n};\n```\n\n### ROUTE('GET /path/*', action)\n\nType: `type`\n\nCoincide con la ruta y con todo lo que hay por debajo.\n\nUna ruta comodín tiene menos prioridad que las rutas fijas y dinámicas, así que solo captura las URL que no toma ninguna otra ruta.\n\nExample: Una ruta comodín para una sección\n```js\nexports.install = function() {\n\tROUTE('GET /app/*', 'app');\n};\n```\n\n### ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])\n\nType: `type`\n\nDeclara un endpoint de la ruta de API.\n\nEl `?` se sustituye por `CONF.$api` (por defecto `/api/`, sin volver a añadir `CONF.$root`). Todos los endpoints comparten una ruta `POST`. El cuerpo de la petición es `{ schema: \"endpoint/param?query\", data: {...} }`: `$.params` se rellena con las partes de la ruta de `schema`, `$.query` con la parte que va después de `?`, y `data` pasa a ser el cuerpo. `+API` y `-API` comprueban el usuario en cada endpoint. Un parámetro que falta es un error para `params.<name>`; un endpoint desconocido, o un cuerpo sin `schema`, recibe `400`. El flag de timeout se aplica al endpoint y el mayor flag de tamaño a la ruta compartida.\n\nExample: Endpoints\n```js\nexports.install = function() {\n\tROUTE('API ? tasks_list --> Tasks/list');\n\tROUTE('+API ? tasks_read/{id} --> Tasks/read');\n\tROUTE('+API ? tasks_save <5MB --> Tasks/save');\n};\n```\n\nExample: Una función en lugar de acciones\n```js\nexports.install = function() {\n\tROUTE('API ? ping', function($) {\n\t\t$.success();\n\t});\n};\n```\n\nExample: Cliente\n```js\nAJAX('POST /api/', { schema: 'tasks_read/42', data: null }, function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')\n\nType: `type`\n\nEjecuta acciones en lugar de una función.\n\nLos nombres después de `-->` son acciones declaradas con `NEWACTION()`, separadas por espacios o comas. El cuerpo de la petición es el payload, y se pasan `$.params`, `$.query` y `$.user`. El resultado se envía como respuesta y un error, con `$.invalid()`. Con varias acciones, marca con `(response)` aquella cuyo resultado es la respuesta; si hay una sola acción, esa es la respuesta.\n\nExample: Una acción\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/ --> Users/list');\n};\n```\n\nExample: Insertar y volver a leer\n```js\nexports.install = function() {\n\tROUTE('+POST /api/users/ --> Users/insert Users/read (response)');\n};\n```\n\n### ROUTE('METHOD /path/ <10MB', action)\n\nType: `type`\n\nEstablece el tamaño máximo del cuerpo de la petición.\n\nUnidades: `b` (bytes), `kB` (kilobytes, 1024 bytes), `MB` (megabytes) y `GB` (gigabytes); la unidad es obligatoria. A un cuerpo mayor se responde con `431`. Sin el flag el límite es `CONF.$httpmaxsize` kB (`CONF.$wsmaxsize` kB para las rutas `SOCKET`).\n\nExample: Subidas de hasta 50 MB\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <50MB', upload);\n};\n```\n\n### ROUTE('METHOD /path/ <30s', action)\n\nType: `type`\n\nEstablece el timeout de la petición.\n\nUnidades: `s` (segundos), `m` (minutos) y `h` (horas). Cuando la acción no responde a tiempo, la petición termina con `503`. Sin el flag, el timeout es `CONF.$httptimeout` segundos. El timeout se comprueba cada 5 segundos.\n\nExample: Una exportación larga\n```js\nexports.install = function() {\n\tROUTE('GET /export/ <10m', exportdata);\n};\n```\n\n### ROUTE('METHOD /path/ #name', action)\n\nType: `type`\n\nEjecuta un middleware antes de la acción.\n\nEl nombre debe estar registrado con `MIDDLEWARE(name, fn)`. Varios `#names` se ejecutan en el orden escrito; un nombre desconocido se omite. Los nombres de middleware contienen letras, dígitos y `_`.\n\nExample: Dos middleware\n```js\nMIDDLEWARE('cors_api', function($, next) {\n\t$.response.headers['x-api'] = '1';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/stats/ #cors_api #nocache', stats);\n};\n```\n\n### ROUTE('METHOD /path/ @json', action)\n\nType: `type`\n\nLa ruta solo coincide cuando el cuerpo de la petición es JSON (`application/json` o `text/json`).\n\nSi la petición no cumple la condición, el router prueba la siguiente ruta con el mismo método y la misma ruta. Cada flag baja en uno la prioridad de la ruta, así que primero se comprueba una ruta con menos flags.\n\nExample: Uso\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/ @json', orders);\n};\n```\n\n### ROUTE('METHOD /path/ @xml', action)\n\nType: `type`\n\nLa ruta solo coincide cuando el cuerpo de la petición es XML (`application/xml` o `text/xml`).\n\nSi la petición no cumple la condición, el router prueba la siguiente ruta con el mismo método y la misma ruta. Cada flag baja en uno la prioridad de la ruta, así que primero se comprueba una ruta con menos flags.\n\nExample: Uso\n```js\nexports.install = function() {\n\tROUTE('POST /feed/ @xml', feed);\n};\n```\n\n### ROUTE('METHOD /path/ @upload', action)\n\nType: `type`\n\nLa ruta solo coincide cuando el cuerpo de la petición es `multipart/form-data`.\n\nSi la petición no cumple la condición, el router prueba la siguiente ruta con el mismo método y la misma ruta. Cada flag baja en uno la prioridad de la ruta, así que primero se comprueba una ruta con menos flags.\n\nExample: Uso\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', function($) {\n\t\t$.json($.files.map(f => f.filename));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @xhr', action)\n\nType: `type`\n\nLa ruta solo coincide cuando la petición tiene la cabecera `X-Requested-With: XMLHttpRequest`.\n\nSi la petición no cumple la condición, el router prueba la siguiente ruta con el mismo método y la misma ruta. Cada flag baja en uno la prioridad de la ruta, así que primero se comprueba una ruta con menos flags.\n\nExample: Uso\n```js\nexports.install = function() {\n\tROUTE('GET /partials/menu/ @xhr', 'partials/menu');\n};\n```\n\n### ROUTE('METHOD /path/ @mobile', action)\n\nType: `type`\n\nLa ruta solo coincide cuando el cliente es un dispositivo móvil.\n\nSi la petición no cumple la condición, el router prueba la siguiente ruta con el mismo método y la misma ruta. Cada flag baja en uno la prioridad de la ruta, así que primero se comprueba una ruta con menos flags.\n\nExample: Uso\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /m/ @mobile', 'mobile');\n};\n```\n\n### ROUTE('METHOD /path/ @robot', action)\n\nType: `type`\n\nLa ruta solo coincide cuando el cliente es un crawler.\n\nSi la petición no cumple la condición, el router prueba la siguiente ruta con el mismo método y la misma ruta. Cada flag baja en uno la prioridad de la ruta, así que primero se comprueba una ruta con menos flags.\n\nExample: Uso\n```js\nexports.install = function() {\n\tROUTE('GET /prerender/ @robot', 'static');\n};\n```\n\n### ROUTE('METHOD /path/ @referrer', action)\n\nType: `type`\n\nLa ruta solo coincide cuando la cabecera `Referer` contiene el host de la petición; `@referer` es el mismo flag.\n\nSi la petición no cumple la condición, el router prueba la siguiente ruta con el mismo método y la misma ruta. Cada flag baja en uno la prioridad de la ruta, así que primero se comprueba una ruta con menos flags.\n\nExample: Uso\n```js\nexports.install = function() {\n\tROUTE('GET /download/ @referrer', download);\n};\n```\n\n### ROUTE('METHOD /path/ @debug', action)\n\nType: `type`\n\nLa ruta solo coincide cuando la aplicación se ejecuta en modo debug.\n\nSi la petición no cumple la condición, el router prueba la siguiente ruta con el mismo método y la misma ruta. Cada flag baja en uno la prioridad de la ruta, así que primero se comprueba una ruta con menos flags.\n\nExample: Uso\n```js\nexports.install = function() {\n\tROUTE('GET /dev/routes/ @debug', function($) {\n\t\t$.json(F.routes.routes.map(r => r.method + ' ' + r.url2));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @release', action)\n\nType: `type`\n\nLa ruta solo coincide cuando la aplicación se ejecuta en modo release.\n\nSi la petición no cumple la condición, el router prueba la siguiente ruta con el mismo método y la misma ruta. Cada flag baja en uno la prioridad de la ruta, así que primero se comprueba una ruta con menos flags.\n\nExample: Uso\n```js\nexports.install = function() {\n\tROUTE('GET /status/ @release', status);\n};\n```\n\n### ROUTE('FILE /path/pattern', action)\n\nType: `type`\n\nGestiona con tu código las peticiones de archivos estáticos.\n\nLas rutas de archivos se comprueban para las URL con extensión. Patrones: un archivo fijo (`/robots.txt`), extensiones en una carpeta (`/docs/*.md|txt`), todos los archivos de una carpeta (`/downloads/*`) y una extensión en cualquier lugar (`*.webp`). La acción recibe el controlador; responde con `$.file()`, `$.image()`, `$.plain()` o `$.resume()` (sirve el archivo desde `/public/`). Una petición que no toma ninguna ruta se sirve desde `/public/` cuando su extensión está en `CONF.$httpfiles`, o recibe `404`.\n\nExample: robots.txt generado\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', function($) {\n\t\t$.plain('User-agent: *\\nDisallow: /admin/');\n\t});\n};\n```\n\nExample: Archivos de una carpeta privada\n```js\nexports.install = function() {\n\tROUTE('FILE /files/*.pdf|docx', function($) {\n\t\t$.file(PATH.databases($.split[1]), true);\n\t});\n};\n```\n\n### ROUTE('SOCKET /path/ [flags]', action)\n\nType: `type`\n\nDeclara un endpoint WebSocket.\n\n`WEBSOCKET` es el mismo método. La ruta, `+`/`-`, `{params}`, `#middleware` y el flag de tamaño funcionan como en las rutas HTTP; el tamaño de mensaje por defecto es `CONF.$wsmaxsize` kB. Consulta [WebSockets](../../guides/websockets/).\n\nExample: Chat\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /chat/{room}/ <1MB', chat);\n};\n```\n\n### ROUTE('#code', action)\n\nType: `type`\n\nSustituye la página de error por defecto para un código de estado.\n\nCuando el framework responde con ese código (por ejemplo `404`, `401`, `431` o `503`), llama a tu acción con el controlador en lugar de renderizar la página de error integrada.\n\nExample: 404 personalizado\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n### Route\n\nType: `class`\n\nEl objeto que devuelve ROUTE().\n\nDescribe una ruta parseada. Lees sus propiedades o llamas a `remove()`; no las cambies después de que se ordenen las rutas. El controlador de una petición tiene su ruta en `$.route`.\n\nExample: Inspeccionar una ruta\n```js\nvar route = ROUTE('+POST /api/orders/ @json <2MB', create);\nconsole.log(route.method, route.auth, route.size, route.flags);\n```\n\n### route.method\n\nType: `property`\n\nEl método HTTP en mayúsculas, sin `+` ni `-`.\n\nReturns: `String`\n\nLas rutas `API` tienen `POST`. Las rutas `FILE` y `SOCKET` conservan el nombre de su método.\n\n### route.url\n\nType: `property`\n\nLa ruta dividida en segmentos en minúsculas.\n\nReturns: `Array`\n\nLos segmentos de parámetro conservan su forma `{name}`. La ruta tal como se escribió (con `CONF.$root`) está en `route.url2`.\n\n### route.params\n\nType: `property`\n\nLos parámetros dinámicos de la ruta.\n\nReturns: `Array`\n\nCada elemento tiene `name` e `index`, la posición del segmento en la ruta.\n\n### route.flags\n\nType: `property`\n\nLos flags `@` de la ruta como objeto.\n\nReturns: `Object`\n\nPor ejemplo, `@json @xhr` da `{ json: 1, xhr: 1 }`.\n\n### route.middleware\n\nType: `property`\n\nLos nombres de los middleware que se ejecutan antes de la acción.\n\nReturns: `Array`\n\nLos flags `#name` en su orden. `MIDDLEWARE(name, fn, assign)` puede añadir nombres a rutas existentes.\n\n### route.auth\n\nType: `property`\n\nLa autorización de la ruta.\n\nReturns: `Number`\n\n`0` para todo el mundo, `1` para usuarios con sesión iniciada (`+`), `2` para visitantes sin sesión iniciada (`-`). La ruta compartida de la API tiene `0`; cada endpoint conserva su propio valor.\n\n### route.size\n\nType: `property`\n\nEl tamaño máximo del cuerpo en bytes.\n\nReturns: `Number`\n\nLo establece el flag de tamaño o el argumento `size`; si no, `CONF.$httpmaxsize * 1024` (`CONF.$wsmaxsize * 1024` en las rutas `SOCKET`).\n\n### route.timeout\n\nType: `property`\n\nEl timeout en segundos, o `0`.\n\nReturns: `Number`\n\n`0` significa que la petición usa `CONF.$httptimeout`.\n\n### route.priority\n\nType: `property`\n\nEl orden en que se comprueban las rutas con el mismo método y la misma ruta.\n\nReturns: `Number`\n\nEmpieza en `100`, cada flag `@` lo baja en uno y un comodín en 50. Los valores más altos se comprueban primero.\n\n### route.type\n\nType: `property`\n\nEl tipo de ruta.\n\nReturns: `String`\n\n`route`, `file` o `websocket`.\n\n### route.remove()\n\nType: `method`\n\nElimina la ruta.\n\nReturns: `undefined`\n\nDa de baja la ruta y vuelve a ordenar la tabla de enrutamiento. Funciona para rutas HTTP, endpoints API (la ruta `POST` compartida de la API se elimina con su último endpoint), rutas `FILE` y rutas `SOCKET`, cuyas conexiones abiertas se cierran.\n\nExample: Una ruta temporal\n```js\nvar route = ROUTE('GET /maintenance/', function($) {\n\t$.plain('Back soon');\n});\n\nsetTimeout(function() {\n\troute.remove();\n}, 60000);\n```\n\n### CORS([origins])\n\nType: `method`\n\nEstablece los orígenes permitidos para las peticiones cross-origin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `origins` | `String` | no | `'*'` | Los orígenes permitidos, `*`, o `+origins` para añadir. |\n\nReturns: `undefined`\n\nSin argumento, se permite cualquier origen (`*`). Si no, indica orígenes completos separados por comas, `;` o `|`. Un elemento que empieza por `*` permite cualquier origen que contenga el resto. Un valor que empieza por `+` añade orígenes a la lista actual. Las peticiones del mismo host siempre pasan. Una petición permitida recibe `Access-Control-Allow-Origin` (el origen), `-Credentials: true`, `-Methods`, `-Headers` y `-Expose-Headers` (`*`), y `OPTIONS` se responde de inmediato. Los demás orígenes reciben `400` con `Invalid origin (CORS)`.\n\nExample: Permitir dos apps\n```js\nCORS('https://app.example.com,https://admin.example.com');\n```\n\nExample: Añadir uno y permitir subdominios\n```js\nCORS('+https://partner.com');\nCORS('+*example.org');\n```\n\nExample: Cualquier origen\n```js\nCORS();\n```\n\n### PROXY(path, [target])\n\nType: `method`\n\nReenvía a otro servidor las peticiones bajo una ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | El comienzo de la ruta de la petición, por ejemplo `/cdn/`. |\n| `target` | `String|Function` | no |  | La URL de destino, la ruta de un socket Unix, o `function($)`. |\n\nReturns: `Proxy` El objeto proxy con métodos encadenables, o nada cuando eliminas un proxy.\n\nLos proxies se comprueban antes que las rutas, para cualquier método y para los upgrades de WebSocket. `path` debe terminar en `/` y recibe `CONF.$root`. `target` es una URL `http://`/`https://`, la ruta de un socket Unix, o una función que recibe el controlador y responde ella misma. La petición reenviada conserva las cabeceras (sin `Host`) y recibe `X-Forwarded-For`, `X-Forwarded-URL` y `X-Forwarded-Host`. Cuando el destino falla, el cliente recibe `503`. `PROXY(path)` sin destino elimina el proxy de esa ruta.\n\nExample: Reenviar a un servicio\n```js\nPROXY('/search/', 'http://127.0.0.1:9200').copy('replace');\n```\n\nExample: Socket Unix\n```js\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nExample: Handler propio\n```js\nPROXY('/ping/', function($) {\n\t$.plain('pong');\n});\n```\n\n### proxy.copy(type)\n\nType: `method`\n\nEstablece cómo se copia la ruta de la petición al destino.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `none`, `replace` o `extend`. |\n\nReturns: `Proxy` El proxy.\n\n`none` (por defecto): la URL de destino con el query string de la petición. `replace`: el destino con la parte de la ruta que va después de la ruta del proxy (cuando la URL de destino tiene su propia ruta, `replace` funciona como `extend`). `extend`: la ruta de destino, más el resto de la ruta de la petición, más los query strings de la petición y del destino.\n\nExample: Conservar las subrutas\n```js\n// GET /cl/something/?q=1 --> https://example.com/something/?q=1\nPROXY('/cl/', 'https://example.com').copy('extend');\n```\n\n### proxy.before(callback)\n\nType: `method`\n\nModifica la petición saliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(uri, $)`. |\n\nReturns: `Proxy` El proxy.\n\n`callback(uri, $)` se ejecuta antes de enviar la petición. `uri` contiene las opciones de la petición de Node.js (`path`, `headers`, `method`...).\n\nExample: Añadir un token\n```js\nPROXY('/api2/', 'https://internal.example.com').before(function(uri, $) {\n\turi.headers['x-token'] = CONF.internal_token;\n});\n```\n\n### proxy.after(callback)\n\nType: `method`\n\nLee la respuesta del destino.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(response)`. |\n\nReturns: `Proxy` El proxy.\n\n`callback(response)` recibe la respuesta de Node.js antes de enviarla al cliente; puedes cambiar `response.headers`.\n\nExample: Eliminar una cabecera\n```js\nPROXY('/cdn/', 'https://cdn.example.com').after(function(response) {\n\tdelete response.headers['set-cookie'];\n});\n```\n\n### proxy.check(callback)\n\nType: `method`\n\nDecide en cada petición si se usa el proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)` que devuelve un booleano. |\n\nReturns: `Proxy` El proxy.\n\n`callback($)` devuelve `true` para reenviar la petición. Si no, la petición va a las rutas.\n\nExample: Solo GET\n```js\nPROXY('/files/', 'http://127.0.0.1:8001').check($ => $.method === 'GET');\n```\n\n### proxy.timeout(ms)\n\nType: `method`\n\nEstablece el timeout de la petición reenviada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes |  | El timeout en milisegundos. |\n\nReturns: `Proxy` El proxy.\n\nEn milisegundos. Sin él (o con `0`) el proxy usa `CONF.$proxytimeout` segundos.\n\nExample: 30 segundos\n```js\nPROXY('/reports/', 'http://127.0.0.1:8002').timeout(30000);\n```\n\n### proxy.remove()\n\nType: `method`\n\nElimina el proxy.\n\nReturns: `undefined`\n\nLas peticiones bajo su ruta vuelven a ir a las rutas. `PROXY(path)` sin destino hace lo mismo.\n\nExample: Eliminar\n```js\nvar proxy = PROXY('/old/', 'http://127.0.0.1:8003');\nproxy.remove();\n```\n\n### $api : /api/\n\nType: `config`\n\nLa ruta que representa `?` en las rutas de API.\n\nReturns: `String`\n\nPor defecto `/api/`. Cuando `$root` está establecido, se añade delante.\n\nExample: /config\n```js\n$api : /rpc/\n```\n\n### $root : /app/\n\nType: `config`\n\nUn prefijo de ruta para todas las rutas.\n\nReturns: `String`\n\nSe antepone a cada ruta, proxy y ruta `$api`, por ejemplo cuando la app se ejecuta bajo `/app/` detrás de un servidor web. Por defecto vacío.\n\nExample: /config\n```js\n$root : /admin/\n```\n\n### $cors : https://app.example.com\n\nType: `config`\n\nLos orígenes permitidos para las peticiones cross-origin.\n\nReturns: `String`\n\nEl mismo valor que acepta `CORS()`: `*`, u orígenes separados por comas, con elementos `*domain` para coincidencias parciales. Por defecto vacío (las peticiones cross-origin no se comprueban).\n\nExample: /config\n```js\n$cors : https://app.example.com, *example.org\n```\n\n### $httpmaxsize : 256\n\nType: `config`\n\nEl tamaño máximo del cuerpo por defecto de las rutas HTTP, en kB.\n\nReturns: `Number`\n\nPor defecto `256`. Una ruta lo sobrescribe con un flag de tamaño.\n\nExample: /config\n```js\n$httpmaxsize : 1024\n```\n\n### $httptimeout : 5\n\nType: `config`\n\nEl timeout por defecto de las peticiones HTTP, en segundos.\n\nReturns: `Number`\n\nPor defecto `5`. Una ruta lo sobrescribe con un flag de timeout.\n\nExample: /config\n```js\n$httptimeout : 15\n```\n\n### $proxytimeout : 5\n\nType: `config`\n\nEl timeout por defecto de las peticiones de `PROXY()`, en segundos.\n\nReturns: `Number`\n\nPor defecto `5`. `proxy.timeout()` lo sobrescribe para un proxy.\n\nExample: /config\n```js\n$proxytimeout : 30\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [size])","since":"","deprecated":false},{"type":"type","name":"+ flag","signature":"ROUTE('+METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"- flag","signature":"ROUTE('-METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"{param}","signature":"ROUTE('GET /path/{name}/', action)","since":"","deprecated":false},{"type":"type","name":"* wildcard","signature":"ROUTE('GET /path/*', action)","since":"","deprecated":false},{"type":"type","name":"API ?","signature":"ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])","since":"","deprecated":false},{"type":"type","name":"--> actions","signature":"ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')","since":"","deprecated":false},{"type":"type","name":"<size","signature":"ROUTE('METHOD /path/ <10MB', action)","since":"","deprecated":false},{"type":"type","name":"<timeout","signature":"ROUTE('METHOD /path/ <30s', action)","since":"","deprecated":false},{"type":"type","name":"#middleware","signature":"ROUTE('METHOD /path/ #name', action)","since":"","deprecated":false},{"type":"type","name":"@json","signature":"ROUTE('METHOD /path/ @json', action)","since":"","deprecated":false},{"type":"type","name":"@xml","signature":"ROUTE('METHOD /path/ @xml', action)","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('METHOD /path/ @upload', action)","since":"","deprecated":false},{"type":"type","name":"@xhr","signature":"ROUTE('METHOD /path/ @xhr', action)","since":"","deprecated":false},{"type":"type","name":"@mobile","signature":"ROUTE('METHOD /path/ @mobile', action)","since":"","deprecated":false},{"type":"type","name":"@robot","signature":"ROUTE('METHOD /path/ @robot', action)","since":"","deprecated":false},{"type":"type","name":"@referrer","signature":"ROUTE('METHOD /path/ @referrer', action)","since":"","deprecated":false},{"type":"type","name":"@debug","signature":"ROUTE('METHOD /path/ @debug', action)","since":"","deprecated":false},{"type":"type","name":"@release","signature":"ROUTE('METHOD /path/ @release', action)","since":"","deprecated":false},{"type":"type","name":"FILE","signature":"ROUTE('FILE /path/pattern', action)","since":"","deprecated":false},{"type":"type","name":"SOCKET","signature":"ROUTE('SOCKET /path/ [flags]', action)","since":"","deprecated":false},{"type":"type","name":"#code","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"class","name":"Route","signature":"Route","since":"","deprecated":false},{"type":"property","name":"route.method","signature":"route.method","since":"","deprecated":false},{"type":"property","name":"route.url","signature":"route.url","since":"","deprecated":false},{"type":"property","name":"route.params","signature":"route.params","since":"","deprecated":false},{"type":"property","name":"route.flags","signature":"route.flags","since":"","deprecated":false},{"type":"property","name":"route.middleware","signature":"route.middleware","since":"","deprecated":false},{"type":"property","name":"route.auth","signature":"route.auth","since":"","deprecated":false},{"type":"property","name":"route.size","signature":"route.size","since":"","deprecated":false},{"type":"property","name":"route.timeout","signature":"route.timeout","since":"","deprecated":false},{"type":"property","name":"route.priority","signature":"route.priority","since":"","deprecated":false},{"type":"property","name":"route.type","signature":"route.type","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([origins])","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(path, [target])","since":"","deprecated":false},{"type":"method","name":"proxy.copy()","signature":"proxy.copy(type)","since":"","deprecated":false},{"type":"method","name":"proxy.before()","signature":"proxy.before(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.after()","signature":"proxy.after(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.check()","signature":"proxy.check(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.timeout()","signature":"proxy.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"proxy.remove()","signature":"proxy.remove()","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : /api/","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root : /app/","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : https://app.example.com","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : 5","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : 5","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JaedEABfT60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/routing/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Routage","summary":"Syntaxe de ROUTE(), flags, l'objet route, CORS(), PROXY() et la configuration du routage.","markdown":"---\ntitle: Routage\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/routing/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Routage\n\n> Syntaxe de ROUTE(), flags, l'objet route, CORS(), PROXY() et la configuration du routage.\n\nChaque partie de la chaîne de `ROUTE()` (préfixes de méthode, paramètres, flags, actions et points d'accès d'API), l'objet route, `CORS()`, `PROXY()` et les clés de configuration du routage. Le guide [Routage](../../guides/routing/) les explique avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### ROUTE(url, [action], [size])\n\nType: `method`\n\nDéclare une route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La méthode, le chemin et les flags, par exemple `+POST /api/orders/ @json <1MB`. |\n| `action` | `Function|String` | no |  | Une fonction appelée avec le contrôleur, ou le nom d'une vue. Sans elle, une vue nommée d'après le premier segment du chemin est rendue (`index` pour `/`). |\n| `size` | `Number` | no | `CONF.$httpmaxsize` | La taille maximale du corps en octets. Elle peut être le deuxième argument quand il n'y a pas d'action. |\n\nReturns: `Route` L'objet route.\n\n`url` est une seule chaîne : la méthode (avec un préfixe facultatif `+` ou `-`), le chemin et des flags facultatifs, des actions après `-->` et des points d'accès d'API après `?`. Les routes sont triées 100 ms après le dernier appel de `ROUTE()`. Un chemin qui commence par `#` déclare une route d'erreur. La fonction globale `ROUTE` est la même fonction que `F.route`.\n\nExample: Une page et un point d'accès JSON\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n\nfunction index($) {\n\t$.view('index');\n}\n```\n\nExample: Une vue sans code\n```js\nexports.install = function() {\n\tROUTE('GET /contact/', 'contact');\n\tROUTE('GET /about/');\n};\n```\n\n### ROUTE('+METHOD /path/', action)\n\nType: `type`\n\nLa route est réservée aux utilisateurs connectés.\n\nLe délégué `AUTH()` doit renvoyer un utilisateur ; sans `AUTH()`, le préfixe n'est pas vérifié et la route sert tout le monde. Quand l'utilisateur n'est pas connecté et qu'aucune autre route de l'URL n'accepte les visiteurs, la réponse est `401`. L'utilisateur se trouve dans `$.user`.\n\nExample: Une page de compte\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', function($) {\n\t\t$.json($.user);\n\t});\n};\n```\n\n### ROUTE('-METHOD /path/', action)\n\nType: `type`\n\nLa route est réservée aux visiteurs non connectés.\n\nUtilise-la avec une route `+` de la même URL pour afficher un contenu différent aux utilisateurs connectés et aux visiteurs. Un utilisateur connecté qui n'atteint qu'une route `-` reçoit `401`.\n\nExample: Connexion ou compte\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n};\n```\n\n### ROUTE('GET /path/{name}/', action)\n\nType: `type`\n\nUn segment dynamique du chemin.\n\nLa valeur du segment est stockée dans `$.params` sous son nom, sous forme de chaîne avec la casse de l'URL de la requête. Un paramètre occupe un segment entier. Une route avec des paramètres ne correspond qu'aux URL ayant le même nombre de segments.\n\nExample: Deux paramètres\n```js\nexports.install = function() {\n\tROUTE('GET /blog/{year}/{slug}/', function($) {\n\t\t$.json({ year: $.params.year, slug: $.params.slug });\n\t});\n};\n```\n\n### ROUTE('GET /path/*', action)\n\nType: `type`\n\nCorrespond au chemin et à tout ce qui se trouve en dessous.\n\nUne route joker a une priorité plus basse que les routes fixes et dynamiques, elle n'attrape donc que les URL qu'aucune autre route ne prend.\n\nExample: Une route fourre-tout pour une section\n```js\nexports.install = function() {\n\tROUTE('GET /app/*', 'app');\n};\n```\n\n### ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])\n\nType: `type`\n\nDéclare un point d'accès de la route d'API.\n\nLe `?` est remplacé par `CONF.$api` (par défaut `/api/`, sans que `CONF.$root` soit ajouté une seconde fois). Tous les points d'accès partagent une seule route `POST`. Le corps de la requête est `{ schema: \"endpoint/param?query\", data: {...} }` : `$.params` est rempli à partir des parties du chemin de `schema`, `$.query` à partir de la partie après `?`, et `data` devient le corps. `+API` et `-API` vérifient l'utilisateur pour chaque point d'accès. Un paramètre manquant est une erreur pour `params.<name>` ; un point d'accès inconnu, ou un corps sans `schema`, reçoit `400`. Le flag de timeout s'applique au point d'accès et le plus grand flag de taille à la route partagée.\n\nExample: Points d'accès\n```js\nexports.install = function() {\n\tROUTE('API ? tasks_list --> Tasks/list');\n\tROUTE('+API ? tasks_read/{id} --> Tasks/read');\n\tROUTE('+API ? tasks_save <5MB --> Tasks/save');\n};\n```\n\nExample: Une fonction au lieu d'actions\n```js\nexports.install = function() {\n\tROUTE('API ? ping', function($) {\n\t\t$.success();\n\t});\n};\n```\n\nExample: Client\n```js\nAJAX('POST /api/', { schema: 'tasks_read/42', data: null }, function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')\n\nType: `type`\n\nExécute des actions au lieu d'une fonction.\n\nLes noms après `-->` sont des actions déclarées avec `NEWACTION()`, séparées par des espaces ou des virgules. Le corps de la requête est le payload, et `$.params`, `$.query` et `$.user` sont transmis. Le résultat est envoyé comme réponse et une erreur avec `$.invalid()`. Avec plusieurs actions, marque avec `(response)` celle dont le résultat constitue la réponse ; une action unique constitue la réponse.\n\nExample: Une action\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/ --> Users/list');\n};\n```\n\nExample: Insérer et relire\n```js\nexports.install = function() {\n\tROUTE('+POST /api/users/ --> Users/insert Users/read (response)');\n};\n```\n\n### ROUTE('METHOD /path/ <10MB', action)\n\nType: `type`\n\nDéfinit la taille maximale du corps de la requête.\n\nUnités : `b` (octets), `kB` (kilooctets, 1024 octets), `MB` (mégaoctets) et `GB` (gigaoctets) ; l'unité est obligatoire. Un corps plus grand reçoit en réponse `431`. Sans le flag, la limite est `CONF.$httpmaxsize` ko (`CONF.$wsmaxsize` ko pour les routes `SOCKET`).\n\nExample: Uploads jusqu'à 50 Mo\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <50MB', upload);\n};\n```\n\n### ROUTE('METHOD /path/ <30s', action)\n\nType: `type`\n\nDéfinit le timeout de la requête.\n\nUnités : `s` (secondes), `m` (minutes) et `h` (heures). Quand l'action ne répond pas à temps, la requête se termine avec `503`. Sans le flag, le timeout est de `CONF.$httptimeout` secondes. Le timeout est vérifié toutes les 5 secondes.\n\nExample: Un long export\n```js\nexports.install = function() {\n\tROUTE('GET /export/ <10m', exportdata);\n};\n```\n\n### ROUTE('METHOD /path/ #name', action)\n\nType: `type`\n\nExécute un middleware avant l'action.\n\nLe nom doit être enregistré avec `MIDDLEWARE(name, fn)`. Plusieurs `#names` s'exécutent dans l'ordre écrit ; un nom inconnu est ignoré. Les noms de middleware contiennent des lettres, des chiffres et `_`.\n\nExample: Deux middlewares\n```js\nMIDDLEWARE('cors_api', function($, next) {\n\t$.response.headers['x-api'] = '1';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/stats/ #cors_api #nocache', stats);\n};\n```\n\n### ROUTE('METHOD /path/ @json', action)\n\nType: `type`\n\nLa route ne correspond que quand le corps de la requête est du JSON (`application/json` ou `text/json`).\n\nSi la requête ne remplit pas la condition, le routeur essaie la route suivante avec la même méthode et le même chemin. Chaque flag abaisse la priorité de la route d'un point, donc une route avec moins de flags est vérifiée en premier.\n\nExample: Utilisation\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/ @json', orders);\n};\n```\n\n### ROUTE('METHOD /path/ @xml', action)\n\nType: `type`\n\nLa route ne correspond que quand le corps de la requête est du XML (`application/xml` ou `text/xml`).\n\nSi la requête ne remplit pas la condition, le routeur essaie la route suivante avec la même méthode et le même chemin. Chaque flag abaisse la priorité de la route d'un point, donc une route avec moins de flags est vérifiée en premier.\n\nExample: Utilisation\n```js\nexports.install = function() {\n\tROUTE('POST /feed/ @xml', feed);\n};\n```\n\n### ROUTE('METHOD /path/ @upload', action)\n\nType: `type`\n\nLa route ne correspond que quand le corps de la requête est `multipart/form-data`.\n\nSi la requête ne remplit pas la condition, le routeur essaie la route suivante avec la même méthode et le même chemin. Chaque flag abaisse la priorité de la route d'un point, donc une route avec moins de flags est vérifiée en premier.\n\nExample: Utilisation\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', function($) {\n\t\t$.json($.files.map(f => f.filename));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @xhr', action)\n\nType: `type`\n\nLa route ne correspond que quand la requête contient l'en-tête `X-Requested-With: XMLHttpRequest`.\n\nSi la requête ne remplit pas la condition, le routeur essaie la route suivante avec la même méthode et le même chemin. Chaque flag abaisse la priorité de la route d'un point, donc une route avec moins de flags est vérifiée en premier.\n\nExample: Utilisation\n```js\nexports.install = function() {\n\tROUTE('GET /partials/menu/ @xhr', 'partials/menu');\n};\n```\n\n### ROUTE('METHOD /path/ @mobile', action)\n\nType: `type`\n\nLa route ne correspond que quand le client est un appareil mobile.\n\nSi la requête ne remplit pas la condition, le routeur essaie la route suivante avec la même méthode et le même chemin. Chaque flag abaisse la priorité de la route d'un point, donc une route avec moins de flags est vérifiée en premier.\n\nExample: Utilisation\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /m/ @mobile', 'mobile');\n};\n```\n\n### ROUTE('METHOD /path/ @robot', action)\n\nType: `type`\n\nLa route ne correspond que quand le client est un robot d'indexation.\n\nSi la requête ne remplit pas la condition, le routeur essaie la route suivante avec la même méthode et le même chemin. Chaque flag abaisse la priorité de la route d'un point, donc une route avec moins de flags est vérifiée en premier.\n\nExample: Utilisation\n```js\nexports.install = function() {\n\tROUTE('GET /prerender/ @robot', 'static');\n};\n```\n\n### ROUTE('METHOD /path/ @referrer', action)\n\nType: `type`\n\nLa route ne correspond que quand l'en-tête `Referer` contient l'hôte de la requête ; `@referer` est le même flag.\n\nSi la requête ne remplit pas la condition, le routeur essaie la route suivante avec la même méthode et le même chemin. Chaque flag abaisse la priorité de la route d'un point, donc une route avec moins de flags est vérifiée en premier.\n\nExample: Utilisation\n```js\nexports.install = function() {\n\tROUTE('GET /download/ @referrer', download);\n};\n```\n\n### ROUTE('METHOD /path/ @debug', action)\n\nType: `type`\n\nLa route ne correspond que quand l'application tourne en mode debug.\n\nSi la requête ne remplit pas la condition, le routeur essaie la route suivante avec la même méthode et le même chemin. Chaque flag abaisse la priorité de la route d'un point, donc une route avec moins de flags est vérifiée en premier.\n\nExample: Utilisation\n```js\nexports.install = function() {\n\tROUTE('GET /dev/routes/ @debug', function($) {\n\t\t$.json(F.routes.routes.map(r => r.method + ' ' + r.url2));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @release', action)\n\nType: `type`\n\nLa route ne correspond que quand l'application tourne en mode release.\n\nSi la requête ne remplit pas la condition, le routeur essaie la route suivante avec la même méthode et le même chemin. Chaque flag abaisse la priorité de la route d'un point, donc une route avec moins de flags est vérifiée en premier.\n\nExample: Utilisation\n```js\nexports.install = function() {\n\tROUTE('GET /status/ @release', status);\n};\n```\n\n### ROUTE('FILE /path/pattern', action)\n\nType: `type`\n\nTraite les requêtes de fichiers statiques avec ton code.\n\nLes routes de fichiers sont vérifiées pour les URL avec une extension. Motifs : un fichier fixe (`/robots.txt`), des extensions dans un dossier (`/docs/*.md|txt`), tous les fichiers d'un dossier (`/downloads/*`) et une extension n'importe où (`*.webp`). L'action reçoit le contrôleur ; réponds avec `$.file()`, `$.image()`, `$.plain()` ou `$.resume()` (sert le fichier depuis `/public/`). Une requête qu'aucune route ne prend est servie depuis `/public/` quand son extension figure dans `CONF.$httpfiles`, sinon elle reçoit `404`.\n\nExample: robots.txt généré\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', function($) {\n\t\t$.plain('User-agent: *\\nDisallow: /admin/');\n\t});\n};\n```\n\nExample: Fichiers d'un dossier privé\n```js\nexports.install = function() {\n\tROUTE('FILE /files/*.pdf|docx', function($) {\n\t\t$.file(PATH.databases($.split[1]), true);\n\t});\n};\n```\n\n### ROUTE('SOCKET /path/ [flags]', action)\n\nType: `type`\n\nDéclare un point d'accès WebSocket.\n\n`WEBSOCKET` est la même méthode. Le chemin, `+`/`-`, `{params}`, `#middleware` et le flag de taille fonctionnent comme dans les routes HTTP ; la taille de message par défaut est de `CONF.$wsmaxsize` kB. Voir [WebSockets](../../guides/websockets/).\n\nExample: Discussion\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /chat/{room}/ <1MB', chat);\n};\n```\n\n### ROUTE('#code', action)\n\nType: `type`\n\nRemplace la page d'erreur par défaut pour un code de statut.\n\nQuand le framework répond avec ce code (par exemple `404`, `401`, `431` ou `503`), il appelle ton action avec le contrôleur au lieu d'effectuer le rendu de la page d'erreur intégrée.\n\nExample: 404 personnalisée\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n### Route\n\nType: `class`\n\nL'objet que renvoie ROUTE().\n\nIl décrit une route analysée. Tu lis ses propriétés ou appelles `remove()` ; ne les modifie pas après le tri des routes. Le contrôleur d'une requête possède sa route dans `$.route`.\n\nExample: Inspecter une route\n```js\nvar route = ROUTE('+POST /api/orders/ @json <2MB', create);\nconsole.log(route.method, route.auth, route.size, route.flags);\n```\n\n### route.method\n\nType: `property`\n\nLa méthode HTTP en majuscules, sans `+` ni `-`.\n\nReturns: `String`\n\nLes routes `API` ont `POST`. Les routes `FILE` et `SOCKET` conservent leur nom de méthode.\n\n### route.url\n\nType: `property`\n\nLe chemin découpé en segments en minuscules.\n\nReturns: `Array`\n\nLes segments de paramètres conservent leur forme `{name}`. Le chemin tel qu'il a été écrit (avec `CONF.$root`) se trouve dans `route.url2`.\n\n### route.params\n\nType: `property`\n\nLes paramètres dynamiques du chemin.\n\nReturns: `Array`\n\nChaque élément possède `name` et `index`, la position du segment dans le chemin.\n\n### route.flags\n\nType: `property`\n\nLes flags `@` de la route sous forme d'objet.\n\nReturns: `Object`\n\nPar exemple `@json @xhr` donne `{ json: 1, xhr: 1 }`.\n\n### route.middleware\n\nType: `property`\n\nLes noms des middlewares qui s'exécutent avant l'action.\n\nReturns: `Array`\n\nLes flags `#name` dans leur ordre. `MIDDLEWARE(name, fn, assign)` peut ajouter des noms aux routes existantes.\n\n### route.auth\n\nType: `property`\n\nL'autorisation de la route.\n\nReturns: `Number`\n\n`0` pour tout le monde, `1` pour les utilisateurs connectés (`+`), `2` pour les visiteurs non connectés (`-`). La route partagée de l'API a `0` ; chaque point d'accès conserve sa propre valeur.\n\n### route.size\n\nType: `property`\n\nLa taille maximale du corps en octets.\n\nReturns: `Number`\n\nDéfinie par le flag de taille ou l'argument `size` ; sinon `CONF.$httpmaxsize * 1024` (`CONF.$wsmaxsize * 1024` pour les routes `SOCKET`).\n\n### route.timeout\n\nType: `property`\n\nLe timeout en secondes, ou `0`.\n\nReturns: `Number`\n\n`0` signifie que la requête utilise `CONF.$httptimeout`.\n\n### route.priority\n\nType: `property`\n\nL'ordre dans lequel les routes ayant la même méthode et le même chemin sont vérifiées.\n\nReturns: `Number`\n\nElle commence à `100`, chaque flag `@` l'abaisse d'un point et un joker de 50. Les valeurs les plus élevées sont vérifiées en premier.\n\n### route.type\n\nType: `property`\n\nLe type de route.\n\nReturns: `String`\n\n`route`, `file` ou `websocket`.\n\n### route.remove()\n\nType: `method`\n\nSupprime la route.\n\nReturns: `undefined`\n\nDésenregistre la route et trie à nouveau la table de routage. Cela fonctionne pour les routes HTTP, les endpoints d'API (la route `POST` partagée de l'API est supprimée avec son dernier endpoint), les routes `FILE` et les routes `SOCKET`, dont les connexions ouvertes sont fermées.\n\nExample: Une route temporaire\n```js\nvar route = ROUTE('GET /maintenance/', function($) {\n\t$.plain('Back soon');\n});\n\nsetTimeout(function() {\n\troute.remove();\n}, 60000);\n```\n\n### CORS([origins])\n\nType: `method`\n\nDéfinit les origines autorisées pour les requêtes cross-origin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `origins` | `String` | no | `'*'` | Les origines autorisées, `*`, ou `+origins` pour en ajouter. |\n\nReturns: `undefined`\n\nSans argument, toutes les origines sont autorisées (`*`). Sinon, indique des origines complètes séparées par des virgules, `;` ou `|`. Un élément qui commence par `*` autorise toute origine qui contient le reste. Une valeur qui commence par `+` ajoute des origines à la liste actuelle. Les requêtes provenant du même hôte passent toujours. Une requête autorisée reçoit `Access-Control-Allow-Origin` (l'origine), `-Credentials: true`, `-Methods`, `-Headers` et `-Expose-Headers` (`*`), et `OPTIONS` reçoit immédiatement une réponse. Les autres origines reçoivent `400` avec `Invalid origin (CORS)`.\n\nExample: Autoriser deux applications\n```js\nCORS('https://app.example.com,https://admin.example.com');\n```\n\nExample: En ajouter une et autoriser les sous-domaines\n```js\nCORS('+https://partner.com');\nCORS('+*example.org');\n```\n\nExample: N'importe quelle origine\n```js\nCORS();\n```\n\n### PROXY(path, [target])\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| `path` | `String` | yes |  | Le début du chemin de la requête, par exemple `/cdn/`. |\n| `target` | `String|Function` | no |  | L'URL cible, un chemin de socket Unix, ou `function($)`. |\n\nReturns: `Proxy` L'objet proxy avec des méthodes chaînables, ou rien quand tu supprimes un proxy.\n\nLes proxys sont vérifiés avant les routes, pour toutes les méthodes et pour les upgrades WebSocket. `path` doit se terminer par `/` et reçoit `CONF.$root`. `target` est une URL `http://`/`https://`, un chemin de socket Unix, ou une fonction qui reçoit le contrôleur et répond elle-même. La requête transmise conserve les en-têtes (sans `Host`) et reçoit `X-Forwarded-For`, `X-Forwarded-URL` et `X-Forwarded-Host`. Quand la cible échoue, le client reçoit `503`. `PROXY(path)` sans cible supprime le proxy de ce chemin.\n\nExample: Transmettre à un service\n```js\nPROXY('/search/', 'http://127.0.0.1:9200').copy('replace');\n```\n\nExample: Socket Unix\n```js\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nExample: Gestionnaire propre\n```js\nPROXY('/ping/', function($) {\n\t$.plain('pong');\n});\n```\n\n### proxy.copy(type)\n\nType: `method`\n\nDéfinit la façon dont le chemin de la requête est copié vers la cible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `none`, `replace` ou `extend`. |\n\nReturns: `Proxy` Le proxy.\n\n`none` (par défaut) : l'URL cible avec la query string de la requête. `replace` : la cible avec la partie du chemin située après le chemin du proxy (quand l'URL cible a son propre chemin, `replace` fonctionne comme `extend`). `extend` : le chemin de la cible, plus le reste du chemin de la requête, plus les query strings de la requête et de la cible.\n\nExample: Conserver les sous-chemins\n```js\n// GET /cl/something/?q=1 --> https://example.com/something/?q=1\nPROXY('/cl/', 'https://example.com').copy('extend');\n```\n\n### proxy.before(callback)\n\nType: `method`\n\nModifie la requête sortante.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(uri, $)`. |\n\nReturns: `Proxy` Le proxy.\n\n`callback(uri, $)` s'exécute avant l'envoi de la requête. `uri` contient les options de requête de Node.js (`path`, `headers`, `method`...).\n\nExample: Ajouter un jeton\n```js\nPROXY('/api2/', 'https://internal.example.com').before(function(uri, $) {\n\turi.headers['x-token'] = CONF.internal_token;\n});\n```\n\n### proxy.after(callback)\n\nType: `method`\n\nLit la réponse de la cible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(response)`. |\n\nReturns: `Proxy` Le proxy.\n\n`callback(response)` reçoit la réponse de Node.js avant son envoi au client ; tu peux modifier `response.headers`.\n\nExample: Supprimer un en-tête\n```js\nPROXY('/cdn/', 'https://cdn.example.com').after(function(response) {\n\tdelete response.headers['set-cookie'];\n});\n```\n\n### proxy.check(callback)\n\nType: `method`\n\nDécide pour chaque requête si le proxy est utilisé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)` qui renvoie un booléen. |\n\nReturns: `Proxy` Le proxy.\n\n`callback($)` renvoie `true` pour transmettre la requête. Sinon, la requête va vers les routes.\n\nExample: Seulement GET\n```js\nPROXY('/files/', 'http://127.0.0.1:8001').check($ => $.method === 'GET');\n```\n\n### proxy.timeout(ms)\n\nType: `method`\n\nDéfinit le timeout de la requête transmise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes |  | Le timeout en millisecondes. |\n\nReturns: `Proxy` Le proxy.\n\nEn millisecondes. Sans lui (ou avec `0`), le proxy utilise `CONF.$proxytimeout` secondes.\n\nExample: 30 secondes\n```js\nPROXY('/reports/', 'http://127.0.0.1:8002').timeout(30000);\n```\n\n### proxy.remove()\n\nType: `method`\n\nSupprime le proxy.\n\nReturns: `undefined`\n\nLes requêtes sous son chemin vont de nouveau vers les routes. `PROXY(path)` sans cible fait la même chose.\n\nExample: Supprimer\n```js\nvar proxy = PROXY('/old/', 'http://127.0.0.1:8003');\nproxy.remove();\n```\n\n### $api : /api/\n\nType: `config`\n\nLe chemin que représente `?` dans les routes d'API.\n\nReturns: `String`\n\nPar défaut `/api/`. Quand `$root` est défini, il est ajouté devant.\n\nExample: /config\n```js\n$api : /rpc/\n```\n\n### $root : /app/\n\nType: `config`\n\nUn préfixe de chemin pour toutes les routes.\n\nReturns: `String`\n\nChaque route, chaque proxy et le chemin `$api` en sont préfixés, par exemple quand l'application tourne sous `/app/` derrière un serveur web. Vide par défaut.\n\nExample: /config\n```js\n$root : /admin/\n```\n\n### $cors : https://app.example.com\n\nType: `config`\n\nLes origines autorisées pour les requêtes cross-origin.\n\nReturns: `String`\n\nLa même valeur que celle acceptée par `CORS()` : `*`, ou des origines séparées par des virgules, avec des éléments `*domain` pour les correspondances partielles. Vide par défaut (les requêtes cross-origin ne sont pas vérifiées).\n\nExample: /config\n```js\n$cors : https://app.example.com, *example.org\n```\n\n### $httpmaxsize : 256\n\nType: `config`\n\nLa taille maximale par défaut du corps des routes HTTP, en kB.\n\nReturns: `Number`\n\nPar défaut `256`. Une route la remplace avec un flag de taille.\n\nExample: /config\n```js\n$httpmaxsize : 1024\n```\n\n### $httptimeout : 5\n\nType: `config`\n\nLe timeout par défaut des requêtes HTTP, en secondes.\n\nReturns: `Number`\n\nPar défaut `5`. Une route le remplace avec un flag de timeout.\n\nExample: /config\n```js\n$httptimeout : 15\n```\n\n### $proxytimeout : 5\n\nType: `config`\n\nLe timeout par défaut des requêtes `PROXY()`, en secondes.\n\nReturns: `Number`\n\nPar défaut `5`. `proxy.timeout()` le remplace pour un proxy.\n\nExample: /config\n```js\n$proxytimeout : 30\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [size])","since":"","deprecated":false},{"type":"type","name":"+ flag","signature":"ROUTE('+METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"- flag","signature":"ROUTE('-METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"{param}","signature":"ROUTE('GET /path/{name}/', action)","since":"","deprecated":false},{"type":"type","name":"* wildcard","signature":"ROUTE('GET /path/*', action)","since":"","deprecated":false},{"type":"type","name":"API ?","signature":"ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])","since":"","deprecated":false},{"type":"type","name":"--> actions","signature":"ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')","since":"","deprecated":false},{"type":"type","name":"<size","signature":"ROUTE('METHOD /path/ <10MB', action)","since":"","deprecated":false},{"type":"type","name":"<timeout","signature":"ROUTE('METHOD /path/ <30s', action)","since":"","deprecated":false},{"type":"type","name":"#middleware","signature":"ROUTE('METHOD /path/ #name', action)","since":"","deprecated":false},{"type":"type","name":"@json","signature":"ROUTE('METHOD /path/ @json', action)","since":"","deprecated":false},{"type":"type","name":"@xml","signature":"ROUTE('METHOD /path/ @xml', action)","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('METHOD /path/ @upload', action)","since":"","deprecated":false},{"type":"type","name":"@xhr","signature":"ROUTE('METHOD /path/ @xhr', action)","since":"","deprecated":false},{"type":"type","name":"@mobile","signature":"ROUTE('METHOD /path/ @mobile', action)","since":"","deprecated":false},{"type":"type","name":"@robot","signature":"ROUTE('METHOD /path/ @robot', action)","since":"","deprecated":false},{"type":"type","name":"@referrer","signature":"ROUTE('METHOD /path/ @referrer', action)","since":"","deprecated":false},{"type":"type","name":"@debug","signature":"ROUTE('METHOD /path/ @debug', action)","since":"","deprecated":false},{"type":"type","name":"@release","signature":"ROUTE('METHOD /path/ @release', action)","since":"","deprecated":false},{"type":"type","name":"FILE","signature":"ROUTE('FILE /path/pattern', action)","since":"","deprecated":false},{"type":"type","name":"SOCKET","signature":"ROUTE('SOCKET /path/ [flags]', action)","since":"","deprecated":false},{"type":"type","name":"#code","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"class","name":"Route","signature":"Route","since":"","deprecated":false},{"type":"property","name":"route.method","signature":"route.method","since":"","deprecated":false},{"type":"property","name":"route.url","signature":"route.url","since":"","deprecated":false},{"type":"property","name":"route.params","signature":"route.params","since":"","deprecated":false},{"type":"property","name":"route.flags","signature":"route.flags","since":"","deprecated":false},{"type":"property","name":"route.middleware","signature":"route.middleware","since":"","deprecated":false},{"type":"property","name":"route.auth","signature":"route.auth","since":"","deprecated":false},{"type":"property","name":"route.size","signature":"route.size","since":"","deprecated":false},{"type":"property","name":"route.timeout","signature":"route.timeout","since":"","deprecated":false},{"type":"property","name":"route.priority","signature":"route.priority","since":"","deprecated":false},{"type":"property","name":"route.type","signature":"route.type","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([origins])","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(path, [target])","since":"","deprecated":false},{"type":"method","name":"proxy.copy()","signature":"proxy.copy(type)","since":"","deprecated":false},{"type":"method","name":"proxy.before()","signature":"proxy.before(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.after()","signature":"proxy.after(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.check()","signature":"proxy.check(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.timeout()","signature":"proxy.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"proxy.remove()","signature":"proxy.remove()","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : /api/","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root : /app/","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : https://app.example.com","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : 5","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : 5","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JaedEABfT60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/routing/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Routing","summary":"Sintassi di ROUTE(), flag, l'oggetto route, CORS(), PROXY() e la configurazione del routing.","markdown":"---\ntitle: Routing\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/routing/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Routing\n\n> Sintassi di ROUTE(), flag, l'oggetto route, CORS(), PROXY() e la configurazione del routing.\n\nOgni parte della stringa di `ROUTE()` (prefissi del metodo, parametri, flag, azioni ed endpoint API), l'oggetto route, `CORS()`, `PROXY()` e le chiavi di configurazione del routing. La guida [Routing](../../guides/routing/) li spiega con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### ROUTE(url, [action], [size])\n\nType: `method`\n\nDichiara una route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Il metodo, il percorso e i flag, per esempio `+POST /api/orders/ @json <1MB`. |\n| `action` | `Function|String` | no |  | Una funzione chiamata con il controller, oppure il nome di una vista. Senza di essa, viene renderizzata una vista con il nome del primo segmento del percorso (`index` per `/`). |\n| `size` | `Number` | no | `CONF.$httpmaxsize` | La dimensione massima del body in byte. Può essere il secondo argomento quando non c'è un'azione. |\n\nReturns: `Route` L'oggetto route.\n\n`url` è una sola stringa: il metodo (con un prefisso opzionale `+` o `-`), il percorso e i flag opzionali, le azioni dopo `-->` e gli endpoint API dopo `?`. Le route vengono ordinate 100 ms dopo l'ultima chiamata a `ROUTE()`. Un percorso che inizia con `#` dichiara una route di errore. La funzione globale `ROUTE` è la stessa funzione di `F.route`.\n\nExample: Una pagina e un endpoint JSON\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n\nfunction index($) {\n\t$.view('index');\n}\n```\n\nExample: Una vista senza codice\n```js\nexports.install = function() {\n\tROUTE('GET /contact/', 'contact');\n\tROUTE('GET /about/');\n};\n```\n\n### ROUTE('+METHOD /path/', action)\n\nType: `type`\n\nLa route è solo per gli utenti che hanno effettuato l'accesso.\n\nIl delegate `AUTH()` deve restituire un utente; senza `AUTH()` il prefisso non viene controllato e la route serve tutti. Quando l'utente non ha effettuato l'accesso e nessun'altra route dell'URL accetta visitatori, la risposta è `401`. L'utente si trova in `$.user`.\n\nExample: Una pagina dell'account\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', function($) {\n\t\t$.json($.user);\n\t});\n};\n```\n\n### ROUTE('-METHOD /path/', action)\n\nType: `type`\n\nLa route è solo per i visitatori che non hanno effettuato l'accesso.\n\nUsala con una route `+` dello stesso URL per mostrare contenuti diversi agli utenti che hanno effettuato l'accesso e ai visitatori. Un utente che ha effettuato l'accesso e raggiunge solo una route `-` riceve `401`.\n\nExample: Login o account\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n};\n```\n\n### ROUTE('GET /path/{name}/', action)\n\nType: `type`\n\nUn segmento dinamico del percorso.\n\nIl valore del segmento viene salvato in `$.params` con il suo nome, come stringa con le maiuscole e minuscole dell'URL della richiesta. Un parametro occupa un intero segmento. Una route con parametri corrisponde solo a URL con lo stesso numero di segmenti.\n\nExample: Due parametri\n```js\nexports.install = function() {\n\tROUTE('GET /blog/{year}/{slug}/', function($) {\n\t\t$.json({ year: $.params.year, slug: $.params.slug });\n\t});\n};\n```\n\n### ROUTE('GET /path/*', action)\n\nType: `type`\n\nCorrisponde al percorso e a tutto ciò che sta sotto.\n\nUna route jolly ha una priorità più bassa delle route fisse e dinamiche, quindi cattura solo gli URL che nessun'altra route prende.\n\nExample: Una route generica per una sezione\n```js\nexports.install = function() {\n\tROUTE('GET /app/*', 'app');\n};\n```\n\n### ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])\n\nType: `type`\n\nDichiara un endpoint della route API.\n\nIl `?` viene sostituito con `CONF.$api` (predefinito `/api/`, senza aggiungere di nuovo `CONF.$root`). Tutti gli endpoint condividono una route `POST`. Il body della richiesta è `{ schema: \"endpoint/param?query\", data: {...} }`: `$.params` viene riempito dalle parti del percorso di `schema`, `$.query` dalla parte dopo `?`, e `data` diventa il body. `+API` e `-API` verificano l'utente per ogni endpoint. Un parametro mancante è un errore per `params.<name>`; un endpoint sconosciuto, o un body senza `schema`, riceve `400`. Il flag di timeout si applica all'endpoint e il flag di dimensione più grande alla route condivisa.\n\nExample: Endpoint\n```js\nexports.install = function() {\n\tROUTE('API ? tasks_list --> Tasks/list');\n\tROUTE('+API ? tasks_read/{id} --> Tasks/read');\n\tROUTE('+API ? tasks_save <5MB --> Tasks/save');\n};\n```\n\nExample: Una funzione invece delle azioni\n```js\nexports.install = function() {\n\tROUTE('API ? ping', function($) {\n\t\t$.success();\n\t});\n};\n```\n\nExample: Client\n```js\nAJAX('POST /api/', { schema: 'tasks_read/42', data: null }, function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')\n\nType: `type`\n\nEsegue azioni invece di una funzione.\n\nI nomi dopo `-->` sono azioni dichiarate con `NEWACTION()`, separate da spazi o virgole. Il body della richiesta è il payload, e `$.params`, `$.query` e `$.user` vengono passati. Il risultato viene inviato come risposta e un errore con `$.invalid()`. Con più azioni, indica con `(response)` quella il cui risultato è la risposta; un'azione singola è la risposta.\n\nExample: Un'azione\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/ --> Users/list');\n};\n```\n\nExample: Inserire e rileggere\n```js\nexports.install = function() {\n\tROUTE('+POST /api/users/ --> Users/insert Users/read (response)');\n};\n```\n\n### ROUTE('METHOD /path/ <10MB', action)\n\nType: `type`\n\nImposta la dimensione massima del body della richiesta.\n\nUnità: `b` (byte), `kB` (kilobyte, 1024 byte), `MB` (megabyte) e `GB` (gigabyte); l'unità è obbligatoria. A un body più grande si risponde con `431`. Senza il flag il limite è `CONF.$httpmaxsize` kB (`CONF.$wsmaxsize` kB per le route `SOCKET`).\n\nExample: Upload fino a 50 MB\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <50MB', upload);\n};\n```\n\n### ROUTE('METHOD /path/ <30s', action)\n\nType: `type`\n\nImposta il timeout della richiesta.\n\nUnità: `s` (secondi), `m` (minuti) e `h` (ore). Quando l'azione non risponde in tempo, la richiesta termina con `503`. Senza il flag il timeout è `CONF.$httptimeout` secondi. Il timeout viene controllato ogni 5 secondi.\n\nExample: Un'esportazione lunga\n```js\nexports.install = function() {\n\tROUTE('GET /export/ <10m', exportdata);\n};\n```\n\n### ROUTE('METHOD /path/ #name', action)\n\nType: `type`\n\nEsegue un middleware prima dell'azione.\n\nIl nome deve essere registrato con `MIDDLEWARE(name, fn)`. Più `#names` vengono eseguiti nell'ordine scritto; un nome sconosciuto viene saltato. I nomi dei middleware contengono lettere, cifre e `_`.\n\nExample: Due middleware\n```js\nMIDDLEWARE('cors_api', function($, next) {\n\t$.response.headers['x-api'] = '1';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/stats/ #cors_api #nocache', stats);\n};\n```\n\n### ROUTE('METHOD /path/ @json', action)\n\nType: `type`\n\nLa route corrisponde solo quando il body della richiesta è JSON (`application/json` o `text/json`).\n\nSe la richiesta non soddisfa la condizione, il router prova la route successiva con lo stesso metodo e lo stesso percorso. Ogni flag abbassa di uno la priorità della route, quindi viene controllata prima una route con meno flag.\n\nExample: Utilizzo\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/ @json', orders);\n};\n```\n\n### ROUTE('METHOD /path/ @xml', action)\n\nType: `type`\n\nLa route corrisponde solo quando il body della richiesta è XML (`application/xml` o `text/xml`).\n\nSe la richiesta non soddisfa la condizione, il router prova la route successiva con lo stesso metodo e lo stesso percorso. Ogni flag abbassa di uno la priorità della route, quindi viene controllata prima una route con meno flag.\n\nExample: Utilizzo\n```js\nexports.install = function() {\n\tROUTE('POST /feed/ @xml', feed);\n};\n```\n\n### ROUTE('METHOD /path/ @upload', action)\n\nType: `type`\n\nLa route corrisponde solo quando il body della richiesta è `multipart/form-data`.\n\nSe la richiesta non soddisfa la condizione, il router prova la route successiva con lo stesso metodo e lo stesso percorso. Ogni flag abbassa di uno la priorità della route, quindi viene controllata prima una route con meno flag.\n\nExample: Utilizzo\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', function($) {\n\t\t$.json($.files.map(f => f.filename));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @xhr', action)\n\nType: `type`\n\nLa route corrisponde solo quando la richiesta ha l'header `X-Requested-With: XMLHttpRequest`.\n\nSe la richiesta non soddisfa la condizione, il router prova la route successiva con lo stesso metodo e lo stesso percorso. Ogni flag abbassa di uno la priorità della route, quindi viene controllata prima una route con meno flag.\n\nExample: Utilizzo\n```js\nexports.install = function() {\n\tROUTE('GET /partials/menu/ @xhr', 'partials/menu');\n};\n```\n\n### ROUTE('METHOD /path/ @mobile', action)\n\nType: `type`\n\nLa route corrisponde solo quando il client è un dispositivo mobile.\n\nSe la richiesta non soddisfa la condizione, il router prova la route successiva con lo stesso metodo e lo stesso percorso. Ogni flag abbassa di uno la priorità della route, quindi viene controllata prima una route con meno flag.\n\nExample: Utilizzo\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /m/ @mobile', 'mobile');\n};\n```\n\n### ROUTE('METHOD /path/ @robot', action)\n\nType: `type`\n\nLa route corrisponde solo quando il client è un crawler.\n\nSe la richiesta non soddisfa la condizione, il router prova la route successiva con lo stesso metodo e lo stesso percorso. Ogni flag abbassa di uno la priorità della route, quindi viene controllata prima una route con meno flag.\n\nExample: Utilizzo\n```js\nexports.install = function() {\n\tROUTE('GET /prerender/ @robot', 'static');\n};\n```\n\n### ROUTE('METHOD /path/ @referrer', action)\n\nType: `type`\n\nLa route corrisponde solo quando l'header `Referer` contiene l'host della richiesta; `@referer` è lo stesso flag.\n\nSe la richiesta non soddisfa la condizione, il router prova la route successiva con lo stesso metodo e lo stesso percorso. Ogni flag abbassa di uno la priorità della route, quindi viene controllata prima una route con meno flag.\n\nExample: Utilizzo\n```js\nexports.install = function() {\n\tROUTE('GET /download/ @referrer', download);\n};\n```\n\n### ROUTE('METHOD /path/ @debug', action)\n\nType: `type`\n\nLa route corrisponde solo quando l'applicazione è in esecuzione in modalità debug.\n\nSe la richiesta non soddisfa la condizione, il router prova la route successiva con lo stesso metodo e lo stesso percorso. Ogni flag abbassa di uno la priorità della route, quindi viene controllata prima una route con meno flag.\n\nExample: Utilizzo\n```js\nexports.install = function() {\n\tROUTE('GET /dev/routes/ @debug', function($) {\n\t\t$.json(F.routes.routes.map(r => r.method + ' ' + r.url2));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @release', action)\n\nType: `type`\n\nLa route corrisponde solo quando l'applicazione è in esecuzione in modalità release.\n\nSe la richiesta non soddisfa la condizione, il router prova la route successiva con lo stesso metodo e lo stesso percorso. Ogni flag abbassa di uno la priorità della route, quindi viene controllata prima una route con meno flag.\n\nExample: Utilizzo\n```js\nexports.install = function() {\n\tROUTE('GET /status/ @release', status);\n};\n```\n\n### ROUTE('FILE /path/pattern', action)\n\nType: `type`\n\nGestisce con il tuo codice le richieste di file statici.\n\nLe route di file vengono controllate per gli URL con un'estensione. Pattern: un file fisso (`/robots.txt`), estensioni in una cartella (`/docs/*.md|txt`), ogni file in una cartella (`/downloads/*`) e un'estensione ovunque (`*.webp`). L'azione riceve il controller; rispondi con `$.file()`, `$.image()`, `$.plain()` o `$.resume()` (serve il file da `/public/`). Una richiesta che nessuna route prende viene servita da `/public/` quando la sua estensione è in `CONF.$httpfiles`, altrimenti riceve `404`.\n\nExample: robots.txt generato\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', function($) {\n\t\t$.plain('User-agent: *\\nDisallow: /admin/');\n\t});\n};\n```\n\nExample: File da una cartella privata\n```js\nexports.install = function() {\n\tROUTE('FILE /files/*.pdf|docx', function($) {\n\t\t$.file(PATH.databases($.split[1]), true);\n\t});\n};\n```\n\n### ROUTE('SOCKET /path/ [flags]', action)\n\nType: `type`\n\nDichiara un endpoint WebSocket.\n\n`WEBSOCKET` è lo stesso metodo. Il percorso, `+`/`-`, `{params}`, `#middleware` e il flag di dimensione funzionano come nelle route HTTP; la dimensione predefinita dei messaggi è `CONF.$wsmaxsize` kB. Vedi [WebSocket](../../guides/websockets/).\n\nExample: Chat\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /chat/{room}/ <1MB', chat);\n};\n```\n\n### ROUTE('#code', action)\n\nType: `type`\n\nSostituisce la pagina di errore predefinita per un codice di stato.\n\nQuando il framework risponde con quel codice (per esempio `404`, `401`, `431` o `503`), chiama la tua azione con il controller invece di renderizzare la pagina di errore integrata.\n\nExample: 404 personalizzata\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n### Route\n\nType: `class`\n\nL'oggetto che ROUTE() restituisce.\n\nDescrive una route analizzata. Puoi leggerne le proprietà o chiamare `remove()`; non modificarle dopo che le route sono state ordinate. Il controller di una richiesta ha la sua route in `$.route`.\n\nExample: Ispezionare una route\n```js\nvar route = ROUTE('+POST /api/orders/ @json <2MB', create);\nconsole.log(route.method, route.auth, route.size, route.flags);\n```\n\n### route.method\n\nType: `property`\n\nIl metodo HTTP in maiuscolo, senza `+` o `-`.\n\nReturns: `String`\n\nLe route `API` hanno `POST`. Le route `FILE` e `SOCKET` mantengono il nome del loro metodo.\n\n### route.url\n\nType: `property`\n\nIl percorso diviso in segmenti in minuscolo.\n\nReturns: `Array`\n\nI segmenti dei parametri mantengono la forma `{name}`. Il percorso così come è stato scritto (con `CONF.$root`) è in `route.url2`.\n\n### route.params\n\nType: `property`\n\nI parametri dinamici del percorso.\n\nReturns: `Array`\n\nOgni elemento ha `name` e `index`, la posizione del segmento nel percorso.\n\n### route.flags\n\nType: `property`\n\nI flag `@` della route come oggetto.\n\nReturns: `Object`\n\nPer esempio `@json @xhr` dà `{ json: 1, xhr: 1 }`.\n\n### route.middleware\n\nType: `property`\n\nI nomi dei middleware che vengono eseguiti prima dell'azione.\n\nReturns: `Array`\n\nI flag `#name` nel loro ordine. `MIDDLEWARE(name, fn, assign)` può aggiungere nomi a route esistenti.\n\n### route.auth\n\nType: `property`\n\nL'autorizzazione della route.\n\nReturns: `Number`\n\n`0` per tutti, `1` per gli utenti che hanno effettuato l'accesso (`+`), `2` per i visitatori che non hanno effettuato l'accesso (`-`). La route condivisa dell'API ha `0`; ogni endpoint mantiene il proprio valore.\n\n### route.size\n\nType: `property`\n\nLa dimensione massima del body in byte.\n\nReturns: `Number`\n\nImpostata dal flag di dimensione o dall'argomento `size`; altrimenti `CONF.$httpmaxsize * 1024` (`CONF.$wsmaxsize * 1024` per le route `SOCKET`).\n\n### route.timeout\n\nType: `property`\n\nIl timeout in secondi, oppure `0`.\n\nReturns: `Number`\n\n`0` significa che la richiesta usa `CONF.$httptimeout`.\n\n### route.priority\n\nType: `property`\n\nL'ordine in cui vengono controllate le route con lo stesso metodo e lo stesso percorso.\n\nReturns: `Number`\n\nParte da `100`, ogni flag `@` lo abbassa di uno e un carattere jolly di 50. I valori più alti vengono controllati per primi.\n\n### route.type\n\nType: `property`\n\nIl tipo di route.\n\nReturns: `String`\n\n`route`, `file` o `websocket`.\n\n### route.remove()\n\nType: `method`\n\nRimuove la route.\n\nReturns: `undefined`\n\nAnnulla la registrazione della route e riordina la tabella di routing. Funziona per le route HTTP, gli endpoint API (la route `POST` condivisa dell'API viene rimossa con il suo ultimo endpoint), le route `FILE` e le route `SOCKET`, le cui connessioni aperte vengono chiuse.\n\nExample: Una route temporanea\n```js\nvar route = ROUTE('GET /maintenance/', function($) {\n\t$.plain('Back soon');\n});\n\nsetTimeout(function() {\n\troute.remove();\n}, 60000);\n```\n\n### CORS([origins])\n\nType: `method`\n\nImposta le origini consentite per le richieste cross-origin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `origins` | `String` | no | `'*'` | Le origini consentite, `*`, oppure `+origins` da aggiungere. |\n\nReturns: `undefined`\n\nSenza argomenti, ogni origine è consentita (`*`). Altrimenti indica le origini complete separate da virgole, `;` o `|`. Un elemento che inizia con `*` consente ogni origine che contiene il resto. Un valore che inizia con `+` aggiunge origini all'elenco corrente. Le richieste dallo stesso host passano sempre. Una richiesta consentita riceve `Access-Control-Allow-Origin` (l'origine), `-Credentials: true`, `-Methods`, `-Headers` e `-Expose-Headers` (`*`), e a `OPTIONS` si risponde subito. Le altre origini ricevono `400` con `Invalid origin (CORS)`.\n\nExample: Consentire due app\n```js\nCORS('https://app.example.com,https://admin.example.com');\n```\n\nExample: Aggiungerne una e consentire i sottodomini\n```js\nCORS('+https://partner.com');\nCORS('+*example.org');\n```\n\nExample: Qualsiasi origine\n```js\nCORS();\n```\n\n### PROXY(path, [target])\n\nType: `method`\n\nInoltra le richieste sotto un percorso a un altro server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | L'inizio del percorso della richiesta, per esempio `/cdn/`. |\n| `target` | `String|Function` | no |  | L'URL di destinazione, il percorso di un socket Unix, oppure `function($)`. |\n\nReturns: `Proxy` L'oggetto proxy con metodi concatenabili, oppure niente quando rimuovi un proxy.\n\nI proxy vengono controllati prima delle route, per ogni metodo e per gli upgrade WebSocket. `path` dovrebbe terminare con `/` e riceve `CONF.$root`. `target` è un URL `http://`/`https://`, il percorso di un socket Unix, oppure una funzione che riceve il controller e risponde da sé. La richiesta inoltrata mantiene gli header (senza `Host`) e riceve `X-Forwarded-For`, `X-Forwarded-URL` e `X-Forwarded-Host`. Quando la destinazione fallisce, il client riceve `503`. `PROXY(path)` senza destinazione rimuove il proxy per quel percorso.\n\nExample: Inoltrare a un servizio\n```js\nPROXY('/search/', 'http://127.0.0.1:9200').copy('replace');\n```\n\nExample: Socket Unix\n```js\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nExample: Handler proprio\n```js\nPROXY('/ping/', function($) {\n\t$.plain('pong');\n});\n```\n\n### proxy.copy(type)\n\nType: `method`\n\nImposta come il percorso della richiesta viene copiato sulla destinazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `none`, `replace` o `extend`. |\n\nReturns: `Proxy` Il proxy.\n\n`none` (predefinito): l'URL di destinazione con la query string della richiesta. `replace`: la destinazione con la parte del percorso dopo il percorso del proxy (quando l'URL di destinazione ha un proprio percorso, `replace` funziona come `extend`). `extend`: il percorso della destinazione, più il resto del percorso della richiesta, più le query string della richiesta e della destinazione.\n\nExample: Mantenere i sottopercorsi\n```js\n// GET /cl/something/?q=1 --> https://example.com/something/?q=1\nPROXY('/cl/', 'https://example.com').copy('extend');\n```\n\n### proxy.before(callback)\n\nType: `method`\n\nModifica la richiesta in uscita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(uri, $)`. |\n\nReturns: `Proxy` Il proxy.\n\n`callback(uri, $)` viene eseguita prima che la richiesta venga inviata. `uri` contiene le opzioni della richiesta di Node.js (`path`, `headers`, `method`...).\n\nExample: Aggiungere un token\n```js\nPROXY('/api2/', 'https://internal.example.com').before(function(uri, $) {\n\turi.headers['x-token'] = CONF.internal_token;\n});\n```\n\n### proxy.after(callback)\n\nType: `method`\n\nLegge la risposta della destinazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(response)`. |\n\nReturns: `Proxy` Il proxy.\n\n`callback(response)` riceve la risposta di Node.js prima che venga inviata al client; puoi modificare `response.headers`.\n\nExample: Rimuovere un header\n```js\nPROXY('/cdn/', 'https://cdn.example.com').after(function(response) {\n\tdelete response.headers['set-cookie'];\n});\n```\n\n### proxy.check(callback)\n\nType: `method`\n\nDecide per ogni richiesta se usare il proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)` che restituisce un booleano. |\n\nReturns: `Proxy` Il proxy.\n\n`callback($)` restituisce `true` per inoltrare la richiesta. Altrimenti la richiesta va alle route.\n\nExample: Solo GET\n```js\nPROXY('/files/', 'http://127.0.0.1:8001').check($ => $.method === 'GET');\n```\n\n### proxy.timeout(ms)\n\nType: `method`\n\nImposta il timeout della richiesta inoltrata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes |  | Il timeout in millisecondi. |\n\nReturns: `Proxy` Il proxy.\n\nIn millisecondi. Senza di esso (o con `0`) il proxy usa `CONF.$proxytimeout` secondi.\n\nExample: 30 secondi\n```js\nPROXY('/reports/', 'http://127.0.0.1:8002').timeout(30000);\n```\n\n### proxy.remove()\n\nType: `method`\n\nRimuove il proxy.\n\nReturns: `undefined`\n\nLe richieste sotto il suo percorso tornano alle route. `PROXY(path)` senza destinazione fa lo stesso.\n\nExample: Rimuovere\n```js\nvar proxy = PROXY('/old/', 'http://127.0.0.1:8003');\nproxy.remove();\n```\n\n### $api : /api/\n\nType: `config`\n\nIl percorso che `?` rappresenta nelle route API.\n\nReturns: `String`\n\nPredefinito `/api/`. Quando `$root` è impostato, viene aggiunto davanti.\n\nExample: /config\n```js\n$api : /rpc/\n```\n\n### $root : /app/\n\nType: `config`\n\nUn prefisso di percorso per tutte le route.\n\nReturns: `String`\n\nOgni route, proxy e percorso `$api` riceve questo prefisso, per esempio quando l'app è in esecuzione sotto `/app/` dietro un web server. Predefinito vuoto.\n\nExample: /config\n```js\n$root : /admin/\n```\n\n### $cors : https://app.example.com\n\nType: `config`\n\nLe origini consentite per le richieste cross-origin.\n\nReturns: `String`\n\nLo stesso valore che accetta `CORS()`: `*`, oppure origini separate da virgole, con elementi `*domain` per corrispondenze parziali. Predefinito vuoto (le richieste cross-origin non vengono verificate).\n\nExample: /config\n```js\n$cors : https://app.example.com, *example.org\n```\n\n### $httpmaxsize : 256\n\nType: `config`\n\nLa dimensione massima predefinita del body delle route HTTP, in kB.\n\nReturns: `Number`\n\nPredefinito `256`. Una route la sovrascrive con un flag di dimensione.\n\nExample: /config\n```js\n$httpmaxsize : 1024\n```\n\n### $httptimeout : 5\n\nType: `config`\n\nIl timeout predefinito delle richieste HTTP, in secondi.\n\nReturns: `Number`\n\nPredefinito `5`. Una route lo sovrascrive con un flag di timeout.\n\nExample: /config\n```js\n$httptimeout : 15\n```\n\n### $proxytimeout : 5\n\nType: `config`\n\nIl timeout predefinito delle richieste `PROXY()`, in secondi.\n\nReturns: `Number`\n\nPredefinito `5`. `proxy.timeout()` lo sovrascrive per un singolo proxy.\n\nExample: /config\n```js\n$proxytimeout : 30\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [size])","since":"","deprecated":false},{"type":"type","name":"+ flag","signature":"ROUTE('+METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"- flag","signature":"ROUTE('-METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"{param}","signature":"ROUTE('GET /path/{name}/', action)","since":"","deprecated":false},{"type":"type","name":"* wildcard","signature":"ROUTE('GET /path/*', action)","since":"","deprecated":false},{"type":"type","name":"API ?","signature":"ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])","since":"","deprecated":false},{"type":"type","name":"--> actions","signature":"ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')","since":"","deprecated":false},{"type":"type","name":"<size","signature":"ROUTE('METHOD /path/ <10MB', action)","since":"","deprecated":false},{"type":"type","name":"<timeout","signature":"ROUTE('METHOD /path/ <30s', action)","since":"","deprecated":false},{"type":"type","name":"#middleware","signature":"ROUTE('METHOD /path/ #name', action)","since":"","deprecated":false},{"type":"type","name":"@json","signature":"ROUTE('METHOD /path/ @json', action)","since":"","deprecated":false},{"type":"type","name":"@xml","signature":"ROUTE('METHOD /path/ @xml', action)","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('METHOD /path/ @upload', action)","since":"","deprecated":false},{"type":"type","name":"@xhr","signature":"ROUTE('METHOD /path/ @xhr', action)","since":"","deprecated":false},{"type":"type","name":"@mobile","signature":"ROUTE('METHOD /path/ @mobile', action)","since":"","deprecated":false},{"type":"type","name":"@robot","signature":"ROUTE('METHOD /path/ @robot', action)","since":"","deprecated":false},{"type":"type","name":"@referrer","signature":"ROUTE('METHOD /path/ @referrer', action)","since":"","deprecated":false},{"type":"type","name":"@debug","signature":"ROUTE('METHOD /path/ @debug', action)","since":"","deprecated":false},{"type":"type","name":"@release","signature":"ROUTE('METHOD /path/ @release', action)","since":"","deprecated":false},{"type":"type","name":"FILE","signature":"ROUTE('FILE /path/pattern', action)","since":"","deprecated":false},{"type":"type","name":"SOCKET","signature":"ROUTE('SOCKET /path/ [flags]', action)","since":"","deprecated":false},{"type":"type","name":"#code","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"class","name":"Route","signature":"Route","since":"","deprecated":false},{"type":"property","name":"route.method","signature":"route.method","since":"","deprecated":false},{"type":"property","name":"route.url","signature":"route.url","since":"","deprecated":false},{"type":"property","name":"route.params","signature":"route.params","since":"","deprecated":false},{"type":"property","name":"route.flags","signature":"route.flags","since":"","deprecated":false},{"type":"property","name":"route.middleware","signature":"route.middleware","since":"","deprecated":false},{"type":"property","name":"route.auth","signature":"route.auth","since":"","deprecated":false},{"type":"property","name":"route.size","signature":"route.size","since":"","deprecated":false},{"type":"property","name":"route.timeout","signature":"route.timeout","since":"","deprecated":false},{"type":"property","name":"route.priority","signature":"route.priority","since":"","deprecated":false},{"type":"property","name":"route.type","signature":"route.type","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([origins])","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(path, [target])","since":"","deprecated":false},{"type":"method","name":"proxy.copy()","signature":"proxy.copy(type)","since":"","deprecated":false},{"type":"method","name":"proxy.before()","signature":"proxy.before(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.after()","signature":"proxy.after(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.check()","signature":"proxy.check(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.timeout()","signature":"proxy.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"proxy.remove()","signature":"proxy.remove()","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : /api/","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root : /app/","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : https://app.example.com","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : 5","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : 5","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JaedEABfT60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/routing/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Smerovanie","summary":"Syntax ROUTE(), príznaky, objekt trasy, CORS(), PROXY() a konfigurácia smerovania.","markdown":"---\ntitle: Smerovanie\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/routing/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Smerovanie\n\n> Syntax ROUTE(), príznaky, objekt trasy, CORS(), PROXY() a konfigurácia smerovania.\n\nKaždá časť reťazca `ROUTE()` (prefixy metódy, parametre, príznaky, akcie a API endpointy), objekt trasy, `CORS()`, `PROXY()` a konfiguračné kľúče smerovania. Návod [Smerovanie](../../guides/routing/) ich vysvetľuje na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### ROUTE(url, [action], [size])\n\nType: `method`\n\nDeklaruje trasu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Metóda, cesta a príznaky, napríklad `+POST /api/orders/ @json <1MB`. |\n| `action` | `Function|String` | no |  | Funkcia, ktorá sa zavolá s kontrolérom, alebo názov pohľadu. Bez nej sa vyrenderuje pohľad pomenovaný podľa prvého segmentu cesty (`index` pre `/`). |\n| `size` | `Number` | no | `CONF.$httpmaxsize` | Maximálna veľkosť tela v bajtoch. Môže byť druhým argumentom, keď nie je zadaná akcia. |\n\nReturns: `Route` Objekt trasy.\n\n`url` je jeden reťazec: metóda (s voliteľným prefixom `+` alebo `-`), cesta a voliteľné príznaky, akcie za `-->` a API endpointy za `?`. Trasy sa zoradia 100 ms po poslednom volaní `ROUTE()`. Cesta, ktorá začína `#`, deklaruje chybovú trasu. Globálna `ROUTE` je tá istá funkcia ako `F.route`.\n\nExample: Stránka a JSON endpoint\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n\tROUTE('GET /api/time/', function($) {\n\t\t$.json({ now: new Date() });\n\t});\n};\n\nfunction index($) {\n\t$.view('index');\n}\n```\n\nExample: Pohľad bez kódu\n```js\nexports.install = function() {\n\tROUTE('GET /contact/', 'contact');\n\tROUTE('GET /about/');\n};\n```\n\n### ROUTE('+METHOD /path/', action)\n\nType: `type`\n\nTrasa je len pre prihlásených používateľov.\n\nDelegát `AUTH()` musí vrátiť používateľa; bez `AUTH()` sa prefix nekontroluje a trasa obsluhuje každého. Keď používateľ nie je prihlásený a žiadna iná trasa URL neprijíma návštevníkov, odpoveď je `401`. Používateľ je v `$.user`.\n\nExample: Stránka účtu\n```js\nexports.install = function() {\n\tROUTE('+GET /account/', function($) {\n\t\t$.json($.user);\n\t});\n};\n```\n\n### ROUTE('-METHOD /path/', action)\n\nType: `type`\n\nTrasa je len pre návštevníkov, ktorí nie sú prihlásení.\n\nPouži ju s trasou `+` pre rovnakú URL, ak chceš prihláseným používateľom a návštevníkom zobraziť rozdielny obsah. Prihlásený používateľ, ktorý sa dostane len k trase `-`, dostane `401`.\n\nExample: Prihlásenie alebo účet\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n};\n```\n\n### ROUTE('GET /path/{name}/', action)\n\nType: `type`\n\nDynamický segment cesty.\n\nHodnota segmentu sa uloží do `$.params` pod jeho názvom ako reťazec s veľkosťou písmen z URL požiadavky. Parameter zaberá celý segment. Trasa s parametrami zodpovedá len URL s rovnakým počtom segmentov.\n\nExample: Dva parametre\n```js\nexports.install = function() {\n\tROUTE('GET /blog/{year}/{slug}/', function($) {\n\t\t$.json({ year: $.params.year, slug: $.params.slug });\n\t});\n};\n```\n\n### ROUTE('GET /path/*', action)\n\nType: `type`\n\nZodpovedá ceste a všetkému pod ňou.\n\nTrasa so zástupným znakom má nižšiu prioritu ako pevné a dynamické trasy, takže zachytí len URL, ktoré si nevezme žiadna iná trasa.\n\nExample: Zachytenie všetkého v sekcii\n```js\nexports.install = function() {\n\tROUTE('GET /app/*', 'app');\n};\n```\n\n### ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])\n\nType: `type`\n\nDeklaruje jeden endpoint API trasy.\n\n`?` sa nahradí hodnotou `CONF.$api` (predvolene `/api/`, bez opätovného pridania `CONF.$root`). Všetky endpointy zdieľajú jednu trasu `POST`. Telo požiadavky je `{ schema: \"endpoint/param?query\", data: {...} }`: `$.params` sa naplní z častí cesty v `schema`, `$.query` z časti za `?` a `data` sa stane telom. `+API` a `-API` kontrolujú používateľa pre každý endpoint. Chýbajúci parameter je chyba pre `params.<name>`; neznámy endpoint alebo telo bez `schema` dostane `400`. Príznak timeoutu platí pre endpoint a najväčší príznak veľkosti pre zdieľanú trasu.\n\nExample: Endpointy\n```js\nexports.install = function() {\n\tROUTE('API ? tasks_list --> Tasks/list');\n\tROUTE('+API ? tasks_read/{id} --> Tasks/read');\n\tROUTE('+API ? tasks_save <5MB --> Tasks/save');\n};\n```\n\nExample: Funkcia namiesto akcií\n```js\nexports.install = function() {\n\tROUTE('API ? ping', function($) {\n\t\t$.success();\n\t});\n};\n```\n\nExample: Klient\n```js\nAJAX('POST /api/', { schema: 'tasks_read/42', data: null }, function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')\n\nType: `type`\n\nSpustí akcie namiesto funkcie.\n\nNázvy za `-->` sú akcie deklarované pomocou `NEWACTION()`, oddelené medzerami alebo čiarkami. Telo požiadavky je payload a `$.params`, `$.query` a `$.user` sa odovzdajú ďalej. Výsledok sa pošle ako odpoveď a chyba pomocou `$.invalid()`. Pri viacerých akciách označ tú, ktorej výsledok je odpoveďou, pomocou `(response)`; jediná akcia je odpoveďou.\n\nExample: Jedna akcia\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/ --> Users/list');\n};\n```\n\nExample: Vloženie a spätné načítanie\n```js\nexports.install = function() {\n\tROUTE('+POST /api/users/ --> Users/insert Users/read (response)');\n};\n```\n\n### ROUTE('METHOD /path/ <10MB', action)\n\nType: `type`\n\nNastaví maximálnu veľkosť tela požiadavky.\n\nJednotky: `b` (bajty), `kB` (kilobajty, 1024 bajtov), `MB` (megabajty) a `GB` (gigabajty); jednotka je povinná. Na väčšie telo sa odpovie s `431`. Bez flagu je limit `CONF.$httpmaxsize` kB (`CONF.$wsmaxsize` kB pre trasy `SOCKET`).\n\nExample: Nahrávanie do 50 MB\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <50MB', upload);\n};\n```\n\n### ROUTE('METHOD /path/ <30s', action)\n\nType: `type`\n\nNastaví timeout požiadavky.\n\nJednotky: `s` (sekundy), `m` (minúty) a `h` (hodiny). Keď akcia neodpovie včas, požiadavka skončí s `503`. Bez príznaku je timeout `CONF.$httptimeout` sekúnd. Timeout sa kontroluje každých 5 sekúnd.\n\nExample: Dlhý export\n```js\nexports.install = function() {\n\tROUTE('GET /export/ <10m', exportdata);\n};\n```\n\n### ROUTE('METHOD /path/ #name', action)\n\nType: `type`\n\nSpustí middleware pred akciou.\n\nNázov musí byť zaregistrovaný pomocou `MIDDLEWARE(name, fn)`. Viacero `#names` sa spustí v zapísanom poradí; neznámy názov sa preskočí. Názvy middleware obsahujú písmená, číslice a `_`.\n\nExample: Dva middleware\n```js\nMIDDLEWARE('cors_api', function($, next) {\n\t$.response.headers['x-api'] = '1';\n\tnext();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/stats/ #cors_api #nocache', stats);\n};\n```\n\n### ROUTE('METHOD /path/ @json', action)\n\nType: `type`\n\nTrasa zodpovedá len vtedy, keď je telo požiadavky JSON (`application/json` alebo `text/json`).\n\nAk požiadavka nespĺňa podmienku, router skúsi ďalšiu trasu s rovnakou metódou a cestou. Každý príznak zníži prioritu trasy o jedna, takže trasa s menším počtom príznakov sa kontroluje skôr.\n\nExample: Použitie\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/ @json', orders);\n};\n```\n\n### ROUTE('METHOD /path/ @xml', action)\n\nType: `type`\n\nTrasa zodpovedá len vtedy, keď je telo požiadavky XML (`application/xml` alebo `text/xml`).\n\nAk požiadavka nespĺňa podmienku, router skúsi ďalšiu trasu s rovnakou metódou a cestou. Každý príznak zníži prioritu trasy o jedna, takže trasa s menším počtom príznakov sa kontroluje skôr.\n\nExample: Použitie\n```js\nexports.install = function() {\n\tROUTE('POST /feed/ @xml', feed);\n};\n```\n\n### ROUTE('METHOD /path/ @upload', action)\n\nType: `type`\n\nTrasa zodpovedá len vtedy, keď je telo požiadavky `multipart/form-data`.\n\nAk požiadavka nespĺňa podmienku, router skúsi ďalšiu trasu s rovnakou metódou a cestou. Každý príznak zníži prioritu trasy o jedna, takže trasa s menším počtom príznakov sa kontroluje skôr.\n\nExample: Použitie\n```js\nexports.install = function() {\n\tROUTE('POST /upload/ @upload <20MB', function($) {\n\t\t$.json($.files.map(f => f.filename));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @xhr', action)\n\nType: `type`\n\nTrasa zodpovedá len vtedy, keď má požiadavka hlavičku `X-Requested-With: XMLHttpRequest`.\n\nAk požiadavka nespĺňa podmienku, router skúsi ďalšiu trasu s rovnakou metódou a cestou. Každý príznak zníži prioritu trasy o jedna, takže trasa s menším počtom príznakov sa kontroluje skôr.\n\nExample: Použitie\n```js\nexports.install = function() {\n\tROUTE('GET /partials/menu/ @xhr', 'partials/menu');\n};\n```\n\n### ROUTE('METHOD /path/ @mobile', action)\n\nType: `type`\n\nTrasa zodpovedá len vtedy, keď je klient mobilné zariadenie.\n\nAk požiadavka nespĺňa podmienku, router skúsi ďalšiu trasu s rovnakou metódou a cestou. Každý príznak zníži prioritu trasy o jedna, takže trasa s menším počtom príznakov sa kontroluje skôr.\n\nExample: Použitie\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /m/ @mobile', 'mobile');\n};\n```\n\n### ROUTE('METHOD /path/ @robot', action)\n\nType: `type`\n\nTrasa zodpovedá len vtedy, keď je klient crawler.\n\nAk požiadavka nespĺňa podmienku, router skúsi ďalšiu trasu s rovnakou metódou a cestou. Každý príznak zníži prioritu trasy o jedna, takže trasa s menším počtom príznakov sa kontroluje skôr.\n\nExample: Použitie\n```js\nexports.install = function() {\n\tROUTE('GET /prerender/ @robot', 'static');\n};\n```\n\n### ROUTE('METHOD /path/ @referrer', action)\n\nType: `type`\n\nTrasa zodpovedá len vtedy, keď hlavička `Referer` obsahuje host požiadavky; `@referer` je ten istý príznak.\n\nAk požiadavka nespĺňa podmienku, router skúsi ďalšiu trasu s rovnakou metódou a cestou. Každý príznak zníži prioritu trasy o jedna, takže trasa s menším počtom príznakov sa kontroluje skôr.\n\nExample: Použitie\n```js\nexports.install = function() {\n\tROUTE('GET /download/ @referrer', download);\n};\n```\n\n### ROUTE('METHOD /path/ @debug', action)\n\nType: `type`\n\nTrasa zodpovedá len vtedy, keď aplikácia beží v režime debug.\n\nAk požiadavka nespĺňa podmienku, router skúsi ďalšiu trasu s rovnakou metódou a cestou. Každý príznak zníži prioritu trasy o jedna, takže trasa s menším počtom príznakov sa kontroluje skôr.\n\nExample: Použitie\n```js\nexports.install = function() {\n\tROUTE('GET /dev/routes/ @debug', function($) {\n\t\t$.json(F.routes.routes.map(r => r.method + ' ' + r.url2));\n\t});\n};\n```\n\n### ROUTE('METHOD /path/ @release', action)\n\nType: `type`\n\nTrasa zodpovedá len vtedy, keď aplikácia beží v režime release.\n\nAk požiadavka nespĺňa podmienku, router skúsi ďalšiu trasu s rovnakou metódou a cestou. Každý príznak zníži prioritu trasy o jedna, takže trasa s menším počtom príznakov sa kontroluje skôr.\n\nExample: Použitie\n```js\nexports.install = function() {\n\tROUTE('GET /status/ @release', status);\n};\n```\n\n### ROUTE('FILE /path/pattern', action)\n\nType: `type`\n\nSpracúva požiadavky na statické súbory tvojím kódom.\n\nTrasy pre súbory sa kontrolujú pre URL s príponou. Vzory: pevný súbor (`/robots.txt`), prípony v priečinku (`/docs/*.md|txt`), každý súbor v priečinku (`/downloads/*`) a prípona kdekoľvek (`*.webp`). Akcia dostane kontrolér; odpovedz pomocou `$.file()`, `$.image()`, `$.plain()` alebo `$.resume()` (obslúži súbor z `/public/`). Požiadavka, ktorú si nevezme žiadna trasa, sa obslúži z `/public/`, keď je jej prípona v `CONF.$httpfiles`, inak dostane `404`.\n\nExample: Generovaný robots.txt\n```js\nexports.install = function() {\n\tROUTE('FILE /robots.txt', function($) {\n\t\t$.plain('User-agent: *\\nDisallow: /admin/');\n\t});\n};\n```\n\nExample: Súbory zo súkromného priečinka\n```js\nexports.install = function() {\n\tROUTE('FILE /files/*.pdf|docx', function($) {\n\t\t$.file(PATH.databases($.split[1]), true);\n\t});\n};\n```\n\n### ROUTE('SOCKET /path/ [flags]', action)\n\nType: `type`\n\nDeklaruje WebSocket endpoint.\n\n`WEBSOCKET` je tá istá metóda. Cesta, `+`/`-`, `{params}`, `#middleware` a príznak veľkosti fungujú ako pri HTTP trasách; predvolená veľkosť správy je `CONF.$wsmaxsize` kB. Pozri [WebSockets](../../guides/websockets/).\n\nExample: Chat\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /chat/{room}/ <1MB', chat);\n};\n```\n\n### ROUTE('#code', action)\n\nType: `type`\n\nNahradí predvolenú chybovú stránku pre stavový kód.\n\nKeď framework odpovedá daným kódom (napríklad `404`, `401`, `431` alebo `503`), zavolá tvoju akciu s kontrolérom namiesto vyrenderovania vstavanej chybovej stránky.\n\nExample: Vlastná 404\n```js\nexports.install = function() {\n\tROUTE('#404', function($) {\n\t\t$.response.status = 404;\n\t\t$.view('404');\n\t});\n};\n```\n\n### Route\n\nType: `class`\n\nObjekt, ktorý vracia ROUTE().\n\nOpisuje spracovanú trasu. Čítaš jeho vlastnosti alebo voláš `remove()`; po zoradení trás ich nemeň. Kontrolér požiadavky má svoju trasu v `$.route`.\n\nExample: Preskúmanie trasy\n```js\nvar route = ROUTE('+POST /api/orders/ @json <2MB', create);\nconsole.log(route.method, route.auth, route.size, route.flags);\n```\n\n### route.method\n\nType: `property`\n\nHTTP metóda veľkými písmenami, bez `+` alebo `-`.\n\nReturns: `String`\n\nTrasy `API` majú `POST`. Trasy `FILE` a `SOCKET` si ponechávajú názov svojej metódy.\n\n### route.url\n\nType: `property`\n\nCesta rozdelená na segmenty malými písmenami.\n\nReturns: `Array`\n\nSegmenty parametrov si ponechávajú tvar `{name}`. Cesta tak, ako je zapísaná (s `CONF.$root`), je v `route.url2`.\n\n### route.params\n\nType: `property`\n\nDynamické parametre cesty.\n\nReturns: `Array`\n\nKaždá položka má `name` a `index`, teda pozíciu segmentu v ceste.\n\n### route.flags\n\nType: `property`\n\nPríznaky `@` trasy ako objekt.\n\nReturns: `Object`\n\nNapríklad `@json @xhr` dáva `{ json: 1, xhr: 1 }`.\n\n### route.middleware\n\nType: `property`\n\nNázvy middleware, ktoré sa spustia pred akciou.\n\nReturns: `Array`\n\nPríznaky `#name` v ich poradí. `MIDDLEWARE(name, fn, assign)` môže pridať názvy k existujúcim trasám.\n\n### route.auth\n\nType: `property`\n\nAutorizácia trasy.\n\nReturns: `Number`\n\n`0` pre všetkých, `1` pre prihlásených používateľov (`+`), `2` pre návštevníkov, ktorí nie sú prihlásení (`-`). Zdieľaná trasa API má `0`; každý endpoint si ponecháva vlastnú hodnotu.\n\n### route.size\n\nType: `property`\n\nMaximálna veľkosť tela v bajtoch.\n\nReturns: `Number`\n\nNastavuje ju príznak veľkosti alebo argument `size`; inak `CONF.$httpmaxsize * 1024` (`CONF.$wsmaxsize * 1024` pre trasy `SOCKET`).\n\n### route.timeout\n\nType: `property`\n\nTimeout v sekundách, alebo `0`.\n\nReturns: `Number`\n\n`0` znamená, že požiadavka používa `CONF.$httptimeout`.\n\n### route.priority\n\nType: `property`\n\nPoradie, v akom sa kontrolujú trasy s rovnakou metódou a cestou.\n\nReturns: `Number`\n\nZačína na `100`, každý príznak `@` ho zníži o jedna a zástupný znak o 50. Vyššie hodnoty sa kontrolujú skôr.\n\n### route.type\n\nType: `property`\n\nDruh trasy.\n\nReturns: `String`\n\n`route`, `file` alebo `websocket`.\n\n### route.remove()\n\nType: `method`\n\nOdstráni trasu.\n\nReturns: `undefined`\n\nOdregistruje trasu a znova zoradí tabuľku smerovania. Funguje pre HTTP trasy, API endpointy (zdieľaná trasa `POST` API sa odstráni s jej posledným endpointom), trasy `FILE` a trasy `SOCKET`, ktorých otvorené spojenia sa zatvoria.\n\nExample: Dočasná trasa\n```js\nvar route = ROUTE('GET /maintenance/', function($) {\n\t$.plain('Back soon');\n});\n\nsetTimeout(function() {\n\troute.remove();\n}, 60000);\n```\n\n### CORS([origins])\n\nType: `method`\n\nNastaví originy povolené pre cross-origin požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `origins` | `String` | no | `'*'` | Povolené originy, `*`, alebo `+origins` na pridanie. |\n\nReturns: `undefined`\n\nBez argumentu je povolený každý origin (`*`). Inak zadaj úplné originy oddelené čiarkami, `;` alebo `|`. Položka, ktorá začína `*`, povolí každý origin, ktorý obsahuje zvyšok. Hodnota, ktorá začína `+`, pridá originy k aktuálnemu zoznamu. Požiadavky z rovnakého hostu prejdú vždy. Povolená požiadavka dostane `Access-Control-Allow-Origin` (origin), `-Credentials: true`, `-Methods`, `-Headers` a `-Expose-Headers` (`*`) a na `OPTIONS` sa odpovie hneď. Ostatné originy dostanú `400` s `Invalid origin (CORS)`.\n\nExample: Povolenie dvoch aplikácií\n```js\nCORS('https://app.example.com,https://admin.example.com');\n```\n\nExample: Pridanie jedného a povolenie subdomén\n```js\nCORS('+https://partner.com');\nCORS('+*example.org');\n```\n\nExample: Akýkoľvek origin\n```js\nCORS();\n```\n\n### PROXY(path, [target])\n\nType: `method`\n\nPrepošle požiadavky pod cestou na iný server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Začiatok cesty požiadavky, napríklad `/cdn/`. |\n| `target` | `String|Function` | no |  | Cieľová URL, cesta k Unix socketu alebo `function($)`. |\n\nReturns: `Proxy` Objekt proxy s reťaziteľnými metódami, alebo nič, keď proxy odstraňuješ.\n\nProxy sa kontrolujú pred trasami, pre každú metódu aj pre WebSocket upgrady. `path` by mala končiť `/` a dostane `CONF.$root`. `target` je URL `http://`/`https://`, cesta k Unix socketu alebo funkcia, ktorá dostane kontrolér a odpovie sama. Preposlaná požiadavka si ponechá hlavičky (bez `Host`) a dostane `X-Forwarded-For`, `X-Forwarded-URL` a `X-Forwarded-Host`. Keď cieľ zlyhá, klient dostane `503`. `PROXY(path)` bez cieľa odstráni proxy pre danú cestu.\n\nExample: Preposlanie na službu\n```js\nPROXY('/search/', 'http://127.0.0.1:9200').copy('replace');\n```\n\nExample: Unix socket\n```js\nPROXY('/legacy/', '/var/run/legacy.sock');\n```\n\nExample: Vlastný handler\n```js\nPROXY('/ping/', function($) {\n\t$.plain('pong');\n});\n```\n\n### proxy.copy(type)\n\nType: `method`\n\nNastaví, ako sa cesta požiadavky skopíruje do cieľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `none`, `replace` alebo `extend`. |\n\nReturns: `Proxy` Proxy.\n\n`none` (predvolene): cieľová URL s query stringom požiadavky. `replace`: cieľ s časťou cesty za cestou proxy (keď má cieľová URL vlastnú cestu, `replace` funguje ako `extend`). `extend`: cieľová cesta plus zvyšok cesty požiadavky plus query stringy požiadavky a cieľa.\n\nExample: Zachovanie podciest\n```js\n// GET /cl/something/?q=1 --> https://example.com/something/?q=1\nPROXY('/cl/', 'https://example.com').copy('extend');\n```\n\n### proxy.before(callback)\n\nType: `method`\n\nZmení odchádzajúcu požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(uri, $)`. |\n\nReturns: `Proxy` Proxy.\n\n`callback(uri, $)` sa spustí pred odoslaním požiadavky. `uri` obsahuje voľby požiadavky Node.js (`path`, `headers`, `method`...).\n\nExample: Pridanie tokenu\n```js\nPROXY('/api2/', 'https://internal.example.com').before(function(uri, $) {\n\turi.headers['x-token'] = CONF.internal_token;\n});\n```\n\n### proxy.after(callback)\n\nType: `method`\n\nPrečíta odpoveď cieľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(response)`. |\n\nReturns: `Proxy` Proxy.\n\n`callback(response)` dostane odpoveď Node.js predtým, ako sa pošle klientovi; môžeš zmeniť `response.headers`.\n\nExample: Odstránenie hlavičky\n```js\nPROXY('/cdn/', 'https://cdn.example.com').after(function(response) {\n\tdelete response.headers['set-cookie'];\n});\n```\n\n### proxy.check(callback)\n\nType: `method`\n\nPre každú požiadavku rozhodne, či sa proxy použije.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)`, ktorá vráti boolean. |\n\nReturns: `Proxy` Proxy.\n\n`callback($)` vráti `true`, ak sa má požiadavka preposlať. Inak požiadavka ide na trasy.\n\nExample: Len GET\n```js\nPROXY('/files/', 'http://127.0.0.1:8001').check($ => $.method === 'GET');\n```\n\n### proxy.timeout(ms)\n\nType: `method`\n\nNastaví timeout preposlanej požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes |  | Timeout v milisekundách. |\n\nReturns: `Proxy` Proxy.\n\nV milisekundách. Bez neho (alebo s `0`) proxy používa `CONF.$proxytimeout` sekúnd.\n\nExample: 30 sekúnd\n```js\nPROXY('/reports/', 'http://127.0.0.1:8002').timeout(30000);\n```\n\n### proxy.remove()\n\nType: `method`\n\nOdstráni proxy.\n\nReturns: `undefined`\n\nPožiadavky pod jej cestou idú opäť na trasy. `PROXY(path)` bez cieľa robí to isté.\n\nExample: Odstránenie\n```js\nvar proxy = PROXY('/old/', 'http://127.0.0.1:8003');\nproxy.remove();\n```\n\n### $api : /api/\n\nType: `config`\n\nCesta, ktorú v API trasách zastupuje `?`.\n\nReturns: `String`\n\nPredvolene `/api/`. Keď je nastavené `$root`, pridá sa pred ňu.\n\nExample: /config\n```js\n$api : /rpc/\n```\n\n### $root : /app/\n\nType: `config`\n\nPrefix cesty pre všetky trasy.\n\nReturns: `String`\n\nPridá sa pred každú trasu, proxy aj cestu `$api`, napríklad keď aplikácia beží pod `/app/` za webovým serverom. Predvolene prázdne.\n\nExample: /config\n```js\n$root : /admin/\n```\n\n### $cors : https://app.example.com\n\nType: `config`\n\nOriginy povolené pre cross-origin požiadavky.\n\nReturns: `String`\n\nRovnaká hodnota, akú prijíma `CORS()`: `*`, alebo originy oddelené čiarkami, s položkami `*domain` pre čiastočnú zhodu. Predvolene prázdne (cross-origin požiadavky sa nekontrolujú).\n\nExample: /config\n```js\n$cors : https://app.example.com, *example.org\n```\n\n### $httpmaxsize : 256\n\nType: `config`\n\nPredvolená maximálna veľkosť tela HTTP trás v kB.\n\nReturns: `Number`\n\nPredvolene `256`. Trasa ju prepíše príznakom veľkosti.\n\nExample: /config\n```js\n$httpmaxsize : 1024\n```\n\n### $httptimeout : 5\n\nType: `config`\n\nPredvolený timeout HTTP požiadaviek v sekundách.\n\nReturns: `Number`\n\nPredvolene `5`. Trasa ho prepíše príznakom timeoutu.\n\nExample: /config\n```js\n$httptimeout : 15\n```\n\n### $proxytimeout : 5\n\nType: `config`\n\nPredvolený timeout požiadaviek `PROXY()` v sekundách.\n\nReturns: `Number`\n\nPredvolene `5`. `proxy.timeout()` ho prepíše pre jednu proxy.\n\nExample: /config\n```js\n$proxytimeout : 30\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [size])","since":"","deprecated":false},{"type":"type","name":"+ flag","signature":"ROUTE('+METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"- flag","signature":"ROUTE('-METHOD /path/', action)","since":"","deprecated":false},{"type":"type","name":"{param}","signature":"ROUTE('GET /path/{name}/', action)","since":"","deprecated":false},{"type":"type","name":"* wildcard","signature":"ROUTE('GET /path/*', action)","since":"","deprecated":false},{"type":"type","name":"API ?","signature":"ROUTE('[+|-]API ? endpoint[/{param}] --> Action', [action])","since":"","deprecated":false},{"type":"type","name":"--> actions","signature":"ROUTE('METHOD /path/ --> Action1 [Action2 (response)]')","since":"","deprecated":false},{"type":"type","name":"<size","signature":"ROUTE('METHOD /path/ <10MB', action)","since":"","deprecated":false},{"type":"type","name":"<timeout","signature":"ROUTE('METHOD /path/ <30s', action)","since":"","deprecated":false},{"type":"type","name":"#middleware","signature":"ROUTE('METHOD /path/ #name', action)","since":"","deprecated":false},{"type":"type","name":"@json","signature":"ROUTE('METHOD /path/ @json', action)","since":"","deprecated":false},{"type":"type","name":"@xml","signature":"ROUTE('METHOD /path/ @xml', action)","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('METHOD /path/ @upload', action)","since":"","deprecated":false},{"type":"type","name":"@xhr","signature":"ROUTE('METHOD /path/ @xhr', action)","since":"","deprecated":false},{"type":"type","name":"@mobile","signature":"ROUTE('METHOD /path/ @mobile', action)","since":"","deprecated":false},{"type":"type","name":"@robot","signature":"ROUTE('METHOD /path/ @robot', action)","since":"","deprecated":false},{"type":"type","name":"@referrer","signature":"ROUTE('METHOD /path/ @referrer', action)","since":"","deprecated":false},{"type":"type","name":"@debug","signature":"ROUTE('METHOD /path/ @debug', action)","since":"","deprecated":false},{"type":"type","name":"@release","signature":"ROUTE('METHOD /path/ @release', action)","since":"","deprecated":false},{"type":"type","name":"FILE","signature":"ROUTE('FILE /path/pattern', action)","since":"","deprecated":false},{"type":"type","name":"SOCKET","signature":"ROUTE('SOCKET /path/ [flags]', action)","since":"","deprecated":false},{"type":"type","name":"#code","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"class","name":"Route","signature":"Route","since":"","deprecated":false},{"type":"property","name":"route.method","signature":"route.method","since":"","deprecated":false},{"type":"property","name":"route.url","signature":"route.url","since":"","deprecated":false},{"type":"property","name":"route.params","signature":"route.params","since":"","deprecated":false},{"type":"property","name":"route.flags","signature":"route.flags","since":"","deprecated":false},{"type":"property","name":"route.middleware","signature":"route.middleware","since":"","deprecated":false},{"type":"property","name":"route.auth","signature":"route.auth","since":"","deprecated":false},{"type":"property","name":"route.size","signature":"route.size","since":"","deprecated":false},{"type":"property","name":"route.timeout","signature":"route.timeout","since":"","deprecated":false},{"type":"property","name":"route.priority","signature":"route.priority","since":"","deprecated":false},{"type":"property","name":"route.type","signature":"route.type","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([origins])","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(path, [target])","since":"","deprecated":false},{"type":"method","name":"proxy.copy()","signature":"proxy.copy(type)","since":"","deprecated":false},{"type":"method","name":"proxy.before()","signature":"proxy.before(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.after()","signature":"proxy.after(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.check()","signature":"proxy.check(callback)","since":"","deprecated":false},{"type":"method","name":"proxy.timeout()","signature":"proxy.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"proxy.remove()","signature":"proxy.remove()","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : /api/","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root : /app/","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : https://app.example.com","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : 5","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : 5","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JafwV6CWx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/controller/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Controller","summary":"Properties and methods of the controller `$` that every route action receives.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/controller/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Controller\n\n> Properties and methods of the controller `$` that every route action receives.\n\nThe controller is the `$` argument of every route action. It holds the request data (`$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.user`...) and the methods that send the response (`$.json()`, `$.success()`, `$.invalid()`, `$.view()`, `$.file()`, `$.redirect()`...). For a walkthrough with examples, read the guide [Controller](../../guides/controller/).\n\n## API\n\n### $.req\n\nType: `property`\n\nThe Node.js request object.\n\nReturns: `IncomingMessage`\n\nThe `http.IncomingMessage` of the request. Use it only for what the controller does not offer.\n\n### $.res\n\nType: `property`\n\nThe Node.js response object.\n\nReturns: `ServerResponse`\n\nThe `http.ServerResponse` of the request. When you write to it yourself, call `$.custom()` first so the framework does not answer the request too.\n\n### $.method\n\nType: `property`\n\nThe HTTP method of the request.\n\nReturns: `String`\n\nAn upper-case string such as `GET`, `POST`, `PUT`, `PATCH` or `DELETE`.\n\nExample: Example\n```js\nROUTE('POST /api/items/', function($) {\n\t// $.method === 'POST'\n\t$.success();\n});\n```\n\n### $.url\n\nType: `property`\n\nThe path of the URL.\n\nReturns: `String`\n\nThe path without the query string. A path without a file extension always ends with `/`, and double slashes are merged. The letters keep their case.\n\nExample: Example\n```js\nROUTE('GET /docs/', function($) {\n\t// /docs?page=1 gives '/docs/'\n\t$.plain($.url);\n});\n```\n\n### $.uri\n\nType: `property`\n\nThe parsed URL.\n\nReturns: `Object`\n\nAn object with `pathname` (the same as `$.url`), `search` (the query string without `?`), `split` (the segments), `ext` (the file extension) and `file` (`true` for a request of a static file).\n\n### $.split\n\nType: `property`\n\nThe segments of the path.\n\nReturns: `String[]`\n\nAn array of the parts of the path: `/blog/2025/hello/` gives `['blog', '2025', 'hello']`. The root path `/` gives an empty array.\n\nExample: Example\n```js\nROUTE('GET /blog/*', function($) {\n\t$.json($.split);\n});\n```\n\n### $.params\n\nType: `property`\n\nThe dynamic parts of the URL.\n\nReturns: `Object`\n\nEach `{name}` of the route becomes a key with the matching segment of the path as a string. Convert numbers and dates yourself.\n\nExample: Example\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id}/', order);\n};\n\nfunction order($) {\n\tvar id = $.params.id;\n\t$.json({ id: id });\n}\n```\n\n### $.query\n\nType: `property`\n\nThe query string as an object.\n\nReturns: `Object`\n\nValues are strings: `?page=2&q=shoes` gives `{ page: '2', q: 'shoes' }`. You can assign a new object. In an API route, it contains the query of the `schema` field.\n\nExample: Paging\n```js\nfunction list($) {\n\tvar page = ($.query.page || '1').parseInt();\n\t$.json({ page: page });\n}\n```\n\n### $.body\n\nType: `property`\n\nThe parsed body of the request.\n\nReturns: `Object`\n\nFor `POST`, `PUT`, `PATCH` and `DELETE` requests. A JSON body is parsed into an object, a URL-encoded form into an object of strings, and a `multipart/form-data` request gives the fields of the form. Other content types keep `{}` and the raw data is in `$.payload`. In an API route, it contains the `data` of the request.\n\nExample: Read the body\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar email = $.body.email;\n\t$.success();\n}\n```\n\n### $.payload\n\nType: `property`\n\nThe raw body as a Buffer.\n\nReturns: `Buffer`\n\nThe bytes of the body for every content type except `multipart/form-data`. Use it for XML, plain text or binary uploads. It is released when the response ends.\n\nExample: Example\n```js\nROUTE('POST /api/xml/', function($) {\n\tvar xml = $.payload.toString('utf8');\n\t$.plain('Received ' + xml.length + ' chars');\n});\n```\n\n### $.files\n\nType: `property`\n\nThe uploaded files.\n\nReturns: `HttpFile[]`\n\nAn array of files (`HttpFile`) from a `multipart/form-data` request, empty for other requests. The files are temporary and are removed when the response ends, unless you move them or call `$.autoclear(false)`.\n\nExample: Example\n```js\nfunction upload($) {\n\tvar names = [];\n\tfor (var file of $.files)\n\t\tnames.push(file.filename + ' (' + file.size + ' bytes)');\n\t$.json(names);\n}\n```\n\n### $.headers\n\nType: `property`\n\nThe request headers.\n\nReturns: `Object`\n\nThe headers object of Node.js: names are in lower case.\n\nExample: Example\n```js\nfunction info($) {\n\t$.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] });\n}\n```\n\n### $.ip\n\nType: `property`\n\nThe IP address of the client.\n\nReturns: `String`\n\nThe first address of `X-Forwarded-For` when the header exists (behind a proxy), otherwise the remote address of the connection.\n\nExample: Example\n```js\nfunction track($) {\n\tconsole.log('Request from', $.ip);\n\t$.success();\n}\n```\n\n### $.ua\n\nType: `property`\n\nA short name of the client from the User-Agent header.\n\nReturns: `String`\n\nThe system and the browser found in `User-Agent`, for example `Mac OS Chrome`, or an empty string without the header.\n\n### $.mobile\n\nType: `property`\n\n`true` for a mobile device.\n\nReturns: `Boolean`\n\n`true` when `User-Agent` matches a phone or a tablet (Android, iPhone, iPad, Mobile, Tablet...).\n\n### $.robot\n\nType: `property`\n\n`true` for a crawler.\n\nReturns: `Boolean`\n\n`true` when `User-Agent` contains `search`, `agent`, `bot`, `crawler` or `spider`.\n\n### $.xhr\n\nType: `property`\n\n`true` for an XMLHttpRequest.\n\nReturns: `Boolean`\n\n`true` when the request has the header `X-Requested-With: XMLHttpRequest`. `$.fallback()` answers such requests with JSON instead of an HTML page.\n\n### $.protocol\n\nType: `property`\n\nThe protocol of the request.\n\nReturns: `String`\n\n`https` for an encrypted connection or when a proxy says so (`X-Forwarded-Proto: https`, `X-Forwarded-SSL: on` or `X-Forwarded-Port: 443`), otherwise `http`.\n\n### $.address\n\nType: `property`\n\nThe full URL of the request.\n\nReturns: `String`\n\nThe protocol, the host and the original URL with the query string, for example `https://example.com/products/?page=2`.\n\n### $.user\n\nType: `property`\n\nThe signed-in user.\n\nReturns: `Object`\n\nThe object your authorization delegate returned for the request, or `undefined` when nobody is signed in. See [Authorization](../../guides/authorization/).\n\nExample: Example\n```js\nROUTE('+GET /api/account/', function($) {\n\t$.json({ name: $.user.name });\n});\n```\n\n### $.language\n\nType: `property`\n\nThe language of the request.\n\nReturns: `String`\n\nThe value your localization delegate returned, or an empty string. It selects the translation of views and of error messages. See [Localization](../../guides/localization/).\n\n### $.response\n\nType: `property`\n\nThe response that will be sent.\n\nReturns: `Object`\n\nAn object with `status` (default `200`), `headers` (an object of response headers), `cache` (HTTP cache for files) and `minify`. Change it before you call a response method.\n\nExample: Status and a header\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\n### $.json(value, [beautify], [replacer])\n\nType: `method`\n\nSends JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value to serialize. |\n| `beautify` | `Boolean` | no | `false` | `true` indents the JSON with tabs. |\n| `replacer` | `Function|Array` | no |  | A replacer for `JSON.stringify()`. |\n\nSerializes `value` with `JSON.stringify()`, sets `content-type: application/json` and headers that disable caching (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). `beautify` indents the output with tabs. `replacer` is passed to `JSON.stringify()` as its second argument: a function `(key, value)` or an array of keys to keep.\n\nExample: Example\n```js\nROUTE('GET /api/products/', function($) {\n\t$.json([{ id: 1, name: 'Shoes' }]);\n});\n```\n\nExample: Beautify and hide a key\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n### $.jsonstring(value)\n\nType: `method`\n\nSends a string that is already JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | A JSON string. |\n\nSends the string as it is with the same headers as `$.json()`. Use it for JSON you have cached or read from a file.\n\nExample: Example\n```js\nfunction cached($) {\n\t$.jsonstring('{\"ok\":true}');\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nSends `{ success: true, value: value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | An optional value for the `value` key. |\n\nA shortcut for the usual answer of an API. Without `value` the response is `{\"success\":true}`.\n\nExample: Example\n```js\nfunction remove($) {\n\tNOSQL('products').remove().id($.params.id);\n\t$.success($.params.id);\n}\n```\n\n### $.invalid(error)\n\nType: `method`\n\nSends an error as JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Error|ErrorBuilder|Number` | yes |  | The error. |\n\nAccepts a string, an `Error`, an `ErrorBuilder` or an HTTP status code. The response is a JSON array such as `[{\"error\":\"Name is required\"}]` with the status `400`, or the given status code (`$.invalid(404)` gives `[{\"error\":\"404: Not Found\"}]` with status `404`). Text written as `@(text)` is translated from a resource. Without an argument it sends `401`. The response is sent asynchronously.\n\nExample: Example\n```js\nfunction save($) {\n\tif (!$.body.email) {\n\t\t$.invalid('@(Email is required)');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nSends an error message and logs the real error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number|ErrorBuilder` | yes |  | The error for the client. |\n| `error` | `Error|String` | no |  | The error for the log. |\n\nSends `message` as `$.invalid(message)` does and writes `error` to the error log with `F.error()` and the URL of the request. The client gets only the message. `message` can also be an `ErrorBuilder`.\n\nExample: Example\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n### $.html(value)\n\nType: `method`\n\nSends HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML. |\n\nSets `content-type: text/html` and sends the string. It is minified when the configuration key `$minifyhtml` is `true` (the default).\n\nExample: Example\n```js\nROUTE('GET /hello/', function($) {\n\t$.html('<h1>Hello</h1>');\n});\n```\n\n### $.throw(error)\n\nType: `method`\n\nWrites an error to the log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | The error. |\n\nReturns: `Controller` The same controller.\n\nPasses `error` with the URL of the request to the error handler of the framework (`DEF.onError`): it is printed, kept in `F.errors` and emitted as the `error` event. Nothing is sent to the client. Returns `$`.\n\nExample: Example\n```js\nfunction save($) {\n\tNOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) {\n\t\terr && $.throw(err);\n\t});\n\t$.success();\n}\n```\n\n### $.plain(value)\n\nType: `method`\n\nSends plain text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The text. |\n\nSets `content-type: text/plain`. `$.text()` is the same method.\n\nExample: Example\n```js\nROUTE('FILE /robots.txt', function($) {\n\t$.plain('User-agent: *');\n});\n```\n\n### $.xml(value)\n\nType: `method`\n\nSends XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | XML. |\n\nSets `content-type: text/xml` and sends the string.\n\nExample: Example\n```js\nfunction feed($) {\n\t$.xml('<?xml version=\"1.0\"?><rss></rss>');\n}\n```\n\n### $.empty()\n\nType: `method`\n\nSends status 204 without a body.\n\nUse it when a request needs no data in the answer.\n\nExample: Example\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.empty();\n});\n```\n\n### $.redirect(url, [permanent])\n\nType: `method`\n\nRedirects the client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The target URL. |\n| `permanent` | `Boolean` | no | `false` | `true` for a permanent redirect (301). |\n\nSets the `Location` header and the status `302`, or `301` when `permanent` is `true`.\n\nExample: Example\n```js\nROUTE('GET /old/', function($) {\n\t$.redirect('/new/', true);\n});\n```\n\n### $.view([name], [model])\n\nType: `method`\n\nRenders a view and sends it as HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The name of the view, without the extension. |\n| `model` | `Object` | no |  | The model for the view. |\n\nReturns: `View` The view instance.\n\nRenders the view `name` from the `/views/` directory with `model` and sends it with `$.html()`. With the layout from `$.layout()`. Without `name` it only returns a new `View` instance for the controller. See [Views](../../guides/views/).\n\nExample: Example\n```js\nfunction detail($) {\n\tNOSQL('products').one().id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.view('detail', response);\n\t\telse\n\t\t\t$.fallback(404);\n\t});\n}\n```\n\n### $.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. |\n\nThe view rendered with `$.view()` is placed into the layout `name`.\n\nExample: Example\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('dashboard');\n}\n```\n\n### $.file(path, [download])\n\nType: `method`\n\nSends a file from the disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | An absolute path of the file. |\n| `download` | `Boolean|String` | no |  | A file name for the download, or `true`. |\n\nSets the content type from the extension and supports `Range` requests, gzip and HTTP cache headers. JS, CSS and HTML files are minified unless their name contains `.min`, `-min` or `@min`. With `download` the browser saves the file: pass `true` to keep its name or a string to rename it. A missing file gives `404`.\n\nExample: Example\n```js\nROUTE('GET /download/', function($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n});\n```\n\n### $.stream(type, stream, [download])\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` | `ReadableStream` | yes |  | The stream. |\n| `download` | `String` | no |  | A file name for the download. |\n\nPipes `stream` to the response with the content type `type` (default `application/octet-stream`). Text types are compressed with gzip when the client supports it. A string `download` sends the stream as an attachment with that name.\n\nExample: Example\n```js\nfunction exportcsv($) {\n\tvar stream = F.Fs.createReadStream(PATH.root('export.csv'));\n\t$.stream('text/csv', stream, 'export.csv');\n}\n```\n\n### $.binary(buffer, type, [download])\n\nType: `method`\n\nSends a Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The data. |\n| `type` | `String` | yes |  | The content type. |\n| `download` | `String` | no |  | A file name for the download. |\n\nSends the bytes with the content type `type`. A string `download` sends them as an attachment with that name.\n\nExample: Example\n```js\nfunction pixel($) {\n\tvar buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');\n\t$.binary(buffer, 'image/gif');\n}\n```\n\n### $.content(value, [type])\n\nType: `method`\n\nSends a string or a Buffer with a content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | The content. |\n| `type` | `String` | no | `'application/octet-stream'` | The content type. |\n\nSends `value` with the header `content-type: type`; without `type` it is `application/octet-stream`. A string is sent as UTF-8. Unlike `$.binary()`, it takes a string too and has no download name.\n\nExample: CSV\n```js\nROUTE('GET /export/', function($) {\n\t$.content('id,name\\n1,Mug\\n', 'text/csv');\n});\n```\n\n### $.image(opt)\n\nType: `method`\n\nProcesses an image and sends it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | The options. |\n\nLoads an image stream, lets you change it and sends the result. `opt.ext` (required) is the extension of the output, `opt.load(next, opt)` calls `next(stream)` with the source, `opt.image(img, opt)` changes the image (see [Images](../../guides/images/)), `opt.cache` is a key to keep the result in the temporary directory, and `opt.date` a date for the HTTP cache.\n\nExample: Example\n```js\nfunction thumbnail($) {\n\t$.image({\n\t\text: 'jpg',\n\t\tcache: 'thumb_' + $.params.id,\n\t\tload: function(next) {\n\t\t\tnext(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg')));\n\t\t},\n\t\timage: function(img) {\n\t\t\timg.resize(200, 200);\n\t\t}\n\t});\n}\n```\n\n### $.filefs(name, id, [download], [checkmeta])\n\nType: `method`\n\nSends a file from a file storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the file storage. |\n| `id` | `String` | yes |  | The identifier of the file. |\n| `download` | `Boolean|String` | no |  | Send as an attachment. |\n| `checkmeta` | `Function` | no |  | A check of the metadata. |\n\nReturns: `Object` The options passed to the storage.\n\nSends the file `id` from the file storage `name` (see [File storage](../../guides/file-storage/)). `download` sends it as an attachment, `true` with its stored name or a string for another name. `checkmeta` is a function that receives the metadata of the file and decides whether it can be sent.\n\nExample: Example\n```js\nROUTE('GET /files/{id}/', function($) {\n\t$.filefs('files', $.params.id);\n});\n```\n\n### $.proxy(opt)\n\nType: `method`\n\nForwards the request to another server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `String|Object` | yes |  | The target URL or options. |\n\nSends the method, the headers, the body and the query string of the request to `opt` (a URL, or an object with `url`, `method`, `headers`, `timeout` (default 10000 ms) and `callback(err, response)`) and answers with the response of that server.\n\nExample: Example\n```js\nROUTE('GET /api/weather/', function($) {\n\t$.proxy('https://weather.example.com/today/');\n});\n```\n\n### $.fallback(code, [error])\n\nType: `method`\n\nSends an error page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | The HTTP status code. |\n| `error` | `String|Error` | no |  | The error for debug mode. |\n\nWhen a route `#code` exists (for example `ROUTE('#404', fn)`), its action handles the request; the status stays `200` unless the action sets `$.response.status`. Otherwise it sends the built-in error page with the status `code`, or `$.invalid(code)` for XHR requests. `error` is shown on the page in debug mode.\n\nExample: Example\n```js\nexports.install = function() {\n\tROUTE('GET /secret/', function($) {\n\t\t$.fallback(404);\n\t});\n\tROUTE('#404', function($) {\n\t\t$.view('404');\n\t});\n};\n```\n\n### $.callback([err], [value])\n\nType: `method`\n\nAnswers from a callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | no |  | An error. |\n| `value` | `Object` | no |  | The value to send. |\n\nReturns: `Function` A callback when called without arguments.\n\nWithout arguments it returns a function `(err, response)` that calls `$.invalid(err)` or `$.json(response)`. With arguments it answers at once: `$.invalid(err)`, `$.success()` when `value` is `undefined`, or `$.json(value)`.\n\nExample: Example\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.callback());\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nReturns a callback that answers with success.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | The value, or `true` for the response of the callback. |\n\nReturns: `Function` A callback.\n\nThe returned function `(err, response)` calls `$.invalid(err)` on an error, otherwise sends `{ success: true, value: value }`. Pass `true` to use the `response` of the callback as the value.\n\nExample: Example\n```js\nROUTE('POST /api/products/', function($) {\n\tNOSQL('products').insert($.body).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` | yes |  | Called when there is no error. |\n\nReturns: `Function` A callback.\n\nThe returned function `(err, a, b, c)` calls `$.invalid(err)` on an error, otherwise `callback(a, b, c)` with the controller as `this`.\n\nExample: Example\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.successful(function(response) {\n\t\t$.json(response);\n\t}));\n});\n```\n\n### $.custom()\n\nType: `method`\n\nTells the framework you send the response yourself.\n\nMarks the controller as finished so that no response method writes to it. Then write to `$.res` with the Node.js API.\n\nExample: Example\n```js\nROUTE('GET /events/', function($) {\n\t$.custom();\n\t$.res.writeHead(200, { 'content-type': 'text/event-stream' });\n\t$.res.write('data: hello\\n\\n');\n});\n```\n\n### $.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nReads or sets a cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the cookie. |\n| `value` | `String` | no |  | The value to set. |\n| `expires` | `Date|String|Object` | no |  | The expiration, or the options. |\n| `options` | `Object` | no |  | The options of the cookie. |\n\nReturns: `String|Controller` The value when reading, the controller when setting.\n\nWith only `name` it returns the decoded value of the cookie, or an empty string. With `value` it adds a `Set-Cookie` header (a cookie with the same name set earlier in the request is replaced) and returns the controller. `expires` is a `Date`, a string such as `'7 days'`, or the options object. The options are `expires`, `domain`, `path` (default `/`), `secure` (default from `$cookiesecure`), `httponly` and `samesite` (default from `$cookiesamesite`, `'Lax'`).\n\nExample: Example\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' });\n\t$.success();\n}\n\nfunction profile($) {\n\t$.json({ session: $.cookie('session') });\n}\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nSets the HTTP cache headers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | The date of the last change. |\n\nSets `Last-Modified` to `date`, `ETag`, and `Expires` and `Cache-Control` when they are not set yet.\n\nExample: Example\n```js\nfunction article($) {\n\tvar updated = new Date(2025, 0, 1);\n\tif ($.notmodified(updated.toUTCString()))\n\t\treturn;\n\t$.httpcache(updated);\n\t$.view('article');\n}\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nAnswers 304 when the client has the same version.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | The date of the last change as a UTC string. |\n\nReturns: `Boolean` `true` when the 304 response was sent.\n\nCompares `date` (a UTC string) with the `If-Modified-Since` header. When they are equal it sends `304 Not Modified` and returns `true`.\n\n### $.hostname([path])\n\nType: `method`\n\nReturns the protocol and the host.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | A path to append. |\n\nReturns: `String` The URL.\n\nGives `protocol://host` of the request with an optional path appended.\n\nExample: Example\n```js\nfunction share($) {\n\t$.json({ url: $.hostname('/products/' + $.params.id + '/') });\n}\n```\n\n### $.href([key], [value])\n\nType: `method`\n\nReturns the query string with one parameter changed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | The name of the parameter, or an object with the parameters to set. |\n| `value` | `String|Number|Array|Object` | no |  | The new value. |\n\nReturns: `String` The query string with `?`, or an empty string.\n\nWithout arguments it returns the query string of the request (`?page=2&sort=name`), or an empty string. `$.href(key, value)` returns it with `key` set to `value`; the other parameters stay. Without `value` the current value of `key` is kept. More arguments after `value` are names of parameters to remove. An array value writes the parameter once for each item and an object value is written as JSON. `$.href({ key: value, ... })` returns the URL of the request with the query string changed by the keys of the object. It works like `@{href()}` in views.\n\nExample: Paging\n```js\n// GET /products/?page=2&sort=name\nfunction products($) {\n\t$.json({\n\t\tnext: $.href('page', 3),           // ?page=3&sort=name\n\t\tcurrent: $.href()                  // ?page=2&sort=name\n\t});\n}\n```\n\nExample: Remove a parameter, or change several\n```js\n// GET /products/?page=2&sort=name&q=pen\n$.href('page', 1, 'sort');           // ?page=1&q=pen\n$.href({ page: 1, sort: 'price' });  // /products/?page=1&sort=price&q=pen\n```\n\n### $.touch([url])\n\nType: `method`\n\nClears the cached state of a static file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | The URL of the file. |\n\nReturns: `Controller` The same controller.\n\nCalls `TOUCH(url)`; without `url` it uses the URL of the request. Use it after the route changes a file in `public/`. Returns `$`.\n\nExample: Example\n```js\nROUTE('POST /api/theme/', function($) {\n\tF.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) {\n\t\tif (err) {\n\t\t\t$.invalidsafe('The theme can\\'t be saved', err);\n\t\t\treturn;\n\t\t}\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t});\n});\n```\n\n### $.action(name, model)\n\nType: `method`\n\nRuns an action with this controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the action, for example `Products/list`. |\n| `model` | `Object` | yes |  | The data for the action. |\n\nReturns: `Object` The action instance.\n\nCalls the action `name` (see [Actions](../../guides/actions/)) with `model` and the controller. Call `.autorespond()` on the result to answer the request with the output of the action.\n\nExample: Example\n```js\nROUTE('POST /api/orders/', function($) {\n\t$.action('Orders/create', $.body).autorespond();\n});\n```\n\n### $.authorize([callback])\n\nType: `method`\n\nRuns the authorization delegate manually.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Receives `(err, user)`. |\n\nReturns: `Promise` When called without a callback.\n\nCalls your authorization delegate for this request. When it returns a user, `$.user` is set. The callback is `(err, user)`; without a callback the method returns a `Promise` with the user (or `undefined`).\n\nExample: Example\n```js\nROUTE('GET /api/me/', async function($) {\n\tvar user = await $.authorize();\n\t$.json({ signed: !!user });\n});\n```\n\n### $.csrf()\n\nType: `method`\n\nCreates a CSRF token.\n\nReturns: `String` The token.\n\nReturns a token bound to the IP address and the browser of the client, valid for the time in `$csrfexpiration` (default `30 minutes`). It needs the configuration key `secret_csrf`; without it the token is an empty string.\n\nExample: Example\n```js\nROUTE('GET /form/', function($) {\n\t$.view('form', { token: $.csrf() });\n});\n```\n\n### $.autoclear([value])\n\nType: `method`\n\nKeeps or removes uploaded files after the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no |  | `false` keeps the files. |\n\nUploaded files are removed when the response ends. `$.autoclear(false)` keeps them, for example when you process them later.\n\n### $.cancel()\n\nType: `method`\n\nStops the processing of the request in an event.\n\nCall it in `ON('request', fn)` or `ON('controller', fn)` when the handler answers the request itself.\n\nExample: Example\n```js\nON('request', function($) {\n\tif ($.url === '/health/') {\n\t\t$.cancel();\n\t\t$.plain('OK');\n\t}\n});\n```\n\n### HttpFile\n\nType: `class`\n\nAn uploaded file in `$.files`.\n\nProperties: `name` (the field of the form), `filename`, `type` (the content type), `size` (bytes), `extension`, `width` and `height` (images), `path` (the temporary file), and `isImage`, `isVideo`, `isAudio`.\n\nMethods:\n\n- `move(filename, [callback])` (also `rename()`) moves the file; without a callback it returns a `Promise`. A moved file is not removed after the response.\n- `copy(filename, callback)` copies the file.\n- `read([callback])` reads the file into a `Buffer`; without a callback it returns a `Promise`.\n- `md5([callback])` computes the MD5 hash in hex; without a callback it returns a `Promise`.\n- `stream([opt])` returns a read stream; `pipe(stream, [opt])` pipes the file into a stream.\n- `image([shell])` returns an image object for [Images](../../guides/images/).\n- `fs(storage, id, [callback])` saves the file into a [file storage](../../guides/file-storage/).\n\nExample: Save to a file storage\n```js\nROUTE('POST /upload/ <10MB', function($) {\n\tvar file = $.files[0];\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n});\n```\n","entries":[{"type":"property","name":"$.req","signature":"$.req","since":"","deprecated":false},{"type":"property","name":"$.res","signature":"$.res","since":"","deprecated":false},{"type":"property","name":"$.method","signature":"$.method","since":"","deprecated":false},{"type":"property","name":"$.url","signature":"$.url","since":"","deprecated":false},{"type":"property","name":"$.uri","signature":"$.uri","since":"","deprecated":false},{"type":"property","name":"$.split","signature":"$.split","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.body","signature":"$.body","since":"","deprecated":false},{"type":"property","name":"$.payload","signature":"$.payload","since":"","deprecated":false},{"type":"property","name":"$.files","signature":"$.files","since":"","deprecated":false},{"type":"property","name":"$.headers","signature":"$.headers","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"property","name":"$.ua","signature":"$.ua","since":"","deprecated":false},{"type":"property","name":"$.mobile","signature":"$.mobile","since":"","deprecated":false},{"type":"property","name":"$.robot","signature":"$.robot","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"","deprecated":false},{"type":"property","name":"$.protocol","signature":"$.protocol","since":"","deprecated":false},{"type":"property","name":"$.address","signature":"$.address","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"method","name":"$.json()","signature":"$.json(value, [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"$.jsonstring()","signature":"$.jsonstring(value)","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"$.html()","signature":"$.html(value)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.plain()","signature":"$.plain(value)","since":"","deprecated":false},{"type":"method","name":"$.xml()","signature":"$.xml(value)","since":"","deprecated":false},{"type":"method","name":"$.empty()","signature":"$.empty()","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"$.view()","signature":"$.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"$.layout()","signature":"$.layout(name)","since":"","deprecated":false},{"type":"method","name":"$.file()","signature":"$.file(path, [download])","since":"","deprecated":false},{"type":"method","name":"$.stream()","signature":"$.stream(type, stream, [download])","since":"","deprecated":false},{"type":"method","name":"$.binary()","signature":"$.binary(buffer, type, [download])","since":"","deprecated":false},{"type":"method","name":"$.content()","signature":"$.content(value, [type])","since":"","deprecated":false},{"type":"method","name":"$.image()","signature":"$.image(opt)","since":"","deprecated":false},{"type":"method","name":"$.filefs()","signature":"$.filefs(name, id, [download], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"$.proxy()","signature":"$.proxy(opt)","since":"","deprecated":false},{"type":"method","name":"$.fallback()","signature":"$.fallback(code, [error])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([err], [value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.custom()","signature":"$.custom()","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"$.httpcache()","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"$.notmodified()","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"$.hostname()","signature":"$.hostname([path])","since":"","deprecated":false},{"type":"method","name":"$.href()","signature":"$.href([key], [value])","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, model)","since":"","deprecated":false},{"type":"method","name":"$.authorize()","signature":"$.authorize([callback])","since":"","deprecated":false},{"type":"method","name":"$.csrf()","signature":"$.csrf()","since":"","deprecated":false},{"type":"method","name":"$.autoclear()","signature":"$.autoclear([value])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"class","name":"HttpFile","signature":"HttpFile","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwV6CWx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/controller/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Controller","summary":"Eigenschaften und Methoden des Controllers `$`, den jede Routen-Aktion erhält.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/controller/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Controller\n\n> Eigenschaften und Methoden des Controllers `$`, den jede Routen-Aktion erhält.\n\nDer Controller ist das Argument `$` jeder Routen-Aktion. Er enthält die Anfragedaten (`$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.user`...) und die Methoden, die die Antwort senden (`$.json()`, `$.success()`, `$.invalid()`, `$.view()`, `$.file()`, `$.redirect()`...). Eine Einführung mit Beispielen findest du in der Anleitung [Controller](../../guides/controller/).\n\n## API\n\n### $.req\n\nType: `property`\n\nDas Request-Objekt von Node.js.\n\nReturns: `IncomingMessage`\n\nDie `http.IncomingMessage` der Anfrage. Verwende sie nur für das, was der Controller nicht bietet.\n\n### $.res\n\nType: `property`\n\nDas Response-Objekt von Node.js.\n\nReturns: `ServerResponse`\n\nDie `http.ServerResponse` der Anfrage. Wenn du selbst hineinschreibst, rufe zuerst `$.custom()` auf, damit das Framework die Anfrage nicht ebenfalls beantwortet.\n\n### $.method\n\nType: `property`\n\nDie HTTP-Methode der Anfrage.\n\nReturns: `String`\n\nEin String in Großbuchstaben wie `GET`, `POST`, `PUT`, `PATCH` oder `DELETE`.\n\nExample: Beispiel\n```js\nROUTE('POST /api/items/', function($) {\n\t// $.method === 'POST'\n\t$.success();\n});\n```\n\n### $.url\n\nType: `property`\n\nDer Pfad der URL.\n\nReturns: `String`\n\nDer Pfad ohne den Query String. Ein Pfad ohne Dateiendung endet immer mit `/`, und doppelte Schrägstriche werden zusammengeführt. Die Groß- und Kleinschreibung bleibt erhalten.\n\nExample: Beispiel\n```js\nROUTE('GET /docs/', function($) {\n\t// /docs?page=1 gives '/docs/'\n\t$.plain($.url);\n});\n```\n\n### $.uri\n\nType: `property`\n\nDie geparste URL.\n\nReturns: `Object`\n\nEin Objekt mit `pathname` (dasselbe wie `$.url`), `search` (der Query String ohne `?`), `split` (die Segmente), `ext` (die Dateiendung) und `file` (`true` für die Anfrage einer statischen Datei).\n\n### $.split\n\nType: `property`\n\nDie Segmente des Pfads.\n\nReturns: `String[]`\n\nEin Array der Teile des Pfads: `/blog/2025/hello/` ergibt `['blog', '2025', 'hello']`. Der Root-Pfad `/` ergibt ein leeres Array.\n\nExample: Beispiel\n```js\nROUTE('GET /blog/*', function($) {\n\t$.json($.split);\n});\n```\n\n### $.params\n\nType: `property`\n\nDie dynamischen Teile der URL.\n\nReturns: `Object`\n\nJedes `{name}` der Route wird zu einem Schlüssel mit dem passenden Segment des Pfads als String. Konvertiere Zahlen und Datumswerte selbst.\n\nExample: Beispiel\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id}/', order);\n};\n\nfunction order($) {\n\tvar id = $.params.id;\n\t$.json({ id: id });\n}\n```\n\n### $.query\n\nType: `property`\n\nDer Query-String als Objekt.\n\nReturns: `Object`\n\nDie Werte sind Strings: `?page=2&q=shoes` ergibt `{ page: '2', q: 'shoes' }`. Du kannst ein neues Objekt zuweisen. In einer API-Route enthält es die Query des Feldes `schema`.\n\nExample: Paginierung\n```js\nfunction list($) {\n\tvar page = ($.query.page || '1').parseInt();\n\t$.json({ page: page });\n}\n```\n\n### $.body\n\nType: `property`\n\nDer geparste Body der Anfrage.\n\nReturns: `Object`\n\nFür `POST`-, `PUT`-, `PATCH`- und `DELETE`-Anfragen. Ein JSON-Body wird in ein Objekt geparst, ein URL-kodiertes Formular in ein Objekt aus Strings, und eine `multipart/form-data`-Anfrage liefert die Felder des Formulars. Andere Content-Types behalten `{}`, und die Rohdaten stehen in `$.payload`. In einer API-Route enthält es die `data` der Anfrage.\n\nExample: Den Body lesen\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar email = $.body.email;\n\t$.success();\n}\n```\n\n### $.payload\n\nType: `property`\n\nDer rohe Body als Buffer.\n\nReturns: `Buffer`\n\nDie Bytes des Bodys für jeden Content-Type außer `multipart/form-data`. Verwende ihn für XML, reinen Text oder binäre Uploads. Er wird freigegeben, wenn die Antwort endet.\n\nExample: Beispiel\n```js\nROUTE('POST /api/xml/', function($) {\n\tvar xml = $.payload.toString('utf8');\n\t$.plain('Received ' + xml.length + ' chars');\n});\n```\n\n### $.files\n\nType: `property`\n\nDie hochgeladenen Dateien.\n\nReturns: `HttpFile[]`\n\nEin Array von Dateien (`HttpFile`) aus einer `multipart/form-data`-Anfrage, bei anderen Anfragen leer. Die Dateien sind temporär und werden entfernt, wenn die Antwort endet, es sei denn, du verschiebst sie oder rufst `$.autoclear(false)` auf.\n\nExample: Beispiel\n```js\nfunction upload($) {\n\tvar names = [];\n\tfor (var file of $.files)\n\t\tnames.push(file.filename + ' (' + file.size + ' bytes)');\n\t$.json(names);\n}\n```\n\n### $.headers\n\nType: `property`\n\nDie Header der Anfrage.\n\nReturns: `Object`\n\nDas Header-Objekt von Node.js: Die Namen sind kleingeschrieben.\n\nExample: Beispiel\n```js\nfunction info($) {\n\t$.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] });\n}\n```\n\n### $.ip\n\nType: `property`\n\nDie IP-Adresse des Clients.\n\nReturns: `String`\n\nDie erste Adresse aus `X-Forwarded-For`, wenn der Header existiert (hinter einem Proxy), sonst die Remote-Adresse der Verbindung.\n\nExample: Beispiel\n```js\nfunction track($) {\n\tconsole.log('Request from', $.ip);\n\t$.success();\n}\n```\n\n### $.ua\n\nType: `property`\n\nEin kurzer Name des Clients aus dem Header User-Agent.\n\nReturns: `String`\n\nDas System und der Browser, die in `User-Agent` gefunden werden, zum Beispiel `Mac OS Chrome`, oder ein leerer String ohne den Header.\n\n### $.mobile\n\nType: `property`\n\n`true` für ein Mobilgerät.\n\nReturns: `Boolean`\n\n`true`, wenn `User-Agent` auf ein Smartphone oder Tablet passt (Android, iPhone, iPad, Mobile, Tablet...).\n\n### $.robot\n\nType: `property`\n\n`true` für einen Crawler.\n\nReturns: `Boolean`\n\n`true`, wenn `User-Agent` `search`, `agent`, `bot`, `crawler` oder `spider` enthält.\n\n### $.xhr\n\nType: `property`\n\n`true` für einen XMLHttpRequest.\n\nReturns: `Boolean`\n\n`true`, wenn die Anfrage den Header `X-Requested-With: XMLHttpRequest` hat. `$.fallback()` beantwortet solche Anfragen mit JSON statt mit einer HTML-Seite.\n\n### $.protocol\n\nType: `property`\n\nDas Protokoll der Anfrage.\n\nReturns: `String`\n\n`https` bei einer verschlüsselten Verbindung oder wenn ein Proxy es angibt (`X-Forwarded-Proto: https`, `X-Forwarded-SSL: on` oder `X-Forwarded-Port: 443`), sonst `http`.\n\n### $.address\n\nType: `property`\n\nDie vollständige URL der Anfrage.\n\nReturns: `String`\n\nDas Protokoll, der Host und die ursprüngliche URL mit dem Query String, zum Beispiel `https://example.com/products/?page=2`.\n\n### $.user\n\nType: `property`\n\nDer angemeldete Benutzer.\n\nReturns: `Object`\n\nDas Objekt, das dein Autorisierungs-Delegate für die Anfrage zurückgegeben hat, oder `undefined`, wenn niemand angemeldet ist. Siehe [Autorisierung](../../guides/authorization/).\n\nExample: Beispiel\n```js\nROUTE('+GET /api/account/', function($) {\n\t$.json({ name: $.user.name });\n});\n```\n\n### $.language\n\nType: `property`\n\nDie Sprache der Anfrage.\n\nReturns: `String`\n\nDer Wert, den dein Lokalisierungs-Delegate zurückgegeben hat, oder ein leerer String. Er bestimmt die Übersetzung von Views und Fehlermeldungen. Siehe [Lokalisierung](../../guides/localization/).\n\n### $.response\n\nType: `property`\n\nDie Antwort, die gesendet wird.\n\nReturns: `Object`\n\nEin Objekt mit `status` (Standard `200`), `headers` (ein Objekt mit Antwort-Headern), `cache` (HTTP-Cache für Dateien) und `minify`. Ändere es, bevor du eine Antwortmethode aufrufst.\n\nExample: Status und ein Header\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\n### $.json(value, [beautify], [replacer])\n\nType: `method`\n\nSendet JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der zu serialisierende Wert. |\n| `beautify` | `Boolean` | no | `false` | `true` rückt das JSON mit Tabs ein. |\n| `replacer` | `Function|Array` | no |  | Ein Replacer für `JSON.stringify()`. |\n\nSerialisiert `value` mit `JSON.stringify()`, setzt `content-type: application/json` und Header, die das Caching abschalten (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). `beautify` rückt die Ausgabe mit Tabs ein. `replacer` wird als zweites Argument an `JSON.stringify()` übergeben: eine Funktion `(key, value)` oder ein Array der zu behaltenden Schlüssel.\n\nExample: Beispiel\n```js\nROUTE('GET /api/products/', function($) {\n\t$.json([{ id: 1, name: 'Shoes' }]);\n});\n```\n\nExample: Formatieren und einen Schlüssel ausblenden\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n### $.jsonstring(value)\n\nType: `method`\n\nSendet einen String, der bereits JSON ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Ein JSON-String. |\n\nSendet den String unverändert mit denselben Headern wie `$.json()`. Verwende es für JSON, das du gecacht oder aus einer Datei gelesen hast.\n\nExample: Beispiel\n```js\nfunction cached($) {\n\t$.jsonstring('{\"ok\":true}');\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nSendet `{ success: true, value: value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Ein optionaler Wert für den Schlüssel `value`. |\n\nEine Abkürzung für die übliche Antwort einer API. Ohne `value` lautet die Antwort `{\"success\":true}`.\n\nExample: Beispiel\n```js\nfunction remove($) {\n\tNOSQL('products').remove().id($.params.id);\n\t$.success($.params.id);\n}\n```\n\n### $.invalid(error)\n\nType: `method`\n\nSendet einen Fehler als JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Error|ErrorBuilder|Number` | yes |  | Der Fehler. |\n\nAkzeptiert einen String, einen `Error`, einen `ErrorBuilder` oder einen HTTP-Statuscode. Die Antwort ist ein JSON-Array wie `[{\"error\":\"Name is required\"}]` mit dem Status `400` oder dem angegebenen Statuscode (`$.invalid(404)` ergibt `[{\"error\":\"404: Not Found\"}]` mit Status `404`). Als `@(text)` geschriebener Text wird aus einer Ressource übersetzt. Ohne Argument sendet es `401`. Die Antwort wird asynchron gesendet.\n\nExample: Beispiel\n```js\nfunction save($) {\n\tif (!$.body.email) {\n\t\t$.invalid('@(Email is required)');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nSendet eine Fehlermeldung und loggt den echten Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number|ErrorBuilder` | yes |  | Der Fehler für den Client. |\n| `error` | `Error|String` | no |  | Der Fehler für das Log. |\n\nSendet `message` so wie `$.invalid(message)` und schreibt `error` mit `F.error()` und der URL der Anfrage ins Fehlerlog. Der Client erhält nur die Meldung. `message` kann auch ein `ErrorBuilder` sein.\n\nExample: Beispiel\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n### $.html(value)\n\nType: `method`\n\nSendet HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML. |\n\nSetzt `content-type: text/html` und sendet den String. Er wird minifiziert, wenn der Konfigurationsschlüssel `$minifyhtml` `true` ist (Standard).\n\nExample: Beispiel\n```js\nROUTE('GET /hello/', function($) {\n\t$.html('<h1>Hello</h1>');\n});\n```\n\n### $.throw(error)\n\nType: `method`\n\nSchreibt einen Fehler ins Log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | Der Fehler. |\n\nReturns: `Controller` Derselbe Controller.\n\nÜbergibt `error` mit der URL der Anfrage an den Fehlerhandler des Frameworks (`DEF.onError`): Er wird ausgegeben, in `F.errors` aufbewahrt und als Event `error` gesendet. An den Client wird nichts gesendet. Gibt `$` zurück.\n\nExample: Beispiel\n```js\nfunction save($) {\n\tNOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) {\n\t\terr && $.throw(err);\n\t});\n\t$.success();\n}\n```\n\n### $.plain(value)\n\nType: `method`\n\nSendet reinen Text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der Text. |\n\nSetzt `content-type: text/plain`. `$.text()` ist dieselbe Methode.\n\nExample: Beispiel\n```js\nROUTE('FILE /robots.txt', function($) {\n\t$.plain('User-agent: *');\n});\n```\n\n### $.xml(value)\n\nType: `method`\n\nSendet XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | XML. |\n\nSetzt `content-type: text/xml` und sendet den String.\n\nExample: Beispiel\n```js\nfunction feed($) {\n\t$.xml('<?xml version=\"1.0\"?><rss></rss>');\n}\n```\n\n### $.empty()\n\nType: `method`\n\nSendet Status 204 ohne Body.\n\nVerwende es, wenn eine Anfrage keine Daten in der Antwort braucht.\n\nExample: Beispiel\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.empty();\n});\n```\n\n### $.redirect(url, [permanent])\n\nType: `method`\n\nLeitet den Client weiter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Ziel-URL. |\n| `permanent` | `Boolean` | no | `false` | `true` für eine permanente Weiterleitung (301). |\n\nSetzt den Header `Location` und den Status `302` oder `301`, wenn `permanent` `true` ist.\n\nExample: Beispiel\n```js\nROUTE('GET /old/', function($) {\n\t$.redirect('/new/', true);\n});\n```\n\n### $.view([name], [model])\n\nType: `method`\n\nRendert eine View und sendet sie als HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Der Name der View, ohne die Endung. |\n| `model` | `Object` | no |  | Das Model für die View. |\n\nReturns: `View` Die View-Instanz.\n\nRendert die View `name` aus dem Verzeichnis `/views/` mit `model` und sendet sie mit `$.html()`. Mit dem Layout aus `$.layout()`. Ohne `name` gibt sie nur eine neue `View`-Instanz für den Controller zurück. Siehe [Views](../../guides/views/).\n\nExample: Beispiel\n```js\nfunction detail($) {\n\tNOSQL('products').one().id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.view('detail', response);\n\t\telse\n\t\t\t$.fallback(404);\n\t});\n}\n```\n\n### $.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. |\n\nDie mit `$.view()` gerenderte View wird in das Layout `name` eingefügt.\n\nExample: Beispiel\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('dashboard');\n}\n```\n\n### $.file(path, [download])\n\nType: `method`\n\nSendet eine Datei von der Festplatte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein absoluter Pfad der Datei. |\n| `download` | `Boolean|String` | no |  | Ein Dateiname für den Download oder `true`. |\n\nSetzt den Content-Type anhand der Endung und unterstützt `Range`-Anfragen, gzip und HTTP-Cache-Header. JS-, CSS- und HTML-Dateien werden minifiziert, es sei denn, ihr Name enthält `.min`, `-min` oder `@min`. Mit `download` speichert der Browser die Datei: Übergib `true`, um ihren Namen zu behalten, oder einen String, um sie umzubenennen. Eine fehlende Datei ergibt `404`.\n\nExample: Beispiel\n```js\nROUTE('GET /download/', function($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n});\n```\n\n### $.stream(type, stream, [download])\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` | `ReadableStream` | yes |  | Der Stream. |\n| `download` | `String` | no |  | Ein Dateiname für den Download. |\n\nLeitet `stream` mit dem Content-Type `type` (Standard `application/octet-stream`) in die Antwort. Text-Typen werden mit gzip komprimiert, wenn der Client es unterstützt. Ein String `download` sendet den Stream als Anhang mit diesem Namen.\n\nExample: Beispiel\n```js\nfunction exportcsv($) {\n\tvar stream = F.Fs.createReadStream(PATH.root('export.csv'));\n\t$.stream('text/csv', stream, 'export.csv');\n}\n```\n\n### $.binary(buffer, type, [download])\n\nType: `method`\n\nSendet einen Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Die Daten. |\n| `type` | `String` | yes |  | Der Content-Type. |\n| `download` | `String` | no |  | Ein Dateiname für den Download. |\n\nSendet die Bytes mit dem Content-Type `type`. Ein String `download` sendet sie als Anhang mit diesem Namen.\n\nExample: Beispiel\n```js\nfunction pixel($) {\n\tvar buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');\n\t$.binary(buffer, 'image/gif');\n}\n```\n\n### $.content(value, [type])\n\nType: `method`\n\nSendet einen String oder einen Buffer mit einem Content-Type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Der Inhalt. |\n| `type` | `String` | no | `'application/octet-stream'` | Der Content-Type. |\n\nSendet `value` mit dem Header `content-type: type`; ohne `type` ist es `application/octet-stream`. Ein String wird als UTF-8 gesendet. Anders als `$.binary()` nimmt es auch einen String an und hat keinen Download-Namen.\n\nExample: CSV\n```js\nROUTE('GET /export/', function($) {\n\t$.content('id,name\\n1,Mug\\n', 'text/csv');\n});\n```\n\n### $.image(opt)\n\nType: `method`\n\nVerarbeitet ein Bild und sendet es.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Die Optionen. |\n\nLädt einen Bild-Stream, lässt dich ihn ändern und sendet das Ergebnis. `opt.ext` (erforderlich) ist die Endung der Ausgabe, `opt.load(next, opt)` ruft `next(stream)` mit der Quelle auf, `opt.image(img, opt)` ändert das Bild (siehe [Bilder](../../guides/images/)), `opt.cache` ist ein Schlüssel, um das Ergebnis im temporären Verzeichnis zu behalten, und `opt.date` ein Datum für den HTTP-Cache.\n\nExample: Beispiel\n```js\nfunction thumbnail($) {\n\t$.image({\n\t\text: 'jpg',\n\t\tcache: 'thumb_' + $.params.id,\n\t\tload: function(next) {\n\t\t\tnext(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg')));\n\t\t},\n\t\timage: function(img) {\n\t\t\timg.resize(200, 200);\n\t\t}\n\t});\n}\n```\n\n### $.filefs(name, id, [download], [checkmeta])\n\nType: `method`\n\nSendet eine Datei aus einem Dateispeicher.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Dateispeichers. |\n| `id` | `String` | yes |  | Die Kennung der Datei. |\n| `download` | `Boolean|String` | no |  | Als Anhang senden. |\n| `checkmeta` | `Function` | no |  | Eine Prüfung der Metadaten. |\n\nReturns: `Object` Die Optionen, die an den Speicher übergeben werden.\n\nSendet die Datei `id` aus dem Dateispeicher `name` (siehe [Dateispeicher](../../guides/file-storage/)). `download` sendet sie als Anhang, `true` mit ihrem gespeicherten Namen oder ein String für einen anderen Namen. `checkmeta` ist eine Funktion, die die Metadaten der Datei erhält und entscheidet, ob sie gesendet werden darf.\n\nExample: Beispiel\n```js\nROUTE('GET /files/{id}/', function($) {\n\t$.filefs('files', $.params.id);\n});\n```\n\n### $.proxy(opt)\n\nType: `method`\n\nLeitet die Anfrage an einen anderen Server weiter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `String|Object` | yes |  | Die Ziel-URL oder Optionen. |\n\nSendet die Methode, die Header, den Body und den Query String der Anfrage an `opt` (eine URL oder ein Objekt mit `url`, `method`, `headers`, `timeout` (Standard 10000 ms) und `callback(err, response)`) und antwortet mit der Antwort dieses Servers.\n\nExample: Beispiel\n```js\nROUTE('GET /api/weather/', function($) {\n\t$.proxy('https://weather.example.com/today/');\n});\n```\n\n### $.fallback(code, [error])\n\nType: `method`\n\nSendet eine Fehlerseite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Der HTTP-Statuscode. |\n| `error` | `String|Error` | no |  | Der Fehler für den Debug-Modus. |\n\nWenn eine Route `#code` existiert (zum Beispiel `ROUTE('#404', fn)`), behandelt deren Aktion die Anfrage; der Status bleibt `200`, außer die Aktion setzt `$.response.status`. Andernfalls sendet sie die eingebaute Fehlerseite mit dem Status `code` oder bei XHR-Anfragen `$.invalid(code)`. `error` wird im Debug-Modus auf der Seite angezeigt.\n\nExample: Beispiel\n```js\nexports.install = function() {\n\tROUTE('GET /secret/', function($) {\n\t\t$.fallback(404);\n\t});\n\tROUTE('#404', function($) {\n\t\t$.view('404');\n\t});\n};\n```\n\n### $.callback([err], [value])\n\nType: `method`\n\nAntwortet aus einem Callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | no |  | Ein Fehler. |\n| `value` | `Object` | no |  | Der zu sendende Wert. |\n\nReturns: `Function` Ein Callback, wenn ohne Argumente aufgerufen.\n\nOhne Argumente gibt sie eine Funktion `(err, response)` zurück, die `$.invalid(err)` oder `$.json(response)` aufruft. Mit Argumenten antwortet sie sofort: `$.invalid(err)`, `$.success()`, wenn `value` `undefined` ist, oder `$.json(value)`.\n\nExample: Beispiel\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.callback());\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nGibt einen Callback zurück, der mit Erfolg antwortet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | Der Wert oder `true` für die Antwort des Callbacks. |\n\nReturns: `Function` Ein Callback.\n\nDie zurückgegebene Funktion `(err, response)` ruft bei einem Fehler `$.invalid(err)` auf, sonst sendet sie `{ success: true, value: value }`. Übergib `true`, um die `response` des Callbacks als Wert zu verwenden.\n\nExample: Beispiel\n```js\nROUTE('POST /api/products/', function($) {\n\tNOSQL('products').insert($.body).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` | yes |  | Wird aufgerufen, wenn kein Fehler auftritt. |\n\nReturns: `Function` Ein Callback.\n\nDie zurückgegebene Funktion `(err, a, b, c)` ruft bei einem Fehler `$.invalid(err)` auf, sonst `callback(a, b, c)` mit dem Controller als `this`.\n\nExample: Beispiel\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.successful(function(response) {\n\t\t$.json(response);\n\t}));\n});\n```\n\n### $.custom()\n\nType: `method`\n\nTeilt dem Framework mit, dass du die Antwort selbst sendest.\n\nMarkiert den Controller als beendet, sodass keine Antwortmethode mehr hineinschreibt. Schreibe dann mit der Node.js-API in `$.res`.\n\nExample: Beispiel\n```js\nROUTE('GET /events/', function($) {\n\t$.custom();\n\t$.res.writeHead(200, { 'content-type': 'text/event-stream' });\n\t$.res.write('data: hello\\n\\n');\n});\n```\n\n### $.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLiest oder setzt ein Cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Cookies. |\n| `value` | `String` | no |  | Der zu setzende Wert. |\n| `expires` | `Date|String|Object` | no |  | Das Ablaufdatum oder die Optionen. |\n| `options` | `Object` | no |  | Die Optionen des Cookies. |\n\nReturns: `String|Controller` Der Wert beim Lesen, der Controller beim Setzen.\n\nNur mit `name` gibt sie den dekodierten Wert des Cookies zurück oder einen leeren String. Mit `value` fügt sie einen Header `Set-Cookie` hinzu (ein Cookie mit demselben Namen, das zuvor in der Anfrage gesetzt wurde, wird ersetzt) und gibt den Controller zurück. `expires` ist ein `Date`, ein String wie `'7 days'` oder das Optionsobjekt. Die Optionen sind `expires`, `domain`, `path` (Standard `/`), `secure` (Standard aus `$cookiesecure`), `httponly` und `samesite` (Standard aus `$cookiesamesite`, `'Lax'`).\n\nExample: Beispiel\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' });\n\t$.success();\n}\n\nfunction profile($) {\n\t$.json({ session: $.cookie('session') });\n}\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nSetzt die HTTP-Cache-Header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | Das Datum der letzten Änderung. |\n\nSetzt `Last-Modified` auf `date`, `ETag` sowie `Expires` und `Cache-Control`, wenn sie noch nicht gesetzt sind.\n\nExample: Beispiel\n```js\nfunction article($) {\n\tvar updated = new Date(2025, 0, 1);\n\tif ($.notmodified(updated.toUTCString()))\n\t\treturn;\n\t$.httpcache(updated);\n\t$.view('article');\n}\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nAntwortet mit 304, wenn der Client dieselbe Version hat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Das Datum der letzten Änderung als UTC-String. |\n\nReturns: `Boolean` `true`, wenn die 304-Antwort gesendet wurde.\n\nVergleicht `date` (ein UTC-String) mit dem Header `If-Modified-Since`. Wenn beide gleich sind, sendet sie `304 Not Modified` und gibt `true` zurück.\n\n### $.hostname([path])\n\nType: `method`\n\nGibt das Protokoll und den Host zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ein anzuhängender Pfad. |\n\nReturns: `String` Die URL.\n\nLiefert `protocol://host` der Anfrage mit einem optional angehängten Pfad.\n\nExample: Beispiel\n```js\nfunction share($) {\n\t$.json({ url: $.hostname('/products/' + $.params.id + '/') });\n}\n```\n\n### $.href([key], [value])\n\nType: `method`\n\nGibt den Query String mit einem geänderten Parameter zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | Der Name des Parameters oder ein Objekt mit den zu setzenden Parametern. |\n| `value` | `String|Number|Array|Object` | no |  | Der neue Wert. |\n\nReturns: `String` Der Query String mit `?` oder ein leerer String.\n\nOhne Argumente gibt es den Query String der Anfrage zurück (`?page=2&sort=name`) oder einen leeren String. `$.href(key, value)` gibt ihn mit `key` auf `value` gesetzt zurück; die anderen Parameter bleiben. Ohne `value` bleibt der aktuelle Wert von `key` erhalten. Weitere Argumente nach `value` sind Namen von Parametern, die entfernt werden. Ein Array als Wert schreibt den Parameter einmal für jedes Element, und ein Objekt als Wert wird als JSON geschrieben. `$.href({ key: value, ... })` gibt die URL der Anfrage zurück, deren Query String durch die Schlüssel des Objekts geändert ist. Es funktioniert wie `@{href()}` in Views.\n\nExample: Blättern\n```js\n// GET /products/?page=2&sort=name\nfunction products($) {\n\t$.json({\n\t\tnext: $.href('page', 3),           // ?page=3&sort=name\n\t\tcurrent: $.href()                  // ?page=2&sort=name\n\t});\n}\n```\n\nExample: Einen Parameter entfernen oder mehrere ändern\n```js\n// GET /products/?page=2&sort=name&q=pen\n$.href('page', 1, 'sort');           // ?page=1&q=pen\n$.href({ page: 1, sort: 'price' });  // /products/?page=1&sort=price&q=pen\n```\n\n### $.touch([url])\n\nType: `method`\n\nLöscht den gecachten Zustand einer statischen Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | Die URL der Datei. |\n\nReturns: `Controller` Derselbe Controller.\n\nRuft `TOUCH(url)` auf; ohne `url` verwendet es die URL der Anfrage. Verwende es, nachdem die Route eine Datei in `public/` geändert hat. Gibt `$` zurück.\n\nExample: Beispiel\n```js\nROUTE('POST /api/theme/', function($) {\n\tF.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) {\n\t\tif (err) {\n\t\t\t$.invalidsafe('The theme can\\'t be saved', err);\n\t\t\treturn;\n\t\t}\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t});\n});\n```\n\n### $.action(name, model)\n\nType: `method`\n\nFührt eine Aktion mit diesem Controller aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Aktion, zum Beispiel `Products/list`. |\n| `model` | `Object` | yes |  | Die Daten für die Aktion. |\n\nReturns: `Object` Die Aktions-Instanz.\n\nRuft die Aktion `name` (siehe [Aktionen](../../guides/actions/)) mit `model` und dem Controller auf. Rufe `.autorespond()` auf dem Ergebnis auf, um die Anfrage mit der Ausgabe der Aktion zu beantworten.\n\nExample: Beispiel\n```js\nROUTE('POST /api/orders/', function($) {\n\t$.action('Orders/create', $.body).autorespond();\n});\n```\n\n### $.authorize([callback])\n\nType: `method`\n\nFührt den Autorisierungs-Delegate manuell aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Erhält `(err, user)`. |\n\nReturns: `Promise` Wenn ohne Callback aufgerufen.\n\nRuft deinen Autorisierungs-Delegate für diese Anfrage auf. Wenn er einen Benutzer zurückgibt, wird `$.user` gesetzt. Der Callback ist `(err, user)`; ohne Callback gibt die Methode ein `Promise` mit dem Benutzer (oder `undefined`) zurück.\n\nExample: Beispiel\n```js\nROUTE('GET /api/me/', async function($) {\n\tvar user = await $.authorize();\n\t$.json({ signed: !!user });\n});\n```\n\n### $.csrf()\n\nType: `method`\n\nErstellt ein CSRF-Token.\n\nReturns: `String` Das Token.\n\nGibt ein Token zurück, das an die IP-Adresse und den Browser des Clients gebunden ist und für die Zeit in `$csrfexpiration` (Standard `30 minutes`) gültig ist. Es benötigt den Konfigurationsschlüssel `secret_csrf`; ohne ihn ist das Token ein leerer String.\n\nExample: Beispiel\n```js\nROUTE('GET /form/', function($) {\n\t$.view('form', { token: $.csrf() });\n});\n```\n\n### $.autoclear([value])\n\nType: `method`\n\nBehält oder entfernt hochgeladene Dateien nach der Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no |  | `false` behält die Dateien. |\n\nHochgeladene Dateien werden entfernt, wenn die Antwort endet. `$.autoclear(false)` behält sie, zum Beispiel wenn du sie später verarbeitest.\n\n### $.cancel()\n\nType: `method`\n\nStoppt die Verarbeitung der Anfrage in einem Ereignis.\n\nRufe sie in `ON('request', fn)` oder `ON('controller', fn)` auf, wenn der Handler die Anfrage selbst beantwortet.\n\nExample: Beispiel\n```js\nON('request', function($) {\n\tif ($.url === '/health/') {\n\t\t$.cancel();\n\t\t$.plain('OK');\n\t}\n});\n```\n\n### HttpFile\n\nType: `class`\n\nEine hochgeladene Datei in `$.files`.\n\nEigenschaften: `name` (das Feld des Formulars), `filename`, `type` (der Content-Type), `size` (Bytes), `extension`, `width` und `height` (Bilder), `path` (die temporäre Datei) sowie `isImage`, `isVideo`, `isAudio`.\n\nMethoden:\n\n- `move(filename, [callback])` (auch `rename()`) verschiebt die Datei; ohne Callback gibt sie ein `Promise` zurück. Eine verschobene Datei wird nach der Antwort nicht entfernt.\n- `copy(filename, callback)` kopiert die Datei.\n- `read([callback])` liest die Datei in einen `Buffer`; ohne Callback gibt sie ein `Promise` zurück.\n- `md5([callback])` berechnet den MD5-Hash in Hex; ohne Callback gibt sie ein `Promise` zurück.\n- `stream([opt])` gibt einen Lese-Stream zurück; `pipe(stream, [opt])` leitet die Datei in einen Stream.\n- `image([shell])` gibt ein Bildobjekt für [Bilder](../../guides/images/) zurück.\n- `fs(storage, id, [callback])` speichert die Datei in einem [Dateispeicher](../../guides/file-storage/).\n\nExample: In einem Dateispeicher speichern\n```js\nROUTE('POST /upload/ <10MB', function($) {\n\tvar file = $.files[0];\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n});\n```\n","entries":[{"type":"property","name":"$.req","signature":"$.req","since":"","deprecated":false},{"type":"property","name":"$.res","signature":"$.res","since":"","deprecated":false},{"type":"property","name":"$.method","signature":"$.method","since":"","deprecated":false},{"type":"property","name":"$.url","signature":"$.url","since":"","deprecated":false},{"type":"property","name":"$.uri","signature":"$.uri","since":"","deprecated":false},{"type":"property","name":"$.split","signature":"$.split","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.body","signature":"$.body","since":"","deprecated":false},{"type":"property","name":"$.payload","signature":"$.payload","since":"","deprecated":false},{"type":"property","name":"$.files","signature":"$.files","since":"","deprecated":false},{"type":"property","name":"$.headers","signature":"$.headers","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"property","name":"$.ua","signature":"$.ua","since":"","deprecated":false},{"type":"property","name":"$.mobile","signature":"$.mobile","since":"","deprecated":false},{"type":"property","name":"$.robot","signature":"$.robot","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"","deprecated":false},{"type":"property","name":"$.protocol","signature":"$.protocol","since":"","deprecated":false},{"type":"property","name":"$.address","signature":"$.address","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"method","name":"$.json()","signature":"$.json(value, [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"$.jsonstring()","signature":"$.jsonstring(value)","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"$.html()","signature":"$.html(value)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.plain()","signature":"$.plain(value)","since":"","deprecated":false},{"type":"method","name":"$.xml()","signature":"$.xml(value)","since":"","deprecated":false},{"type":"method","name":"$.empty()","signature":"$.empty()","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"$.view()","signature":"$.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"$.layout()","signature":"$.layout(name)","since":"","deprecated":false},{"type":"method","name":"$.file()","signature":"$.file(path, [download])","since":"","deprecated":false},{"type":"method","name":"$.stream()","signature":"$.stream(type, stream, [download])","since":"","deprecated":false},{"type":"method","name":"$.binary()","signature":"$.binary(buffer, type, [download])","since":"","deprecated":false},{"type":"method","name":"$.content()","signature":"$.content(value, [type])","since":"","deprecated":false},{"type":"method","name":"$.image()","signature":"$.image(opt)","since":"","deprecated":false},{"type":"method","name":"$.filefs()","signature":"$.filefs(name, id, [download], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"$.proxy()","signature":"$.proxy(opt)","since":"","deprecated":false},{"type":"method","name":"$.fallback()","signature":"$.fallback(code, [error])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([err], [value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.custom()","signature":"$.custom()","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"$.httpcache()","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"$.notmodified()","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"$.hostname()","signature":"$.hostname([path])","since":"","deprecated":false},{"type":"method","name":"$.href()","signature":"$.href([key], [value])","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, model)","since":"","deprecated":false},{"type":"method","name":"$.authorize()","signature":"$.authorize([callback])","since":"","deprecated":false},{"type":"method","name":"$.csrf()","signature":"$.csrf()","since":"","deprecated":false},{"type":"method","name":"$.autoclear()","signature":"$.autoclear([value])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"class","name":"HttpFile","signature":"HttpFile","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwV6CWx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/controller/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Controller","summary":"Propiedades y métodos del controlador `$` que recibe cada acción de ruta.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/controller/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Controller\n\n> Propiedades y métodos del controlador `$` que recibe cada acción de ruta.\n\nEl controlador es el argumento `$` de cada acción de ruta. Contiene los datos de la petición (`$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.user`...) y los métodos que envían la respuesta (`$.json()`, `$.success()`, `$.invalid()`, `$.view()`, `$.file()`, `$.redirect()`...). Para un recorrido con ejemplos, lee la guía [Controlador](../../guides/controller/).\n\n## API\n\n### $.req\n\nType: `property`\n\nEl objeto de petición de Node.js.\n\nReturns: `IncomingMessage`\n\nEl `http.IncomingMessage` de la petición. Úsalo solo para lo que el controlador no ofrece.\n\n### $.res\n\nType: `property`\n\nEl objeto de respuesta de Node.js.\n\nReturns: `ServerResponse`\n\nEl `http.ServerResponse` de la petición. Si escribes en él tú mismo, llama antes a `$.custom()` para que el framework no responda también a la petición.\n\n### $.method\n\nType: `property`\n\nEl método HTTP de la petición.\n\nReturns: `String`\n\nUna cadena en mayúsculas como `GET`, `POST`, `PUT`, `PATCH` o `DELETE`.\n\nExample: Ejemplo\n```js\nROUTE('POST /api/items/', function($) {\n\t// $.method === 'POST'\n\t$.success();\n});\n```\n\n### $.url\n\nType: `property`\n\nLa ruta de la URL.\n\nReturns: `String`\n\nLa ruta sin el query string. Una ruta sin extensión de archivo siempre termina en `/`, y las barras dobles se unifican. Las letras conservan sus mayúsculas y minúsculas.\n\nExample: Ejemplo\n```js\nROUTE('GET /docs/', function($) {\n\t// /docs?page=1 gives '/docs/'\n\t$.plain($.url);\n});\n```\n\n### $.uri\n\nType: `property`\n\nLa URL parseada.\n\nReturns: `Object`\n\nUn objeto con `pathname` (igual que `$.url`), `search` (el query string sin `?`), `split` (los segmentos), `ext` (la extensión del archivo) y `file` (`true` para una petición de un archivo estático).\n\n### $.split\n\nType: `property`\n\nLos segmentos de la ruta.\n\nReturns: `String[]`\n\nUn array con las partes de la ruta: `/blog/2025/hello/` da `['blog', '2025', 'hello']`. La ruta raíz `/` da un array vacío.\n\nExample: Ejemplo\n```js\nROUTE('GET /blog/*', function($) {\n\t$.json($.split);\n});\n```\n\n### $.params\n\nType: `property`\n\nLas partes dinámicas de la URL.\n\nReturns: `Object`\n\nCada `{name}` de la ruta se convierte en una clave con el segmento correspondiente de la ruta como cadena. Convierte tú mismo los números y las fechas.\n\nExample: Ejemplo\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id}/', order);\n};\n\nfunction order($) {\n\tvar id = $.params.id;\n\t$.json({ id: id });\n}\n```\n\n### $.query\n\nType: `property`\n\nLa query string como objeto.\n\nReturns: `Object`\n\nLos valores son cadenas: `?page=2&q=shoes` da `{ page: '2', q: 'shoes' }`. Puedes asignar un objeto nuevo. En una ruta de API contiene la query del campo `schema`.\n\nExample: Paginación\n```js\nfunction list($) {\n\tvar page = ($.query.page || '1').parseInt();\n\t$.json({ page: page });\n}\n```\n\n### $.body\n\nType: `property`\n\nEl cuerpo de la petición ya procesado.\n\nReturns: `Object`\n\nPara peticiones `POST`, `PUT`, `PATCH` y `DELETE`. Un cuerpo JSON se parsea a un objeto, un formulario URL-encoded a un objeto de cadenas, y una petición `multipart/form-data` da los campos del formulario. Los demás content types mantienen `{}` y los datos sin procesar están en `$.payload`. En una ruta de API contiene el `data` de la petición.\n\nExample: Leer el cuerpo\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar email = $.body.email;\n\t$.success();\n}\n```\n\n### $.payload\n\nType: `property`\n\nEl cuerpo sin procesar como Buffer.\n\nReturns: `Buffer`\n\nLos bytes del cuerpo para cualquier content type excepto `multipart/form-data`. Úsalo para XML, texto plano o subidas binarias. Se libera cuando termina la respuesta.\n\nExample: Ejemplo\n```js\nROUTE('POST /api/xml/', function($) {\n\tvar xml = $.payload.toString('utf8');\n\t$.plain('Received ' + xml.length + ' chars');\n});\n```\n\n### $.files\n\nType: `property`\n\nLos archivos subidos.\n\nReturns: `HttpFile[]`\n\nUn array de archivos (`HttpFile`) de una petición `multipart/form-data`, vacío en las demás peticiones. Los archivos son temporales y se eliminan cuando termina la respuesta, salvo que los muevas o llames a `$.autoclear(false)`.\n\nExample: Ejemplo\n```js\nfunction upload($) {\n\tvar names = [];\n\tfor (var file of $.files)\n\t\tnames.push(file.filename + ' (' + file.size + ' bytes)');\n\t$.json(names);\n}\n```\n\n### $.headers\n\nType: `property`\n\nLas cabeceras de la petición.\n\nReturns: `Object`\n\nEl objeto de cabeceras de Node.js: los nombres están en minúsculas.\n\nExample: Ejemplo\n```js\nfunction info($) {\n\t$.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] });\n}\n```\n\n### $.ip\n\nType: `property`\n\nLa dirección IP del cliente.\n\nReturns: `String`\n\nLa primera dirección de `X-Forwarded-For` cuando existe la cabecera (detrás de un proxy); si no, la dirección remota de la conexión.\n\nExample: Ejemplo\n```js\nfunction track($) {\n\tconsole.log('Request from', $.ip);\n\t$.success();\n}\n```\n\n### $.ua\n\nType: `property`\n\nUn nombre corto del cliente a partir de la cabecera User-Agent.\n\nReturns: `String`\n\nEl sistema y el navegador encontrados en `User-Agent`, por ejemplo `Mac OS Chrome`, o una cadena vacía si no hay cabecera.\n\n### $.mobile\n\nType: `property`\n\n`true` para un dispositivo móvil.\n\nReturns: `Boolean`\n\n`true` cuando `User-Agent` corresponde a un teléfono o una tableta (Android, iPhone, iPad, Mobile, Tablet...).\n\n### $.robot\n\nType: `property`\n\n`true` para un crawler.\n\nReturns: `Boolean`\n\n`true` cuando `User-Agent` contiene `search`, `agent`, `bot`, `crawler` o `spider`.\n\n### $.xhr\n\nType: `property`\n\n`true` para un XMLHttpRequest.\n\nReturns: `Boolean`\n\n`true` cuando la petición tiene la cabecera `X-Requested-With: XMLHttpRequest`. `$.fallback()` responde a estas peticiones con JSON en lugar de una página HTML.\n\n### $.protocol\n\nType: `property`\n\nEl protocolo de la petición.\n\nReturns: `String`\n\n`https` para una conexión cifrada o cuando un proxy lo indica (`X-Forwarded-Proto: https`, `X-Forwarded-SSL: on` o `X-Forwarded-Port: 443`); si no, `http`.\n\n### $.address\n\nType: `property`\n\nLa URL completa de la petición.\n\nReturns: `String`\n\nEl protocolo, el host y la URL original con el query string, por ejemplo `https://example.com/products/?page=2`.\n\n### $.user\n\nType: `property`\n\nEl usuario autenticado.\n\nReturns: `Object`\n\nEl objeto que devolvió tu delegado de autorización para la petición, o `undefined` cuando no hay nadie con sesión iniciada. Consulta [Autorización](../../guides/authorization/).\n\nExample: Ejemplo\n```js\nROUTE('+GET /api/account/', function($) {\n\t$.json({ name: $.user.name });\n});\n```\n\n### $.language\n\nType: `property`\n\nEl idioma de la petición.\n\nReturns: `String`\n\nEl valor que devolvió tu delegado de localización, o una cadena vacía. Selecciona la traducción de las vistas y de los mensajes de error. Consulta [Localización](../../guides/localization/).\n\n### $.response\n\nType: `property`\n\nLa respuesta que se enviará.\n\nReturns: `Object`\n\nUn objeto con `status` (por defecto `200`), `headers` (un objeto con las cabeceras de la respuesta), `cache` (caché HTTP para archivos) y `minify`. Cámbialo antes de llamar a un método de respuesta.\n\nExample: Estado y una cabecera\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\n### $.json(value, [beautify], [replacer])\n\nType: `method`\n\nEnvía JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor que serializar. |\n| `beautify` | `Boolean` | no | `false` | `true` indenta el JSON con tabuladores. |\n| `replacer` | `Function|Array` | no |  | Un replacer para `JSON.stringify()`. |\n\nSerializa `value` con `JSON.stringify()`, establece `content-type: application/json` y cabeceras que desactivan la caché (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). `beautify` indenta la salida con tabuladores. `replacer` se pasa a `JSON.stringify()` como su segundo argumento: una función `(key, value)` o un array de claves que conservar.\n\nExample: Ejemplo\n```js\nROUTE('GET /api/products/', function($) {\n\t$.json([{ id: 1, name: 'Shoes' }]);\n});\n```\n\nExample: Formatear y ocultar una clave\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n### $.jsonstring(value)\n\nType: `method`\n\nEnvía una cadena que ya es JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Una cadena JSON. |\n\nEnvía la cadena tal cual con las mismas cabeceras que `$.json()`. Úsalo para JSON que tienes en caché o que has leído de un archivo.\n\nExample: Ejemplo\n```js\nfunction cached($) {\n\t$.jsonstring('{\"ok\":true}');\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nEnvía `{ success: true, value: value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Un valor opcional para la clave `value`. |\n\nUn atajo para la respuesta habitual de una API. Sin `value` la respuesta es `{\"success\":true}`.\n\nExample: Ejemplo\n```js\nfunction remove($) {\n\tNOSQL('products').remove().id($.params.id);\n\t$.success($.params.id);\n}\n```\n\n### $.invalid(error)\n\nType: `method`\n\nEnvía un error como JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Error|ErrorBuilder|Number` | yes |  | El error. |\n\nAcepta una cadena, un `Error`, un `ErrorBuilder` o un código de estado HTTP. La respuesta es un array JSON como `[{\"error\":\"Name is required\"}]` con el estado `400`, o el código de estado indicado (`$.invalid(404)` da `[{\"error\":\"404: Not Found\"}]` con el estado `404`). El texto escrito como `@(text)` se traduce desde un recurso. Sin argumento envía `401`. La respuesta se envía de forma asíncrona.\n\nExample: Ejemplo\n```js\nfunction save($) {\n\tif (!$.body.email) {\n\t\t$.invalid('@(Email is required)');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nEnvía un mensaje de error y registra el error real.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number|ErrorBuilder` | yes |  | El error para el cliente. |\n| `error` | `Error|String` | no |  | El error para el log. |\n\nEnvía `message` como lo hace `$.invalid(message)` y escribe `error` en el log de errores con `F.error()` y la URL de la petición. El cliente solo recibe el mensaje. `message` también puede ser un `ErrorBuilder`.\n\nExample: Ejemplo\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n### $.html(value)\n\nType: `method`\n\nEnvía HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML. |\n\nEstablece `content-type: text/html` y envía la cadena. Se minifica cuando la clave de configuración `$minifyhtml` es `true` (el valor por defecto).\n\nExample: Ejemplo\n```js\nROUTE('GET /hello/', function($) {\n\t$.html('<h1>Hello</h1>');\n});\n```\n\n### $.throw(error)\n\nType: `method`\n\nEscribe un error en el log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | El error. |\n\nReturns: `Controller` El mismo controlador.\n\nPasa `error` con la URL de la petición al manejador de errores del framework (`DEF.onError`): se imprime, se guarda en `F.errors` y se emite como el evento `error`. No se envía nada al cliente. Devuelve `$`.\n\nExample: Ejemplo\n```js\nfunction save($) {\n\tNOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) {\n\t\terr && $.throw(err);\n\t});\n\t$.success();\n}\n```\n\n### $.plain(value)\n\nType: `method`\n\nEnvía texto plano.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El texto. |\n\nEstablece `content-type: text/plain`. `$.text()` es el mismo método.\n\nExample: Ejemplo\n```js\nROUTE('FILE /robots.txt', function($) {\n\t$.plain('User-agent: *');\n});\n```\n\n### $.xml(value)\n\nType: `method`\n\nEnvía XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | XML. |\n\nEstablece `content-type: text/xml` y envía la cadena.\n\nExample: Ejemplo\n```js\nfunction feed($) {\n\t$.xml('<?xml version=\"1.0\"?><rss></rss>');\n}\n```\n\n### $.empty()\n\nType: `method`\n\nEnvía el estado 204 sin cuerpo.\n\nÚsalo cuando una petición no necesita datos en la respuesta.\n\nExample: Ejemplo\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.empty();\n});\n```\n\n### $.redirect(url, [permanent])\n\nType: `method`\n\nRedirige al cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL de destino. |\n| `permanent` | `Boolean` | no | `false` | `true` para una redirección permanente (301). |\n\nEstablece la cabecera `Location` y el estado `302`, o `301` cuando `permanent` es `true`.\n\nExample: Ejemplo\n```js\nROUTE('GET /old/', function($) {\n\t$.redirect('/new/', true);\n});\n```\n\n### $.view([name], [model])\n\nType: `method`\n\nRenderiza una vista y la envía como HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | El nombre de la vista, sin la extensión. |\n| `model` | `Object` | no |  | El modelo para la vista. |\n\nReturns: `View` La instancia de la vista.\n\nRenderiza la vista `name` del directorio `/views/` con `model` y la envía con `$.html()`. Usa la plantilla (layout) de `$.layout()`. Sin `name` solo devuelve una nueva instancia de `View` para el controlador. Consulta [Vistas](../../guides/views/).\n\nExample: Ejemplo\n```js\nfunction detail($) {\n\tNOSQL('products').one().id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.view('detail', response);\n\t\telse\n\t\t\t$.fallback(404);\n\t});\n}\n```\n\n### $.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 plantilla (layout). |\n\nLa vista renderizada con `$.view()` se coloca dentro de la plantilla (layout) `name`.\n\nExample: Ejemplo\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('dashboard');\n}\n```\n\n### $.file(path, [download])\n\nType: `method`\n\nEnvía un archivo del disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una ruta absoluta del archivo. |\n| `download` | `Boolean|String` | no |  | Un nombre de archivo para la descarga, o `true`. |\n\nEstablece el content type según la extensión y admite peticiones `Range`, gzip y cabeceras de caché HTTP. Los archivos JS, CSS y HTML se minifican salvo que su nombre contenga `.min`, `-min` o `@min`. Con `download` el navegador guarda el archivo: pasa `true` para mantener su nombre o una cadena para renombrarlo. Un archivo inexistente da `404`.\n\nExample: Ejemplo\n```js\nROUTE('GET /download/', function($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n});\n```\n\n### $.stream(type, stream, [download])\n\nType: `method`\n\nEnvía un stream legible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El content type. |\n| `stream` | `ReadableStream` | yes |  | El stream. |\n| `download` | `String` | no |  | Un nombre de archivo para la descarga. |\n\nCanaliza `stream` hacia la respuesta con el content type `type` (por defecto `application/octet-stream`). Los tipos de texto se comprimen con gzip cuando el cliente lo admite. Una cadena `download` envía el stream como adjunto con ese nombre.\n\nExample: Ejemplo\n```js\nfunction exportcsv($) {\n\tvar stream = F.Fs.createReadStream(PATH.root('export.csv'));\n\t$.stream('text/csv', stream, 'export.csv');\n}\n```\n\n### $.binary(buffer, type, [download])\n\nType: `method`\n\nEnvía un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Los datos. |\n| `type` | `String` | yes |  | El content type. |\n| `download` | `String` | no |  | Un nombre de archivo para la descarga. |\n\nEnvía los bytes con el content type `type`. Una cadena `download` los envía como adjunto con ese nombre.\n\nExample: Ejemplo\n```js\nfunction pixel($) {\n\tvar buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');\n\t$.binary(buffer, 'image/gif');\n}\n```\n\n### $.content(value, [type])\n\nType: `method`\n\nEnvía un string o un Buffer con un content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | El contenido. |\n| `type` | `String` | no | `'application/octet-stream'` | El content type. |\n\nEnvía `value` con la cabecera `content-type: type`; sin `type` es `application/octet-stream`. Un string se envía como UTF-8. A diferencia de `$.binary()`, también acepta un string y no tiene nombre de descarga.\n\nExample: CSV\n```js\nROUTE('GET /export/', function($) {\n\t$.content('id,name\\n1,Mug\\n', 'text/csv');\n});\n```\n\n### $.image(opt)\n\nType: `method`\n\nProcesa una imagen y la envía.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Las opciones. |\n\nCarga un stream de imagen, te permite modificarla y envía el resultado. `opt.ext` (obligatorio) es la extensión de la salida, `opt.load(next, opt)` llama a `next(stream)` con el origen, `opt.image(img, opt)` modifica la imagen (consulta [Imágenes](../../guides/images/)), `opt.cache` es una clave para guardar el resultado en el directorio temporal, y `opt.date` una fecha para la caché HTTP.\n\nExample: Ejemplo\n```js\nfunction thumbnail($) {\n\t$.image({\n\t\text: 'jpg',\n\t\tcache: 'thumb_' + $.params.id,\n\t\tload: function(next) {\n\t\t\tnext(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg')));\n\t\t},\n\t\timage: function(img) {\n\t\t\timg.resize(200, 200);\n\t\t}\n\t});\n}\n```\n\n### $.filefs(name, id, [download], [checkmeta])\n\nType: `method`\n\nEnvía un archivo de un almacenamiento de archivos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del almacenamiento de archivos. |\n| `id` | `String` | yes |  | El identificador del archivo. |\n| `download` | `Boolean|String` | no |  | Enviar como adjunto. |\n| `checkmeta` | `Function` | no |  | Una comprobación de los metadatos. |\n\nReturns: `Object` Las opciones que se pasan al almacenamiento.\n\nEnvía el archivo `id` del almacenamiento de archivos `name` (consulta [Almacenamiento de archivos](../../guides/file-storage/)). `download` lo envía como adjunto: `true` con su nombre almacenado o una cadena para otro nombre. `checkmeta` es una función que recibe los metadatos del archivo y decide si se puede enviar.\n\nExample: Ejemplo\n```js\nROUTE('GET /files/{id}/', function($) {\n\t$.filefs('files', $.params.id);\n});\n```\n\n### $.proxy(opt)\n\nType: `method`\n\nReenvía la petición a otro servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `String|Object` | yes |  | La URL de destino o las opciones. |\n\nEnvía el método, las cabeceras, el cuerpo y el query string de la petición a `opt` (una URL, o un objeto con `url`, `method`, `headers`, `timeout` (por defecto 10000 ms) y `callback(err, response)`) y responde con la respuesta de ese servidor.\n\nExample: Ejemplo\n```js\nROUTE('GET /api/weather/', function($) {\n\t$.proxy('https://weather.example.com/today/');\n});\n```\n\n### $.fallback(code, [error])\n\nType: `method`\n\nEnvía una página de error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | El código de estado HTTP. |\n| `error` | `String|Error` | no |  | El error para el modo debug. |\n\nCuando existe una ruta `#code` (por ejemplo `ROUTE('#404', fn)`), su acción gestiona la petición; el estado sigue siendo `200` salvo que la acción establezca `$.response.status`. Si no, envía la página de error integrada con el estado `code`, o `$.invalid(code)` en las peticiones XHR. `error` se muestra en la página en modo debug.\n\nExample: Ejemplo\n```js\nexports.install = function() {\n\tROUTE('GET /secret/', function($) {\n\t\t$.fallback(404);\n\t});\n\tROUTE('#404', function($) {\n\t\t$.view('404');\n\t});\n};\n```\n\n### $.callback([err], [value])\n\nType: `method`\n\nResponde desde un callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | no |  | Un error. |\n| `value` | `Object` | no |  | El valor que se envía. |\n\nReturns: `Function` Un callback cuando se llama sin argumentos.\n\nSin argumentos devuelve una función `(err, response)` que llama a `$.invalid(err)` o `$.json(response)`. Con argumentos responde de inmediato: `$.invalid(err)`, `$.success()` cuando `value` es `undefined`, o `$.json(value)`.\n\nExample: Ejemplo\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.callback());\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nDevuelve un callback que responde con éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | El valor, o `true` para la respuesta del callback. |\n\nReturns: `Function` Un callback.\n\nLa función devuelta `(err, response)` llama a `$.invalid(err)` si hay un error; si no, envía `{ success: true, value: value }`. Pasa `true` para usar la `response` del callback como valor.\n\nExample: Ejemplo\n```js\nROUTE('POST /api/products/', function($) {\n\tNOSQL('products').insert($.body).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` | yes |  | Se llama cuando no hay error. |\n\nReturns: `Function` Un callback.\n\nLa función devuelta `(err, a, b, c)` llama a `$.invalid(err)` si hay un error; si no, a `callback(a, b, c)` con el controlador como `this`.\n\nExample: Ejemplo\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.successful(function(response) {\n\t\t$.json(response);\n\t}));\n});\n```\n\n### $.custom()\n\nType: `method`\n\nIndica al framework que tú mismo envías la respuesta.\n\nMarca el controlador como finalizado para que ningún método de respuesta escriba en él. Después escribe en `$.res` con la API de Node.js.\n\nExample: Ejemplo\n```js\nROUTE('GET /events/', function($) {\n\t$.custom();\n\t$.res.writeHead(200, { 'content-type': 'text/event-stream' });\n\t$.res.write('data: hello\\n\\n');\n});\n```\n\n### $.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLee o establece una cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la cookie. |\n| `value` | `String` | no |  | El valor que se establece. |\n| `expires` | `Date|String|Object` | no |  | La expiración, o las opciones. |\n| `options` | `Object` | no |  | Las opciones de la cookie. |\n\nReturns: `String|Controller` El valor al leer, el controlador al establecer.\n\nSolo con `name` devuelve el valor decodificado de la cookie, o una cadena vacía. Con `value` añade una cabecera `Set-Cookie` (una cookie con el mismo nombre establecida antes en la petición se reemplaza) y devuelve el controlador. `expires` es un `Date`, una cadena como `'7 days'`, o el objeto de opciones. Las opciones son `expires`, `domain`, `path` (por defecto `/`), `secure` (por defecto según `$cookiesecure`), `httponly` y `samesite` (por defecto según `$cookiesamesite`, `'Lax'`).\n\nExample: Ejemplo\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' });\n\t$.success();\n}\n\nfunction profile($) {\n\t$.json({ session: $.cookie('session') });\n}\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nEstablece las cabeceras de caché HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | La fecha del último cambio. |\n\nEstablece `Last-Modified` a `date`, `ETag`, y `Expires` y `Cache-Control` cuando aún no están establecidas.\n\nExample: Ejemplo\n```js\nfunction article($) {\n\tvar updated = new Date(2025, 0, 1);\n\tif ($.notmodified(updated.toUTCString()))\n\t\treturn;\n\t$.httpcache(updated);\n\t$.view('article');\n}\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nResponde 304 cuando el cliente tiene la misma versión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | La fecha del último cambio como cadena UTC. |\n\nReturns: `Boolean` `true` cuando se envió la respuesta 304.\n\nCompara `date` (una cadena UTC) con la cabecera `If-Modified-Since`. Cuando son iguales envía `304 Not Modified` y devuelve `true`.\n\n### $.hostname([path])\n\nType: `method`\n\nDevuelve el protocolo y el host.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Una ruta que se añade. |\n\nReturns: `String` La URL.\n\nDa `protocol://host` de la petición con una ruta opcional añadida.\n\nExample: Ejemplo\n```js\nfunction share($) {\n\t$.json({ url: $.hostname('/products/' + $.params.id + '/') });\n}\n```\n\n### $.href([key], [value])\n\nType: `method`\n\nDevuelve el query string con un parámetro cambiado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | El nombre del parámetro, o un objeto con los parámetros que se establecen. |\n| `value` | `String|Number|Array|Object` | no |  | El nuevo valor. |\n\nReturns: `String` El query string con `?`, o un string vacío.\n\nSin argumentos devuelve el query string de la petición (`?page=2&sort=name`), o un string vacío. `$.href(key, value)` lo devuelve con `key` establecido a `value`; los demás parámetros se mantienen. Sin `value` se conserva el valor actual de `key`. Los argumentos que siguen a `value` son nombres de parámetros que se eliminan. Un valor array escribe el parámetro una vez por cada elemento y un valor objeto se escribe como JSON. `$.href({ key: value, ... })` devuelve la URL de la petición con el query string cambiado según las claves del objeto. Funciona como `@{href()}` en las vistas.\n\nExample: Paginación\n```js\n// GET /products/?page=2&sort=name\nfunction products($) {\n\t$.json({\n\t\tnext: $.href('page', 3),           // ?page=3&sort=name\n\t\tcurrent: $.href()                  // ?page=2&sort=name\n\t});\n}\n```\n\nExample: Eliminar un parámetro, o cambiar varios\n```js\n// GET /products/?page=2&sort=name&q=pen\n$.href('page', 1, 'sort');           // ?page=1&q=pen\n$.href({ page: 1, sort: 'price' });  // /products/?page=1&sort=price&q=pen\n```\n\n### $.touch([url])\n\nType: `method`\n\nBorra el estado en caché de un archivo estático.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | La URL del archivo. |\n\nReturns: `Controller` El mismo controlador.\n\nLlama a `TOUCH(url)`; sin `url` usa la URL de la petición. Úsalo después de que la ruta cambie un archivo en `public/`. Devuelve `$`.\n\nExample: Ejemplo\n```js\nROUTE('POST /api/theme/', function($) {\n\tF.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) {\n\t\tif (err) {\n\t\t\t$.invalidsafe('The theme can\\'t be saved', err);\n\t\t\treturn;\n\t\t}\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t});\n});\n```\n\n### $.action(name, model)\n\nType: `method`\n\nEjecuta una acción con este controlador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la acción, por ejemplo `Products/list`. |\n| `model` | `Object` | yes |  | Los datos para la acción. |\n\nReturns: `Object` La instancia de la acción.\n\nLlama a la acción `name` (consulta [Acciones](../../guides/actions/)) con `model` y el controlador. Llama a `.autorespond()` sobre el resultado para responder a la petición con la salida de la acción.\n\nExample: Ejemplo\n```js\nROUTE('POST /api/orders/', function($) {\n\t$.action('Orders/create', $.body).autorespond();\n});\n```\n\n### $.authorize([callback])\n\nType: `method`\n\nEjecuta manualmente el delegado de autorización.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Recibe `(err, user)`. |\n\nReturns: `Promise` Cuando se llama sin callback.\n\nLlama a tu delegado de autorización para esta petición. Cuando devuelve un usuario, se establece `$.user`. El callback es `(err, user)`; sin callback el método devuelve una `Promise` con el usuario (o `undefined`).\n\nExample: Ejemplo\n```js\nROUTE('GET /api/me/', async function($) {\n\tvar user = await $.authorize();\n\t$.json({ signed: !!user });\n});\n```\n\n### $.csrf()\n\nType: `method`\n\nCrea un token CSRF.\n\nReturns: `String` El token.\n\nDevuelve un token vinculado a la dirección IP y al navegador del cliente, válido durante el tiempo de `$csrfexpiration` (por defecto `30 minutes`). Necesita la clave de configuración `secret_csrf`; sin ella el token es una cadena vacía.\n\nExample: Ejemplo\n```js\nROUTE('GET /form/', function($) {\n\t$.view('form', { token: $.csrf() });\n});\n```\n\n### $.autoclear([value])\n\nType: `method`\n\nConserva o elimina los archivos subidos después de la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no |  | `false` conserva los archivos. |\n\nLos archivos subidos se eliminan cuando termina la respuesta. `$.autoclear(false)` los conserva, por ejemplo cuando los procesas más tarde.\n\n### $.cancel()\n\nType: `method`\n\nDetiene el procesamiento de la petición en un evento.\n\nLlámalo en `ON('request', fn)` o `ON('controller', fn)` cuando el handler responde él mismo a la petición.\n\nExample: Ejemplo\n```js\nON('request', function($) {\n\tif ($.url === '/health/') {\n\t\t$.cancel();\n\t\t$.plain('OK');\n\t}\n});\n```\n\n### HttpFile\n\nType: `class`\n\nUn archivo subido en `$.files`.\n\nPropiedades: `name` (el campo del formulario), `filename`, `type` (el content type), `size` (bytes), `extension`, `width` y `height` (imágenes), `path` (el archivo temporal), e `isImage`, `isVideo`, `isAudio`.\n\nMétodos:\n\n- `move(filename, [callback])` (también `rename()`) mueve el archivo; sin callback devuelve una `Promise`. Un archivo movido no se elimina después de la respuesta.\n- `copy(filename, callback)` copia el archivo.\n- `read([callback])` lee el archivo en un `Buffer`; sin callback devuelve una `Promise`.\n- `md5([callback])` calcula el hash MD5 en hexadecimal; sin callback devuelve una `Promise`.\n- `stream([opt])` devuelve un stream de lectura; `pipe(stream, [opt])` canaliza el archivo hacia un stream.\n- `image([shell])` devuelve un objeto de imagen para [Imágenes](../../guides/images/).\n- `fs(storage, id, [callback])` guarda el archivo en un [almacenamiento de archivos](../../guides/file-storage/).\n\nExample: Guardar en un almacenamiento de archivos\n```js\nROUTE('POST /upload/ <10MB', function($) {\n\tvar file = $.files[0];\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n});\n```\n","entries":[{"type":"property","name":"$.req","signature":"$.req","since":"","deprecated":false},{"type":"property","name":"$.res","signature":"$.res","since":"","deprecated":false},{"type":"property","name":"$.method","signature":"$.method","since":"","deprecated":false},{"type":"property","name":"$.url","signature":"$.url","since":"","deprecated":false},{"type":"property","name":"$.uri","signature":"$.uri","since":"","deprecated":false},{"type":"property","name":"$.split","signature":"$.split","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.body","signature":"$.body","since":"","deprecated":false},{"type":"property","name":"$.payload","signature":"$.payload","since":"","deprecated":false},{"type":"property","name":"$.files","signature":"$.files","since":"","deprecated":false},{"type":"property","name":"$.headers","signature":"$.headers","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"property","name":"$.ua","signature":"$.ua","since":"","deprecated":false},{"type":"property","name":"$.mobile","signature":"$.mobile","since":"","deprecated":false},{"type":"property","name":"$.robot","signature":"$.robot","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"","deprecated":false},{"type":"property","name":"$.protocol","signature":"$.protocol","since":"","deprecated":false},{"type":"property","name":"$.address","signature":"$.address","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"method","name":"$.json()","signature":"$.json(value, [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"$.jsonstring()","signature":"$.jsonstring(value)","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"$.html()","signature":"$.html(value)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.plain()","signature":"$.plain(value)","since":"","deprecated":false},{"type":"method","name":"$.xml()","signature":"$.xml(value)","since":"","deprecated":false},{"type":"method","name":"$.empty()","signature":"$.empty()","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"$.view()","signature":"$.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"$.layout()","signature":"$.layout(name)","since":"","deprecated":false},{"type":"method","name":"$.file()","signature":"$.file(path, [download])","since":"","deprecated":false},{"type":"method","name":"$.stream()","signature":"$.stream(type, stream, [download])","since":"","deprecated":false},{"type":"method","name":"$.binary()","signature":"$.binary(buffer, type, [download])","since":"","deprecated":false},{"type":"method","name":"$.content()","signature":"$.content(value, [type])","since":"","deprecated":false},{"type":"method","name":"$.image()","signature":"$.image(opt)","since":"","deprecated":false},{"type":"method","name":"$.filefs()","signature":"$.filefs(name, id, [download], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"$.proxy()","signature":"$.proxy(opt)","since":"","deprecated":false},{"type":"method","name":"$.fallback()","signature":"$.fallback(code, [error])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([err], [value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.custom()","signature":"$.custom()","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"$.httpcache()","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"$.notmodified()","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"$.hostname()","signature":"$.hostname([path])","since":"","deprecated":false},{"type":"method","name":"$.href()","signature":"$.href([key], [value])","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, model)","since":"","deprecated":false},{"type":"method","name":"$.authorize()","signature":"$.authorize([callback])","since":"","deprecated":false},{"type":"method","name":"$.csrf()","signature":"$.csrf()","since":"","deprecated":false},{"type":"method","name":"$.autoclear()","signature":"$.autoclear([value])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"class","name":"HttpFile","signature":"HttpFile","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwV6CWx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/controller/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Controller","summary":"Propriétés et méthodes du contrôleur `$` que reçoit chaque action de route.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/controller/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Controller\n\n> Propriétés et méthodes du contrôleur `$` que reçoit chaque action de route.\n\nLe contrôleur est l'argument `$` de chaque action de route. Il contient les données de la requête (`$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.user`...) et les méthodes qui envoient la réponse (`$.json()`, `$.success()`, `$.invalid()`, `$.view()`, `$.file()`, `$.redirect()`...). Pour une présentation avec des exemples, lis le guide [Contrôleur](../../guides/controller/).\n\n## API\n\n### $.req\n\nType: `property`\n\nL'objet de requête de Node.js.\n\nReturns: `IncomingMessage`\n\nLe `http.IncomingMessage` de la requête. Utilise-le uniquement pour ce que le contrôleur ne propose pas.\n\n### $.res\n\nType: `property`\n\nL'objet de réponse de Node.js.\n\nReturns: `ServerResponse`\n\nLe `http.ServerResponse` de la requête. Quand tu y écris toi-même, appelle d'abord `$.custom()` pour que le framework ne réponde pas lui aussi à la requête.\n\n### $.method\n\nType: `property`\n\nLa méthode HTTP de la requête.\n\nReturns: `String`\n\nUne chaîne en majuscules comme `GET`, `POST`, `PUT`, `PATCH` ou `DELETE`.\n\nExample: Exemple\n```js\nROUTE('POST /api/items/', function($) {\n\t// $.method === 'POST'\n\t$.success();\n});\n```\n\n### $.url\n\nType: `property`\n\nLe chemin de l'URL.\n\nReturns: `String`\n\nLe chemin sans la query string. Un chemin sans extension de fichier se termine toujours par `/`, et les doubles barres obliques sont fusionnées. Les lettres conservent leur casse.\n\nExample: Exemple\n```js\nROUTE('GET /docs/', function($) {\n\t// /docs?page=1 gives '/docs/'\n\t$.plain($.url);\n});\n```\n\n### $.uri\n\nType: `property`\n\nL'URL analysée.\n\nReturns: `Object`\n\nUn objet avec `pathname` (identique à `$.url`), `search` (la query string sans `?`), `split` (les segments), `ext` (l'extension du fichier) et `file` (`true` pour une requête de fichier statique).\n\n### $.split\n\nType: `property`\n\nLes segments du chemin.\n\nReturns: `String[]`\n\nUn tableau des parties du chemin : `/blog/2025/hello/` donne `['blog', '2025', 'hello']`. Le chemin racine `/` donne un tableau vide.\n\nExample: Exemple\n```js\nROUTE('GET /blog/*', function($) {\n\t$.json($.split);\n});\n```\n\n### $.params\n\nType: `property`\n\nLes parties dynamiques de l'URL.\n\nReturns: `Object`\n\nChaque `{name}` de la route devient une clé avec le segment correspondant du chemin sous forme de chaîne. Convertis toi-même les nombres et les dates.\n\nExample: Exemple\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id}/', order);\n};\n\nfunction order($) {\n\tvar id = $.params.id;\n\t$.json({ id: id });\n}\n```\n\n### $.query\n\nType: `property`\n\nLa query string sous forme d'objet.\n\nReturns: `Object`\n\nLes valeurs sont des chaînes : `?page=2&q=shoes` donne `{ page: '2', q: 'shoes' }`. Tu peux affecter un nouvel objet. Dans une route d'API, elle contient la query du champ `schema`.\n\nExample: Pagination\n```js\nfunction list($) {\n\tvar page = ($.query.page || '1').parseInt();\n\t$.json({ page: page });\n}\n```\n\n### $.body\n\nType: `property`\n\nLe corps analysé de la requête.\n\nReturns: `Object`\n\nPour les requêtes `POST`, `PUT`, `PATCH` et `DELETE`. Un corps JSON est analysé en objet, un formulaire URL-encoded en objet de chaînes, et une requête `multipart/form-data` donne les champs du formulaire. Les autres types de contenu conservent `{}` et les données brutes sont dans `$.payload`. Dans une route d'API, il contient les `data` de la requête.\n\nExample: Lire le corps\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar email = $.body.email;\n\t$.success();\n}\n```\n\n### $.payload\n\nType: `property`\n\nLe corps brut sous forme de Buffer.\n\nReturns: `Buffer`\n\nLes octets du corps pour tous les types de contenu sauf `multipart/form-data`. Utilise-le pour du XML, du texte brut ou des envois binaires. Il est libéré à la fin de la réponse.\n\nExample: Exemple\n```js\nROUTE('POST /api/xml/', function($) {\n\tvar xml = $.payload.toString('utf8');\n\t$.plain('Received ' + xml.length + ' chars');\n});\n```\n\n### $.files\n\nType: `property`\n\nLes fichiers uploadés.\n\nReturns: `HttpFile[]`\n\nUn tableau de fichiers (`HttpFile`) d'une requête `multipart/form-data`, vide pour les autres requêtes. Les fichiers sont temporaires et sont supprimés à la fin de la réponse, sauf si tu les déplaces ou appelles `$.autoclear(false)`.\n\nExample: Exemple\n```js\nfunction upload($) {\n\tvar names = [];\n\tfor (var file of $.files)\n\t\tnames.push(file.filename + ' (' + file.size + ' bytes)');\n\t$.json(names);\n}\n```\n\n### $.headers\n\nType: `property`\n\nLes en-têtes de la requête.\n\nReturns: `Object`\n\nL'objet des en-têtes de Node.js : les noms sont en minuscules.\n\nExample: Exemple\n```js\nfunction info($) {\n\t$.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] });\n}\n```\n\n### $.ip\n\nType: `property`\n\nL'adresse IP du client.\n\nReturns: `String`\n\nLa première adresse de `X-Forwarded-For` quand l'en-tête existe (derrière un proxy), sinon l'adresse distante de la connexion.\n\nExample: Exemple\n```js\nfunction track($) {\n\tconsole.log('Request from', $.ip);\n\t$.success();\n}\n```\n\n### $.ua\n\nType: `property`\n\nUn nom court du client issu de l'en-tête User-Agent.\n\nReturns: `String`\n\nLe système et le navigateur trouvés dans `User-Agent`, par exemple `Mac OS Chrome`, ou une chaîne vide sans l'en-tête.\n\n### $.mobile\n\nType: `property`\n\n`true` pour un appareil mobile.\n\nReturns: `Boolean`\n\n`true` quand `User-Agent` correspond à un téléphone ou à une tablette (Android, iPhone, iPad, Mobile, Tablet...).\n\n### $.robot\n\nType: `property`\n\n`true` pour un robot d'indexation.\n\nReturns: `Boolean`\n\n`true` quand `User-Agent` contient `search`, `agent`, `bot`, `crawler` ou `spider`.\n\n### $.xhr\n\nType: `property`\n\n`true` pour une XMLHttpRequest.\n\nReturns: `Boolean`\n\n`true` quand la requête contient l'en-tête `X-Requested-With: XMLHttpRequest`. `$.fallback()` répond à ces requêtes avec du JSON au lieu d'une page HTML.\n\n### $.protocol\n\nType: `property`\n\nLe protocole de la requête.\n\nReturns: `String`\n\n`https` pour une connexion chiffrée ou quand un proxy l'indique (`X-Forwarded-Proto: https`, `X-Forwarded-SSL: on` ou `X-Forwarded-Port: 443`), sinon `http`.\n\n### $.address\n\nType: `property`\n\nL'URL complète de la requête.\n\nReturns: `String`\n\nLe protocole, l'hôte et l'URL d'origine avec la query string, par exemple `https://example.com/products/?page=2`.\n\n### $.user\n\nType: `property`\n\nL'utilisateur connecté.\n\nReturns: `Object`\n\nL'objet que ton délégué d'autorisation a renvoyé pour la requête, ou `undefined` quand personne n'est connecté. Voir [Autorisation](../../guides/authorization/).\n\nExample: Exemple\n```js\nROUTE('+GET /api/account/', function($) {\n\t$.json({ name: $.user.name });\n});\n```\n\n### $.language\n\nType: `property`\n\nLa langue de la requête.\n\nReturns: `String`\n\nLa valeur renvoyée par ton délégué de localisation, ou une chaîne vide. Elle sélectionne la traduction des vues et des messages d'erreur. Voir [Localisation](../../guides/localization/).\n\n### $.response\n\nType: `property`\n\nLa réponse qui sera envoyée.\n\nReturns: `Object`\n\nUn objet avec `status` (par défaut `200`), `headers` (un objet d'en-têtes de réponse), `cache` (cache HTTP pour les fichiers) et `minify`. Modifie-le avant d'appeler une méthode de réponse.\n\nExample: Statut et en-tête\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\n### $.json(value, [beautify], [replacer])\n\nType: `method`\n\nEnvoie du JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur à sérialiser. |\n| `beautify` | `Boolean` | no | `false` | `true` indente le JSON avec des tabulations. |\n| `replacer` | `Function|Array` | no |  | Un replacer pour `JSON.stringify()`. |\n\nSérialise `value` avec `JSON.stringify()`, définit `content-type: application/json` et des en-têtes qui désactivent le cache (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). `beautify` indente la sortie avec des tabulations. `replacer` est passé à `JSON.stringify()` comme second argument : une fonction `(key, value)` ou un tableau des clés à conserver.\n\nExample: Exemple\n```js\nROUTE('GET /api/products/', function($) {\n\t$.json([{ id: 1, name: 'Shoes' }]);\n});\n```\n\nExample: Indenter et masquer une clé\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n### $.jsonstring(value)\n\nType: `method`\n\nEnvoie une chaîne qui est déjà du JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Une chaîne JSON. |\n\nEnvoie la chaîne telle quelle avec les mêmes en-têtes que `$.json()`. Utilise-la pour du JSON mis en cache ou lu depuis un fichier.\n\nExample: Exemple\n```js\nfunction cached($) {\n\t$.jsonstring('{\"ok\":true}');\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nEnvoie `{ success: true, value: value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Une valeur facultative pour la clé `value`. |\n\nUn raccourci pour la réponse habituelle d'une API. Sans `value`, la réponse est `{\"success\":true}`.\n\nExample: Exemple\n```js\nfunction remove($) {\n\tNOSQL('products').remove().id($.params.id);\n\t$.success($.params.id);\n}\n```\n\n### $.invalid(error)\n\nType: `method`\n\nEnvoie une erreur en JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Error|ErrorBuilder|Number` | yes |  | L'erreur. |\n\nAccepte une chaîne, une `Error`, un `ErrorBuilder` ou un code de statut HTTP. La réponse est un tableau JSON comme `[{\"error\":\"Name is required\"}]` avec le statut `400`, ou le code de statut donné (`$.invalid(404)` donne `[{\"error\":\"404: Not Found\"}]` avec le statut `404`). Un texte écrit sous la forme `@(text)` est traduit à partir d'une ressource. Sans argument, elle envoie `401`. La réponse est envoyée de manière asynchrone.\n\nExample: Exemple\n```js\nfunction save($) {\n\tif (!$.body.email) {\n\t\t$.invalid('@(Email is required)');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nEnvoie un message d'erreur et enregistre l'erreur réelle dans le log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number|ErrorBuilder` | yes |  | L'erreur pour le client. |\n| `error` | `Error|String` | no |  | L'erreur pour le log. |\n\nEnvoie `message` comme le fait `$.invalid(message)` et écrit `error` dans le log des erreurs avec `F.error()` et l'URL de la requête. Le client ne reçoit que le message. `message` peut aussi être un `ErrorBuilder`.\n\nExample: Exemple\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n### $.html(value)\n\nType: `method`\n\nEnvoie du HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Du HTML. |\n\nDéfinit `content-type: text/html` et envoie la chaîne. Elle est minifiée quand la clé de configuration `$minifyhtml` vaut `true` (la valeur par défaut).\n\nExample: Exemple\n```js\nROUTE('GET /hello/', function($) {\n\t$.html('<h1>Hello</h1>');\n});\n```\n\n### $.throw(error)\n\nType: `method`\n\nÉcrit une erreur dans le log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | L'erreur. |\n\nReturns: `Controller` Le même contrôleur.\n\nPasse `error` avec l'URL de la requête au gestionnaire d'erreurs du framework (`DEF.onError`) : elle est affichée, conservée dans `F.errors` et émise comme événement `error`. Rien n'est envoyé au client. Renvoie `$`.\n\nExample: Exemple\n```js\nfunction save($) {\n\tNOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) {\n\t\terr && $.throw(err);\n\t});\n\t$.success();\n}\n```\n\n### $.plain(value)\n\nType: `method`\n\nEnvoie du texte brut.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le texte. |\n\nDéfinit `content-type: text/plain`. `$.text()` est la même méthode.\n\nExample: Exemple\n```js\nROUTE('FILE /robots.txt', function($) {\n\t$.plain('User-agent: *');\n});\n```\n\n### $.xml(value)\n\nType: `method`\n\nEnvoie du XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Du XML. |\n\nDéfinit `content-type: text/xml` et envoie la chaîne.\n\nExample: Exemple\n```js\nfunction feed($) {\n\t$.xml('<?xml version=\"1.0\"?><rss></rss>');\n}\n```\n\n### $.empty()\n\nType: `method`\n\nEnvoie le statut 204 sans corps.\n\nUtilise-la quand une requête n'a besoin d'aucune donnée dans la réponse.\n\nExample: Exemple\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.empty();\n});\n```\n\n### $.redirect(url, [permanent])\n\nType: `method`\n\nRedirige le client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL cible. |\n| `permanent` | `Boolean` | no | `false` | `true` pour une redirection permanente (301). |\n\nDéfinit l'en-tête `Location` et le statut `302`, ou `301` quand `permanent` vaut `true`.\n\nExample: Exemple\n```js\nROUTE('GET /old/', function($) {\n\t$.redirect('/new/', true);\n});\n```\n\n### $.view([name], [model])\n\nType: `method`\n\nEffectue le rendu d'une vue et l'envoie en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Le nom de la vue, sans l'extension. |\n| `model` | `Object` | no |  | Le modèle de la vue. |\n\nReturns: `View` L'instance de la vue.\n\nEffectue le rendu de la vue `name` du répertoire `/views/` avec `model` et l'envoie avec `$.html()`. Avec le layout de `$.layout()`. Sans `name`, elle renvoie seulement une nouvelle instance de `View` pour le contrôleur. Voir [Vues](../../guides/views/).\n\nExample: Exemple\n```js\nfunction detail($) {\n\tNOSQL('products').one().id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.view('detail', response);\n\t\telse\n\t\t\t$.fallback(404);\n\t});\n}\n```\n\n### $.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. |\n\nLa vue rendue avec `$.view()` est placée dans le layout `name`.\n\nExample: Exemple\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('dashboard');\n}\n```\n\n### $.file(path, [download])\n\nType: `method`\n\nEnvoie un fichier du disque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un chemin absolu du fichier. |\n| `download` | `Boolean|String` | no |  | Un nom de fichier pour le téléchargement, ou `true`. |\n\nDéfinit le type de contenu à partir de l'extension et prend en charge les requêtes `Range`, gzip et les en-têtes de cache HTTP. Les fichiers JS, CSS et HTML sont minifiés sauf si leur nom contient `.min`, `-min` ou `@min`. Avec `download`, le navigateur enregistre le fichier : passe `true` pour conserver son nom ou une chaîne pour le renommer. Un fichier manquant donne `404`.\n\nExample: Exemple\n```js\nROUTE('GET /download/', function($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n});\n```\n\n### $.stream(type, stream, [download])\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` | `ReadableStream` | yes |  | Le flux. |\n| `download` | `String` | no |  | Un nom de fichier pour le téléchargement. |\n\nRedirige `stream` vers la réponse avec le type de contenu `type` (par défaut `application/octet-stream`). Les types texte sont compressés avec gzip quand le client le prend en charge. Une chaîne `download` envoie le flux comme pièce jointe avec ce nom.\n\nExample: Exemple\n```js\nfunction exportcsv($) {\n\tvar stream = F.Fs.createReadStream(PATH.root('export.csv'));\n\t$.stream('text/csv', stream, 'export.csv');\n}\n```\n\n### $.binary(buffer, type, [download])\n\nType: `method`\n\nEnvoie 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| `download` | `String` | no |  | Un nom de fichier pour le téléchargement. |\n\nEnvoie les octets avec le type de contenu `type`. Une chaîne `download` les envoie comme pièce jointe avec ce nom.\n\nExample: Exemple\n```js\nfunction pixel($) {\n\tvar buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');\n\t$.binary(buffer, 'image/gif');\n}\n```\n\n### $.content(value, [type])\n\nType: `method`\n\nEnvoie une chaîne ou un Buffer avec un type de contenu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Le contenu. |\n| `type` | `String` | no | `'application/octet-stream'` | Le type de contenu. |\n\nEnvoie `value` avec l'en-tête `content-type: type` ; sans `type`, c'est `application/octet-stream`. Une chaîne est envoyée en UTF-8. Contrairement à `$.binary()`, elle accepte aussi une chaîne et n'a pas de nom de téléchargement.\n\nExample: CSV\n```js\nROUTE('GET /export/', function($) {\n\t$.content('id,name\\n1,Mug\\n', 'text/csv');\n});\n```\n\n### $.image(opt)\n\nType: `method`\n\nTraite une image et l'envoie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Les options. |\n\nCharge un flux d'image, te permet de le modifier et envoie le résultat. `opt.ext` (obligatoire) est l'extension de la sortie, `opt.load(next, opt)` appelle `next(stream)` avec la source, `opt.image(img, opt)` modifie l'image (voir [Images](../../guides/images/)), `opt.cache` est une clé pour conserver le résultat dans le répertoire temporaire, et `opt.date` une date pour le cache HTTP.\n\nExample: Exemple\n```js\nfunction thumbnail($) {\n\t$.image({\n\t\text: 'jpg',\n\t\tcache: 'thumb_' + $.params.id,\n\t\tload: function(next) {\n\t\t\tnext(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg')));\n\t\t},\n\t\timage: function(img) {\n\t\t\timg.resize(200, 200);\n\t\t}\n\t});\n}\n```\n\n### $.filefs(name, id, [download], [checkmeta])\n\nType: `method`\n\nEnvoie un fichier d'un stockage de fichiers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du stockage de fichiers. |\n| `id` | `String` | yes |  | L'identifiant du fichier. |\n| `download` | `Boolean|String` | no |  | Envoyer comme pièce jointe. |\n| `checkmeta` | `Function` | no |  | Une vérification des métadonnées. |\n\nReturns: `Object` Les options passées au stockage.\n\nEnvoie le fichier `id` du stockage de fichiers `name` (voir [Stockage de fichiers](../../guides/file-storage/)). `download` l'envoie comme pièce jointe, `true` avec son nom enregistré ou une chaîne pour un autre nom. `checkmeta` est une fonction qui reçoit les métadonnées du fichier et décide s'il peut être envoyé.\n\nExample: Exemple\n```js\nROUTE('GET /files/{id}/', function($) {\n\t$.filefs('files', $.params.id);\n});\n```\n\n### $.proxy(opt)\n\nType: `method`\n\nTransmet la requête à un autre serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `String|Object` | yes |  | L'URL cible ou les options. |\n\nEnvoie la méthode, les en-têtes, le corps et la query string de la requête à `opt` (une URL, ou un objet avec `url`, `method`, `headers`, `timeout` (par défaut 10000 ms) et `callback(err, response)`) et répond avec la réponse de ce serveur.\n\nExample: Exemple\n```js\nROUTE('GET /api/weather/', function($) {\n\t$.proxy('https://weather.example.com/today/');\n});\n```\n\n### $.fallback(code, [error])\n\nType: `method`\n\nEnvoie une page d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Le code de statut HTTP. |\n| `error` | `String|Error` | no |  | L'erreur pour le mode debug. |\n\nQuand une route `#code` existe (par exemple `ROUTE('#404', fn)`), son action gère la requête ; le statut reste `200` sauf si l'action définit `$.response.status`. Sinon, elle envoie la page d'erreur intégrée avec le statut `code`, ou `$.invalid(code)` pour les requêtes XHR. `error` est affichée sur la page en mode debug.\n\nExample: Exemple\n```js\nexports.install = function() {\n\tROUTE('GET /secret/', function($) {\n\t\t$.fallback(404);\n\t});\n\tROUTE('#404', function($) {\n\t\t$.view('404');\n\t});\n};\n```\n\n### $.callback([err], [value])\n\nType: `method`\n\nRépond à partir d'un callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | no |  | Une erreur. |\n| `value` | `Object` | no |  | La valeur à envoyer. |\n\nReturns: `Function` Un callback quand elle est appelée sans arguments.\n\nSans arguments, elle renvoie une fonction `(err, response)` qui appelle `$.invalid(err)` ou `$.json(response)`. Avec des arguments, elle répond immédiatement : `$.invalid(err)`, `$.success()` quand `value` vaut `undefined`, ou `$.json(value)`.\n\nExample: Exemple\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.callback());\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nRenvoie un callback qui répond avec un succès.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | La valeur, ou `true` pour la réponse du callback. |\n\nReturns: `Function` Un callback.\n\nLa fonction renvoyée `(err, response)` appelle `$.invalid(err)` en cas d'erreur, sinon elle envoie `{ success: true, value: value }`. Passe `true` pour utiliser la `response` du callback comme valeur.\n\nExample: Exemple\n```js\nROUTE('POST /api/products/', function($) {\n\tNOSQL('products').insert($.body).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` | yes |  | Appelé quand il n'y a pas d'erreur. |\n\nReturns: `Function` Un callback.\n\nLa fonction renvoyée `(err, a, b, c)` appelle `$.invalid(err)` en cas d'erreur, sinon `callback(a, b, c)` avec le contrôleur comme `this`.\n\nExample: Exemple\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.successful(function(response) {\n\t\t$.json(response);\n\t}));\n});\n```\n\n### $.custom()\n\nType: `method`\n\nIndique au framework que tu envoies toi-même la réponse.\n\nMarque le contrôleur comme terminé afin qu'aucune méthode de réponse n'y écrive. Écris ensuite dans `$.res` avec l'API de Node.js.\n\nExample: Exemple\n```js\nROUTE('GET /events/', function($) {\n\t$.custom();\n\t$.res.writeHead(200, { 'content-type': 'text/event-stream' });\n\t$.res.write('data: hello\\n\\n');\n});\n```\n\n### $.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLit ou définit un cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du cookie. |\n| `value` | `String` | no |  | La valeur à définir. |\n| `expires` | `Date|String|Object` | no |  | L'expiration, ou les options. |\n| `options` | `Object` | no |  | Les options du cookie. |\n\nReturns: `String|Controller` La valeur en lecture, le contrôleur en écriture.\n\nAvec seulement `name`, elle renvoie la valeur décodée du cookie, ou une chaîne vide. Avec `value`, elle ajoute un en-tête `Set-Cookie` (un cookie du même nom défini plus tôt dans la requête est remplacé) et renvoie le contrôleur. `expires` est une `Date`, une chaîne comme `'7 days'`, ou l'objet d'options. Les options sont `expires`, `domain`, `path` (par défaut `/`), `secure` (par défaut issu de `$cookiesecure`), `httponly` et `samesite` (par défaut issu de `$cookiesamesite`, `'Lax'`).\n\nExample: Exemple\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' });\n\t$.success();\n}\n\nfunction profile($) {\n\t$.json({ session: $.cookie('session') });\n}\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nDéfinit les en-têtes de cache HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | La date de la dernière modification. |\n\nDéfinit `Last-Modified` à `date`, `ETag`, ainsi que `Expires` et `Cache-Control` quand ils ne sont pas encore définis.\n\nExample: Exemple\n```js\nfunction article($) {\n\tvar updated = new Date(2025, 0, 1);\n\tif ($.notmodified(updated.toUTCString()))\n\t\treturn;\n\t$.httpcache(updated);\n\t$.view('article');\n}\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nRépond 304 quand le client possède la même version.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | La date de la dernière modification sous forme de chaîne UTC. |\n\nReturns: `Boolean` `true` quand la réponse 304 a été envoyée.\n\nCompare `date` (une chaîne UTC) avec l'en-tête `If-Modified-Since`. Quand elles sont égales, elle envoie `304 Not Modified` et renvoie `true`.\n\n### $.hostname([path])\n\nType: `method`\n\nRenvoie le protocole et l'hôte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un chemin à ajouter. |\n\nReturns: `String` L'URL.\n\nDonne `protocol://host` de la requête avec un chemin facultatif ajouté à la fin.\n\nExample: Exemple\n```js\nfunction share($) {\n\t$.json({ url: $.hostname('/products/' + $.params.id + '/') });\n}\n```\n\n### $.href([key], [value])\n\nType: `method`\n\nRenvoie la query string avec un paramètre modifié.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | Le nom du paramètre, ou un objet avec les paramètres à définir. |\n| `value` | `String|Number|Array|Object` | no |  | La nouvelle valeur. |\n\nReturns: `String` La query string avec `?`, ou une chaîne vide.\n\nSans arguments, elle renvoie la query string de la requête (`?page=2&sort=name`), ou une chaîne vide. `$.href(key, value)` la renvoie avec `key` défini à `value` ; les autres paramètres restent. Sans `value`, la valeur actuelle de `key` est conservée. Les arguments supplémentaires après `value` sont des noms de paramètres à supprimer. Une valeur tableau écrit le paramètre une fois pour chaque élément et une valeur objet est écrite en JSON. `$.href({ key: value, ... })` renvoie l'URL de la requête avec la query string modifiée par les clés de l'objet. Elle fonctionne comme `@{href()}` dans les vues.\n\nExample: Pagination\n```js\n// GET /products/?page=2&sort=name\nfunction products($) {\n\t$.json({\n\t\tnext: $.href('page', 3),           // ?page=3&sort=name\n\t\tcurrent: $.href()                  // ?page=2&sort=name\n\t});\n}\n```\n\nExample: Supprimer un paramètre, ou en modifier plusieurs\n```js\n// GET /products/?page=2&sort=name&q=pen\n$.href('page', 1, 'sort');           // ?page=1&q=pen\n$.href({ page: 1, sort: 'price' });  // /products/?page=1&sort=price&q=pen\n```\n\n### $.touch([url])\n\nType: `method`\n\nEfface l'état mis en cache d'un fichier statique.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | L'URL du fichier. |\n\nReturns: `Controller` Le même contrôleur.\n\nAppelle `TOUCH(url)` ; sans `url`, elle utilise l'URL de la requête. Utilise-la après que la route a modifié un fichier dans `public/`. Renvoie `$`.\n\nExample: Exemple\n```js\nROUTE('POST /api/theme/', function($) {\n\tF.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) {\n\t\tif (err) {\n\t\t\t$.invalidsafe('The theme can\\'t be saved', err);\n\t\t\treturn;\n\t\t}\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t});\n});\n```\n\n### $.action(name, model)\n\nType: `method`\n\nExécute une action avec ce contrôleur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'action, par exemple `Products/list`. |\n| `model` | `Object` | yes |  | Les données pour l'action. |\n\nReturns: `Object` L'instance de l'action.\n\nAppelle l'action `name` (voir [Actions](../../guides/actions/)) avec `model` et le contrôleur. Appelle `.autorespond()` sur le résultat pour répondre à la requête avec la sortie de l'action.\n\nExample: Exemple\n```js\nROUTE('POST /api/orders/', function($) {\n\t$.action('Orders/create', $.body).autorespond();\n});\n```\n\n### $.authorize([callback])\n\nType: `method`\n\nExécute manuellement le délégué d'autorisation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Reçoit `(err, user)`. |\n\nReturns: `Promise` Quand elle est appelée sans callback.\n\nAppelle ton délégué d'autorisation pour cette requête. Quand il renvoie un utilisateur, `$.user` est défini. Le callback est `(err, user)` ; sans callback, la méthode renvoie une `Promise` avec l'utilisateur (ou `undefined`).\n\nExample: Exemple\n```js\nROUTE('GET /api/me/', async function($) {\n\tvar user = await $.authorize();\n\t$.json({ signed: !!user });\n});\n```\n\n### $.csrf()\n\nType: `method`\n\nCrée un jeton CSRF.\n\nReturns: `String` Le jeton.\n\nRenvoie un jeton lié à l'adresse IP et au navigateur du client, valable pendant la durée de `$csrfexpiration` (par défaut `30 minutes`). Elle nécessite la clé de configuration `secret_csrf` ; sans elle, le jeton est une chaîne vide.\n\nExample: Exemple\n```js\nROUTE('GET /form/', function($) {\n\t$.view('form', { token: $.csrf() });\n});\n```\n\n### $.autoclear([value])\n\nType: `method`\n\nConserve ou supprime les fichiers envoyés après la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no |  | `false` conserve les fichiers. |\n\nLes fichiers envoyés sont supprimés à la fin de la réponse. `$.autoclear(false)` les conserve, par exemple quand tu les traites plus tard.\n\n### $.cancel()\n\nType: `method`\n\nArrête le traitement de la requête dans un événement.\n\nAppelle-la dans `ON('request', fn)` ou `ON('controller', fn)` quand le gestionnaire répond lui-même à la requête.\n\nExample: Exemple\n```js\nON('request', function($) {\n\tif ($.url === '/health/') {\n\t\t$.cancel();\n\t\t$.plain('OK');\n\t}\n});\n```\n\n### HttpFile\n\nType: `class`\n\nUn fichier envoyé dans `$.files`.\n\nPropriétés : `name` (le champ du formulaire), `filename`, `type` (le type de contenu), `size` (octets), `extension`, `width` et `height` (images), `path` (le fichier temporaire), ainsi que `isImage`, `isVideo`, `isAudio`.\n\nMéthodes :\n\n- `move(filename, [callback])` (aussi `rename()`) déplace le fichier ; sans callback, elle renvoie une `Promise`. Un fichier déplacé n'est pas supprimé après la réponse.\n- `copy(filename, callback)` copie le fichier.\n- `read([callback])` lit le fichier dans un `Buffer` ; sans callback, elle renvoie une `Promise`.\n- `md5([callback])` calcule le hachage MD5 en hexadécimal ; sans callback, elle renvoie une `Promise`.\n- `stream([opt])` renvoie un flux de lecture ; `pipe(stream, [opt])` redirige le fichier vers un flux.\n- `image([shell])` renvoie un objet image pour [Images](../../guides/images/).\n- `fs(storage, id, [callback])` enregistre le fichier dans un [stockage de fichiers](../../guides/file-storage/).\n\nExample: Enregistrer dans un stockage de fichiers\n```js\nROUTE('POST /upload/ <10MB', function($) {\n\tvar file = $.files[0];\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n});\n```\n","entries":[{"type":"property","name":"$.req","signature":"$.req","since":"","deprecated":false},{"type":"property","name":"$.res","signature":"$.res","since":"","deprecated":false},{"type":"property","name":"$.method","signature":"$.method","since":"","deprecated":false},{"type":"property","name":"$.url","signature":"$.url","since":"","deprecated":false},{"type":"property","name":"$.uri","signature":"$.uri","since":"","deprecated":false},{"type":"property","name":"$.split","signature":"$.split","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.body","signature":"$.body","since":"","deprecated":false},{"type":"property","name":"$.payload","signature":"$.payload","since":"","deprecated":false},{"type":"property","name":"$.files","signature":"$.files","since":"","deprecated":false},{"type":"property","name":"$.headers","signature":"$.headers","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"property","name":"$.ua","signature":"$.ua","since":"","deprecated":false},{"type":"property","name":"$.mobile","signature":"$.mobile","since":"","deprecated":false},{"type":"property","name":"$.robot","signature":"$.robot","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"","deprecated":false},{"type":"property","name":"$.protocol","signature":"$.protocol","since":"","deprecated":false},{"type":"property","name":"$.address","signature":"$.address","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"method","name":"$.json()","signature":"$.json(value, [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"$.jsonstring()","signature":"$.jsonstring(value)","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"$.html()","signature":"$.html(value)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.plain()","signature":"$.plain(value)","since":"","deprecated":false},{"type":"method","name":"$.xml()","signature":"$.xml(value)","since":"","deprecated":false},{"type":"method","name":"$.empty()","signature":"$.empty()","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"$.view()","signature":"$.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"$.layout()","signature":"$.layout(name)","since":"","deprecated":false},{"type":"method","name":"$.file()","signature":"$.file(path, [download])","since":"","deprecated":false},{"type":"method","name":"$.stream()","signature":"$.stream(type, stream, [download])","since":"","deprecated":false},{"type":"method","name":"$.binary()","signature":"$.binary(buffer, type, [download])","since":"","deprecated":false},{"type":"method","name":"$.content()","signature":"$.content(value, [type])","since":"","deprecated":false},{"type":"method","name":"$.image()","signature":"$.image(opt)","since":"","deprecated":false},{"type":"method","name":"$.filefs()","signature":"$.filefs(name, id, [download], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"$.proxy()","signature":"$.proxy(opt)","since":"","deprecated":false},{"type":"method","name":"$.fallback()","signature":"$.fallback(code, [error])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([err], [value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.custom()","signature":"$.custom()","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"$.httpcache()","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"$.notmodified()","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"$.hostname()","signature":"$.hostname([path])","since":"","deprecated":false},{"type":"method","name":"$.href()","signature":"$.href([key], [value])","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, model)","since":"","deprecated":false},{"type":"method","name":"$.authorize()","signature":"$.authorize([callback])","since":"","deprecated":false},{"type":"method","name":"$.csrf()","signature":"$.csrf()","since":"","deprecated":false},{"type":"method","name":"$.autoclear()","signature":"$.autoclear([value])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"class","name":"HttpFile","signature":"HttpFile","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwV6CWx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/controller/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Controller","summary":"Proprietà e metodi del controller `$` che ogni azione di una route riceve.","markdown":"---\ntitle: Controller\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/controller/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Controller\n\n> Proprietà e metodi del controller `$` che ogni azione di una route riceve.\n\nIl controller è l'argomento `$` di ogni azione di una route. Contiene i dati della richiesta (`$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.user`...) e i metodi che inviano la risposta (`$.json()`, `$.success()`, `$.invalid()`, `$.view()`, `$.file()`, `$.redirect()`...). Per una panoramica con esempi, leggi la guida [Controller](../../guides/controller/).\n\n## API\n\n### $.req\n\nType: `property`\n\nL'oggetto request di Node.js.\n\nReturns: `IncomingMessage`\n\nL'`http.IncomingMessage` della richiesta. Usalo solo per ciò che il controller non offre.\n\n### $.res\n\nType: `property`\n\nL'oggetto response di Node.js.\n\nReturns: `ServerResponse`\n\nL'`http.ServerResponse` della richiesta. Quando ci scrivi tu, chiama prima `$.custom()` così il framework non risponde anch'esso alla richiesta.\n\n### $.method\n\nType: `property`\n\nIl metodo HTTP della richiesta.\n\nReturns: `String`\n\nUna stringa in maiuscolo come `GET`, `POST`, `PUT`, `PATCH` o `DELETE`.\n\nExample: Esempio\n```js\nROUTE('POST /api/items/', function($) {\n\t// $.method === 'POST'\n\t$.success();\n});\n```\n\n### $.url\n\nType: `property`\n\nIl percorso dell'URL.\n\nReturns: `String`\n\nIl percorso senza la query string. Un percorso senza estensione di file termina sempre con `/`, e gli slash doppi vengono uniti. Le lettere mantengono maiuscole e minuscole.\n\nExample: Esempio\n```js\nROUTE('GET /docs/', function($) {\n\t// /docs?page=1 gives '/docs/'\n\t$.plain($.url);\n});\n```\n\n### $.uri\n\nType: `property`\n\nL'URL analizzato.\n\nReturns: `Object`\n\nUn oggetto con `pathname` (uguale a `$.url`), `search` (la query string senza `?`), `split` (i segmenti), `ext` (l'estensione del file) e `file` (`true` per la richiesta di un file statico).\n\n### $.split\n\nType: `property`\n\nI segmenti del percorso.\n\nReturns: `String[]`\n\nUn array delle parti del percorso: `/blog/2025/hello/` dà `['blog', '2025', 'hello']`. Il percorso radice `/` dà un array vuoto.\n\nExample: Esempio\n```js\nROUTE('GET /blog/*', function($) {\n\t$.json($.split);\n});\n```\n\n### $.params\n\nType: `property`\n\nLe parti dinamiche dell'URL.\n\nReturns: `Object`\n\nOgni `{name}` della route diventa una chiave con il segmento corrispondente del percorso come stringa. Converti tu numeri e date.\n\nExample: Esempio\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id}/', order);\n};\n\nfunction order($) {\n\tvar id = $.params.id;\n\t$.json({ id: id });\n}\n```\n\n### $.query\n\nType: `property`\n\nLa query string come oggetto.\n\nReturns: `Object`\n\nI valori sono stringhe: `?page=2&q=shoes` dà `{ page: '2', q: 'shoes' }`. Puoi assegnare un nuovo oggetto. In una route API, contiene la query del campo `schema`.\n\nExample: Paginazione\n```js\nfunction list($) {\n\tvar page = ($.query.page || '1').parseInt();\n\t$.json({ page: page });\n}\n```\n\n### $.body\n\nType: `property`\n\nIl corpo della richiesta già analizzato.\n\nReturns: `Object`\n\nPer le richieste `POST`, `PUT`, `PATCH` e `DELETE`. Un body JSON viene analizzato in un oggetto, un form URL-encoded in un oggetto di stringhe, e una richiesta `multipart/form-data` dà i campi del form. Gli altri content type mantengono `{}` e i dati grezzi sono in `$.payload`. In una route API, contiene i `data` della richiesta.\n\nExample: Leggere il body\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar email = $.body.email;\n\t$.success();\n}\n```\n\n### $.payload\n\nType: `property`\n\nIl body grezzo come Buffer.\n\nReturns: `Buffer`\n\nI byte del body per ogni content type tranne `multipart/form-data`. Usalo per XML, testo semplice o upload binari. Viene rilasciato quando la risposta termina.\n\nExample: Esempio\n```js\nROUTE('POST /api/xml/', function($) {\n\tvar xml = $.payload.toString('utf8');\n\t$.plain('Received ' + xml.length + ' chars');\n});\n```\n\n### $.files\n\nType: `property`\n\nI file caricati.\n\nReturns: `HttpFile[]`\n\nUn array di file (`HttpFile`) di una richiesta `multipart/form-data`, vuoto per le altre richieste. I file sono temporanei e vengono rimossi quando la risposta termina, a meno che tu non li sposti o chiami `$.autoclear(false)`.\n\nExample: Esempio\n```js\nfunction upload($) {\n\tvar names = [];\n\tfor (var file of $.files)\n\t\tnames.push(file.filename + ' (' + file.size + ' bytes)');\n\t$.json(names);\n}\n```\n\n### $.headers\n\nType: `property`\n\nGli header della richiesta.\n\nReturns: `Object`\n\nL'oggetto headers di Node.js: i nomi sono in minuscolo.\n\nExample: Esempio\n```js\nfunction info($) {\n\t$.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] });\n}\n```\n\n### $.ip\n\nType: `property`\n\nL'indirizzo IP del client.\n\nReturns: `String`\n\nIl primo indirizzo di `X-Forwarded-For` quando l'header esiste (dietro un proxy), altrimenti l'indirizzo remoto della connessione.\n\nExample: Esempio\n```js\nfunction track($) {\n\tconsole.log('Request from', $.ip);\n\t$.success();\n}\n```\n\n### $.ua\n\nType: `property`\n\nUn nome breve del client ricavato dall'header User-Agent.\n\nReturns: `String`\n\nIl sistema e il browser trovati in `User-Agent`, per esempio `Mac OS Chrome`, oppure una stringa vuota se l'header manca.\n\n### $.mobile\n\nType: `property`\n\n`true` per un dispositivo mobile.\n\nReturns: `Boolean`\n\n`true` quando `User-Agent` corrisponde a un telefono o a un tablet (Android, iPhone, iPad, Mobile, Tablet...).\n\n### $.robot\n\nType: `property`\n\n`true` per un crawler.\n\nReturns: `Boolean`\n\n`true` quando `User-Agent` contiene `search`, `agent`, `bot`, `crawler` o `spider`.\n\n### $.xhr\n\nType: `property`\n\n`true` per una XMLHttpRequest.\n\nReturns: `Boolean`\n\n`true` quando la richiesta ha l'header `X-Requested-With: XMLHttpRequest`. `$.fallback()` risponde a queste richieste con JSON invece che con una pagina HTML.\n\n### $.protocol\n\nType: `property`\n\nIl protocollo della richiesta.\n\nReturns: `String`\n\n`https` per una connessione cifrata o quando lo indica un proxy (`X-Forwarded-Proto: https`, `X-Forwarded-SSL: on` o `X-Forwarded-Port: 443`), altrimenti `http`.\n\n### $.address\n\nType: `property`\n\nL'URL completo della richiesta.\n\nReturns: `String`\n\nIl protocollo, l'host e l'URL originale con la query string, per esempio `https://example.com/products/?page=2`.\n\n### $.user\n\nType: `property`\n\nL'utente autenticato.\n\nReturns: `Object`\n\nL'oggetto che il tuo delegate di autorizzazione ha restituito per la richiesta, oppure `undefined` quando nessuno ha effettuato l'accesso. Vedi [Autorizzazione](../../guides/authorization/).\n\nExample: Esempio\n```js\nROUTE('+GET /api/account/', function($) {\n\t$.json({ name: $.user.name });\n});\n```\n\n### $.language\n\nType: `property`\n\nLa lingua della richiesta.\n\nReturns: `String`\n\nIl valore restituito dal tuo delegate di localizzazione, oppure una stringa vuota. Seleziona la traduzione delle viste e dei messaggi di errore. Vedi [Localizzazione](../../guides/localization/).\n\n### $.response\n\nType: `property`\n\nLa risposta che verrà inviata.\n\nReturns: `Object`\n\nUn oggetto con `status` (predefinito `200`), `headers` (un oggetto di header della risposta), `cache` (cache HTTP per i file) e `minify`. Modificalo prima di chiamare un metodo di risposta.\n\nExample: Stato e un header\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\n### $.json(value, [beautify], [replacer])\n\nType: `method`\n\nInvia JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore da serializzare. |\n| `beautify` | `Boolean` | no | `false` | `true` indenta il JSON con tabulazioni. |\n| `replacer` | `Function|Array` | no |  | Un replacer per `JSON.stringify()`. |\n\nSerializza `value` con `JSON.stringify()`, imposta `content-type: application/json` e header che disattivano la cache (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). `beautify` indenta l'output con tabulazioni. `replacer` viene passato a `JSON.stringify()` come secondo argomento: una funzione `(key, value)` o un array di chiavi da mantenere.\n\nExample: Esempio\n```js\nROUTE('GET /api/products/', function($) {\n\t$.json([{ id: 1, name: 'Shoes' }]);\n});\n```\n\nExample: Formattare e nascondere una chiave\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n### $.jsonstring(value)\n\nType: `method`\n\nInvia una stringa che è già JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Una stringa JSON. |\n\nInvia la stringa così com'è con gli stessi header di `$.json()`. Usalo per JSON che hai in cache o che hai letto da un file.\n\nExample: Esempio\n```js\nfunction cached($) {\n\t$.jsonstring('{\"ok\":true}');\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nInvia `{ success: true, value: value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Un valore opzionale per la chiave `value`. |\n\nUna scorciatoia per la risposta tipica di un'API. Senza `value` la risposta è `{\"success\":true}`.\n\nExample: Esempio\n```js\nfunction remove($) {\n\tNOSQL('products').remove().id($.params.id);\n\t$.success($.params.id);\n}\n```\n\n### $.invalid(error)\n\nType: `method`\n\nInvia un errore come JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Error|ErrorBuilder|Number` | yes |  | L'errore. |\n\nAccetta una stringa, un `Error`, un `ErrorBuilder` o un codice di stato HTTP. La risposta è un array JSON come `[{\"error\":\"Name is required\"}]` con lo stato `400`, oppure il codice di stato indicato (`$.invalid(404)` dà `[{\"error\":\"404: Not Found\"}]` con stato `404`). Il testo scritto come `@(text)` viene tradotto da una risorsa. Senza argomenti invia `401`. La risposta viene inviata in modo asincrono.\n\nExample: Esempio\n```js\nfunction save($) {\n\tif (!$.body.email) {\n\t\t$.invalid('@(Email is required)');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nInvia un messaggio di errore e registra l'errore reale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number|ErrorBuilder` | yes |  | L'errore per il client. |\n| `error` | `Error|String` | no |  | L'errore per il log. |\n\nInvia `message` come fa `$.invalid(message)` e scrive `error` nel log degli errori con `F.error()` e l'URL della richiesta. Il client riceve solo il messaggio. `message` può essere anche un `ErrorBuilder`.\n\nExample: Esempio\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n### $.html(value)\n\nType: `method`\n\nInvia HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML. |\n\nImposta `content-type: text/html` e invia la stringa. Viene minificata quando la chiave di configurazione `$minifyhtml` è `true` (il valore predefinito).\n\nExample: Esempio\n```js\nROUTE('GET /hello/', function($) {\n\t$.html('<h1>Hello</h1>');\n});\n```\n\n### $.throw(error)\n\nType: `method`\n\nScrive un errore nel log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | L'errore. |\n\nReturns: `Controller` Lo stesso controller.\n\nPassa `error` con l'URL della richiesta al gestore degli errori del framework (`DEF.onError`): viene stampato, conservato in `F.errors` ed emesso come evento `error`. Al client non viene inviato nulla. Restituisce `$`.\n\nExample: Esempio\n```js\nfunction save($) {\n\tNOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) {\n\t\terr && $.throw(err);\n\t});\n\t$.success();\n}\n```\n\n### $.plain(value)\n\nType: `method`\n\nInvia testo semplice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il testo. |\n\nImposta `content-type: text/plain`. `$.text()` è lo stesso metodo.\n\nExample: Esempio\n```js\nROUTE('FILE /robots.txt', function($) {\n\t$.plain('User-agent: *');\n});\n```\n\n### $.xml(value)\n\nType: `method`\n\nInvia XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | XML. |\n\nImposta `content-type: text/xml` e invia la stringa.\n\nExample: Esempio\n```js\nfunction feed($) {\n\t$.xml('<?xml version=\"1.0\"?><rss></rss>');\n}\n```\n\n### $.empty()\n\nType: `method`\n\nInvia lo stato 204 senza body.\n\nUsalo quando una richiesta non ha bisogno di dati nella risposta.\n\nExample: Esempio\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.empty();\n});\n```\n\n### $.redirect(url, [permanent])\n\nType: `method`\n\nReindirizza il client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL di destinazione. |\n| `permanent` | `Boolean` | no | `false` | `true` per un redirect permanente (301). |\n\nImposta l'header `Location` e lo stato `302`, oppure `301` quando `permanent` è `true`.\n\nExample: Esempio\n```js\nROUTE('GET /old/', function($) {\n\t$.redirect('/new/', true);\n});\n```\n\n### $.view([name], [model])\n\nType: `method`\n\nRenderizza una vista e la invia come HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Il nome della vista, senza estensione. |\n| `model` | `Object` | no |  | Il model per la vista. |\n\nReturns: `View` L'istanza della vista.\n\nRenderizza la vista `name` della directory `/views/` con `model` e la invia con `$.html()`. Con il layout di `$.layout()`. Senza `name` restituisce solo una nuova istanza di `View` per il controller. Vedi [Viste](../../guides/views/).\n\nExample: Esempio\n```js\nfunction detail($) {\n\tNOSQL('products').one().id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.view('detail', response);\n\t\telse\n\t\t\t$.fallback(404);\n\t});\n}\n```\n\n### $.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. |\n\nLa vista renderizzata con `$.view()` viene inserita nel layout `name`.\n\nExample: Esempio\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('dashboard');\n}\n```\n\n### $.file(path, [download])\n\nType: `method`\n\nInvia un file dal disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un percorso assoluto del file. |\n| `download` | `Boolean|String` | no |  | Un nome di file per il download, oppure `true`. |\n\nImposta il content type dall'estensione e supporta le richieste `Range`, gzip e gli header di cache HTTP. I file JS, CSS e HTML vengono minificati a meno che il loro nome contenga `.min`, `-min` o `@min`. Con `download` il browser salva il file: passa `true` per mantenerne il nome o una stringa per rinominarlo. Un file mancante dà `404`.\n\nExample: Esempio\n```js\nROUTE('GET /download/', function($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n});\n```\n\n### $.stream(type, stream, [download])\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` | `ReadableStream` | yes |  | Lo stream. |\n| `download` | `String` | no |  | Un nome di file per il download. |\n\nInvia `stream` alla risposta tramite pipe con il content type `type` (predefinito `application/octet-stream`). I tipi testuali vengono compressi con gzip quando il client lo supporta. Una stringa `download` invia lo stream come allegato con quel nome.\n\nExample: Esempio\n```js\nfunction exportcsv($) {\n\tvar stream = F.Fs.createReadStream(PATH.root('export.csv'));\n\t$.stream('text/csv', stream, 'export.csv');\n}\n```\n\n### $.binary(buffer, type, [download])\n\nType: `method`\n\nInvia un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | I dati. |\n| `type` | `String` | yes |  | Il content type. |\n| `download` | `String` | no |  | Un nome di file per il download. |\n\nInvia i byte con il content type `type`. Una stringa `download` li invia come allegato con quel nome.\n\nExample: Esempio\n```js\nfunction pixel($) {\n\tvar buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');\n\t$.binary(buffer, 'image/gif');\n}\n```\n\n### $.content(value, [type])\n\nType: `method`\n\nInvia una stringa o un Buffer con un content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Il contenuto. |\n| `type` | `String` | no | `'application/octet-stream'` | Il content type. |\n\nInvia `value` con l'header `content-type: type`; senza `type` è `application/octet-stream`. Una stringa viene inviata come UTF-8. A differenza di `$.binary()`, accetta anche una stringa e non ha un nome di download.\n\nExample: CSV\n```js\nROUTE('GET /export/', function($) {\n\t$.content('id,name\\n1,Mug\\n', 'text/csv');\n});\n```\n\n### $.image(opt)\n\nType: `method`\n\nElabora un'immagine e la invia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Le opzioni. |\n\nCarica uno stream di immagine, ti permette di modificarlo e invia il risultato. `opt.ext` (obbligatorio) è l'estensione dell'output, `opt.load(next, opt)` chiama `next(stream)` con la sorgente, `opt.image(img, opt)` modifica l'immagine (vedi [Immagini](../../guides/images/)), `opt.cache` è una chiave per conservare il risultato nella directory temporanea, e `opt.date` una data per la cache HTTP.\n\nExample: Esempio\n```js\nfunction thumbnail($) {\n\t$.image({\n\t\text: 'jpg',\n\t\tcache: 'thumb_' + $.params.id,\n\t\tload: function(next) {\n\t\t\tnext(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg')));\n\t\t},\n\t\timage: function(img) {\n\t\t\timg.resize(200, 200);\n\t\t}\n\t});\n}\n```\n\n### $.filefs(name, id, [download], [checkmeta])\n\nType: `method`\n\nInvia un file da un file storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del file storage. |\n| `id` | `String` | yes |  | L'identificatore del file. |\n| `download` | `Boolean|String` | no |  | Invia come allegato. |\n| `checkmeta` | `Function` | no |  | Un controllo dei metadati. |\n\nReturns: `Object` Le opzioni passate allo storage.\n\nInvia il file `id` dal file storage `name` (vedi [File storage](../../guides/file-storage/)). `download` lo invia come allegato, `true` con il nome salvato o una stringa per un altro nome. `checkmeta` è una funzione che riceve i metadati del file e decide se può essere inviato.\n\nExample: Esempio\n```js\nROUTE('GET /files/{id}/', function($) {\n\t$.filefs('files', $.params.id);\n});\n```\n\n### $.proxy(opt)\n\nType: `method`\n\nInoltra la richiesta a un altro server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `String|Object` | yes |  | L'URL di destinazione o le opzioni. |\n\nInvia il metodo, gli header, il body e la query string della richiesta a `opt` (un URL, oppure un oggetto con `url`, `method`, `headers`, `timeout` (predefinito 10000 ms) e `callback(err, response)`) e risponde con la risposta di quel server.\n\nExample: Esempio\n```js\nROUTE('GET /api/weather/', function($) {\n\t$.proxy('https://weather.example.com/today/');\n});\n```\n\n### $.fallback(code, [error])\n\nType: `method`\n\nInvia una pagina di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Il codice di stato HTTP. |\n| `error` | `String|Error` | no |  | L'errore per la modalità debug. |\n\nQuando esiste una route `#code` (per esempio `ROUTE('#404', fn)`), la sua azione gestisce la richiesta; lo stato resta `200` a meno che l'azione non imposti `$.response.status`. Altrimenti invia la pagina di errore integrata con lo stato `code`, oppure `$.invalid(code)` per le richieste XHR. `error` viene mostrato nella pagina in modalità debug.\n\nExample: Esempio\n```js\nexports.install = function() {\n\tROUTE('GET /secret/', function($) {\n\t\t$.fallback(404);\n\t});\n\tROUTE('#404', function($) {\n\t\t$.view('404');\n\t});\n};\n```\n\n### $.callback([err], [value])\n\nType: `method`\n\nRisponde da una callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | no |  | Un errore. |\n| `value` | `Object` | no |  | Il valore da inviare. |\n\nReturns: `Function` Una callback quando viene chiamato senza argomenti.\n\nSenza argomenti restituisce una funzione `(err, response)` che chiama `$.invalid(err)` o `$.json(response)`. Con argomenti risponde subito: `$.invalid(err)`, `$.success()` quando `value` è `undefined`, oppure `$.json(value)`.\n\nExample: Esempio\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.callback());\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nRestituisce una callback che risponde con successo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | Il valore, oppure `true` per la risposta della callback. |\n\nReturns: `Function` Una callback.\n\nLa funzione restituita `(err, response)` chiama `$.invalid(err)` in caso di errore, altrimenti invia `{ success: true, value: value }`. Passa `true` per usare la `response` della callback come valore.\n\nExample: Esempio\n```js\nROUTE('POST /api/products/', function($) {\n\tNOSQL('products').insert($.body).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` | yes |  | Chiamata quando non c'è errore. |\n\nReturns: `Function` Una callback.\n\nLa funzione restituita `(err, a, b, c)` chiama `$.invalid(err)` in caso di errore, altrimenti `callback(a, b, c)` con il controller come `this`.\n\nExample: Esempio\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.successful(function(response) {\n\t\t$.json(response);\n\t}));\n});\n```\n\n### $.custom()\n\nType: `method`\n\nIndica al framework che invii tu la risposta.\n\nSegna il controller come terminato, così nessun metodo di risposta ci scrive. Poi scrivi su `$.res` con l'API di Node.js.\n\nExample: Esempio\n```js\nROUTE('GET /events/', function($) {\n\t$.custom();\n\t$.res.writeHead(200, { 'content-type': 'text/event-stream' });\n\t$.res.write('data: hello\\n\\n');\n});\n```\n\n### $.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLegge o imposta un cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del cookie. |\n| `value` | `String` | no |  | Il valore da impostare. |\n| `expires` | `Date|String|Object` | no |  | La scadenza, oppure le opzioni. |\n| `options` | `Object` | no |  | Le opzioni del cookie. |\n\nReturns: `String|Controller` Il valore in lettura, il controller in scrittura.\n\nCon il solo `name` restituisce il valore decodificato del cookie, oppure una stringa vuota. Con `value` aggiunge un header `Set-Cookie` (un cookie con lo stesso nome impostato prima nella richiesta viene sostituito) e restituisce il controller. `expires` è un `Date`, una stringa come `'7 days'`, oppure l'oggetto delle opzioni. Le opzioni sono `expires`, `domain`, `path` (predefinito `/`), `secure` (predefinito da `$cookiesecure`), `httponly` e `samesite` (predefinito da `$cookiesamesite`, `'Lax'`).\n\nExample: Esempio\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' });\n\t$.success();\n}\n\nfunction profile($) {\n\t$.json({ session: $.cookie('session') });\n}\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nImposta gli header di cache HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | La data dell'ultima modifica. |\n\nImposta `Last-Modified` a `date`, `ETag`, e `Expires` e `Cache-Control` quando non sono ancora impostati.\n\nExample: Esempio\n```js\nfunction article($) {\n\tvar updated = new Date(2025, 0, 1);\n\tif ($.notmodified(updated.toUTCString()))\n\t\treturn;\n\t$.httpcache(updated);\n\t$.view('article');\n}\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nRisponde 304 quando il client ha la stessa versione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | La data dell'ultima modifica come stringa UTC. |\n\nReturns: `Boolean` `true` quando la risposta 304 è stata inviata.\n\nConfronta `date` (una stringa UTC) con l'header `If-Modified-Since`. Quando sono uguali invia `304 Not Modified` e restituisce `true`.\n\n### $.hostname([path])\n\nType: `method`\n\nRestituisce il protocollo e l'host.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un percorso da aggiungere. |\n\nReturns: `String` L'URL.\n\nDà `protocol://host` della richiesta con un percorso opzionale aggiunto in coda.\n\nExample: Esempio\n```js\nfunction share($) {\n\t$.json({ url: $.hostname('/products/' + $.params.id + '/') });\n}\n```\n\n### $.href([key], [value])\n\nType: `method`\n\nRestituisce la query string con un parametro modificato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | Il nome del parametro, o un oggetto con i parametri da impostare. |\n| `value` | `String|Number|Array|Object` | no |  | Il nuovo valore. |\n\nReturns: `String` La query string con `?`, o una stringa vuota.\n\nSenza argomenti restituisce la query string della richiesta (`?page=2&sort=name`), oppure una stringa vuota. `$.href(key, value)` la restituisce con `key` impostato a `value`; gli altri parametri restano. Senza `value` viene mantenuto il valore attuale di `key`. Altri argomenti dopo `value` sono nomi di parametri da rimuovere. Un valore array scrive il parametro una volta per ogni elemento e un valore oggetto viene scritto come JSON. `$.href({ key: value, ... })` restituisce l'URL della richiesta con la query string modificata dalle chiavi dell'oggetto. Funziona come `@{href()}` nelle viste.\n\nExample: Paginazione\n```js\n// GET /products/?page=2&sort=name\nfunction products($) {\n\t$.json({\n\t\tnext: $.href('page', 3),           // ?page=3&sort=name\n\t\tcurrent: $.href()                  // ?page=2&sort=name\n\t});\n}\n```\n\nExample: Rimuovere un parametro o modificarne diversi\n```js\n// GET /products/?page=2&sort=name&q=pen\n$.href('page', 1, 'sort');           // ?page=1&q=pen\n$.href({ page: 1, sort: 'price' });  // /products/?page=1&sort=price&q=pen\n```\n\n### $.touch([url])\n\nType: `method`\n\nCancella lo stato in cache di un file statico.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | L'URL del file. |\n\nReturns: `Controller` Lo stesso controller.\n\nChiama `TOUCH(url)`; senza `url` usa l'URL della richiesta. Usalo dopo che la route ha modificato un file in `public/`. Restituisce `$`.\n\nExample: Esempio\n```js\nROUTE('POST /api/theme/', function($) {\n\tF.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) {\n\t\tif (err) {\n\t\t\t$.invalidsafe('The theme can\\'t be saved', err);\n\t\t\treturn;\n\t\t}\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t});\n});\n```\n\n### $.action(name, model)\n\nType: `method`\n\nEsegue un'azione con questo controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'azione, ad esempio `Products/list`. |\n| `model` | `Object` | yes |  | I dati per l'azione. |\n\nReturns: `Object` L'istanza dell'azione.\n\nChiama l'azione `name` (vedi [Azioni](../../guides/actions/)) con `model` e il controller. Chiama `.autorespond()` sul risultato per rispondere alla richiesta con l'output dell'azione.\n\nExample: Esempio\n```js\nROUTE('POST /api/orders/', function($) {\n\t$.action('Orders/create', $.body).autorespond();\n});\n```\n\n### $.authorize([callback])\n\nType: `method`\n\nEsegue manualmente il delegate di autorizzazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Riceve `(err, user)`. |\n\nReturns: `Promise` Quando viene chiamato senza callback.\n\nChiama il tuo delegate di autorizzazione per questa richiesta. Quando restituisce un utente, `$.user` viene impostato. La callback è `(err, user)`; senza callback il metodo restituisce una `Promise` con l'utente (oppure `undefined`).\n\nExample: Esempio\n```js\nROUTE('GET /api/me/', async function($) {\n\tvar user = await $.authorize();\n\t$.json({ signed: !!user });\n});\n```\n\n### $.csrf()\n\nType: `method`\n\nCrea un token CSRF.\n\nReturns: `String` Il token.\n\nRestituisce un token legato all'indirizzo IP e al browser del client, valido per il tempo indicato in `$csrfexpiration` (predefinito `30 minutes`). Richiede la chiave di configurazione `secret_csrf`; senza di essa il token è una stringa vuota.\n\nExample: Esempio\n```js\nROUTE('GET /form/', function($) {\n\t$.view('form', { token: $.csrf() });\n});\n```\n\n### $.autoclear([value])\n\nType: `method`\n\nMantiene o rimuove i file caricati dopo la risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no |  | `false` mantiene i file. |\n\nI file caricati vengono rimossi quando la risposta termina. `$.autoclear(false)` li mantiene, per esempio quando li elabori più tardi.\n\n### $.cancel()\n\nType: `method`\n\nInterrompe l'elaborazione della richiesta in un evento.\n\nChiamalo in `ON('request', fn)` o `ON('controller', fn)` quando l'handler risponde da sé alla richiesta.\n\nExample: Esempio\n```js\nON('request', function($) {\n\tif ($.url === '/health/') {\n\t\t$.cancel();\n\t\t$.plain('OK');\n\t}\n});\n```\n\n### HttpFile\n\nType: `class`\n\nUn file caricato in `$.files`.\n\nProprietà: `name` (il campo del form), `filename`, `type` (il content type), `size` (byte), `extension`, `width` e `height` (immagini), `path` (il file temporaneo), e `isImage`, `isVideo`, `isAudio`.\n\nMetodi:\n\n- `move(filename, [callback])` (anche `rename()`) sposta il file; senza callback restituisce una `Promise`. Un file spostato non viene rimosso dopo la risposta.\n- `copy(filename, callback)` copia il file.\n- `read([callback])` legge il file in un `Buffer`; senza callback restituisce una `Promise`.\n- `md5([callback])` calcola l'hash MD5 in esadecimale; senza callback restituisce una `Promise`.\n- `stream([opt])` restituisce uno stream di lettura; `pipe(stream, [opt])` invia il file in uno stream tramite pipe.\n- `image([shell])` restituisce un oggetto immagine per [Immagini](../../guides/images/).\n- `fs(storage, id, [callback])` salva il file in un [file storage](../../guides/file-storage/).\n\nExample: Salvare in un file storage\n```js\nROUTE('POST /upload/ <10MB', function($) {\n\tvar file = $.files[0];\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n});\n```\n","entries":[{"type":"property","name":"$.req","signature":"$.req","since":"","deprecated":false},{"type":"property","name":"$.res","signature":"$.res","since":"","deprecated":false},{"type":"property","name":"$.method","signature":"$.method","since":"","deprecated":false},{"type":"property","name":"$.url","signature":"$.url","since":"","deprecated":false},{"type":"property","name":"$.uri","signature":"$.uri","since":"","deprecated":false},{"type":"property","name":"$.split","signature":"$.split","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.body","signature":"$.body","since":"","deprecated":false},{"type":"property","name":"$.payload","signature":"$.payload","since":"","deprecated":false},{"type":"property","name":"$.files","signature":"$.files","since":"","deprecated":false},{"type":"property","name":"$.headers","signature":"$.headers","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"property","name":"$.ua","signature":"$.ua","since":"","deprecated":false},{"type":"property","name":"$.mobile","signature":"$.mobile","since":"","deprecated":false},{"type":"property","name":"$.robot","signature":"$.robot","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"","deprecated":false},{"type":"property","name":"$.protocol","signature":"$.protocol","since":"","deprecated":false},{"type":"property","name":"$.address","signature":"$.address","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"method","name":"$.json()","signature":"$.json(value, [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"$.jsonstring()","signature":"$.jsonstring(value)","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"$.html()","signature":"$.html(value)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.plain()","signature":"$.plain(value)","since":"","deprecated":false},{"type":"method","name":"$.xml()","signature":"$.xml(value)","since":"","deprecated":false},{"type":"method","name":"$.empty()","signature":"$.empty()","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"$.view()","signature":"$.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"$.layout()","signature":"$.layout(name)","since":"","deprecated":false},{"type":"method","name":"$.file()","signature":"$.file(path, [download])","since":"","deprecated":false},{"type":"method","name":"$.stream()","signature":"$.stream(type, stream, [download])","since":"","deprecated":false},{"type":"method","name":"$.binary()","signature":"$.binary(buffer, type, [download])","since":"","deprecated":false},{"type":"method","name":"$.content()","signature":"$.content(value, [type])","since":"","deprecated":false},{"type":"method","name":"$.image()","signature":"$.image(opt)","since":"","deprecated":false},{"type":"method","name":"$.filefs()","signature":"$.filefs(name, id, [download], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"$.proxy()","signature":"$.proxy(opt)","since":"","deprecated":false},{"type":"method","name":"$.fallback()","signature":"$.fallback(code, [error])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([err], [value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.custom()","signature":"$.custom()","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"$.httpcache()","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"$.notmodified()","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"$.hostname()","signature":"$.hostname([path])","since":"","deprecated":false},{"type":"method","name":"$.href()","signature":"$.href([key], [value])","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, model)","since":"","deprecated":false},{"type":"method","name":"$.authorize()","signature":"$.authorize([callback])","since":"","deprecated":false},{"type":"method","name":"$.csrf()","signature":"$.csrf()","since":"","deprecated":false},{"type":"method","name":"$.autoclear()","signature":"$.autoclear([value])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"class","name":"HttpFile","signature":"HttpFile","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwV6CWx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/controller/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Kontrolér","summary":"Vlastnosti a metódy kontroléra `$`, ktorý dostane každá akcia trasy.","markdown":"---\ntitle: \"Kontrolér\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/controller/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Kontrolér\n\n> Vlastnosti a metódy kontroléra `$`, ktorý dostane každá akcia trasy.\n\nKontrolér je argument `$` každej akcie trasy. Obsahuje údaje požiadavky (`$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.user`...) a metódy, ktoré odosielajú odpoveď (`$.json()`, `$.success()`, `$.invalid()`, `$.view()`, `$.file()`, `$.redirect()`...). Podrobný prehľad s príkladmi nájdeš v návode [Kontrolér](../../guides/controller/).\n\n## API\n\n### $.req\n\nType: `property`\n\nObjekt požiadavky Node.js.\n\nReturns: `IncomingMessage`\n\n`http.IncomingMessage` požiadavky. Použi ho len na to, čo kontrolér neponúka.\n\n### $.res\n\nType: `property`\n\nObjekt odpovede Node.js.\n\nReturns: `ServerResponse`\n\n`http.ServerResponse` požiadavky. Keď doň zapisuješ sám, najprv zavolaj `$.custom()`, aby na požiadavku neodpovedal aj framework.\n\n### $.method\n\nType: `property`\n\nHTTP metóda požiadavky.\n\nReturns: `String`\n\nReťazec veľkými písmenami, napríklad `GET`, `POST`, `PUT`, `PATCH` alebo `DELETE`.\n\nExample: Príklad\n```js\nROUTE('POST /api/items/', function($) {\n\t// $.method === 'POST'\n\t$.success();\n});\n```\n\n### $.url\n\nType: `property`\n\nCesta URL.\n\nReturns: `String`\n\nCesta bez query stringu. Cesta bez prípony súboru vždy končí `/` a dvojité lomky sa zlúčia. Písmená si zachovajú veľkosť.\n\nExample: Príklad\n```js\nROUTE('GET /docs/', function($) {\n\t// /docs?page=1 gives '/docs/'\n\t$.plain($.url);\n});\n```\n\n### $.uri\n\nType: `property`\n\nSpracovaná URL.\n\nReturns: `Object`\n\nObjekt s `pathname` (rovnaké ako `$.url`), `search` (query string bez `?`), `split` (segmenty), `ext` (prípona súboru) a `file` (`true` pri požiadavke na statický súbor).\n\n### $.split\n\nType: `property`\n\nSegmenty cesty.\n\nReturns: `String[]`\n\nPole častí cesty: `/blog/2025/hello/` dáva `['blog', '2025', 'hello']`. Koreňová cesta `/` dáva prázdne pole.\n\nExample: Príklad\n```js\nROUTE('GET /blog/*', function($) {\n\t$.json($.split);\n});\n```\n\n### $.params\n\nType: `property`\n\nDynamické časti URL.\n\nReturns: `Object`\n\nKaždé `{name}` trasy sa stane kľúčom s príslušným segmentom cesty ako reťazcom. Čísla a dátumy si preveď sám.\n\nExample: Príklad\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id}/', order);\n};\n\nfunction order($) {\n\tvar id = $.params.id;\n\t$.json({ id: id });\n}\n```\n\n### $.query\n\nType: `property`\n\nQuery string ako objekt.\n\nReturns: `Object`\n\nHodnoty sú reťazce: `?page=2&q=shoes` dáva `{ page: '2', q: 'shoes' }`. Môžeš priradiť nový objekt. V API trase obsahuje query z poľa `schema`.\n\nExample: Stránkovanie\n```js\nfunction list($) {\n\tvar page = ($.query.page || '1').parseInt();\n\t$.json({ page: page });\n}\n```\n\n### $.body\n\nType: `property`\n\nSpracované telo požiadavky.\n\nReturns: `Object`\n\nPre požiadavky `POST`, `PUT`, `PATCH` a `DELETE`. JSON telo sa spracuje na objekt, URL-encoded formulár na objekt reťazcov a požiadavka `multipart/form-data` dá polia formulára. Pri iných typoch obsahu zostane `{}` a surové dáta sú v `$.payload`. V API trase obsahuje `data` požiadavky.\n\nExample: Čítanie tela\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact($) {\n\tvar email = $.body.email;\n\t$.success();\n}\n```\n\n### $.payload\n\nType: `property`\n\nSurové telo ako Buffer.\n\nReturns: `Buffer`\n\nBajty tela pre každý typ obsahu okrem `multipart/form-data`. Použi ho pre XML, čistý text alebo binárne nahrávanie. Uvoľní sa po skončení odpovede.\n\nExample: Príklad\n```js\nROUTE('POST /api/xml/', function($) {\n\tvar xml = $.payload.toString('utf8');\n\t$.plain('Received ' + xml.length + ' chars');\n});\n```\n\n### $.files\n\nType: `property`\n\nNahrané súbory.\n\nReturns: `HttpFile[]`\n\nPole súborov (`HttpFile`) z požiadavky `multipart/form-data`, pri iných požiadavkách prázdne. Súbory sú dočasné a odstránia sa po skončení odpovede, ak ich nepresunieš alebo nezavoláš `$.autoclear(false)`.\n\nExample: Príklad\n```js\nfunction upload($) {\n\tvar names = [];\n\tfor (var file of $.files)\n\t\tnames.push(file.filename + ' (' + file.size + ' bytes)');\n\t$.json(names);\n}\n```\n\n### $.headers\n\nType: `property`\n\nHlavičky požiadavky.\n\nReturns: `Object`\n\nObjekt hlavičiek z Node.js: názvy sú malými písmenami.\n\nExample: Príklad\n```js\nfunction info($) {\n\t$.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] });\n}\n```\n\n### $.ip\n\nType: `property`\n\nIP adresa klienta.\n\nReturns: `String`\n\nPrvá adresa z `X-Forwarded-For`, keď hlavička existuje (za proxy), inak vzdialená adresa spojenia.\n\nExample: Príklad\n```js\nfunction track($) {\n\tconsole.log('Request from', $.ip);\n\t$.success();\n}\n```\n\n### $.ua\n\nType: `property`\n\nKrátky názov klienta z hlavičky User-Agent.\n\nReturns: `String`\n\nSystém a prehliadač nájdený v `User-Agent`, napríklad `Mac OS Chrome`, alebo prázdny reťazec bez tejto hlavičky.\n\n### $.mobile\n\nType: `property`\n\n`true` pre mobilné zariadenie.\n\nReturns: `Boolean`\n\n`true`, keď `User-Agent` zodpovedá telefónu alebo tabletu (Android, iPhone, iPad, Mobile, Tablet...).\n\n### $.robot\n\nType: `property`\n\n`true` pre crawler.\n\nReturns: `Boolean`\n\n`true`, keď `User-Agent` obsahuje `search`, `agent`, `bot`, `crawler` alebo `spider`.\n\n### $.xhr\n\nType: `property`\n\n`true` pre XMLHttpRequest.\n\nReturns: `Boolean`\n\n`true`, keď má požiadavka hlavičku `X-Requested-With: XMLHttpRequest`. `$.fallback()` odpovedá na takéto požiadavky pomocou JSON namiesto HTML stránky.\n\n### $.protocol\n\nType: `property`\n\nProtokol požiadavky.\n\nReturns: `String`\n\n`https` pri šifrovanom spojení alebo keď to hlási proxy (`X-Forwarded-Proto: https`, `X-Forwarded-SSL: on` alebo `X-Forwarded-Port: 443`), inak `http`.\n\n### $.address\n\nType: `property`\n\nÚplná URL požiadavky.\n\nReturns: `String`\n\nProtokol, host a pôvodná URL s query stringom, napríklad `https://example.com/products/?page=2`.\n\n### $.user\n\nType: `property`\n\nPrihlásený používateľ.\n\nReturns: `Object`\n\nObjekt, ktorý pre požiadavku vrátil tvoj autorizačný delegát, alebo `undefined`, keď nie je nikto prihlásený. Pozri [Autorizácia](../../guides/authorization/).\n\nExample: Príklad\n```js\nROUTE('+GET /api/account/', function($) {\n\t$.json({ name: $.user.name });\n});\n```\n\n### $.language\n\nType: `property`\n\nJazyk požiadavky.\n\nReturns: `String`\n\nHodnota, ktorú vrátil tvoj lokalizačný delegát, alebo prázdny reťazec. Vyberá preklad pohľadov a chybových hlásení. Pozri [Lokalizácia](../../guides/localization/).\n\n### $.response\n\nType: `property`\n\nOdpoveď, ktorá sa odošle.\n\nReturns: `Object`\n\nObjekt so `status` (predvolene `200`), `headers` (objekt hlavičiek odpovede), `cache` (HTTP cache pre súbory) a `minify`. Zmeň ho predtým, ako zavoláš metódu odpovede.\n\nExample: Stav a hlavička\n```js\nfunction create($) {\n\t$.response.status = 201;\n\t$.response.headers['x-version'] = '1';\n\t$.json({ id: UID() });\n}\n```\n\n### $.json(value, [beautify], [replacer])\n\nType: `method`\n\nOdošle JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota na serializáciu. |\n| `beautify` | `Boolean` | no | `false` | `true` odsadí JSON tabulátormi. |\n| `replacer` | `Function|Array` | no |  | Replacer pre `JSON.stringify()`. |\n\nSerializuje `value` cez `JSON.stringify()`, nastaví `content-type: application/json` a hlavičky, ktoré vypínajú cache (`cache-control: private, no-cache, no-store, max-age=0`, `expires: -1`). `beautify` odsadí výstup tabulátormi. `replacer` sa odovzdá do `JSON.stringify()` ako jeho druhý argument: funkcia `(key, value)` alebo pole kľúčov, ktoré sa majú ponechať.\n\nExample: Príklad\n```js\nROUTE('GET /api/products/', function($) {\n\t$.json([{ id: 1, name: 'Shoes' }]);\n});\n```\n\nExample: Formátovanie a skrytie kľúča\n```js\nROUTE('GET /api/debug/', function($) {\n\t$.json({ id: 1, password: 'secret' }, true, function(key, value) {\n\t\treturn key === 'password' ? undefined : value;\n\t});\n});\n```\n\n### $.jsonstring(value)\n\nType: `method`\n\nOdošle reťazec, ktorý už je JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | JSON reťazec. |\n\nOdošle reťazec tak, ako je, s rovnakými hlavičkami ako `$.json()`. Použi ho pre JSON, ktorý máš v cache alebo si ho prečítal zo súboru.\n\nExample: Príklad\n```js\nfunction cached($) {\n\t$.jsonstring('{\"ok\":true}');\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nOdošle `{ success: true, value: value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Voliteľná hodnota pre kľúč `value`. |\n\nSkratka pre bežnú odpoveď API. Bez `value` je odpoveď `{\"success\":true}`.\n\nExample: Príklad\n```js\nfunction remove($) {\n\tNOSQL('products').remove().id($.params.id);\n\t$.success($.params.id);\n}\n```\n\n### $.invalid(error)\n\nType: `method`\n\nOdošle chybu ako JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Error|ErrorBuilder|Number` | yes |  | Chyba. |\n\nPrijíma reťazec, `Error`, `ErrorBuilder` alebo HTTP stavový kód. Odpoveď je JSON pole, napríklad `[{\"error\":\"Name is required\"}]` so stavom `400`, alebo s daným stavovým kódom (`$.invalid(404)` dáva `[{\"error\":\"404: Not Found\"}]` so stavom `404`). Text zapísaný ako `@(text)` sa preloží zo zdroja. Bez argumentu odošle `401`. Odpoveď sa odošle asynchrónne.\n\nExample: Príklad\n```js\nfunction save($) {\n\tif (!$.body.email) {\n\t\t$.invalid('@(Email is required)');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nPošle chybovú správu a zaloguje skutočnú chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number|ErrorBuilder` | yes |  | Chyba pre klienta. |\n| `error` | `Error|String` | no |  | Chyba pre log. |\n\nPošle `message` tak, ako to robí `$.invalid(message)`, a zapíše `error` do chybového logu cez `F.error()` spolu s URL požiadavky. Klient dostane iba správu. `message` môže byť aj `ErrorBuilder`.\n\nExample: Príklad\n```js\nfunction report($) {\n\tF.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {\n\t\tif (err)\n\t\t\t$.invalidsafe('The report is not available', err);\n\t\telse\n\t\t\t$.content(buffer, 'text/csv');\n\t});\n}\n```\n\n### $.html(value)\n\nType: `method`\n\nOdošle HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML. |\n\nNastaví `content-type: text/html` a odošle reťazec. Minifikuje sa, keď je konfiguračný kľúč `$minifyhtml` `true` (predvolene).\n\nExample: Príklad\n```js\nROUTE('GET /hello/', function($) {\n\t$.html('<h1>Hello</h1>');\n});\n```\n\n### $.throw(error)\n\nType: `method`\n\nZapíše chybu do logu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | Chyba. |\n\nReturns: `Controller` Ten istý controller.\n\nOdovzdá `error` s URL požiadavky chybovému handleru frameworku (`DEF.onError`): vypíše sa, uloží sa v `F.errors` a vyšle sa ako udalosť `error`. Klientovi sa nič nepošle. Vráti `$`.\n\nExample: Príklad\n```js\nfunction save($) {\n\tNOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) {\n\t\terr && $.throw(err);\n\t});\n\t$.success();\n}\n```\n\n### $.plain(value)\n\nType: `method`\n\nOdošle čistý text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Text. |\n\nNastaví `content-type: text/plain`. `$.text()` je tá istá metóda.\n\nExample: Príklad\n```js\nROUTE('FILE /robots.txt', function($) {\n\t$.plain('User-agent: *');\n});\n```\n\n### $.xml(value)\n\nType: `method`\n\nOdošle XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | XML. |\n\nNastaví `content-type: text/xml` a odošle reťazec.\n\nExample: Príklad\n```js\nfunction feed($) {\n\t$.xml('<?xml version=\"1.0\"?><rss></rss>');\n}\n```\n\n### $.empty()\n\nType: `method`\n\nOdošle stav 204 bez tela.\n\nPouži ho, keď požiadavka nepotrebuje v odpovedi žiadne dáta.\n\nExample: Príklad\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.empty();\n});\n```\n\n### $.redirect(url, [permanent])\n\nType: `method`\n\nPresmeruje klienta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Cieľová URL. |\n| `permanent` | `Boolean` | no | `false` | `true` pre trvalé presmerovanie (301). |\n\nNastaví hlavičku `Location` a stav `302`, alebo `301`, keď je `permanent` `true`.\n\nExample: Príklad\n```js\nROUTE('GET /old/', function($) {\n\t$.redirect('/new/', true);\n});\n```\n\n### $.view([name], [model])\n\nType: `method`\n\nVyrenderuje pohľad a odošle ho ako HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Názov pohľadu bez prípony. |\n| `model` | `Object` | no |  | Model pre pohľad. |\n\nReturns: `View` Inštancia pohľadu.\n\nVyrenderuje pohľad `name` z adresára `/views/` s `model` a odošle ho pomocou `$.html()`. S layoutom z `$.layout()`. Bez `name` len vráti novú inštanciu `View` pre kontrolér. Pozri [Pohľady](../../guides/views/).\n\nExample: Príklad\n```js\nfunction detail($) {\n\tNOSQL('products').one().id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.view('detail', response);\n\t\telse\n\t\t\t$.fallback(404);\n\t});\n}\n```\n\n### $.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 pohľadu layoutu. |\n\nPohľad vyrenderovaný pomocou `$.view()` sa vloží do layoutu `name`.\n\nExample: Príklad\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('dashboard');\n}\n```\n\n### $.file(path, [download])\n\nType: `method`\n\nOdošle súbor z disku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Absolútna cesta k súboru. |\n| `download` | `Boolean|String` | no |  | Názov súboru pre stiahnutie, alebo `true`. |\n\nNastaví typ obsahu podľa prípony a podporuje požiadavky `Range`, gzip a hlavičky HTTP cache. Súbory JS, CSS a HTML sa minifikujú, ak ich názov neobsahuje `.min`, `-min` alebo `@min`. S `download` prehliadač súbor uloží: odovzdaj `true` na zachovanie jeho názvu alebo reťazec na premenovanie. Chýbajúci súbor dáva `404`.\n\nExample: Príklad\n```js\nROUTE('GET /download/', function($) {\n\t$.file(PATH.root('reports/2025.pdf'), 'report.pdf');\n});\n```\n\n### $.stream(type, stream, [download])\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` | `ReadableStream` | yes |  | Stream. |\n| `download` | `String` | no |  | Názov súboru pre stiahnutie. |\n\nPresmeruje `stream` do odpovede s typom obsahu `type` (predvolene `application/octet-stream`). Textové typy sa komprimujú pomocou gzip, keď to klient podporuje. Reťazec `download` odošle stream ako prílohu s týmto názvom.\n\nExample: Príklad\n```js\nfunction exportcsv($) {\n\tvar stream = F.Fs.createReadStream(PATH.root('export.csv'));\n\t$.stream('text/csv', stream, 'export.csv');\n}\n```\n\n### $.binary(buffer, type, [download])\n\nType: `method`\n\nOdošle Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Dáta. |\n| `type` | `String` | yes |  | Typ obsahu. |\n| `download` | `String` | no |  | Názov súboru pre stiahnutie. |\n\nOdošle bajty s typom obsahu `type`. Reťazec `download` ich odošle ako prílohu s týmto názvom.\n\nExample: Príklad\n```js\nfunction pixel($) {\n\tvar buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');\n\t$.binary(buffer, 'image/gif');\n}\n```\n\n### $.content(value, [type])\n\nType: `method`\n\nPošle reťazec alebo Buffer s typom obsahu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Obsah. |\n| `type` | `String` | no | `'application/octet-stream'` | Typ obsahu. |\n\nPošle `value` s hlavičkou `content-type: type`; bez `type` je to `application/octet-stream`. Reťazec sa pošle ako UTF-8. Na rozdiel od `$.binary()` prijíma aj reťazec a nemá názov na stiahnutie.\n\nExample: CSV\n```js\nROUTE('GET /export/', function($) {\n\t$.content('id,name\\n1,Mug\\n', 'text/csv');\n});\n```\n\n### $.image(opt)\n\nType: `method`\n\nSpracuje obrázok a odošle ho.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Voľby. |\n\nNačíta stream obrázka, umožní ti ho zmeniť a odošle výsledok. `opt.ext` (povinné) je prípona výstupu, `opt.load(next, opt)` zavolá `next(stream)` so zdrojom, `opt.image(img, opt)` mení obrázok (pozri [Obrázky](../../guides/images/)), `opt.cache` je kľúč na uchovanie výsledku v dočasnom adresári a `opt.date` dátum pre HTTP cache.\n\nExample: Príklad\n```js\nfunction thumbnail($) {\n\t$.image({\n\t\text: 'jpg',\n\t\tcache: 'thumb_' + $.params.id,\n\t\tload: function(next) {\n\t\t\tnext(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg')));\n\t\t},\n\t\timage: function(img) {\n\t\t\timg.resize(200, 200);\n\t\t}\n\t});\n}\n```\n\n### $.filefs(name, id, [download], [checkmeta])\n\nType: `method`\n\nOdošle súbor z úložiska súborov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov úložiska súborov. |\n| `id` | `String` | yes |  | Identifikátor súboru. |\n| `download` | `Boolean|String` | no |  | Odoslať ako prílohu. |\n| `checkmeta` | `Function` | no |  | Kontrola metadát. |\n\nReturns: `Object` Voľby odovzdané úložisku.\n\nOdošle súbor `id` z úložiska súborov `name` (pozri [Úložisko súborov](../../guides/file-storage/)). `download` ho odošle ako prílohu, `true` s jeho uloženým názvom alebo reťazec pre iný názov. `checkmeta` je funkcia, ktorá dostane metadáta súboru a rozhodne, či ho možno odoslať.\n\nExample: Príklad\n```js\nROUTE('GET /files/{id}/', function($) {\n\t$.filefs('files', $.params.id);\n});\n```\n\n### $.proxy(opt)\n\nType: `method`\n\nPrepošle požiadavku na iný server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `String|Object` | yes |  | Cieľová URL alebo voľby. |\n\nOdošle metódu, hlavičky, telo a query string požiadavky na `opt` (URL alebo objekt s `url`, `method`, `headers`, `timeout` (predvolene 10000 ms) a `callback(err, response)`) a odpovie odpoveďou daného servera.\n\nExample: Príklad\n```js\nROUTE('GET /api/weather/', function($) {\n\t$.proxy('https://weather.example.com/today/');\n});\n```\n\n### $.fallback(code, [error])\n\nType: `method`\n\nOdošle chybovú stránku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | HTTP stavový kód. |\n| `error` | `String|Error` | no |  | Chyba pre režim debug. |\n\nKeď existuje trasa `#code` (napríklad `ROUTE('#404', fn)`), požiadavku spracuje jej akcia; stav zostane `200`, pokiaľ akcia nenastaví `$.response.status`. Inak odošle vstavanú chybovú stránku so stavom `code`, alebo `$.invalid(code)` pri XHR požiadavkách. `error` sa zobrazí na stránke v režime debug.\n\nExample: Príklad\n```js\nexports.install = function() {\n\tROUTE('GET /secret/', function($) {\n\t\t$.fallback(404);\n\t});\n\tROUTE('#404', function($) {\n\t\t$.view('404');\n\t});\n};\n```\n\n### $.callback([err], [value])\n\nType: `method`\n\nOdpovie z callbacku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | no |  | Chyba. |\n| `value` | `Object` | no |  | Hodnota na odoslanie. |\n\nReturns: `Function` Callback, keď sa volá bez argumentov.\n\nBez argumentov vráti funkciu `(err, response)`, ktorá zavolá `$.invalid(err)` alebo `$.json(response)`. S argumentmi odpovie hneď: `$.invalid(err)`, `$.success()`, keď je `value` `undefined`, alebo `$.json(value)`.\n\nExample: Príklad\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.callback());\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nVráti callback, ktorý odpovie úspechom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | Hodnota, alebo `true` pre odpoveď callbacku. |\n\nReturns: `Function` Callback.\n\nVrátená funkcia `(err, response)` pri chybe zavolá `$.invalid(err)`, inak odošle `{ success: true, value: value }`. Odovzdaj `true`, ak chceš ako hodnotu použiť `response` z callbacku.\n\nExample: Príklad\n```js\nROUTE('POST /api/products/', function($) {\n\tNOSQL('products').insert($.body).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` | yes |  | Zavolá sa, keď nenastane chyba. |\n\nReturns: `Function` Callback.\n\nVrátená funkcia `(err, a, b, c)` pri chybe zavolá `$.invalid(err)`, inak `callback(a, b, c)` s kontrolérom ako `this`.\n\nExample: Príklad\n```js\nROUTE('GET /api/products/', function($) {\n\tNOSQL('products').find().callback($.successful(function(response) {\n\t\t$.json(response);\n\t}));\n});\n```\n\n### $.custom()\n\nType: `method`\n\nOznámi frameworku, že odpoveď odosielaš sám.\n\nOznačí kontrolér ako dokončený, aby doň žiadna metóda odpovede nezapisovala. Potom zapisuj do `$.res` pomocou API Node.js.\n\nExample: Príklad\n```js\nROUTE('GET /events/', function($) {\n\t$.custom();\n\t$.res.writeHead(200, { 'content-type': 'text/event-stream' });\n\t$.res.write('data: hello\\n\\n');\n});\n```\n\n### $.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nPrečíta alebo nastaví cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie. |\n| `value` | `String` | no |  | Hodnota na nastavenie. |\n| `expires` | `Date|String|Object` | no |  | Expirácia, alebo voľby. |\n| `options` | `Object` | no |  | Voľby cookie. |\n\nReturns: `String|Controller` Hodnota pri čítaní, kontrolér pri nastavovaní.\n\nLen s `name` vráti dekódovanú hodnotu cookie alebo prázdny reťazec. S `value` pridá hlavičku `Set-Cookie` (cookie s rovnakým názvom nastavená skôr v tej istej požiadavke sa nahradí) a vráti kontrolér. `expires` je `Date`, reťazec ako `'7 days'` alebo objekt volieb. Voľby sú `expires`, `domain`, `path` (predvolene `/`), `secure` (predvolene z `$cookiesecure`), `httponly` a `samesite` (predvolene z `$cookiesamesite`, `'Lax'`).\n\nExample: Príklad\n```js\nfunction login($) {\n\t$.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' });\n\t$.success();\n}\n\nfunction profile($) {\n\t$.json({ session: $.cookie('session') });\n}\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nNastaví hlavičky HTTP cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | Dátum poslednej zmeny. |\n\nNastaví `Last-Modified` na `date`, `ETag` a `Expires` a `Cache-Control`, ak ešte nie sú nastavené.\n\nExample: Príklad\n```js\nfunction article($) {\n\tvar updated = new Date(2025, 0, 1);\n\tif ($.notmodified(updated.toUTCString()))\n\t\treturn;\n\t$.httpcache(updated);\n\t$.view('article');\n}\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nOdpovie 304, keď má klient rovnakú verziu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Dátum poslednej zmeny ako UTC reťazec. |\n\nReturns: `Boolean` `true`, keď sa odoslala odpoveď 304.\n\nPorovná `date` (UTC reťazec) s hlavičkou `If-Modified-Since`. Keď sú rovnaké, odošle `304 Not Modified` a vráti `true`.\n\n### $.hostname([path])\n\nType: `method`\n\nVráti protokol a host.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Cesta na pripojenie. |\n\nReturns: `String` URL.\n\nDá `protocol://host` požiadavky s voliteľne pripojenou cestou.\n\nExample: Príklad\n```js\nfunction share($) {\n\t$.json({ url: $.hostname('/products/' + $.params.id + '/') });\n}\n```\n\n### $.href([key], [value])\n\nType: `method`\n\nVráti query string s jedným zmeneným parametrom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | Názov parametra alebo objekt s parametrami, ktoré sa majú nastaviť. |\n| `value` | `String|Number|Array|Object` | no |  | Nová hodnota. |\n\nReturns: `String` Query string s `?` alebo prázdny reťazec.\n\nBez argumentov vráti query string požiadavky (`?page=2&sort=name`) alebo prázdny reťazec. `$.href(key, value)` ho vráti s `key` nastaveným na `value`; ostatné parametre zostanú. Bez `value` sa ponechá aktuálna hodnota `key`. Ďalšie argumenty za `value` sú názvy parametrov, ktoré sa majú odstrániť. Hodnota typu pole zapíše parameter raz pre každú položku a hodnota typu objekt sa zapíše ako JSON. `$.href({ key: value, ... })` vráti URL požiadavky s query stringom zmeneným podľa kľúčov objektu. Funguje ako `@{href()}` vo view.\n\nExample: Stránkovanie\n```js\n// GET /products/?page=2&sort=name\nfunction products($) {\n\t$.json({\n\t\tnext: $.href('page', 3),           // ?page=3&sort=name\n\t\tcurrent: $.href()                  // ?page=2&sort=name\n\t});\n}\n```\n\nExample: Odstránenie parametra alebo zmena viacerých\n```js\n// GET /products/?page=2&sort=name&q=pen\n$.href('page', 1, 'sort');           // ?page=1&q=pen\n$.href({ page: 1, sort: 'price' });  // /products/?page=1&sort=price&q=pen\n```\n\n### $.touch([url])\n\nType: `method`\n\nVymaže uložený stav statického súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | URL súboru. |\n\nReturns: `Controller` Ten istý controller.\n\nZavolá `TOUCH(url)`; bez `url` použije URL požiadavky. Použi ho po tom, ako routa zmení súbor v `public/`. Vráti `$`.\n\nExample: Príklad\n```js\nROUTE('POST /api/theme/', function($) {\n\tF.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) {\n\t\tif (err) {\n\t\t\t$.invalidsafe('The theme can\\'t be saved', err);\n\t\t\treturn;\n\t\t}\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t});\n});\n```\n\n### $.action(name, model)\n\nType: `method`\n\nSpustí akciu s týmto kontrolérom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno akcie, napríklad `Products/list`. |\n| `model` | `Object` | yes |  | Dáta pre akciu. |\n\nReturns: `Object` Inštancia akcie.\n\nZavolá akciu `name` (pozri [Akcie](../../guides/actions/)) s `model` a kontrolérom. Zavolaj na výsledku `.autorespond()`, ak chceš na požiadavku odpovedať výstupom akcie.\n\nExample: Príklad\n```js\nROUTE('POST /api/orders/', function($) {\n\t$.action('Orders/create', $.body).autorespond();\n});\n```\n\n### $.authorize([callback])\n\nType: `method`\n\nRučne spustí autorizačný delegát.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Dostane `(err, user)`. |\n\nReturns: `Promise` Keď sa volá bez callbacku.\n\nZavolá tvoj autorizačný delegát pre túto požiadavku. Keď vráti používateľa, nastaví sa `$.user`. Callback je `(err, user)`; bez callbacku metóda vráti `Promise` s používateľom (alebo `undefined`).\n\nExample: Príklad\n```js\nROUTE('GET /api/me/', async function($) {\n\tvar user = await $.authorize();\n\t$.json({ signed: !!user });\n});\n```\n\n### $.csrf()\n\nType: `method`\n\nVytvorí CSRF token.\n\nReturns: `String` Token.\n\nVráti token viazaný na IP adresu a prehliadač klienta, platný počas času v `$csrfexpiration` (predvolene `30 minutes`). Potrebuje konfiguračný kľúč `secret_csrf`; bez neho je token prázdny reťazec.\n\nExample: Príklad\n```js\nROUTE('GET /form/', function($) {\n\t$.view('form', { token: $.csrf() });\n});\n```\n\n### $.autoclear([value])\n\nType: `method`\n\nPonechá alebo odstráni nahrané súbory po odpovedi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no |  | `false` ponechá súbory. |\n\nNahrané súbory sa odstránia po skončení odpovede. `$.autoclear(false)` ich ponechá, napríklad keď ich spracúvaš neskôr.\n\n### $.cancel()\n\nType: `method`\n\nZastaví spracovanie požiadavky v udalosti.\n\nZavolaj ju v `ON('request', fn)` alebo `ON('controller', fn)`, keď handler odpovedá na požiadavku sám.\n\nExample: Príklad\n```js\nON('request', function($) {\n\tif ($.url === '/health/') {\n\t\t$.cancel();\n\t\t$.plain('OK');\n\t}\n});\n```\n\n### HttpFile\n\nType: `class`\n\nNahraný súbor v `$.files`.\n\nVlastnosti: `name` (pole formulára), `filename`, `type` (typ obsahu), `size` (bajty), `extension`, `width` a `height` (obrázky), `path` (dočasný súbor) a `isImage`, `isVideo`, `isAudio`.\n\nMetódy:\n\n- `move(filename, [callback])` (aj `rename()`) presunie súbor; bez callbacku vráti `Promise`. Presunutý súbor sa po odpovedi neodstráni.\n- `copy(filename, callback)` skopíruje súbor.\n- `read([callback])` načíta súbor do `Buffer`; bez callbacku vráti `Promise`.\n- `md5([callback])` vypočíta MD5 hash v hex; bez callbacku vráti `Promise`.\n- `stream([opt])` vráti čitateľný stream; `pipe(stream, [opt])` presmeruje súbor do streamu.\n- `image([shell])` vráti objekt obrázka pre [Obrázky](../../guides/images/).\n- `fs(storage, id, [callback])` uloží súbor do [úložiska súborov](../../guides/file-storage/).\n\nExample: Uloženie do úložiska súborov\n```js\nROUTE('POST /upload/ <10MB', function($) {\n\tvar file = $.files[0];\n\tfile.fs('files', UID(), function(err, meta) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.success(meta.id);\n\t});\n});\n```\n","entries":[{"type":"property","name":"$.req","signature":"$.req","since":"","deprecated":false},{"type":"property","name":"$.res","signature":"$.res","since":"","deprecated":false},{"type":"property","name":"$.method","signature":"$.method","since":"","deprecated":false},{"type":"property","name":"$.url","signature":"$.url","since":"","deprecated":false},{"type":"property","name":"$.uri","signature":"$.uri","since":"","deprecated":false},{"type":"property","name":"$.split","signature":"$.split","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.body","signature":"$.body","since":"","deprecated":false},{"type":"property","name":"$.payload","signature":"$.payload","since":"","deprecated":false},{"type":"property","name":"$.files","signature":"$.files","since":"","deprecated":false},{"type":"property","name":"$.headers","signature":"$.headers","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"property","name":"$.ua","signature":"$.ua","since":"","deprecated":false},{"type":"property","name":"$.mobile","signature":"$.mobile","since":"","deprecated":false},{"type":"property","name":"$.robot","signature":"$.robot","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"","deprecated":false},{"type":"property","name":"$.protocol","signature":"$.protocol","since":"","deprecated":false},{"type":"property","name":"$.address","signature":"$.address","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"method","name":"$.json()","signature":"$.json(value, [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"$.jsonstring()","signature":"$.jsonstring(value)","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"$.html()","signature":"$.html(value)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.plain()","signature":"$.plain(value)","since":"","deprecated":false},{"type":"method","name":"$.xml()","signature":"$.xml(value)","since":"","deprecated":false},{"type":"method","name":"$.empty()","signature":"$.empty()","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"$.view()","signature":"$.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"$.layout()","signature":"$.layout(name)","since":"","deprecated":false},{"type":"method","name":"$.file()","signature":"$.file(path, [download])","since":"","deprecated":false},{"type":"method","name":"$.stream()","signature":"$.stream(type, stream, [download])","since":"","deprecated":false},{"type":"method","name":"$.binary()","signature":"$.binary(buffer, type, [download])","since":"","deprecated":false},{"type":"method","name":"$.content()","signature":"$.content(value, [type])","since":"","deprecated":false},{"type":"method","name":"$.image()","signature":"$.image(opt)","since":"","deprecated":false},{"type":"method","name":"$.filefs()","signature":"$.filefs(name, id, [download], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"$.proxy()","signature":"$.proxy(opt)","since":"","deprecated":false},{"type":"method","name":"$.fallback()","signature":"$.fallback(code, [error])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([err], [value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.custom()","signature":"$.custom()","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"$.httpcache()","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"$.notmodified()","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"$.hostname()","signature":"$.hostname([path])","since":"","deprecated":false},{"type":"method","name":"$.href()","signature":"$.href([key], [value])","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, model)","since":"","deprecated":false},{"type":"method","name":"$.authorize()","signature":"$.authorize([callback])","since":"","deprecated":false},{"type":"method","name":"$.csrf()","signature":"$.csrf()","since":"","deprecated":false},{"type":"method","name":"$.autoclear()","signature":"$.autoclear([value])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"class","name":"HttpFile","signature":"HttpFile","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwUcAPx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/actions/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Actions","summary":"NEWACTION() options, the $ object, ACTION() callers, NEWSCHEMA() and transformations.","markdown":"---\ntitle: Actions\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/actions/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Actions\n\n> NEWACTION() options, the $ object, ACTION() callers, NEWSCHEMA() and transformations.\n\nThe functions, options and objects of actions in Total.js 5: `NEWACTION()` and its options, the `$` object passed to an action, the caller returned by `ACTION()`/`EXEC()`, `NEWSCHEMA()`, and `NEWTRANSFORM()`/`TRANSFORM()`.\n\nFor an introduction with examples, read the guide [Actions](../../guides/actions/). Schemas for `input`, `output`, `params` and `query` are described in [JSON schemas](../../guides/json-schemas/).\n\n## API\n\n### NEWACTION(name, options)\n\nType: `method`\n\nDeclares an action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the action, e.g. `products_create` |\n| `options` | `Object` | yes |  | The definition: `action`, `input`, `output`, `params`, `query`, `user`, `permissions`, `route` and the other options |\n\nReturns: `Object` The definition of the action\n\nRegisters the action under `name` and returns the definition object. When `name` is an object, it is the options and the name is taken from its `id` or `name` property. An action with the same name is removed first (with its route). The returned object has `remove()`, which removes the action and its route. All registered actions are in `F.actions`.\n\nExample: A complete action\n```js\nNEWACTION('products_update', {\n\tname: 'Update a product',\n\tparams: '*id:UID',\n\tinput: '*name:String, price:Number',\n\tpermissions: 'products',\n\troute: '+PUT /api/products/{id}/',\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).error(404).callback($.done($.params.id));\n\t}\n});\n```\n\nExample: Remove an action\n```js\nvar action = NEWACTION('temp_test', { action: $ => $.success() });\naction.remove();\n```\n\n### ACTION(name, [payload], [controller])\n\nType: `method`\n\nRuns one or more actions from code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Action name, or names separated by spaces; a `+` or `-` prefix says whether the action uses the payload |\n| `payload` | `Object` | no |  | The data validated by the `input` option |\n| `controller` | `Controller` | no |  | A controller of an HTTP request |\n\nReturns: `ActionCaller` The caller with `callback()`, `promise()`, `user()` and the other methods\n\nReturns an action caller. The call starts on the next tick, so set the user, query, params and callback by chaining. `name` can contain several actions separated by spaces or commas; they run in order with the same `$`. The result is the response of the action marked ` (response)`, or an object with the responses of all actions by their names. A single action is always the response. With a controller, the user, query and params are taken from it.\n\nExample: Callback\n```js\nACTION('products_list').query({ search: 'mouse' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Several actions\n```js\nACTION('orders_create orders_notify (response)', model).user(user).callback(function(err, response) {\n\t// response is the response of orders_notify\n});\n```\n\n### EXEC(name, [payload], [controller])\n\nType: `method`\n\nAn alias of `ACTION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Action name or names |\n| `payload` | `Object` | no |  | The payload |\n| `controller` | `Controller` | no |  | A controller |\n\nReturns: `ActionCaller` The caller\n\nThe same function as `ACTION()`.\n\nExample: Promise\n```js\nvar response = await EXEC('products_create', { name: 'Mouse' }).user(user).promise();\n```\n\n### NEWSCHEMA(name, callback)\n\nType: `method`\n\nGroups actions under a common name.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the schema |\n| `callback` | `Function|String` | yes |  | `function(schema)`, or an inline schema definition |\n\nReturns: `Object` Nothing for a callback; the JSON schema for a string\n\nCalls `callback(schema)`; `schema.action(name, options)` declares the action `<schema name>/<name>` with `NEWACTION()` and returns it. The created actions are also in `schema.actions`. A leading `@` in the name is removed. When the second argument is a string, `NEWSCHEMA()` registers a JSON schema with that inline definition instead, and returns it.\n\nExample: Actions of a schema\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('read', {\n\t\tparams: '*id:UID',\n\t\taction: function($) {\n\t\t\tDATA.read('users').id($.params.id).error(404).callback($);\n\t\t}\n\t});\n\n});\n\nACTION('Users/read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\nExample: A JSON schema\n```js\nNEWSCHEMA('Address', '*street:String, *city:String, zip:Zip');\n```\n\n### NEWTRANSFORM(name, fn, [id])\n\nType: `method`\n\nAdds a function to a named transformation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the transformation |\n| `fn` | `Function` | yes |  | `function($, value)` |\n| `id` | `String` | no |  | An identifier for removing the function later |\n\nReturns: `Object` An object with `id`, `action` and `remove()`\n\nFunctions of one name run in the order they were added. Each receives `($, value)`; it changes `value` or assigns a new `$.value`, then calls `$.next()`, or stops the chain with `$.invalid(error)` (the callback of `TRANSFORM()` then receives the errors). `$.user` and `$.controller` are set when the transformation is run with a controller. Returns an object with `remove()`. `NEWTRANSFORM(name, null, id)` removes the function with that `id`.\n\nExample: Add and remove\n```js\nNEWTRANSFORM('user', function($, value) {\n\tdelete value.password;\n\t$.next();\n}, 'password');\n\nNEWTRANSFORM('user', null, 'password');\n```\n\n### TRANSFORM(name, value, [callback], [controller])\n\nType: `method`\n\nRuns a named transformation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the transformation |\n| `value` | `Object` | yes |  | The value to transform |\n| `callback` | `Function` | no |  | `function(err, value)` |\n| `controller` | `Controller` | no |  | A controller; its user is `$.user` in the functions |\n\nReturns: `Promise` A Promise when there is no callback\n\nRuns all functions added with `NEWTRANSFORM(name)` and calls `callback(err, value)` with the final value. A name without functions returns the value unchanged. Without a callback, it returns a Promise and the third argument is the controller. The Promise rejects with the errors of `$.invalid()`; when the third argument is the `$` of an action (or a controller), the errors go to its `invalid()` instead.\n\nExample: Callback\n```js\nTRANSFORM('user', user, function(err, value) {\n\tconsole.log(value);\n});\n```\n\nExample: Promise\n```js\nvar value = await TRANSFORM('user', user);\n```\n\nExample: Errors of the Promise form\n```js\ntry {\n\tvar value = await TRANSFORM('user', user);\n} catch (err) {\n\tconsole.log(err.toString()); // the errors of $.invalid()\n}\n```\n\n### ON('@' + name, function($, response) {})\n\nType: `event`\n\nEmitted after an action responds successfully.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | The `$` of the action |\n| `response` | `Object` | yes |  | The response of the action |\n\nThe event name is `@` and the name of the action. It runs after the response, so it is a good place for notifications, statistics or caches. It is not emitted when the action fails.\n\nExample: Notification\n```js\nON('@orders_create', function($, response) {\n\tconsole.log('New order', response.value, 'by', $.user.id);\n});\n```\n\n### action: Function\n\nType: `config`\n\nThe logic of the action.\n\nReturns: `Function`\n\n`function($, model)`. `model` is the validated payload (the same as `$.model`). The function must end the call with `$.success()`, `$.callback()`, `$.invalid()` or a callback from `$.done()`. It can be `async`: when its promise rejects (an exception in the function), the call ends with the error `500: Internal Server Error` and the exception is written to the error log, so the caller does not wait for a timeout.\n\nExample: Basic\n```js\nNEWACTION('ping', {\n\taction: function($) {\n\t\t$.success(NOW);\n\t}\n});\n```\n\n### input: String|Object\n\nType: `config`\n\nSchema of the payload.\n\nReturns: `String|Object`\n\nAn inline schema (`'*name:String, email:Email'`) or the name of a JSON schema with `@` (`'@product'`). The payload is validated and cleaned before the action runs; on failure the action does not run and the caller gets the errors. Without `input` the payload is not validated. See [JSON schemas](../../guides/json-schemas/).\n\nExample: Inline schema\n```js\nNEWACTION('contact_send', {\n\tinput: '*name:String, *email:Email, message:String',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### output: String|Object\n\nType: `config`\n\nSchema of the response.\n\nReturns: `String|Object`\n\nThe response is passed through this schema, so only the declared fields leave the action. Use it with `$.callback()`: with `$.success()` the schema is applied to the whole `{ success, value }` object.\n\nExample: Hide fields\n```js\nNEWACTION('users_read', {\n\tparams: '*id:UID',\n\toutput: 'id:UID, name:String, email:Email',\n\taction: function($) {\n\t\tDATA.read('users').id($.params.id).callback($);\n\t}\n});\n```\n\n### params: String|Object\n\nType: `config`\n\nSchema of the URL parameters.\n\nReturns: `String|Object`\n\nValidates `$.params`, the dynamic parts of the route (`{id}`). Errors have the prefix `params.`.\n\nExample: Parameter\n```js\nNEWACTION('products_remove', {\n\tparams: '*id:UID',\n\troute: '+DELETE /api/products/{id}/',\n\taction: function($) {\n\t\tDATA.remove('products').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### query: String|Object\n\nType: `config`\n\nSchema of the query string.\n\nReturns: `String|Object`\n\nValidates `$.query`. Errors have the prefix `query.`.\n\nExample: Query\n```js\nNEWACTION('products_search', {\n\tquery: '*q:String, page:Number',\n\troute: 'GET /api/products/search/',\n\taction: function($) {\n\t\tDATA.find('products').search('name', $.query.q).callback($);\n\t}\n});\n```\n\n### user: Boolean\n\nType: `config`\n\nRequires a signed-in or an anonymous user.\n\nReturns: `Boolean`\n\n`true`: the action fails with 401 when `$.user` is empty. `false`: it fails with 401 when there is a user. The options `sa: true` or `su: true` require a user with the `sa` or `su` flag.\n\nExample: Signed-in user\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### permissions: String|Array\n\nType: `config`\n\nRequired permissions.\n\nReturns: `String|Array`\n\nA string separated by commas or semicolons, or an array. The user needs at least one of them in `user.permissions` or `user.roles` (an array or an object); `sa` and `su` users pass always. Otherwise the action fails with 401.\n\nExample: Permissions\n```js\nNEWACTION('invoices_remove', {\n\tpermissions: 'invoices_remove,admin',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tDATA.remove('invoices').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### route: String\n\nType: `config`\n\nA route that runs the action.\n\nReturns: `String`\n\nA route string as in [Routing](../../guides/routing/) (`'+POST /api/products/'`). The framework appends ` --> <name>` and creates the route; the option then holds the route object. `url` is the same option under another name. With `encrypt: true` the route gets the `@encrypt` flag.\n\n`route: true` creates an `API ?` endpoint named after the action (`+API ?` when the action has the `user` or `permissions` option).\n\nExample: Route\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: API endpoint\n```js\nNEWACTION('products_list', {\n\troute: '+API ?',\n\taction: function($) {\n\t\tDATA.find('products').callback($);\n\t}\n});\n```\n\n### middleware: String\n\nType: `config`\n\nMiddleware to run before the action.\n\nReturns: `String`\n\nNames of middleware registered with `MIDDLEWARE()`, separated by spaces, commas or `|`. Each runs as `fn($, next)` before the action; a missing middleware is logged and skipped. See [Middleware](../../guides/middleware/).\n\nExample: Middleware\n```js\nNEWACTION('reports_build', {\n\tmiddleware: 'ratelimit',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### partial: Boolean\n\nType: `config`\n\nValidates the input partially.\n\nReturns: `Boolean`\n\nWith `true`, `input` validates only the fields present in the payload and does not check required fields. Useful for `PATCH` updates.\n\nExample: Patch\n```js\nNEWACTION('products_patch', {\n\tparams: '*id:UID',\n\tinput: '*name:String, *price:Number',\n\tpartial: true,\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).callback($.done());\n\t}\n});\n```\n\n### extend: String\n\nType: `config`\n\nAdds the response to the payload.\n\nReturns: `String`\n\nThe response is stored in the payload under this key (a path with dots is allowed) and the whole payload becomes the response. Without a payload an empty object is used. Useful in a chain of actions that build one object.\n\nExample: Extend\n```js\nNEWACTION('order_totals', {\n\textend: 'totals',\n\taction: function($, model) {\n\t\t$.callback({ count: 3, price: 120 });\n\t}\n});\n// response: { ...payload, totals: { count: 3, price: 120 } }\n```\n\n### audit: Boolean|String\n\nType: `config`\n\nWrites an audit record after success.\n\nReturns: `Boolean|String`\n\n`true` writes a record without a message; a string is a Tangular template rendered with `$` (`'{{ $.user.name }} created {{ $.model.name }}'`). The record has the user, IP, URL, the action name and the data, and goes to `DEF.onAudit` (by default the file `logs/actions.log`).\n\nExample: Audit message\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taudit: '{{ $.user.name }} created {{ $.model.name }}',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### config: Object\n\nType: `config`\n\nCustom configuration of the action.\n\nReturns: `Object`\n\nAny object; it is available as `$.config` in the action, so one function can serve several actions.\n\nExample: Shared logic\n```js\nfunction list($) {\n\tDATA.find($.config.table).callback($);\n}\n\nNEWACTION('products_list', { config: { table: 'products' }, action: list });\nNEWACTION('orders_list', { config: { table: 'orders' }, action: list });\n```\n\n### timeout: Number\n\nType: `config` · Since: `0.0.16`\n\nA time limit of the action.\n\nReturns: `Number`\n\nIn milliseconds. When the action does not respond in time, it fails with the error `Timeout.`; a later response is ignored.\n\nExample: Timeout\n```js\nNEWACTION('reports_export', {\n\ttimeout: 10000,\n\taction: function($) {\n\t\tsetTimeout(() => $.success(), 2000);\n\t}\n});\n```\n\n### cache: true | { query, params, input, user, language, key, expire }\n\nType: `config`\n\nKeeps the response of the action in the cache.\n\nReturns: `Boolean|Object`\n\nThe first successful response is kept in the cache (`CACHE`) and the next calls get a copy of it: the middleware and the action do not run. The response is copied both when it is stored and when it is read, so a caller can change its copy safely. Errors are not cached.\n\nWith `true` the action has one cached response. An object makes one entry for each combination of values:\n\n| Key | Value |\n| --- | --- |\n| `query`, `params`, `input` | `true` (all fields of the schema of the action) or a comma-separated list of fields |\n| `user` | `true` (`$.user.id`) or a comma-separated list of keys of `$.user` |\n| `language` | `true`: one entry for each `$.language` |\n| `key` | A name for the entries; `CACHE.reset('action|' + key + '|')` removes them |\n| `expire` | How long an entry is kept, default `'5 minutes'` |\n\nWithout `user`, all users share the same cached response.\n\nExample: A list cached per page\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number,category:String',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').where('category', $.query.category).page($.query.page, 20).callback($);\n\t}\n});\n\n// after a product is saved\nCACHE.reset('action|products|');\n```\n\nExample: One entry per user\n```js\nNEWACTION('Account|profile', {\n\tuser: true,\n\tcache: { user: true, expire: '1 minute' },\n\taction: function($) {\n\t\tDATA.read('users').id($.user.id).callback($);\n\t}\n});\n```\n\n### summary: String\n\nType: `config`\n\nA description of the action.\n\nReturns: `String`\n\nFree text about what the action does. The [MCP server](../../guides/mcp-server/) sends it to AI clients as the description of the tool; without `summary` it sends the `name` option.\n\nExample: Summary\n```js\nNEWACTION('tasks_create', {\n\tsummary: 'Creates a task and returns its ID',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### oninput: Function\n\nType: `config` · Since: `0.0.19`\n\nCalled right before the action.\n\nReturns: `Function`\n\n`function($)`. It runs after validation and middleware, so `$.model`, `$.params` and `$.query` are ready and you can change them.\n\nExample: Prepare data\n```js\nNEWACTION('notes_create', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.model.body = $.model.body.trim();\n\t},\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### mcp: Boolean\n\nType: `config`\n\nMakes the action a tool of the MCP server.\n\nReturns: `Boolean`\n\nWith `true` and the configuration key `$mcp`, AI clients can list and call the action at `POST /$mcp/`. The `input`, `query` and `params` schemas become the arguments of the tool. See [MCP server](../../guides/mcp-server/).\n\nExample: A tool\n```js\nNEWACTION('tasks_list', {\n\tsummary: 'Lists the tasks',\n\tmcp: true,\n\taction: function($) {\n\t\tNOSQL('tasks').find().callback($);\n\t}\n});\n```\n\n### onoutput: Function\n\nType: `config` · Since: `0.0.19`\n\nCalled after the action responds.\n\nReturns: `Function`\n\n`function(err, response, $)`. It runs after a successful response has been delivered, so `err` is `null`; it is not called when the action fails.\n\nExample: Log\n```js\nNEWACTION('orders_create', {\n\tinput: '*productid:UID',\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, $.user ? $.user.id : '', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### $.model\n\nType: `property`\n\nThe validated payload.\n\nReturns: `Object`\n\nThe payload after `input` validation, or the raw payload without `input`. `$.payload` and `$.value` are the same value; you can also assign it. It is also the second argument of `action`.\n\nExample: Model\n```js\naction: function($) {\n\tvar name = $.model.name;\n\t$.success(name);\n}\n```\n\n### $.input\n\nType: `property` · Since: `0.0.19`\n\nAnother name of `$.model`.\n\nReturns: `Object`\n\nReads and assigns the same value as `$.model`.\n\nExample: Input\n```js\noninput: function($) {\n\t$.input.email = $.input.email.toLowerCase();\n}\n```\n\n### $.params\n\nType: `property`\n\nThe URL parameters.\n\nReturns: `Object`\n\nValidated by the `params` option. In an HTTP request it contains the dynamic parts of the route; from code it is set with `ACTION().params()`.\n\nExample: Params\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback($);\n}\n```\n\n### $.query\n\nType: `property`\n\nThe query string.\n\nReturns: `Object`\n\nValidated by the `query` option. From code it is set with `ACTION().query()`.\n\nExample: Query\n```js\naction: function($) {\n\tvar page = $.query.page || 1;\n\t$.success(page);\n}\n```\n\n### $.user\n\nType: `property`\n\nThe current user.\n\nReturns: `Object`\n\nThe user of the HTTP request (see [Authorization](../../guides/authorization/)), or the user set with `ACTION().user()`. Empty for anonymous calls.\n\nExample: User\n```js\naction: function($) {\n\t$.success($.user.name);\n}\n```\n\n### $.config\n\nType: `property`\n\nThe `config` option of the action.\n\nReturns: `Object`\n\nAn empty object when the action has no `config`.\n\nExample: Config\n```js\naction: function($) {\n\t$.success($.config.table);\n}\n```\n\n### $.id\n\nType: `property`\n\nThe name of the running action.\n\nReturns: `String`\n\nIn a chain of actions, the name of the current one.\n\nExample: Name\n```js\naction: function($) {\n\tconsole.log('Running', $.id);\n\t$.success();\n}\n```\n\n### $.controller\n\nType: `property`\n\nThe controller of the HTTP request.\n\nReturns: `Controller`\n\n`undefined` when the action is called from code without a controller. `$.client` is the same; `$.websocket` is set when the controller is a WebSocket client.\n\nExample: Controller\n```js\naction: function($) {\n\t$.success($.controller ? $.controller.url : 'code');\n}\n```\n\n### $.error\n\nType: `property`\n\nThe errors of the call.\n\nReturns: `ErrorBuilder`\n\nAn `ErrorBuilder`. `$.invalid()` adds to it; `$.error.length` is the number of errors.\n\nExample: Errors\n```js\naction: function($) {\n\tif (!$.model.items.length) {\n\t\t$.invalid('No items', 'items');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.response\n\nType: `property`\n\nThe responses of the actions in a chain.\n\nReturns: `Object`\n\nAn object with the responses of the actions that already finished in the same call, by their names. The next action of the chain can use them.\n\nExample: Previous response\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tvar created = $.response.orders_create;\n\t\t$.success(created);\n\t}\n});\n```\n\n### $.xhr\n\nType: `property` · Since: `0.0.19`\n\nWhether the request is an XHR request.\n\nReturns: `Boolean`\n\n`true` when the HTTP request has the `X-Requested-With: XMLHttpRequest` header; `null` without a controller.\n\nExample: XHR\n```js\naction: function($) {\n\tif ($.xhr)\n\t\t$.success();\n\telse\n\t\t$.redirect('/');\n}\n```\n\n### $.meta\n\nType: `property` · Since: `0.0.19`\n\nThe definition of the action.\n\nReturns: `Object`\n\nThe object passed to `NEWACTION()`, with all its options.\n\nExample: Meta\n```js\naction: function($) {\n\t$.success($.meta.name);\n}\n```\n\n### $.env\n\nType: `property`\n\nThe environment of the call.\n\nReturns: `Any`\n\nThe value passed to `ACTION().env()`; `undefined` when it is not set. Use it to tell the action where it is called from, for example from a test or a job. `$.action()` does not pass it on: call `.env($)` on the inner call.\n\nExample: Environment\n```js\nNEWACTION('orders_sync', {\n\taction: function($) {\n\t\tif ($.env === 'test') {\n\t\t\t$.success();\n\t\t\treturn;\n\t\t}\n\t\t$.success('synced');\n\t}\n});\n\nACTION('orders_sync').env('test').callback(console.log);\n```\n\n### $.ip\n\nType: `property`\n\nRequest data shortcuts.\n\nReturns: `String`\n\n`$.ip`, `$.address`, `$.headers`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.split2`, `$.files`, `$.body`, `$.mobile`, `$.ua`, `$.language` and `$.sessionid` read the same properties of the controller. Without a controller they are empty (`null`, `''` or an empty array).\n\nExample: IP and agent\n```js\naction: function($) {\n\t$.success({ ip: $.ip, ua: $.ua });\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nEnds the action with a success object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | A value for the `value` property |\n\nResponds with `{ success: true, value: value }` (the shape comes from `DEF.onSuccess`). Without a value, `value` is `undefined`.\n\nExample: Success\n```js\naction: function($) {\n\t$.success(UID());\n}\n```\n\n### $.invalid(error, [path], [index])\n\nType: `method`\n\nEnds the action with an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number|Error` | yes |  | The error, or an HTTP status code |\n| `path` | `String` | no |  | The field the error belongs to |\n| `index` | `Number` | no |  | The index of the item in an array |\n\nReturns: `ErrorBuilder` The errors\n\nAdds the error to `$.error` and fails the call. A number above 399 is an HTTP status (`401`, `404`); a string is an error message. The caller's callback gets the `ErrorBuilder`, a route responds with the errors. Returns `$.error`.\n\nExample: Not found\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.callback(response);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n}\n```\n\n### $.callback([value])\n\nType: `method`\n\nEnds the action with a value as it is.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | The response |\n\nReturns: `Function` A callback when called without arguments\n\nResponds with `value` without wrapping it. Without arguments, it returns a `function(err, response)` callback that adds `err` to the errors and responds with `response`. `$.pipe` is the same method. You can also pass `$` itself to a database `callback()`.\n\nExample: Value\n```js\naction: function($) {\n\t$.callback({ count: 5 });\n}\n```\n\nExample: Callback of a query\n```js\naction: function($) {\n\tDATA.find('products').callback($.callback());\n}\n```\n\n### $.done([value])\n\nType: `method`\n\nReturns a callback that ends the action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | The value of the success object, or `true` for the response |\n\nReturns: `Function` `function(err, response)`\n\nReturns `function(err, response)`. An error ends the action with the error; otherwise it calls `$.success(value)`, or `$.success(response)` when `value` is `true`.\n\nExample: Done\n```js\naction: function($, model) {\n\tmodel.id = UID();\n\tDATA.insert('products', model).callback($.done(model.id));\n}\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method`\n\nCalls a callback function as a Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | A function whose last argument is `function(err, response)` |\n| `a` | `Object` | no |  | First argument |\n| `b` | `Object` | no |  | Second argument |\n| `c` | `Object` | no |  | Third argument |\n\nReturns: `Promise` The response\n\nCalls `fn(a, b, c, callback)` and resolves with the response. An error ends the action with `$.invalid()` and the Promise never resolves.\n\nExample: Promisify\n```js\naction: async function($) {\n\tvar files = await $.promisify(F.Fs.readdir, PATH.public());\n\t$.success(files);\n}\n```\n\n### $.action(name, [payload])\n\nType: `method`\n\nRuns another action from an action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Action name or names |\n| `payload` | `Object` | no |  | The payload |\n\nReturns: `ActionCaller` The caller\n\nSame as `ACTION()` with the controller of this action. Without a controller, the new call gets the user, query and params of this one.\n\nExample: Nested action\n```js\naction: async function($, model) {\n\tvar response = await $.action('stock_check', model).promise($);\n\t$.success(response);\n}\n```\n\n### $.transform(name, value, [callback])\n\nType: `method`\n\nRuns a transformation with the controller of the action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the transformation |\n| `value` | `Object` | yes |  | The value |\n| `callback` | `Function` | no |  | `function(err, value)` |\n\nReturns: `Promise` A Promise without a callback\n\nSame as `TRANSFORM()`, with the controller (and its user) of the action. Without a callback it returns a Promise.\n\nExample: Transform\n```js\naction: async function($) {\n\tvar user = await DATA.read('users').id($.params.id).promise($);\n\t$.callback(await $.transform('user', user));\n}\n```\n\n### $.unauthorized(permission, [permission2], [...])\n\nType: `method`\n\nChecks permissions of the user.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | yes |  | A permission name; more can follow |\n\nReturns: `Boolean` `true` when the user is not allowed\n\nReturns `false` when `$.user` has at least one of the permissions (in `permissions` or `roles`) or is `sa`/`su`. Otherwise it calls `$.invalid(401)` and returns `true`, so you only return.\n\nExample: Check\n```js\naction: function($) {\n\tif ($.unauthorized('reports'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.redirect(url)\n\nType: `method`\n\nRedirects the HTTP request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The target URL |\n\nRedirects the controller to `url` and cancels the action; the caller gets no response.\n\nExample: Redirect\n```js\naction: function($) {\n\t$.redirect('/login/');\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nEnds the action with a message and logs the real error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | The error for the caller, or an HTTP status code |\n| `error` | `Error|String` | no |  | The error for the log |\n\nReturns: `ErrorBuilder` The errors\n\nAdds `message` to `$.error` and fails the call, like `$.invalid(message)`. `error` is written to the error log with `F.error()` (the name of the action and the URL are added) and is not sent to the caller. Use it when the error has details that the client must not see. Returns `$.error`.\n\nExample: Hide the details\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n### ACTION(name).callback(fn)\n\nType: `method`\n\nReceives the result of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Options` | yes |  | `function(err, response)` or a `$` |\n\nReturns: `ActionCaller` The caller, for chaining\n\n`fn(err, response)`; `err` is an `ErrorBuilder` or `null`, When you pass the `$` of another action, errors go to its `$.invalid()` and the response to its `$.callback()`. `.pipe()` is the same method.\n\nExample: Callback\n```js\nACTION('products_list').callback(function(err, response) {\n\tconsole.log(err ? err.toString() : response);\n});\n```\n\nExample: Pass to another action\n```js\naction: function($) {\n\tACTION('products_list').user($).callback($);\n}\n```\n\n### $.throw(error)\n\nType: `method`\n\nWrites an error to the log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | The error |\n\nReturns: `Options` The same `$`\n\nPasses `error` to the error handler of the framework (`DEF.onError`) with the name of the action and the URL: it is printed, kept in `F.errors` and emitted as the `error` event. The action goes on; to end it, call `$.invalid()`. Returns `$`.\n\nExample: Log and continue\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tNOSQL('notifications').insert({ type: 'order', dtcreated: NOW }).callback(function(err) {\n\t\t\terr && $.throw(err);\n\t\t});\n\t\t$.success();\n\t}\n});\n```\n\n### $.touch([url])\n\nType: `method`\n\nClears the cached state of a static file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | The URL of the file |\n\nReturns: `Options` The same `$`\n\nCalls `TOUCH(url)`. Without `url` it uses the URL of the request; without a controller (an action called from code) every static file is cleared. Use it after the action changes a file in `public/`. Returns `$`.\n\nExample: After a change\n```js\nNEWACTION('theme_save', {\n\tinput: '*css:String',\n\taction: async function($, model) {\n\t\tawait F.FsPromises.writeFile(PATH.public('css/theme.css'), model.css);\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t}\n});\n```\n\n### ACTION(name).promise([$])\n\nType: `method`\n\nReturns a Promise with the result.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | no |  | The `$` of an action that receives the errors |\n\nReturns: `Promise` The response\n\nResolves with the response. On error it rejects with an `Error` whose message contains the errors; with `$`, the error goes to `$.invalid()` instead and the Promise does not resolve.\n\nExample: Await\n```js\nvar response = await ACTION('products_list').promise();\n```\n\n### ACTION(name).user(user)\n\nType: `method`\n\nSets the user of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object|Options` | yes |  | A user object, or a `$` |\n\nReturns: `ActionCaller` The caller, for chaining\n\nSets `$.user`. When you pass a `$`, its user is used.\n\nExample: User\n```js\nACTION('account_read').user({ id: '123', name: 'Peter' }).callback(console.log);\n```\n\n### ACTION(name).query(obj)\n\nType: `method`\n\nSets the query string of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The query |\n\nReturns: `ActionCaller` The caller, for chaining\n\nSets the object validated by the `query` option.\n\nExample: Query\n```js\nACTION('products_list').query({ page: 2 }).callback(console.log);\n```\n\n### ACTION(name).params(obj)\n\nType: `method`\n\nSets the URL parameters of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The parameters |\n\nReturns: `ActionCaller` The caller, for chaining\n\nSets the object validated by the `params` option.\n\nExample: Params\n```js\nACTION('products_read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\n### ACTION(name).ctrl(controller)\n\nType: `method`\n\nRuns the call with a controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | A controller |\n\nReturns: `ActionCaller` The caller, for chaining\n\nThe action gets `$.controller` and the request shortcuts. Accepts a controller or an object with a `controller` property (a `$`).\n\nExample: Controller\n```js\nfunction handler($) {\n\tACTION('products_list').ctrl($).autorespond();\n}\n```\n\n### ACTION(name).autorespond()\n\nType: `method`\n\nSends the result to the controller.\n\nReturns: `ActionCaller` The caller, for chaining\n\nOn error it calls `controller.invalid(err)`; otherwise it responds with the controller in the format set by `$.output()` (JSON by default). Routes with `-->` use it. Needs a controller.\n\nExample: Route handler\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', function($) {\n\t\t$.action('products_list').autorespond();\n\t});\n};\n```\n\n### ACTION(name).status(fn)\n\nType: `method`\n\nReceives status messages from the action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` The caller, for chaining\n\nThe action sends them with `$.status(a, b, c, d)`; the arguments go to `fn`. Without this method, `$.status()` does nothing.\n\nExample: Status\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\t$.status('started');\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').status(console.log).callback(console.log);\n```\n\n### ACTION(name).progress(fn)\n\nType: `method` · Since: `0.0.16`\n\nReceives progress messages from the action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` The caller, for chaining\n\nThe action sends them with `$.progress(a, b, c, d)`; the arguments go to `fn` with `$` as `this`. Without this method, `$.progress()` does nothing.\n\nExample: Progress\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\tfor (var i = 1; i <= 10; i++)\n\t\t\t$.progress(i * 10);\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').progress(p => console.log(p + '%')).callback(console.log);\n```\n\n### ACTION(name).config(obj)\n\nType: `method` · Since: `0.0.17`\n\nAdds configuration for this call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Keys for `$.config` |\n\nReturns: `ActionCaller` The caller, for chaining\n\nThe keys of `obj` are merged into a copy of the action's `config`, so `$.config` holds both; the definition of the action is not changed.\n\nExample: Config\n```js\nNEWACTION('report_build', {\n\tconfig: { format: 'pdf' },\n\taction: function($) {\n\t\t$.success($.config);\n\t}\n});\n\nACTION('report_build').config({ lang: 'en' }).callback(console.log);\n// { success: true, value: { format: 'pdf', lang: 'en' } }\n```\n\n### ACTION(name).env(value)\n\nType: `method`\n\nSets the environment of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any|Options` | yes |  | The environment, such as `'test'`, or a `$` |\n\nReturns: `ActionCaller` The caller, for chaining\n\nSets `$.env` in the action. When you pass a `$`, its `env` is used, so an inner call can keep the environment of the outer one.\n\nExample: Environment\n```js\nACTION('orders_sync').env('test').callback(console.log);\n```\n\nExample: Pass it on\n```js\nNEWACTION('orders_close', {\n\taction: async function($) {\n\t\tawait $.action('orders_sync').env($).promise($);\n\t\t$.success();\n\t}\n});\n```\n\n### SUCCESS([value])\n\nType: `method`\n\nCreates the success object that actions and controllers respond with.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | A value for the `value` property |\n\nReturns: `Object` `{ success: true, value: value }`\n\nReturns `{ success: true, value: value }`. The shape comes from `DEF.onSuccess`, the same function `$.success()` uses, so a custom `DEF.onSuccess` changes both. Use it when you build a response yourself, for example in a controller or in a callback.\n\nExample: A success response in a controller\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.json(SUCCESS(NOW));\n});\n```\n","entries":[{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, callback)","since":"","deprecated":false},{"type":"method","name":"NEWTRANSFORM()","signature":"NEWTRANSFORM(name, fn, [id])","since":"","deprecated":false},{"type":"method","name":"TRANSFORM()","signature":"TRANSFORM(name, value, [callback], [controller])","since":"","deprecated":false},{"type":"event","name":"ON('@{action}')","signature":"ON('@' + name, function($, response) {})","since":"","deprecated":false},{"type":"config","name":"NEWACTION.action","signature":"action: Function","since":"","deprecated":false},{"type":"config","name":"NEWACTION.input","signature":"input: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.output","signature":"output: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.params","signature":"params: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.query","signature":"query: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.user","signature":"user: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.permissions","signature":"permissions: String|Array","since":"","deprecated":false},{"type":"config","name":"NEWACTION.route","signature":"route: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.middleware","signature":"middleware: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.partial","signature":"partial: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.extend","signature":"extend: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.audit","signature":"audit: Boolean|String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.config","signature":"config: Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.timeout","signature":"timeout: Number","since":"0.0.16","deprecated":false},{"type":"config","name":"NEWACTION.cache","signature":"cache: true | { query, params, input, user, language, key, expire }","since":"","deprecated":false},{"type":"config","name":"NEWACTION.summary","signature":"summary: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.oninput","signature":"oninput: Function","since":"0.0.19","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.onoutput","signature":"onoutput: Function","since":"0.0.19","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.input","signature":"$.input","since":"0.0.19","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.config","signature":"$.config","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"0.0.19","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"0.0.19","deprecated":false},{"type":"property","name":"$.env","signature":"$.env","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [payload])","since":"","deprecated":false},{"type":"method","name":"$.transform()","signature":"$.transform(name, value, [callback])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized()","signature":"$.unauthorized(permission, [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"ACTION().callback()","signature":"ACTION(name).callback(fn)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"ACTION().promise()","signature":"ACTION(name).promise([$])","since":"","deprecated":false},{"type":"method","name":"ACTION().user()","signature":"ACTION(name).user(user)","since":"","deprecated":false},{"type":"method","name":"ACTION().query()","signature":"ACTION(name).query(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().params()","signature":"ACTION(name).params(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().ctrl()","signature":"ACTION(name).ctrl(controller)","since":"","deprecated":false},{"type":"method","name":"ACTION().autorespond()","signature":"ACTION(name).autorespond()","since":"","deprecated":false},{"type":"method","name":"ACTION().status()","signature":"ACTION(name).status(fn)","since":"","deprecated":false},{"type":"method","name":"ACTION().progress()","signature":"ACTION(name).progress(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ACTION().config()","signature":"ACTION(name).config(obj)","since":"0.0.17","deprecated":false},{"type":"method","name":"ACTION().env()","signature":"ACTION(name).env(value)","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([value])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwUcAPx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/actions/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Aktionen","summary":"Optionen von NEWACTION(), das $-Objekt, Aufrufer von ACTION(), NEWSCHEMA() und Transformationen.","markdown":"---\ntitle: Aktionen\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/actions/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Aktionen\n\n> Optionen von NEWACTION(), das $-Objekt, Aufrufer von ACTION(), NEWSCHEMA() und Transformationen.\n\nDie Funktionen, Optionen und Objekte der Aktionen in Total.js 5: `NEWACTION()` und seine Optionen, das `$`-Objekt, das eine Aktion erhält, der Aufrufer, den `ACTION()`/`EXEC()` zurückgibt, `NEWSCHEMA()` sowie `NEWTRANSFORM()`/`TRANSFORM()`.\n\nEine Einführung mit Beispielen findest du in der Anleitung [Aktionen](../../guides/actions/). Die Schemas für `input`, `output`, `params` und `query` sind in [JSON-Schemas](../../guides/json-schemas/) beschrieben.\n\n## API\n\n### NEWACTION(name, options)\n\nType: `method`\n\nDeklariert eine Aktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Aktion, z. B. `products_create` |\n| `options` | `Object` | yes |  | Die Definition: `action`, `input`, `output`, `params`, `query`, `user`, `permissions`, `route` und die übrigen Optionen |\n\nReturns: `Object` Die Definition der Aktion\n\nRegistriert die Aktion unter `name` und gibt das Definitionsobjekt zurück. Wenn `name` ein Objekt ist, sind das die Optionen, und der Name wird aus seiner Eigenschaft `id` oder `name` übernommen. Eine Aktion mit demselben Namen wird zuerst entfernt (samt ihrer Route). Das zurückgegebene Objekt hat `remove()`, das die Aktion und ihre Route entfernt. Alle registrierten Aktionen findest du in `F.actions`.\n\nExample: Eine vollständige Aktion\n```js\nNEWACTION('products_update', {\n\tname: 'Update a product',\n\tparams: '*id:UID',\n\tinput: '*name:String, price:Number',\n\tpermissions: 'products',\n\troute: '+PUT /api/products/{id}/',\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).error(404).callback($.done($.params.id));\n\t}\n});\n```\n\nExample: Eine Aktion entfernen\n```js\nvar action = NEWACTION('temp_test', { action: $ => $.success() });\naction.remove();\n```\n\n### ACTION(name, [payload], [controller])\n\nType: `method`\n\nFührt eine oder mehrere Aktionen aus dem Code aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Aktion oder durch Leerzeichen getrennte Namen; ein Präfix `+` oder `-` gibt an, ob die Aktion den Payload verwendet |\n| `payload` | `Object` | no |  | Die von der Option `input` validierten Daten |\n| `controller` | `Controller` | no |  | Ein Controller eines HTTP-Requests |\n\nReturns: `ActionCaller` Der Aufrufer mit `callback()`, `promise()`, `user()` und den übrigen Methoden\n\nGibt einen Aufrufer der Aktion zurück. Der Aufruf startet im nächsten Tick, also setzt du Benutzer, Query, Parameter und Callback per Verkettung. `name` kann mehrere Aktionen enthalten, getrennt durch Leerzeichen oder Kommas; sie laufen nacheinander mit demselben `$`. Das Ergebnis ist die Antwort der mit ` (response)` markierten Aktion oder ein Objekt mit den Antworten aller Aktionen nach ihren Namen. Bei einer einzelnen Aktion ist es immer deren Antwort. Mit einem Controller werden Benutzer, Query und Parameter von ihm übernommen.\n\nExample: Callback\n```js\nACTION('products_list').query({ search: 'mouse' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Mehrere Aktionen\n```js\nACTION('orders_create orders_notify (response)', model).user(user).callback(function(err, response) {\n\t// response is the response of orders_notify\n});\n```\n\n### EXEC(name, [payload], [controller])\n\nType: `method`\n\nEin Alias von `ACTION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name oder Namen der Aktion |\n| `payload` | `Object` | no |  | Der Payload |\n| `controller` | `Controller` | no |  | Ein Controller |\n\nReturns: `ActionCaller` Der Aufrufer\n\nDieselbe Funktion wie `ACTION()`.\n\nExample: Promise\n```js\nvar response = await EXEC('products_create', { name: 'Mouse' }).user(user).promise();\n```\n\n### NEWSCHEMA(name, callback)\n\nType: `method`\n\nFasst Aktionen unter einem gemeinsamen Namen zusammen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Schemas |\n| `callback` | `Function|String` | yes |  | `function(schema)` oder eine Inline-Schema-Definition |\n\nReturns: `Object` Nichts bei einem Callback; das JSON-Schema bei einem String\n\nRuft `callback(schema)` auf; `schema.action(name, options)` deklariert die Aktion `<schema name>/<name>` mit `NEWACTION()` und gibt sie zurück. Die erstellten Aktionen stehen auch in `schema.actions`. Ein führendes `@` im Namen wird entfernt. Ist das zweite Argument ein String, registriert `NEWSCHEMA()` stattdessen ein JSON-Schema mit dieser Inline-Definition und gibt es zurück.\n\nExample: Aktionen eines Schemas\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('read', {\n\t\tparams: '*id:UID',\n\t\taction: function($) {\n\t\t\tDATA.read('users').id($.params.id).error(404).callback($);\n\t\t}\n\t});\n\n});\n\nACTION('Users/read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\nExample: Ein JSON-Schema\n```js\nNEWSCHEMA('Address', '*street:String, *city:String, zip:Zip');\n```\n\n### NEWTRANSFORM(name, fn, [id])\n\nType: `method`\n\nFügt einer benannten Transformation eine Funktion hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Transformation |\n| `fn` | `Function` | yes |  | `function($, value)` |\n| `id` | `String` | no |  | Ein Bezeichner, um die Funktion später zu entfernen |\n\nReturns: `Object` Ein Objekt mit `id`, `action` und `remove()`\n\nFunktionen eines Namens laufen in der Reihenfolge, in der sie hinzugefügt wurden. Jede erhält `($, value)`; sie ändert `value` oder weist ein neues `$.value` zu und ruft dann `$.next()` auf oder stoppt die Kette mit `$.invalid(error)` (der Callback von `TRANSFORM()` erhält dann die Fehler). `$.user` und `$.controller` sind gesetzt, wenn die Transformation mit einem Controller ausgeführt wird. Gibt ein Objekt mit `remove()` zurück. `NEWTRANSFORM(name, null, id)` entfernt die Funktion mit dieser `id`.\n\nExample: Hinzufügen und entfernen\n```js\nNEWTRANSFORM('user', function($, value) {\n\tdelete value.password;\n\t$.next();\n}, 'password');\n\nNEWTRANSFORM('user', null, 'password');\n```\n\n### TRANSFORM(name, value, [callback], [controller])\n\nType: `method`\n\nFührt eine benannte Transformation aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Transformation |\n| `value` | `Object` | yes |  | Der zu transformierende Wert |\n| `callback` | `Function` | no |  | `function(err, value)` |\n| `controller` | `Controller` | no |  | Ein Controller; sein Benutzer ist `$.user` in den Funktionen |\n\nReturns: `Promise` Ein Promise, wenn es keinen Callback gibt\n\nFührt alle Funktionen aus, die mit `NEWTRANSFORM(name)` hinzugefügt wurden, und ruft `callback(err, value)` mit dem endgültigen Wert auf. Ein Name ohne Funktionen gibt den Wert unverändert zurück. Ohne Callback gibt es ein Promise zurück, und das dritte Argument ist der Controller. Das Promise wird mit den Fehlern von `$.invalid()` abgelehnt; ist das dritte Argument das `$` einer Aktion (oder ein Controller), gehen die Fehler stattdessen an dessen `invalid()`.\n\nExample: Callback\n```js\nTRANSFORM('user', user, function(err, value) {\n\tconsole.log(value);\n});\n```\n\nExample: Promise\n```js\nvar value = await TRANSFORM('user', user);\n```\n\nExample: Fehler der Promise-Form\n```js\ntry {\n\tvar value = await TRANSFORM('user', user);\n} catch (err) {\n\tconsole.log(err.toString()); // the errors of $.invalid()\n}\n```\n\n### ON('@' + name, function($, response) {})\n\nType: `event`\n\nWird ausgelöst, nachdem eine Aktion erfolgreich geantwortet hat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | Das `$` der Aktion |\n| `response` | `Object` | yes |  | Die Antwort der Aktion |\n\nDer Event-Name ist `@` plus der Name der Aktion. Er läuft nach der Antwort und eignet sich daher für Benachrichtigungen, Statistiken oder Caches. Er wird nicht ausgelöst, wenn die Aktion fehlschlägt.\n\nExample: Benachrichtigung\n```js\nON('@orders_create', function($, response) {\n\tconsole.log('New order', response.value, 'by', $.user.id);\n});\n```\n\n### action: Function\n\nType: `config`\n\nDie Logik der Aktion.\n\nReturns: `Function`\n\n`function($, model)`. `model` sind die validierten Nutzdaten (dasselbe wie `$.model`). Die Funktion muss den Aufruf mit `$.success()`, `$.callback()`, `$.invalid()` oder einem Callback von `$.done()` beenden. Sie kann `async` sein: Wird ihr Promise abgelehnt (eine Exception in der Funktion), endet der Aufruf mit dem Fehler `500: Internal Server Error` und die Exception wird ins Fehlerprotokoll geschrieben, sodass der Aufrufer nicht auf ein Timeout wartet.\n\nExample: Grundlagen\n```js\nNEWACTION('ping', {\n\taction: function($) {\n\t\t$.success(NOW);\n\t}\n});\n```\n\n### input: String|Object\n\nType: `config`\n\nSchema des Payloads.\n\nReturns: `String|Object`\n\nEin Inline-Schema (`'*name:String, email:Email'`) oder der Name eines JSON-Schemas mit `@` (`'@product'`). Der Payload wird validiert und bereinigt, bevor die Aktion läuft; schlägt das fehl, läuft die Aktion nicht und der Aufrufer erhält die Fehler. Ohne `input` wird der Payload nicht validiert. Siehe [JSON-Schemas](../../guides/json-schemas/).\n\nExample: Inline-Schema\n```js\nNEWACTION('contact_send', {\n\tinput: '*name:String, *email:Email, message:String',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### output: String|Object\n\nType: `config`\n\nSchema der Antwort.\n\nReturns: `String|Object`\n\nDie Antwort wird durch dieses Schema geleitet, sodass nur die deklarierten Felder die Aktion verlassen. Verwende es mit `$.callback()`: Mit `$.success()` wird das Schema auf das ganze Objekt `{ success, value }` angewendet.\n\nExample: Felder ausblenden\n```js\nNEWACTION('users_read', {\n\tparams: '*id:UID',\n\toutput: 'id:UID, name:String, email:Email',\n\taction: function($) {\n\t\tDATA.read('users').id($.params.id).callback($);\n\t}\n});\n```\n\n### params: String|Object\n\nType: `config`\n\nSchema der URL-Parameter.\n\nReturns: `String|Object`\n\nValidiert `$.params`, die dynamischen Teile der Route (`{id}`). Fehler haben das Präfix `params.`.\n\nExample: Parameter\n```js\nNEWACTION('products_remove', {\n\tparams: '*id:UID',\n\troute: '+DELETE /api/products/{id}/',\n\taction: function($) {\n\t\tDATA.remove('products').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### query: String|Object\n\nType: `config`\n\nSchema des Query-Strings.\n\nReturns: `String|Object`\n\nValidiert `$.query`. Fehler haben das Präfix `query.`.\n\nExample: Query\n```js\nNEWACTION('products_search', {\n\tquery: '*q:String, page:Number',\n\troute: 'GET /api/products/search/',\n\taction: function($) {\n\t\tDATA.find('products').search('name', $.query.q).callback($);\n\t}\n});\n```\n\n### user: Boolean\n\nType: `config`\n\nVerlangt einen angemeldeten oder einen anonymen Benutzer.\n\nReturns: `Boolean`\n\n`true`: Die Aktion schlägt mit 401 fehl, wenn `$.user` leer ist. `false`: Sie schlägt mit 401 fehl, wenn es einen Benutzer gibt. Die Optionen `sa: true` oder `su: true` verlangen einen Benutzer mit dem Flag `sa` oder `su`.\n\nExample: Angemeldeter Benutzer\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### permissions: String|Array\n\nType: `config`\n\nErforderliche Berechtigungen.\n\nReturns: `String|Array`\n\nEin durch Kommas oder Semikolons getrennter String oder ein Array. Der Benutzer braucht mindestens eine davon in `user.permissions` oder `user.roles` (ein Array oder ein Objekt); Benutzer mit `sa` und `su` kommen immer durch. Andernfalls schlägt die Aktion mit 401 fehl.\n\nExample: Berechtigungen\n```js\nNEWACTION('invoices_remove', {\n\tpermissions: 'invoices_remove,admin',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tDATA.remove('invoices').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### route: String\n\nType: `config`\n\nEine Route, die die Aktion ausführt.\n\nReturns: `String`\n\nEin Routen-String wie in [Routing](../../guides/routing/) (`'+POST /api/products/'`). Das Framework hängt ` --> <name>` an und erstellt die Route; die Option enthält dann das Routenobjekt. `url` ist dieselbe Option unter einem anderen Namen. Mit `encrypt: true` erhält die Route das Flag `@encrypt`.\n\n`route: true` erstellt einen nach der Aktion benannten `API ?`-Endpunkt (`+API ?`, wenn die Aktion die Option `user` oder `permissions` hat).\n\nExample: Route\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: API-Endpunkt\n```js\nNEWACTION('products_list', {\n\troute: '+API ?',\n\taction: function($) {\n\t\tDATA.find('products').callback($);\n\t}\n});\n```\n\n### middleware: String\n\nType: `config`\n\nMiddleware, die vor der Aktion läuft.\n\nReturns: `String`\n\nNamen von mit `MIDDLEWARE()` registrierter Middleware, getrennt durch Leerzeichen, Kommas oder `|`. Jede läuft als `fn($, next)` vor der Aktion; eine fehlende Middleware wird protokolliert und übersprungen. Siehe [Middleware](../../guides/middleware/).\n\nExample: Middleware\n```js\nNEWACTION('reports_build', {\n\tmiddleware: 'ratelimit',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### partial: Boolean\n\nType: `config`\n\nValidiert die Eingabe teilweise.\n\nReturns: `Boolean`\n\nMit `true` validiert `input` nur die im Payload vorhandenen Felder und prüft keine Pflichtfelder. Nützlich für Updates mit `PATCH`.\n\nExample: Patch\n```js\nNEWACTION('products_patch', {\n\tparams: '*id:UID',\n\tinput: '*name:String, *price:Number',\n\tpartial: true,\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).callback($.done());\n\t}\n});\n```\n\n### extend: String\n\nType: `config`\n\nFügt die Antwort dem Payload hinzu.\n\nReturns: `String`\n\nDie Antwort wird im Payload unter diesem Schlüssel gespeichert (ein Pfad mit Punkten ist erlaubt), und der gesamte Payload wird zur Antwort. Ohne Payload wird ein leeres Objekt verwendet. Nützlich in einer Kette von Aktionen, die ein Objekt aufbauen.\n\nExample: Erweitern\n```js\nNEWACTION('order_totals', {\n\textend: 'totals',\n\taction: function($, model) {\n\t\t$.callback({ count: 3, price: 120 });\n\t}\n});\n// response: { ...payload, totals: { count: 3, price: 120 } }\n```\n\n### audit: Boolean|String\n\nType: `config`\n\nSchreibt nach Erfolg einen Audit-Eintrag.\n\nReturns: `Boolean|String`\n\n`true` schreibt einen Eintrag ohne Nachricht; ein String ist ein Tangular-Template, das mit `$` gerendert wird (`'{{ $.user.name }} created {{ $.model.name }}'`). Der Eintrag enthält Benutzer, IP, URL, den Namen der Aktion und die Daten und geht an `DEF.onAudit` (standardmäßig die Datei `logs/actions.log`).\n\nExample: Audit-Nachricht\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taudit: '{{ $.user.name }} created {{ $.model.name }}',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### config: Object\n\nType: `config`\n\nEigene Konfiguration der Aktion.\n\nReturns: `Object`\n\nEin beliebiges Objekt; es steht in der Aktion als `$.config` zur Verfügung, sodass eine Funktion mehrere Aktionen bedienen kann.\n\nExample: Gemeinsame Logik\n```js\nfunction list($) {\n\tDATA.find($.config.table).callback($);\n}\n\nNEWACTION('products_list', { config: { table: 'products' }, action: list });\nNEWACTION('orders_list', { config: { table: 'orders' }, action: list });\n```\n\n### timeout: Number\n\nType: `config` · Since: `0.0.16`\n\nEin Zeitlimit der Aktion.\n\nReturns: `Number`\n\nIn Millisekunden. Antwortet die Aktion nicht rechtzeitig, schlägt sie mit dem Fehler `Timeout.` fehl; eine spätere Antwort wird ignoriert.\n\nExample: Timeout\n```js\nNEWACTION('reports_export', {\n\ttimeout: 10000,\n\taction: function($) {\n\t\tsetTimeout(() => $.success(), 2000);\n\t}\n});\n```\n\n### cache: true | { query, params, input, user, language, key, expire }\n\nType: `config`\n\nHält die Antwort der Aktion im Cache.\n\nReturns: `Boolean|Object`\n\nDie erste erfolgreiche Antwort wird im Cache (`CACHE`) gehalten, und die nächsten Aufrufe erhalten eine Kopie davon: Die Middleware und die Aktion laufen nicht. Die Antwort wird sowohl beim Speichern als auch beim Lesen kopiert, sodass ein Aufrufer seine Kopie gefahrlos ändern kann. Fehler werden nicht gecacht.\n\nMit `true` hat die Aktion eine einzige gecachte Antwort. Ein Objekt erzeugt einen Eintrag für jede Kombination von Werten:\n\n| Schlüssel | Wert |\n| --- | --- |\n| `query`, `params`, `input` | `true` (alle Felder des Schemas der Aktion) oder eine kommagetrennte Liste von Feldern |\n| `user` | `true` (`$.user.id`) oder eine kommagetrennte Liste von Schlüsseln von `$.user` |\n| `language` | `true`: ein Eintrag für jede `$.language` |\n| `key` | Ein Name für die Einträge; `CACHE.reset('action|' + key + '|')` entfernt sie |\n| `expire` | Wie lange ein Eintrag gehalten wird, Standard `'5 minutes'` |\n\nOhne `user` teilen sich alle Benutzer dieselbe gecachte Antwort.\n\nExample: Eine Liste, pro Seite gecacht\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number,category:String',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').where('category', $.query.category).page($.query.page, 20).callback($);\n\t}\n});\n\n// after a product is saved\nCACHE.reset('action|products|');\n```\n\nExample: Ein Eintrag pro Benutzer\n```js\nNEWACTION('Account|profile', {\n\tuser: true,\n\tcache: { user: true, expire: '1 minute' },\n\taction: function($) {\n\t\tDATA.read('users').id($.user.id).callback($);\n\t}\n});\n```\n\n### summary: String\n\nType: `config`\n\nEine Beschreibung der Aktion.\n\nReturns: `String`\n\nFreier Text darüber, was die Aktion tut. Der [MCP-Server](../../guides/mcp-server/) sendet ihn an KI-Clients als Beschreibung des Tools; ohne `summary` sendet er die Option `name`.\n\nExample: Beschreibung\n```js\nNEWACTION('tasks_create', {\n\tsummary: 'Creates a task and returns its ID',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### oninput: Function\n\nType: `config` · Since: `0.0.19`\n\nWird direkt vor der Aktion aufgerufen.\n\nReturns: `Function`\n\n`function($)`. Sie läuft nach der Validierung und der Middleware, daher sind `$.model`, `$.params` und `$.query` bereit und du kannst sie ändern.\n\nExample: Daten vorbereiten\n```js\nNEWACTION('notes_create', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.model.body = $.model.body.trim();\n\t},\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### mcp: Boolean\n\nType: `config`\n\nMacht die Aktion zu einem Tool des MCP-Servers.\n\nReturns: `Boolean`\n\nMit `true` und dem Konfigurationsschlüssel `$mcp` können KI-Clients die Aktion unter `POST /$mcp/` auflisten und aufrufen. Die Schemas `input`, `query` und `params` werden zu den Argumenten des Tools. Siehe [MCP-Server](../../guides/mcp-server/).\n\nExample: Ein Tool\n```js\nNEWACTION('tasks_list', {\n\tsummary: 'Lists the tasks',\n\tmcp: true,\n\taction: function($) {\n\t\tNOSQL('tasks').find().callback($);\n\t}\n});\n```\n\n### onoutput: Function\n\nType: `config` · Since: `0.0.19`\n\nWird aufgerufen, nachdem die Aktion geantwortet hat.\n\nReturns: `Function`\n\n`function(err, response, $)`. Sie läuft, nachdem eine erfolgreiche Antwort ausgeliefert wurde, daher ist `err` `null`; sie wird nicht aufgerufen, wenn die Aktion fehlschlägt.\n\nExample: Loggen\n```js\nNEWACTION('orders_create', {\n\tinput: '*productid:UID',\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, $.user ? $.user.id : '', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### $.model\n\nType: `property`\n\nDer validierte Payload.\n\nReturns: `Object`\n\nDer Payload nach der Validierung durch `input` oder der Roh-Payload ohne `input`. `$.payload` und `$.value` sind derselbe Wert; du kannst ihn auch zuweisen. Er ist auch das zweite Argument von `action`.\n\nExample: Model\n```js\naction: function($) {\n\tvar name = $.model.name;\n\t$.success(name);\n}\n```\n\n### $.input\n\nType: `property` · Since: `0.0.19`\n\nEin anderer Name für `$.model`.\n\nReturns: `Object`\n\nLiest und setzt denselben Wert wie `$.model`.\n\nExample: Eingabe\n```js\noninput: function($) {\n\t$.input.email = $.input.email.toLowerCase();\n}\n```\n\n### $.params\n\nType: `property`\n\nDie URL-Parameter.\n\nReturns: `Object`\n\nValidiert durch die Option `params`. In einem HTTP-Request enthält es die dynamischen Teile der Route; aus dem Code wird es mit `ACTION().params()` gesetzt.\n\nExample: Params\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback($);\n}\n```\n\n### $.query\n\nType: `property`\n\nDer Query-String.\n\nReturns: `Object`\n\nValidiert durch die Option `query`. Aus dem Code wird es mit `ACTION().query()` gesetzt.\n\nExample: Query\n```js\naction: function($) {\n\tvar page = $.query.page || 1;\n\t$.success(page);\n}\n```\n\n### $.user\n\nType: `property`\n\nDer aktuelle Benutzer.\n\nReturns: `Object`\n\nDer Benutzer des HTTP-Requests (siehe [Autorisierung](../../guides/authorization/)) oder der mit `ACTION().user()` gesetzte Benutzer. Leer bei anonymen Aufrufen.\n\nExample: Benutzer\n```js\naction: function($) {\n\t$.success($.user.name);\n}\n```\n\n### $.config\n\nType: `property`\n\nDie Option `config` der Aktion.\n\nReturns: `Object`\n\nEin leeres Objekt, wenn die Aktion kein `config` hat.\n\nExample: Config\n```js\naction: function($) {\n\t$.success($.config.table);\n}\n```\n\n### $.id\n\nType: `property`\n\nDer Name der laufenden Aktion.\n\nReturns: `String`\n\nIn einer Kette von Aktionen der Name der aktuellen.\n\nExample: Name\n```js\naction: function($) {\n\tconsole.log('Running', $.id);\n\t$.success();\n}\n```\n\n### $.controller\n\nType: `property`\n\nDer Controller des HTTP-Requests.\n\nReturns: `Controller`\n\n`undefined`, wenn die Aktion ohne Controller aus dem Code aufgerufen wird. `$.client` ist dasselbe; `$.websocket` ist gesetzt, wenn der Controller ein WebSocket-Client ist.\n\nExample: Controller\n```js\naction: function($) {\n\t$.success($.controller ? $.controller.url : 'code');\n}\n```\n\n### $.error\n\nType: `property`\n\nDie Fehler des Aufrufs.\n\nReturns: `ErrorBuilder`\n\nEin `ErrorBuilder`. `$.invalid()` fügt ihm Fehler hinzu; `$.error.length` ist die Anzahl der Fehler.\n\nExample: Fehler\n```js\naction: function($) {\n\tif (!$.model.items.length) {\n\t\t$.invalid('No items', 'items');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.response\n\nType: `property`\n\nDie Antworten der Aktionen in einer Kette.\n\nReturns: `Object`\n\nEin Objekt mit den Antworten der Aktionen, die im selben Aufruf bereits fertig sind, nach ihren Namen. Die nächste Aktion der Kette kann sie verwenden.\n\nExample: Vorherige Antwort\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tvar created = $.response.orders_create;\n\t\t$.success(created);\n\t}\n});\n```\n\n### $.xhr\n\nType: `property` · Since: `0.0.19`\n\nOb die Anfrage eine XHR-Anfrage ist.\n\nReturns: `Boolean`\n\n`true`, wenn die HTTP-Anfrage den Header `X-Requested-With: XMLHttpRequest` hat; `null` ohne Controller.\n\nExample: XHR\n```js\naction: function($) {\n\tif ($.xhr)\n\t\t$.success();\n\telse\n\t\t$.redirect('/');\n}\n```\n\n### $.meta\n\nType: `property` · Since: `0.0.19`\n\nDie Definition der Aktion.\n\nReturns: `Object`\n\nDas an `NEWACTION()` übergebene Objekt, mit all seinen Optionen.\n\nExample: Meta\n```js\naction: function($) {\n\t$.success($.meta.name);\n}\n```\n\n### $.env\n\nType: `property`\n\nDie Umgebung des Aufrufs.\n\nReturns: `Any`\n\nDer an `ACTION().env()` übergebene Wert; `undefined`, wenn er nicht gesetzt ist. Verwende ihn, um der Aktion zu sagen, von wo sie aufgerufen wird, zum Beispiel aus einem Test oder einem Job. `$.action()` gibt ihn nicht weiter: Rufe `.env($)` am inneren Aufruf auf.\n\nExample: Umgebung\n```js\nNEWACTION('orders_sync', {\n\taction: function($) {\n\t\tif ($.env === 'test') {\n\t\t\t$.success();\n\t\t\treturn;\n\t\t}\n\t\t$.success('synced');\n\t}\n});\n\nACTION('orders_sync').env('test').callback(console.log);\n```\n\n### $.ip\n\nType: `property`\n\nKurzformen für Request-Daten.\n\nReturns: `String`\n\n`$.ip`, `$.address`, `$.headers`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.split2`, `$.files`, `$.body`, `$.mobile`, `$.ua`, `$.language` und `$.sessionid` lesen die gleichnamigen Eigenschaften des Controllers. Ohne Controller sind sie leer (`null`, `''` oder ein leeres Array).\n\nExample: IP und User-Agent\n```js\naction: function($) {\n\t$.success({ ip: $.ip, ua: $.ua });\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nBeendet die Aktion mit einem Erfolgsobjekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Ein Wert für die Eigenschaft `value` |\n\nAntwortet mit `{ success: true, value: value }` (die Form stammt von `DEF.onSuccess`). Ohne Wert ist `value` gleich `undefined`.\n\nExample: Erfolg\n```js\naction: function($) {\n\t$.success(UID());\n}\n```\n\n### $.invalid(error, [path], [index])\n\nType: `method`\n\nBeendet die Aktion mit einem Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number|Error` | yes |  | Der Fehler oder ein HTTP-Statuscode |\n| `path` | `String` | no |  | Das Feld, zu dem der Fehler gehört |\n| `index` | `Number` | no |  | Der Index des Elements in einem Array |\n\nReturns: `ErrorBuilder` Die Fehler\n\nFügt den Fehler zu `$.error` hinzu und lässt den Aufruf fehlschlagen. Eine Zahl über 399 ist ein HTTP-Status (`401`, `404`); ein String ist eine Fehlermeldung. Der Callback des Aufrufers erhält den `ErrorBuilder`, eine Route antwortet mit den Fehlern. Gibt `$.error` zurück.\n\nExample: Nicht gefunden\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.callback(response);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n}\n```\n\n### $.callback([value])\n\nType: `method`\n\nBeendet die Aktion mit einem Wert, so wie er ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Die Antwort |\n\nReturns: `Function` Ein Callback, wenn sie ohne Argumente aufgerufen wird\n\nAntwortet mit `value`, ohne ihn zu verpacken. Ohne Argumente gibt sie einen Callback `function(err, response)` zurück, der `err` zu den Fehlern hinzufügt und mit `response` antwortet. `$.pipe` ist dieselbe Methode. Du kannst auch `$` selbst an ein `callback()` einer Datenbank übergeben.\n\nExample: Wert\n```js\naction: function($) {\n\t$.callback({ count: 5 });\n}\n```\n\nExample: Callback einer Abfrage\n```js\naction: function($) {\n\tDATA.find('products').callback($.callback());\n}\n```\n\n### $.done([value])\n\nType: `method`\n\nGibt einen Callback zurück, der die Aktion beendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | Der Wert des Erfolgsobjekts oder `true` für die Antwort |\n\nReturns: `Function` `function(err, response)`\n\nGibt `function(err, response)` zurück. Ein Fehler beendet die Aktion mit dem Fehler; andernfalls ruft er `$.success(value)` auf, oder `$.success(response)`, wenn `value` gleich `true` ist.\n\nExample: Done\n```js\naction: function($, model) {\n\tmodel.id = UID();\n\tDATA.insert('products', model).callback($.done(model.id));\n}\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method`\n\nRuft eine Callback-Funktion als Promise auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Eine Funktion, deren letztes Argument `function(err, response)` ist |\n| `a` | `Object` | no |  | Erstes Argument |\n| `b` | `Object` | no |  | Zweites Argument |\n| `c` | `Object` | no |  | Drittes Argument |\n\nReturns: `Promise` Die Antwort\n\nRuft `fn(a, b, c, callback)` auf und löst mit der Antwort auf. Ein Fehler beendet die Aktion mit `$.invalid()`, und das Promise löst nie auf.\n\nExample: Promisify\n```js\naction: async function($) {\n\tvar files = await $.promisify(F.Fs.readdir, PATH.public());\n\t$.success(files);\n}\n```\n\n### $.action(name, [payload])\n\nType: `method`\n\nFührt aus einer Aktion eine andere Aktion aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name oder Namen der Aktion |\n| `payload` | `Object` | no |  | Der Payload |\n\nReturns: `ActionCaller` Der Aufrufer\n\nWie `ACTION()` mit dem Controller dieser Aktion. Ohne Controller erhält der neue Aufruf Benutzer, Query und Parameter dieses Aufrufs.\n\nExample: Verschachtelte Aktion\n```js\naction: async function($, model) {\n\tvar response = await $.action('stock_check', model).promise($);\n\t$.success(response);\n}\n```\n\n### $.transform(name, value, [callback])\n\nType: `method`\n\nFührt eine Transformation mit dem Controller der Aktion aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Transformation |\n| `value` | `Object` | yes |  | Der Wert |\n| `callback` | `Function` | no |  | `function(err, value)` |\n\nReturns: `Promise` Ein Promise ohne Callback\n\nWie `TRANSFORM()`, mit dem Controller (und seinem Benutzer) der Aktion. Ohne Callback gibt sie ein Promise zurück.\n\nExample: Transformation\n```js\naction: async function($) {\n\tvar user = await DATA.read('users').id($.params.id).promise($);\n\t$.callback(await $.transform('user', user));\n}\n```\n\n### $.unauthorized(permission, [permission2], [...])\n\nType: `method`\n\nPrüft die Berechtigungen des Benutzers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | yes |  | Ein Berechtigungsname; weitere können folgen |\n\nReturns: `Boolean` `true`, wenn der Benutzer keine Berechtigung hat\n\nGibt `false` zurück, wenn `$.user` mindestens eine der Berechtigungen hat (in `permissions` oder `roles`) oder `sa`/`su` ist. Andernfalls ruft sie `$.invalid(401)` auf und gibt `true` zurück, sodass du nur noch zurückkehren musst.\n\nExample: Prüfung\n```js\naction: function($) {\n\tif ($.unauthorized('reports'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.redirect(url)\n\nType: `method`\n\nLeitet den HTTP-Request um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Ziel-URL |\n\nLeitet den Controller auf `url` um und bricht die Aktion ab; der Aufrufer erhält keine Antwort.\n\nExample: Umleitung\n```js\naction: function($) {\n\t$.redirect('/login/');\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nBeendet die Aktion mit einer Meldung und loggt den echten Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | Der Fehler für den Aufrufer oder ein HTTP-Statuscode |\n| `error` | `Error|String` | no |  | Der Fehler für das Log |\n\nReturns: `ErrorBuilder` Die Fehler\n\nFügt `message` zu `$.error` hinzu und lässt den Aufruf fehlschlagen, wie `$.invalid(message)`. `error` wird mit `F.error()` ins Fehlerlog geschrieben (der Name der Aktion und die URL werden hinzugefügt) und nicht an den Aufrufer gesendet. Verwende es, wenn der Fehler Details enthält, die der Client nicht sehen darf. Gibt `$.error` zurück.\n\nExample: Die Details verbergen\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n### ACTION(name).callback(fn)\n\nType: `method`\n\nEmpfängt das Ergebnis des Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Options` | yes |  | `function(err, response)` oder ein `$` |\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\n`fn(err, response)`; `err` ist ein `ErrorBuilder` oder `null`, Wenn du das `$` einer anderen Aktion übergibst, gehen Fehler an deren `$.invalid()` und die Antwort an deren `$.callback()`. `.pipe()` ist dieselbe Methode.\n\nExample: Callback\n```js\nACTION('products_list').callback(function(err, response) {\n\tconsole.log(err ? err.toString() : response);\n});\n```\n\nExample: An eine andere Aktion übergeben\n```js\naction: function($) {\n\tACTION('products_list').user($).callback($);\n}\n```\n\n### $.throw(error)\n\nType: `method`\n\nSchreibt einen Fehler ins Log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | Der Fehler |\n\nReturns: `Options` Dasselbe `$`\n\nÜbergibt `error` mit dem Namen der Aktion und der URL an den Fehlerhandler des Frameworks (`DEF.onError`): Er wird ausgegeben, in `F.errors` aufbewahrt und als Event `error` gesendet. Die Aktion läuft weiter; um sie zu beenden, rufe `$.invalid()` auf. Gibt `$` zurück.\n\nExample: Loggen und weitermachen\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tNOSQL('notifications').insert({ type: 'order', dtcreated: NOW }).callback(function(err) {\n\t\t\terr && $.throw(err);\n\t\t});\n\t\t$.success();\n\t}\n});\n```\n\n### $.touch([url])\n\nType: `method`\n\nLöscht den gecachten Zustand einer statischen Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | Die URL der Datei |\n\nReturns: `Options` Dasselbe `$`\n\nRuft `TOUCH(url)` auf. Ohne `url` verwendet es die URL der Anfrage; ohne Controller (eine aus dem Code aufgerufene Aktion) wird jede statische Datei gelöscht. Verwende es, nachdem die Aktion eine Datei in `public/` geändert hat. Gibt `$` zurück.\n\nExample: Nach einer Änderung\n```js\nNEWACTION('theme_save', {\n\tinput: '*css:String',\n\taction: async function($, model) {\n\t\tawait F.FsPromises.writeFile(PATH.public('css/theme.css'), model.css);\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t}\n});\n```\n\n### ACTION(name).promise([$])\n\nType: `method`\n\nGibt ein Promise mit dem Ergebnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | no |  | Das `$` einer Aktion, die die Fehler erhält |\n\nReturns: `Promise` Die Antwort\n\nLöst mit der Antwort auf. Bei einem Fehler wird es mit einem `Error` abgelehnt, dessen Nachricht die Fehler enthält; mit `$` geht der Fehler stattdessen an `$.invalid()`, und das Promise löst nicht auf.\n\nExample: Await\n```js\nvar response = await ACTION('products_list').promise();\n```\n\n### ACTION(name).user(user)\n\nType: `method`\n\nSetzt den Benutzer des Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object|Options` | yes |  | Ein Benutzerobjekt oder ein `$` |\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\nSetzt `$.user`. Wenn du ein `$` übergibst, wird dessen Benutzer verwendet.\n\nExample: Benutzer\n```js\nACTION('account_read').user({ id: '123', name: 'Peter' }).callback(console.log);\n```\n\n### ACTION(name).query(obj)\n\nType: `method`\n\nSetzt den Query-String des Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Die Query |\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\nSetzt das Objekt, das von der Option `query` validiert wird.\n\nExample: Query\n```js\nACTION('products_list').query({ page: 2 }).callback(console.log);\n```\n\n### ACTION(name).params(obj)\n\nType: `method`\n\nSetzt die URL-Parameter des Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Die Parameter |\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\nSetzt das Objekt, das von der Option `params` validiert wird.\n\nExample: Parameter\n```js\nACTION('products_read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\n### ACTION(name).ctrl(controller)\n\nType: `method`\n\nFührt den Aufruf mit einem Controller aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Ein Controller |\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\nDie Aktion erhält `$.controller` und die Request-Kurzformen. Akzeptiert einen Controller oder ein Objekt mit einer Eigenschaft `controller` (ein `$`).\n\nExample: Controller\n```js\nfunction handler($) {\n\tACTION('products_list').ctrl($).autorespond();\n}\n```\n\n### ACTION(name).autorespond()\n\nType: `method`\n\nSendet das Ergebnis an den Controller.\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\nBei einem Fehler ruft sie `controller.invalid(err)` auf; andernfalls antwortet sie über den Controller im mit `$.output()` gesetzten Format (standardmäßig JSON). Routen mit `-->` verwenden sie. Benötigt einen Controller.\n\nExample: Routen-Handler\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', function($) {\n\t\t$.action('products_list').autorespond();\n\t});\n};\n```\n\n### ACTION(name).status(fn)\n\nType: `method`\n\nEmpfängt Statusmeldungen der Aktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\nDie Aktion sendet sie mit `$.status(a, b, c, d)`; die Argumente gehen an `fn`. Ohne diese Methode tut `$.status()` nichts.\n\nExample: Status\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\t$.status('started');\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').status(console.log).callback(console.log);\n```\n\n### ACTION(name).progress(fn)\n\nType: `method` · Since: `0.0.16`\n\nEmpfängt Fortschrittsmeldungen der Aktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\nDie Aktion sendet sie mit `$.progress(a, b, c, d)`; die Argumente gehen an `fn` mit `$` als `this`. Ohne diese Methode macht `$.progress()` nichts.\n\nExample: Fortschritt\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\tfor (var i = 1; i <= 10; i++)\n\t\t\t$.progress(i * 10);\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').progress(p => console.log(p + '%')).callback(console.log);\n```\n\n### ACTION(name).config(obj)\n\nType: `method` · Since: `0.0.17`\n\nFügt Konfiguration für diesen Aufruf hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Schlüssel für `$.config` |\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\nDie Schlüssel von `obj` werden in eine Kopie der `config` der Aktion übernommen, sodass `$.config` beides enthält; die Definition der Aktion wird nicht geändert.\n\nExample: Konfiguration\n```js\nNEWACTION('report_build', {\n\tconfig: { format: 'pdf' },\n\taction: function($) {\n\t\t$.success($.config);\n\t}\n});\n\nACTION('report_build').config({ lang: 'en' }).callback(console.log);\n// { success: true, value: { format: 'pdf', lang: 'en' } }\n```\n\n### ACTION(name).env(value)\n\nType: `method`\n\nSetzt die Umgebung des Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any|Options` | yes |  | Die Umgebung, etwa `'test'`, oder ein `$` |\n\nReturns: `ActionCaller` Der Aufrufer, zum Verketten\n\nSetzt `$.env` in der Aktion. Wenn du ein `$` übergibst, wird dessen `env` verwendet, sodass ein innerer Aufruf die Umgebung des äußeren behalten kann.\n\nExample: Umgebung\n```js\nACTION('orders_sync').env('test').callback(console.log);\n```\n\nExample: Weitergeben\n```js\nNEWACTION('orders_close', {\n\taction: async function($) {\n\t\tawait $.action('orders_sync').env($).promise($);\n\t\t$.success();\n\t}\n});\n```\n\n### SUCCESS([value])\n\nType: `method`\n\nErstellt das Erfolgsobjekt, mit dem Aktionen und Controller antworten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Ein Wert für die Eigenschaft `value` |\n\nReturns: `Object` `{ success: true, value: value }`\n\nGibt `{ success: true, value: value }` zurück. Die Form stammt von `DEF.onSuccess`, derselben Funktion, die `$.success()` verwendet; ein eigenes `DEF.onSuccess` ändert also beide. Verwende sie, wenn du eine Antwort selbst aufbaust, zum Beispiel in einem Controller oder in einem Callback.\n\nExample: Eine Erfolgsantwort in einem Controller\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.json(SUCCESS(NOW));\n});\n```\n","entries":[{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, callback)","since":"","deprecated":false},{"type":"method","name":"NEWTRANSFORM()","signature":"NEWTRANSFORM(name, fn, [id])","since":"","deprecated":false},{"type":"method","name":"TRANSFORM()","signature":"TRANSFORM(name, value, [callback], [controller])","since":"","deprecated":false},{"type":"event","name":"ON('@{action}')","signature":"ON('@' + name, function($, response) {})","since":"","deprecated":false},{"type":"config","name":"NEWACTION.action","signature":"action: Function","since":"","deprecated":false},{"type":"config","name":"NEWACTION.input","signature":"input: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.output","signature":"output: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.params","signature":"params: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.query","signature":"query: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.user","signature":"user: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.permissions","signature":"permissions: String|Array","since":"","deprecated":false},{"type":"config","name":"NEWACTION.route","signature":"route: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.middleware","signature":"middleware: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.partial","signature":"partial: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.extend","signature":"extend: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.audit","signature":"audit: Boolean|String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.config","signature":"config: Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.timeout","signature":"timeout: Number","since":"0.0.16","deprecated":false},{"type":"config","name":"NEWACTION.cache","signature":"cache: true | { query, params, input, user, language, key, expire }","since":"","deprecated":false},{"type":"config","name":"NEWACTION.summary","signature":"summary: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.oninput","signature":"oninput: Function","since":"0.0.19","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.onoutput","signature":"onoutput: Function","since":"0.0.19","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.input","signature":"$.input","since":"0.0.19","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.config","signature":"$.config","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"0.0.19","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"0.0.19","deprecated":false},{"type":"property","name":"$.env","signature":"$.env","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [payload])","since":"","deprecated":false},{"type":"method","name":"$.transform()","signature":"$.transform(name, value, [callback])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized()","signature":"$.unauthorized(permission, [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"ACTION().callback()","signature":"ACTION(name).callback(fn)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"ACTION().promise()","signature":"ACTION(name).promise([$])","since":"","deprecated":false},{"type":"method","name":"ACTION().user()","signature":"ACTION(name).user(user)","since":"","deprecated":false},{"type":"method","name":"ACTION().query()","signature":"ACTION(name).query(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().params()","signature":"ACTION(name).params(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().ctrl()","signature":"ACTION(name).ctrl(controller)","since":"","deprecated":false},{"type":"method","name":"ACTION().autorespond()","signature":"ACTION(name).autorespond()","since":"","deprecated":false},{"type":"method","name":"ACTION().status()","signature":"ACTION(name).status(fn)","since":"","deprecated":false},{"type":"method","name":"ACTION().progress()","signature":"ACTION(name).progress(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ACTION().config()","signature":"ACTION(name).config(obj)","since":"0.0.17","deprecated":false},{"type":"method","name":"ACTION().env()","signature":"ACTION(name).env(value)","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([value])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwUcAPx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/actions/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Acciones","summary":"Opciones de NEWACTION(), el objeto $, los llamadores de ACTION(), NEWSCHEMA() y las transformaciones.","markdown":"---\ntitle: Acciones\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/actions/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Acciones\n\n> Opciones de NEWACTION(), el objeto $, los llamadores de ACTION(), NEWSCHEMA() y las transformaciones.\n\nLas funciones, opciones y objetos de las acciones en Total.js 5: `NEWACTION()` y sus opciones, el objeto `$` que recibe una acción, el llamador que devuelve `ACTION()`/`EXEC()`, `NEWSCHEMA()` y `NEWTRANSFORM()`/`TRANSFORM()`.\n\nPara una introducción con ejemplos, lee la guía [Acciones](../../guides/actions/). Los esquemas de `input`, `output`, `params` y `query` se describen en [Esquemas JSON](../../guides/json-schemas/).\n\n## API\n\n### NEWACTION(name, options)\n\nType: `method`\n\nDeclara una acción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la acción, p. ej. `products_create` |\n| `options` | `Object` | yes |  | La definición: `action`, `input`, `output`, `params`, `query`, `user`, `permissions`, `route` y las demás opciones |\n\nReturns: `Object` La definición de la acción\n\nRegistra la acción bajo `name` y devuelve el objeto de definición. Cuando `name` es un objeto, son las opciones y el nombre se toma de su propiedad `id` o `name`. Una acción con el mismo nombre se elimina primero (junto con su ruta). El objeto devuelto tiene `remove()`, que elimina la acción y su ruta. Todas las acciones registradas están en `F.actions`.\n\nExample: Una acción completa\n```js\nNEWACTION('products_update', {\n\tname: 'Update a product',\n\tparams: '*id:UID',\n\tinput: '*name:String, price:Number',\n\tpermissions: 'products',\n\troute: '+PUT /api/products/{id}/',\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).error(404).callback($.done($.params.id));\n\t}\n});\n```\n\nExample: Eliminar una acción\n```js\nvar action = NEWACTION('temp_test', { action: $ => $.success() });\naction.remove();\n```\n\n### ACTION(name, [payload], [controller])\n\nType: `method`\n\nEjecuta una o varias acciones desde el código.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la acción, o nombres separados por espacios; un prefijo `+` o `-` indica si la acción usa el payload |\n| `payload` | `Object` | no |  | Los datos que valida la opción `input` |\n| `controller` | `Controller` | no |  | Un controlador de una petición HTTP |\n\nReturns: `ActionCaller` El llamador con `callback()`, `promise()`, `user()` y los demás métodos\n\nDevuelve un llamador de la acción. La llamada empieza en el siguiente tick, así que estableces el usuario, la query, los parámetros y el callback encadenando métodos. `name` puede contener varias acciones separadas por espacios o comas; se ejecutan en orden con el mismo `$`. El resultado es la respuesta de la acción marcada con ` (response)`, o un objeto con las respuestas de todas las acciones por sus nombres. Una sola acción siempre es la respuesta. Con un controlador, el usuario, la query y los parámetros se toman de él.\n\nExample: Callback\n```js\nACTION('products_list').query({ search: 'mouse' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Varias acciones\n```js\nACTION('orders_create orders_notify (response)', model).user(user).callback(function(err, response) {\n\t// response is the response of orders_notify\n});\n```\n\n### EXEC(name, [payload], [controller])\n\nType: `method`\n\nUn alias de `ACTION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre o nombres de la acción |\n| `payload` | `Object` | no |  | El payload |\n| `controller` | `Controller` | no |  | Un controlador |\n\nReturns: `ActionCaller` El llamador\n\nLa misma función que `ACTION()`.\n\nExample: Promesa\n```js\nvar response = await EXEC('products_create', { name: 'Mouse' }).user(user).promise();\n```\n\n### NEWSCHEMA(name, callback)\n\nType: `method`\n\nAgrupa acciones bajo un nombre común.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del esquema |\n| `callback` | `Function|String` | yes |  | `function(schema)`, o una definición de esquema inline |\n\nReturns: `Object` Nada con un callback; el esquema JSON con una cadena\n\nLlama a `callback(schema)`; `schema.action(name, options)` declara la acción `<schema name>/<name>` con `NEWACTION()` y la devuelve. Las acciones creadas también están en `schema.actions`. Se elimina una `@` inicial del nombre. Cuando el segundo argumento es una cadena, `NEWSCHEMA()` registra en su lugar un esquema JSON con esa definición inline y lo devuelve.\n\nExample: Acciones de un esquema\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('read', {\n\t\tparams: '*id:UID',\n\t\taction: function($) {\n\t\t\tDATA.read('users').id($.params.id).error(404).callback($);\n\t\t}\n\t});\n\n});\n\nACTION('Users/read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\nExample: Un esquema JSON\n```js\nNEWSCHEMA('Address', '*street:String, *city:String, zip:Zip');\n```\n\n### NEWTRANSFORM(name, fn, [id])\n\nType: `method`\n\nAñade una función a una transformación con nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la transformación |\n| `fn` | `Function` | yes |  | `function($, value)` |\n| `id` | `String` | no |  | Un identificador para eliminar la función más tarde |\n\nReturns: `Object` Un objeto con `id`, `action` y `remove()`\n\nLas funciones de un mismo nombre se ejecutan en el orden en que se añadieron. Cada una recibe `($, value)`; modifica `value` o asigna un nuevo `$.value`, y luego llama a `$.next()`, o detiene la cadena con `$.invalid(error)` (el callback de `TRANSFORM()` recibe entonces los errores). `$.user` y `$.controller` se establecen cuando la transformación se ejecuta con un controlador. Devuelve un objeto con `remove()`. `NEWTRANSFORM(name, null, id)` elimina la función con ese `id`.\n\nExample: Añadir y eliminar\n```js\nNEWTRANSFORM('user', function($, value) {\n\tdelete value.password;\n\t$.next();\n}, 'password');\n\nNEWTRANSFORM('user', null, 'password');\n```\n\n### TRANSFORM(name, value, [callback], [controller])\n\nType: `method`\n\nEjecuta una transformación con nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la transformación |\n| `value` | `Object` | yes |  | El valor que se transforma |\n| `callback` | `Function` | no |  | `function(err, value)` |\n| `controller` | `Controller` | no |  | Un controlador; su usuario es `$.user` en las funciones |\n\nReturns: `Promise` Una Promise cuando no hay callback\n\nEjecuta todas las funciones añadidas con `NEWTRANSFORM(name)` y llama a `callback(err, value)` con el valor final. Un nombre sin funciones devuelve el valor sin cambios. Sin callback, devuelve una Promise y el tercer argumento es el controlador. La Promise se rechaza con los errores de `$.invalid()`; cuando el tercer argumento es el `$` de una acción (o un controlador), los errores van a su `invalid()`.\n\nExample: Callback\n```js\nTRANSFORM('user', user, function(err, value) {\n\tconsole.log(value);\n});\n```\n\nExample: Promise\n```js\nvar value = await TRANSFORM('user', user);\n```\n\nExample: Errores de la forma con Promise\n```js\ntry {\n\tvar value = await TRANSFORM('user', user);\n} catch (err) {\n\tconsole.log(err.toString()); // the errors of $.invalid()\n}\n```\n\n### ON('@' + name, function($, response) {})\n\nType: `event`\n\nSe emite después de que una acción responde con éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | El `$` de la acción |\n| `response` | `Object` | yes |  | La respuesta de la acción |\n\nEl nombre del evento es `@` más el nombre de la acción. Se ejecuta después de la respuesta, así que es un buen lugar para notificaciones, estadísticas o cachés. No se emite cuando la acción falla.\n\nExample: Notificación\n```js\nON('@orders_create', function($, response) {\n\tconsole.log('New order', response.value, 'by', $.user.id);\n});\n```\n\n### action: Function\n\nType: `config`\n\nLa lógica de la acción.\n\nReturns: `Function`\n\n`function($, model)`. `model` es el payload validado (lo mismo que `$.model`). La función tiene que terminar la llamada con `$.success()`, `$.callback()`, `$.invalid()` o un callback de `$.done()`. Puede ser `async`: cuando su promesa se rechaza (una excepción en la función), la llamada termina con el error `500: Internal Server Error` y la excepción se escribe en el registro de errores, así que quien llama no espera a un timeout.\n\nExample: Básico\n```js\nNEWACTION('ping', {\n\taction: function($) {\n\t\t$.success(NOW);\n\t}\n});\n```\n\n### input: String|Object\n\nType: `config`\n\nEsquema del payload.\n\nReturns: `String|Object`\n\nUn esquema inline (`'*name:String, email:Email'`) o el nombre de un esquema JSON con `@` (`'@product'`). El payload se valida y se limpia antes de que se ejecute la acción; si falla, la acción no se ejecuta y el llamador recibe los errores. Sin `input` el payload no se valida. Consulta [Esquemas JSON](../../guides/json-schemas/).\n\nExample: Esquema inline\n```js\nNEWACTION('contact_send', {\n\tinput: '*name:String, *email:Email, message:String',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### output: String|Object\n\nType: `config`\n\nEsquema de la respuesta.\n\nReturns: `String|Object`\n\nLa respuesta pasa por este esquema, así que solo los campos declarados salen de la acción. Úsalo con `$.callback()`: con `$.success()` el esquema se aplica a todo el objeto `{ success, value }`.\n\nExample: Ocultar campos\n```js\nNEWACTION('users_read', {\n\tparams: '*id:UID',\n\toutput: 'id:UID, name:String, email:Email',\n\taction: function($) {\n\t\tDATA.read('users').id($.params.id).callback($);\n\t}\n});\n```\n\n### params: String|Object\n\nType: `config`\n\nEsquema de los parámetros de la URL.\n\nReturns: `String|Object`\n\nValida `$.params`, las partes dinámicas de la ruta (`{id}`). Los errores llevan el prefijo `params.`.\n\nExample: Parámetro\n```js\nNEWACTION('products_remove', {\n\tparams: '*id:UID',\n\troute: '+DELETE /api/products/{id}/',\n\taction: function($) {\n\t\tDATA.remove('products').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### query: String|Object\n\nType: `config`\n\nEsquema de la query string.\n\nReturns: `String|Object`\n\nValida `$.query`. Los errores llevan el prefijo `query.`.\n\nExample: Query\n```js\nNEWACTION('products_search', {\n\tquery: '*q:String, page:Number',\n\troute: 'GET /api/products/search/',\n\taction: function($) {\n\t\tDATA.find('products').search('name', $.query.q).callback($);\n\t}\n});\n```\n\n### user: Boolean\n\nType: `config`\n\nExige un usuario con sesión iniciada o un usuario anónimo.\n\nReturns: `Boolean`\n\n`true`: la acción falla con 401 cuando `$.user` está vacío. `false`: falla con 401 cuando hay un usuario. Las opciones `sa: true` o `su: true` exigen un usuario con el flag `sa` o `su`.\n\nExample: Usuario con sesión iniciada\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### permissions: String|Array\n\nType: `config`\n\nPermisos necesarios.\n\nReturns: `String|Array`\n\nUna cadena separada por comas o puntos y comas, o un array. El usuario necesita al menos uno de ellos en `user.permissions` o `user.roles` (un array o un objeto); los usuarios `sa` y `su` pasan siempre. En caso contrario, la acción falla con 401.\n\nExample: Permisos\n```js\nNEWACTION('invoices_remove', {\n\tpermissions: 'invoices_remove,admin',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tDATA.remove('invoices').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### route: String\n\nType: `config`\n\nUna ruta que ejecuta la acción.\n\nReturns: `String`\n\nUn string de ruta como en [Enrutamiento](../../guides/routing/) (`'+POST /api/products/'`). El framework añade ` --> <name>` y crea la ruta; la opción contiene entonces el objeto de la ruta. `url` es la misma opción con otro nombre. Con `encrypt: true` la ruta recibe el flag `@encrypt`.\n\n`route: true` crea un endpoint `API ?` con el nombre de la acción (`+API ?` cuando la acción tiene la opción `user` o `permissions`).\n\nExample: Ruta\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: Endpoint de API\n```js\nNEWACTION('products_list', {\n\troute: '+API ?',\n\taction: function($) {\n\t\tDATA.find('products').callback($);\n\t}\n});\n```\n\n### middleware: String\n\nType: `config`\n\nMiddleware que se ejecuta antes de la acción.\n\nReturns: `String`\n\nNombres de middleware registrados con `MIDDLEWARE()`, separados por espacios, comas o `|`. Cada uno se ejecuta como `fn($, next)` antes de la acción; un middleware que no existe se registra en el log y se omite. Consulta [Middleware](../../guides/middleware/).\n\nExample: Middleware\n```js\nNEWACTION('reports_build', {\n\tmiddleware: 'ratelimit',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### partial: Boolean\n\nType: `config`\n\nValida la entrada parcialmente.\n\nReturns: `Boolean`\n\nCon `true`, `input` valida solo los campos presentes en el payload y no comprueba los campos obligatorios. Útil para actualizaciones con `PATCH`.\n\nExample: Patch\n```js\nNEWACTION('products_patch', {\n\tparams: '*id:UID',\n\tinput: '*name:String, *price:Number',\n\tpartial: true,\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).callback($.done());\n\t}\n});\n```\n\n### extend: String\n\nType: `config`\n\nAñade la respuesta al payload.\n\nReturns: `String`\n\nLa respuesta se guarda en el payload bajo esta clave (se admite una ruta con puntos) y el payload completo pasa a ser la respuesta. Sin payload se usa un objeto vacío. Útil en una cadena de acciones que construyen un único objeto.\n\nExample: Extend\n```js\nNEWACTION('order_totals', {\n\textend: 'totals',\n\taction: function($, model) {\n\t\t$.callback({ count: 3, price: 120 });\n\t}\n});\n// response: { ...payload, totals: { count: 3, price: 120 } }\n```\n\n### audit: Boolean|String\n\nType: `config`\n\nEscribe un registro de auditoría tras el éxito.\n\nReturns: `Boolean|String`\n\n`true` escribe un registro sin mensaje; una cadena es una plantilla de Tangular renderizada con `$` (`'{{ $.user.name }} created {{ $.model.name }}'`). El registro contiene el usuario, la IP, la URL, el nombre de la acción y los datos, y va a `DEF.onAudit` (por defecto, el archivo `logs/actions.log`).\n\nExample: Mensaje de auditoría\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taudit: '{{ $.user.name }} created {{ $.model.name }}',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### config: Object\n\nType: `config`\n\nConfiguración personalizada de la acción.\n\nReturns: `Object`\n\nCualquier objeto; está disponible como `$.config` en la acción, así que una función puede servir a varias acciones.\n\nExample: Lógica compartida\n```js\nfunction list($) {\n\tDATA.find($.config.table).callback($);\n}\n\nNEWACTION('products_list', { config: { table: 'products' }, action: list });\nNEWACTION('orders_list', { config: { table: 'orders' }, action: list });\n```\n\n### timeout: Number\n\nType: `config` · Since: `0.0.16`\n\nUn límite de tiempo de la acción.\n\nReturns: `Number`\n\nEn milisegundos. Cuando la acción no responde a tiempo, falla con el error `Timeout.`; una respuesta posterior se ignora.\n\nExample: Timeout\n```js\nNEWACTION('reports_export', {\n\ttimeout: 10000,\n\taction: function($) {\n\t\tsetTimeout(() => $.success(), 2000);\n\t}\n});\n```\n\n### cache: true | { query, params, input, user, language, key, expire }\n\nType: `config`\n\nGuarda la respuesta de la acción en la caché.\n\nReturns: `Boolean|Object`\n\nLa primera respuesta correcta se guarda en la caché (`CACHE`) y las llamadas siguientes reciben una copia: el middleware y la acción no se ejecutan. La respuesta se copia tanto al guardarla como al leerla, así que quien llama puede cambiar su copia sin problemas. Los errores no se guardan en la caché.\n\nCon `true` la acción tiene una sola respuesta en caché. Un objeto crea una entrada para cada combinación de valores:\n\n| Clave | Valor |\n| --- | --- |\n| `query`, `params`, `input` | `true` (todos los campos del esquema de la acción) o una lista de campos separados por comas |\n| `user` | `true` (`$.user.id`) o una lista de claves de `$.user` separadas por comas |\n| `language` | `true`: una entrada para cada `$.language` |\n| `key` | Un nombre para las entradas; `CACHE.reset('action|' + key + '|')` las elimina |\n| `expire` | Cuánto tiempo se guarda una entrada, por defecto `'5 minutes'` |\n\nSin `user`, todos los usuarios comparten la misma respuesta en caché.\n\nExample: Una lista en caché por página\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number,category:String',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').where('category', $.query.category).page($.query.page, 20).callback($);\n\t}\n});\n\n// after a product is saved\nCACHE.reset('action|products|');\n```\n\nExample: Una entrada por usuario\n```js\nNEWACTION('Account|profile', {\n\tuser: true,\n\tcache: { user: true, expire: '1 minute' },\n\taction: function($) {\n\t\tDATA.read('users').id($.user.id).callback($);\n\t}\n});\n```\n\n### summary: String\n\nType: `config`\n\nUna descripción de la acción.\n\nReturns: `String`\n\nTexto libre sobre lo que hace la acción. El [servidor MCP](../../guides/mcp-server/) lo envía a los clientes de IA como descripción de la herramienta; sin `summary` envía la opción `name`.\n\nExample: Resumen\n```js\nNEWACTION('tasks_create', {\n\tsummary: 'Creates a task and returns its ID',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### oninput: Function\n\nType: `config` · Since: `0.0.19`\n\nSe llama justo antes de la acción.\n\nReturns: `Function`\n\n`function($)`. Se ejecuta después de la validación y del middleware, así que `$.model`, `$.params` y `$.query` están listos y puedes modificarlos.\n\nExample: Preparar datos\n```js\nNEWACTION('notes_create', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.model.body = $.model.body.trim();\n\t},\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### mcp: Boolean\n\nType: `config`\n\nConvierte la acción en una herramienta del servidor MCP.\n\nReturns: `Boolean`\n\nCon `true` y la clave de configuración `$mcp`, los clientes de IA pueden listar y llamar a la acción en `POST /$mcp/`. Los esquemas `input`, `query` y `params` se convierten en los argumentos de la herramienta. Consulta [Servidor MCP](../../guides/mcp-server/).\n\nExample: Una herramienta\n```js\nNEWACTION('tasks_list', {\n\tsummary: 'Lists the tasks',\n\tmcp: true,\n\taction: function($) {\n\t\tNOSQL('tasks').find().callback($);\n\t}\n});\n```\n\n### onoutput: Function\n\nType: `config` · Since: `0.0.19`\n\nSe llama después de que la acción responde.\n\nReturns: `Function`\n\n`function(err, response, $)`. Se ejecuta después de entregar una respuesta correcta, así que `err` es `null`; no se llama cuando la acción falla.\n\nExample: Log\n```js\nNEWACTION('orders_create', {\n\tinput: '*productid:UID',\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, $.user ? $.user.id : '', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### $.model\n\nType: `property`\n\nEl payload validado.\n\nReturns: `Object`\n\nEl payload después de la validación de `input`, o el payload sin procesar si no hay `input`. `$.payload` y `$.value` son el mismo valor; también puedes asignarlo. También es el segundo argumento de `action`.\n\nExample: Model\n```js\naction: function($) {\n\tvar name = $.model.name;\n\t$.success(name);\n}\n```\n\n### $.input\n\nType: `property` · Since: `0.0.19`\n\nOtro nombre de `$.model`.\n\nReturns: `Object`\n\nLee y asigna el mismo valor que `$.model`.\n\nExample: Entrada\n```js\noninput: function($) {\n\t$.input.email = $.input.email.toLowerCase();\n}\n```\n\n### $.params\n\nType: `property`\n\nLos parámetros de la URL.\n\nReturns: `Object`\n\nLos valida la opción `params`. En una petición HTTP contiene las partes dinámicas de la ruta; desde el código se establece con `ACTION().params()`.\n\nExample: Params\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback($);\n}\n```\n\n### $.query\n\nType: `property`\n\nLa query string.\n\nReturns: `Object`\n\nLa valida la opción `query`. Desde el código se establece con `ACTION().query()`.\n\nExample: Query\n```js\naction: function($) {\n\tvar page = $.query.page || 1;\n\t$.success(page);\n}\n```\n\n### $.user\n\nType: `property`\n\nEl usuario actual.\n\nReturns: `Object`\n\nEl usuario de la petición HTTP (consulta [Autorización](../../guides/authorization/)), o el usuario establecido con `ACTION().user()`. Vacío en las llamadas anónimas.\n\nExample: Usuario\n```js\naction: function($) {\n\t$.success($.user.name);\n}\n```\n\n### $.config\n\nType: `property`\n\nLa opción `config` de la acción.\n\nReturns: `Object`\n\nUn objeto vacío cuando la acción no tiene `config`.\n\nExample: Config\n```js\naction: function($) {\n\t$.success($.config.table);\n}\n```\n\n### $.id\n\nType: `property`\n\nEl nombre de la acción en ejecución.\n\nReturns: `String`\n\nEn una cadena de acciones, el nombre de la actual.\n\nExample: Nombre\n```js\naction: function($) {\n\tconsole.log('Running', $.id);\n\t$.success();\n}\n```\n\n### $.controller\n\nType: `property`\n\nEl controlador de la petición HTTP.\n\nReturns: `Controller`\n\n`undefined` cuando la acción se llama desde el código sin controlador. `$.client` es lo mismo; `$.websocket` se establece cuando el controlador es un cliente WebSocket.\n\nExample: Controlador\n```js\naction: function($) {\n\t$.success($.controller ? $.controller.url : 'code');\n}\n```\n\n### $.error\n\nType: `property`\n\nLos errores de la llamada.\n\nReturns: `ErrorBuilder`\n\nUn `ErrorBuilder`. `$.invalid()` añade errores; `$.error.length` es el número de errores.\n\nExample: Errores\n```js\naction: function($) {\n\tif (!$.model.items.length) {\n\t\t$.invalid('No items', 'items');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.response\n\nType: `property`\n\nLas respuestas de las acciones de una cadena.\n\nReturns: `Object`\n\nUn objeto con las respuestas de las acciones que ya terminaron en la misma llamada, por sus nombres. La siguiente acción de la cadena puede usarlas.\n\nExample: Respuesta anterior\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tvar created = $.response.orders_create;\n\t\t$.success(created);\n\t}\n});\n```\n\n### $.xhr\n\nType: `property` · Since: `0.0.19`\n\nSi la petición es una petición XHR.\n\nReturns: `Boolean`\n\n`true` cuando la petición HTTP tiene la cabecera `X-Requested-With: XMLHttpRequest`; `null` sin controlador.\n\nExample: XHR\n```js\naction: function($) {\n\tif ($.xhr)\n\t\t$.success();\n\telse\n\t\t$.redirect('/');\n}\n```\n\n### $.meta\n\nType: `property` · Since: `0.0.19`\n\nLa definición de la acción.\n\nReturns: `Object`\n\nEl objeto pasado a `NEWACTION()`, con todas sus opciones.\n\nExample: Meta\n```js\naction: function($) {\n\t$.success($.meta.name);\n}\n```\n\n### $.env\n\nType: `property`\n\nEl entorno de la llamada.\n\nReturns: `Any`\n\nEl valor pasado a `ACTION().env()`; `undefined` cuando no está establecido. Úsalo para indicar a la acción desde dónde se la llama, por ejemplo desde un test o un job. `$.action()` no lo transmite: llama a `.env($)` en la llamada interna.\n\nExample: Entorno\n```js\nNEWACTION('orders_sync', {\n\taction: function($) {\n\t\tif ($.env === 'test') {\n\t\t\t$.success();\n\t\t\treturn;\n\t\t}\n\t\t$.success('synced');\n\t}\n});\n\nACTION('orders_sync').env('test').callback(console.log);\n```\n\n### $.ip\n\nType: `property`\n\nAtajos a los datos de la petición.\n\nReturns: `String`\n\n`$.ip`, `$.address`, `$.headers`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.split2`, `$.files`, `$.body`, `$.mobile`, `$.ua`, `$.language` y `$.sessionid` leen las mismas propiedades del controlador. Sin controlador están vacíos (`null`, `''` o un array vacío).\n\nExample: IP y agente\n```js\naction: function($) {\n\t$.success({ ip: $.ip, ua: $.ua });\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nTermina la acción con un objeto de éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Un valor para la propiedad `value` |\n\nResponde con `{ success: true, value: value }` (la forma la define `DEF.onSuccess`). Sin valor, `value` es `undefined`.\n\nExample: Éxito\n```js\naction: function($) {\n\t$.success(UID());\n}\n```\n\n### $.invalid(error, [path], [index])\n\nType: `method`\n\nTermina la acción con un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number|Error` | yes |  | El error, o un código de estado HTTP |\n| `path` | `String` | no |  | El campo al que pertenece el error |\n| `index` | `Number` | no |  | El índice del elemento en un array |\n\nReturns: `ErrorBuilder` Los errores\n\nAñade el error a `$.error` y hace fallar la llamada. Un número mayor que 399 es un estado HTTP (`401`, `404`); una cadena es un mensaje de error. El callback del llamador recibe el `ErrorBuilder` y una ruta responde con los errores. Devuelve `$.error`.\n\nExample: No encontrado\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.callback(response);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n}\n```\n\n### $.callback([value])\n\nType: `method`\n\nTermina la acción con un valor tal cual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | La respuesta |\n\nReturns: `Function` Un callback cuando se llama sin argumentos\n\nResponde con `value` sin envolverlo. Sin argumentos, devuelve un callback `function(err, response)` que añade `err` a los errores y responde con `response`. `$.pipe` es el mismo método. También puedes pasar el propio `$` al `callback()` de una base de datos.\n\nExample: Valor\n```js\naction: function($) {\n\t$.callback({ count: 5 });\n}\n```\n\nExample: Callback de una consulta\n```js\naction: function($) {\n\tDATA.find('products').callback($.callback());\n}\n```\n\n### $.done([value])\n\nType: `method`\n\nDevuelve un callback que termina la acción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | El valor del objeto de éxito, o `true` para la respuesta |\n\nReturns: `Function` `function(err, response)`\n\nDevuelve `function(err, response)`. Un error termina la acción con el error; si no, llama a `$.success(value)`, o a `$.success(response)` cuando `value` es `true`.\n\nExample: Done\n```js\naction: function($, model) {\n\tmodel.id = UID();\n\tDATA.insert('products', model).callback($.done(model.id));\n}\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method`\n\nLlama a una función con callback como una Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Una función cuyo último argumento es `function(err, response)` |\n| `a` | `Object` | no |  | Primer argumento |\n| `b` | `Object` | no |  | Segundo argumento |\n| `c` | `Object` | no |  | Tercer argumento |\n\nReturns: `Promise` La respuesta\n\nLlama a `fn(a, b, c, callback)` y se resuelve con la respuesta. Un error termina la acción con `$.invalid()` y la Promise nunca se resuelve.\n\nExample: Promisify\n```js\naction: async function($) {\n\tvar files = await $.promisify(F.Fs.readdir, PATH.public());\n\t$.success(files);\n}\n```\n\n### $.action(name, [payload])\n\nType: `method`\n\nEjecuta otra acción desde una acción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre o nombres de la acción |\n| `payload` | `Object` | no |  | El payload |\n\nReturns: `ActionCaller` El llamador\n\nIgual que `ACTION()` con el controlador de esta acción. Sin controlador, la nueva llamada recibe el usuario, la query y los parámetros de esta.\n\nExample: Acción anidada\n```js\naction: async function($, model) {\n\tvar response = await $.action('stock_check', model).promise($);\n\t$.success(response);\n}\n```\n\n### $.transform(name, value, [callback])\n\nType: `method`\n\nEjecuta una transformación con el controlador de la acción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la transformación |\n| `value` | `Object` | yes |  | El valor |\n| `callback` | `Function` | no |  | `function(err, value)` |\n\nReturns: `Promise` Una Promise sin callback\n\nIgual que `TRANSFORM()`, con el controlador (y su usuario) de la acción. Sin callback devuelve una Promise.\n\nExample: Transformar\n```js\naction: async function($) {\n\tvar user = await DATA.read('users').id($.params.id).promise($);\n\t$.callback(await $.transform('user', user));\n}\n```\n\n### $.unauthorized(permission, [permission2], [...])\n\nType: `method`\n\nComprueba los permisos del usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | yes |  | Un nombre de permiso; pueden seguir más |\n\nReturns: `Boolean` `true` cuando el usuario no tiene permiso\n\nDevuelve `false` cuando `$.user` tiene al menos uno de los permisos (en `permissions` o `roles`) o es `sa`/`su`. En caso contrario, llama a `$.invalid(401)` y devuelve `true`, así que solo tienes que hacer return.\n\nExample: Comprobar\n```js\naction: function($) {\n\tif ($.unauthorized('reports'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.redirect(url)\n\nType: `method`\n\nRedirige la petición HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL de destino |\n\nRedirige el controlador a `url` y cancela la acción; el llamador no recibe respuesta.\n\nExample: Redirección\n```js\naction: function($) {\n\t$.redirect('/login/');\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nTermina la acción con un mensaje y registra el error real.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | El error para quien llama, o un código de estado HTTP |\n| `error` | `Error|String` | no |  | El error para el log |\n\nReturns: `ErrorBuilder` Los errores\n\nAñade `message` a `$.error` y hace fallar la llamada, como `$.invalid(message)`. `error` se escribe en el log de errores con `F.error()` (se añaden el nombre de la acción y la URL) y no se envía a quien llama. Úsalo cuando el error tiene detalles que el cliente no debe ver. Devuelve `$.error`.\n\nExample: Ocultar los detalles\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n### ACTION(name).callback(fn)\n\nType: `method`\n\nRecibe el resultado de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Options` | yes |  | `function(err, response)` o un `$` |\n\nReturns: `ActionCaller` El llamador, para encadenar\n\n`fn(err, response)`; `err` es un `ErrorBuilder` o `null`. Cuando pasas el `$` de otra acción, los errores van a su `$.invalid()` y la respuesta a su `$.callback()`. `.pipe()` es el mismo método.\n\nExample: Callback\n```js\nACTION('products_list').callback(function(err, response) {\n\tconsole.log(err ? err.toString() : response);\n});\n```\n\nExample: Pasar a otra acción\n```js\naction: function($) {\n\tACTION('products_list').user($).callback($);\n}\n```\n\n### $.throw(error)\n\nType: `method`\n\nEscribe un error en el log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | El error |\n\nReturns: `Options` El mismo `$`\n\nPasa `error` al manejador de errores del framework (`DEF.onError`) con el nombre de la acción y la URL: se imprime, se guarda en `F.errors` y se emite como el evento `error`. La acción continúa; para terminarla, llama a `$.invalid()`. Devuelve `$`.\n\nExample: Registrar y continuar\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tNOSQL('notifications').insert({ type: 'order', dtcreated: NOW }).callback(function(err) {\n\t\t\terr && $.throw(err);\n\t\t});\n\t\t$.success();\n\t}\n});\n```\n\n### $.touch([url])\n\nType: `method`\n\nBorra el estado en caché de un archivo estático.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | La URL del archivo |\n\nReturns: `Options` El mismo `$`\n\nLlama a `TOUCH(url)`. Sin `url` usa la URL de la petición; sin controlador (una acción llamada desde el código) se borran todos los archivos estáticos. Úsalo después de que la acción cambie un archivo en `public/`. Devuelve `$`.\n\nExample: Después de un cambio\n```js\nNEWACTION('theme_save', {\n\tinput: '*css:String',\n\taction: async function($, model) {\n\t\tawait F.FsPromises.writeFile(PATH.public('css/theme.css'), model.css);\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t}\n});\n```\n\n### ACTION(name).promise([$])\n\nType: `method`\n\nDevuelve una Promise con el resultado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | no |  | El `$` de una acción que recibe los errores |\n\nReturns: `Promise` La respuesta\n\nSe resuelve con la respuesta. Si hay un error, se rechaza con un `Error` cuyo mensaje contiene los errores; con `$`, el error va en su lugar a `$.invalid()` y la Promise no se resuelve.\n\nExample: Await\n```js\nvar response = await ACTION('products_list').promise();\n```\n\n### ACTION(name).user(user)\n\nType: `method`\n\nEstablece el usuario de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object|Options` | yes |  | Un objeto de usuario, o un `$` |\n\nReturns: `ActionCaller` El llamador, para encadenar\n\nEstablece `$.user`. Cuando pasas un `$`, se usa su usuario.\n\nExample: Usuario\n```js\nACTION('account_read').user({ id: '123', name: 'Peter' }).callback(console.log);\n```\n\n### ACTION(name).query(obj)\n\nType: `method`\n\nEstablece la query string de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | La query |\n\nReturns: `ActionCaller` El llamador, para encadenar\n\nEstablece el objeto que valida la opción `query`.\n\nExample: Query\n```js\nACTION('products_list').query({ page: 2 }).callback(console.log);\n```\n\n### ACTION(name).params(obj)\n\nType: `method`\n\nEstablece los parámetros de la URL de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Los parámetros |\n\nReturns: `ActionCaller` El llamador, para encadenar\n\nEstablece el objeto que valida la opción `params`.\n\nExample: Params\n```js\nACTION('products_read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\n### ACTION(name).ctrl(controller)\n\nType: `method`\n\nEjecuta la llamada con un controlador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Un controlador |\n\nReturns: `ActionCaller` El llamador, para encadenar\n\nLa acción recibe `$.controller` y los atajos de la petición. Acepta un controlador o un objeto con una propiedad `controller` (un `$`).\n\nExample: Controlador\n```js\nfunction handler($) {\n\tACTION('products_list').ctrl($).autorespond();\n}\n```\n\n### ACTION(name).autorespond()\n\nType: `method`\n\nEnvía el resultado al controlador.\n\nReturns: `ActionCaller` El llamador, para encadenar\n\nSi hay un error, llama a `controller.invalid(err)`; si no, responde con el controlador en el formato establecido por `$.output()` (JSON por defecto). Las rutas con `-->` lo usan. Necesita un controlador.\n\nExample: Handler de ruta\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', function($) {\n\t\t$.action('products_list').autorespond();\n\t});\n};\n```\n\n### ACTION(name).status(fn)\n\nType: `method`\n\nRecibe mensajes de estado de la acción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` El llamador, para encadenar\n\nLa acción los envía con `$.status(a, b, c, d)`; los argumentos van a `fn`. Sin este método, `$.status()` no hace nada.\n\nExample: Estado\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\t$.status('started');\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').status(console.log).callback(console.log);\n```\n\n### ACTION(name).progress(fn)\n\nType: `method` · Since: `0.0.16`\n\nRecibe mensajes de progreso de la acción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` El llamador, para encadenar\n\nLa acción los envía con `$.progress(a, b, c, d)`; los argumentos van a `fn` con `$` como `this`. Sin este método, `$.progress()` no hace nada.\n\nExample: Progreso\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\tfor (var i = 1; i <= 10; i++)\n\t\t\t$.progress(i * 10);\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').progress(p => console.log(p + '%')).callback(console.log);\n```\n\n### ACTION(name).config(obj)\n\nType: `method` · Since: `0.0.17`\n\nAñade configuración para esta llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Claves para `$.config` |\n\nReturns: `ActionCaller` El llamador, para encadenar\n\nLas claves de `obj` se fusionan en una copia del `config` de la acción, así `$.config` contiene ambas; la definición de la acción no cambia.\n\nExample: Config\n```js\nNEWACTION('report_build', {\n\tconfig: { format: 'pdf' },\n\taction: function($) {\n\t\t$.success($.config);\n\t}\n});\n\nACTION('report_build').config({ lang: 'en' }).callback(console.log);\n// { success: true, value: { format: 'pdf', lang: 'en' } }\n```\n\n### ACTION(name).env(value)\n\nType: `method`\n\nEstablece el entorno de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any|Options` | yes |  | El entorno, como `'test'`, o un `$` |\n\nReturns: `ActionCaller` El llamador, para encadenar\n\nEstablece `$.env` en la acción. Cuando pasas un `$`, se usa su `env`, así una llamada interna puede conservar el entorno de la externa.\n\nExample: Entorno\n```js\nACTION('orders_sync').env('test').callback(console.log);\n```\n\nExample: Transmitirlo\n```js\nNEWACTION('orders_close', {\n\taction: async function($) {\n\t\tawait $.action('orders_sync').env($).promise($);\n\t\t$.success();\n\t}\n});\n```\n\n### SUCCESS([value])\n\nType: `method`\n\nCrea el objeto de éxito con el que responden las acciones y los controladores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Un valor para la propiedad `value` |\n\nReturns: `Object` `{ success: true, value: value }`\n\nDevuelve `{ success: true, value: value }`. La forma la define `DEF.onSuccess`, la misma función que usa `$.success()`, así que un `DEF.onSuccess` personalizado cambia ambos. Úsalo cuando construyas una respuesta tú mismo, por ejemplo en un controlador o en un callback.\n\nExample: Una respuesta de éxito en un controlador\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.json(SUCCESS(NOW));\n});\n```\n","entries":[{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, callback)","since":"","deprecated":false},{"type":"method","name":"NEWTRANSFORM()","signature":"NEWTRANSFORM(name, fn, [id])","since":"","deprecated":false},{"type":"method","name":"TRANSFORM()","signature":"TRANSFORM(name, value, [callback], [controller])","since":"","deprecated":false},{"type":"event","name":"ON('@{action}')","signature":"ON('@' + name, function($, response) {})","since":"","deprecated":false},{"type":"config","name":"NEWACTION.action","signature":"action: Function","since":"","deprecated":false},{"type":"config","name":"NEWACTION.input","signature":"input: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.output","signature":"output: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.params","signature":"params: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.query","signature":"query: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.user","signature":"user: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.permissions","signature":"permissions: String|Array","since":"","deprecated":false},{"type":"config","name":"NEWACTION.route","signature":"route: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.middleware","signature":"middleware: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.partial","signature":"partial: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.extend","signature":"extend: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.audit","signature":"audit: Boolean|String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.config","signature":"config: Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.timeout","signature":"timeout: Number","since":"0.0.16","deprecated":false},{"type":"config","name":"NEWACTION.cache","signature":"cache: true | { query, params, input, user, language, key, expire }","since":"","deprecated":false},{"type":"config","name":"NEWACTION.summary","signature":"summary: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.oninput","signature":"oninput: Function","since":"0.0.19","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.onoutput","signature":"onoutput: Function","since":"0.0.19","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.input","signature":"$.input","since":"0.0.19","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.config","signature":"$.config","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"0.0.19","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"0.0.19","deprecated":false},{"type":"property","name":"$.env","signature":"$.env","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [payload])","since":"","deprecated":false},{"type":"method","name":"$.transform()","signature":"$.transform(name, value, [callback])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized()","signature":"$.unauthorized(permission, [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"ACTION().callback()","signature":"ACTION(name).callback(fn)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"ACTION().promise()","signature":"ACTION(name).promise([$])","since":"","deprecated":false},{"type":"method","name":"ACTION().user()","signature":"ACTION(name).user(user)","since":"","deprecated":false},{"type":"method","name":"ACTION().query()","signature":"ACTION(name).query(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().params()","signature":"ACTION(name).params(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().ctrl()","signature":"ACTION(name).ctrl(controller)","since":"","deprecated":false},{"type":"method","name":"ACTION().autorespond()","signature":"ACTION(name).autorespond()","since":"","deprecated":false},{"type":"method","name":"ACTION().status()","signature":"ACTION(name).status(fn)","since":"","deprecated":false},{"type":"method","name":"ACTION().progress()","signature":"ACTION(name).progress(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ACTION().config()","signature":"ACTION(name).config(obj)","since":"0.0.17","deprecated":false},{"type":"method","name":"ACTION().env()","signature":"ACTION(name).env(value)","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([value])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwUcAPx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/actions/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Actions","summary":"Options de NEWACTION(), l'objet $, appelants de ACTION(), NEWSCHEMA() et transformations.","markdown":"---\ntitle: Actions\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/actions/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Actions\n\n> Options de NEWACTION(), l'objet $, appelants de ACTION(), NEWSCHEMA() et transformations.\n\nLes fonctions, options et objets des actions dans Total.js 5 : `NEWACTION()` et ses options, l'objet `$` transmis à une action, l'appelant retourné par `ACTION()`/`EXEC()`, `NEWSCHEMA()`, ainsi que `NEWTRANSFORM()`/`TRANSFORM()`.\n\nPour une introduction avec des exemples, lis le guide [Actions](../../guides/actions/). Les schémas pour `input`, `output`, `params` et `query` sont décrits dans [Schémas JSON](../../guides/json-schemas/).\n\n## API\n\n### NEWACTION(name, options)\n\nType: `method`\n\nDéclare une action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'action, par exemple `products_create` |\n| `options` | `Object` | yes |  | La définition : `action`, `input`, `output`, `params`, `query`, `user`, `permissions`, `route` et les autres options |\n\nReturns: `Object` La définition de l'action\n\nEnregistre l'action sous `name` et renvoie l'objet de définition. Quand `name` est un objet, ce sont les options et le nom est pris de sa propriété `id` ou `name`. Une action portant le même nom est d'abord supprimée (avec sa route). L'objet renvoyé possède `remove()`, qui supprime l'action et sa route. Toutes les actions enregistrées se trouvent dans `F.actions`.\n\nExample: Une action complète\n```js\nNEWACTION('products_update', {\n\tname: 'Update a product',\n\tparams: '*id:UID',\n\tinput: '*name:String, price:Number',\n\tpermissions: 'products',\n\troute: '+PUT /api/products/{id}/',\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).error(404).callback($.done($.params.id));\n\t}\n});\n```\n\nExample: Supprimer une action\n```js\nvar action = NEWACTION('temp_test', { action: $ => $.success() });\naction.remove();\n```\n\n### ACTION(name, [payload], [controller])\n\nType: `method`\n\nExécute une ou plusieurs actions depuis le code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'action, ou noms séparés par des espaces ; un préfixe `+` ou `-` indique si l'action utilise le payload |\n| `payload` | `Object` | no |  | Les données validées par l'option `input` |\n| `controller` | `Controller` | no |  | Un contrôleur d'une requête HTTP |\n\nReturns: `ActionCaller` L'appelant avec `callback()`, `promise()`, `user()` et les autres méthodes\n\nRetourne un appelant d'action. L'appel démarre au tick suivant : définis donc l'utilisateur, la query, les paramètres et le callback par chaînage. `name` peut contenir plusieurs actions séparées par des espaces ou des virgules ; elles s'exécutent dans l'ordre avec le même `$`. Le résultat est la réponse de l'action marquée ` (response)`, ou un objet contenant les réponses de toutes les actions par leur nom. Une action unique est toujours la réponse. Avec un contrôleur, l'utilisateur, la query et les paramètres sont pris depuis celui-ci.\n\nExample: Callback\n```js\nACTION('products_list').query({ search: 'mouse' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Plusieurs actions\n```js\nACTION('orders_create orders_notify (response)', model).user(user).callback(function(err, response) {\n\t// response is the response of orders_notify\n});\n```\n\n### EXEC(name, [payload], [controller])\n\nType: `method`\n\nUn alias de `ACTION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom ou noms de l'action |\n| `payload` | `Object` | no |  | Le payload |\n| `controller` | `Controller` | no |  | Un contrôleur |\n\nReturns: `ActionCaller` L'appelant\n\nLa même fonction que `ACTION()`.\n\nExample: Promesse\n```js\nvar response = await EXEC('products_create', { name: 'Mouse' }).user(user).promise();\n```\n\n### NEWSCHEMA(name, callback)\n\nType: `method`\n\nRegroupe des actions sous un nom commun.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du schéma |\n| `callback` | `Function|String` | yes |  | `function(schema)`, ou une définition de schéma inline |\n\nReturns: `Object` Rien pour un callback ; le schéma JSON pour une chaîne\n\nAppelle `callback(schema)` ; `schema.action(name, options)` déclare l'action `<schema name>/<name>` avec `NEWACTION()` et la retourne. Les actions créées se trouvent aussi dans `schema.actions`. Un `@` en début de nom est supprimé. Lorsque le second argument est une chaîne, `NEWSCHEMA()` enregistre à la place un schéma JSON avec cette définition inline, et le retourne.\n\nExample: Actions d'un schéma\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('read', {\n\t\tparams: '*id:UID',\n\t\taction: function($) {\n\t\t\tDATA.read('users').id($.params.id).error(404).callback($);\n\t\t}\n\t});\n\n});\n\nACTION('Users/read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\nExample: Un schéma JSON\n```js\nNEWSCHEMA('Address', '*street:String, *city:String, zip:Zip');\n```\n\n### NEWTRANSFORM(name, fn, [id])\n\nType: `method`\n\nAjoute une fonction à une transformation nommée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la transformation |\n| `fn` | `Function` | yes |  | `function($, value)` |\n| `id` | `String` | no |  | Un identifiant pour supprimer la fonction plus tard |\n\nReturns: `Object` Un objet avec `id`, `action` et `remove()`\n\nLes fonctions d'un même nom s'exécutent dans l'ordre où elles ont été ajoutées. Chacune reçoit `($, value)` ; elle modifie `value` ou assigne une nouvelle `$.value`, puis appelle `$.next()`, ou arrête la chaîne avec `$.invalid(error)` (le callback de `TRANSFORM()` reçoit alors les erreurs). `$.user` et `$.controller` sont définis quand la transformation est exécutée avec un contrôleur. Renvoie un objet avec `remove()`. `NEWTRANSFORM(name, null, id)` supprime la fonction ayant cet `id`.\n\nExample: Ajouter et supprimer\n```js\nNEWTRANSFORM('user', function($, value) {\n\tdelete value.password;\n\t$.next();\n}, 'password');\n\nNEWTRANSFORM('user', null, 'password');\n```\n\n### TRANSFORM(name, value, [callback], [controller])\n\nType: `method`\n\nExécute une transformation nommée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la transformation |\n| `value` | `Object` | yes |  | La valeur à transformer |\n| `callback` | `Function` | no |  | `function(err, value)` |\n| `controller` | `Controller` | no |  | Un contrôleur ; son utilisateur est `$.user` dans les fonctions |\n\nReturns: `Promise` Une Promise lorsqu'il n'y a pas de callback\n\nExécute toutes les fonctions ajoutées avec `NEWTRANSFORM(name)` et appelle `callback(err, value)` avec la valeur finale. Un nom sans fonctions renvoie la valeur inchangée. Sans callback, elle renvoie une Promise et le troisième argument est le contrôleur. La Promise est rejetée avec les erreurs de `$.invalid()` ; quand le troisième argument est le `$` d'une action (ou un contrôleur), les erreurs vont plutôt à son `invalid()`.\n\nExample: Callback\n```js\nTRANSFORM('user', user, function(err, value) {\n\tconsole.log(value);\n});\n```\n\nExample: Promise\n```js\nvar value = await TRANSFORM('user', user);\n```\n\nExample: Erreurs de la forme Promise\n```js\ntry {\n\tvar value = await TRANSFORM('user', user);\n} catch (err) {\n\tconsole.log(err.toString()); // the errors of $.invalid()\n}\n```\n\n### ON('@' + name, function($, response) {})\n\nType: `event`\n\nÉmis après qu'une action a répondu avec succès.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | Le `$` de l'action |\n| `response` | `Object` | yes |  | La réponse de l'action |\n\nLe nom de l'événement est `@` suivi du nom de l'action. Il s'exécute après la réponse : c'est donc un bon endroit pour les notifications, les statistiques ou les caches. Il n'est pas émis lorsque l'action échoue.\n\nExample: Notification\n```js\nON('@orders_create', function($, response) {\n\tconsole.log('New order', response.value, 'by', $.user.id);\n});\n```\n\n### action: Function\n\nType: `config`\n\nLa logique de l'action.\n\nReturns: `Function`\n\n`function($, model)`. `model` est le payload validé (le même que `$.model`). La fonction doit terminer l'appel avec `$.success()`, `$.callback()`, `$.invalid()` ou un callback de `$.done()`. Elle peut être `async` : quand sa promesse est rejetée (une exception dans la fonction), l'appel se termine avec l'erreur `500: Internal Server Error` et l'exception est écrite dans le journal des erreurs, donc l'appelant n'attend pas un timeout.\n\nExample: Exemple de base\n```js\nNEWACTION('ping', {\n\taction: function($) {\n\t\t$.success(NOW);\n\t}\n});\n```\n\n### input: String|Object\n\nType: `config`\n\nSchéma du payload.\n\nReturns: `String|Object`\n\nUn schéma inline (`'*name:String, email:Email'`) ou le nom d'un schéma JSON avec `@` (`'@product'`). Le payload est validé et nettoyé avant l'exécution de l'action ; en cas d'échec, l'action ne s'exécute pas et l'appelant reçoit les erreurs. Sans `input`, le payload n'est pas validé. Voir [Schémas JSON](../../guides/json-schemas/).\n\nExample: Schéma inline\n```js\nNEWACTION('contact_send', {\n\tinput: '*name:String, *email:Email, message:String',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### output: String|Object\n\nType: `config`\n\nSchéma de la réponse.\n\nReturns: `String|Object`\n\nLa réponse passe par ce schéma : seuls les champs déclarés sortent donc de l'action. Utilise-le avec `$.callback()` : avec `$.success()`, le schéma est appliqué à l'objet `{ success, value }` entier.\n\nExample: Masquer des champs\n```js\nNEWACTION('users_read', {\n\tparams: '*id:UID',\n\toutput: 'id:UID, name:String, email:Email',\n\taction: function($) {\n\t\tDATA.read('users').id($.params.id).callback($);\n\t}\n});\n```\n\n### params: String|Object\n\nType: `config`\n\nSchéma des paramètres d'URL.\n\nReturns: `String|Object`\n\nValide `$.params`, les parties dynamiques de la route (`{id}`). Les erreurs ont le préfixe `params.`.\n\nExample: Paramètre\n```js\nNEWACTION('products_remove', {\n\tparams: '*id:UID',\n\troute: '+DELETE /api/products/{id}/',\n\taction: function($) {\n\t\tDATA.remove('products').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### query: String|Object\n\nType: `config`\n\nSchéma de la query string.\n\nReturns: `String|Object`\n\nValide `$.query`. Les erreurs ont le préfixe `query.`.\n\nExample: Query\n```js\nNEWACTION('products_search', {\n\tquery: '*q:String, page:Number',\n\troute: 'GET /api/products/search/',\n\taction: function($) {\n\t\tDATA.find('products').search('name', $.query.q).callback($);\n\t}\n});\n```\n\n### user: Boolean\n\nType: `config`\n\nExige un utilisateur connecté ou anonyme.\n\nReturns: `Boolean`\n\n`true` : l'action échoue avec 401 lorsque `$.user` est vide. `false` : elle échoue avec 401 lorsqu'il y a un utilisateur. Les options `sa: true` ou `su: true` exigent un utilisateur avec le flag `sa` ou `su`.\n\nExample: Utilisateur connecté\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### permissions: String|Array\n\nType: `config`\n\nPermissions requises.\n\nReturns: `String|Array`\n\nUne chaîne séparée par des virgules ou des points-virgules, ou un tableau. L'utilisateur doit en avoir au moins une dans `user.permissions` ou `user.roles` (un tableau ou un objet) ; les utilisateurs `sa` et `su` passent toujours. Sinon, l'action échoue avec 401.\n\nExample: Permissions\n```js\nNEWACTION('invoices_remove', {\n\tpermissions: 'invoices_remove,admin',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tDATA.remove('invoices').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### route: String\n\nType: `config`\n\nUne route qui exécute l'action.\n\nReturns: `String`\n\nUne chaîne de route comme dans [Routage](../../guides/routing/) (`'+POST /api/products/'`). Le framework ajoute ` --> <name>` et crée la route ; l'option contient ensuite l'objet route. `url` est la même option sous un autre nom. Avec `encrypt: true`, la route reçoit le flag `@encrypt`.\n\n`route: true` crée un endpoint `API ?` nommé d'après l'action (`+API ?` lorsque l'action a l'option `user` ou `permissions`).\n\nExample: Route\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: Endpoint d'API\n```js\nNEWACTION('products_list', {\n\troute: '+API ?',\n\taction: function($) {\n\t\tDATA.find('products').callback($);\n\t}\n});\n```\n\n### middleware: String\n\nType: `config`\n\nMiddleware à exécuter avant l'action.\n\nReturns: `String`\n\nNoms de middlewares enregistrés avec `MIDDLEWARE()`, séparés par des espaces, des virgules ou `|`. Chacun s'exécute sous la forme `fn($, next)` avant l'action ; un middleware manquant est journalisé et ignoré. Voir [Middleware](../../guides/middleware/).\n\nExample: Middleware\n```js\nNEWACTION('reports_build', {\n\tmiddleware: 'ratelimit',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### partial: Boolean\n\nType: `config`\n\nValide l'entrée partiellement.\n\nReturns: `Boolean`\n\nAvec `true`, `input` ne valide que les champs présents dans le payload et ne vérifie pas les champs requis. Utile pour les mises à jour `PATCH`.\n\nExample: Patch\n```js\nNEWACTION('products_patch', {\n\tparams: '*id:UID',\n\tinput: '*name:String, *price:Number',\n\tpartial: true,\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).callback($.done());\n\t}\n});\n```\n\n### extend: String\n\nType: `config`\n\nAjoute la réponse au payload.\n\nReturns: `String`\n\nLa réponse est stockée dans le payload sous cette clé (un chemin avec des points est autorisé) et le payload entier devient la réponse. Sans payload, un objet vide est utilisé. Utile dans une chaîne d'actions qui construisent un seul objet.\n\nExample: Extension\n```js\nNEWACTION('order_totals', {\n\textend: 'totals',\n\taction: function($, model) {\n\t\t$.callback({ count: 3, price: 120 });\n\t}\n});\n// response: { ...payload, totals: { count: 3, price: 120 } }\n```\n\n### audit: Boolean|String\n\nType: `config`\n\nÉcrit un enregistrement d'audit après un succès.\n\nReturns: `Boolean|String`\n\n`true` écrit un enregistrement sans message ; une chaîne est un template Tangular rendu avec `$` (`'{{ $.user.name }} created {{ $.model.name }}'`). L'enregistrement contient l'utilisateur, l'IP, l'URL, le nom de l'action et les données, et est transmis à `DEF.onAudit` (par défaut le fichier `logs/actions.log`).\n\nExample: Message d'audit\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taudit: '{{ $.user.name }} created {{ $.model.name }}',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### config: Object\n\nType: `config`\n\nConfiguration personnalisée de l'action.\n\nReturns: `Object`\n\nN'importe quel objet ; il est disponible sous `$.config` dans l'action, de sorte qu'une seule fonction peut servir plusieurs actions.\n\nExample: Logique partagée\n```js\nfunction list($) {\n\tDATA.find($.config.table).callback($);\n}\n\nNEWACTION('products_list', { config: { table: 'products' }, action: list });\nNEWACTION('orders_list', { config: { table: 'orders' }, action: list });\n```\n\n### timeout: Number\n\nType: `config` · Since: `0.0.16`\n\nUne limite de temps pour l'action.\n\nReturns: `Number`\n\nEn millisecondes. Quand l'action ne répond pas à temps, elle échoue avec l'erreur `Timeout.` ; une réponse ultérieure est ignorée.\n\nExample: Timeout\n```js\nNEWACTION('reports_export', {\n\ttimeout: 10000,\n\taction: function($) {\n\t\tsetTimeout(() => $.success(), 2000);\n\t}\n});\n```\n\n### cache: true | { query, params, input, user, language, key, expire }\n\nType: `config`\n\nGarde la réponse de l'action dans le cache.\n\nReturns: `Boolean|Object`\n\nLa première réponse réussie est gardée dans le cache (`CACHE`) et les appels suivants en reçoivent une copie : le middleware et l'action ne s'exécutent pas. La réponse est copiée à la fois quand elle est stockée et quand elle est lue, donc un appelant peut modifier sa copie sans risque. Les erreurs ne sont pas mises en cache.\n\nAvec `true`, l'action a une seule réponse en cache. Un objet crée une entrée pour chaque combinaison de valeurs :\n\n| Clé | Valeur |\n| --- | --- |\n| `query`, `params`, `input` | `true` (tous les champs du schéma de l'action) ou une liste de champs séparés par des virgules |\n| `user` | `true` (`$.user.id`) ou une liste de clés de `$.user` séparées par des virgules |\n| `language` | `true` : une entrée pour chaque `$.language` |\n| `key` | Un nom pour les entrées ; `CACHE.reset('action|' + key + '|')` les supprime |\n| `expire` | Durée de conservation d'une entrée, par défaut `'5 minutes'` |\n\nSans `user`, tous les utilisateurs partagent la même réponse en cache.\n\nExample: Une liste en cache par page\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number,category:String',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').where('category', $.query.category).page($.query.page, 20).callback($);\n\t}\n});\n\n// after a product is saved\nCACHE.reset('action|products|');\n```\n\nExample: Une entrée par utilisateur\n```js\nNEWACTION('Account|profile', {\n\tuser: true,\n\tcache: { user: true, expire: '1 minute' },\n\taction: function($) {\n\t\tDATA.read('users').id($.user.id).callback($);\n\t}\n});\n```\n\n### summary: String\n\nType: `config`\n\nUne description de l'action.\n\nReturns: `String`\n\nTexte libre sur ce que fait l'action. Le [serveur MCP](../../guides/mcp-server/) l'envoie aux clients d'IA comme description de l'outil ; sans `summary`, il envoie l'option `name`.\n\nExample: Résumé\n```js\nNEWACTION('tasks_create', {\n\tsummary: 'Creates a task and returns its ID',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### oninput: Function\n\nType: `config` · Since: `0.0.19`\n\nAppelée juste avant l'action.\n\nReturns: `Function`\n\n`function($)`. Elle s'exécute après la validation et les middlewares : `$.model`, `$.params` et `$.query` sont donc prêts et tu peux les modifier.\n\nExample: Préparer les données\n```js\nNEWACTION('notes_create', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.model.body = $.model.body.trim();\n\t},\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### mcp: Boolean\n\nType: `config`\n\nFait de l'action un outil du serveur MCP.\n\nReturns: `Boolean`\n\nAvec `true` et la clé de configuration `$mcp`, les clients d'IA peuvent lister et appeler l'action sur `POST /$mcp/`. Les schémas `input`, `query` et `params` deviennent les arguments de l'outil. Voir [Serveur MCP](../../guides/mcp-server/).\n\nExample: Un outil\n```js\nNEWACTION('tasks_list', {\n\tsummary: 'Lists the tasks',\n\tmcp: true,\n\taction: function($) {\n\t\tNOSQL('tasks').find().callback($);\n\t}\n});\n```\n\n### onoutput: Function\n\nType: `config` · Since: `0.0.19`\n\nAppelée après la réponse de l'action.\n\nReturns: `Function`\n\n`function(err, response, $)`. Elle s'exécute après la livraison d'une réponse réussie, donc `err` vaut `null` ; elle n'est pas appelée quand l'action échoue.\n\nExample: Log\n```js\nNEWACTION('orders_create', {\n\tinput: '*productid:UID',\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, $.user ? $.user.id : '', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### $.model\n\nType: `property`\n\nLe payload validé.\n\nReturns: `Object`\n\nLe payload après la validation par `input`, ou le payload brut sans `input`. `$.payload` et `$.value` sont la même valeur ; tu peux aussi l'assigner. C'est également le second argument de `action`.\n\nExample: Modèle\n```js\naction: function($) {\n\tvar name = $.model.name;\n\t$.success(name);\n}\n```\n\n### $.input\n\nType: `property` · Since: `0.0.19`\n\nUn autre nom de `$.model`.\n\nReturns: `Object`\n\nLit et assigne la même valeur que `$.model`.\n\nExample: Entrée\n```js\noninput: function($) {\n\t$.input.email = $.input.email.toLowerCase();\n}\n```\n\n### $.params\n\nType: `property`\n\nLes paramètres d'URL.\n\nReturns: `Object`\n\nValidés par l'option `params`. Dans une requête HTTP, ils contiennent les parties dynamiques de la route ; depuis le code, ils sont définis avec `ACTION().params()`.\n\nExample: Params\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback($);\n}\n```\n\n### $.query\n\nType: `property`\n\nLa query string.\n\nReturns: `Object`\n\nValidée par l'option `query`. Depuis le code, elle est définie avec `ACTION().query()`.\n\nExample: Query\n```js\naction: function($) {\n\tvar page = $.query.page || 1;\n\t$.success(page);\n}\n```\n\n### $.user\n\nType: `property`\n\nL'utilisateur courant.\n\nReturns: `Object`\n\nL'utilisateur de la requête HTTP (voir [Autorisation](../../guides/authorization/)), ou l'utilisateur défini avec `ACTION().user()`. Vide pour les appels anonymes.\n\nExample: Utilisateur\n```js\naction: function($) {\n\t$.success($.user.name);\n}\n```\n\n### $.config\n\nType: `property`\n\nL'option `config` de l'action.\n\nReturns: `Object`\n\nUn objet vide lorsque l'action n'a pas de `config`.\n\nExample: Config\n```js\naction: function($) {\n\t$.success($.config.table);\n}\n```\n\n### $.id\n\nType: `property`\n\nLe nom de l'action en cours d'exécution.\n\nReturns: `String`\n\nDans une chaîne d'actions, le nom de l'action courante.\n\nExample: Nom\n```js\naction: function($) {\n\tconsole.log('Running', $.id);\n\t$.success();\n}\n```\n\n### $.controller\n\nType: `property`\n\nLe contrôleur de la requête HTTP.\n\nReturns: `Controller`\n\n`undefined` lorsque l'action est appelée depuis le code sans contrôleur. `$.client` est identique ; `$.websocket` est défini lorsque le contrôleur est un client WebSocket.\n\nExample: Contrôleur\n```js\naction: function($) {\n\t$.success($.controller ? $.controller.url : 'code');\n}\n```\n\n### $.error\n\nType: `property`\n\nLes erreurs de l'appel.\n\nReturns: `ErrorBuilder`\n\nUn `ErrorBuilder`. `$.invalid()` y ajoute des erreurs ; `$.error.length` est le nombre d'erreurs.\n\nExample: Erreurs\n```js\naction: function($) {\n\tif (!$.model.items.length) {\n\t\t$.invalid('No items', 'items');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.response\n\nType: `property`\n\nLes réponses des actions d'une chaîne.\n\nReturns: `Object`\n\nUn objet contenant, par leur nom, les réponses des actions déjà terminées dans le même appel. L'action suivante de la chaîne peut les utiliser.\n\nExample: Réponse précédente\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tvar created = $.response.orders_create;\n\t\t$.success(created);\n\t}\n});\n```\n\n### $.xhr\n\nType: `property` · Since: `0.0.19`\n\nIndique si la requête est une requête XHR.\n\nReturns: `Boolean`\n\n`true` quand la requête HTTP a l'en-tête `X-Requested-With: XMLHttpRequest` ; `null` sans contrôleur.\n\nExample: XHR\n```js\naction: function($) {\n\tif ($.xhr)\n\t\t$.success();\n\telse\n\t\t$.redirect('/');\n}\n```\n\n### $.meta\n\nType: `property` · Since: `0.0.19`\n\nLa définition de l'action.\n\nReturns: `Object`\n\nL'objet passé à `NEWACTION()`, avec toutes ses options.\n\nExample: Meta\n```js\naction: function($) {\n\t$.success($.meta.name);\n}\n```\n\n### $.env\n\nType: `property`\n\nL'environnement de l'appel.\n\nReturns: `Any`\n\nLa valeur passée à `ACTION().env()` ; `undefined` quand elle n'est pas définie. Utilise-la pour indiquer à l'action d'où elle est appelée, par exemple depuis un test ou un job. `$.action()` ne la transmet pas : appelle `.env($)` sur l'appel interne.\n\nExample: Environnement\n```js\nNEWACTION('orders_sync', {\n\taction: function($) {\n\t\tif ($.env === 'test') {\n\t\t\t$.success();\n\t\t\treturn;\n\t\t}\n\t\t$.success('synced');\n\t}\n});\n\nACTION('orders_sync').env('test').callback(console.log);\n```\n\n### $.ip\n\nType: `property`\n\nRaccourcis vers les données de la requête.\n\nReturns: `String`\n\n`$.ip`, `$.address`, `$.headers`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.split2`, `$.files`, `$.body`, `$.mobile`, `$.ua`, `$.language` et `$.sessionid` lisent les mêmes propriétés du contrôleur. Sans contrôleur, ils sont vides (`null`, `''` ou un tableau vide).\n\nExample: IP et user agent\n```js\naction: function($) {\n\t$.success({ ip: $.ip, ua: $.ua });\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nTermine l'action avec un objet de succès.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Une valeur pour la propriété `value` |\n\nRépond avec `{ success: true, value: value }` (la forme provient de `DEF.onSuccess`). Sans valeur, `value` vaut `undefined`.\n\nExample: Succès\n```js\naction: function($) {\n\t$.success(UID());\n}\n```\n\n### $.invalid(error, [path], [index])\n\nType: `method`\n\nTermine l'action avec une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number|Error` | yes |  | L'erreur, ou un code de statut HTTP |\n| `path` | `String` | no |  | Le champ auquel l'erreur appartient |\n| `index` | `Number` | no |  | L'index de l'élément dans un tableau |\n\nReturns: `ErrorBuilder` Les erreurs\n\nAjoute l'erreur à `$.error` et fait échouer l'appel. Un nombre supérieur à 399 est un statut HTTP (`401`, `404`) ; une chaîne est un message d'erreur. Le callback de l'appelant reçoit l'`ErrorBuilder`, une route répond avec les erreurs. Retourne `$.error`.\n\nExample: Introuvable\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.callback(response);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n}\n```\n\n### $.callback([value])\n\nType: `method`\n\nTermine l'action avec une valeur telle quelle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | La réponse |\n\nReturns: `Function` Un callback lorsqu'elle est appelée sans arguments\n\nRépond avec `value` sans l'envelopper. Sans arguments, elle retourne un callback `function(err, response)` qui ajoute `err` aux erreurs et répond avec `response`. `$.pipe` est la même méthode. Tu peux aussi passer `$` lui-même au `callback()` d'une base de données.\n\nExample: Valeur\n```js\naction: function($) {\n\t$.callback({ count: 5 });\n}\n```\n\nExample: Callback d'une requête\n```js\naction: function($) {\n\tDATA.find('products').callback($.callback());\n}\n```\n\n### $.done([value])\n\nType: `method`\n\nRetourne un callback qui termine l'action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | La valeur de l'objet de succès, ou `true` pour la réponse |\n\nReturns: `Function` `function(err, response)`\n\nRetourne `function(err, response)`. Une erreur termine l'action avec l'erreur ; sinon, elle appelle `$.success(value)`, ou `$.success(response)` lorsque `value` vaut `true`.\n\nExample: Done\n```js\naction: function($, model) {\n\tmodel.id = UID();\n\tDATA.insert('products', model).callback($.done(model.id));\n}\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method`\n\nAppelle une fonction à callback sous forme de Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Une fonction dont le dernier argument est `function(err, response)` |\n| `a` | `Object` | no |  | Premier argument |\n| `b` | `Object` | no |  | Deuxième argument |\n| `c` | `Object` | no |  | Troisième argument |\n\nReturns: `Promise` La réponse\n\nAppelle `fn(a, b, c, callback)` et résout avec la réponse. Une erreur termine l'action avec `$.invalid()` et la Promise n'est jamais résolue.\n\nExample: Promisify\n```js\naction: async function($) {\n\tvar files = await $.promisify(F.Fs.readdir, PATH.public());\n\t$.success(files);\n}\n```\n\n### $.action(name, [payload])\n\nType: `method`\n\nExécute une autre action depuis une action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom ou noms de l'action |\n| `payload` | `Object` | no |  | Le payload |\n\nReturns: `ActionCaller` L'appelant\n\nIdentique à `ACTION()` avec le contrôleur de cette action. Sans contrôleur, le nouvel appel reçoit l'utilisateur, la query et les paramètres de celui-ci.\n\nExample: Action imbriquée\n```js\naction: async function($, model) {\n\tvar response = await $.action('stock_check', model).promise($);\n\t$.success(response);\n}\n```\n\n### $.transform(name, value, [callback])\n\nType: `method`\n\nExécute une transformation avec le contrôleur de l'action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la transformation |\n| `value` | `Object` | yes |  | La valeur |\n| `callback` | `Function` | no |  | `function(err, value)` |\n\nReturns: `Promise` Une Promise sans callback\n\nIdentique à `TRANSFORM()`, avec le contrôleur (et son utilisateur) de l'action. Sans callback, elle retourne une Promise.\n\nExample: Transformation\n```js\naction: async function($) {\n\tvar user = await DATA.read('users').id($.params.id).promise($);\n\t$.callback(await $.transform('user', user));\n}\n```\n\n### $.unauthorized(permission, [permission2], [...])\n\nType: `method`\n\nVérifie les permissions de l'utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | yes |  | Un nom de permission ; d'autres peuvent suivre |\n\nReturns: `Boolean` `true` lorsque l'utilisateur n'est pas autorisé\n\nRetourne `false` lorsque `$.user` possède au moins une des permissions (dans `permissions` ou `roles`) ou est `sa`/`su`. Sinon, elle appelle `$.invalid(401)` et retourne `true` : il te suffit alors de faire un return.\n\nExample: Vérification\n```js\naction: function($) {\n\tif ($.unauthorized('reports'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.redirect(url)\n\nType: `method`\n\nRedirige la requête HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL cible |\n\nRedirige le contrôleur vers `url` et annule l'action ; l'appelant ne reçoit aucune réponse.\n\nExample: Redirection\n```js\naction: function($) {\n\t$.redirect('/login/');\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nTermine l'action avec un message et enregistre l'erreur réelle dans le log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | L'erreur pour l'appelant, ou un code de statut HTTP |\n| `error` | `Error|String` | no |  | L'erreur pour le log |\n\nReturns: `ErrorBuilder` Les erreurs\n\nAjoute `message` à `$.error` et fait échouer l'appel, comme `$.invalid(message)`. `error` est écrit dans le log des erreurs avec `F.error()` (le nom de l'action et l'URL sont ajoutés) et n'est pas envoyé à l'appelant. Utilise-la quand l'erreur contient des détails que le client ne doit pas voir. Renvoie `$.error`.\n\nExample: Masquer les détails\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n### ACTION(name).callback(fn)\n\nType: `method`\n\nReçoit le résultat de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Options` | yes |  | `function(err, response)` ou un `$` |\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\n`fn(err, response)` ; `err` est un `ErrorBuilder` ou `null`. Lorsque tu passes le `$` d'une autre action, les erreurs vont dans son `$.invalid()` et la réponse dans son `$.callback()`. `.pipe()` est la même méthode.\n\nExample: Callback\n```js\nACTION('products_list').callback(function(err, response) {\n\tconsole.log(err ? err.toString() : response);\n});\n```\n\nExample: Transmettre à une autre action\n```js\naction: function($) {\n\tACTION('products_list').user($).callback($);\n}\n```\n\n### $.throw(error)\n\nType: `method`\n\nÉcrit une erreur dans le log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | L'erreur |\n\nReturns: `Options` Le même `$`\n\nPasse `error` au gestionnaire d'erreurs du framework (`DEF.onError`) avec le nom de l'action et l'URL : elle est affichée, conservée dans `F.errors` et émise comme événement `error`. L'action continue ; pour la terminer, appelle `$.invalid()`. Renvoie `$`.\n\nExample: Enregistrer dans le log et continuer\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tNOSQL('notifications').insert({ type: 'order', dtcreated: NOW }).callback(function(err) {\n\t\t\terr && $.throw(err);\n\t\t});\n\t\t$.success();\n\t}\n});\n```\n\n### $.touch([url])\n\nType: `method`\n\nEfface l'état mis en cache d'un fichier statique.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | L'URL du fichier |\n\nReturns: `Options` Le même `$`\n\nAppelle `TOUCH(url)`. Sans `url`, elle utilise l'URL de la requête ; sans contrôleur (une action appelée depuis le code), tous les fichiers statiques sont effacés. Utilise-la après que l'action a modifié un fichier dans `public/`. Renvoie `$`.\n\nExample: Après une modification\n```js\nNEWACTION('theme_save', {\n\tinput: '*css:String',\n\taction: async function($, model) {\n\t\tawait F.FsPromises.writeFile(PATH.public('css/theme.css'), model.css);\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t}\n});\n```\n\n### ACTION(name).promise([$])\n\nType: `method`\n\nRetourne une Promise avec le résultat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | no |  | Le `$` d'une action qui reçoit les erreurs |\n\nReturns: `Promise` La réponse\n\nRésout avec la réponse. En cas d'erreur, elle rejette avec une `Error` dont le message contient les erreurs ; avec `$`, l'erreur va à la place dans `$.invalid()` et la Promise n'est pas résolue.\n\nExample: Await\n```js\nvar response = await ACTION('products_list').promise();\n```\n\n### ACTION(name).user(user)\n\nType: `method`\n\nDéfinit l'utilisateur de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object|Options` | yes |  | Un objet utilisateur, ou un `$` |\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\nDéfinit `$.user`. Lorsque tu passes un `$`, son utilisateur est utilisé.\n\nExample: Utilisateur\n```js\nACTION('account_read').user({ id: '123', name: 'Peter' }).callback(console.log);\n```\n\n### ACTION(name).query(obj)\n\nType: `method`\n\nDéfinit la query string de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | La query |\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\nDéfinit l'objet validé par l'option `query`.\n\nExample: Query\n```js\nACTION('products_list').query({ page: 2 }).callback(console.log);\n```\n\n### ACTION(name).params(obj)\n\nType: `method`\n\nDéfinit les paramètres d'URL de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Les paramètres |\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\nDéfinit l'objet validé par l'option `params`.\n\nExample: Params\n```js\nACTION('products_read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\n### ACTION(name).ctrl(controller)\n\nType: `method`\n\nExécute l'appel avec un contrôleur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Un contrôleur |\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\nL'action reçoit `$.controller` et les raccourcis de la requête. Accepte un contrôleur ou un objet avec une propriété `controller` (un `$`).\n\nExample: Contrôleur\n```js\nfunction handler($) {\n\tACTION('products_list').ctrl($).autorespond();\n}\n```\n\n### ACTION(name).autorespond()\n\nType: `method`\n\nEnvoie le résultat au contrôleur.\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\nEn cas d'erreur, elle appelle `controller.invalid(err)` ; sinon, elle répond via le contrôleur dans le format défini par `$.output()` (JSON par défaut). Les routes avec `-->` l'utilisent. Nécessite un contrôleur.\n\nExample: Handler de route\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', function($) {\n\t\t$.action('products_list').autorespond();\n\t});\n};\n```\n\n### ACTION(name).status(fn)\n\nType: `method`\n\nReçoit les messages de statut de l'action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\nL'action les envoie avec `$.status(a, b, c, d)` ; les arguments sont transmis à `fn`. Sans cette méthode, `$.status()` ne fait rien.\n\nExample: Statut\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\t$.status('started');\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').status(console.log).callback(console.log);\n```\n\n### ACTION(name).progress(fn)\n\nType: `method` · Since: `0.0.16`\n\nReçoit les messages de progression de l'action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\nL'action les envoie avec `$.progress(a, b, c, d)` ; les arguments sont transmis à `fn` avec `$` comme `this`. Sans cette méthode, `$.progress()` ne fait rien.\n\nExample: Progression\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\tfor (var i = 1; i <= 10; i++)\n\t\t\t$.progress(i * 10);\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').progress(p => console.log(p + '%')).callback(console.log);\n```\n\n### ACTION(name).config(obj)\n\nType: `method` · Since: `0.0.17`\n\nAjoute une configuration pour cet appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Clés pour `$.config` |\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\nLes clés de `obj` sont fusionnées dans une copie de la `config` de l'action : `$.config` contient donc les deux ; la définition de l'action n'est pas modifiée.\n\nExample: Configuration\n```js\nNEWACTION('report_build', {\n\tconfig: { format: 'pdf' },\n\taction: function($) {\n\t\t$.success($.config);\n\t}\n});\n\nACTION('report_build').config({ lang: 'en' }).callback(console.log);\n// { success: true, value: { format: 'pdf', lang: 'en' } }\n```\n\n### ACTION(name).env(value)\n\nType: `method`\n\nDéfinit l'environnement de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any|Options` | yes |  | L'environnement, comme `'test'`, ou un `$` |\n\nReturns: `ActionCaller` L'appelant, pour le chaînage\n\nDéfinit `$.env` dans l'action. Quand tu passes un `$`, son `env` est utilisé, de sorte qu'un appel interne peut garder l'environnement de l'appel externe.\n\nExample: Environnement\n```js\nACTION('orders_sync').env('test').callback(console.log);\n```\n\nExample: Le transmettre\n```js\nNEWACTION('orders_close', {\n\taction: async function($) {\n\t\tawait $.action('orders_sync').env($).promise($);\n\t\t$.success();\n\t}\n});\n```\n\n### SUCCESS([value])\n\nType: `method`\n\nCrée l'objet de succès avec lequel répondent les actions et les contrôleurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Une valeur pour la propriété `value` |\n\nReturns: `Object` `{ success: true, value: value }`\n\nRetourne `{ success: true, value: value }`. La forme provient de `DEF.onSuccess`, la même fonction qu'utilise `$.success()` : un `DEF.onSuccess` personnalisé modifie donc les deux. Utilise-la lorsque tu construis toi-même une réponse, par exemple dans un contrôleur ou dans un callback.\n\nExample: Une réponse de succès dans un contrôleur\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.json(SUCCESS(NOW));\n});\n```\n","entries":[{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, callback)","since":"","deprecated":false},{"type":"method","name":"NEWTRANSFORM()","signature":"NEWTRANSFORM(name, fn, [id])","since":"","deprecated":false},{"type":"method","name":"TRANSFORM()","signature":"TRANSFORM(name, value, [callback], [controller])","since":"","deprecated":false},{"type":"event","name":"ON('@{action}')","signature":"ON('@' + name, function($, response) {})","since":"","deprecated":false},{"type":"config","name":"NEWACTION.action","signature":"action: Function","since":"","deprecated":false},{"type":"config","name":"NEWACTION.input","signature":"input: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.output","signature":"output: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.params","signature":"params: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.query","signature":"query: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.user","signature":"user: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.permissions","signature":"permissions: String|Array","since":"","deprecated":false},{"type":"config","name":"NEWACTION.route","signature":"route: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.middleware","signature":"middleware: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.partial","signature":"partial: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.extend","signature":"extend: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.audit","signature":"audit: Boolean|String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.config","signature":"config: Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.timeout","signature":"timeout: Number","since":"0.0.16","deprecated":false},{"type":"config","name":"NEWACTION.cache","signature":"cache: true | { query, params, input, user, language, key, expire }","since":"","deprecated":false},{"type":"config","name":"NEWACTION.summary","signature":"summary: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.oninput","signature":"oninput: Function","since":"0.0.19","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.onoutput","signature":"onoutput: Function","since":"0.0.19","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.input","signature":"$.input","since":"0.0.19","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.config","signature":"$.config","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"0.0.19","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"0.0.19","deprecated":false},{"type":"property","name":"$.env","signature":"$.env","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [payload])","since":"","deprecated":false},{"type":"method","name":"$.transform()","signature":"$.transform(name, value, [callback])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized()","signature":"$.unauthorized(permission, [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"ACTION().callback()","signature":"ACTION(name).callback(fn)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"ACTION().promise()","signature":"ACTION(name).promise([$])","since":"","deprecated":false},{"type":"method","name":"ACTION().user()","signature":"ACTION(name).user(user)","since":"","deprecated":false},{"type":"method","name":"ACTION().query()","signature":"ACTION(name).query(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().params()","signature":"ACTION(name).params(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().ctrl()","signature":"ACTION(name).ctrl(controller)","since":"","deprecated":false},{"type":"method","name":"ACTION().autorespond()","signature":"ACTION(name).autorespond()","since":"","deprecated":false},{"type":"method","name":"ACTION().status()","signature":"ACTION(name).status(fn)","since":"","deprecated":false},{"type":"method","name":"ACTION().progress()","signature":"ACTION(name).progress(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ACTION().config()","signature":"ACTION(name).config(obj)","since":"0.0.17","deprecated":false},{"type":"method","name":"ACTION().env()","signature":"ACTION(name).env(value)","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([value])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwUcAPx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/actions/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Azioni","summary":"Opzioni di NEWACTION(), l'oggetto $, i chiamanti di ACTION(), NEWSCHEMA() e le trasformazioni.","markdown":"---\ntitle: Azioni\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/actions/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Azioni\n\n> Opzioni di NEWACTION(), l'oggetto $, i chiamanti di ACTION(), NEWSCHEMA() e le trasformazioni.\n\nLe funzioni, le opzioni e gli oggetti delle azioni in Total.js 5: `NEWACTION()` e le sue opzioni, l'oggetto `$` passato a un'azione, il chiamante restituito da `ACTION()`/`EXEC()`, `NEWSCHEMA()` e `NEWTRANSFORM()`/`TRANSFORM()`.\n\nPer un'introduzione con esempi, leggi la guida [Azioni](../../guides/actions/). Gli schemi per `input`, `output`, `params` e `query` sono descritti in [Schemi JSON](../../guides/json-schemas/).\n\n## API\n\n### NEWACTION(name, options)\n\nType: `method`\n\nDichiara un'azione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'azione, ad es. `products_create` |\n| `options` | `Object` | yes |  | La definizione: `action`, `input`, `output`, `params`, `query`, `user`, `permissions`, `route` e le altre opzioni |\n\nReturns: `Object` La definizione dell'azione\n\nRegistra l'azione con il nome `name` e restituisce l'oggetto di definizione. Quando `name` è un oggetto, sono le opzioni e il nome viene preso dalla sua proprietà `id` o `name`. Un'azione con lo stesso nome viene prima rimossa (insieme alla sua route). L'oggetto restituito ha `remove()`, che rimuove l'azione e la sua route. Tutte le azioni registrate sono in `F.actions`.\n\nExample: Un'azione completa\n```js\nNEWACTION('products_update', {\n\tname: 'Update a product',\n\tparams: '*id:UID',\n\tinput: '*name:String, price:Number',\n\tpermissions: 'products',\n\troute: '+PUT /api/products/{id}/',\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).error(404).callback($.done($.params.id));\n\t}\n});\n```\n\nExample: Rimuovere un'azione\n```js\nvar action = NEWACTION('temp_test', { action: $ => $.success() });\naction.remove();\n```\n\n### ACTION(name, [payload], [controller])\n\nType: `method`\n\nEsegue una o più azioni dal codice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'azione, o nomi separati da spazi; un prefisso `+` o `-` indica se l'azione usa il payload |\n| `payload` | `Object` | no |  | I dati validati dall'opzione `input` |\n| `controller` | `Controller` | no |  | Un controller di una richiesta HTTP |\n\nReturns: `ActionCaller` Il chiamante con `callback()`, `promise()`, `user()` e gli altri metodi\n\nRestituisce un chiamante di azione. La chiamata parte al tick successivo, quindi imposta utente, query, parametri e callback concatenando i metodi. `name` può contenere più azioni separate da spazi o virgole; vengono eseguite in ordine con lo stesso `$`. Il risultato è la risposta dell'azione contrassegnata con ` (response)`, oppure un oggetto con le risposte di tutte le azioni indicizzate per nome. Con una sola azione il risultato è sempre la sua risposta. Con un controller, utente, query e parametri vengono presi da esso.\n\nExample: Callback\n```js\nACTION('products_list').query({ search: 'mouse' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Più azioni\n```js\nACTION('orders_create orders_notify (response)', model).user(user).callback(function(err, response) {\n\t// response is the response of orders_notify\n});\n```\n\n### EXEC(name, [payload], [controller])\n\nType: `method`\n\nUn alias di `ACTION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome o nomi dell'azione |\n| `payload` | `Object` | no |  | Il payload |\n| `controller` | `Controller` | no |  | Un controller |\n\nReturns: `ActionCaller` Il chiamante\n\nLa stessa funzione di `ACTION()`.\n\nExample: Promise\n```js\nvar response = await EXEC('products_create', { name: 'Mouse' }).user(user).promise();\n```\n\n### NEWSCHEMA(name, callback)\n\nType: `method`\n\nRaggruppa le azioni sotto un nome comune.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dello schema |\n| `callback` | `Function|String` | yes |  | `function(schema)`, oppure una definizione di schema inline |\n\nReturns: `Object` Niente per una callback; lo schema JSON per una stringa\n\nChiama `callback(schema)`; `schema.action(name, options)` dichiara l'azione `<schema name>/<name>` con `NEWACTION()` e la restituisce. Le azioni create si trovano anche in `schema.actions`. Un `@` iniziale nel nome viene rimosso. Quando il secondo argomento è una stringa, `NEWSCHEMA()` registra invece uno schema JSON con quella definizione inline e lo restituisce.\n\nExample: Azioni di uno schema\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('read', {\n\t\tparams: '*id:UID',\n\t\taction: function($) {\n\t\t\tDATA.read('users').id($.params.id).error(404).callback($);\n\t\t}\n\t});\n\n});\n\nACTION('Users/read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\nExample: Uno schema JSON\n```js\nNEWSCHEMA('Address', '*street:String, *city:String, zip:Zip');\n```\n\n### NEWTRANSFORM(name, fn, [id])\n\nType: `method`\n\nAggiunge una funzione a una trasformazione con nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome della trasformazione |\n| `fn` | `Function` | yes |  | `function($, value)` |\n| `id` | `String` | no |  | Un identificatore per rimuovere la funzione in seguito |\n\nReturns: `Object` Un oggetto con `id`, `action` e `remove()`\n\nLe funzioni con lo stesso nome vengono eseguite nell'ordine in cui sono state aggiunte. Ognuna riceve `($, value)`; modifica `value` o assegna un nuovo `$.value`, poi chiama `$.next()`, oppure interrompe la catena con `$.invalid(error)` (la callback di `TRANSFORM()` riceve allora gli errori). `$.user` e `$.controller` sono impostati quando la trasformazione viene eseguita con un controller. Restituisce un oggetto con `remove()`. `NEWTRANSFORM(name, null, id)` rimuove la funzione con quell'`id`.\n\nExample: Aggiungere e rimuovere\n```js\nNEWTRANSFORM('user', function($, value) {\n\tdelete value.password;\n\t$.next();\n}, 'password');\n\nNEWTRANSFORM('user', null, 'password');\n```\n\n### TRANSFORM(name, value, [callback], [controller])\n\nType: `method`\n\nEsegue una trasformazione con nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome della trasformazione |\n| `value` | `Object` | yes |  | Il valore da trasformare |\n| `callback` | `Function` | no |  | `function(err, value)` |\n| `controller` | `Controller` | no |  | Un controller; il suo utente è `$.user` nelle funzioni |\n\nReturns: `Promise` Una Promise quando non c'è una callback\n\nEsegue tutte le funzioni aggiunte con `NEWTRANSFORM(name)` e chiama `callback(err, value)` con il valore finale. Un nome senza funzioni restituisce il valore invariato. Senza una callback restituisce una Promise e il terzo argomento è il controller. La Promise viene rifiutata con gli errori di `$.invalid()`; quando il terzo argomento è il `$` di un'azione (o un controller), gli errori vanno invece al suo `invalid()`.\n\nExample: Callback\n```js\nTRANSFORM('user', user, function(err, value) {\n\tconsole.log(value);\n});\n```\n\nExample: Promise\n```js\nvar value = await TRANSFORM('user', user);\n```\n\nExample: Errori della forma con Promise\n```js\ntry {\n\tvar value = await TRANSFORM('user', user);\n} catch (err) {\n\tconsole.log(err.toString()); // the errors of $.invalid()\n}\n```\n\n### ON('@' + name, function($, response) {})\n\nType: `event`\n\nEmesso dopo che un'azione ha risposto con successo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | Il `$` dell'azione |\n| `response` | `Object` | yes |  | La risposta dell'azione |\n\nIl nome dell'evento è `@` seguito dal nome dell'azione. Viene eseguito dopo la risposta, quindi è un buon punto per notifiche, statistiche o cache. Non viene emesso quando l'azione fallisce.\n\nExample: Notifica\n```js\nON('@orders_create', function($, response) {\n\tconsole.log('New order', response.value, 'by', $.user.id);\n});\n```\n\n### action: Function\n\nType: `config`\n\nLa logica dell'azione.\n\nReturns: `Function`\n\n`function($, model)`. `model` è il payload validato (lo stesso di `$.model`). La funzione deve terminare la chiamata con `$.success()`, `$.callback()`, `$.invalid()` o con una callback di `$.done()`. Può essere `async`: quando la sua promise viene rifiutata (un'eccezione nella funzione), la chiamata termina con l'errore `500: Internal Server Error` e l'eccezione viene scritta nel log degli errori, così il chiamante non aspetta un timeout.\n\nExample: Base\n```js\nNEWACTION('ping', {\n\taction: function($) {\n\t\t$.success(NOW);\n\t}\n});\n```\n\n### input: String|Object\n\nType: `config`\n\nSchema del payload.\n\nReturns: `String|Object`\n\nUno schema inline (`'*name:String, email:Email'`) o il nome di uno schema JSON con `@` (`'@product'`). Il payload viene validato e ripulito prima dell'esecuzione dell'azione; in caso di errore l'azione non viene eseguita e il chiamante riceve gli errori. Senza `input` il payload non viene validato. Vedi [Schemi JSON](../../guides/json-schemas/).\n\nExample: Schema inline\n```js\nNEWACTION('contact_send', {\n\tinput: '*name:String, *email:Email, message:String',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### output: String|Object\n\nType: `config`\n\nSchema della risposta.\n\nReturns: `String|Object`\n\nLa risposta passa attraverso questo schema, quindi solo i campi dichiarati escono dall'azione. Usalo con `$.callback()`: con `$.success()` lo schema viene applicato all'intero oggetto `{ success, value }`.\n\nExample: Nascondere campi\n```js\nNEWACTION('users_read', {\n\tparams: '*id:UID',\n\toutput: 'id:UID, name:String, email:Email',\n\taction: function($) {\n\t\tDATA.read('users').id($.params.id).callback($);\n\t}\n});\n```\n\n### params: String|Object\n\nType: `config`\n\nSchema dei parametri dell'URL.\n\nReturns: `String|Object`\n\nValida `$.params`, le parti dinamiche della route (`{id}`). Gli errori hanno il prefisso `params.`.\n\nExample: Parametro\n```js\nNEWACTION('products_remove', {\n\tparams: '*id:UID',\n\troute: '+DELETE /api/products/{id}/',\n\taction: function($) {\n\t\tDATA.remove('products').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### query: String|Object\n\nType: `config`\n\nSchema della query string.\n\nReturns: `String|Object`\n\nValida `$.query`. Gli errori hanno il prefisso `query.`.\n\nExample: Query\n```js\nNEWACTION('products_search', {\n\tquery: '*q:String, page:Number',\n\troute: 'GET /api/products/search/',\n\taction: function($) {\n\t\tDATA.find('products').search('name', $.query.q).callback($);\n\t}\n});\n```\n\n### user: Boolean\n\nType: `config`\n\nRichiede un utente autenticato o anonimo.\n\nReturns: `Boolean`\n\n`true`: l'azione fallisce con 401 quando `$.user` è vuoto. `false`: fallisce con 401 quando c'è un utente. Le opzioni `sa: true` o `su: true` richiedono un utente con il flag `sa` o `su`.\n\nExample: Utente autenticato\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### permissions: String|Array\n\nType: `config`\n\nPermessi richiesti.\n\nReturns: `String|Array`\n\nUna stringa separata da virgole o punti e virgola, oppure un array. L'utente ne deve avere almeno uno in `user.permissions` o `user.roles` (un array o un oggetto); gli utenti `sa` e `su` passano sempre. Altrimenti l'azione fallisce con 401.\n\nExample: Permessi\n```js\nNEWACTION('invoices_remove', {\n\tpermissions: 'invoices_remove,admin',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tDATA.remove('invoices').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### route: String\n\nType: `config`\n\nUna route che esegue l'azione.\n\nReturns: `String`\n\nUna stringa di route come in [Routing](../../guides/routing/) (`'+POST /api/products/'`). Il framework aggiunge ` --> <name>` e crea la route; l'opzione contiene poi l'oggetto route. `url` è la stessa opzione con un altro nome. Con `encrypt: true` la route riceve il flag `@encrypt`.\n\n`route: true` crea un endpoint `API ?` con il nome dell'azione (`+API ?` quando l'azione ha l'opzione `user` o `permissions`).\n\nExample: Route\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: Endpoint API\n```js\nNEWACTION('products_list', {\n\troute: '+API ?',\n\taction: function($) {\n\t\tDATA.find('products').callback($);\n\t}\n});\n```\n\n### middleware: String\n\nType: `config`\n\nMiddleware da eseguire prima dell'azione.\n\nReturns: `String`\n\nNomi di middleware registrati con `MIDDLEWARE()`, separati da spazi, virgole o `|`. Ognuno viene eseguito come `fn($, next)` prima dell'azione; un middleware mancante viene registrato nel log e saltato. Vedi [Middleware](../../guides/middleware/).\n\nExample: Middleware\n```js\nNEWACTION('reports_build', {\n\tmiddleware: 'ratelimit',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### partial: Boolean\n\nType: `config`\n\nValida l'input parzialmente.\n\nReturns: `Boolean`\n\nCon `true`, `input` valida solo i campi presenti nel payload e non controlla i campi obbligatori. Utile per gli aggiornamenti `PATCH`.\n\nExample: Patch\n```js\nNEWACTION('products_patch', {\n\tparams: '*id:UID',\n\tinput: '*name:String, *price:Number',\n\tpartial: true,\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).callback($.done());\n\t}\n});\n```\n\n### extend: String\n\nType: `config`\n\nAggiunge la risposta al payload.\n\nReturns: `String`\n\nLa risposta viene salvata nel payload sotto questa chiave (è ammesso un percorso con punti) e l'intero payload diventa la risposta. Senza payload viene usato un oggetto vuoto. Utile in una catena di azioni che costruiscono un unico oggetto.\n\nExample: Extend\n```js\nNEWACTION('order_totals', {\n\textend: 'totals',\n\taction: function($, model) {\n\t\t$.callback({ count: 3, price: 120 });\n\t}\n});\n// response: { ...payload, totals: { count: 3, price: 120 } }\n```\n\n### audit: Boolean|String\n\nType: `config`\n\nScrive un record di audit dopo il successo.\n\nReturns: `Boolean|String`\n\n`true` scrive un record senza messaggio; una stringa è un template Tangular renderizzato con `$` (`'{{ $.user.name }} created {{ $.model.name }}'`). Il record contiene l'utente, l'IP, l'URL, il nome dell'azione e i dati, e viene passato a `DEF.onAudit` (di default il file `logs/actions.log`).\n\nExample: Messaggio di audit\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taudit: '{{ $.user.name }} created {{ $.model.name }}',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### config: Object\n\nType: `config`\n\nConfigurazione personalizzata dell'azione.\n\nReturns: `Object`\n\nUn oggetto qualsiasi; è disponibile come `$.config` nell'azione, così una sola funzione può servire più azioni.\n\nExample: Logica condivisa\n```js\nfunction list($) {\n\tDATA.find($.config.table).callback($);\n}\n\nNEWACTION('products_list', { config: { table: 'products' }, action: list });\nNEWACTION('orders_list', { config: { table: 'orders' }, action: list });\n```\n\n### timeout: Number\n\nType: `config` · Since: `0.0.16`\n\nUn limite di tempo dell'azione.\n\nReturns: `Number`\n\nIn millisecondi. Quando l'azione non risponde in tempo, fallisce con l'errore `Timeout.`; una risposta successiva viene ignorata.\n\nExample: Timeout\n```js\nNEWACTION('reports_export', {\n\ttimeout: 10000,\n\taction: function($) {\n\t\tsetTimeout(() => $.success(), 2000);\n\t}\n});\n```\n\n### cache: true | { query, params, input, user, language, key, expire }\n\nType: `config`\n\nMantiene la risposta dell'azione nella cache.\n\nReturns: `Boolean|Object`\n\nLa prima risposta riuscita viene salvata nella cache (`CACHE`) e le chiamate successive ne ricevono una copia: il middleware e l'azione non vengono eseguiti. La risposta viene copiata sia quando viene salvata sia quando viene letta, così un chiamante può modificare la sua copia senza rischi. Gli errori non vengono messi in cache.\n\nCon `true` l'azione ha una sola risposta in cache. Un oggetto crea una voce per ogni combinazione di valori:\n\n| Chiave | Valore |\n| --- | --- |\n| `query`, `params`, `input` | `true` (tutti i campi dello schema dell'azione) o un elenco di campi separati da virgole |\n| `user` | `true` (`$.user.id`) o un elenco di chiavi di `$.user` separate da virgole |\n| `language` | `true`: una voce per ogni `$.language` |\n| `key` | Un nome per le voci; `CACHE.reset('action|' + key + '|')` le rimuove |\n| `expire` | Per quanto tempo viene mantenuta una voce, predefinito `'5 minutes'` |\n\nSenza `user`, tutti gli utenti condividono la stessa risposta in cache.\n\nExample: Un elenco in cache per pagina\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number,category:String',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').where('category', $.query.category).page($.query.page, 20).callback($);\n\t}\n});\n\n// after a product is saved\nCACHE.reset('action|products|');\n```\n\nExample: Una voce per utente\n```js\nNEWACTION('Account|profile', {\n\tuser: true,\n\tcache: { user: true, expire: '1 minute' },\n\taction: function($) {\n\t\tDATA.read('users').id($.user.id).callback($);\n\t}\n});\n```\n\n### summary: String\n\nType: `config`\n\nUna descrizione dell'azione.\n\nReturns: `String`\n\nTesto libero su ciò che fa l'azione. Il [server MCP](../../guides/mcp-server/) lo invia ai client AI come descrizione del tool; senza `summary` invia l'opzione `name`.\n\nExample: Summary\n```js\nNEWACTION('tasks_create', {\n\tsummary: 'Creates a task and returns its ID',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### oninput: Function\n\nType: `config` · Since: `0.0.19`\n\nChiamato subito prima dell'azione.\n\nReturns: `Function`\n\n`function($)`. Viene eseguito dopo la validazione e i middleware, quindi `$.model`, `$.params` e `$.query` sono pronti e puoi modificarli.\n\nExample: Preparare i dati\n```js\nNEWACTION('notes_create', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.model.body = $.model.body.trim();\n\t},\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### mcp: Boolean\n\nType: `config`\n\nRende l'azione un tool del server MCP.\n\nReturns: `Boolean`\n\nCon `true` e la chiave di configurazione `$mcp`, i client AI possono elencare e chiamare l'azione su `POST /$mcp/`. Gli schemi `input`, `query` e `params` diventano gli argomenti del tool. Vedi [Server MCP](../../guides/mcp-server/).\n\nExample: Un tool\n```js\nNEWACTION('tasks_list', {\n\tsummary: 'Lists the tasks',\n\tmcp: true,\n\taction: function($) {\n\t\tNOSQL('tasks').find().callback($);\n\t}\n});\n```\n\n### onoutput: Function\n\nType: `config` · Since: `0.0.19`\n\nChiamato dopo che l'azione ha risposto.\n\nReturns: `Function`\n\n`function(err, response, $)`. Viene eseguito dopo che una risposta riuscita è stata consegnata, quindi `err` è `null`; non viene chiamato quando l'azione fallisce.\n\nExample: Log\n```js\nNEWACTION('orders_create', {\n\tinput: '*productid:UID',\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, $.user ? $.user.id : '', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### $.model\n\nType: `property`\n\nIl payload validato.\n\nReturns: `Object`\n\nIl payload dopo la validazione di `input`, o il payload grezzo senza `input`. `$.payload` e `$.value` sono lo stesso valore; puoi anche assegnarlo. È anche il secondo argomento di `action`.\n\nExample: Model\n```js\naction: function($) {\n\tvar name = $.model.name;\n\t$.success(name);\n}\n```\n\n### $.input\n\nType: `property` · Since: `0.0.19`\n\nUn altro nome di `$.model`.\n\nReturns: `Object`\n\nLegge e assegna lo stesso valore di `$.model`.\n\nExample: Input\n```js\noninput: function($) {\n\t$.input.email = $.input.email.toLowerCase();\n}\n```\n\n### $.params\n\nType: `property`\n\nI parametri dell'URL.\n\nReturns: `Object`\n\nValidati dall'opzione `params`. In una richiesta HTTP contiene le parti dinamiche della route; dal codice si imposta con `ACTION().params()`.\n\nExample: Params\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback($);\n}\n```\n\n### $.query\n\nType: `property`\n\nLa query string.\n\nReturns: `Object`\n\nValidata dall'opzione `query`. Dal codice si imposta con `ACTION().query()`.\n\nExample: Query\n```js\naction: function($) {\n\tvar page = $.query.page || 1;\n\t$.success(page);\n}\n```\n\n### $.user\n\nType: `property`\n\nL'utente corrente.\n\nReturns: `Object`\n\nL'utente della richiesta HTTP (vedi [Autorizzazione](../../guides/authorization/)), o l'utente impostato con `ACTION().user()`. Vuoto per le chiamate anonime.\n\nExample: Utente\n```js\naction: function($) {\n\t$.success($.user.name);\n}\n```\n\n### $.config\n\nType: `property`\n\nL'opzione `config` dell'azione.\n\nReturns: `Object`\n\nUn oggetto vuoto quando l'azione non ha `config`.\n\nExample: Config\n```js\naction: function($) {\n\t$.success($.config.table);\n}\n```\n\n### $.id\n\nType: `property`\n\nIl nome dell'azione in esecuzione.\n\nReturns: `String`\n\nIn una catena di azioni, il nome di quella corrente.\n\nExample: Nome\n```js\naction: function($) {\n\tconsole.log('Running', $.id);\n\t$.success();\n}\n```\n\n### $.controller\n\nType: `property`\n\nIl controller della richiesta HTTP.\n\nReturns: `Controller`\n\n`undefined` quando l'azione viene chiamata dal codice senza controller. `$.client` è la stessa cosa; `$.websocket` è impostato quando il controller è un client WebSocket.\n\nExample: Controller\n```js\naction: function($) {\n\t$.success($.controller ? $.controller.url : 'code');\n}\n```\n\n### $.error\n\nType: `property`\n\nGli errori della chiamata.\n\nReturns: `ErrorBuilder`\n\nUn `ErrorBuilder`. `$.invalid()` vi aggiunge errori; `$.error.length` è il numero di errori.\n\nExample: Errori\n```js\naction: function($) {\n\tif (!$.model.items.length) {\n\t\t$.invalid('No items', 'items');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.response\n\nType: `property`\n\nLe risposte delle azioni in una catena.\n\nReturns: `Object`\n\nUn oggetto con le risposte, indicizzate per nome, delle azioni già terminate nella stessa chiamata. L'azione successiva della catena può usarle.\n\nExample: Risposta precedente\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tvar created = $.response.orders_create;\n\t\t$.success(created);\n\t}\n});\n```\n\n### $.xhr\n\nType: `property` · Since: `0.0.19`\n\nIndica se la richiesta è una richiesta XHR.\n\nReturns: `Boolean`\n\n`true` quando la richiesta HTTP ha l'header `X-Requested-With: XMLHttpRequest`; `null` senza controller.\n\nExample: XHR\n```js\naction: function($) {\n\tif ($.xhr)\n\t\t$.success();\n\telse\n\t\t$.redirect('/');\n}\n```\n\n### $.meta\n\nType: `property` · Since: `0.0.19`\n\nLa definizione dell'azione.\n\nReturns: `Object`\n\nL'oggetto passato a `NEWACTION()`, con tutte le sue opzioni.\n\nExample: Meta\n```js\naction: function($) {\n\t$.success($.meta.name);\n}\n```\n\n### $.env\n\nType: `property`\n\nL'ambiente della chiamata.\n\nReturns: `Any`\n\nIl valore passato a `ACTION().env()`; `undefined` quando non è impostato. Usalo per dire all'azione da dove viene chiamata, per esempio da un test o da un job. `$.action()` non lo trasmette: chiama `.env($)` sulla chiamata interna.\n\nExample: Ambiente\n```js\nNEWACTION('orders_sync', {\n\taction: function($) {\n\t\tif ($.env === 'test') {\n\t\t\t$.success();\n\t\t\treturn;\n\t\t}\n\t\t$.success('synced');\n\t}\n});\n\nACTION('orders_sync').env('test').callback(console.log);\n```\n\n### $.ip\n\nType: `property`\n\nScorciatoie per i dati della richiesta.\n\nReturns: `String`\n\n`$.ip`, `$.address`, `$.headers`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.split2`, `$.files`, `$.body`, `$.mobile`, `$.ua`, `$.language` e `$.sessionid` leggono le stesse proprietà del controller. Senza controller sono vuote (`null`, `''` o un array vuoto).\n\nExample: IP e user agent\n```js\naction: function($) {\n\t$.success({ ip: $.ip, ua: $.ua });\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nTermina l'azione con un oggetto di successo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Un valore per la proprietà `value` |\n\nRisponde con `{ success: true, value: value }` (la forma deriva da `DEF.onSuccess`). Senza valore, `value` è `undefined`.\n\nExample: Successo\n```js\naction: function($) {\n\t$.success(UID());\n}\n```\n\n### $.invalid(error, [path], [index])\n\nType: `method`\n\nTermina l'azione con un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number|Error` | yes |  | L'errore, o un codice di stato HTTP |\n| `path` | `String` | no |  | Il campo a cui appartiene l'errore |\n| `index` | `Number` | no |  | L'indice dell'elemento in un array |\n\nReturns: `ErrorBuilder` Gli errori\n\nAggiunge l'errore a `$.error` e fa fallire la chiamata. Un numero superiore a 399 è uno stato HTTP (`401`, `404`); una stringa è un messaggio di errore. La callback del chiamante riceve l'`ErrorBuilder`, una route risponde con gli errori. Restituisce `$.error`.\n\nExample: Non trovato\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.callback(response);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n}\n```\n\n### $.callback([value])\n\nType: `method`\n\nTermina l'azione con un valore così com'è.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | La risposta |\n\nReturns: `Function` Una callback quando viene chiamato senza argomenti\n\nRisponde con `value` senza incapsularlo. Senza argomenti, restituisce una callback `function(err, response)` che aggiunge `err` agli errori e risponde con `response`. `$.pipe` è lo stesso metodo. Puoi anche passare `$` stesso a una `callback()` di database.\n\nExample: Valore\n```js\naction: function($) {\n\t$.callback({ count: 5 });\n}\n```\n\nExample: Callback di una query\n```js\naction: function($) {\n\tDATA.find('products').callback($.callback());\n}\n```\n\n### $.done([value])\n\nType: `method`\n\nRestituisce una callback che termina l'azione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | Il valore dell'oggetto di successo, o `true` per la risposta |\n\nReturns: `Function` `function(err, response)`\n\nRestituisce `function(err, response)`. Un errore termina l'azione con l'errore; altrimenti chiama `$.success(value)`, oppure `$.success(response)` quando `value` è `true`.\n\nExample: Done\n```js\naction: function($, model) {\n\tmodel.id = UID();\n\tDATA.insert('products', model).callback($.done(model.id));\n}\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method`\n\nChiama una funzione con callback come Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Una funzione il cui ultimo argomento è `function(err, response)` |\n| `a` | `Object` | no |  | Primo argomento |\n| `b` | `Object` | no |  | Secondo argomento |\n| `c` | `Object` | no |  | Terzo argomento |\n\nReturns: `Promise` La risposta\n\nChiama `fn(a, b, c, callback)` e si risolve con la risposta. Un errore termina l'azione con `$.invalid()` e la Promise non si risolve mai.\n\nExample: Promisify\n```js\naction: async function($) {\n\tvar files = await $.promisify(F.Fs.readdir, PATH.public());\n\t$.success(files);\n}\n```\n\n### $.action(name, [payload])\n\nType: `method`\n\nEsegue un'altra azione da un'azione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome o nomi dell'azione |\n| `payload` | `Object` | no |  | Il payload |\n\nReturns: `ActionCaller` Il chiamante\n\nCome `ACTION()` con il controller di questa azione. Senza controller, la nuova chiamata riceve utente, query e parametri di questa.\n\nExample: Azione annidata\n```js\naction: async function($, model) {\n\tvar response = await $.action('stock_check', model).promise($);\n\t$.success(response);\n}\n```\n\n### $.transform(name, value, [callback])\n\nType: `method`\n\nEsegue una trasformazione con il controller dell'azione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome della trasformazione |\n| `value` | `Object` | yes |  | Il valore |\n| `callback` | `Function` | no |  | `function(err, value)` |\n\nReturns: `Promise` Una Promise senza callback\n\nCome `TRANSFORM()`, con il controller (e il suo utente) dell'azione. Senza callback restituisce una Promise.\n\nExample: Trasformazione\n```js\naction: async function($) {\n\tvar user = await DATA.read('users').id($.params.id).promise($);\n\t$.callback(await $.transform('user', user));\n}\n```\n\n### $.unauthorized(permission, [permission2], [...])\n\nType: `method`\n\nControlla i permessi dell'utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | yes |  | Il nome di un permesso; possono seguirne altri |\n\nReturns: `Boolean` `true` quando l'utente non è autorizzato\n\nRestituisce `false` quando `$.user` ha almeno uno dei permessi (in `permissions` o `roles`) oppure è `sa`/`su`. Altrimenti chiama `$.invalid(401)` e restituisce `true`, così ti basta fare return.\n\nExample: Controllo\n```js\naction: function($) {\n\tif ($.unauthorized('reports'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.redirect(url)\n\nType: `method`\n\nReindirizza la richiesta HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL di destinazione |\n\nReindirizza il controller a `url` e annulla l'azione; il chiamante non riceve alcuna risposta.\n\nExample: Redirect\n```js\naction: function($) {\n\t$.redirect('/login/');\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nTermina l'azione con un messaggio e registra l'errore reale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | L'errore per il chiamante, oppure un codice di stato HTTP |\n| `error` | `Error|String` | no |  | L'errore per il log |\n\nReturns: `ErrorBuilder` Gli errori\n\nAggiunge `message` a `$.error` e fa fallire la chiamata, come `$.invalid(message)`. `error` viene scritto nel log degli errori con `F.error()` (vengono aggiunti il nome dell'azione e l'URL) e non viene inviato al chiamante. Usalo quando l'errore contiene dettagli che il client non deve vedere. Restituisce `$.error`.\n\nExample: Nascondere i dettagli\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n### ACTION(name).callback(fn)\n\nType: `method`\n\nRiceve il risultato della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Options` | yes |  | `function(err, response)` o un `$` |\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\n`fn(err, response)`; `err` è un `ErrorBuilder` o `null`, Quando passi il `$` di un'altra azione, gli errori vanno al suo `$.invalid()` e la risposta al suo `$.callback()`. `.pipe()` è lo stesso metodo.\n\nExample: Callback\n```js\nACTION('products_list').callback(function(err, response) {\n\tconsole.log(err ? err.toString() : response);\n});\n```\n\nExample: Passare a un'altra azione\n```js\naction: function($) {\n\tACTION('products_list').user($).callback($);\n}\n```\n\n### $.throw(error)\n\nType: `method`\n\nScrive un errore nel log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | L'errore |\n\nReturns: `Options` Lo stesso `$`\n\nPassa `error` al gestore degli errori del framework (`DEF.onError`) con il nome dell'azione e l'URL: viene stampato, conservato in `F.errors` ed emesso come evento `error`. L'azione continua; per terminarla, chiama `$.invalid()`. Restituisce `$`.\n\nExample: Registrare e continuare\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tNOSQL('notifications').insert({ type: 'order', dtcreated: NOW }).callback(function(err) {\n\t\t\terr && $.throw(err);\n\t\t});\n\t\t$.success();\n\t}\n});\n```\n\n### $.touch([url])\n\nType: `method`\n\nCancella lo stato in cache di un file statico.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | L'URL del file |\n\nReturns: `Options` Lo stesso `$`\n\nChiama `TOUCH(url)`. Senza `url` usa l'URL della richiesta; senza controller (un'azione chiamata dal codice) viene cancellato lo stato di ogni file statico. Usalo dopo che l'azione ha modificato un file in `public/`. Restituisce `$`.\n\nExample: Dopo una modifica\n```js\nNEWACTION('theme_save', {\n\tinput: '*css:String',\n\taction: async function($, model) {\n\t\tawait F.FsPromises.writeFile(PATH.public('css/theme.css'), model.css);\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t}\n});\n```\n\n### ACTION(name).promise([$])\n\nType: `method`\n\nRestituisce una Promise con il risultato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | no |  | Il `$` di un'azione che riceve gli errori |\n\nReturns: `Promise` La risposta\n\nSi risolve con la risposta. In caso di errore viene rifiutata con un `Error` il cui messaggio contiene gli errori; con `$`, l'errore va invece a `$.invalid()` e la Promise non si risolve.\n\nExample: Await\n```js\nvar response = await ACTION('products_list').promise();\n```\n\n### ACTION(name).user(user)\n\nType: `method`\n\nImposta l'utente della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object|Options` | yes |  | Un oggetto utente, o un `$` |\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\nImposta `$.user`. Quando passi un `$`, viene usato il suo utente.\n\nExample: Utente\n```js\nACTION('account_read').user({ id: '123', name: 'Peter' }).callback(console.log);\n```\n\n### ACTION(name).query(obj)\n\nType: `method`\n\nImposta la query string della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | La query |\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\nImposta l'oggetto validato dall'opzione `query`.\n\nExample: Query\n```js\nACTION('products_list').query({ page: 2 }).callback(console.log);\n```\n\n### ACTION(name).params(obj)\n\nType: `method`\n\nImposta i parametri dell'URL della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | I parametri |\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\nImposta l'oggetto validato dall'opzione `params`.\n\nExample: Params\n```js\nACTION('products_read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\n### ACTION(name).ctrl(controller)\n\nType: `method`\n\nEsegue la chiamata con un controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Un controller |\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\nL'azione riceve `$.controller` e le scorciatoie della richiesta. Accetta un controller o un oggetto con una proprietà `controller` (un `$`).\n\nExample: Controller\n```js\nfunction handler($) {\n\tACTION('products_list').ctrl($).autorespond();\n}\n```\n\n### ACTION(name).autorespond()\n\nType: `method`\n\nInvia il risultato al controller.\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\nIn caso di errore chiama `controller.invalid(err)`; altrimenti risponde tramite il controller nel formato impostato da `$.output()` (JSON di default). Le route con `-->` lo usano. Richiede un controller.\n\nExample: Handler di route\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', function($) {\n\t\t$.action('products_list').autorespond();\n\t});\n};\n```\n\n### ACTION(name).status(fn)\n\nType: `method`\n\nRiceve i messaggi di stato dall'azione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\nL'azione li invia con `$.status(a, b, c, d)`; gli argomenti vanno a `fn`. Senza questo metodo, `$.status()` non fa nulla.\n\nExample: Stato\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\t$.status('started');\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').status(console.log).callback(console.log);\n```\n\n### ACTION(name).progress(fn)\n\nType: `method` · Since: `0.0.16`\n\nRiceve i messaggi di avanzamento dall'azione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\nL'azione li invia con `$.progress(a, b, c, d)`; gli argomenti vanno a `fn` con `$` come `this`. Senza questo metodo, `$.progress()` non fa nulla.\n\nExample: Avanzamento\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\tfor (var i = 1; i <= 10; i++)\n\t\t\t$.progress(i * 10);\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').progress(p => console.log(p + '%')).callback(console.log);\n```\n\n### ACTION(name).config(obj)\n\nType: `method` · Since: `0.0.17`\n\nAggiunge configurazione per questa chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Chiavi per `$.config` |\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\nLe chiavi di `obj` vengono unite a una copia del `config` dell'azione, così `$.config` contiene entrambi; la definizione dell'azione non viene modificata.\n\nExample: Config\n```js\nNEWACTION('report_build', {\n\tconfig: { format: 'pdf' },\n\taction: function($) {\n\t\t$.success($.config);\n\t}\n});\n\nACTION('report_build').config({ lang: 'en' }).callback(console.log);\n// { success: true, value: { format: 'pdf', lang: 'en' } }\n```\n\n### ACTION(name).env(value)\n\nType: `method`\n\nImposta l'ambiente della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any|Options` | yes |  | L'ambiente, come `'test'`, oppure un `$` |\n\nReturns: `ActionCaller` Il chiamante, per il concatenamento\n\nImposta `$.env` nell'azione. Quando passi un `$`, viene usato il suo `env`, così una chiamata interna può mantenere l'ambiente di quella esterna.\n\nExample: Ambiente\n```js\nACTION('orders_sync').env('test').callback(console.log);\n```\n\nExample: Trasmetterlo\n```js\nNEWACTION('orders_close', {\n\taction: async function($) {\n\t\tawait $.action('orders_sync').env($).promise($);\n\t\t$.success();\n\t}\n});\n```\n\n### SUCCESS([value])\n\nType: `method`\n\nCrea l'oggetto di successo con cui rispondono azioni e controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Un valore per la proprietà `value` |\n\nReturns: `Object` `{ success: true, value: value }`\n\nRestituisce `{ success: true, value: value }`. La forma deriva da `DEF.onSuccess`, la stessa funzione usata da `$.success()`, quindi un `DEF.onSuccess` personalizzato modifica entrambi. Usalo quando costruisci tu stesso una risposta, ad esempio in un controller o in una callback.\n\nExample: Una risposta di successo in un controller\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.json(SUCCESS(NOW));\n});\n```\n","entries":[{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, callback)","since":"","deprecated":false},{"type":"method","name":"NEWTRANSFORM()","signature":"NEWTRANSFORM(name, fn, [id])","since":"","deprecated":false},{"type":"method","name":"TRANSFORM()","signature":"TRANSFORM(name, value, [callback], [controller])","since":"","deprecated":false},{"type":"event","name":"ON('@{action}')","signature":"ON('@' + name, function($, response) {})","since":"","deprecated":false},{"type":"config","name":"NEWACTION.action","signature":"action: Function","since":"","deprecated":false},{"type":"config","name":"NEWACTION.input","signature":"input: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.output","signature":"output: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.params","signature":"params: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.query","signature":"query: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.user","signature":"user: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.permissions","signature":"permissions: String|Array","since":"","deprecated":false},{"type":"config","name":"NEWACTION.route","signature":"route: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.middleware","signature":"middleware: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.partial","signature":"partial: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.extend","signature":"extend: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.audit","signature":"audit: Boolean|String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.config","signature":"config: Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.timeout","signature":"timeout: Number","since":"0.0.16","deprecated":false},{"type":"config","name":"NEWACTION.cache","signature":"cache: true | { query, params, input, user, language, key, expire }","since":"","deprecated":false},{"type":"config","name":"NEWACTION.summary","signature":"summary: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.oninput","signature":"oninput: Function","since":"0.0.19","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.onoutput","signature":"onoutput: Function","since":"0.0.19","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.input","signature":"$.input","since":"0.0.19","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.config","signature":"$.config","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"0.0.19","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"0.0.19","deprecated":false},{"type":"property","name":"$.env","signature":"$.env","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [payload])","since":"","deprecated":false},{"type":"method","name":"$.transform()","signature":"$.transform(name, value, [callback])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized()","signature":"$.unauthorized(permission, [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"ACTION().callback()","signature":"ACTION(name).callback(fn)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"ACTION().promise()","signature":"ACTION(name).promise([$])","since":"","deprecated":false},{"type":"method","name":"ACTION().user()","signature":"ACTION(name).user(user)","since":"","deprecated":false},{"type":"method","name":"ACTION().query()","signature":"ACTION(name).query(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().params()","signature":"ACTION(name).params(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().ctrl()","signature":"ACTION(name).ctrl(controller)","since":"","deprecated":false},{"type":"method","name":"ACTION().autorespond()","signature":"ACTION(name).autorespond()","since":"","deprecated":false},{"type":"method","name":"ACTION().status()","signature":"ACTION(name).status(fn)","since":"","deprecated":false},{"type":"method","name":"ACTION().progress()","signature":"ACTION(name).progress(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ACTION().config()","signature":"ACTION(name).config(obj)","since":"0.0.17","deprecated":false},{"type":"method","name":"ACTION().env()","signature":"ACTION(name).env(value)","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([value])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwUcAPx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/actions/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Akcie","summary":"Voľby NEWACTION(), objekt $, volania ACTION(), NEWSCHEMA() a transformácie.","markdown":"---\ntitle: Akcie\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/actions/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Akcie\n\n> Voľby NEWACTION(), objekt $, volania ACTION(), NEWSCHEMA() a transformácie.\n\nFunkcie, voľby a objekty akcií v Total.js 5: `NEWACTION()` a jeho voľby, objekt `$` odovzdaný akcii, objekt volania vrátený z `ACTION()`/`EXEC()`, `NEWSCHEMA()` a `NEWTRANSFORM()`/`TRANSFORM()`.\n\nÚvod s príkladmi nájdeš v návode [Akcie](../../guides/actions/). Schémy pre `input`, `output`, `params` a `query` sú opísané v [JSON schémach](../../guides/json-schemas/).\n\n## API\n\n### NEWACTION(name, options)\n\nType: `method`\n\nDeklaruje akciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno akcie, napr. `products_create` |\n| `options` | `Object` | yes |  | Definícia: `action`, `input`, `output`, `params`, `query`, `user`, `permissions`, `route` a ďalšie voľby |\n\nReturns: `Object` Definícia akcie\n\nZaregistruje akciu pod menom `name` a vráti objekt definície. Keď je `name` objekt, sú to voľby a meno sa vezme z jeho vlastnosti `id` alebo `name`. Akcia s rovnakým menom sa najprv odstráni (aj s jej routou). Vrátený objekt má `remove()`, ktorá odstráni akciu a jej routu. Všetky zaregistrované akcie nájdeš v `F.actions`.\n\nExample: Kompletná akcia\n```js\nNEWACTION('products_update', {\n\tname: 'Update a product',\n\tparams: '*id:UID',\n\tinput: '*name:String, price:Number',\n\tpermissions: 'products',\n\troute: '+PUT /api/products/{id}/',\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).error(404).callback($.done($.params.id));\n\t}\n});\n```\n\nExample: Odstránenie akcie\n```js\nvar action = NEWACTION('temp_test', { action: $ => $.success() });\naction.remove();\n```\n\n### ACTION(name, [payload], [controller])\n\nType: `method`\n\nSpustí jednu alebo viac akcií z kódu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno akcie alebo mená oddelené medzerami; prefix `+` alebo `-` určuje, či akcia používa payload |\n| `payload` | `Object` | no |  | Dáta validované voľbou `input` |\n| `controller` | `Controller` | no |  | Controller HTTP požiadavky |\n\nReturns: `ActionCaller` Objekt volania s metódami `callback()`, `promise()`, `user()` a ďalšími\n\nVráti objekt volania akcie. Volanie sa spustí v nasledujúcom ticku, takže používateľa, query, parametre a callback nastavíš reťazením. `name` môže obsahovať viac akcií oddelených medzerami alebo čiarkami; spustia sa postupne s rovnakým `$`. Výsledkom je odpoveď akcie označenej ` (response)` alebo objekt s odpoveďami všetkých akcií podľa ich mien. Pri jednej akcii je výsledkom vždy jej odpoveď. S controllerom sa používateľ, query a parametre vezmú z neho.\n\nExample: Callback\n```js\nACTION('products_list').query({ search: 'mouse' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Viac akcií\n```js\nACTION('orders_create orders_notify (response)', model).user(user).callback(function(err, response) {\n\t// response is the response of orders_notify\n});\n```\n\n### EXEC(name, [payload], [controller])\n\nType: `method`\n\nAlias pre `ACTION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno alebo mená akcií |\n| `payload` | `Object` | no |  | Payload |\n| `controller` | `Controller` | no |  | Controller |\n\nReturns: `ActionCaller` Objekt volania\n\nRovnaká funkcia ako `ACTION()`.\n\nExample: Promise\n```js\nvar response = await EXEC('products_create', { name: 'Mouse' }).user(user).promise();\n```\n\n### NEWSCHEMA(name, callback)\n\nType: `method`\n\nZoskupí akcie pod spoločné meno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno schémy |\n| `callback` | `Function|String` | yes |  | `function(schema)` alebo inline definícia schémy |\n\nReturns: `Object` Nič pri callbacku; JSON schému pri reťazci\n\nZavolá `callback(schema)`; `schema.action(name, options)` deklaruje akciu `<schema name>/<name>` pomocou `NEWACTION()` a vráti ju. Vytvorené akcie sú aj v `schema.actions`. Úvodný `@` v mene sa odstráni. Ak je druhý argument reťazec, `NEWSCHEMA()` namiesto toho zaregistruje JSON schému s touto inline definíciou a vráti ju.\n\nExample: Akcie schémy\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('read', {\n\t\tparams: '*id:UID',\n\t\taction: function($) {\n\t\t\tDATA.read('users').id($.params.id).error(404).callback($);\n\t\t}\n\t});\n\n});\n\nACTION('Users/read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\nExample: JSON schéma\n```js\nNEWSCHEMA('Address', '*street:String, *city:String, zip:Zip');\n```\n\n### NEWTRANSFORM(name, fn, [id])\n\nType: `method`\n\nPridá funkciu do pomenovanej transformácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno transformácie |\n| `fn` | `Function` | yes |  | `function($, value)` |\n| `id` | `String` | no |  | Identifikátor na neskoršie odstránenie funkcie |\n\nReturns: `Object` Objekt s `id`, `action` a `remove()`\n\nFunkcie s jedným názvom sa spúšťajú v poradí, v akom boli pridané. Každá dostane `($, value)`; zmení `value` alebo priradí nové `$.value`, potom zavolá `$.next()`, alebo reťaz zastaví cez `$.invalid(error)` (callback `TRANSFORM()` potom dostane chyby). `$.user` a `$.controller` sú nastavené, keď sa transformácia spustí s controllerom. Vráti objekt s `remove()`. `NEWTRANSFORM(name, null, id)` odstráni funkciu s daným `id`.\n\nExample: Pridanie a odstránenie\n```js\nNEWTRANSFORM('user', function($, value) {\n\tdelete value.password;\n\t$.next();\n}, 'password');\n\nNEWTRANSFORM('user', null, 'password');\n```\n\n### TRANSFORM(name, value, [callback], [controller])\n\nType: `method`\n\nSpustí pomenovanú transformáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno transformácie |\n| `value` | `Object` | yes |  | Hodnota na transformáciu |\n| `callback` | `Function` | no |  | `function(err, value)` |\n| `controller` | `Controller` | no |  | Controller; jeho používateľ je vo funkciách `$.user` |\n\nReturns: `Promise` Promise, ak nie je callback\n\nSpustí všetky funkcie pridané cez `NEWTRANSFORM(name)` a zavolá `callback(err, value)` s výslednou hodnotou. Názov bez funkcií vráti hodnotu nezmenenú. Bez callbacku vráti Promise a tretí argument je controller. Promise sa zamietne s chybami z `$.invalid()`; keď je tretím argumentom `$` akcie (alebo controller), chyby idú namiesto toho do jeho `invalid()`.\n\nExample: Callback\n```js\nTRANSFORM('user', user, function(err, value) {\n\tconsole.log(value);\n});\n```\n\nExample: Promise\n```js\nvar value = await TRANSFORM('user', user);\n```\n\nExample: Chyby vo forme s Promise\n```js\ntry {\n\tvar value = await TRANSFORM('user', user);\n} catch (err) {\n\tconsole.log(err.toString()); // the errors of $.invalid()\n}\n```\n\n### ON('@' + name, function($, response) {})\n\nType: `event`\n\nVyvolá sa po úspešnej odpovedi akcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | `$` akcie |\n| `response` | `Object` | yes |  | Odpoveď akcie |\n\nMeno udalosti je `@` a meno akcie. Spustí sa po odpovedi, takže je to vhodné miesto pre notifikácie, štatistiky alebo cache. Nevyvolá sa, keď akcia zlyhá.\n\nExample: Notifikácia\n```js\nON('@orders_create', function($, response) {\n\tconsole.log('New order', response.value, 'by', $.user.id);\n});\n```\n\n### action: Function\n\nType: `config`\n\nLogika akcie.\n\nReturns: `Function`\n\n`function($, model)`. `model` je zvalidovaný payload (to isté ako `$.model`). Funkcia musí volanie ukončiť cez `$.success()`, `$.callback()`, `$.invalid()` alebo callback z `$.done()`. Môže byť `async`: keď sa jej promise zamietne (výnimka vo funkcii), volanie skončí chybou `500: Internal Server Error` a výnimka sa zapíše do logu chýb, takže volajúci nečaká na timeout.\n\nExample: Základ\n```js\nNEWACTION('ping', {\n\taction: function($) {\n\t\t$.success(NOW);\n\t}\n});\n```\n\n### input: String|Object\n\nType: `config`\n\nSchéma payloadu.\n\nReturns: `String|Object`\n\nInline schéma (`'*name:String, email:Email'`) alebo meno JSON schémy s `@` (`'@product'`). Payload sa pred spustením akcie validuje a vyčistí; pri chybe sa akcia nespustí a volajúci dostane chyby. Bez `input` sa payload nevaliduje. Pozri [JSON schémy](../../guides/json-schemas/).\n\nExample: Inline schéma\n```js\nNEWACTION('contact_send', {\n\tinput: '*name:String, *email:Email, message:String',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### output: String|Object\n\nType: `config`\n\nSchéma odpovede.\n\nReturns: `String|Object`\n\nOdpoveď prejde cez túto schému, takže z akcie odídu iba deklarované polia. Používaj ju s `$.callback()`: pri `$.success()` sa schéma použije na celý objekt `{ success, value }`.\n\nExample: Skrytie polí\n```js\nNEWACTION('users_read', {\n\tparams: '*id:UID',\n\toutput: 'id:UID, name:String, email:Email',\n\taction: function($) {\n\t\tDATA.read('users').id($.params.id).callback($);\n\t}\n});\n```\n\n### params: String|Object\n\nType: `config`\n\nSchéma URL parametrov.\n\nReturns: `String|Object`\n\nValiduje `$.params`, dynamické časti routy (`{id}`). Chyby majú prefix `params.`.\n\nExample: Parameter\n```js\nNEWACTION('products_remove', {\n\tparams: '*id:UID',\n\troute: '+DELETE /api/products/{id}/',\n\taction: function($) {\n\t\tDATA.remove('products').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### query: String|Object\n\nType: `config`\n\nSchéma query stringu.\n\nReturns: `String|Object`\n\nValiduje `$.query`. Chyby majú prefix `query.`.\n\nExample: Query\n```js\nNEWACTION('products_search', {\n\tquery: '*q:String, page:Number',\n\troute: 'GET /api/products/search/',\n\taction: function($) {\n\t\tDATA.find('products').search('name', $.query.q).callback($);\n\t}\n});\n```\n\n### user: Boolean\n\nType: `config`\n\nVyžaduje prihláseného alebo anonymného používateľa.\n\nReturns: `Boolean`\n\n`true`: akcia zlyhá s 401, keď je `$.user` prázdny. `false`: zlyhá s 401, keď používateľ existuje. Voľby `sa: true` alebo `su: true` vyžadujú používateľa s príznakom `sa` alebo `su`.\n\nExample: Prihlásený používateľ\n```js\nNEWACTION('account_read', {\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### permissions: String|Array\n\nType: `config`\n\nPožadované oprávnenia.\n\nReturns: `String|Array`\n\nReťazec oddelený čiarkami alebo bodkočiarkami, alebo pole. Používateľ potrebuje aspoň jedno z nich v `user.permissions` alebo `user.roles` (pole alebo objekt); používatelia `sa` a `su` prejdú vždy. Inak akcia zlyhá s 401.\n\nExample: Oprávnenia\n```js\nNEWACTION('invoices_remove', {\n\tpermissions: 'invoices_remove,admin',\n\tparams: '*id:UID',\n\taction: function($) {\n\t\tDATA.remove('invoices').id($.params.id).callback($.done());\n\t}\n});\n```\n\n### route: String\n\nType: `config`\n\nRouta, ktorá spúšťa akciu.\n\nReturns: `String`\n\nReťazec routy ako v [Routing](../../guides/routing/) (`'+POST /api/products/'`). Framework pripojí ` --> <name>` a vytvorí routu; možnosť potom obsahuje objekt routy. `url` je tá istá možnosť pod iným názvom. S `encrypt: true` routa dostane flag `@encrypt`.\n\n`route: true` vytvorí endpoint `API ?` pomenovaný podľa akcie (`+API ?`, keď má akcia možnosť `user` alebo `permissions`).\n\nExample: Routa\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\troute: '+POST /api/products/',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: API endpoint\n```js\nNEWACTION('products_list', {\n\troute: '+API ?',\n\taction: function($) {\n\t\tDATA.find('products').callback($);\n\t}\n});\n```\n\n### middleware: String\n\nType: `config`\n\nMiddleware, ktoré sa spustí pred akciou.\n\nReturns: `String`\n\nMená middleware zaregistrovaných cez `MIDDLEWARE()`, oddelené medzerami, čiarkami alebo `|`. Každé sa spustí ako `fn($, next)` pred akciou; chýbajúce middleware sa zaloguje a preskočí. Pozri [Middleware](../../guides/middleware/).\n\nExample: Middleware\n```js\nNEWACTION('reports_build', {\n\tmiddleware: 'ratelimit',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### partial: Boolean\n\nType: `config`\n\nValiduje vstup čiastočne.\n\nReturns: `Boolean`\n\nS `true` validuje `input` len polia prítomné v payloade a nekontroluje povinné polia. Hodí sa pre aktualizácie cez `PATCH`.\n\nExample: Patch\n```js\nNEWACTION('products_patch', {\n\tparams: '*id:UID',\n\tinput: '*name:String, *price:Number',\n\tpartial: true,\n\taction: function($, model) {\n\t\tDATA.modify('products', model).id($.params.id).callback($.done());\n\t}\n});\n```\n\n### extend: String\n\nType: `config`\n\nPridá odpoveď do payloadu.\n\nReturns: `String`\n\nOdpoveď sa uloží do payloadu pod týmto kľúčom (povolená je aj cesta s bodkami) a odpoveďou sa stane celý payload. Bez payloadu sa použije prázdny objekt. Hodí sa v reťazci akcií, ktoré skladajú jeden objekt.\n\nExample: Extend\n```js\nNEWACTION('order_totals', {\n\textend: 'totals',\n\taction: function($, model) {\n\t\t$.callback({ count: 3, price: 120 });\n\t}\n});\n// response: { ...payload, totals: { count: 3, price: 120 } }\n```\n\n### audit: Boolean|String\n\nType: `config`\n\nPo úspechu zapíše auditný záznam.\n\nReturns: `Boolean|String`\n\n`true` zapíše záznam bez správy; reťazec je Tangular šablóna vykreslená s `$` (`'{{ $.user.name }} created {{ $.model.name }}'`). Záznam obsahuje používateľa, IP, URL, meno akcie a dáta a ide do `DEF.onAudit` (predvolene súbor `logs/actions.log`).\n\nExample: Auditná správa\n```js\nNEWACTION('products_create', {\n\tinput: '*name:String',\n\taudit: '{{ $.user.name }} created {{ $.model.name }}',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### config: Object\n\nType: `config`\n\nVlastná konfigurácia akcie.\n\nReturns: `Object`\n\nĽubovoľný objekt; v akcii je dostupný ako `$.config`, takže jedna funkcia môže slúžiť viacerým akciám.\n\nExample: Zdieľaná logika\n```js\nfunction list($) {\n\tDATA.find($.config.table).callback($);\n}\n\nNEWACTION('products_list', { config: { table: 'products' }, action: list });\nNEWACTION('orders_list', { config: { table: 'orders' }, action: list });\n```\n\n### timeout: Number\n\nType: `config` · Since: `0.0.16`\n\nČasový limit akcie.\n\nReturns: `Number`\n\nV milisekundách. Keď akcia neodpovie včas, zlyhá s chybou `Timeout.`; neskoršia odpoveď sa ignoruje.\n\nExample: Timeout\n```js\nNEWACTION('reports_export', {\n\ttimeout: 10000,\n\taction: function($) {\n\t\tsetTimeout(() => $.success(), 2000);\n\t}\n});\n```\n\n### cache: true | { query, params, input, user, language, key, expire }\n\nType: `config`\n\nUchová odpoveď akcie v cache.\n\nReturns: `Boolean|Object`\n\nPrvá úspešná odpoveď sa uloží do cache (`CACHE`) a ďalšie volania dostanú jej kópiu: middleware ani akcia sa nespustia. Odpoveď sa kopíruje pri uložení aj pri čítaní, takže volajúci môže svoju kópiu bezpečne meniť. Chyby sa do cache neukladajú.\n\nS `true` má akcia jednu odpoveď v cache. Objekt vytvorí jeden záznam pre každú kombináciu hodnôt:\n\n| Kľúč | Hodnota |\n| --- | --- |\n| `query`, `params`, `input` | `true` (všetky polia schémy akcie) alebo zoznam polí oddelených čiarkami |\n| `user` | `true` (`$.user.id`) alebo zoznam kľúčov `$.user` oddelených čiarkami |\n| `language` | `true`: jeden záznam pre každý `$.language` |\n| `key` | Názov záznamov; `CACHE.reset('action|' + key + '|')` ich odstráni |\n| `expire` | Ako dlho sa záznam uchová, predvolene `'5 minutes'` |\n\nBez `user` zdieľajú všetci používatelia tú istú odpoveď z cache.\n\nExample: Zoznam v cache pre každú stránku\n```js\nNEWACTION('Products|list', {\n\tquery: 'page:Number,category:String',\n\tcache: { query: true, key: 'products', expire: '10 minutes' },\n\taction: function($) {\n\t\tDATA.list('products').where('category', $.query.category).page($.query.page, 20).callback($);\n\t}\n});\n\n// after a product is saved\nCACHE.reset('action|products|');\n```\n\nExample: Jeden záznam pre každého používateľa\n```js\nNEWACTION('Account|profile', {\n\tuser: true,\n\tcache: { user: true, expire: '1 minute' },\n\taction: function($) {\n\t\tDATA.read('users').id($.user.id).callback($);\n\t}\n});\n```\n\n### summary: String\n\nType: `config`\n\nPopis akcie.\n\nReturns: `String`\n\nVoľný text o tom, čo akcia robí. [MCP server](../../guides/mcp-server/) ho posiela AI klientom ako popis nástroja; bez `summary` pošle možnosť `name`.\n\nExample: Popis\n```js\nNEWACTION('tasks_create', {\n\tsummary: 'Creates a task and returns its ID',\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### oninput: Function\n\nType: `config` · Since: `0.0.19`\n\nVolá sa tesne pred akciou.\n\nReturns: `Function`\n\n`function($)`. Spustí sa po validácii a middleware, takže `$.model`, `$.params` a `$.query` sú pripravené a môžeš ich meniť.\n\nExample: Príprava dát\n```js\nNEWACTION('notes_create', {\n\tinput: '*body:String',\n\toninput: function($) {\n\t\t$.model.body = $.model.body.trim();\n\t},\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### mcp: Boolean\n\nType: `config`\n\nUrobí z akcie nástroj MCP servera.\n\nReturns: `Boolean`\n\nS `true` a konfiguračným kľúčom `$mcp` môžu AI klienti akciu vypísať a zavolať na `POST /$mcp/`. Schémy `input`, `query` a `params` sa stanú argumentmi nástroja. Pozri [MCP server](../../guides/mcp-server/).\n\nExample: Nástroj\n```js\nNEWACTION('tasks_list', {\n\tsummary: 'Lists the tasks',\n\tmcp: true,\n\taction: function($) {\n\t\tNOSQL('tasks').find().callback($);\n\t}\n});\n```\n\n### onoutput: Function\n\nType: `config` · Since: `0.0.19`\n\nVolá sa po odpovedi akcie.\n\nReturns: `Function`\n\n`function(err, response, $)`. Spustí sa po doručení úspešnej odpovede, takže `err` je `null`; nevolá sa, keď akcia zlyhá.\n\nExample: Log\n```js\nNEWACTION('orders_create', {\n\tinput: '*productid:UID',\n\tonoutput: function(err, response, $) {\n\t\tconsole.log($.id, $.user ? $.user.id : '', response);\n\t},\n\taction: function($, model) {\n\t\t$.success(UID());\n\t}\n});\n```\n\n### $.model\n\nType: `property`\n\nValidovaný payload.\n\nReturns: `Object`\n\nPayload po validácii cez `input` alebo surový payload bez `input`. `$.payload` a `$.value` sú tá istá hodnota; môžeš ju aj priradiť. Je to aj druhý argument `action`.\n\nExample: Model\n```js\naction: function($) {\n\tvar name = $.model.name;\n\t$.success(name);\n}\n```\n\n### $.input\n\nType: `property` · Since: `0.0.19`\n\nIný názov pre `$.model`.\n\nReturns: `Object`\n\nČíta a priraďuje tú istú hodnotu ako `$.model`.\n\nExample: Vstup\n```js\noninput: function($) {\n\t$.input.email = $.input.email.toLowerCase();\n}\n```\n\n### $.params\n\nType: `property`\n\nURL parametre.\n\nReturns: `Object`\n\nValidované voľbou `params`. V HTTP požiadavke obsahujú dynamické časti routy; z kódu sa nastavujú cez `ACTION().params()`.\n\nExample: Params\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback($);\n}\n```\n\n### $.query\n\nType: `property`\n\nQuery string.\n\nReturns: `Object`\n\nValidovaný voľbou `query`. Z kódu sa nastavuje cez `ACTION().query()`.\n\nExample: Query\n```js\naction: function($) {\n\tvar page = $.query.page || 1;\n\t$.success(page);\n}\n```\n\n### $.user\n\nType: `property`\n\nAktuálny používateľ.\n\nReturns: `Object`\n\nPoužívateľ HTTP požiadavky (pozri [Autorizáciu](../../guides/authorization/)) alebo používateľ nastavený cez `ACTION().user()`. Pri anonymných volaniach je prázdny.\n\nExample: Používateľ\n```js\naction: function($) {\n\t$.success($.user.name);\n}\n```\n\n### $.config\n\nType: `property`\n\nVoľba `config` akcie.\n\nReturns: `Object`\n\nPrázdny objekt, ak akcia nemá `config`.\n\nExample: Config\n```js\naction: function($) {\n\t$.success($.config.table);\n}\n```\n\n### $.id\n\nType: `property`\n\nMeno bežiacej akcie.\n\nReturns: `String`\n\nV reťazci akcií meno aktuálnej akcie.\n\nExample: Meno\n```js\naction: function($) {\n\tconsole.log('Running', $.id);\n\t$.success();\n}\n```\n\n### $.controller\n\nType: `property`\n\nController HTTP požiadavky.\n\nReturns: `Controller`\n\n`undefined`, keď sa akcia volá z kódu bez controllera. `$.client` je to isté; `$.websocket` je nastavený, keď je controller WebSocket klient.\n\nExample: Controller\n```js\naction: function($) {\n\t$.success($.controller ? $.controller.url : 'code');\n}\n```\n\n### $.error\n\nType: `property`\n\nChyby volania.\n\nReturns: `ErrorBuilder`\n\n`ErrorBuilder`. `$.invalid()` doň pridáva; `$.error.length` je počet chýb.\n\nExample: Chyby\n```js\naction: function($) {\n\tif (!$.model.items.length) {\n\t\t$.invalid('No items', 'items');\n\t\treturn;\n\t}\n\t$.success();\n}\n```\n\n### $.response\n\nType: `property`\n\nOdpovede akcií v reťazci.\n\nReturns: `Object`\n\nObjekt s odpoveďami akcií, ktoré už v tom istom volaní skončili, podľa ich mien. Nasledujúca akcia reťazca ich môže použiť.\n\nExample: Predchádzajúca odpoveď\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tvar created = $.response.orders_create;\n\t\t$.success(created);\n\t}\n});\n```\n\n### $.xhr\n\nType: `property` · Since: `0.0.19`\n\nČi je požiadavka XHR požiadavkou.\n\nReturns: `Boolean`\n\n`true`, keď má HTTP požiadavka hlavičku `X-Requested-With: XMLHttpRequest`; `null` bez controllera.\n\nExample: XHR\n```js\naction: function($) {\n\tif ($.xhr)\n\t\t$.success();\n\telse\n\t\t$.redirect('/');\n}\n```\n\n### $.meta\n\nType: `property` · Since: `0.0.19`\n\nDefinícia akcie.\n\nReturns: `Object`\n\nObjekt odovzdaný do `NEWACTION()` so všetkými jeho možnosťami.\n\nExample: Meta\n```js\naction: function($) {\n\t$.success($.meta.name);\n}\n```\n\n### $.env\n\nType: `property`\n\nProstredie volania.\n\nReturns: `Any`\n\nHodnota odovzdaná do `ACTION().env()`; `undefined`, keď nie je nastavená. Použi ju, aby si akcii povedal, odkiaľ sa volá, napríklad z testu alebo z jobu. `$.action()` ju neodovzdá ďalej: na vnútornom volaní zavolaj `.env($)`.\n\nExample: Prostredie\n```js\nNEWACTION('orders_sync', {\n\taction: function($) {\n\t\tif ($.env === 'test') {\n\t\t\t$.success();\n\t\t\treturn;\n\t\t}\n\t\t$.success('synced');\n\t}\n});\n\nACTION('orders_sync').env('test').callback(console.log);\n```\n\n### $.ip\n\nType: `property`\n\nSkratky pre dáta požiadavky.\n\nReturns: `String`\n\n`$.ip`, `$.address`, `$.headers`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.split2`, `$.files`, `$.body`, `$.mobile`, `$.ua`, `$.language` a `$.sessionid` čítajú rovnaké vlastnosti controllera. Bez controllera sú prázdne (`null`, `''` alebo prázdne pole).\n\nExample: IP a agent\n```js\naction: function($) {\n\t$.success({ ip: $.ip, ua: $.ua });\n}\n```\n\n### $.success([value])\n\nType: `method`\n\nUkončí akciu objektom úspechu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Hodnota pre vlastnosť `value` |\n\nOdpovie `{ success: true, value: value }` (tvar pochádza z `DEF.onSuccess`). Bez hodnoty je `value` `undefined`.\n\nExample: Úspech\n```js\naction: function($) {\n\t$.success(UID());\n}\n```\n\n### $.invalid(error, [path], [index])\n\nType: `method`\n\nUkončí akciu chybou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number|Error` | yes |  | Chyba alebo HTTP status kód |\n| `path` | `String` | no |  | Pole, ku ktorému chyba patrí |\n| `index` | `Number` | no |  | Index položky v poli |\n\nReturns: `ErrorBuilder` Chyby\n\nPridá chybu do `$.error` a volanie zlyhá. Číslo nad 399 je HTTP status (`401`, `404`); reťazec je chybová správa. Callback volajúceho dostane `ErrorBuilder`, routa odpovie chybami. Vráti `$.error`.\n\nExample: Nenájdené\n```js\naction: function($) {\n\tDATA.read('products').id($.params.id).callback(function(err, response) {\n\t\tif (response)\n\t\t\t$.callback(response);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n}\n```\n\n### $.callback([value])\n\nType: `method`\n\nUkončí akciu hodnotou tak, ako je.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Odpoveď |\n\nReturns: `Function` Callback, ak sa volá bez argumentov\n\nOdpovie hodnotou `value` bez obalenia. Bez argumentov vráti callback `function(err, response)`, ktorý pridá `err` k chybám a odpovie hodnotou `response`. `$.pipe` je tá istá metóda. Do databázového `callback()` môžeš odovzdať aj samotný `$`.\n\nExample: Hodnota\n```js\naction: function($) {\n\t$.callback({ count: 5 });\n}\n```\n\nExample: Callback dotazu\n```js\naction: function($) {\n\tDATA.find('products').callback($.callback());\n}\n```\n\n### $.done([value])\n\nType: `method`\n\nVráti callback, ktorý ukončí akciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Boolean` | no |  | Hodnota objektu úspechu alebo `true` pre odpoveď |\n\nReturns: `Function` `function(err, response)`\n\nVráti `function(err, response)`. Chyba ukončí akciu s chybou; inak zavolá `$.success(value)` alebo `$.success(response)`, keď je `value` `true`.\n\nExample: Done\n```js\naction: function($, model) {\n\tmodel.id = UID();\n\tDATA.insert('products', model).callback($.done(model.id));\n}\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method`\n\nZavolá callback funkciu ako Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Funkcia, ktorej posledný argument je `function(err, response)` |\n| `a` | `Object` | no |  | Prvý argument |\n| `b` | `Object` | no |  | Druhý argument |\n| `c` | `Object` | no |  | Tretí argument |\n\nReturns: `Promise` Odpoveď\n\nZavolá `fn(a, b, c, callback)` a resolvne sa s odpoveďou. Chyba ukončí akciu cez `$.invalid()` a Promise sa nikdy nevyrieši.\n\nExample: Promisify\n```js\naction: async function($) {\n\tvar files = await $.promisify(F.Fs.readdir, PATH.public());\n\t$.success(files);\n}\n```\n\n### $.action(name, [payload])\n\nType: `method`\n\nSpustí inú akciu z akcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno alebo mená akcií |\n| `payload` | `Object` | no |  | Payload |\n\nReturns: `ActionCaller` Objekt volania\n\nRovnaké ako `ACTION()` s controllerom tejto akcie. Bez controllera dostane nové volanie používateľa, query a parametre tohto volania.\n\nExample: Vnorená akcia\n```js\naction: async function($, model) {\n\tvar response = await $.action('stock_check', model).promise($);\n\t$.success(response);\n}\n```\n\n### $.transform(name, value, [callback])\n\nType: `method`\n\nSpustí transformáciu s controllerom akcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno transformácie |\n| `value` | `Object` | yes |  | Hodnota |\n| `callback` | `Function` | no |  | `function(err, value)` |\n\nReturns: `Promise` Promise bez callbacku\n\nRovnaké ako `TRANSFORM()`, s controllerom (a jeho používateľom) akcie. Bez callbacku vráti Promise.\n\nExample: Transformácia\n```js\naction: async function($) {\n\tvar user = await DATA.read('users').id($.params.id).promise($);\n\t$.callback(await $.transform('user', user));\n}\n```\n\n### $.unauthorized(permission, [permission2], [...])\n\nType: `method`\n\nSkontroluje oprávnenia používateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | yes |  | Meno oprávnenia; môžu nasledovať ďalšie |\n\nReturns: `Boolean` `true`, keď používateľ nemá povolenie\n\nVráti `false`, keď má `$.user` aspoň jedno z oprávnení (v `permissions` alebo `roles`) alebo je `sa`/`su`. Inak zavolá `$.invalid(401)` a vráti `true`, takže stačí len vrátiť sa.\n\nExample: Kontrola\n```js\naction: function($) {\n\tif ($.unauthorized('reports'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.redirect(url)\n\nType: `method`\n\nPresmeruje HTTP požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Cieľová URL |\n\nPresmeruje controller na `url` a zruší akciu; volajúci nedostane žiadnu odpoveď.\n\nExample: Presmerovanie\n```js\naction: function($) {\n\t$.redirect('/login/');\n}\n```\n\n### $.invalidsafe(message, [error])\n\nType: `method`\n\nUkončí akciu so správou a zaloguje skutočnú chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | Chyba pre volajúceho alebo HTTP stavový kód |\n| `error` | `Error|String` | no |  | Chyba pre log |\n\nReturns: `ErrorBuilder` Chyby\n\nPridá `message` do `$.error` a volanie zlyhá, ako pri `$.invalid(message)`. `error` sa zapíše do chybového logu cez `F.error()` (pridá sa názov akcie a URL) a volajúcemu sa nepošle. Použi ho, keď má chyba podrobnosti, ktoré klient nesmie vidieť. Vráti `$.error`.\n\nExample: Skrytie podrobností\n```js\nNEWACTION('orders_invoice', {\n\taction: async function($) {\n\t\ttry {\n\t\t\tvar template = await F.FsPromises.readFile(PATH.root('templates/invoice.html'), 'utf8');\n\t\t\t$.success(template.length);\n\t\t} catch (e) {\n\t\t\t$.invalidsafe('The invoice can\\'t be created', e);\n\t\t}\n\t}\n});\n```\n\n### ACTION(name).callback(fn)\n\nType: `method`\n\nPrijme výsledok volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Options` | yes |  | `function(err, response)` alebo `$` |\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\n`fn(err, response)`; `err` je `ErrorBuilder` alebo `null`, Keď odovzdáš `$` inej akcie, chyby idú do jej `$.invalid()` a odpoveď do jej `$.callback()`. `.pipe()` je tá istá metóda.\n\nExample: Callback\n```js\nACTION('products_list').callback(function(err, response) {\n\tconsole.log(err ? err.toString() : response);\n});\n```\n\nExample: Odovzdanie inej akcii\n```js\naction: function($) {\n\tACTION('products_list').user($).callback($);\n}\n```\n\n### $.throw(error)\n\nType: `method`\n\nZapíše chybu do logu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | Chyba |\n\nReturns: `Options` Ten istý `$`\n\nOdovzdá `error` chybovému handleru frameworku (`DEF.onError`) s názvom akcie a URL: vypíše sa, uloží sa v `F.errors` a vyšle sa ako udalosť `error`. Akcia pokračuje; ak ju chceš ukončiť, zavolaj `$.invalid()`. Vráti `$`.\n\nExample: Zalogovanie a pokračovanie\n```js\nNEWACTION('orders_notify', {\n\taction: function($) {\n\t\tNOSQL('notifications').insert({ type: 'order', dtcreated: NOW }).callback(function(err) {\n\t\t\terr && $.throw(err);\n\t\t});\n\t\t$.success();\n\t}\n});\n```\n\n### $.touch([url])\n\nType: `method`\n\nVymaže uložený stav statického súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `$.url` | URL súboru |\n\nReturns: `Options` Ten istý `$`\n\nZavolá `TOUCH(url)`. Bez `url` použije URL požiadavky; bez controllera (akcia volaná z kódu) sa vymaže každý statický súbor. Použi ho po tom, ako akcia zmení súbor v `public/`. Vráti `$`.\n\nExample: Po zmene\n```js\nNEWACTION('theme_save', {\n\tinput: '*css:String',\n\taction: async function($, model) {\n\t\tawait F.FsPromises.writeFile(PATH.public('css/theme.css'), model.css);\n\t\t$.touch('/css/theme.css');\n\t\t$.success();\n\t}\n});\n```\n\n### ACTION(name).promise([$])\n\nType: `method`\n\nVráti Promise s výsledkom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | no |  | `$` akcie, ktorá dostane chyby |\n\nReturns: `Promise` Odpoveď\n\nResolvne sa s odpoveďou. Pri chybe sa rejectne s `Error`, ktorého správa obsahuje chyby; s `$` ide chyba namiesto toho do `$.invalid()` a Promise sa nevyrieši.\n\nExample: Await\n```js\nvar response = await ACTION('products_list').promise();\n```\n\n### ACTION(name).user(user)\n\nType: `method`\n\nNastaví používateľa volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object|Options` | yes |  | Objekt používateľa alebo `$` |\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\nNastaví `$.user`. Keď odovzdáš `$`, použije sa jeho používateľ.\n\nExample: Používateľ\n```js\nACTION('account_read').user({ id: '123', name: 'Peter' }).callback(console.log);\n```\n\n### ACTION(name).query(obj)\n\nType: `method`\n\nNastaví query string volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Query |\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\nNastaví objekt validovaný voľbou `query`.\n\nExample: Query\n```js\nACTION('products_list').query({ page: 2 }).callback(console.log);\n```\n\n### ACTION(name).params(obj)\n\nType: `method`\n\nNastaví URL parametre volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Parametre |\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\nNastaví objekt validovaný voľbou `params`.\n\nExample: Parametre\n```js\nACTION('products_read').params({ id: 'Jae9QB1c461f' }).callback(console.log);\n```\n\n### ACTION(name).ctrl(controller)\n\nType: `method`\n\nSpustí volanie s controllerom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Controller |\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\nAkcia dostane `$.controller` a skratky požiadavky. Prijíma controller alebo objekt s vlastnosťou `controller` (`$`).\n\nExample: Controller\n```js\nfunction handler($) {\n\tACTION('products_list').ctrl($).autorespond();\n}\n```\n\n### ACTION(name).autorespond()\n\nType: `method`\n\nPošle výsledok do controllera.\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\nPri chybe zavolá `controller.invalid(err)`; inak odpovie cez controller vo formáte nastavenom cez `$.output()` (predvolene JSON). Používajú ho routy s `-->`. Potrebuje controller.\n\nExample: Handler routy\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', function($) {\n\t\t$.action('products_list').autorespond();\n\t});\n};\n```\n\n### ACTION(name).status(fn)\n\nType: `method`\n\nPrijíma stavové správy z akcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\nAkcia ich posiela cez `$.status(a, b, c, d)`; argumenty idú do `fn`. Bez tejto metódy `$.status()` nerobí nič.\n\nExample: Stav\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\t$.status('started');\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').status(console.log).callback(console.log);\n```\n\n### ACTION(name).progress(fn)\n\nType: `method` · Since: `0.0.16`\n\nPrijíma správy o priebehu z akcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(a, b, c, d)` |\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\nAkcia ich posiela pomocou `$.progress(a, b, c, d)`; argumenty idú do `fn` s `$` ako `this`. Bez tejto metódy `$.progress()` nerobí nič.\n\nExample: Priebeh\n```js\nNEWACTION('import_run', {\n\taction: function($) {\n\t\tfor (var i = 1; i <= 10; i++)\n\t\t\t$.progress(i * 10);\n\t\t$.success();\n\t}\n});\n\nACTION('import_run').progress(p => console.log(p + '%')).callback(console.log);\n```\n\n### ACTION(name).config(obj)\n\nType: `method` · Since: `0.0.17`\n\nPridá konfiguráciu pre toto volanie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Kľúče pre `$.config` |\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\nKľúče `obj` sa zlúčia do kópie `config` akcie, takže `$.config` obsahuje oboje; definícia akcie sa nemení.\n\nExample: Config\n```js\nNEWACTION('report_build', {\n\tconfig: { format: 'pdf' },\n\taction: function($) {\n\t\t$.success($.config);\n\t}\n});\n\nACTION('report_build').config({ lang: 'en' }).callback(console.log);\n// { success: true, value: { format: 'pdf', lang: 'en' } }\n```\n\n### ACTION(name).env(value)\n\nType: `method`\n\nNastaví prostredie volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any|Options` | yes |  | Prostredie, napríklad `'test'`, alebo `$` |\n\nReturns: `ActionCaller` Objekt volania, na reťazenie\n\nNastaví `$.env` v akcii. Keď odovzdáš `$`, použije sa jeho `env`, takže vnútorné volanie si môže ponechať prostredie vonkajšieho.\n\nExample: Prostredie\n```js\nACTION('orders_sync').env('test').callback(console.log);\n```\n\nExample: Odovzdanie ďalej\n```js\nNEWACTION('orders_close', {\n\taction: async function($) {\n\t\tawait $.action('orders_sync').env($).promise($);\n\t\t$.success();\n\t}\n});\n```\n\n### SUCCESS([value])\n\nType: `method`\n\nVytvorí objekt úspechu, ktorým odpovedajú akcie a controllery.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Hodnota pre vlastnosť `value` |\n\nReturns: `Object` `{ success: true, value: value }`\n\nVráti `{ success: true, value: value }`. Tvar pochádza z `DEF.onSuccess`, tej istej funkcie, ktorú používa `$.success()`, takže vlastný `DEF.onSuccess` zmení oboje. Použi ho, keď si odpoveď skladáš sám, napríklad v controlleri alebo v callbacku.\n\nExample: Úspešná odpoveď v controlleri\n```js\nROUTE('POST /api/ping/', function($) {\n\t$.json(SUCCESS(NOW));\n});\n```\n","entries":[{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [payload], [controller])","since":"","deprecated":false},{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, callback)","since":"","deprecated":false},{"type":"method","name":"NEWTRANSFORM()","signature":"NEWTRANSFORM(name, fn, [id])","since":"","deprecated":false},{"type":"method","name":"TRANSFORM()","signature":"TRANSFORM(name, value, [callback], [controller])","since":"","deprecated":false},{"type":"event","name":"ON('@{action}')","signature":"ON('@' + name, function($, response) {})","since":"","deprecated":false},{"type":"config","name":"NEWACTION.action","signature":"action: Function","since":"","deprecated":false},{"type":"config","name":"NEWACTION.input","signature":"input: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.output","signature":"output: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.params","signature":"params: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.query","signature":"query: String|Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.user","signature":"user: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.permissions","signature":"permissions: String|Array","since":"","deprecated":false},{"type":"config","name":"NEWACTION.route","signature":"route: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.middleware","signature":"middleware: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.partial","signature":"partial: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.extend","signature":"extend: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.audit","signature":"audit: Boolean|String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.config","signature":"config: Object","since":"","deprecated":false},{"type":"config","name":"NEWACTION.timeout","signature":"timeout: Number","since":"0.0.16","deprecated":false},{"type":"config","name":"NEWACTION.cache","signature":"cache: true | { query, params, input, user, language, key, expire }","since":"","deprecated":false},{"type":"config","name":"NEWACTION.summary","signature":"summary: String","since":"","deprecated":false},{"type":"config","name":"NEWACTION.oninput","signature":"oninput: Function","since":"0.0.19","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.onoutput","signature":"onoutput: Function","since":"0.0.19","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.input","signature":"$.input","since":"0.0.19","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.config","signature":"$.config","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.xhr","signature":"$.xhr","since":"0.0.19","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"0.0.19","deprecated":false},{"type":"property","name":"$.env","signature":"$.env","since":"","deprecated":false},{"type":"property","name":"$.ip","signature":"$.ip","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [payload])","since":"","deprecated":false},{"type":"method","name":"$.transform()","signature":"$.transform(name, value, [callback])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized()","signature":"$.unauthorized(permission, [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.invalidsafe()","signature":"$.invalidsafe(message, [error])","since":"","deprecated":false},{"type":"method","name":"ACTION().callback()","signature":"ACTION(name).callback(fn)","since":"","deprecated":false},{"type":"method","name":"$.throw()","signature":"$.throw(error)","since":"","deprecated":false},{"type":"method","name":"$.touch()","signature":"$.touch([url])","since":"","deprecated":false},{"type":"method","name":"ACTION().promise()","signature":"ACTION(name).promise([$])","since":"","deprecated":false},{"type":"method","name":"ACTION().user()","signature":"ACTION(name).user(user)","since":"","deprecated":false},{"type":"method","name":"ACTION().query()","signature":"ACTION(name).query(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().params()","signature":"ACTION(name).params(obj)","since":"","deprecated":false},{"type":"method","name":"ACTION().ctrl()","signature":"ACTION(name).ctrl(controller)","since":"","deprecated":false},{"type":"method","name":"ACTION().autorespond()","signature":"ACTION(name).autorespond()","since":"","deprecated":false},{"type":"method","name":"ACTION().status()","signature":"ACTION(name).status(fn)","since":"","deprecated":false},{"type":"method","name":"ACTION().progress()","signature":"ACTION(name).progress(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ACTION().config()","signature":"ACTION(name).config(obj)","since":"0.0.17","deprecated":false},{"type":"method","name":"ACTION().env()","signature":"ACTION(name).env(value)","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([value])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwVXEVx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Schemas and validation","summary":"Inline schema types and modifiers, JSON schema keywords, schema methods and ErrorBuilder.","markdown":"---\ntitle: Schemas and validation\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/json-schemas/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Schemas and validation\n\n> Inline schema types and modifiers, JSON schema keywords, schema methods and ErrorBuilder.\n\nThe types and modifiers of inline schemas, the keywords of JSON schemas, the methods to register and run schemas, and the `ErrorBuilder` class. For an introduction with examples, read [Schemas and validation](../../guides/json-schemas/).\n\n## API\n\n### NEWSCHEMA(name, schema)\n\nType: `method`\n\nRegisters an inline schema under a name.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the schema; a leading `@` is ignored. |\n| `schema` | `String|Function` | yes |  | An inline schema, or a function that defines actions. |\n\nReturns: `Object` The JSON schema object when `schema` is a string.\n\nWith a string, the inline schema is parsed and stored in `F.jsonschemas[name]`. A leading `@` in the name is removed, so `'@Address'` and `'Address'` register the same name. Other schemas and actions use it as `@Address`.\n\nWith a function, the function receives an object with `name`, `actions` and `action(name, meta)`. `action()` creates an action called `<schema name>/<action name>` with [NEWACTION](../../guides/actions/).\n\nExample: Register and use a schema\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\nNEWSCHEMA('@Customer', '*name:String,address:@Address');\n\nNEWACTION('Customers/save', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: Actions in a schema\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('list', {\n\t\tquery: 'page:Number',\n\t\taction: function($) {\n\t\t\t$.callback([]);\n\t\t}\n\t});\n});\n// creates the action \"Orders/list\"\n```\n\n### '...'.toJSONSchema([name], [url])\n\nType: `method`\n\nParses an inline schema into a JSON schema object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Stores the schema in `F.jsonschemas` under this name and uses it in `$id`. |\n| `url` | `String` | no | `CONF.url` | The base URL of `$id`. |\n\nReturns: `Object` A JSON schema object.\n\nReturns an object with `$id`, `$schema`, `type: 'object'`, `properties`, `required`, `errors` (the `//` messages) and the methods `transform()` and `validate()`. With `name`, the schema is also stored in `F.jsonschemas[name]`.\n\nThe `$id` is `url + name + '.json'`. Without `url`, `CONF.url` is used, or `https://schemas.totaljs.com/`. Without `name`, a hash of the string is used. `String.parseSchema()` is the same method.\n\nExample: Parse and validate\n```js\nvar schema = '*name:String(50),email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'peter@example.com' });\nconsole.log(result.response);\n```\n\nExample: Register under a name\n```js\n'*street:String,*city:String'.toJSONSchema('Address');\n// F.jsonschemas.Address exists now\n```\n\n### F.newjsonschema(name, [schema])\n\nType: `method`\n\nRegisters a JSON schema or an inline schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | The name of the schema, an inline schema, or a JSON schema object with `$id`. |\n| `schema` | `Object|String` | no |  | A JSON schema object or an inline schema. |\n\nReturns: `Object` The registered schema.\n\nThe schema is stored in `F.jsonschemas` under the name and under its `$id`, and gets the `transform()` method. The forms:\n\n- `F.newjsonschema(object)`: a JSON schema object; its `$id` is the name.\n- `F.newjsonschema(name, object)`: a JSON schema object under `name`.\n- `F.newjsonschema(name, 'inline schema')`: an inline schema; `$id` is set to `name`.\n- `F.newjsonschema('inline schema')`: an inline schema registered under its generated `$id`.\n\nThe files of the `jsonschemas/` folder are registered with this method.\n\nExample: A JSON schema object\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tprice: { type: 'number', minimum: 1 }\n\t},\n\trequired: ['name']\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nExample: An inline schema\n```js\nF.newjsonschema('Contact', '*name:String,*email:Email');\n```\n\n### F.jsonschemas\n\nType: `property`\n\nAll registered schemas by name.\n\nReturns: `Object`\n\nAn object of every schema registered by `NEWSCHEMA()`, `F.newjsonschema()`, `toJSONSchema(name)` and the `jsonschemas/` folder. `@name` in inline schemas and actions, and `$ref` in JSON schemas, look up schemas here.\n\nExample: Validate with a registered schema\n```js\nNEWSCHEMA('@Contact', '*name:String,*email:Email');\n\nvar result = F.jsonschemas.Contact.transform({ name: 'Peter', email: 'bad' });\nif (result.error)\n\tconsole.log(result.error.output());\n```\n\n### jsonschemas/*.json\n\nType: `config`\n\nA folder of schemas loaded when the application starts.\n\nEvery `.json` file is parsed and registered with `F.newjsonschema()`; the file name without the extension is the name of the schema. The folder is loaded before the folders with code, so actions can use its schemas with `@name`.\n\nExample: jsonschemas/Address.json\n```js\n{\n\t\"$id\": \"Address\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" },\n\t\t\"zip\": { \"type\": \"string\", \"subtype\": \"zip\" }\n\t},\n\t\"required\": [\"street\", \"city\"]\n}\n```\n\nExample: Use it\n```js\nNEWACTION('Addresses/create', {\n\tinput: '@Address',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### schema.transform(value, [partial], [error], [path])\n\nType: `method`\n\nValidates and converts a value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value to validate. |\n| `partial` | `Boolean` | no | `false` | Validates only the fields that exist in the value. |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | A builder that receives the errors. |\n| `path` | `String` | no |  | A path prefix for the error paths. |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nReturns `{ error, response }`. `response` is the converted value: for an object schema, a new object with only the fields of the schema, or `undefined` when no field has a value. `error` is an `ErrorBuilder` with the errors, or `null` when there are none.\n\nWith `partial`, fields that are `undefined` in the value are skipped, so missing required fields do not fail. Pass your own `ErrorBuilder` as `error` to collect errors of several validations in one builder.\n\nExample: Validate a body\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'wrong' });\n\nif (result.error)\n\tconsole.log(result.error.output());\n\t// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'email' }]\nelse\n\tconsole.log(result.response);\n```\n\nExample: Partial update\n```js\nvar schema = '*name:String,*email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ age: 40 }, true);\n// result.response === { age: 40 }, result.error === null\n```\n\n### schema.validate(value, [partial], [path])\n\nType: `method`\n\nValidates a value and throws on the first error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value to validate. |\n| `partial` | `Boolean` | no | `false` | Validates only the fields that exist in the value. |\n| `path` | `String` | no |  | A path prefix for the error paths. |\n\nReturns: `Object` The converted value.\n\nReturns the converted value. When the value is not valid, it throws an `Error` with the message of the first error. Use it where an exception is simpler than checking `result.error`. Only schemas made from an inline schema have this method.\n\nExample: Throw on invalid data\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\n\ntry {\n\tvar model = schema.validate({ name: 'Peter' });\n} catch (e) {\n\tconsole.log(e.message); // The field \"email\" is invalid\n}\n```\n\n### schema.toAITool(name)\n\nType: `method`\n\nCreates an AI tool definition from an inline schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the tool. |\n\nReturns: `Object` The tool definition.\n\nReturns a function-tool object for AI models. Each field becomes a parameter with its `type` and, as its description, the `//` message of the field (an empty string without one). The required fields of the schema are the required parameters. The description of the tool is `schema.summary` or `schema.description` when you set one. It exists on schemas made from an inline schema (`toJSONSchema()`, `NEWSCHEMA()`), not on JSON schema objects registered with `F.newjsonschema()`. See [AI models](../../guides/ai-models/).\n\nExample: A tool from a schema\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nschema.description = 'Returns the weather forecast';\n\nvar tool = schema.toAITool('weather');\n// {\n//\t type: 'function',\n//\t function: {\n//\t\t name: 'weather',\n//\t\t description: 'Returns the weather forecast',\n//\t\t parameters: {\n//\t\t\t type: 'object',\n//\t\t\t properties: {\n//\t\t\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t\t\t days: { type: 'number', description: 'Number of days' }\n//\t\t\t },\n//\t\t\t required: ['city'],\n//\t\t\t additionalProperties: false\n//\t\t }\n//\t }\n// }\n```\n\n### schema.toAIObject(name, [description])\n\nType: `method`\n\nConverts an inline schema into a named JSON Schema object for AI models.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the object. |\n| `description` | `String` | no |  | A description of the object. |\n\nReturns: `Object` The JSON Schema object.\n\nReturns `{ name, description, type: 'object', properties, required, additionalProperties: false }`. The properties use standard JSON Schema: `Date` is `{ type: 'string', format: 'date-time' }`, `Email` has `format: 'email'`, an enum has `enum`, an array has `items`, and a type that can be `null` (such as `String2`, `UID`, `GUID`, `JSON`, `IP` or `Base64`) is `['string', 'null']`. The `//` message of a field is its `description`. `required` is left out when no field is required. Like `toAITool()`, it exists on schemas made from an inline schema.\n\nExample: A structured answer\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// {\n//\t name: 'forecast',\n//\t description: 'The weather forecast for a city',\n//\t properties: {\n//\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t days: { type: 'number', description: 'Number of days' }\n//\t },\n//\t type: 'object',\n//\t additionalProperties: false,\n//\t required: ['city']\n// }\n```\n\n### *name:Type  or  !name:Type\n\nType: `type`\n\nMarks a field of an inline schema as required.\n\nA required field fails when its value is empty. For strings that is an empty value before trimming (a text of only spaces passes and becomes `''`); for numbers a missing or non-numeric value (`0` passes); for booleans a missing value (`false` passes); for dates a value that can't be parsed; for arrays an empty array or a value that is not an array. A required nested object (`{...}` or `@name`) does not fail when it is missing. `!` is the same as `*`.\n\nExample: Required fields\n```js\nvar schema = '*name:String,*email:Email,phone:Phone'.toJSONSchema();\nvar result = schema.transform({ name: '' });\n// errors for \"name\" and \"email\"\n```\n\n### name:Type // Message\n\nType: `type`\n\nSets a custom error message for a field of an inline schema.\n\nThe text after `//` is the error message of the field. Because commas separate fields, the message can't contain a comma; write the schema on several lines (one field per line) when the messages are long. The messages are stored in `schema.errors`.\n\nExample: Custom messages\n```js\nvar schema = `*name:String // Enter your name\n\t*email:Email // Enter a valid email address`.toJSONSchema();\n\nvar result = schema.transform({ email: 'x' });\nconsole.log(result.error.output());\n// [{ name: 'name', error: 'Enter your name', ... }, { name: 'email', error: 'Enter a valid email address', ... }]\n```\n\n### name:String  name:String(max)  name:Text  name:String2\n\nType: `type`\n\nText values.\n\nAny value is converted to a string, trimmed, and non-breaking spaces become normal spaces. A missing value is `''`. `String(50)` sets the maximum length; a longer text is an error. The length is checked before trimming, so spaces around the text count. `Text` is the same as `String`. `String2` turns an empty value into `null`.\n\nExample: Strings\n```js\nvar schema = '*title:String(100),note:Text,code:String2'.toJSONSchema();\nschema.transform({ title: '  Hello  ', code: '' }).response;\n// { title: 'Hello', note: '', code: null }\n```\n\n### name:Number  (Number2, Int, Integer, Float, Decimal)\n\nType: `type`\n\nNumeric values.\n\nA number stays a number; a string with digits is parsed with `String.parseFloat()` (`'33'` gives `33`, `'1,5'` gives `1.5`). Other values are treated as missing and the field is left out of the response. `Number2`, `Int`, `Integer`, `Float` and `Decimal` are names of the same type.\n\nExample: Numbers\n```js\nvar schema = 'price:Number,count:Int'.toJSONSchema();\nschema.transform({ price: '9,90', count: '3' }).response;\n// { price: 9.9, count: 3 }\n```\n\n### name:SmallInt\n\nType: `type`\n\nA number from -32767 to 32767.\n\nParsed like `Number`; a value outside the range is an error.\n\nExample: SmallInt\n```js\n'priority:SmallInt'.toJSONSchema().transform({ priority: 40000 }).error.output();\n// [{ name: 'priority', error: 'The field \"priority\" is invalid', path: 'priority' }]\n```\n\n### name:TinyInt\n\nType: `type`\n\nA number from 0 to 255.\n\nParsed like `Number`; a value outside the range is an error.\n\nExample: TinyInt\n```js\n'level:TinyInt'.toJSONSchema().transform({ level: '12' }).response;\n// { level: 12 }\n```\n\n### name:Boolean  name:Bool\n\nType: `type`\n\nTrue or false.\n\nA boolean stays as it is; other values are parsed with `String.parseBoolean()` (`'true'`, `'1'`, `'on'` give `true`). The field is always in the response: a missing value is `false`.\n\nExample: Checkbox\n```js\n'newsletter:Boolean,terms:Bool'.toJSONSchema().transform({ newsletter: 'on' }).response;\n// { newsletter: true, terms: false }\n```\n\n### name:Date\n\nType: `type`\n\nA date.\n\nA `Date` stays as it is; other values are parsed with `String.parseDate()`. A value that can't be parsed, a missing value, or a date before 1 January 1970 is `null`.\n\nExample: Date\n```js\n'birthday:Date'.toJSONSchema().transform({ birthday: '1990-05-20' }).response;\n// { birthday: Date }\n```\n\n### name:Email\n\nType: `type`\n\nAn email address.\n\nAll whitespace is removed and the value is converted to lower case, then checked with `String.isEmail()`. An empty value is allowed unless the field is required.\n\nExample: Email\n```js\n'*email:Email'.toJSONSchema().transform({ email: ' Peter@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Email2\n\nType: `type`\n\nAn email address without its tag.\n\nWorks like `Email` and also removes the tag of the address: the part from `+` to `@`, so `name+tag@domain.com` becomes `name@domain.com`. Use it when one person must not register twice with tagged addresses. In JSON schemas it is `subtype: 'email2'`; `toAIObject()` and the MCP server describe it as `format: 'email'`.\n\nExample: Email2\n```js\n'*email:Email2'.toJSONSchema().transform({ email: ' Peter+News@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Phone\n\nType: `type`\n\nA phone number.\n\nWhitespace is removed, then the value is checked with `String.isPhone()`.\n\nExample: Phone\n```js\n'phone:Phone'.toJSONSchema().transform({ phone: '+421 900 123 456' }).response;\n// { phone: '+421900123456' }\n```\n\n### name:URL\n\nType: `type`\n\nA URL address.\n\nTrimmed and checked with `String.isURL()`.\n\nExample: URL\n```js\n'website:URL'.toJSONSchema().transform({ website: 'https://www.totaljs.com' }).response;\n```\n\n### name:Zip\n\nType: `type`\n\nA ZIP code.\n\nTrimmed and checked with `String.isZIP()`.\n\nExample: Zip\n```js\n'zip:Zip'.toJSONSchema().transform({ zip: '12345' }).response;\n```\n\n### name:UID\n\nType: `type`\n\nA Total.js unique identifier.\n\nTrimmed and checked with `String.isUID()`, the format made by `UID()`. An empty value becomes `null`.\n\nExample: UID\n```js\n'*id:UID'.toJSONSchema().transform({ id: UID() }).response;\n```\n\n### name:GUID\n\nType: `type`\n\nA GUID.\n\nTrimmed and checked with `String.isGUID()`. An empty value becomes `null`.\n\nExample: GUID\n```js\n'token:GUID'.toJSONSchema().transform({ token: GUID() }).response;\n```\n\n### name:Name\n\nType: `type`\n\nA person name.\n\nThe value is formatted with `String.toName()`: every word starts with an upper-case letter.\n\nExample: Name\n```js\n'fullname:Name'.toJSONSchema().transform({ fullname: 'peter sirka' }).response;\n// { fullname: 'Peter Sirka' }\n```\n\n### name:Lower  name:Lowercase  name:Upper  name:Uppercase\n\nType: `type`\n\nText in lower or upper case.\n\n`Lower` and `Lowercase` trim the value and convert it to lower case. `Upper` and `Uppercase` convert it to upper case.\n\nExample: Case\n```js\n'login:Lower,country:Upper'.toJSONSchema().transform({ login: 'PETER', country: 'sk' }).response;\n// { login: 'peter', country: 'SK' }\n```\n\n### name:Capitalize  name:Capitalize2\n\nType: `type`\n\nText with capital letters.\n\n`Capitalize` puts the first letter of every word in upper case. `Capitalize2` puts only the first letter of the text in upper case.\n\nExample: Capitalize\n```js\n'title:Capitalize,sentence:Capitalize2'.toJSONSchema().transform({ title: 'hello world', sentence: 'hello world' }).response;\n// { title: 'Hello World', sentence: 'Hello world' }\n```\n\n### name:Color\n\nType: `type`\n\nA hex color.\n\nThe value must be `#RGB`, `#RRGGBB` or `#RRGGBBAA` (letters in any case).\n\nExample: Color\n```js\n'color:Color'.toJSONSchema().transform({ color: '#4285F4' }).response;\n```\n\n### name:Icon\n\nType: `type`\n\nAn icon class.\n\nThe value must be an icon class of Total.js icons or Font Awesome: a prefix (`ti`, `tic`, `fa`, `far`, `fab`, `fad`, `fal`, `fas`), a space, and the icon name with a `ti-`, `tic-` or `fa-` prefix, for example `ti ti-home` or `fas fa-check`.\n\nExample: Icon\n```js\n'icon:Icon'.toJSONSchema().transform({ icon: 'ti ti-home' }).response;\n```\n\n### name:Base64\n\nType: `type`\n\nA Base64 string.\n\nTrimmed and checked with `String.isBase64()`. An empty value becomes `null`.\n\nExample: Base64\n```js\n'file:Base64'.toJSONSchema().transform({ file: 'SGVsbG8=' }).response;\n```\n\n### name:JSON\n\nType: `type`\n\nA JSON text.\n\nTrimmed and checked with `String.isJSON()`: the value must start and end like a JSON object, array or string, or be a number. The content is not parsed and the value stays a string; parse it with `String.parseJSON()` when you need the object. An empty value becomes `null`.\n\nExample: JSON\n```js\n'settings:JSON'.toJSONSchema().transform({ settings: '{\"theme\":\"dark\"}' }).response;\n// { settings: '{\"theme\":\"dark\"}' }\n\n'settings:JSON'.toJSONSchema().transform({ settings: 'dark' }).error.output();\n// [{ name: 'settings', error: 'The field \"settings\" is invalid', path: 'settings' }]\n```\n\n### name:DataURI\n\nType: `type`\n\nA data URI parsed into a buffer.\n\nThe value must be a Base64 data URI such as `data:image/png;base64,...`. It is parsed with `String.parseDataURI()` into `{ type, buffer }`, where `type` is the content type and `buffer` the decoded data. An empty value becomes `null`.\n\nExample: Upload a photo as JSON\n```js\nNEWACTION('Users/photo', {\n\tinput: '*photo:DataURI',\n\taction: function($, model) {\n\t\t// model.photo.type === 'image/png'\n\t\t// model.photo.buffer is a Buffer\n\t\t$.success();\n\t}\n});\n```\n\n### name:IP\n\nType: `type`\n\nAn IP address.\n\nTrimmed and checked with Node.js `net.isIP()`: a canonical IPv4 address (`10.0.0.1`) or an IPv6 address (`::1`). A host name or a short form such as `127.1` is invalid. An empty value becomes `null`.\n\nExample: IP\n```js\n'server:IP'.toJSONSchema().transform({ server: ' 10.0.0.1 ' }).response;\n// { server: '10.0.0.1' }\n\n'server:IP'.toJSONSchema().transform({ server: '10.0.0.300' }).error.output();\n// [{ name: 'server', error: 'The field \"server\" is invalid', path: 'server' }]\n```\n\n### name:DataURI2\n\nType: `type`\n\nA data URI kept as text.\n\nThe value must be a Base64 data URI, like `DataURI`, but it is not parsed: the response contains the original text. Use it when you store the data URI as it is. An empty value becomes `null`.\n\nExample: Keep the text\n```js\n'avatar:DataURI2'.toJSONSchema().transform({ avatar: 'data:image/png;base64,iVBORw0KGgo=' }).response;\n// { avatar: 'data:image/png;base64,iVBORw0KGgo=' }\n```\n\n### name:SafeString\n\nType: `type`\n\nText without XSS or SQL injection patterns.\n\nTrimmed and rejected when `String.isXSS()` or `String.isSQLInjection()` finds a dangerous pattern, such as an HTML tag.\n\nExample: SafeString\n```js\n'comment:SafeString'.toJSONSchema().transform({ comment: '<script>alert(1)</script>' }).error.output();\n// [{ name: 'comment', error: 'The field \"comment\" is invalid', path: 'comment' }]\n```\n\n### name:Search\n\nType: `type`\n\nA normalized search phrase.\n\nTrimmed and converted with `String.toSearch()`: lower case, without diacritics and with simplified letters, so it can be compared with indexed search text.\n\nExample: Search\n```js\n'q:Search'.toJSONSchema().transform({ q: 'Hello Wörld' }).response;\n// { q: 'helo world' }\n```\n\n### name:{a|b|c}  or  { type: 'string', enum: [...] }\n\nType: `type`\n\nA value from a fixed list.\n\nIn an inline schema, list the values in braces, separated by `|` or `;`. In a JSON schema, use the `enum` keyword with an array. A value that is not in the list is an error; an empty value is allowed unless the field is required.\n\nExample: Inline enum\n```js\n'*status:{draft|published|archived}'.toJSONSchema().transform({ status: 'published' }).response;\n```\n\nExample: JSON schema enum\n```js\nF.newjsonschema({\n\t$id: 'Task',\n\ttype: 'object',\n\tproperties: {\n\t\tpriority: { type: 'string', enum: ['low', 'normal', 'high'] }\n\t}\n});\n```\n\n### name:[Type]\n\nType: `type`\n\nAn array of values of one type.\n\nThe value must be an array; anything else leaves the field out (or fails when the field is required). Every item is converted to the type, for example `[Number]` turns `['1', 2]` into `[1, 2]`. `[{...}]` is an array of nested objects and `[@name]` an array validated by a registered schema; the error paths contain the index, such as `items[1].price`.\n\nExample: Arrays\n```js\nvar schema = 'tags:[String],scores:[Number],lines:[{sku:String,qty:Number}]'.toJSONSchema();\nschema.transform({ tags: ['a', ' b '], scores: ['1', 2], lines: [{ sku: 'A1', qty: '2' }] }).response;\n// { tags: ['a', 'b'], scores: [1, 2], lines: [{ sku: 'A1', qty: 2 }] }\n```\n\n### name:{field:Type,...}\n\nType: `type`\n\nA nested object.\n\nBraces with fields (not an enum) make a nested object with its own fields, modifiers and types. The nested object is validated like the main one and its errors have paths such as `address.city`. A nested object can contain further nested objects and arrays, for example `order:{lines:[{sku:String,qty:Number}],shipping:{address:{city:String}}}`.\n\nExample: Nested object\n```js\nvar schema = '*name:String,address:{street:String,*city:String,zip:Zip}'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', address: { street: 'Main 1' } });\n// error: { name: 'city', path: 'address.city' }\n```\n\n### name:@Schema  name:[@Schema]\n\nType: `type`\n\nA nested object validated by a registered schema.\n\nThe value is validated by the schema registered as `Schema` (with `NEWSCHEMA()`, `F.newjsonschema()` or the `jsonschemas/` folder). `[@Schema]` validates every item of an array. The errors keep the paths of the nested object.\n\nExample: Reuse a schema\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String');\nNEWSCHEMA('@Company', '*name:String,headquarters:@Address,branches:[@Address]');\n\nvar result = F.jsonschemas.Company.transform({ name: 'Acme', branches: [{ street: 'A 1', city: 'X' }, { street: 'B 2' }] });\n// error: { name: 'city', path: 'branches[1].city', index: 1 }\n```\n\n### required: ['field', ...]\n\nType: `property`\n\nThe required fields of an object schema.\n\nAn array of property names. The rules for empty values are the same as for `*` in inline schemas.\n\nExample: required\n```js\nF.newjsonschema({\n\t$id: 'Login',\n\ttype: 'object',\n\tproperties: {\n\t\temail: { type: 'string', subtype: 'email' },\n\t\tpassword: { type: 'string' }\n\t},\n\trequired: ['email', 'password']\n});\n```\n\n### { type: 'string', subtype: 'email' }\n\nType: `property`\n\nA Total.js keyword that selects a special conversion.\n\nFor `string` properties, `subtype` uses the conversion of an inline type: `email`, `email2`, `phone`, `url`, `zip`, `uid`, `guid`, `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`, `color`, `icon`, `base64`, `datauri`, `datauri2`, `safestring`, `search`, `json` or `ip`. `ipaddress` is the same as `ip` and exists only in JSON schemas. For `number` properties, `smallint` and `tinyint` check the range. An empty string stays `''`; add `nullable: true` to get `null`.\n\nExample: subtype\n```js\nF.newjsonschema({\n\t$id: 'Server',\n\ttype: 'object',\n\tproperties: {\n\t\thost: { type: 'string', subtype: 'ip' },\n\t\tconfig: { type: 'string', subtype: 'json' },\n\t\tport: { type: 'number', subtype: 'smallint' }\n\t}\n});\n```\n\n### { type: 'string', nullable: true }\n\nType: `property`\n\nA Total.js keyword that turns an empty string into null.\n\nFor a `string` property, an empty value becomes `null` instead of `''`. Inline types `String2`, `UID`, `GUID`, `Base64`, `DataURI` and `DataURI2` set it for you.\n\nExample: nullable\n```js\nvar schema = F.newjsonschema({ $id: 'Note', type: 'object', properties: { text: { type: 'string', nullable: true } } });\nschema.transform({ text: '' }).response;\n// { text: null }\n```\n\n### { type: 'string', minLength: 3, maxLength: 50 }\n\nType: `property`\n\nThe length limits of a string.\n\n`minLength` and `maxLength` check the number of characters of a string. `String(50)` in an inline schema sets `maxLength`.\n\nExample: Length\n```js\nF.newjsonschema({\n\t$id: 'Nick',\n\ttype: 'object',\n\tproperties: { nick: { type: 'string', minLength: 3, maxLength: 20 } }\n});\n```\n\n### { type: 'number', minimum: 1, maximum: 100 }\n\nType: `property`\n\nThe limits of a number.\n\n`minimum` and `maximum` are inclusive limits, `exclusiveMinimum` and `exclusiveMaximum` exclusive ones. `multipleOf` requires a value divisible by the given number.\n\nExample: Number limits\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\tquantity: { type: 'number', minimum: 1, maximum: 100 },\n\t\tdiscount: { type: 'number', exclusiveMaximum: 50 },\n\t\tpack: { type: 'number', multipleOf: 6 }\n\t}\n});\n```\n\n### { type: 'array', items: { type: 'string' } }\n\nType: `property`\n\nThe schema of the items of an array.\n\n`items` is one schema for every item: a type with its keywords (`string`, `number`, `boolean`, `date`), an `object` with its own `properties` and `required`, or a `$ref`. Each item of an object is validated and converted like a nested object; an error of an item has the name and the path `field.property` and the position of the item in `index`. `minItems` sets the smallest number of items of a non-empty array; an empty array fails only when the field is required. `uniqueItems: true` removes duplicate values.\n\nExample: Array of tags\n```js\nF.newjsonschema({\n\t$id: 'Article',\n\ttype: 'object',\n\tproperties: {\n\t\ttags: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true }\n\t}\n});\n\nF.jsonschemas.Article.transform({ tags: ['a', 'b', 'a'] }).response;\n// { tags: ['a', 'b'] }\n```\n\nExample: Array of objects\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\titems: { type: 'array', items: { type: 'object', properties: { sku: { type: 'string' }, qty: { type: 'number' } }, required: ['qty'] } }\n\t}\n});\n\nvar result = F.jsonschemas.Order.transform({ items: [{ sku: 'A', qty: '2' }, { sku: 'B' }] });\n// result.error.items[0]: name 'items.qty', path 'items.qty', index 1\n```\n\n### { type: 'object', $ref: '#/definitions/Name' }\n\nType: `property`\n\nA reference to another schema.\n\n`$ref` validates an object (or every item of an array, in `items`) by another schema. A value starting with `#/` points to the `definitions` of the same schema, for example `#/definitions/Address`. Any other value is the name or `$id` of a schema registered in `F.jsonschemas`.\n\nExample: Local and registered references\n```js\nF.newjsonschema({ $id: 'Address', type: 'object', properties: { city: { type: 'string' } }, required: ['city'] });\n\nF.newjsonschema({\n\t$id: 'Invoice',\n\ttype: 'object',\n\tproperties: {\n\t\tbilling: { type: 'object', $ref: 'Address' },\n\t\tlines: { type: 'array', items: { $ref: '#/definitions/Line' } }\n\t},\n\tdefinitions: {\n\t\tLine: { type: 'object', properties: { name: { type: 'string' }, price: { type: 'number' } } }\n\t}\n});\n```\n\n### new ErrorBuilder()\n\nType: `class`\n\nA list of errors with an HTTP status.\n\nReturns: `ErrorBuilder`\n\nValidation returns its errors in an `ErrorBuilder`, and actions and controllers answer with it as a JSON array. You can create one to collect your own errors. Its properties: `items` (the raw errors), `length` (the number of errors), `status` (the HTTP status, `400` by default) and `prefix` (a text put before the names of field errors).\n\nExample: Collect errors\n```js\nvar err = new ErrorBuilder();\n\nif (!model.email)\n\terr.push2('email');\n\nif (model.age < 18)\n\terr.push('You must be 18 or older');\n\nif (err.length)\n\tconsole.log(err.output());\n```\n\n### err.push(error, [path], [index])\n\nType: `method`\n\nAdds an error message or an HTTP status.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number` | yes |  | A message or an HTTP status code. |\n| `path` | `String` | no |  | The path of the field. |\n| `index` | `Number` | no |  | The index of an array item. |\n\nReturns: `ErrorBuilder` The same builder.\n\nA number from 400 up sets `status` and adds the HTTP status text, for example `404` adds `404: Not Found`. Any other value is added as the message. Without a value, `401` is pushed. A message that starts with `@(` is translated by `output()`, for example `err.push('@(Access denied)')`.\n\nExample: Messages and statuses\n```js\nvar err = new ErrorBuilder();\nerr.push('The product is sold out');\nerr.push(409);\nerr.status;\t // 409\nerr.output();   // [{ error: 'The product is sold out' }, { error: '409: Conflict' }]\n```\n\n### err.push2(name, [path], [index], [error])\n\nType: `method`\n\nAdds an error of a field, with an optional message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the field. |\n| `path` | `String` | no |  | The path of the field. |\n| `index` | `Number` | no |  | The index of an array item. |\n\nReturns: `ErrorBuilder` The same builder.\n\nAdds an error for the field `name` (with `prefix` before it). Without `error`, the message is resolved by `output()`: first the `//` messages of the schema, then the resource with the field name in the language of the output, then `The field \"name\" is invalid`. With `error`, that text is the message.\n\nSignature: `err.push2(name, [path], [index], [error])`.\n\nExample: Field error\n```js\nvar err = new ErrorBuilder();\nerr.push2('email', 'contact.email');\nerr.output();\n// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'contact.email' }]\n```\n\n### err.output([language])\n\nType: `method`\n\nReturns the errors as an array of objects.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | The language for resources and translations. |\n\nReturns: `Array` The list of errors.\n\nEach item is `{ name, error, path, index }` with the final message. Messages of field errors are read from the resources of `language`, `@(...)` texts are translated, and the replacements of `replace()` are applied. When a global `ErrorBuilder.transform()` handler exists, its result is returned instead.\n\nExample: Output\n```js\nvar err = new ErrorBuilder();\nerr.push2('name');\nconsole.log(err.output('en'));\n```\n\n### err.toString([language], [divider])\n\nType: `method`\n\nReturns the messages as one text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | The language. |\n| `divider` | `String` | no | `'\\n'` | The text between messages. |\n\nReturns: `String`\n\nThe messages of `output(language)` joined by `divider`.\n\nExample: Text\n```js\nvar err = new ErrorBuilder();\nerr.push('First');\nerr.push('Second');\nerr.toString();\t\t\t   // 'First\\nSecond'\nerr.toString('default', ', '); // 'First, Second'\n```\n\n### err.reject([language])\n\nType: `method`\n\nReturns the errors as an Error object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | The language. |\n\nReturns: `Error`\n\nCreates `new Error()` with all messages joined without a divider. Useful to reject a promise.\n\nExample: Reject a promise\n```js\nreturn new Promise(function(resolve, reject) {\n\tvar err = new ErrorBuilder();\n\terr.push('Not allowed');\n\treject(err.reject());\n});\n```\n\n### err.throw()\n\nType: `method`\n\nMakes the builder throw on the next error.\n\nReturns: `ErrorBuilder` The same builder.\n\nAfter `throw()`, every `push()` or `push2()` throws an `Error` with the message of the first error. `schema.validate()` uses it.\n\nExample: Throw at once\n```js\nvar err = new ErrorBuilder().throw();\ntry {\n\terr.push('Invalid token');\n} catch (e) {\n\tconsole.log(e.message); // Invalid token\n}\n```\n\n### err.replace(search, value)\n\nType: `method`\n\nReplaces a text in all messages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String` | yes |  | The text to find. |\n| `value` | `String` | yes |  | The new text. |\n\nReturns: `ErrorBuilder` The same builder.\n\nThe replacement is applied by `output()` to every message, so you can push a message with a placeholder and fill it later.\n\nExample: Placeholder\n```js\nvar err = new ErrorBuilder();\nerr.push('The limit is {limit} items');\nerr.replace('{limit}', 10);\nerr.toString(); // 'The limit is 10 items'\n```\n\n### ErrorBuilder.assign(value)\n\nType: `method`\n\nCreates a builder from an error output, a message or an Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Array|String|Number|Error` | yes |  | The errors. |\n\nReturns: `ErrorBuilder` A new builder.\n\nWith an array, every item that has `error` is added (for example the JSON errors returned by another Total.js app). A number or a string is pushed, and an `Error` is pushed as its text.\n\nExample: Errors from another service\n```js\nvar err = ErrorBuilder.assign([{ name: 'email', error: 'Email is taken' }]);\nerr.length; // 1\n```\n\n### ErrorBuilder.transform(callback)\n\nType: `method`\n\nSets a global handler that changes the output of every ErrorBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(output, language)` that returns the new output. |\n\n`callback(output, language)` receives the array made by `output()` and returns what `output()` returns instead. Because actions and controllers send `output()` to the client, this changes the format of all error responses.\n\nExample: A custom error format\n```js\nErrorBuilder.transform(function(output, language) {\n\treturn { success: false, errors: output };\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, schema)","since":"","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"'...'.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"F.newjsonschema()","signature":"F.newjsonschema(name, [schema])","since":"","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"jsonschemas/","signature":"jsonschemas/*.json","since":"","deprecated":false},{"type":"method","name":"schema.transform()","signature":"schema.transform(value, [partial], [error], [path])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(value, [partial], [path])","since":"","deprecated":false},{"type":"method","name":"schema.toAITool()","signature":"schema.toAITool(name)","since":"","deprecated":false},{"type":"method","name":"schema.toAIObject()","signature":"schema.toAIObject(name, [description])","since":"","deprecated":false},{"type":"type","name":"*field","signature":"*name:Type  or  !name:Type","since":"","deprecated":false},{"type":"type","name":"// message","signature":"name:Type // Message","since":"","deprecated":false},{"type":"type","name":"String","signature":"name:String  name:String(max)  name:Text  name:String2","since":"","deprecated":false},{"type":"type","name":"Number","signature":"name:Number  (Number2, Int, Integer, Float, Decimal)","since":"","deprecated":false},{"type":"type","name":"SmallInt","signature":"name:SmallInt","since":"","deprecated":false},{"type":"type","name":"TinyInt","signature":"name:TinyInt","since":"","deprecated":false},{"type":"type","name":"Boolean","signature":"name:Boolean  name:Bool","since":"","deprecated":false},{"type":"type","name":"Date","signature":"name:Date","since":"","deprecated":false},{"type":"type","name":"Email","signature":"name:Email","since":"","deprecated":false},{"type":"type","name":"Email2","signature":"name:Email2","since":"","deprecated":false},{"type":"type","name":"Phone","signature":"name:Phone","since":"","deprecated":false},{"type":"type","name":"URL","signature":"name:URL","since":"","deprecated":false},{"type":"type","name":"Zip","signature":"name:Zip","since":"","deprecated":false},{"type":"type","name":"UID","signature":"name:UID","since":"","deprecated":false},{"type":"type","name":"GUID","signature":"name:GUID","since":"","deprecated":false},{"type":"type","name":"Name","signature":"name:Name","since":"","deprecated":false},{"type":"type","name":"Lower / Upper","signature":"name:Lower  name:Lowercase  name:Upper  name:Uppercase","since":"","deprecated":false},{"type":"type","name":"Capitalize","signature":"name:Capitalize  name:Capitalize2","since":"","deprecated":false},{"type":"type","name":"Color","signature":"name:Color","since":"","deprecated":false},{"type":"type","name":"Icon","signature":"name:Icon","since":"","deprecated":false},{"type":"type","name":"Base64","signature":"name:Base64","since":"","deprecated":false},{"type":"type","name":"JSON","signature":"name:JSON","since":"","deprecated":false},{"type":"type","name":"DataURI","signature":"name:DataURI","since":"","deprecated":false},{"type":"type","name":"IP","signature":"name:IP","since":"","deprecated":false},{"type":"type","name":"DataURI2","signature":"name:DataURI2","since":"","deprecated":false},{"type":"type","name":"SafeString","signature":"name:SafeString","since":"","deprecated":false},{"type":"type","name":"Search","signature":"name:Search","since":"","deprecated":false},{"type":"type","name":"Enum","signature":"name:{a|b|c}  or  { type: 'string', enum: [...] }","since":"","deprecated":false},{"type":"type","name":"Array","signature":"name:[Type]","since":"","deprecated":false},{"type":"type","name":"Object","signature":"name:{field:Type,...}","since":"","deprecated":false},{"type":"type","name":"@name","signature":"name:@Schema  name:[@Schema]","since":"","deprecated":false},{"type":"property","name":"required","signature":"required: ['field', ...]","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"{ type: 'string', subtype: 'email' }","since":"","deprecated":false},{"type":"property","name":"nullable","signature":"{ type: 'string', nullable: true }","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"{ type: 'string', minLength: 3, maxLength: 50 }","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"{ type: 'number', minimum: 1, maximum: 100 }","since":"","deprecated":false},{"type":"property","name":"items","signature":"{ type: 'array', items: { type: 'string' } }","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"{ type: 'object', $ref: '#/definitions/Name' }","since":"","deprecated":false},{"type":"class","name":"ErrorBuilder","signature":"new ErrorBuilder()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push()","signature":"err.push(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push2()","signature":"err.push2(name, [path], [index], [error])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.output()","signature":"err.output([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.toString()","signature":"err.toString([language], [divider])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.reject()","signature":"err.reject([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.throw()","signature":"err.throw()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.replace()","signature":"err.replace(search, value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.assign()","signature":"ErrorBuilder.assign(value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.transform()","signature":"ErrorBuilder.transform(callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwVXEVx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Schemas und Validierung","summary":"Typen und Modifikatoren von Inline-Schemas, Schlüsselwörter von JSON-Schemas, Schema-Methoden und ErrorBuilder.","markdown":"---\ntitle: Schemas und Validierung\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/json-schemas/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Schemas und Validierung\n\n> Typen und Modifikatoren von Inline-Schemas, Schlüsselwörter von JSON-Schemas, Schema-Methoden und ErrorBuilder.\n\nDie Typen und Modifikatoren von Inline-Schemas, die Schlüsselwörter von JSON-Schemas, die Methoden zum Registrieren und Ausführen von Schemas und die Klasse `ErrorBuilder`. Eine Einführung mit Beispielen findest du in [Schemas und Validierung](../../guides/json-schemas/).\n\n## API\n\n### NEWSCHEMA(name, schema)\n\nType: `method`\n\nRegistriert ein Inline-Schema unter einem Namen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Schemas; ein führendes `@` wird ignoriert. |\n| `schema` | `String|Function` | yes |  | Ein Inline-Schema oder eine Funktion, die Aktionen definiert. |\n\nReturns: `Object` Das JSON-Schema-Objekt, wenn `schema` ein String ist.\n\nMit einem String wird das Inline-Schema geparst und in `F.jsonschemas[name]` gespeichert. Ein führendes `@` im Namen wird entfernt, sodass `'@Address'` und `'Address'` denselben Namen registrieren. Andere Schemas und Aktionen verwenden es als `@Address`.\n\nMit einer Funktion erhält die Funktion ein Objekt mit `name`, `actions` und `action(name, meta)`. `action()` erstellt mit [NEWACTION](../../guides/actions/) eine Aktion namens `<schema name>/<action name>`.\n\nExample: Ein Schema registrieren und verwenden\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\nNEWSCHEMA('@Customer', '*name:String,address:@Address');\n\nNEWACTION('Customers/save', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: Aktionen in einem Schema\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('list', {\n\t\tquery: 'page:Number',\n\t\taction: function($) {\n\t\t\t$.callback([]);\n\t\t}\n\t});\n});\n// creates the action \"Orders/list\"\n```\n\n### '...'.toJSONSchema([name], [url])\n\nType: `method`\n\nParst ein Inline-Schema in ein JSON-Schema-Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Speichert das Schema in `F.jsonschemas` unter diesem Namen und verwendet ihn in `$id`. |\n| `url` | `String` | no | `CONF.url` | Die Basis-URL von `$id`. |\n\nReturns: `Object` Ein JSON-Schema-Objekt.\n\nGibt ein Objekt mit `$id`, `$schema`, `type: 'object'`, `properties`, `required`, `errors` (den `//`-Meldungen) und den Methoden `transform()` und `validate()` zurück. Mit `name` wird das Schema auch in `F.jsonschemas[name]` gespeichert.\n\nDie `$id` ist `url + name + '.json'`. Ohne `url` wird `CONF.url` verwendet oder `https://schemas.totaljs.com/`. Ohne `name` wird ein Hash des Strings verwendet. `String.parseSchema()` ist dieselbe Methode.\n\nExample: Parsen und validieren\n```js\nvar schema = '*name:String(50),email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'peter@example.com' });\nconsole.log(result.response);\n```\n\nExample: Unter einem Namen registrieren\n```js\n'*street:String,*city:String'.toJSONSchema('Address');\n// F.jsonschemas.Address exists now\n```\n\n### F.newjsonschema(name, [schema])\n\nType: `method`\n\nRegistriert ein JSON-Schema oder ein Inline-Schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Der Name des Schemas, ein Inline-Schema oder ein JSON-Schema-Objekt mit `$id`. |\n| `schema` | `Object|String` | no |  | Ein JSON-Schema-Objekt oder ein Inline-Schema. |\n\nReturns: `Object` Das registrierte Schema.\n\nDas Schema wird in `F.jsonschemas` unter dem Namen und unter seiner `$id` gespeichert und erhält die Methode `transform()`. Die Formen:\n\n- `F.newjsonschema(object)`: ein JSON-Schema-Objekt; seine `$id` ist der Name.\n- `F.newjsonschema(name, object)`: ein JSON-Schema-Objekt unter `name`.\n- `F.newjsonschema(name, 'inline schema')`: ein Inline-Schema; `$id` wird auf `name` gesetzt.\n- `F.newjsonschema('inline schema')`: ein Inline-Schema, registriert unter seiner generierten `$id`.\n\nDie Dateien des Ordners `jsonschemas/` werden mit dieser Methode registriert.\n\nExample: Ein JSON-Schema-Objekt\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tprice: { type: 'number', minimum: 1 }\n\t},\n\trequired: ['name']\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nExample: Ein Inline-Schema\n```js\nF.newjsonschema('Contact', '*name:String,*email:Email');\n```\n\n### F.jsonschemas\n\nType: `property`\n\nAlle registrierten Schemas nach Namen.\n\nReturns: `Object`\n\nEin Objekt mit jedem Schema, das von `NEWSCHEMA()`, `F.newjsonschema()`, `toJSONSchema(name)` und dem Ordner `jsonschemas/` registriert wurde. `@name` in Inline-Schemas und Aktionen sowie `$ref` in JSON-Schemas suchen Schemas hier.\n\nExample: Mit einem registrierten Schema validieren\n```js\nNEWSCHEMA('@Contact', '*name:String,*email:Email');\n\nvar result = F.jsonschemas.Contact.transform({ name: 'Peter', email: 'bad' });\nif (result.error)\n\tconsole.log(result.error.output());\n```\n\n### jsonschemas/*.json\n\nType: `config`\n\nEin Ordner mit Schemas, der beim Start der Anwendung geladen wird.\n\nJede `.json`-Datei wird geparst und mit `F.newjsonschema()` registriert; der Dateiname ohne Endung ist der Name des Schemas. Der Ordner wird vor den Ordnern mit Code geladen, sodass Aktionen seine Schemas mit `@name` verwenden können.\n\nExample: jsonschemas/Address.json\n```js\n{\n\t\"$id\": \"Address\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" },\n\t\t\"zip\": { \"type\": \"string\", \"subtype\": \"zip\" }\n\t},\n\t\"required\": [\"street\", \"city\"]\n}\n```\n\nExample: Verwendung\n```js\nNEWACTION('Addresses/create', {\n\tinput: '@Address',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### schema.transform(value, [partial], [error], [path])\n\nType: `method`\n\nValidiert und konvertiert einen Wert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der zu validierende Wert. |\n| `partial` | `Boolean` | no | `false` | Validiert nur die Felder, die im Wert vorhanden sind. |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Ein Builder, der die Fehler erhält. |\n| `path` | `String` | no |  | Ein Pfadpräfix für die Fehlerpfade. |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nGibt `{ error, response }` zurück. `response` ist der umgewandelte Wert: bei einem Objektschema ein neues Objekt nur mit den Feldern des Schemas, oder `undefined`, wenn kein Feld einen Wert hat. `error` ist ein `ErrorBuilder` mit den Fehlern oder `null`, wenn es keine gibt.\n\nMit `partial` werden Felder übersprungen, die im Wert `undefined` sind, sodass fehlende Pflichtfelder nicht fehlschlagen. Übergib deinen eigenen `ErrorBuilder` als `error`, um die Fehler mehrerer Validierungen in einem Builder zu sammeln.\n\nExample: Einen Body validieren\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'wrong' });\n\nif (result.error)\n\tconsole.log(result.error.output());\n\t// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'email' }]\nelse\n\tconsole.log(result.response);\n```\n\nExample: Teilweises Update\n```js\nvar schema = '*name:String,*email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ age: 40 }, true);\n// result.response === { age: 40 }, result.error === null\n```\n\n### schema.validate(value, [partial], [path])\n\nType: `method`\n\nValidiert einen Wert und wirft beim ersten Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der zu validierende Wert. |\n| `partial` | `Boolean` | no | `false` | Validiert nur die Felder, die im Wert vorhanden sind. |\n| `path` | `String` | no |  | Ein Pfadpräfix für die Fehlerpfade. |\n\nReturns: `Object` Der konvertierte Wert.\n\nGibt den konvertierten Wert zurück. Ist der Wert ungültig, wirft sie einen `Error` mit der Meldung des ersten Fehlers. Verwende sie dort, wo eine Exception einfacher ist als die Prüfung von `result.error`. Nur Schemas, die aus einem Inline-Schema erstellt wurden, haben diese Methode.\n\nExample: Bei ungültigen Daten werfen\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\n\ntry {\n\tvar model = schema.validate({ name: 'Peter' });\n} catch (e) {\n\tconsole.log(e.message); // The field \"email\" is invalid\n}\n```\n\n### schema.toAITool(name)\n\nType: `method`\n\nErstellt eine KI-Tool-Definition aus einem Inline-Schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Tools. |\n\nReturns: `Object` Die Tool-Definition.\n\nGibt ein Function-Tool-Objekt für KI-Modelle zurück. Jedes Feld wird zu einem Parameter mit seinem `type` und, als Beschreibung, der `//`-Meldung des Feldes (ein leerer String, wenn es keine gibt). Die erforderlichen Felder des Schemas sind die erforderlichen Parameter. Die Beschreibung des Tools ist `schema.summary` oder `schema.description`, wenn du eine setzt. Es existiert an Schemas, die aus einem Inline-Schema erzeugt wurden (`toJSONSchema()`, `NEWSCHEMA()`), nicht an JSON-Schema-Objekten, die mit `F.newjsonschema()` registriert wurden. Siehe [KI-Modelle](../../guides/ai-models/).\n\nExample: Ein Tool aus einem Schema\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nschema.description = 'Returns the weather forecast';\n\nvar tool = schema.toAITool('weather');\n// {\n//\t type: 'function',\n//\t function: {\n//\t\t name: 'weather',\n//\t\t description: 'Returns the weather forecast',\n//\t\t parameters: {\n//\t\t\t type: 'object',\n//\t\t\t properties: {\n//\t\t\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t\t\t days: { type: 'number', description: 'Number of days' }\n//\t\t\t },\n//\t\t\t required: ['city'],\n//\t\t\t additionalProperties: false\n//\t\t }\n//\t }\n// }\n```\n\n### schema.toAIObject(name, [description])\n\nType: `method`\n\nWandelt ein Inline-Schema in ein benanntes JSON-Schema-Objekt für KI-Modelle um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Objekts. |\n| `description` | `String` | no |  | Eine Beschreibung des Objekts. |\n\nReturns: `Object` Das JSON-Schema-Objekt.\n\nGibt `{ name, description, type: 'object', properties, required, additionalProperties: false }` zurück. Die Eigenschaften verwenden Standard-JSON-Schema: `Date` ist `{ type: 'string', format: 'date-time' }`, `Email` hat `format: 'email'`, ein Enum hat `enum`, ein Array hat `items`, und ein Typ, der `null` sein kann (etwa `String2`, `UID`, `GUID`, `JSON`, `IP` oder `Base64`), ist `['string', 'null']`. Die `//`-Meldung eines Feldes ist seine `description`. `required` entfällt, wenn kein Feld erforderlich ist. Wie `toAITool()` existiert es an Schemas, die aus einem Inline-Schema erzeugt wurden.\n\nExample: Eine strukturierte Antwort\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// {\n//\t name: 'forecast',\n//\t description: 'The weather forecast for a city',\n//\t properties: {\n//\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t days: { type: 'number', description: 'Number of days' }\n//\t },\n//\t type: 'object',\n//\t additionalProperties: false,\n//\t required: ['city']\n// }\n```\n\n### *name:Type  or  !name:Type\n\nType: `type`\n\nMarkiert ein Feld eines Inline-Schemas als Pflichtfeld.\n\nEin Pflichtfeld schlägt fehl, wenn sein Wert leer ist. Bei Strings ist das ein leerer Wert vor dem Trimmen (ein Text nur aus Leerzeichen besteht die Prüfung und wird zu `''`); bei Zahlen ein fehlender oder nicht numerischer Wert (`0` besteht); bei Booleans ein fehlender Wert (`false` besteht); bei Datumswerten ein Wert, der nicht geparst werden kann; bei Arrays ein leeres Array oder ein Wert, der kein Array ist. Ein verschachteltes Pflichtobjekt (`{...}` oder `@name`) schlägt nicht fehl, wenn es fehlt. `!` ist dasselbe wie `*`.\n\nExample: Pflichtfelder\n```js\nvar schema = '*name:String,*email:Email,phone:Phone'.toJSONSchema();\nvar result = schema.transform({ name: '' });\n// errors for \"name\" and \"email\"\n```\n\n### name:Type // Message\n\nType: `type`\n\nSetzt eine eigene Fehlermeldung für ein Feld eines Inline-Schemas.\n\nDer Text nach `//` ist die Fehlermeldung des Feldes. Da Kommas die Felder trennen, darf die Meldung kein Komma enthalten; schreib das Schema auf mehrere Zeilen (ein Feld pro Zeile), wenn die Meldungen lang sind. Die Meldungen werden in `schema.errors` gespeichert.\n\nExample: Eigene Meldungen\n```js\nvar schema = `*name:String // Enter your name\n\t*email:Email // Enter a valid email address`.toJSONSchema();\n\nvar result = schema.transform({ email: 'x' });\nconsole.log(result.error.output());\n// [{ name: 'name', error: 'Enter your name', ... }, { name: 'email', error: 'Enter a valid email address', ... }]\n```\n\n### name:String  name:String(max)  name:Text  name:String2\n\nType: `type`\n\nTextwerte.\n\nJeder Wert wird in einen String umgewandelt und getrimmt, und geschützte Leerzeichen werden zu normalen Leerzeichen. Ein fehlender Wert ist `''`. `String(50)` legt die maximale Länge fest; ein längerer Text ist ein Fehler. Die Länge wird vor dem Trimmen geprüft, Leerzeichen um den Text zählen also mit. `Text` ist dasselbe wie `String`. `String2` macht aus einem leeren Wert `null`.\n\nExample: Strings\n```js\nvar schema = '*title:String(100),note:Text,code:String2'.toJSONSchema();\nschema.transform({ title: '  Hello  ', code: '' }).response;\n// { title: 'Hello', note: '', code: null }\n```\n\n### name:Number  (Number2, Int, Integer, Float, Decimal)\n\nType: `type`\n\nNumerische Werte.\n\nEine Zahl bleibt eine Zahl; ein String mit Ziffern wird mit `String.parseFloat()` geparst (`'33'` ergibt `33`, `'1,5'` ergibt `1.5`). Andere Werte gelten als fehlend, und das Feld wird aus der Antwort weggelassen. `Number2`, `Int`, `Integer`, `Float` und `Decimal` sind Namen desselben Typs.\n\nExample: Zahlen\n```js\nvar schema = 'price:Number,count:Int'.toJSONSchema();\nschema.transform({ price: '9,90', count: '3' }).response;\n// { price: 9.9, count: 3 }\n```\n\n### name:SmallInt\n\nType: `type`\n\nEine Zahl von -32767 bis 32767.\n\nWird wie `Number` geparst; ein Wert außerhalb des Bereichs ist ein Fehler.\n\nExample: SmallInt\n```js\n'priority:SmallInt'.toJSONSchema().transform({ priority: 40000 }).error.output();\n// [{ name: 'priority', error: 'The field \"priority\" is invalid', path: 'priority' }]\n```\n\n### name:TinyInt\n\nType: `type`\n\nEine Zahl von 0 bis 255.\n\nWird wie `Number` geparst; ein Wert außerhalb des Bereichs ist ein Fehler.\n\nExample: TinyInt\n```js\n'level:TinyInt'.toJSONSchema().transform({ level: '12' }).response;\n// { level: 12 }\n```\n\n### name:Boolean  name:Bool\n\nType: `type`\n\nWahr oder falsch.\n\nEin Boolean bleibt, wie er ist; andere Werte werden mit `String.parseBoolean()` geparst (`'true'`, `'1'`, `'on'` ergeben `true`). Das Feld ist immer in der Antwort: Ein fehlender Wert ist `false`.\n\nExample: Checkbox\n```js\n'newsletter:Boolean,terms:Bool'.toJSONSchema().transform({ newsletter: 'on' }).response;\n// { newsletter: true, terms: false }\n```\n\n### name:Date\n\nType: `type`\n\nEin Datum.\n\nEin `Date` bleibt, wie es ist; andere Werte werden mit `String.parseDate()` geparst. Ein Wert, der nicht geparst werden kann, ein fehlender Wert oder ein Datum vor dem 1. Januar 1970 ist `null`.\n\nExample: Datum\n```js\n'birthday:Date'.toJSONSchema().transform({ birthday: '1990-05-20' }).response;\n// { birthday: Date }\n```\n\n### name:Email\n\nType: `type`\n\nEine E-Mail-Adresse.\n\nAlle Leerzeichen werden entfernt und der Wert wird in Kleinbuchstaben konvertiert, dann mit `String.isEmail()` geprüft. Ein leerer Wert ist erlaubt, außer das Feld ist ein Pflichtfeld.\n\nExample: E-Mail\n```js\n'*email:Email'.toJSONSchema().transform({ email: ' Peter@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Email2\n\nType: `type`\n\nEine E-Mail-Adresse ohne ihren Tag.\n\nFunktioniert wie `Email` und entfernt zusätzlich den Tag der Adresse: den Teil von `+` bis `@`, sodass `name+tag@domain.com` zu `name@domain.com` wird. Verwende es, wenn sich eine Person nicht zweimal mit getaggten Adressen registrieren darf. In JSON-Schemas ist es `subtype: 'email2'`; `toAIObject()` und der MCP-Server beschreiben es als `format: 'email'`.\n\nExample: Email2\n```js\n'*email:Email2'.toJSONSchema().transform({ email: ' Peter+News@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Phone\n\nType: `type`\n\nEine Telefonnummer.\n\nLeerzeichen werden entfernt, dann wird der Wert mit `String.isPhone()` geprüft.\n\nExample: Telefon\n```js\n'phone:Phone'.toJSONSchema().transform({ phone: '+421 900 123 456' }).response;\n// { phone: '+421900123456' }\n```\n\n### name:URL\n\nType: `type`\n\nEine URL-Adresse.\n\nGetrimmt und mit `String.isURL()` geprüft.\n\nExample: URL\n```js\n'website:URL'.toJSONSchema().transform({ website: 'https://www.totaljs.com' }).response;\n```\n\n### name:Zip\n\nType: `type`\n\nEine Postleitzahl.\n\nGetrimmt und mit `String.isZIP()` geprüft.\n\nExample: Zip\n```js\n'zip:Zip'.toJSONSchema().transform({ zip: '12345' }).response;\n```\n\n### name:UID\n\nType: `type`\n\nEin eindeutiger Bezeichner von Total.js.\n\nGetrimmt und mit `String.isUID()` geprüft, dem Format, das `UID()` erzeugt. Ein leerer Wert wird zu `null`.\n\nExample: UID\n```js\n'*id:UID'.toJSONSchema().transform({ id: UID() }).response;\n```\n\n### name:GUID\n\nType: `type`\n\nEine GUID.\n\nGetrimmt und mit `String.isGUID()` geprüft. Ein leerer Wert wird zu `null`.\n\nExample: GUID\n```js\n'token:GUID'.toJSONSchema().transform({ token: GUID() }).response;\n```\n\n### name:Name\n\nType: `type`\n\nEin Personenname.\n\nDer Wert wird mit `String.toName()` formatiert: Jedes Wort beginnt mit einem Großbuchstaben.\n\nExample: Name\n```js\n'fullname:Name'.toJSONSchema().transform({ fullname: 'peter sirka' }).response;\n// { fullname: 'Peter Sirka' }\n```\n\n### name:Lower  name:Lowercase  name:Upper  name:Uppercase\n\nType: `type`\n\nText in Klein- oder Großbuchstaben.\n\n`Lower` und `Lowercase` trimmen den Wert und konvertieren ihn in Kleinbuchstaben. `Upper` und `Uppercase` konvertieren ihn in Großbuchstaben.\n\nExample: Schreibweise\n```js\n'login:Lower,country:Upper'.toJSONSchema().transform({ login: 'PETER', country: 'sk' }).response;\n// { login: 'peter', country: 'SK' }\n```\n\n### name:Capitalize  name:Capitalize2\n\nType: `type`\n\nText mit Großbuchstaben.\n\n`Capitalize` schreibt den ersten Buchstaben jedes Wortes groß. `Capitalize2` schreibt nur den ersten Buchstaben des Textes groß.\n\nExample: Capitalize\n```js\n'title:Capitalize,sentence:Capitalize2'.toJSONSchema().transform({ title: 'hello world', sentence: 'hello world' }).response;\n// { title: 'Hello World', sentence: 'Hello world' }\n```\n\n### name:Color\n\nType: `type`\n\nEine Hex-Farbe.\n\nDer Wert muss `#RGB`, `#RRGGBB` oder `#RRGGBBAA` sein (Buchstaben in beliebiger Schreibweise).\n\nExample: Farbe\n```js\n'color:Color'.toJSONSchema().transform({ color: '#4285F4' }).response;\n```\n\n### name:Icon\n\nType: `type`\n\nEine Icon-Klasse.\n\nDer Wert muss eine Icon-Klasse von Total.js-Icons oder Font Awesome sein: ein Präfix (`ti`, `tic`, `fa`, `far`, `fab`, `fad`, `fal`, `fas`), ein Leerzeichen und der Icon-Name mit einem Präfix `ti-`, `tic-` oder `fa-`, zum Beispiel `ti ti-home` oder `fas fa-check`.\n\nExample: Icon\n```js\n'icon:Icon'.toJSONSchema().transform({ icon: 'ti ti-home' }).response;\n```\n\n### name:Base64\n\nType: `type`\n\nEin Base64-String.\n\nGetrimmt und mit `String.isBase64()` geprüft. Ein leerer Wert wird zu `null`.\n\nExample: Base64\n```js\n'file:Base64'.toJSONSchema().transform({ file: 'SGVsbG8=' }).response;\n```\n\n### name:JSON\n\nType: `type`\n\nEin JSON-Text.\n\nGetrimmt und mit `String.isJSON()` geprüft: Der Wert muss wie ein JSON-Objekt, -Array oder -String beginnen und enden oder eine Zahl sein. Der Inhalt wird nicht geparst, und der Wert bleibt ein String; parse ihn mit `String.parseJSON()`, wenn du das Objekt brauchst. Ein leerer Wert wird zu `null`.\n\nExample: JSON\n```js\n'settings:JSON'.toJSONSchema().transform({ settings: '{\"theme\":\"dark\"}' }).response;\n// { settings: '{\"theme\":\"dark\"}' }\n\n'settings:JSON'.toJSONSchema().transform({ settings: 'dark' }).error.output();\n// [{ name: 'settings', error: 'The field \"settings\" is invalid', path: 'settings' }]\n```\n\n### name:DataURI\n\nType: `type`\n\nEine Data-URI, die in einen Buffer geparst wird.\n\nDer Wert muss eine Base64-Data-URI wie `data:image/png;base64,...` sein. Sie wird mit `String.parseDataURI()` zu `{ type, buffer }` geparst, wobei `type` der Content-Type und `buffer` die dekodierten Daten sind. Ein leerer Wert wird zu `null`.\n\nExample: Ein Foto als JSON hochladen\n```js\nNEWACTION('Users/photo', {\n\tinput: '*photo:DataURI',\n\taction: function($, model) {\n\t\t// model.photo.type === 'image/png'\n\t\t// model.photo.buffer is a Buffer\n\t\t$.success();\n\t}\n});\n```\n\n### name:IP\n\nType: `type`\n\nEine IP-Adresse.\n\nGetrimmt und mit `net.isIP()` von Node.js geprüft: eine kanonische IPv4-Adresse (`10.0.0.1`) oder eine IPv6-Adresse (`::1`). Ein Hostname oder eine Kurzform wie `127.1` ist ungültig. Ein leerer Wert wird zu `null`.\n\nExample: IP\n```js\n'server:IP'.toJSONSchema().transform({ server: ' 10.0.0.1 ' }).response;\n// { server: '10.0.0.1' }\n\n'server:IP'.toJSONSchema().transform({ server: '10.0.0.300' }).error.output();\n// [{ name: 'server', error: 'The field \"server\" is invalid', path: 'server' }]\n```\n\n### name:DataURI2\n\nType: `type`\n\nEine Data-URI, die als Text erhalten bleibt.\n\nDer Wert muss eine Base64-Data-URI sein, wie bei `DataURI`, wird aber nicht geparst: Die Antwort enthält den ursprünglichen Text. Verwende den Typ, wenn du die Data-URI unverändert speicherst. Ein leerer Wert wird zu `null`.\n\nExample: Den Text behalten\n```js\n'avatar:DataURI2'.toJSONSchema().transform({ avatar: 'data:image/png;base64,iVBORw0KGgo=' }).response;\n// { avatar: 'data:image/png;base64,iVBORw0KGgo=' }\n```\n\n### name:SafeString\n\nType: `type`\n\nText ohne XSS- oder SQL-Injection-Muster.\n\nGetrimmt und abgelehnt, wenn `String.isXSS()` oder `String.isSQLInjection()` ein gefährliches Muster findet, etwa ein HTML-Tag.\n\nExample: SafeString\n```js\n'comment:SafeString'.toJSONSchema().transform({ comment: '<script>alert(1)</script>' }).error.output();\n// [{ name: 'comment', error: 'The field \"comment\" is invalid', path: 'comment' }]\n```\n\n### name:Search\n\nType: `type`\n\nEin normalisierter Suchbegriff.\n\nGetrimmt und mit `String.toSearch()` konvertiert: Kleinbuchstaben, ohne diakritische Zeichen und mit vereinfachten Buchstaben, sodass er mit indiziertem Suchtext verglichen werden kann.\n\nExample: Suche\n```js\n'q:Search'.toJSONSchema().transform({ q: 'Hello Wörld' }).response;\n// { q: 'helo world' }\n```\n\n### name:{a|b|c}  or  { type: 'string', enum: [...] }\n\nType: `type`\n\nEin Wert aus einer festen Liste.\n\nIn einem Inline-Schema führst du die Werte in geschweiften Klammern auf, getrennt durch `|` oder `;`. In einem JSON-Schema verwendest du das Schlüsselwort `enum` mit einem Array. Ein Wert, der nicht in der Liste steht, ist ein Fehler; ein leerer Wert ist erlaubt, außer das Feld ist ein Pflichtfeld.\n\nExample: Inline-Enum\n```js\n'*status:{draft|published|archived}'.toJSONSchema().transform({ status: 'published' }).response;\n```\n\nExample: Enum im JSON-Schema\n```js\nF.newjsonschema({\n\t$id: 'Task',\n\ttype: 'object',\n\tproperties: {\n\t\tpriority: { type: 'string', enum: ['low', 'normal', 'high'] }\n\t}\n});\n```\n\n### name:[Type]\n\nType: `type`\n\nEin Array von Werten eines Typs.\n\nDer Wert muss ein Array sein; alles andere lässt das Feld weg (oder schlägt fehl, wenn das Feld ein Pflichtfeld ist). Jedes Element wird in den Typ konvertiert, zum Beispiel macht `[Number]` aus `['1', 2]` den Wert `[1, 2]`. `[{...}]` ist ein Array verschachtelter Objekte und `[@name]` ein Array, das von einem registrierten Schema validiert wird; die Fehlerpfade enthalten den Index, etwa `items[1].price`.\n\nExample: Arrays\n```js\nvar schema = 'tags:[String],scores:[Number],lines:[{sku:String,qty:Number}]'.toJSONSchema();\nschema.transform({ tags: ['a', ' b '], scores: ['1', 2], lines: [{ sku: 'A1', qty: '2' }] }).response;\n// { tags: ['a', 'b'], scores: [1, 2], lines: [{ sku: 'A1', qty: 2 }] }\n```\n\n### name:{field:Type,...}\n\nType: `type`\n\nEin verschachteltes Objekt.\n\nGeschweifte Klammern mit Feldern (kein Enum) erzeugen ein verschachteltes Objekt mit eigenen Feldern, Modifikatoren und Typen. Das verschachtelte Objekt wird wie das Hauptobjekt validiert, und seine Fehler haben Pfade wie `address.city`. Ein verschachteltes Objekt kann weitere verschachtelte Objekte und Arrays enthalten, zum Beispiel `order:{lines:[{sku:String,qty:Number}],shipping:{address:{city:String}}}`.\n\nExample: Verschachteltes Objekt\n```js\nvar schema = '*name:String,address:{street:String,*city:String,zip:Zip}'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', address: { street: 'Main 1' } });\n// error: { name: 'city', path: 'address.city' }\n```\n\n### name:@Schema  name:[@Schema]\n\nType: `type`\n\nEin verschachteltes Objekt, das von einem registrierten Schema validiert wird.\n\nDer Wert wird von dem als `Schema` registrierten Schema validiert (mit `NEWSCHEMA()`, `F.newjsonschema()` oder dem Ordner `jsonschemas/`). `[@Schema]` validiert jedes Element eines Arrays. Die Fehler behalten die Pfade des verschachtelten Objekts.\n\nExample: Ein Schema wiederverwenden\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String');\nNEWSCHEMA('@Company', '*name:String,headquarters:@Address,branches:[@Address]');\n\nvar result = F.jsonschemas.Company.transform({ name: 'Acme', branches: [{ street: 'A 1', city: 'X' }, { street: 'B 2' }] });\n// error: { name: 'city', path: 'branches[1].city', index: 1 }\n```\n\n### required: ['field', ...]\n\nType: `property`\n\nDie Pflichtfelder eines Objekt-Schemas.\n\nEin Array von Eigenschaftsnamen. Die Regeln für leere Werte sind dieselben wie bei `*` in Inline-Schemas.\n\nExample: required\n```js\nF.newjsonschema({\n\t$id: 'Login',\n\ttype: 'object',\n\tproperties: {\n\t\temail: { type: 'string', subtype: 'email' },\n\t\tpassword: { type: 'string' }\n\t},\n\trequired: ['email', 'password']\n});\n```\n\n### { type: 'string', subtype: 'email' }\n\nType: `property`\n\nEin Total.js-Schlüsselwort, das eine spezielle Konvertierung auswählt.\n\nBei `string`-Eigenschaften verwendet `subtype` die Umwandlung eines Inline-Typs: `email`, `email2`, `phone`, `url`, `zip`, `uid`, `guid`, `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`, `color`, `icon`, `base64`, `datauri`, `datauri2`, `safestring`, `search`, `json` oder `ip`. `ipaddress` ist dasselbe wie `ip` und existiert nur in JSON-Schemas. Bei `number`-Eigenschaften prüfen `smallint` und `tinyint` den Wertebereich. Ein leerer String bleibt `''`; füge `nullable: true` hinzu, um `null` zu erhalten.\n\nExample: subtype\n```js\nF.newjsonschema({\n\t$id: 'Server',\n\ttype: 'object',\n\tproperties: {\n\t\thost: { type: 'string', subtype: 'ip' },\n\t\tconfig: { type: 'string', subtype: 'json' },\n\t\tport: { type: 'number', subtype: 'smallint' }\n\t}\n});\n```\n\n### { type: 'string', nullable: true }\n\nType: `property`\n\nEin Total.js-Schlüsselwort, das einen leeren String in null umwandelt.\n\nBei einer `string`-Eigenschaft wird ein leerer Wert zu `null` statt `''`. Die Inline-Typen `String2`, `UID`, `GUID`, `Base64`, `DataURI` und `DataURI2` setzen es für dich.\n\nExample: nullable\n```js\nvar schema = F.newjsonschema({ $id: 'Note', type: 'object', properties: { text: { type: 'string', nullable: true } } });\nschema.transform({ text: '' }).response;\n// { text: null }\n```\n\n### { type: 'string', minLength: 3, maxLength: 50 }\n\nType: `property`\n\nDie Längengrenzen eines Strings.\n\n`minLength` und `maxLength` prüfen die Anzahl der Zeichen eines Strings. `String(50)` in einem Inline-Schema setzt `maxLength`.\n\nExample: Länge\n```js\nF.newjsonschema({\n\t$id: 'Nick',\n\ttype: 'object',\n\tproperties: { nick: { type: 'string', minLength: 3, maxLength: 20 } }\n});\n```\n\n### { type: 'number', minimum: 1, maximum: 100 }\n\nType: `property`\n\nDie Grenzen einer Zahl.\n\n`minimum` und `maximum` sind inklusive Grenzen, `exclusiveMinimum` und `exclusiveMaximum` exklusive. `multipleOf` verlangt einen Wert, der durch die angegebene Zahl teilbar ist.\n\nExample: Zahlengrenzen\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\tquantity: { type: 'number', minimum: 1, maximum: 100 },\n\t\tdiscount: { type: 'number', exclusiveMaximum: 50 },\n\t\tpack: { type: 'number', multipleOf: 6 }\n\t}\n});\n```\n\n### { type: 'array', items: { type: 'string' } }\n\nType: `property`\n\nDas Schema der Elemente eines Arrays.\n\n`items` ist ein Schema für jedes Element: ein Typ mit seinen Schlüsselwörtern (`string`, `number`, `boolean`, `date`), ein `object` mit eigenen `properties` und `required` oder ein `$ref`. Jedes Element eines Objekts wird wie ein verschachteltes Objekt validiert und umgewandelt; ein Fehler eines Elements hat den Namen und den Pfad `field.property` und die Position des Elements in `index`. `minItems` legt die kleinste Anzahl von Elementen eines nicht leeren Arrays fest; ein leeres Array schlägt nur fehl, wenn das Feld erforderlich ist. `uniqueItems: true` entfernt doppelte Werte.\n\nExample: Array von Tags\n```js\nF.newjsonschema({\n\t$id: 'Article',\n\ttype: 'object',\n\tproperties: {\n\t\ttags: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true }\n\t}\n});\n\nF.jsonschemas.Article.transform({ tags: ['a', 'b', 'a'] }).response;\n// { tags: ['a', 'b'] }\n```\n\nExample: Array von Objekten\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\titems: { type: 'array', items: { type: 'object', properties: { sku: { type: 'string' }, qty: { type: 'number' } }, required: ['qty'] } }\n\t}\n});\n\nvar result = F.jsonschemas.Order.transform({ items: [{ sku: 'A', qty: '2' }, { sku: 'B' }] });\n// result.error.items[0]: name 'items.qty', path 'items.qty', index 1\n```\n\n### { type: 'object', $ref: '#/definitions/Name' }\n\nType: `property`\n\nEine Referenz auf ein anderes Schema.\n\n`$ref` validiert ein Objekt (oder in `items` jedes Element eines Arrays) mit einem anderen Schema. Ein Wert, der mit `#/` beginnt, verweist auf die `definitions` desselben Schemas, zum Beispiel `#/definitions/Address`. Jeder andere Wert ist der Name oder die `$id` eines in `F.jsonschemas` registrierten Schemas.\n\nExample: Lokale und registrierte Referenzen\n```js\nF.newjsonschema({ $id: 'Address', type: 'object', properties: { city: { type: 'string' } }, required: ['city'] });\n\nF.newjsonschema({\n\t$id: 'Invoice',\n\ttype: 'object',\n\tproperties: {\n\t\tbilling: { type: 'object', $ref: 'Address' },\n\t\tlines: { type: 'array', items: { $ref: '#/definitions/Line' } }\n\t},\n\tdefinitions: {\n\t\tLine: { type: 'object', properties: { name: { type: 'string' }, price: { type: 'number' } } }\n\t}\n});\n```\n\n### new ErrorBuilder()\n\nType: `class`\n\nEine Liste von Fehlern mit einem HTTP-Status.\n\nReturns: `ErrorBuilder`\n\nDie Validierung gibt ihre Fehler in einem `ErrorBuilder` zurück, und Aktionen und Controller antworten damit als JSON-Array. Du kannst einen erstellen, um eigene Fehler zu sammeln. Seine Eigenschaften: `items` (die rohen Fehler), `length` (die Anzahl der Fehler), `status` (der HTTP-Status, standardmäßig `400`) und `prefix` (ein Text, der den Namen von Feldfehlern vorangestellt wird).\n\nExample: Fehler sammeln\n```js\nvar err = new ErrorBuilder();\n\nif (!model.email)\n\terr.push2('email');\n\nif (model.age < 18)\n\terr.push('You must be 18 or older');\n\nif (err.length)\n\tconsole.log(err.output());\n```\n\n### err.push(error, [path], [index])\n\nType: `method`\n\nFügt eine Fehlermeldung oder einen HTTP-Status hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number` | yes |  | Eine Meldung oder ein HTTP-Statuscode. |\n| `path` | `String` | no |  | Der Pfad des Feldes. |\n| `index` | `Number` | no |  | Der Index eines Array-Elements. |\n\nReturns: `ErrorBuilder` Derselbe Builder.\n\nEine Zahl ab 400 setzt `status` und fügt den Text des HTTP-Status hinzu, zum Beispiel fügt `404` den Text `404: Not Found` hinzu. Jeder andere Wert wird als Meldung hinzugefügt. Ohne Wert wird `401` hinzugefügt. Eine Meldung, die mit `@(` beginnt, wird von `output()` übersetzt, zum Beispiel `err.push('@(Access denied)')`.\n\nExample: Meldungen und Status\n```js\nvar err = new ErrorBuilder();\nerr.push('The product is sold out');\nerr.push(409);\nerr.status;\t // 409\nerr.output();   // [{ error: 'The product is sold out' }, { error: '409: Conflict' }]\n```\n\n### err.push2(name, [path], [index], [error])\n\nType: `method`\n\nFügt einen Feldfehler hinzu, mit optionaler Meldung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Feldes. |\n| `path` | `String` | no |  | Der Pfad des Feldes. |\n| `index` | `Number` | no |  | Der Index eines Array-Elements. |\n\nReturns: `ErrorBuilder` Derselbe Builder.\n\nFügt einen Fehler für das Feld `name` hinzu (mit vorangestelltem `prefix`). Ohne `error` wird die Meldung von `output()` ermittelt: zuerst die `//`-Meldungen des Schemas, dann die Ressource mit dem Feldnamen in der Sprache der Ausgabe, dann `The field \"name\" is invalid`. Mit `error` ist dieser Text die Meldung.\n\nSignatur: `err.push2(name, [path], [index], [error])`.\n\nExample: Feldfehler\n```js\nvar err = new ErrorBuilder();\nerr.push2('email', 'contact.email');\nerr.output();\n// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'contact.email' }]\n```\n\n### err.output([language])\n\nType: `method`\n\nGibt die Fehler als Array von Objekten zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Die Sprache für Ressourcen und Übersetzungen. |\n\nReturns: `Array` Die Liste der Fehler.\n\nJedes Element ist `{ name, error, path, index }` mit der endgültigen Meldung. Meldungen von Feldfehlern werden aus den Ressourcen von `language` gelesen, `@(...)`-Texte werden übersetzt, und die Ersetzungen von `replace()` werden angewendet. Wenn ein globaler Handler `ErrorBuilder.transform()` existiert, wird stattdessen sein Ergebnis zurückgegeben.\n\nExample: Ausgabe\n```js\nvar err = new ErrorBuilder();\nerr.push2('name');\nconsole.log(err.output('en'));\n```\n\n### err.toString([language], [divider])\n\nType: `method`\n\nGibt die Meldungen als einen Text zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Die Sprache. |\n| `divider` | `String` | no | `'\\n'` | Der Text zwischen den Meldungen. |\n\nReturns: `String`\n\nDie Meldungen von `output(language)`, verbunden durch `divider`.\n\nExample: Text\n```js\nvar err = new ErrorBuilder();\nerr.push('First');\nerr.push('Second');\nerr.toString();\t\t\t   // 'First\\nSecond'\nerr.toString('default', ', '); // 'First, Second'\n```\n\n### err.reject([language])\n\nType: `method`\n\nGibt die Fehler als Error-Objekt zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Die Sprache. |\n\nReturns: `Error`\n\nErstellt `new Error()` mit allen Meldungen, ohne Trennzeichen verbunden. Nützlich, um ein Promise abzulehnen.\n\nExample: Ein Promise ablehnen\n```js\nreturn new Promise(function(resolve, reject) {\n\tvar err = new ErrorBuilder();\n\terr.push('Not allowed');\n\treject(err.reject());\n});\n```\n\n### err.throw()\n\nType: `method`\n\nLässt den Builder beim nächsten Fehler werfen.\n\nReturns: `ErrorBuilder` Derselbe Builder.\n\nNach `throw()` wirft jedes `push()` oder `push2()` einen `Error` mit der Meldung des ersten Fehlers. `schema.validate()` verwendet es.\n\nExample: Sofort werfen\n```js\nvar err = new ErrorBuilder().throw();\ntry {\n\terr.push('Invalid token');\n} catch (e) {\n\tconsole.log(e.message); // Invalid token\n}\n```\n\n### err.replace(search, value)\n\nType: `method`\n\nErsetzt einen Text in allen Meldungen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String` | yes |  | Der zu suchende Text. |\n| `value` | `String` | yes |  | Der neue Text. |\n\nReturns: `ErrorBuilder` Derselbe Builder.\n\nDie Ersetzung wird von `output()` auf jede Meldung angewendet, sodass du eine Meldung mit einem Platzhalter hinzufügen und ihn später füllen kannst.\n\nExample: Platzhalter\n```js\nvar err = new ErrorBuilder();\nerr.push('The limit is {limit} items');\nerr.replace('{limit}', 10);\nerr.toString(); // 'The limit is 10 items'\n```\n\n### ErrorBuilder.assign(value)\n\nType: `method`\n\nErstellt einen Builder aus einer Fehlerausgabe, einer Meldung oder einem Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Array|String|Number|Error` | yes |  | Die Fehler. |\n\nReturns: `ErrorBuilder` Ein neuer Builder.\n\nBei einem Array wird jedes Element mit `error` hinzugefügt (zum Beispiel die JSON-Fehler, die eine andere Total.js-App zurückgibt). Eine Zahl oder ein String wird hinzugefügt, und ein `Error` wird als sein Text hinzugefügt.\n\nExample: Fehler von einem anderen Dienst\n```js\nvar err = ErrorBuilder.assign([{ name: 'email', error: 'Email is taken' }]);\nerr.length; // 1\n```\n\n### ErrorBuilder.transform(callback)\n\nType: `method`\n\nSetzt einen globalen Handler, der die Ausgabe jedes ErrorBuilder ändert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(output, language)`, die die neue Ausgabe zurückgibt. |\n\n`callback(output, language)` erhält das von `output()` erzeugte Array und gibt zurück, was `output()` stattdessen zurückgibt. Da Aktionen und Controller `output()` an den Client senden, ändert das das Format aller Fehlerantworten.\n\nExample: Ein eigenes Fehlerformat\n```js\nErrorBuilder.transform(function(output, language) {\n\treturn { success: false, errors: output };\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, schema)","since":"","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"'...'.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"F.newjsonschema()","signature":"F.newjsonschema(name, [schema])","since":"","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"jsonschemas/","signature":"jsonschemas/*.json","since":"","deprecated":false},{"type":"method","name":"schema.transform()","signature":"schema.transform(value, [partial], [error], [path])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(value, [partial], [path])","since":"","deprecated":false},{"type":"method","name":"schema.toAITool()","signature":"schema.toAITool(name)","since":"","deprecated":false},{"type":"method","name":"schema.toAIObject()","signature":"schema.toAIObject(name, [description])","since":"","deprecated":false},{"type":"type","name":"*field","signature":"*name:Type  or  !name:Type","since":"","deprecated":false},{"type":"type","name":"// message","signature":"name:Type // Message","since":"","deprecated":false},{"type":"type","name":"String","signature":"name:String  name:String(max)  name:Text  name:String2","since":"","deprecated":false},{"type":"type","name":"Number","signature":"name:Number  (Number2, Int, Integer, Float, Decimal)","since":"","deprecated":false},{"type":"type","name":"SmallInt","signature":"name:SmallInt","since":"","deprecated":false},{"type":"type","name":"TinyInt","signature":"name:TinyInt","since":"","deprecated":false},{"type":"type","name":"Boolean","signature":"name:Boolean  name:Bool","since":"","deprecated":false},{"type":"type","name":"Date","signature":"name:Date","since":"","deprecated":false},{"type":"type","name":"Email","signature":"name:Email","since":"","deprecated":false},{"type":"type","name":"Email2","signature":"name:Email2","since":"","deprecated":false},{"type":"type","name":"Phone","signature":"name:Phone","since":"","deprecated":false},{"type":"type","name":"URL","signature":"name:URL","since":"","deprecated":false},{"type":"type","name":"Zip","signature":"name:Zip","since":"","deprecated":false},{"type":"type","name":"UID","signature":"name:UID","since":"","deprecated":false},{"type":"type","name":"GUID","signature":"name:GUID","since":"","deprecated":false},{"type":"type","name":"Name","signature":"name:Name","since":"","deprecated":false},{"type":"type","name":"Lower / Upper","signature":"name:Lower  name:Lowercase  name:Upper  name:Uppercase","since":"","deprecated":false},{"type":"type","name":"Capitalize","signature":"name:Capitalize  name:Capitalize2","since":"","deprecated":false},{"type":"type","name":"Color","signature":"name:Color","since":"","deprecated":false},{"type":"type","name":"Icon","signature":"name:Icon","since":"","deprecated":false},{"type":"type","name":"Base64","signature":"name:Base64","since":"","deprecated":false},{"type":"type","name":"JSON","signature":"name:JSON","since":"","deprecated":false},{"type":"type","name":"DataURI","signature":"name:DataURI","since":"","deprecated":false},{"type":"type","name":"IP","signature":"name:IP","since":"","deprecated":false},{"type":"type","name":"DataURI2","signature":"name:DataURI2","since":"","deprecated":false},{"type":"type","name":"SafeString","signature":"name:SafeString","since":"","deprecated":false},{"type":"type","name":"Search","signature":"name:Search","since":"","deprecated":false},{"type":"type","name":"Enum","signature":"name:{a|b|c}  or  { type: 'string', enum: [...] }","since":"","deprecated":false},{"type":"type","name":"Array","signature":"name:[Type]","since":"","deprecated":false},{"type":"type","name":"Object","signature":"name:{field:Type,...}","since":"","deprecated":false},{"type":"type","name":"@name","signature":"name:@Schema  name:[@Schema]","since":"","deprecated":false},{"type":"property","name":"required","signature":"required: ['field', ...]","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"{ type: 'string', subtype: 'email' }","since":"","deprecated":false},{"type":"property","name":"nullable","signature":"{ type: 'string', nullable: true }","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"{ type: 'string', minLength: 3, maxLength: 50 }","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"{ type: 'number', minimum: 1, maximum: 100 }","since":"","deprecated":false},{"type":"property","name":"items","signature":"{ type: 'array', items: { type: 'string' } }","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"{ type: 'object', $ref: '#/definitions/Name' }","since":"","deprecated":false},{"type":"class","name":"ErrorBuilder","signature":"new ErrorBuilder()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push()","signature":"err.push(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push2()","signature":"err.push2(name, [path], [index], [error])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.output()","signature":"err.output([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.toString()","signature":"err.toString([language], [divider])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.reject()","signature":"err.reject([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.throw()","signature":"err.throw()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.replace()","signature":"err.replace(search, value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.assign()","signature":"ErrorBuilder.assign(value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.transform()","signature":"ErrorBuilder.transform(callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwVXEVx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Esquemas y validación","summary":"Tipos y modificadores de los esquemas inline, palabras clave de los esquemas JSON, métodos de los esquemas y ErrorBuilder.","markdown":"---\ntitle: \"Esquemas y validación\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/json-schemas/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Esquemas y validación\n\n> Tipos y modificadores de los esquemas inline, palabras clave de los esquemas JSON, métodos de los esquemas y ErrorBuilder.\n\nLos tipos y modificadores de los esquemas inline, las palabras clave de los esquemas JSON, los métodos para registrar y ejecutar esquemas y la clase `ErrorBuilder`. Para una introducción con ejemplos, lee [Esquemas y validación](../../guides/json-schemas/).\n\n## API\n\n### NEWSCHEMA(name, schema)\n\nType: `method`\n\nRegistra un esquema inline con un nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del esquema; se ignora una `@` inicial. |\n| `schema` | `String|Function` | yes |  | Un esquema inline, o una función que define acciones. |\n\nReturns: `Object` El objeto de esquema JSON cuando `schema` es una cadena.\n\nCon una cadena, el esquema inline se analiza y se guarda en `F.jsonschemas[name]`. Se elimina una `@` inicial del nombre, así que `'@Address'` y `'Address'` registran el mismo nombre. Otros esquemas y acciones lo usan como `@Address`.\n\nCon una función, la función recibe un objeto con `name`, `actions` y `action(name, meta)`. `action()` crea una acción llamada `<schema name>/<action name>` con [NEWACTION](../../guides/actions/).\n\nExample: Registrar y usar un esquema\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\nNEWSCHEMA('@Customer', '*name:String,address:@Address');\n\nNEWACTION('Customers/save', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: Acciones en un esquema\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('list', {\n\t\tquery: 'page:Number',\n\t\taction: function($) {\n\t\t\t$.callback([]);\n\t\t}\n\t});\n});\n// creates the action \"Orders/list\"\n```\n\n### '...'.toJSONSchema([name], [url])\n\nType: `method`\n\nAnaliza un esquema inline y lo convierte en un objeto de esquema JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Guarda el esquema en `F.jsonschemas` con este nombre y lo usa en `$id`. |\n| `url` | `String` | no | `CONF.url` | La URL base de `$id`. |\n\nReturns: `Object` Un objeto de esquema JSON.\n\nDevuelve un objeto con `$id`, `$schema`, `type: 'object'`, `properties`, `required`, `errors` (los mensajes `//`) y los métodos `transform()` y `validate()`. Con `name`, el esquema también se guarda en `F.jsonschemas[name]`.\n\nEl `$id` es `url + name + '.json'`. Sin `url`, se usa `CONF.url`, o `https://schemas.totaljs.com/`. Sin `name`, se usa un hash de la cadena. `String.parseSchema()` es el mismo método.\n\nExample: Analizar y validar\n```js\nvar schema = '*name:String(50),email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'peter@example.com' });\nconsole.log(result.response);\n```\n\nExample: Registrar con un nombre\n```js\n'*street:String,*city:String'.toJSONSchema('Address');\n// F.jsonschemas.Address exists now\n```\n\n### F.newjsonschema(name, [schema])\n\nType: `method`\n\nRegistra un esquema JSON o un esquema inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | El nombre del esquema, un esquema inline o un objeto de esquema JSON con `$id`. |\n| `schema` | `Object|String` | no |  | Un objeto de esquema JSON o un esquema inline. |\n\nReturns: `Object` El esquema registrado.\n\nEl esquema se guarda en `F.jsonschemas` con el nombre y con su `$id`, y recibe el método `transform()`. Las formas:\n\n- `F.newjsonschema(object)`: un objeto de esquema JSON; su `$id` es el nombre.\n- `F.newjsonschema(name, object)`: un objeto de esquema JSON con el nombre `name`.\n- `F.newjsonschema(name, 'inline schema')`: un esquema inline; `$id` se establece en `name`.\n- `F.newjsonschema('inline schema')`: un esquema inline registrado con su `$id` generado.\n\nLos archivos de la carpeta `jsonschemas/` se registran con este método.\n\nExample: Un objeto de esquema JSON\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tprice: { type: 'number', minimum: 1 }\n\t},\n\trequired: ['name']\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nExample: Un esquema inline\n```js\nF.newjsonschema('Contact', '*name:String,*email:Email');\n```\n\n### F.jsonschemas\n\nType: `property`\n\nTodos los esquemas registrados por nombre.\n\nReturns: `Object`\n\nUn objeto con todos los esquemas registrados por `NEWSCHEMA()`, `F.newjsonschema()`, `toJSONSchema(name)` y la carpeta `jsonschemas/`. `@name` en los esquemas inline y las acciones, y `$ref` en los esquemas JSON, buscan los esquemas aquí.\n\nExample: Validar con un esquema registrado\n```js\nNEWSCHEMA('@Contact', '*name:String,*email:Email');\n\nvar result = F.jsonschemas.Contact.transform({ name: 'Peter', email: 'bad' });\nif (result.error)\n\tconsole.log(result.error.output());\n```\n\n### jsonschemas/*.json\n\nType: `config`\n\nUna carpeta de esquemas que se carga cuando arranca la aplicación.\n\nCada archivo `.json` se analiza y se registra con `F.newjsonschema()`; el nombre del archivo sin la extensión es el nombre del esquema. La carpeta se carga antes que las carpetas con código, así que las acciones pueden usar sus esquemas con `@name`.\n\nExample: jsonschemas/Address.json\n```js\n{\n\t\"$id\": \"Address\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" },\n\t\t\"zip\": { \"type\": \"string\", \"subtype\": \"zip\" }\n\t},\n\t\"required\": [\"street\", \"city\"]\n}\n```\n\nExample: Usarlo\n```js\nNEWACTION('Addresses/create', {\n\tinput: '@Address',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### schema.transform(value, [partial], [error], [path])\n\nType: `method`\n\nValida y convierte un valor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor que se valida. |\n| `partial` | `Boolean` | no | `false` | Valida solo los campos que existen en el valor. |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un builder que recibe los errores. |\n| `path` | `String` | no |  | Un prefijo para las rutas de los errores. |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nDevuelve `{ error, response }`. `response` es el valor convertido: para un esquema de objeto, un objeto nuevo solo con los campos del esquema, o `undefined` cuando ningún campo tiene valor. `error` es un `ErrorBuilder` con los errores, o `null` cuando no hay ninguno.\n\nCon `partial`, los campos que son `undefined` en el valor se omiten, así que los campos obligatorios que faltan no fallan. Pasa tu propio `ErrorBuilder` como `error` para reunir en un solo builder los errores de varias validaciones.\n\nExample: Validar un cuerpo\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'wrong' });\n\nif (result.error)\n\tconsole.log(result.error.output());\n\t// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'email' }]\nelse\n\tconsole.log(result.response);\n```\n\nExample: Actualización parcial\n```js\nvar schema = '*name:String,*email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ age: 40 }, true);\n// result.response === { age: 40 }, result.error === null\n```\n\n### schema.validate(value, [partial], [path])\n\nType: `method`\n\nValida un valor y lanza una excepción en el primer error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor que se valida. |\n| `partial` | `Boolean` | no | `false` | Valida solo los campos que existen en el valor. |\n| `path` | `String` | no |  | Un prefijo para las rutas de los errores. |\n\nReturns: `Object` El valor convertido.\n\nDevuelve el valor convertido. Cuando el valor no es válido, lanza un `Error` con el mensaje del primer error. Úsalo donde una excepción sea más sencilla que comprobar `result.error`. Solo los esquemas creados a partir de un esquema inline tienen este método.\n\nExample: Lanzar una excepción con datos no válidos\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\n\ntry {\n\tvar model = schema.validate({ name: 'Peter' });\n} catch (e) {\n\tconsole.log(e.message); // The field \"email\" is invalid\n}\n```\n\n### schema.toAITool(name)\n\nType: `method`\n\nCrea una definición de herramienta de IA a partir de un esquema en línea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la herramienta. |\n\nReturns: `Object` La definición de la herramienta.\n\nDevuelve un objeto de herramienta de función para modelos de IA. Cada campo se convierte en un parámetro con su `type` y, como descripción, el mensaje `//` del campo (un string vacío si no lo tiene). Los campos obligatorios del esquema son los parámetros obligatorios. La descripción de la herramienta es `schema.summary` o `schema.description` cuando estableces uno. Existe en los esquemas creados a partir de un esquema en línea (`toJSONSchema()`, `NEWSCHEMA()`), no en los objetos de esquema JSON registrados con `F.newjsonschema()`. Consulta [Modelos de IA](../../guides/ai-models/).\n\nExample: Una herramienta a partir de un esquema\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nschema.description = 'Returns the weather forecast';\n\nvar tool = schema.toAITool('weather');\n// {\n//\t type: 'function',\n//\t function: {\n//\t\t name: 'weather',\n//\t\t description: 'Returns the weather forecast',\n//\t\t parameters: {\n//\t\t\t type: 'object',\n//\t\t\t properties: {\n//\t\t\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t\t\t days: { type: 'number', description: 'Number of days' }\n//\t\t\t },\n//\t\t\t required: ['city'],\n//\t\t\t additionalProperties: false\n//\t\t }\n//\t }\n// }\n```\n\n### schema.toAIObject(name, [description])\n\nType: `method`\n\nConvierte un esquema en línea en un objeto JSON Schema con nombre para modelos de IA.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del objeto. |\n| `description` | `String` | no |  | Una descripción del objeto. |\n\nReturns: `Object` El objeto JSON Schema.\n\nDevuelve `{ name, description, type: 'object', properties, required, additionalProperties: false }`. Las propiedades usan JSON Schema estándar: `Date` es `{ type: 'string', format: 'date-time' }`, `Email` tiene `format: 'email'`, un enum tiene `enum`, un array tiene `items`, y un tipo que puede ser `null` (como `String2`, `UID`, `GUID`, `JSON`, `IP` o `Base64`) es `['string', 'null']`. El mensaje `//` de un campo es su `description`. `required` se omite cuando ningún campo es obligatorio. Como `toAITool()`, existe en los esquemas creados a partir de un esquema en línea.\n\nExample: Una respuesta estructurada\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// {\n//\t name: 'forecast',\n//\t description: 'The weather forecast for a city',\n//\t properties: {\n//\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t days: { type: 'number', description: 'Number of days' }\n//\t },\n//\t type: 'object',\n//\t additionalProperties: false,\n//\t required: ['city']\n// }\n```\n\n### *name:Type  or  !name:Type\n\nType: `type`\n\nMarca un campo de un esquema inline como obligatorio.\n\nUn campo obligatorio falla cuando su valor está vacío. Para los strings, es un valor vacío antes de recortar (un texto solo con espacios pasa y se convierte en `''`); para los números, un valor que falta o no es numérico (`0` pasa); para los booleanos, un valor que falta (`false` pasa); para las fechas, un valor que no se puede parsear; para los arrays, un array vacío o un valor que no es un array. Un objeto anidado obligatorio (`{...}` o `@name`) no falla cuando falta. `!` es lo mismo que `*`.\n\nExample: Campos obligatorios\n```js\nvar schema = '*name:String,*email:Email,phone:Phone'.toJSONSchema();\nvar result = schema.transform({ name: '' });\n// errors for \"name\" and \"email\"\n```\n\n### name:Type // Message\n\nType: `type`\n\nEstablece un mensaje de error personalizado para un campo de un esquema inline.\n\nEl texto después de `//` es el mensaje de error del campo. Como las comas separan los campos, el mensaje no puede contener una coma; escribe el esquema en varias líneas (un campo por línea) cuando los mensajes sean largos. Los mensajes se guardan en `schema.errors`.\n\nExample: Mensajes personalizados\n```js\nvar schema = `*name:String // Enter your name\n\t*email:Email // Enter a valid email address`.toJSONSchema();\n\nvar result = schema.transform({ email: 'x' });\nconsole.log(result.error.output());\n// [{ name: 'name', error: 'Enter your name', ... }, { name: 'email', error: 'Enter a valid email address', ... }]\n```\n\n### name:String  name:String(max)  name:Text  name:String2\n\nType: `type`\n\nValores de texto.\n\nCualquier valor se convierte en string, se recorta, y los espacios de no separación se convierten en espacios normales. Un valor que falta es `''`. `String(50)` establece la longitud máxima; un texto más largo es un error. La longitud se comprueba antes de recortar, así que los espacios alrededor del texto cuentan. `Text` es lo mismo que `String`. `String2` convierte un valor vacío en `null`.\n\nExample: Cadenas\n```js\nvar schema = '*title:String(100),note:Text,code:String2'.toJSONSchema();\nschema.transform({ title: '  Hello  ', code: '' }).response;\n// { title: 'Hello', note: '', code: null }\n```\n\n### name:Number  (Number2, Int, Integer, Float, Decimal)\n\nType: `type`\n\nValores numéricos.\n\nUn número sigue siendo un número; una cadena con dígitos se analiza con `String.parseFloat()` (`'33'` da `33`, `'1,5'` da `1.5`). Los demás valores se tratan como ausentes y el campo se omite en la respuesta. `Number2`, `Int`, `Integer`, `Float` y `Decimal` son nombres del mismo tipo.\n\nExample: Números\n```js\nvar schema = 'price:Number,count:Int'.toJSONSchema();\nschema.transform({ price: '9,90', count: '3' }).response;\n// { price: 9.9, count: 3 }\n```\n\n### name:SmallInt\n\nType: `type`\n\nUn número de -32767 a 32767.\n\nSe analiza como `Number`; un valor fuera del rango es un error.\n\nExample: SmallInt\n```js\n'priority:SmallInt'.toJSONSchema().transform({ priority: 40000 }).error.output();\n// [{ name: 'priority', error: 'The field \"priority\" is invalid', path: 'priority' }]\n```\n\n### name:TinyInt\n\nType: `type`\n\nUn número de 0 a 255.\n\nSe analiza como `Number`; un valor fuera del rango es un error.\n\nExample: TinyInt\n```js\n'level:TinyInt'.toJSONSchema().transform({ level: '12' }).response;\n// { level: 12 }\n```\n\n### name:Boolean  name:Bool\n\nType: `type`\n\nVerdadero o falso.\n\nUn booleano se queda como está; los demás valores se analizan con `String.parseBoolean()` (`'true'`, `'1'`, `'on'` dan `true`). El campo siempre está en la respuesta: un valor que falta es `false`.\n\nExample: Casilla de verificación\n```js\n'newsletter:Boolean,terms:Bool'.toJSONSchema().transform({ newsletter: 'on' }).response;\n// { newsletter: true, terms: false }\n```\n\n### name:Date\n\nType: `type`\n\nUna fecha.\n\nUn `Date` se mantiene tal cual; los demás valores se parsean con `String.parseDate()`. Un valor que no se puede parsear, un valor que falta o una fecha anterior al 1 de enero de 1970 es `null`.\n\nExample: Fecha\n```js\n'birthday:Date'.toJSONSchema().transform({ birthday: '1990-05-20' }).response;\n// { birthday: Date }\n```\n\n### name:Email\n\nType: `type`\n\nUna dirección de email.\n\nSe eliminan todos los espacios en blanco y el valor se convierte a minúsculas; después se comprueba con `String.isEmail()`. Se permite un valor vacío salvo que el campo sea obligatorio.\n\nExample: Email\n```js\n'*email:Email'.toJSONSchema().transform({ email: ' Peter@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Email2\n\nType: `type`\n\nUna dirección de correo sin su etiqueta.\n\nReturns: `undefined` Nada\n\nFunciona como `Email` y además quita la etiqueta de la dirección: la parte que va de `+` a `@`, así que `name+tag@domain.com` se convierte en `name@domain.com`. Úsalo cuando una persona no deba registrarse dos veces con direcciones etiquetadas. En los esquemas JSON es `subtype: 'email2'`; `toAIObject()` y el servidor MCP lo describen como `format: 'email'`.\n\nExample: Email2\n```js\n'*email:Email2'.toJSONSchema().transform({ email: ' Peter+News@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Phone\n\nType: `type`\n\nUn número de teléfono.\n\nSe eliminan los espacios en blanco y después el valor se comprueba con `String.isPhone()`.\n\nExample: Teléfono\n```js\n'phone:Phone'.toJSONSchema().transform({ phone: '+421 900 123 456' }).response;\n// { phone: '+421900123456' }\n```\n\n### name:URL\n\nType: `type`\n\nUna dirección URL.\n\nSe recortan los espacios y se comprueba con `String.isURL()`.\n\nExample: URL\n```js\n'website:URL'.toJSONSchema().transform({ website: 'https://www.totaljs.com' }).response;\n```\n\n### name:Zip\n\nType: `type`\n\nUn código postal.\n\nSe recortan los espacios y se comprueba con `String.isZIP()`.\n\nExample: Zip\n```js\n'zip:Zip'.toJSONSchema().transform({ zip: '12345' }).response;\n```\n\n### name:UID\n\nType: `type`\n\nUn identificador único de Total.js.\n\nSe recortan los espacios y se comprueba con `String.isUID()`, el formato que genera `UID()`. Un valor vacío pasa a ser `null`.\n\nExample: UID\n```js\n'*id:UID'.toJSONSchema().transform({ id: UID() }).response;\n```\n\n### name:GUID\n\nType: `type`\n\nUn GUID.\n\nSe recortan los espacios y se comprueba con `String.isGUID()`. Un valor vacío pasa a ser `null`.\n\nExample: GUID\n```js\n'token:GUID'.toJSONSchema().transform({ token: GUID() }).response;\n```\n\n### name:Name\n\nType: `type`\n\nUn nombre de persona.\n\nEl valor se formatea con `String.toName()`: cada palabra empieza por una letra mayúscula.\n\nExample: Nombre\n```js\n'fullname:Name'.toJSONSchema().transform({ fullname: 'peter sirka' }).response;\n// { fullname: 'Peter Sirka' }\n```\n\n### name:Lower  name:Lowercase  name:Upper  name:Uppercase\n\nType: `type`\n\nTexto en minúsculas o mayúsculas.\n\n`Lower` y `Lowercase` recortan los espacios del valor y lo convierten a minúsculas. `Upper` y `Uppercase` lo convierten a mayúsculas.\n\nExample: Mayúsculas y minúsculas\n```js\n'login:Lower,country:Upper'.toJSONSchema().transform({ login: 'PETER', country: 'sk' }).response;\n// { login: 'peter', country: 'SK' }\n```\n\n### name:Capitalize  name:Capitalize2\n\nType: `type`\n\nTexto con letras mayúsculas.\n\n`Capitalize` pone en mayúscula la primera letra de cada palabra. `Capitalize2` pone en mayúscula solo la primera letra del texto.\n\nExample: Capitalize\n```js\n'title:Capitalize,sentence:Capitalize2'.toJSONSchema().transform({ title: 'hello world', sentence: 'hello world' }).response;\n// { title: 'Hello World', sentence: 'Hello world' }\n```\n\n### name:Color\n\nType: `type`\n\nUn color hexadecimal.\n\nEl valor debe ser `#RGB`, `#RRGGBB` o `#RRGGBBAA` (letras en mayúsculas o minúsculas).\n\nExample: Color\n```js\n'color:Color'.toJSONSchema().transform({ color: '#4285F4' }).response;\n```\n\n### name:Icon\n\nType: `type`\n\nUna clase de icono.\n\nEl valor debe ser una clase de icono de Total.js icons o de Font Awesome: un prefijo (`ti`, `tic`, `fa`, `far`, `fab`, `fad`, `fal`, `fas`), un espacio y el nombre del icono con un prefijo `ti-`, `tic-` o `fa-`, por ejemplo `ti ti-home` o `fas fa-check`.\n\nExample: Icono\n```js\n'icon:Icon'.toJSONSchema().transform({ icon: 'ti ti-home' }).response;\n```\n\n### name:Base64\n\nType: `type`\n\nUna cadena Base64.\n\nSe recortan los espacios y se comprueba con `String.isBase64()`. Un valor vacío pasa a ser `null`.\n\nExample: Base64\n```js\n'file:Base64'.toJSONSchema().transform({ file: 'SGVsbG8=' }).response;\n```\n\n### name:JSON\n\nType: `type`\n\nUn texto JSON.\n\nSe recorta y se comprueba con `String.isJSON()`: el valor debe empezar y terminar como un objeto, un array o un string JSON, o ser un número. El contenido no se parsea y el valor sigue siendo un string; parséalo con `String.parseJSON()` cuando necesites el objeto. Un valor vacío se convierte en `null`.\n\nExample: JSON\n```js\n'settings:JSON'.toJSONSchema().transform({ settings: '{\"theme\":\"dark\"}' }).response;\n// { settings: '{\"theme\":\"dark\"}' }\n\n'settings:JSON'.toJSONSchema().transform({ settings: 'dark' }).error.output();\n// [{ name: 'settings', error: 'The field \"settings\" is invalid', path: 'settings' }]\n```\n\n### name:DataURI\n\nType: `type`\n\nUn data URI analizado en un buffer.\n\nEl valor debe ser un data URI en Base64 como `data:image/png;base64,...`. Se analiza con `String.parseDataURI()` en `{ type, buffer }`, donde `type` es el tipo de contenido y `buffer` los datos decodificados. Un valor vacío pasa a ser `null`.\n\nExample: Subir una foto como JSON\n```js\nNEWACTION('Users/photo', {\n\tinput: '*photo:DataURI',\n\taction: function($, model) {\n\t\t// model.photo.type === 'image/png'\n\t\t// model.photo.buffer is a Buffer\n\t\t$.success();\n\t}\n});\n```\n\n### name:IP\n\nType: `type`\n\nUna dirección IP.\n\nSe recorta y se comprueba con `net.isIP()` de Node.js: una dirección IPv4 canónica (`10.0.0.1`) o una dirección IPv6 (`::1`). Un nombre de host o una forma corta como `127.1` no es válido. Un valor vacío se convierte en `null`.\n\nExample: IP\n```js\n'server:IP'.toJSONSchema().transform({ server: ' 10.0.0.1 ' }).response;\n// { server: '10.0.0.1' }\n\n'server:IP'.toJSONSchema().transform({ server: '10.0.0.300' }).error.output();\n// [{ name: 'server', error: 'The field \"server\" is invalid', path: 'server' }]\n```\n\n### name:DataURI2\n\nType: `type`\n\nUn data URI conservado como texto.\n\nEl valor debe ser un data URI en Base64, como `DataURI`, pero no se analiza: la respuesta contiene el texto original. Úsalo cuando guardes el data URI tal cual. Un valor vacío pasa a ser `null`.\n\nExample: Conservar el texto\n```js\n'avatar:DataURI2'.toJSONSchema().transform({ avatar: 'data:image/png;base64,iVBORw0KGgo=' }).response;\n// { avatar: 'data:image/png;base64,iVBORw0KGgo=' }\n```\n\n### name:SafeString\n\nType: `type`\n\nTexto sin patrones de XSS ni de inyección SQL.\n\nSe recortan los espacios y se rechaza cuando `String.isXSS()` o `String.isSQLInjection()` encuentran un patrón peligroso, como una etiqueta HTML.\n\nExample: SafeString\n```js\n'comment:SafeString'.toJSONSchema().transform({ comment: '<script>alert(1)</script>' }).error.output();\n// [{ name: 'comment', error: 'The field \"comment\" is invalid', path: 'comment' }]\n```\n\n### name:Search\n\nType: `type`\n\nUna frase de búsqueda normalizada.\n\nSe recortan los espacios y se convierte con `String.toSearch()`: en minúsculas, sin diacríticos y con letras simplificadas, para poder compararla con texto de búsqueda indexado.\n\nExample: Búsqueda\n```js\n'q:Search'.toJSONSchema().transform({ q: 'Hello Wörld' }).response;\n// { q: 'helo world' }\n```\n\n### name:{a|b|c}  or  { type: 'string', enum: [...] }\n\nType: `type`\n\nUn valor de una lista fija.\n\nEn un esquema inline, enumera los valores entre llaves, separados por `|` o `;`. En un esquema JSON, usa la palabra clave `enum` con un array. Un valor que no está en la lista es un error; se permite un valor vacío salvo que el campo sea obligatorio.\n\nExample: Enum inline\n```js\n'*status:{draft|published|archived}'.toJSONSchema().transform({ status: 'published' }).response;\n```\n\nExample: Enum en un esquema JSON\n```js\nF.newjsonschema({\n\t$id: 'Task',\n\ttype: 'object',\n\tproperties: {\n\t\tpriority: { type: 'string', enum: ['low', 'normal', 'high'] }\n\t}\n});\n```\n\n### name:[Type]\n\nType: `type`\n\nUn array de valores de un tipo.\n\nEl valor debe ser un array; cualquier otra cosa hace que se omita el campo (o falla cuando el campo es obligatorio). Cada elemento se convierte al tipo, por ejemplo `[Number]` convierte `['1', 2]` en `[1, 2]`. `[{...}]` es un array de objetos anidados y `[@name]` un array validado por un esquema registrado; las rutas de los errores contienen el índice, como `items[1].price`.\n\nExample: Arrays\n```js\nvar schema = 'tags:[String],scores:[Number],lines:[{sku:String,qty:Number}]'.toJSONSchema();\nschema.transform({ tags: ['a', ' b '], scores: ['1', 2], lines: [{ sku: 'A1', qty: '2' }] }).response;\n// { tags: ['a', 'b'], scores: [1, 2], lines: [{ sku: 'A1', qty: 2 }] }\n```\n\n### name:{field:Type,...}\n\nType: `type`\n\nUn objeto anidado.\n\nLas llaves con campos (no un enum) crean un objeto anidado con sus propios campos, modificadores y tipos. El objeto anidado se valida como el principal y sus errores tienen rutas como `address.city`. Un objeto anidado puede contener más objetos anidados y arrays, por ejemplo `order:{lines:[{sku:String,qty:Number}],shipping:{address:{city:String}}}`.\n\nExample: Objeto anidado\n```js\nvar schema = '*name:String,address:{street:String,*city:String,zip:Zip}'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', address: { street: 'Main 1' } });\n// error: { name: 'city', path: 'address.city' }\n```\n\n### name:@Schema  name:[@Schema]\n\nType: `type`\n\nUn objeto anidado validado por un esquema registrado.\n\nEl valor se valida con el esquema registrado como `Schema` (con `NEWSCHEMA()`, `F.newjsonschema()` o la carpeta `jsonschemas/`). `[@Schema]` valida cada elemento de un array. Los errores conservan las rutas del objeto anidado.\n\nExample: Reutilizar un esquema\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String');\nNEWSCHEMA('@Company', '*name:String,headquarters:@Address,branches:[@Address]');\n\nvar result = F.jsonschemas.Company.transform({ name: 'Acme', branches: [{ street: 'A 1', city: 'X' }, { street: 'B 2' }] });\n// error: { name: 'city', path: 'branches[1].city', index: 1 }\n```\n\n### required: ['field', ...]\n\nType: `property`\n\nLos campos obligatorios de un esquema de objeto.\n\nUn array de nombres de propiedades. Las reglas para los valores vacíos son las mismas que para `*` en los esquemas inline.\n\nExample: required\n```js\nF.newjsonschema({\n\t$id: 'Login',\n\ttype: 'object',\n\tproperties: {\n\t\temail: { type: 'string', subtype: 'email' },\n\t\tpassword: { type: 'string' }\n\t},\n\trequired: ['email', 'password']\n});\n```\n\n### { type: 'string', subtype: 'email' }\n\nType: `property`\n\nUna palabra clave de Total.js que selecciona una conversión especial.\n\nReturns: `undefined` Nada\n\nPara las propiedades `string`, `subtype` usa la conversión de un tipo en línea: `email`, `email2`, `phone`, `url`, `zip`, `uid`, `guid`, `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`, `color`, `icon`, `base64`, `datauri`, `datauri2`, `safestring`, `search`, `json` o `ip`. `ipaddress` es igual que `ip` y solo existe en los esquemas JSON. Para las propiedades `number`, `smallint` y `tinyint` comprueban el rango. Un string vacío sigue siendo `''`; añade `nullable: true` para obtener `null`.\n\nExample: subtype\n```js\nF.newjsonschema({\n\t$id: 'Server',\n\ttype: 'object',\n\tproperties: {\n\t\thost: { type: 'string', subtype: 'ip' },\n\t\tconfig: { type: 'string', subtype: 'json' },\n\t\tport: { type: 'number', subtype: 'smallint' }\n\t}\n});\n```\n\n### { type: 'string', nullable: true }\n\nType: `property`\n\nUna palabra clave de Total.js que convierte una cadena vacía en null.\n\nPara una propiedad `string`, un valor vacío pasa a ser `null` en lugar de `''`. Los tipos inline `String2`, `UID`, `GUID`, `Base64`, `DataURI` y `DataURI2` la establecen por ti.\n\nExample: nullable\n```js\nvar schema = F.newjsonschema({ $id: 'Note', type: 'object', properties: { text: { type: 'string', nullable: true } } });\nschema.transform({ text: '' }).response;\n// { text: null }\n```\n\n### { type: 'string', minLength: 3, maxLength: 50 }\n\nType: `property`\n\nLos límites de longitud de una cadena.\n\n`minLength` y `maxLength` comprueban el número de caracteres de una cadena. `String(50)` en un esquema inline establece `maxLength`.\n\nExample: Longitud\n```js\nF.newjsonschema({\n\t$id: 'Nick',\n\ttype: 'object',\n\tproperties: { nick: { type: 'string', minLength: 3, maxLength: 20 } }\n});\n```\n\n### { type: 'number', minimum: 1, maximum: 100 }\n\nType: `property`\n\nLos límites de un número.\n\n`minimum` y `maximum` son límites inclusivos; `exclusiveMinimum` y `exclusiveMaximum`, exclusivos. `multipleOf` exige un valor divisible por el número indicado.\n\nExample: Límites numéricos\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\tquantity: { type: 'number', minimum: 1, maximum: 100 },\n\t\tdiscount: { type: 'number', exclusiveMaximum: 50 },\n\t\tpack: { type: 'number', multipleOf: 6 }\n\t}\n});\n```\n\n### { type: 'array', items: { type: 'string' } }\n\nType: `property`\n\nEl esquema de los elementos de un array.\n\nReturns: `undefined` Nada\n\n`items` es un esquema para cada elemento: un tipo con sus palabras clave (`string`, `number`, `boolean`, `date`), un `object` con sus propias `properties` y `required`, o un `$ref`. Cada elemento de tipo objeto se valida y se convierte como un objeto anidado; el error de un elemento tiene el nombre y la ruta `field.property`, y la posición del elemento en `index`. `minItems` fija el número mínimo de elementos de un array no vacío; un array vacío solo falla cuando el campo es obligatorio. `uniqueItems: true` elimina los valores duplicados.\n\nExample: Array de etiquetas\n```js\nF.newjsonschema({\n\t$id: 'Article',\n\ttype: 'object',\n\tproperties: {\n\t\ttags: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true }\n\t}\n});\n\nF.jsonschemas.Article.transform({ tags: ['a', 'b', 'a'] }).response;\n// { tags: ['a', 'b'] }\n```\n\nExample: Array de objetos\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\titems: { type: 'array', items: { type: 'object', properties: { sku: { type: 'string' }, qty: { type: 'number' } }, required: ['qty'] } }\n\t}\n});\n\nvar result = F.jsonschemas.Order.transform({ items: [{ sku: 'A', qty: '2' }, { sku: 'B' }] });\n// result.error.items[0]: name 'items.qty', path 'items.qty', index 1\n```\n\n### { type: 'object', $ref: '#/definitions/Name' }\n\nType: `property`\n\nUna referencia a otro esquema.\n\n`$ref` valida un objeto (o cada elemento de un array, en `items`) con otro esquema. Un valor que empieza por `#/` apunta a las `definitions` del mismo esquema, por ejemplo `#/definitions/Address`. Cualquier otro valor es el nombre o el `$id` de un esquema registrado en `F.jsonschemas`.\n\nExample: Referencias locales y registradas\n```js\nF.newjsonschema({ $id: 'Address', type: 'object', properties: { city: { type: 'string' } }, required: ['city'] });\n\nF.newjsonschema({\n\t$id: 'Invoice',\n\ttype: 'object',\n\tproperties: {\n\t\tbilling: { type: 'object', $ref: 'Address' },\n\t\tlines: { type: 'array', items: { $ref: '#/definitions/Line' } }\n\t},\n\tdefinitions: {\n\t\tLine: { type: 'object', properties: { name: { type: 'string' }, price: { type: 'number' } } }\n\t}\n});\n```\n\n### new ErrorBuilder()\n\nType: `class`\n\nUna lista de errores con un estado HTTP.\n\nReturns: `ErrorBuilder`\n\nLa validación devuelve sus errores en un `ErrorBuilder`, y las acciones y los controladores responden con él como un array JSON. Puedes crear uno para recoger tus propios errores. Sus propiedades: `items` (los errores sin procesar), `length` (el número de errores), `status` (el estado HTTP, `400` por defecto) y `prefix` (un texto que se antepone a los nombres de los errores de campo).\n\nExample: Recoger errores\n```js\nvar err = new ErrorBuilder();\n\nif (!model.email)\n\terr.push2('email');\n\nif (model.age < 18)\n\terr.push('You must be 18 or older');\n\nif (err.length)\n\tconsole.log(err.output());\n```\n\n### err.push(error, [path], [index])\n\nType: `method`\n\nAñade un mensaje de error o un estado HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number` | yes |  | Un mensaje o un código de estado HTTP. |\n| `path` | `String` | no |  | La ruta del campo. |\n| `index` | `Number` | no |  | El índice de un elemento de un array. |\n\nReturns: `ErrorBuilder` El mismo builder.\n\nUn número a partir de 400 establece `status` y añade el texto del estado HTTP; por ejemplo, `404` añade `404: Not Found`. Cualquier otro valor se añade como mensaje. Sin valor, se añade `401`. Un mensaje que empieza por `@(` lo traduce `output()`, por ejemplo `err.push('@(Access denied)')`.\n\nExample: Mensajes y estados\n```js\nvar err = new ErrorBuilder();\nerr.push('The product is sold out');\nerr.push(409);\nerr.status;\t // 409\nerr.output();   // [{ error: 'The product is sold out' }, { error: '409: Conflict' }]\n```\n\n### err.push2(name, [path], [index], [error])\n\nType: `method`\n\nAñade un error de un campo, con un mensaje opcional.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del campo. |\n| `path` | `String` | no |  | La ruta del campo. |\n| `index` | `Number` | no |  | El índice de un elemento de un array. |\n\nReturns: `ErrorBuilder` El mismo builder.\n\nAñade un error para el campo `name` (con `prefix` delante). Sin `error`, el mensaje lo resuelve `output()`: primero los mensajes `//` del esquema, luego el recurso con el nombre del campo en el idioma de la salida, y luego `The field \"name\" is invalid`. Con `error`, ese texto es el mensaje.\n\nFirma: `err.push2(name, [path], [index], [error])`.\n\nExample: Error de campo\n```js\nvar err = new ErrorBuilder();\nerr.push2('email', 'contact.email');\nerr.output();\n// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'contact.email' }]\n```\n\n### err.output([language])\n\nType: `method`\n\nDevuelve los errores como un array de objetos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | El idioma para los recursos y las traducciones. |\n\nReturns: `Array` La lista de errores.\n\nCada elemento es `{ name, error, path, index }` con el mensaje final. Los mensajes de los errores de campo se leen de los recursos de `language`, los textos `@(...)` se traducen y se aplican las sustituciones de `replace()`. Cuando existe un handler global `ErrorBuilder.transform()`, se devuelve su resultado en su lugar.\n\nExample: Salida\n```js\nvar err = new ErrorBuilder();\nerr.push2('name');\nconsole.log(err.output('en'));\n```\n\n### err.toString([language], [divider])\n\nType: `method`\n\nDevuelve los mensajes como un solo texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | El idioma. |\n| `divider` | `String` | no | `'\\n'` | El texto entre los mensajes. |\n\nReturns: `String`\n\nLos mensajes de `output(language)` unidos con `divider`.\n\nExample: Texto\n```js\nvar err = new ErrorBuilder();\nerr.push('First');\nerr.push('Second');\nerr.toString();\t\t\t   // 'First\\nSecond'\nerr.toString('default', ', '); // 'First, Second'\n```\n\n### err.reject([language])\n\nType: `method`\n\nDevuelve los errores como un objeto Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | El idioma. |\n\nReturns: `Error`\n\nCrea `new Error()` con todos los mensajes unidos sin separador. Útil para rechazar una promesa.\n\nExample: Rechazar una promesa\n```js\nreturn new Promise(function(resolve, reject) {\n\tvar err = new ErrorBuilder();\n\terr.push('Not allowed');\n\treject(err.reject());\n});\n```\n\n### err.throw()\n\nType: `method`\n\nHace que el builder lance una excepción en el siguiente error.\n\nReturns: `ErrorBuilder` El mismo builder.\n\nDespués de `throw()`, cada `push()` o `push2()` lanza un `Error` con el mensaje del primer error. `schema.validate()` lo usa.\n\nExample: Lanzar de inmediato\n```js\nvar err = new ErrorBuilder().throw();\ntry {\n\terr.push('Invalid token');\n} catch (e) {\n\tconsole.log(e.message); // Invalid token\n}\n```\n\n### err.replace(search, value)\n\nType: `method`\n\nReemplaza un texto en todos los mensajes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String` | yes |  | El texto que se busca. |\n| `value` | `String` | yes |  | El texto nuevo. |\n\nReturns: `ErrorBuilder` El mismo builder.\n\n`output()` aplica el reemplazo a cada mensaje, así que puedes añadir un mensaje con un marcador y rellenarlo después.\n\nExample: Marcador\n```js\nvar err = new ErrorBuilder();\nerr.push('The limit is {limit} items');\nerr.replace('{limit}', 10);\nerr.toString(); // 'The limit is 10 items'\n```\n\n### ErrorBuilder.assign(value)\n\nType: `method`\n\nCrea un builder a partir de una salida de errores, un mensaje o un Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Array|String|Number|Error` | yes |  | Los errores. |\n\nReturns: `ErrorBuilder` Un builder nuevo.\n\nCon un array, se añade cada elemento que tiene `error` (por ejemplo, los errores JSON que devuelve otra aplicación de Total.js). Un número o una cadena se añade, y un `Error` se añade como su texto.\n\nExample: Errores de otro servicio\n```js\nvar err = ErrorBuilder.assign([{ name: 'email', error: 'Email is taken' }]);\nerr.length; // 1\n```\n\n### ErrorBuilder.transform(callback)\n\nType: `method`\n\nEstablece un manejador global que cambia la salida de cada ErrorBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(output, language)` que devuelve la nueva salida. |\n\n`callback(output, language)` recibe el array que genera `output()` y devuelve lo que `output()` devolverá en su lugar. Como las acciones y los controladores envían `output()` al cliente, esto cambia el formato de todas las respuestas de error.\n\nExample: Un formato de error personalizado\n```js\nErrorBuilder.transform(function(output, language) {\n\treturn { success: false, errors: output };\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, schema)","since":"","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"'...'.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"F.newjsonschema()","signature":"F.newjsonschema(name, [schema])","since":"","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"jsonschemas/","signature":"jsonschemas/*.json","since":"","deprecated":false},{"type":"method","name":"schema.transform()","signature":"schema.transform(value, [partial], [error], [path])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(value, [partial], [path])","since":"","deprecated":false},{"type":"method","name":"schema.toAITool()","signature":"schema.toAITool(name)","since":"","deprecated":false},{"type":"method","name":"schema.toAIObject()","signature":"schema.toAIObject(name, [description])","since":"","deprecated":false},{"type":"type","name":"*field","signature":"*name:Type  or  !name:Type","since":"","deprecated":false},{"type":"type","name":"// message","signature":"name:Type // Message","since":"","deprecated":false},{"type":"type","name":"String","signature":"name:String  name:String(max)  name:Text  name:String2","since":"","deprecated":false},{"type":"type","name":"Number","signature":"name:Number  (Number2, Int, Integer, Float, Decimal)","since":"","deprecated":false},{"type":"type","name":"SmallInt","signature":"name:SmallInt","since":"","deprecated":false},{"type":"type","name":"TinyInt","signature":"name:TinyInt","since":"","deprecated":false},{"type":"type","name":"Boolean","signature":"name:Boolean  name:Bool","since":"","deprecated":false},{"type":"type","name":"Date","signature":"name:Date","since":"","deprecated":false},{"type":"type","name":"Email","signature":"name:Email","since":"","deprecated":false},{"type":"type","name":"Email2","signature":"name:Email2","since":"","deprecated":false},{"type":"type","name":"Phone","signature":"name:Phone","since":"","deprecated":false},{"type":"type","name":"URL","signature":"name:URL","since":"","deprecated":false},{"type":"type","name":"Zip","signature":"name:Zip","since":"","deprecated":false},{"type":"type","name":"UID","signature":"name:UID","since":"","deprecated":false},{"type":"type","name":"GUID","signature":"name:GUID","since":"","deprecated":false},{"type":"type","name":"Name","signature":"name:Name","since":"","deprecated":false},{"type":"type","name":"Lower / Upper","signature":"name:Lower  name:Lowercase  name:Upper  name:Uppercase","since":"","deprecated":false},{"type":"type","name":"Capitalize","signature":"name:Capitalize  name:Capitalize2","since":"","deprecated":false},{"type":"type","name":"Color","signature":"name:Color","since":"","deprecated":false},{"type":"type","name":"Icon","signature":"name:Icon","since":"","deprecated":false},{"type":"type","name":"Base64","signature":"name:Base64","since":"","deprecated":false},{"type":"type","name":"JSON","signature":"name:JSON","since":"","deprecated":false},{"type":"type","name":"DataURI","signature":"name:DataURI","since":"","deprecated":false},{"type":"type","name":"IP","signature":"name:IP","since":"","deprecated":false},{"type":"type","name":"DataURI2","signature":"name:DataURI2","since":"","deprecated":false},{"type":"type","name":"SafeString","signature":"name:SafeString","since":"","deprecated":false},{"type":"type","name":"Search","signature":"name:Search","since":"","deprecated":false},{"type":"type","name":"Enum","signature":"name:{a|b|c}  or  { type: 'string', enum: [...] }","since":"","deprecated":false},{"type":"type","name":"Array","signature":"name:[Type]","since":"","deprecated":false},{"type":"type","name":"Object","signature":"name:{field:Type,...}","since":"","deprecated":false},{"type":"type","name":"@name","signature":"name:@Schema  name:[@Schema]","since":"","deprecated":false},{"type":"property","name":"required","signature":"required: ['field', ...]","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"{ type: 'string', subtype: 'email' }","since":"","deprecated":false},{"type":"property","name":"nullable","signature":"{ type: 'string', nullable: true }","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"{ type: 'string', minLength: 3, maxLength: 50 }","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"{ type: 'number', minimum: 1, maximum: 100 }","since":"","deprecated":false},{"type":"property","name":"items","signature":"{ type: 'array', items: { type: 'string' } }","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"{ type: 'object', $ref: '#/definitions/Name' }","since":"","deprecated":false},{"type":"class","name":"ErrorBuilder","signature":"new ErrorBuilder()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push()","signature":"err.push(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push2()","signature":"err.push2(name, [path], [index], [error])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.output()","signature":"err.output([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.toString()","signature":"err.toString([language], [divider])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.reject()","signature":"err.reject([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.throw()","signature":"err.throw()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.replace()","signature":"err.replace(search, value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.assign()","signature":"ErrorBuilder.assign(value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.transform()","signature":"ErrorBuilder.transform(callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwVXEVx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Schémas et validation","summary":"Types et modificateurs des schémas inline, mots-clés des schémas JSON, méthodes des schémas et ErrorBuilder.","markdown":"---\ntitle: \"Schémas et validation\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/json-schemas/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Schémas et validation\n\n> Types et modificateurs des schémas inline, mots-clés des schémas JSON, méthodes des schémas et ErrorBuilder.\n\nLes types et modificateurs des schémas inline, les mots-clés des schémas JSON, les méthodes pour enregistrer et exécuter les schémas, ainsi que la classe `ErrorBuilder`. Pour une introduction avec des exemples, lis [Schémas et validation](../../guides/json-schemas/).\n\n## API\n\n### NEWSCHEMA(name, schema)\n\nType: `method`\n\nEnregistre un schéma inline sous un nom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du schéma ; un `@` initial est ignoré. |\n| `schema` | `String|Function` | yes |  | Un schéma inline, ou une fonction qui définit des actions. |\n\nReturns: `Object` L'objet schéma JSON lorsque `schema` est une chaîne.\n\nAvec une chaîne, le schéma inline est analysé et stocké dans `F.jsonschemas[name]`. Un `@` en début de nom est supprimé : `'@Address'` et `'Address'` enregistrent donc le même nom. Les autres schémas et les actions l'utilisent sous la forme `@Address`.\n\nAvec une fonction, la fonction reçoit un objet avec `name`, `actions` et `action(name, meta)`. `action()` crée une action nommée `<schema name>/<action name>` avec [NEWACTION](../../guides/actions/).\n\nExample: Enregistrer et utiliser un schéma\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\nNEWSCHEMA('@Customer', '*name:String,address:@Address');\n\nNEWACTION('Customers/save', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: Actions dans un schéma\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('list', {\n\t\tquery: 'page:Number',\n\t\taction: function($) {\n\t\t\t$.callback([]);\n\t\t}\n\t});\n});\n// creates the action \"Orders/list\"\n```\n\n### '...'.toJSONSchema([name], [url])\n\nType: `method`\n\nAnalyse un schéma inline et le convertit en objet schéma JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Stocke le schéma dans `F.jsonschemas` sous ce nom et l'utilise dans `$id`. |\n| `url` | `String` | no | `CONF.url` | L'URL de base de `$id`. |\n\nReturns: `Object` Un objet schéma JSON.\n\nRetourne un objet avec `$id`, `$schema`, `type: 'object'`, `properties`, `required`, `errors` (les messages `//`) et les méthodes `transform()` et `validate()`. Avec `name`, le schéma est aussi stocké dans `F.jsonschemas[name]`.\n\nLe `$id` vaut `url + name + '.json'`. Sans `url`, `CONF.url` est utilisé, ou `https://schemas.totaljs.com/`. Sans `name`, un hash de la chaîne est utilisé. `String.parseSchema()` est la même méthode.\n\nExample: Analyser et valider\n```js\nvar schema = '*name:String(50),email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'peter@example.com' });\nconsole.log(result.response);\n```\n\nExample: Enregistrer sous un nom\n```js\n'*street:String,*city:String'.toJSONSchema('Address');\n// F.jsonschemas.Address exists now\n```\n\n### F.newjsonschema(name, [schema])\n\nType: `method`\n\nEnregistre un schéma JSON ou un schéma inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Le nom du schéma, un schéma inline, ou un objet schéma JSON avec `$id`. |\n| `schema` | `Object|String` | no |  | Un objet schéma JSON ou un schéma inline. |\n\nReturns: `Object` Le schéma enregistré.\n\nLe schéma est stocké dans `F.jsonschemas` sous le nom et sous son `$id`, et reçoit la méthode `transform()`. Les formes :\n\n- `F.newjsonschema(object)` : un objet schéma JSON ; son `$id` est le nom.\n- `F.newjsonschema(name, object)` : un objet schéma JSON sous `name`.\n- `F.newjsonschema(name, 'inline schema')` : un schéma inline ; `$id` est défini sur `name`.\n- `F.newjsonschema('inline schema')` : un schéma inline enregistré sous son `$id` généré.\n\nLes fichiers du dossier `jsonschemas/` sont enregistrés avec cette méthode.\n\nExample: Un objet schéma JSON\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tprice: { type: 'number', minimum: 1 }\n\t},\n\trequired: ['name']\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nExample: Un schéma inline\n```js\nF.newjsonschema('Contact', '*name:String,*email:Email');\n```\n\n### F.jsonschemas\n\nType: `property`\n\nTous les schémas enregistrés, par nom.\n\nReturns: `Object`\n\nUn objet contenant chaque schéma enregistré par `NEWSCHEMA()`, `F.newjsonschema()`, `toJSONSchema(name)` et le dossier `jsonschemas/`. `@name` dans les schémas inline et les actions, ainsi que `$ref` dans les schémas JSON, recherchent les schémas ici.\n\nExample: Valider avec un schéma enregistré\n```js\nNEWSCHEMA('@Contact', '*name:String,*email:Email');\n\nvar result = F.jsonschemas.Contact.transform({ name: 'Peter', email: 'bad' });\nif (result.error)\n\tconsole.log(result.error.output());\n```\n\n### jsonschemas/*.json\n\nType: `config`\n\nUn dossier de schémas chargé au démarrage de l'application.\n\nChaque fichier `.json` est analysé et enregistré avec `F.newjsonschema()` ; le nom du fichier sans l'extension est le nom du schéma. Le dossier est chargé avant les dossiers contenant du code : les actions peuvent donc utiliser ses schémas avec `@name`.\n\nExample: jsonschemas/Address.json\n```js\n{\n\t\"$id\": \"Address\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" },\n\t\t\"zip\": { \"type\": \"string\", \"subtype\": \"zip\" }\n\t},\n\t\"required\": [\"street\", \"city\"]\n}\n```\n\nExample: Utilisation\n```js\nNEWACTION('Addresses/create', {\n\tinput: '@Address',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### schema.transform(value, [partial], [error], [path])\n\nType: `method`\n\nValide et convertit une valeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur à valider. |\n| `partial` | `Boolean` | no | `false` | Ne valide que les champs qui existent dans la valeur. |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un builder qui reçoit les erreurs. |\n| `path` | `String` | no |  | Un préfixe de chemin pour les chemins des erreurs. |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nRenvoie `{ error, response }`. `response` est la valeur convertie : pour un schéma d'objet, un nouvel objet avec uniquement les champs du schéma, ou `undefined` lorsqu'aucun champ n'a de valeur. `error` est un `ErrorBuilder` avec les erreurs, ou `null` lorsqu'il n'y en a pas.\n\nAvec `partial`, les champs qui valent `undefined` dans la valeur sont ignorés : les champs obligatoires manquants n'échouent donc pas. Passe ton propre `ErrorBuilder` comme `error` pour collecter les erreurs de plusieurs validations dans un seul builder.\n\nExample: Valider un corps\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'wrong' });\n\nif (result.error)\n\tconsole.log(result.error.output());\n\t// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'email' }]\nelse\n\tconsole.log(result.response);\n```\n\nExample: Mise à jour partielle\n```js\nvar schema = '*name:String,*email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ age: 40 }, true);\n// result.response === { age: 40 }, result.error === null\n```\n\n### schema.validate(value, [partial], [path])\n\nType: `method`\n\nValide une valeur et lève une exception à la première erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur à valider. |\n| `partial` | `Boolean` | no | `false` | Ne valide que les champs qui existent dans la valeur. |\n| `path` | `String` | no |  | Un préfixe de chemin pour les chemins des erreurs. |\n\nReturns: `Object` La valeur convertie.\n\nRetourne la valeur convertie. Lorsque la valeur n'est pas valide, elle lève une `Error` avec le message de la première erreur. Utilise-la lorsqu'une exception est plus simple que de vérifier `result.error`. Seuls les schémas créés à partir d'un schéma inline possèdent cette méthode.\n\nExample: Lever une exception sur des données invalides\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\n\ntry {\n\tvar model = schema.validate({ name: 'Peter' });\n} catch (e) {\n\tconsole.log(e.message); // The field \"email\" is invalid\n}\n```\n\n### schema.toAITool(name)\n\nType: `method`\n\nCrée une définition d'outil d'IA à partir d'un schéma en ligne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'outil. |\n\nReturns: `Object` La définition de l'outil.\n\nRenvoie un objet function-tool pour les modèles d'IA. Chaque champ devient un paramètre avec son `type` et, comme description, le message `//` du champ (une chaîne vide s'il n'y en a pas). Les champs obligatoires du schéma sont les paramètres obligatoires. La description de l'outil est `schema.summary` ou `schema.description` quand tu en définis une. Elle existe sur les schémas créés à partir d'un schéma en ligne (`toJSONSchema()`, `NEWSCHEMA()`), pas sur les objets de schéma JSON enregistrés avec `F.newjsonschema()`. Voir [Modèles d'IA](../../guides/ai-models/).\n\nExample: Un outil à partir d'un schéma\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nschema.description = 'Returns the weather forecast';\n\nvar tool = schema.toAITool('weather');\n// {\n//\t type: 'function',\n//\t function: {\n//\t\t name: 'weather',\n//\t\t description: 'Returns the weather forecast',\n//\t\t parameters: {\n//\t\t\t type: 'object',\n//\t\t\t properties: {\n//\t\t\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t\t\t days: { type: 'number', description: 'Number of days' }\n//\t\t\t },\n//\t\t\t required: ['city'],\n//\t\t\t additionalProperties: false\n//\t\t }\n//\t }\n// }\n```\n\n### schema.toAIObject(name, [description])\n\nType: `method`\n\nConvertit un schéma en ligne en objet JSON Schema nommé pour les modèles d'IA.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'objet. |\n| `description` | `String` | no |  | Une description de l'objet. |\n\nReturns: `Object` L'objet JSON Schema.\n\nRenvoie `{ name, description, type: 'object', properties, required, additionalProperties: false }`. Les propriétés utilisent le JSON Schema standard : `Date` est `{ type: 'string', format: 'date-time' }`, `Email` a `format: 'email'`, un enum a `enum`, un tableau a `items`, et un type qui peut valoir `null` (comme `String2`, `UID`, `GUID`, `JSON`, `IP` ou `Base64`) est `['string', 'null']`. Le message `//` d'un champ est sa `description`. `required` est omis quand aucun champ n'est obligatoire. Comme `toAITool()`, elle existe sur les schémas créés à partir d'un schéma en ligne.\n\nExample: Une réponse structurée\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// {\n//\t name: 'forecast',\n//\t description: 'The weather forecast for a city',\n//\t properties: {\n//\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t days: { type: 'number', description: 'Number of days' }\n//\t },\n//\t type: 'object',\n//\t additionalProperties: false,\n//\t required: ['city']\n// }\n```\n\n### *name:Type  or  !name:Type\n\nType: `type`\n\nMarque un champ d'un schéma inline comme requis.\n\nUn champ obligatoire échoue lorsque sa valeur est vide. Pour les chaînes, c'est une valeur vide avant le trim (un texte composé uniquement d'espaces passe et devient `''`) ; pour les nombres, une valeur manquante ou non numérique (`0` passe) ; pour les booléens, une valeur manquante (`false` passe) ; pour les dates, une valeur qui ne peut pas être analysée ; pour les tableaux, un tableau vide ou une valeur qui n'est pas un tableau. Un objet imbriqué obligatoire (`{...}` ou `@name`) n'échoue pas lorsqu'il manque. `!` équivaut à `*`.\n\nExample: Champs requis\n```js\nvar schema = '*name:String,*email:Email,phone:Phone'.toJSONSchema();\nvar result = schema.transform({ name: '' });\n// errors for \"name\" and \"email\"\n```\n\n### name:Type // Message\n\nType: `type`\n\nDéfinit un message d'erreur personnalisé pour un champ d'un schéma inline.\n\nLe texte après `//` est le message d'erreur du champ. Comme les virgules séparent les champs, le message ne peut pas contenir de virgule ; écris le schéma sur plusieurs lignes (un champ par ligne) lorsque les messages sont longs. Les messages sont stockés dans `schema.errors`.\n\nExample: Messages personnalisés\n```js\nvar schema = `*name:String // Enter your name\n\t*email:Email // Enter a valid email address`.toJSONSchema();\n\nvar result = schema.transform({ email: 'x' });\nconsole.log(result.error.output());\n// [{ name: 'name', error: 'Enter your name', ... }, { name: 'email', error: 'Enter a valid email address', ... }]\n```\n\n### name:String  name:String(max)  name:Text  name:String2\n\nType: `type`\n\nValeurs textuelles.\n\nToute valeur est convertie en chaîne, trimée, et les espaces insécables deviennent des espaces normaux. Une valeur manquante vaut `''`. `String(50)` définit la longueur maximale ; un texte plus long est une erreur. La longueur est vérifiée avant le trim, donc les espaces autour du texte comptent. `Text` équivaut à `String`. `String2` transforme une valeur vide en `null`.\n\nExample: Chaînes\n```js\nvar schema = '*title:String(100),note:Text,code:String2'.toJSONSchema();\nschema.transform({ title: '  Hello  ', code: '' }).response;\n// { title: 'Hello', note: '', code: null }\n```\n\n### name:Number  (Number2, Int, Integer, Float, Decimal)\n\nType: `type`\n\nValeurs numériques.\n\nUn nombre reste un nombre ; une chaîne contenant des chiffres est analysée avec `String.parseFloat()` (`'33'` donne `33`, `'1,5'` donne `1.5`). Les autres valeurs sont traitées comme manquantes et le champ est omis de la réponse. `Number2`, `Int`, `Integer`, `Float` et `Decimal` sont des noms du même type.\n\nExample: Nombres\n```js\nvar schema = 'price:Number,count:Int'.toJSONSchema();\nschema.transform({ price: '9,90', count: '3' }).response;\n// { price: 9.9, count: 3 }\n```\n\n### name:SmallInt\n\nType: `type`\n\nUn nombre de -32767 à 32767.\n\nAnalysé comme `Number` ; une valeur hors de l'intervalle est une erreur.\n\nExample: SmallInt\n```js\n'priority:SmallInt'.toJSONSchema().transform({ priority: 40000 }).error.output();\n// [{ name: 'priority', error: 'The field \"priority\" is invalid', path: 'priority' }]\n```\n\n### name:TinyInt\n\nType: `type`\n\nUn nombre de 0 à 255.\n\nAnalysé comme `Number` ; une valeur hors de l'intervalle est une erreur.\n\nExample: TinyInt\n```js\n'level:TinyInt'.toJSONSchema().transform({ level: '12' }).response;\n// { level: 12 }\n```\n\n### name:Boolean  name:Bool\n\nType: `type`\n\nVrai ou faux.\n\nUn booléen reste tel quel ; les autres valeurs sont analysées avec `String.parseBoolean()` (`'true'`, `'1'`, `'on'` donnent `true`). Le champ est toujours présent dans la réponse : une valeur manquante vaut `false`.\n\nExample: Case à cocher\n```js\n'newsletter:Boolean,terms:Bool'.toJSONSchema().transform({ newsletter: 'on' }).response;\n// { newsletter: true, terms: false }\n```\n\n### name:Date\n\nType: `type`\n\nUne date.\n\nUne `Date` reste telle quelle ; les autres valeurs sont analysées avec `String.parseDate()`. Une valeur qui ne peut pas être analysée, une valeur manquante ou une date antérieure au 1er janvier 1970 vaut `null`.\n\nExample: Date\n```js\n'birthday:Date'.toJSONSchema().transform({ birthday: '1990-05-20' }).response;\n// { birthday: Date }\n```\n\n### name:Email\n\nType: `type`\n\nUne adresse e-mail.\n\nTous les espaces sont supprimés et la valeur est convertie en minuscules, puis vérifiée avec `String.isEmail()`. Une valeur vide est autorisée sauf si le champ est requis.\n\nExample: E-mail\n```js\n'*email:Email'.toJSONSchema().transform({ email: ' Peter@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Email2\n\nType: `type`\n\nUne adresse e-mail sans son tag.\n\nFonctionne comme `Email` et supprime en plus le tag de l'adresse : la partie qui va de `+` à `@`, donc `name+tag@domain.com` devient `name@domain.com`. Utilise-le quand une même personne ne doit pas s'inscrire deux fois avec des adresses taguées. Dans les schémas JSON, c'est `subtype: 'email2'` ; `toAIObject()` et le serveur MCP le décrivent comme `format: 'email'`.\n\nExample: Email2\n```js\n'*email:Email2'.toJSONSchema().transform({ email: ' Peter+News@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Phone\n\nType: `type`\n\nUn numéro de téléphone.\n\nLes espaces sont supprimés, puis la valeur est vérifiée avec `String.isPhone()`.\n\nExample: Téléphone\n```js\n'phone:Phone'.toJSONSchema().transform({ phone: '+421 900 123 456' }).response;\n// { phone: '+421900123456' }\n```\n\n### name:URL\n\nType: `type`\n\nUne adresse URL.\n\nNettoyée des espaces en début et fin et vérifiée avec `String.isURL()`.\n\nExample: URL\n```js\n'website:URL'.toJSONSchema().transform({ website: 'https://www.totaljs.com' }).response;\n```\n\n### name:Zip\n\nType: `type`\n\nUn code postal.\n\nNettoyé des espaces en début et fin et vérifié avec `String.isZIP()`.\n\nExample: Zip\n```js\n'zip:Zip'.toJSONSchema().transform({ zip: '12345' }).response;\n```\n\n### name:UID\n\nType: `type`\n\nUn identifiant unique Total.js.\n\nNettoyé des espaces en début et fin et vérifié avec `String.isUID()`, le format produit par `UID()`. Une valeur vide devient `null`.\n\nExample: UID\n```js\n'*id:UID'.toJSONSchema().transform({ id: UID() }).response;\n```\n\n### name:GUID\n\nType: `type`\n\nUn GUID.\n\nNettoyé des espaces en début et fin et vérifié avec `String.isGUID()`. Une valeur vide devient `null`.\n\nExample: GUID\n```js\n'token:GUID'.toJSONSchema().transform({ token: GUID() }).response;\n```\n\n### name:Name\n\nType: `type`\n\nUn nom de personne.\n\nLa valeur est formatée avec `String.toName()` : chaque mot commence par une majuscule.\n\nExample: Nom\n```js\n'fullname:Name'.toJSONSchema().transform({ fullname: 'peter sirka' }).response;\n// { fullname: 'Peter Sirka' }\n```\n\n### name:Lower  name:Lowercase  name:Upper  name:Uppercase\n\nType: `type`\n\nTexte en minuscules ou en majuscules.\n\n`Lower` et `Lowercase` nettoient la valeur des espaces en début et fin et la convertissent en minuscules. `Upper` et `Uppercase` la convertissent en majuscules.\n\nExample: Casse\n```js\n'login:Lower,country:Upper'.toJSONSchema().transform({ login: 'PETER', country: 'sk' }).response;\n// { login: 'peter', country: 'SK' }\n```\n\n### name:Capitalize  name:Capitalize2\n\nType: `type`\n\nTexte avec des majuscules.\n\n`Capitalize` met en majuscule la première lettre de chaque mot. `Capitalize2` met en majuscule uniquement la première lettre du texte.\n\nExample: Capitalize\n```js\n'title:Capitalize,sentence:Capitalize2'.toJSONSchema().transform({ title: 'hello world', sentence: 'hello world' }).response;\n// { title: 'Hello World', sentence: 'Hello world' }\n```\n\n### name:Color\n\nType: `type`\n\nUne couleur hexadécimale.\n\nLa valeur doit être `#RGB`, `#RRGGBB` ou `#RRGGBBAA` (lettres dans n'importe quelle casse).\n\nExample: Couleur\n```js\n'color:Color'.toJSONSchema().transform({ color: '#4285F4' }).response;\n```\n\n### name:Icon\n\nType: `type`\n\nUne classe d'icône.\n\nLa valeur doit être une classe d'icône des icônes Total.js ou de Font Awesome : un préfixe (`ti`, `tic`, `fa`, `far`, `fab`, `fad`, `fal`, `fas`), un espace, et le nom de l'icône avec un préfixe `ti-`, `tic-` ou `fa-`, par exemple `ti ti-home` ou `fas fa-check`.\n\nExample: Icône\n```js\n'icon:Icon'.toJSONSchema().transform({ icon: 'ti ti-home' }).response;\n```\n\n### name:Base64\n\nType: `type`\n\nUne chaîne Base64.\n\nNettoyée des espaces en début et fin et vérifiée avec `String.isBase64()`. Une valeur vide devient `null`.\n\nExample: Base64\n```js\n'file:Base64'.toJSONSchema().transform({ file: 'SGVsbG8=' }).response;\n```\n\n### name:JSON\n\nType: `type`\n\nUn texte JSON.\n\nDébarrassé des espaces aux extrémités et vérifié avec `String.isJSON()` : la valeur doit commencer et se terminer comme un objet, un tableau ou une chaîne JSON, ou être un nombre. Le contenu n'est pas analysé et la valeur reste une chaîne ; analyse-la avec `String.parseJSON()` quand tu as besoin de l'objet. Une valeur vide devient `null`.\n\nExample: JSON\n```js\n'settings:JSON'.toJSONSchema().transform({ settings: '{\"theme\":\"dark\"}' }).response;\n// { settings: '{\"theme\":\"dark\"}' }\n\n'settings:JSON'.toJSONSchema().transform({ settings: 'dark' }).error.output();\n// [{ name: 'settings', error: 'The field \"settings\" is invalid', path: 'settings' }]\n```\n\n### name:DataURI\n\nType: `type`\n\nUne data URI convertie en buffer.\n\nLa valeur doit être une data URI en Base64 comme `data:image/png;base64,...`. Elle est analysée avec `String.parseDataURI()` en `{ type, buffer }`, où `type` est le content type et `buffer` les données décodées. Une valeur vide devient `null`.\n\nExample: Envoyer une photo en JSON\n```js\nNEWACTION('Users/photo', {\n\tinput: '*photo:DataURI',\n\taction: function($, model) {\n\t\t// model.photo.type === 'image/png'\n\t\t// model.photo.buffer is a Buffer\n\t\t$.success();\n\t}\n});\n```\n\n### name:IP\n\nType: `type`\n\nUne adresse IP.\n\nDébarrassée des espaces aux extrémités et vérifiée avec `net.isIP()` de Node.js : une adresse IPv4 canonique (`10.0.0.1`) ou une adresse IPv6 (`::1`). Un nom d'hôte ou une forme courte comme `127.1` n'est pas valide. Une valeur vide devient `null`.\n\nExample: IP\n```js\n'server:IP'.toJSONSchema().transform({ server: ' 10.0.0.1 ' }).response;\n// { server: '10.0.0.1' }\n\n'server:IP'.toJSONSchema().transform({ server: '10.0.0.300' }).error.output();\n// [{ name: 'server', error: 'The field \"server\" is invalid', path: 'server' }]\n```\n\n### name:DataURI2\n\nType: `type`\n\nUne data URI conservée en tant que texte.\n\nLa valeur doit être une data URI en Base64, comme pour `DataURI`, mais elle n'est pas analysée : la réponse contient le texte original. Utilise-la lorsque tu stockes la data URI telle quelle. Une valeur vide devient `null`.\n\nExample: Conserver le texte\n```js\n'avatar:DataURI2'.toJSONSchema().transform({ avatar: 'data:image/png;base64,iVBORw0KGgo=' }).response;\n// { avatar: 'data:image/png;base64,iVBORw0KGgo=' }\n```\n\n### name:SafeString\n\nType: `type`\n\nTexte sans motifs XSS ni d'injection SQL.\n\nNettoyé des espaces en début et fin et rejeté lorsque `String.isXSS()` ou `String.isSQLInjection()` détecte un motif dangereux, comme une balise HTML.\n\nExample: SafeString\n```js\n'comment:SafeString'.toJSONSchema().transform({ comment: '<script>alert(1)</script>' }).error.output();\n// [{ name: 'comment', error: 'The field \"comment\" is invalid', path: 'comment' }]\n```\n\n### name:Search\n\nType: `type`\n\nUne expression de recherche normalisée.\n\nNettoyée des espaces en début et fin et convertie avec `String.toSearch()` : en minuscules, sans diacritiques et avec des lettres simplifiées, afin de pouvoir être comparée à un texte de recherche indexé.\n\nExample: Recherche\n```js\n'q:Search'.toJSONSchema().transform({ q: 'Hello Wörld' }).response;\n// { q: 'helo world' }\n```\n\n### name:{a|b|c}  or  { type: 'string', enum: [...] }\n\nType: `type`\n\nUne valeur issue d'une liste fixe.\n\nDans un schéma inline, liste les valeurs entre accolades, séparées par `|` ou `;`. Dans un schéma JSON, utilise le mot-clé `enum` avec un tableau. Une valeur absente de la liste est une erreur ; une valeur vide est autorisée sauf si le champ est requis.\n\nExample: Enum inline\n```js\n'*status:{draft|published|archived}'.toJSONSchema().transform({ status: 'published' }).response;\n```\n\nExample: Enum de schéma JSON\n```js\nF.newjsonschema({\n\t$id: 'Task',\n\ttype: 'object',\n\tproperties: {\n\t\tpriority: { type: 'string', enum: ['low', 'normal', 'high'] }\n\t}\n});\n```\n\n### name:[Type]\n\nType: `type`\n\nUn tableau de valeurs d'un seul type.\n\nLa valeur doit être un tableau ; toute autre valeur entraîne l'omission du champ (ou un échec lorsque le champ est requis). Chaque élément est converti dans le type, par exemple `[Number]` transforme `['1', 2]` en `[1, 2]`. `[{...}]` est un tableau d'objets imbriqués et `[@name]` un tableau validé par un schéma enregistré ; les chemins des erreurs contiennent l'index, comme `items[1].price`.\n\nExample: Tableaux\n```js\nvar schema = 'tags:[String],scores:[Number],lines:[{sku:String,qty:Number}]'.toJSONSchema();\nschema.transform({ tags: ['a', ' b '], scores: ['1', 2], lines: [{ sku: 'A1', qty: '2' }] }).response;\n// { tags: ['a', 'b'], scores: [1, 2], lines: [{ sku: 'A1', qty: 2 }] }\n```\n\n### name:{field:Type,...}\n\nType: `type`\n\nUn objet imbriqué.\n\nDes accolades contenant des champs (et non un enum) créent un objet imbriqué avec ses propres champs, modificateurs et types. L'objet imbriqué est validé comme l'objet principal et ses erreurs ont des chemins comme `address.city`. Un objet imbriqué peut contenir d'autres objets imbriqués et tableaux, par exemple `order:{lines:[{sku:String,qty:Number}],shipping:{address:{city:String}}}`.\n\nExample: Objet imbriqué\n```js\nvar schema = '*name:String,address:{street:String,*city:String,zip:Zip}'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', address: { street: 'Main 1' } });\n// error: { name: 'city', path: 'address.city' }\n```\n\n### name:@Schema  name:[@Schema]\n\nType: `type`\n\nUn objet imbriqué validé par un schéma enregistré.\n\nLa valeur est validée par le schéma enregistré sous `Schema` (avec `NEWSCHEMA()`, `F.newjsonschema()` ou le dossier `jsonschemas/`). `[@Schema]` valide chaque élément d'un tableau. Les erreurs conservent les chemins de l'objet imbriqué.\n\nExample: Réutiliser un schéma\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String');\nNEWSCHEMA('@Company', '*name:String,headquarters:@Address,branches:[@Address]');\n\nvar result = F.jsonschemas.Company.transform({ name: 'Acme', branches: [{ street: 'A 1', city: 'X' }, { street: 'B 2' }] });\n// error: { name: 'city', path: 'branches[1].city', index: 1 }\n```\n\n### required: ['field', ...]\n\nType: `property`\n\nLes champs requis d'un schéma d'objet.\n\nUn tableau de noms de propriétés. Les règles pour les valeurs vides sont les mêmes que pour `*` dans les schémas inline.\n\nExample: required\n```js\nF.newjsonschema({\n\t$id: 'Login',\n\ttype: 'object',\n\tproperties: {\n\t\temail: { type: 'string', subtype: 'email' },\n\t\tpassword: { type: 'string' }\n\t},\n\trequired: ['email', 'password']\n});\n```\n\n### { type: 'string', subtype: 'email' }\n\nType: `property`\n\nUn mot-clé Total.js qui sélectionne une conversion spéciale.\n\nPour les propriétés `string`, `subtype` utilise la conversion d'un type inline : `email`, `email2`, `phone`, `url`, `zip`, `uid`, `guid`, `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`, `color`, `icon`, `base64`, `datauri`, `datauri2`, `safestring`, `search`, `json` ou `ip`. `ipaddress` est identique à `ip` et n'existe que dans les schémas JSON. Pour les propriétés `number`, `smallint` et `tinyint` vérifient la plage. Une chaîne vide reste `''` ; ajoute `nullable: true` pour obtenir `null`.\n\nExample: subtype\n```js\nF.newjsonschema({\n\t$id: 'Server',\n\ttype: 'object',\n\tproperties: {\n\t\thost: { type: 'string', subtype: 'ip' },\n\t\tconfig: { type: 'string', subtype: 'json' },\n\t\tport: { type: 'number', subtype: 'smallint' }\n\t}\n});\n```\n\n### { type: 'string', nullable: true }\n\nType: `property`\n\nUn mot-clé Total.js qui transforme une chaîne vide en null.\n\nPour une propriété `string`, une valeur vide devient `null` au lieu de `''`. Les types inline `String2`, `UID`, `GUID`, `Base64`, `DataURI` et `DataURI2` le définissent pour toi.\n\nExample: nullable\n```js\nvar schema = F.newjsonschema({ $id: 'Note', type: 'object', properties: { text: { type: 'string', nullable: true } } });\nschema.transform({ text: '' }).response;\n// { text: null }\n```\n\n### { type: 'string', minLength: 3, maxLength: 50 }\n\nType: `property`\n\nLes limites de longueur d'une chaîne.\n\n`minLength` et `maxLength` vérifient le nombre de caractères d'une chaîne. `String(50)` dans un schéma inline définit `maxLength`.\n\nExample: Longueur\n```js\nF.newjsonschema({\n\t$id: 'Nick',\n\ttype: 'object',\n\tproperties: { nick: { type: 'string', minLength: 3, maxLength: 20 } }\n});\n```\n\n### { type: 'number', minimum: 1, maximum: 100 }\n\nType: `property`\n\nLes limites d'un nombre.\n\n`minimum` et `maximum` sont des limites inclusives, `exclusiveMinimum` et `exclusiveMaximum` des limites exclusives. `multipleOf` exige une valeur divisible par le nombre donné.\n\nExample: Limites numériques\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\tquantity: { type: 'number', minimum: 1, maximum: 100 },\n\t\tdiscount: { type: 'number', exclusiveMaximum: 50 },\n\t\tpack: { type: 'number', multipleOf: 6 }\n\t}\n});\n```\n\n### { type: 'array', items: { type: 'string' } }\n\nType: `property`\n\nLe schéma des éléments d'un tableau.\n\n`items` est un seul schéma pour chaque élément : un type avec ses mots-clés (`string`, `number`, `boolean`, `date`), un `object` avec ses propres `properties` et `required`, ou une `$ref`. Chaque élément d'un objet est validé et converti comme un objet imbriqué ; une erreur d'un élément a le nom et le chemin `field.property` et la position de l'élément dans `index`. `minItems` définit le plus petit nombre d'éléments d'un tableau non vide ; un tableau vide n'échoue que lorsque le champ est obligatoire. `uniqueItems: true` supprime les valeurs en double.\n\nExample: Tableau de tags\n```js\nF.newjsonschema({\n\t$id: 'Article',\n\ttype: 'object',\n\tproperties: {\n\t\ttags: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true }\n\t}\n});\n\nF.jsonschemas.Article.transform({ tags: ['a', 'b', 'a'] }).response;\n// { tags: ['a', 'b'] }\n```\n\nExample: Tableau d'objets\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\titems: { type: 'array', items: { type: 'object', properties: { sku: { type: 'string' }, qty: { type: 'number' } }, required: ['qty'] } }\n\t}\n});\n\nvar result = F.jsonschemas.Order.transform({ items: [{ sku: 'A', qty: '2' }, { sku: 'B' }] });\n// result.error.items[0]: name 'items.qty', path 'items.qty', index 1\n```\n\n### { type: 'object', $ref: '#/definitions/Name' }\n\nType: `property`\n\nUne référence à un autre schéma.\n\n`$ref` valide un objet (ou chaque élément d'un tableau, dans `items`) avec un autre schéma. Une valeur commençant par `#/` pointe vers les `definitions` du même schéma, par exemple `#/definitions/Address`. Toute autre valeur est le nom ou le `$id` d'un schéma enregistré dans `F.jsonschemas`.\n\nExample: Références locales et enregistrées\n```js\nF.newjsonschema({ $id: 'Address', type: 'object', properties: { city: { type: 'string' } }, required: ['city'] });\n\nF.newjsonschema({\n\t$id: 'Invoice',\n\ttype: 'object',\n\tproperties: {\n\t\tbilling: { type: 'object', $ref: 'Address' },\n\t\tlines: { type: 'array', items: { $ref: '#/definitions/Line' } }\n\t},\n\tdefinitions: {\n\t\tLine: { type: 'object', properties: { name: { type: 'string' }, price: { type: 'number' } } }\n\t}\n});\n```\n\n### new ErrorBuilder()\n\nType: `class`\n\nUne liste d'erreurs avec un statut HTTP.\n\nReturns: `ErrorBuilder`\n\nLa validation retourne ses erreurs dans un `ErrorBuilder`, et les actions et les contrôleurs répondent avec celui-ci sous forme de tableau JSON. Tu peux en créer un pour collecter tes propres erreurs. Ses propriétés : `items` (les erreurs brutes), `length` (le nombre d'erreurs), `status` (le statut HTTP, `400` par défaut) et `prefix` (un texte placé avant les noms des erreurs de champ).\n\nExample: Collecter des erreurs\n```js\nvar err = new ErrorBuilder();\n\nif (!model.email)\n\terr.push2('email');\n\nif (model.age < 18)\n\terr.push('You must be 18 or older');\n\nif (err.length)\n\tconsole.log(err.output());\n```\n\n### err.push(error, [path], [index])\n\nType: `method`\n\nAjoute un message d'erreur ou un statut HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number` | yes |  | Un message ou un code de statut HTTP. |\n| `path` | `String` | no |  | Le chemin du champ. |\n| `index` | `Number` | no |  | L'index d'un élément de tableau. |\n\nReturns: `ErrorBuilder` Le même builder.\n\nUn nombre à partir de 400 définit `status` et ajoute le texte du statut HTTP, par exemple `404` ajoute `404: Not Found`. Toute autre valeur est ajoutée comme message. Sans valeur, `401` est ajouté. Un message qui commence par `@(` est traduit par `output()`, par exemple `err.push('@(Access denied)')`.\n\nExample: Messages et statuts\n```js\nvar err = new ErrorBuilder();\nerr.push('The product is sold out');\nerr.push(409);\nerr.status;\t // 409\nerr.output();   // [{ error: 'The product is sold out' }, { error: '409: Conflict' }]\n```\n\n### err.push2(name, [path], [index], [error])\n\nType: `method`\n\nAjoute une erreur de champ, avec un message facultatif.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `path` | `String` | no |  | Le chemin du champ. |\n| `index` | `Number` | no |  | L'index d'un élément de tableau. |\n\nReturns: `ErrorBuilder` Le même builder.\n\nAjoute une erreur pour le champ `name` (précédé de `prefix`). Sans `error`, le message est résolu par `output()` : d'abord les messages `//` du schéma, puis la ressource portant le nom du champ dans la langue de la sortie, puis `The field \"name\" is invalid`. Avec `error`, ce texte est le message.\n\nSignature : `err.push2(name, [path], [index], [error])`.\n\nExample: Erreur de champ\n```js\nvar err = new ErrorBuilder();\nerr.push2('email', 'contact.email');\nerr.output();\n// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'contact.email' }]\n```\n\n### err.output([language])\n\nType: `method`\n\nRetourne les erreurs sous forme de tableau d'objets.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | La langue des ressources et des traductions. |\n\nReturns: `Array` La liste des erreurs.\n\nChaque élément est `{ name, error, path, index }` avec le message final. Les messages des erreurs de champ sont lus dans les ressources de `language`, les textes `@(...)` sont traduits, et les remplacements de `replace()` sont appliqués. Lorsqu'un handler global `ErrorBuilder.transform()` existe, son résultat est renvoyé à la place.\n\nExample: Sortie\n```js\nvar err = new ErrorBuilder();\nerr.push2('name');\nconsole.log(err.output('en'));\n```\n\n### err.toString([language], [divider])\n\nType: `method`\n\nRetourne les messages sous forme d'un seul texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | La langue. |\n| `divider` | `String` | no | `'\\n'` | Le texte entre les messages. |\n\nReturns: `String`\n\nLes messages de `output(language)` joints par `divider`.\n\nExample: Texte\n```js\nvar err = new ErrorBuilder();\nerr.push('First');\nerr.push('Second');\nerr.toString();\t\t\t   // 'First\\nSecond'\nerr.toString('default', ', '); // 'First, Second'\n```\n\n### err.reject([language])\n\nType: `method`\n\nRetourne les erreurs sous forme d'objet Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | La langue. |\n\nReturns: `Error`\n\nCrée `new Error()` avec tous les messages joints sans séparateur. Utile pour rejeter une promesse.\n\nExample: Rejeter une promesse\n```js\nreturn new Promise(function(resolve, reject) {\n\tvar err = new ErrorBuilder();\n\terr.push('Not allowed');\n\treject(err.reject());\n});\n```\n\n### err.throw()\n\nType: `method`\n\nFait lever une exception au builder à la prochaine erreur.\n\nReturns: `ErrorBuilder` Le même builder.\n\nAprès `throw()`, chaque `push()` ou `push2()` lève une `Error` avec le message de la première erreur. `schema.validate()` l'utilise.\n\nExample: Lever immédiatement\n```js\nvar err = new ErrorBuilder().throw();\ntry {\n\terr.push('Invalid token');\n} catch (e) {\n\tconsole.log(e.message); // Invalid token\n}\n```\n\n### err.replace(search, value)\n\nType: `method`\n\nRemplace un texte dans tous les messages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String` | yes |  | Le texte à rechercher. |\n| `value` | `String` | yes |  | Le nouveau texte. |\n\nReturns: `ErrorBuilder` Le même builder.\n\nLe remplacement est appliqué par `output()` à chaque message : tu peux donc ajouter un message avec un placeholder et le compléter plus tard.\n\nExample: Placeholder\n```js\nvar err = new ErrorBuilder();\nerr.push('The limit is {limit} items');\nerr.replace('{limit}', 10);\nerr.toString(); // 'The limit is 10 items'\n```\n\n### ErrorBuilder.assign(value)\n\nType: `method`\n\nCrée un builder à partir d'une sortie d'erreurs, d'un message ou d'une Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Array|String|Number|Error` | yes |  | Les erreurs. |\n\nReturns: `ErrorBuilder` Un nouveau builder.\n\nAvec un tableau, chaque élément qui possède `error` est ajouté (par exemple les erreurs JSON retournées par une autre application Total.js). Un nombre ou une chaîne est ajouté, et une `Error` est ajoutée sous forme de son texte.\n\nExample: Erreurs d'un autre service\n```js\nvar err = ErrorBuilder.assign([{ name: 'email', error: 'Email is taken' }]);\nerr.length; // 1\n```\n\n### ErrorBuilder.transform(callback)\n\nType: `method`\n\nDéfinit un gestionnaire global qui modifie la sortie de chaque ErrorBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(output, language)` qui retourne la nouvelle sortie. |\n\n`callback(output, language)` reçoit le tableau produit par `output()` et retourne ce que `output()` retournera à la place. Comme les actions et les contrôleurs envoient `output()` au client, cela modifie le format de toutes les réponses d'erreur.\n\nExample: Un format d'erreur personnalisé\n```js\nErrorBuilder.transform(function(output, language) {\n\treturn { success: false, errors: output };\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, schema)","since":"","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"'...'.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"F.newjsonschema()","signature":"F.newjsonschema(name, [schema])","since":"","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"jsonschemas/","signature":"jsonschemas/*.json","since":"","deprecated":false},{"type":"method","name":"schema.transform()","signature":"schema.transform(value, [partial], [error], [path])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(value, [partial], [path])","since":"","deprecated":false},{"type":"method","name":"schema.toAITool()","signature":"schema.toAITool(name)","since":"","deprecated":false},{"type":"method","name":"schema.toAIObject()","signature":"schema.toAIObject(name, [description])","since":"","deprecated":false},{"type":"type","name":"*field","signature":"*name:Type  or  !name:Type","since":"","deprecated":false},{"type":"type","name":"// message","signature":"name:Type // Message","since":"","deprecated":false},{"type":"type","name":"String","signature":"name:String  name:String(max)  name:Text  name:String2","since":"","deprecated":false},{"type":"type","name":"Number","signature":"name:Number  (Number2, Int, Integer, Float, Decimal)","since":"","deprecated":false},{"type":"type","name":"SmallInt","signature":"name:SmallInt","since":"","deprecated":false},{"type":"type","name":"TinyInt","signature":"name:TinyInt","since":"","deprecated":false},{"type":"type","name":"Boolean","signature":"name:Boolean  name:Bool","since":"","deprecated":false},{"type":"type","name":"Date","signature":"name:Date","since":"","deprecated":false},{"type":"type","name":"Email","signature":"name:Email","since":"","deprecated":false},{"type":"type","name":"Email2","signature":"name:Email2","since":"","deprecated":false},{"type":"type","name":"Phone","signature":"name:Phone","since":"","deprecated":false},{"type":"type","name":"URL","signature":"name:URL","since":"","deprecated":false},{"type":"type","name":"Zip","signature":"name:Zip","since":"","deprecated":false},{"type":"type","name":"UID","signature":"name:UID","since":"","deprecated":false},{"type":"type","name":"GUID","signature":"name:GUID","since":"","deprecated":false},{"type":"type","name":"Name","signature":"name:Name","since":"","deprecated":false},{"type":"type","name":"Lower / Upper","signature":"name:Lower  name:Lowercase  name:Upper  name:Uppercase","since":"","deprecated":false},{"type":"type","name":"Capitalize","signature":"name:Capitalize  name:Capitalize2","since":"","deprecated":false},{"type":"type","name":"Color","signature":"name:Color","since":"","deprecated":false},{"type":"type","name":"Icon","signature":"name:Icon","since":"","deprecated":false},{"type":"type","name":"Base64","signature":"name:Base64","since":"","deprecated":false},{"type":"type","name":"JSON","signature":"name:JSON","since":"","deprecated":false},{"type":"type","name":"DataURI","signature":"name:DataURI","since":"","deprecated":false},{"type":"type","name":"IP","signature":"name:IP","since":"","deprecated":false},{"type":"type","name":"DataURI2","signature":"name:DataURI2","since":"","deprecated":false},{"type":"type","name":"SafeString","signature":"name:SafeString","since":"","deprecated":false},{"type":"type","name":"Search","signature":"name:Search","since":"","deprecated":false},{"type":"type","name":"Enum","signature":"name:{a|b|c}  or  { type: 'string', enum: [...] }","since":"","deprecated":false},{"type":"type","name":"Array","signature":"name:[Type]","since":"","deprecated":false},{"type":"type","name":"Object","signature":"name:{field:Type,...}","since":"","deprecated":false},{"type":"type","name":"@name","signature":"name:@Schema  name:[@Schema]","since":"","deprecated":false},{"type":"property","name":"required","signature":"required: ['field', ...]","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"{ type: 'string', subtype: 'email' }","since":"","deprecated":false},{"type":"property","name":"nullable","signature":"{ type: 'string', nullable: true }","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"{ type: 'string', minLength: 3, maxLength: 50 }","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"{ type: 'number', minimum: 1, maximum: 100 }","since":"","deprecated":false},{"type":"property","name":"items","signature":"{ type: 'array', items: { type: 'string' } }","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"{ type: 'object', $ref: '#/definitions/Name' }","since":"","deprecated":false},{"type":"class","name":"ErrorBuilder","signature":"new ErrorBuilder()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push()","signature":"err.push(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push2()","signature":"err.push2(name, [path], [index], [error])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.output()","signature":"err.output([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.toString()","signature":"err.toString([language], [divider])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.reject()","signature":"err.reject([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.throw()","signature":"err.throw()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.replace()","signature":"err.replace(search, value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.assign()","signature":"ErrorBuilder.assign(value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.transform()","signature":"ErrorBuilder.transform(callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwVXEVx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Schemi e validazione","summary":"Tipi e modificatori degli schemi inline, parole chiave degli schemi JSON, metodi degli schemi ed ErrorBuilder.","markdown":"---\ntitle: Schemi e validazione\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/json-schemas/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Schemi e validazione\n\n> Tipi e modificatori degli schemi inline, parole chiave degli schemi JSON, metodi degli schemi ed ErrorBuilder.\n\nI tipi e i modificatori degli schemi inline, le parole chiave degli schemi JSON, i metodi per registrare ed eseguire gli schemi e la classe `ErrorBuilder`. Per un'introduzione con esempi, leggi [Schemi e validazione](../../guides/json-schemas/).\n\n## API\n\n### NEWSCHEMA(name, schema)\n\nType: `method`\n\nRegistra uno schema inline con un nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dello schema; un `@` iniziale viene ignorato. |\n| `schema` | `String|Function` | yes |  | Uno schema inline, o una funzione che definisce azioni. |\n\nReturns: `Object` L'oggetto schema JSON quando `schema` è una stringa.\n\nCon una stringa, lo schema inline viene interpretato e salvato in `F.jsonschemas[name]`. Un `@` iniziale nel nome viene rimosso, quindi `'@Address'` e `'Address'` registrano lo stesso nome. Altri schemi e azioni lo usano come `@Address`.\n\nCon una funzione, la funzione riceve un oggetto con `name`, `actions` e `action(name, meta)`. `action()` crea un'azione chiamata `<schema name>/<action name>` con [NEWACTION](../../guides/actions/).\n\nExample: Registrare e usare uno schema\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\nNEWSCHEMA('@Customer', '*name:String,address:@Address');\n\nNEWACTION('Customers/save', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: Azioni in uno schema\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('list', {\n\t\tquery: 'page:Number',\n\t\taction: function($) {\n\t\t\t$.callback([]);\n\t\t}\n\t});\n});\n// creates the action \"Orders/list\"\n```\n\n### '...'.toJSONSchema([name], [url])\n\nType: `method`\n\nInterpreta uno schema inline in un oggetto schema JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Salva lo schema in `F.jsonschemas` con questo nome e lo usa in `$id`. |\n| `url` | `String` | no | `CONF.url` | L'URL di base di `$id`. |\n\nReturns: `Object` Un oggetto schema JSON.\n\nRestituisce un oggetto con `$id`, `$schema`, `type: 'object'`, `properties`, `required`, `errors` (i messaggi `//`) e i metodi `transform()` e `validate()`. Con `name`, lo schema viene anche salvato in `F.jsonschemas[name]`.\n\nL'`$id` è `url + name + '.json'`. Senza `url`, viene usato `CONF.url`, oppure `https://schemas.totaljs.com/`. Senza `name`, viene usato un hash della stringa. `String.parseSchema()` è lo stesso metodo.\n\nExample: Interpretare e validare\n```js\nvar schema = '*name:String(50),email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'peter@example.com' });\nconsole.log(result.response);\n```\n\nExample: Registrare con un nome\n```js\n'*street:String,*city:String'.toJSONSchema('Address');\n// F.jsonschemas.Address exists now\n```\n\n### F.newjsonschema(name, [schema])\n\nType: `method`\n\nRegistra uno schema JSON o uno schema inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Il nome dello schema, uno schema inline, o un oggetto schema JSON con `$id`. |\n| `schema` | `Object|String` | no |  | Un oggetto schema JSON o uno schema inline. |\n\nReturns: `Object` Lo schema registrato.\n\nLo schema viene salvato in `F.jsonschemas` con il nome e con il suo `$id`, e riceve il metodo `transform()`. Le forme:\n\n- `F.newjsonschema(object)`: un oggetto schema JSON; il suo `$id` è il nome.\n- `F.newjsonschema(name, object)`: un oggetto schema JSON con il nome `name`.\n- `F.newjsonschema(name, 'inline schema')`: uno schema inline; `$id` viene impostato a `name`.\n- `F.newjsonschema('inline schema')`: uno schema inline registrato con il suo `$id` generato.\n\nI file della cartella `jsonschemas/` vengono registrati con questo metodo.\n\nExample: Un oggetto schema JSON\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tprice: { type: 'number', minimum: 1 }\n\t},\n\trequired: ['name']\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nExample: Uno schema inline\n```js\nF.newjsonschema('Contact', '*name:String,*email:Email');\n```\n\n### F.jsonschemas\n\nType: `property`\n\nTutti gli schemi registrati, per nome.\n\nReturns: `Object`\n\nUn oggetto con ogni schema registrato da `NEWSCHEMA()`, `F.newjsonschema()`, `toJSONSchema(name)` e dalla cartella `jsonschemas/`. `@name` negli schemi inline e nelle azioni, e `$ref` negli schemi JSON, cercano gli schemi qui.\n\nExample: Validare con uno schema registrato\n```js\nNEWSCHEMA('@Contact', '*name:String,*email:Email');\n\nvar result = F.jsonschemas.Contact.transform({ name: 'Peter', email: 'bad' });\nif (result.error)\n\tconsole.log(result.error.output());\n```\n\n### jsonschemas/*.json\n\nType: `config`\n\nUna cartella di schemi caricata all'avvio dell'applicazione.\n\nOgni file `.json` viene interpretato e registrato con `F.newjsonschema()`; il nome del file senza estensione è il nome dello schema. La cartella viene caricata prima delle cartelle con il codice, quindi le azioni possono usarne gli schemi con `@name`.\n\nExample: jsonschemas/Address.json\n```js\n{\n\t\"$id\": \"Address\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" },\n\t\t\"zip\": { \"type\": \"string\", \"subtype\": \"zip\" }\n\t},\n\t\"required\": [\"street\", \"city\"]\n}\n```\n\nExample: Usarlo\n```js\nNEWACTION('Addresses/create', {\n\tinput: '@Address',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### schema.transform(value, [partial], [error], [path])\n\nType: `method`\n\nValida e converte un valore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore da validare. |\n| `partial` | `Boolean` | no | `false` | Valida solo i campi presenti nel valore. |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un builder che riceve gli errori. |\n| `path` | `String` | no |  | Un prefisso per i percorsi degli errori. |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nRestituisce `{ error, response }`. `response` è il valore convertito: per uno schema oggetto, un nuovo oggetto con solo i campi dello schema, oppure `undefined` quando nessun campo ha un valore. `error` è un `ErrorBuilder` con gli errori, oppure `null` quando non ce ne sono.\n\nCon `partial`, i campi che sono `undefined` nel valore vengono saltati, quindi i campi obbligatori mancanti non fanno fallire la validazione. Passa il tuo `ErrorBuilder` come `error` per raccogliere gli errori di più validazioni in un unico builder.\n\nExample: Validare un body\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'wrong' });\n\nif (result.error)\n\tconsole.log(result.error.output());\n\t// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'email' }]\nelse\n\tconsole.log(result.response);\n```\n\nExample: Aggiornamento parziale\n```js\nvar schema = '*name:String,*email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ age: 40 }, true);\n// result.response === { age: 40 }, result.error === null\n```\n\n### schema.validate(value, [partial], [path])\n\nType: `method`\n\nValida un valore e lancia un'eccezione al primo errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore da validare. |\n| `partial` | `Boolean` | no | `false` | Valida solo i campi presenti nel valore. |\n| `path` | `String` | no |  | Un prefisso per i percorsi degli errori. |\n\nReturns: `Object` Il valore convertito.\n\nRestituisce il valore convertito. Quando il valore non è valido, lancia un `Error` con il messaggio del primo errore. Usalo dove un'eccezione è più semplice che controllare `result.error`. Solo gli schemi creati da uno schema inline hanno questo metodo.\n\nExample: Eccezione su dati non validi\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\n\ntry {\n\tvar model = schema.validate({ name: 'Peter' });\n} catch (e) {\n\tconsole.log(e.message); // The field \"email\" is invalid\n}\n```\n\n### schema.toAITool(name)\n\nType: `method`\n\nCrea la definizione di un tool AI da uno schema inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del tool. |\n\nReturns: `Object` La definizione del tool.\n\nRestituisce un oggetto function-tool per i modelli AI. Ogni campo diventa un parametro con il suo `type` e, come descrizione, il messaggio `//` del campo (una stringa vuota se manca). I campi obbligatori dello schema sono i parametri obbligatori. La descrizione del tool è `schema.summary` o `schema.description` quando ne imposti uno. Esiste sugli schemi creati da uno schema inline (`toJSONSchema()`, `NEWSCHEMA()`), non sugli oggetti JSON Schema registrati con `F.newjsonschema()`. Vedi [Modelli AI](../../guides/ai-models/).\n\nExample: Un tool da uno schema\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nschema.description = 'Returns the weather forecast';\n\nvar tool = schema.toAITool('weather');\n// {\n//\t type: 'function',\n//\t function: {\n//\t\t name: 'weather',\n//\t\t description: 'Returns the weather forecast',\n//\t\t parameters: {\n//\t\t\t type: 'object',\n//\t\t\t properties: {\n//\t\t\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t\t\t days: { type: 'number', description: 'Number of days' }\n//\t\t\t },\n//\t\t\t required: ['city'],\n//\t\t\t additionalProperties: false\n//\t\t }\n//\t }\n// }\n```\n\n### schema.toAIObject(name, [description])\n\nType: `method`\n\nConverte uno schema inline in un oggetto JSON Schema con nome per i modelli AI.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'oggetto. |\n| `description` | `String` | no |  | Una descrizione dell'oggetto. |\n\nReturns: `Object` L'oggetto JSON Schema.\n\nRestituisce `{ name, description, type: 'object', properties, required, additionalProperties: false }`. Le proprietà usano JSON Schema standard: `Date` è `{ type: 'string', format: 'date-time' }`, `Email` ha `format: 'email'`, un enum ha `enum`, un array ha `items` e un tipo che può essere `null` (come `String2`, `UID`, `GUID`, `JSON`, `IP` o `Base64`) è `['string', 'null']`. Il messaggio `//` di un campo è la sua `description`. `required` viene omesso quando nessun campo è obbligatorio. Come `toAITool()`, esiste sugli schemi creati da uno schema inline.\n\nExample: Una risposta strutturata\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// {\n//\t name: 'forecast',\n//\t description: 'The weather forecast for a city',\n//\t properties: {\n//\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t days: { type: 'number', description: 'Number of days' }\n//\t },\n//\t type: 'object',\n//\t additionalProperties: false,\n//\t required: ['city']\n// }\n```\n\n### *name:Type  or  !name:Type\n\nType: `type`\n\nContrassegna un campo di uno schema inline come obbligatorio.\n\nUn campo obbligatorio fallisce quando il suo valore è vuoto. Per le stringhe è un valore vuoto prima del trim (un testo di soli spazi passa e diventa `''`); per i numeri un valore mancante o non numerico (`0` passa); per i booleani un valore mancante (`false` passa); per le date un valore che non può essere interpretato; per gli array un array vuoto o un valore che non è un array. Un oggetto annidato obbligatorio (`{...}` o `@name`) non fallisce quando manca. `!` equivale a `*`.\n\nExample: Campi obbligatori\n```js\nvar schema = '*name:String,*email:Email,phone:Phone'.toJSONSchema();\nvar result = schema.transform({ name: '' });\n// errors for \"name\" and \"email\"\n```\n\n### name:Type // Message\n\nType: `type`\n\nImposta un messaggio di errore personalizzato per un campo di uno schema inline.\n\nIl testo dopo `//` è il messaggio di errore del campo. Poiché le virgole separano i campi, il messaggio non può contenere virgole; scrivi lo schema su più righe (un campo per riga) quando i messaggi sono lunghi. I messaggi vengono salvati in `schema.errors`.\n\nExample: Messaggi personalizzati\n```js\nvar schema = `*name:String // Enter your name\n\t*email:Email // Enter a valid email address`.toJSONSchema();\n\nvar result = schema.transform({ email: 'x' });\nconsole.log(result.error.output());\n// [{ name: 'name', error: 'Enter your name', ... }, { name: 'email', error: 'Enter a valid email address', ... }]\n```\n\n### name:String  name:String(max)  name:Text  name:String2\n\nType: `type`\n\nValori di testo.\n\nQualsiasi valore viene convertito in stringa, sottoposto a trim, e gli spazi non separabili diventano spazi normali. Un valore mancante è `''`. `String(50)` imposta la lunghezza massima; un testo più lungo è un errore. La lunghezza viene controllata prima del trim, quindi gli spazi attorno al testo contano. `Text` equivale a `String`. `String2` trasforma un valore vuoto in `null`.\n\nExample: Stringhe\n```js\nvar schema = '*title:String(100),note:Text,code:String2'.toJSONSchema();\nschema.transform({ title: '  Hello  ', code: '' }).response;\n// { title: 'Hello', note: '', code: null }\n```\n\n### name:Number  (Number2, Int, Integer, Float, Decimal)\n\nType: `type`\n\nValori numerici.\n\nUn numero resta un numero; una stringa con cifre viene interpretata con `String.parseFloat()` (`'33'` dà `33`, `'1,5'` dà `1.5`). Gli altri valori sono trattati come mancanti e il campo viene omesso dalla risposta. `Number2`, `Int`, `Integer`, `Float` e `Decimal` sono nomi dello stesso tipo.\n\nExample: Numeri\n```js\nvar schema = 'price:Number,count:Int'.toJSONSchema();\nschema.transform({ price: '9,90', count: '3' }).response;\n// { price: 9.9, count: 3 }\n```\n\n### name:SmallInt\n\nType: `type`\n\nUn numero da -32767 a 32767.\n\nInterpretato come `Number`; un valore fuori intervallo è un errore.\n\nExample: SmallInt\n```js\n'priority:SmallInt'.toJSONSchema().transform({ priority: 40000 }).error.output();\n// [{ name: 'priority', error: 'The field \"priority\" is invalid', path: 'priority' }]\n```\n\n### name:TinyInt\n\nType: `type`\n\nUn numero da 0 a 255.\n\nInterpretato come `Number`; un valore fuori intervallo è un errore.\n\nExample: TinyInt\n```js\n'level:TinyInt'.toJSONSchema().transform({ level: '12' }).response;\n// { level: 12 }\n```\n\n### name:Boolean  name:Bool\n\nType: `type`\n\nVero o falso.\n\nUn booleano resta com'è; gli altri valori vengono interpretati con `String.parseBoolean()` (`'true'`, `'1'`, `'on'` danno `true`). Il campo è sempre presente nella risposta: un valore mancante è `false`.\n\nExample: Checkbox\n```js\n'newsletter:Boolean,terms:Bool'.toJSONSchema().transform({ newsletter: 'on' }).response;\n// { newsletter: true, terms: false }\n```\n\n### name:Date\n\nType: `type`\n\nUna data.\n\nUn `Date` resta com'è; gli altri valori vengono interpretati con `String.parseDate()`. Un valore che non può essere interpretato, un valore mancante o una data precedente al 1° gennaio 1970 è `null`.\n\nExample: Data\n```js\n'birthday:Date'.toJSONSchema().transform({ birthday: '1990-05-20' }).response;\n// { birthday: Date }\n```\n\n### name:Email\n\nType: `type`\n\nUn indirizzo email.\n\nTutti gli spazi vengono rimossi e il valore viene convertito in minuscolo, poi controllato con `String.isEmail()`. Un valore vuoto è ammesso, a meno che il campo non sia obbligatorio.\n\nExample: Email\n```js\n'*email:Email'.toJSONSchema().transform({ email: ' Peter@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Email2\n\nType: `type`\n\nUn indirizzo e-mail senza il suo tag.\n\nFunziona come `Email` e in più rimuove il tag dell'indirizzo: la parte da `+` a `@`, così `name+tag@domain.com` diventa `name@domain.com`. Usalo quando una persona non deve registrarsi due volte con indirizzi con tag. Negli schemi JSON è `subtype: 'email2'`; `toAIObject()` e il server MCP lo descrivono come `format: 'email'`.\n\nExample: Email2\n```js\n'*email:Email2'.toJSONSchema().transform({ email: ' Peter+News@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Phone\n\nType: `type`\n\nUn numero di telefono.\n\nGli spazi vengono rimossi, poi il valore viene controllato con `String.isPhone()`.\n\nExample: Telefono\n```js\n'phone:Phone'.toJSONSchema().transform({ phone: '+421 900 123 456' }).response;\n// { phone: '+421900123456' }\n```\n\n### name:URL\n\nType: `type`\n\nUn indirizzo URL.\n\nRipulito dagli spazi e controllato con `String.isURL()`.\n\nExample: URL\n```js\n'website:URL'.toJSONSchema().transform({ website: 'https://www.totaljs.com' }).response;\n```\n\n### name:Zip\n\nType: `type`\n\nUn CAP.\n\nRipulito dagli spazi e controllato con `String.isZIP()`.\n\nExample: Zip\n```js\n'zip:Zip'.toJSONSchema().transform({ zip: '12345' }).response;\n```\n\n### name:UID\n\nType: `type`\n\nUn identificatore univoco di Total.js.\n\nRipulito dagli spazi e controllato con `String.isUID()`, il formato generato da `UID()`. Un valore vuoto diventa `null`.\n\nExample: UID\n```js\n'*id:UID'.toJSONSchema().transform({ id: UID() }).response;\n```\n\n### name:GUID\n\nType: `type`\n\nUn GUID.\n\nRipulito dagli spazi e controllato con `String.isGUID()`. Un valore vuoto diventa `null`.\n\nExample: GUID\n```js\n'token:GUID'.toJSONSchema().transform({ token: GUID() }).response;\n```\n\n### name:Name\n\nType: `type`\n\nUn nome di persona.\n\nIl valore viene formattato con `String.toName()`: ogni parola inizia con una lettera maiuscola.\n\nExample: Nome\n```js\n'fullname:Name'.toJSONSchema().transform({ fullname: 'peter sirka' }).response;\n// { fullname: 'Peter Sirka' }\n```\n\n### name:Lower  name:Lowercase  name:Upper  name:Uppercase\n\nType: `type`\n\nTesto in minuscolo o maiuscolo.\n\n`Lower` e `Lowercase` ripuliscono il valore dagli spazi e lo convertono in minuscolo. `Upper` e `Uppercase` lo convertono in maiuscolo.\n\nExample: Maiuscole e minuscole\n```js\n'login:Lower,country:Upper'.toJSONSchema().transform({ login: 'PETER', country: 'sk' }).response;\n// { login: 'peter', country: 'SK' }\n```\n\n### name:Capitalize  name:Capitalize2\n\nType: `type`\n\nTesto con iniziali maiuscole.\n\n`Capitalize` mette in maiuscolo la prima lettera di ogni parola. `Capitalize2` mette in maiuscolo solo la prima lettera del testo.\n\nExample: Capitalize\n```js\n'title:Capitalize,sentence:Capitalize2'.toJSONSchema().transform({ title: 'hello world', sentence: 'hello world' }).response;\n// { title: 'Hello World', sentence: 'Hello world' }\n```\n\n### name:Color\n\nType: `type`\n\nUn colore esadecimale.\n\nIl valore deve essere `#RGB`, `#RRGGBB` o `#RRGGBBAA` (lettere maiuscole o minuscole).\n\nExample: Colore\n```js\n'color:Color'.toJSONSchema().transform({ color: '#4285F4' }).response;\n```\n\n### name:Icon\n\nType: `type`\n\nUna classe di icona.\n\nIl valore deve essere una classe di icona di Total.js icons o di Font Awesome: un prefisso (`ti`, `tic`, `fa`, `far`, `fab`, `fad`, `fal`, `fas`), uno spazio e il nome dell'icona con un prefisso `ti-`, `tic-` o `fa-`, ad esempio `ti ti-home` o `fas fa-check`.\n\nExample: Icona\n```js\n'icon:Icon'.toJSONSchema().transform({ icon: 'ti ti-home' }).response;\n```\n\n### name:Base64\n\nType: `type`\n\nUna stringa Base64.\n\nRipulita dagli spazi e controllata con `String.isBase64()`. Un valore vuoto diventa `null`.\n\nExample: Base64\n```js\n'file:Base64'.toJSONSchema().transform({ file: 'SGVsbG8=' }).response;\n```\n\n### name:JSON\n\nType: `type`\n\nUn testo JSON.\n\nRipulito dagli spazi e controllato con `String.isJSON()`: il valore deve iniziare e finire come un oggetto, un array o una stringa JSON, oppure essere un numero. Il contenuto non viene interpretato e il valore resta una stringa; interpretalo con `String.parseJSON()` quando ti serve l'oggetto. Un valore vuoto diventa `null`.\n\nExample: JSON\n```js\n'settings:JSON'.toJSONSchema().transform({ settings: '{\"theme\":\"dark\"}' }).response;\n// { settings: '{\"theme\":\"dark\"}' }\n\n'settings:JSON'.toJSONSchema().transform({ settings: 'dark' }).error.output();\n// [{ name: 'settings', error: 'The field \"settings\" is invalid', path: 'settings' }]\n```\n\n### name:DataURI\n\nType: `type`\n\nUn data URI interpretato in un buffer.\n\nIl valore deve essere un data URI Base64 come `data:image/png;base64,...`. Viene interpretato con `String.parseDataURI()` in `{ type, buffer }`, dove `type` è il content type e `buffer` i dati decodificati. Un valore vuoto diventa `null`.\n\nExample: Caricare una foto come JSON\n```js\nNEWACTION('Users/photo', {\n\tinput: '*photo:DataURI',\n\taction: function($, model) {\n\t\t// model.photo.type === 'image/png'\n\t\t// model.photo.buffer is a Buffer\n\t\t$.success();\n\t}\n});\n```\n\n### name:IP\n\nType: `type`\n\nUn indirizzo IP.\n\nRipulito dagli spazi e controllato con `net.isIP()` di Node.js: un indirizzo IPv4 canonico (`10.0.0.1`) o un indirizzo IPv6 (`::1`). Un nome host o una forma breve come `127.1` non è valido. Un valore vuoto diventa `null`.\n\nExample: IP\n```js\n'server:IP'.toJSONSchema().transform({ server: ' 10.0.0.1 ' }).response;\n// { server: '10.0.0.1' }\n\n'server:IP'.toJSONSchema().transform({ server: '10.0.0.300' }).error.output();\n// [{ name: 'server', error: 'The field \"server\" is invalid', path: 'server' }]\n```\n\n### name:DataURI2\n\nType: `type`\n\nUn data URI mantenuto come testo.\n\nIl valore deve essere un data URI Base64, come `DataURI`, ma non viene interpretato: la risposta contiene il testo originale. Usalo quando salvi il data URI così com'è. Un valore vuoto diventa `null`.\n\nExample: Mantenere il testo\n```js\n'avatar:DataURI2'.toJSONSchema().transform({ avatar: 'data:image/png;base64,iVBORw0KGgo=' }).response;\n// { avatar: 'data:image/png;base64,iVBORw0KGgo=' }\n```\n\n### name:SafeString\n\nType: `type`\n\nTesto senza pattern di XSS o SQL injection.\n\nRipulito dagli spazi e rifiutato quando `String.isXSS()` o `String.isSQLInjection()` trova un pattern pericoloso, come un tag HTML.\n\nExample: SafeString\n```js\n'comment:SafeString'.toJSONSchema().transform({ comment: '<script>alert(1)</script>' }).error.output();\n// [{ name: 'comment', error: 'The field \"comment\" is invalid', path: 'comment' }]\n```\n\n### name:Search\n\nType: `type`\n\nUna frase di ricerca normalizzata.\n\nRipulita dagli spazi e convertita con `String.toSearch()`: minuscolo, senza segni diacritici e con lettere semplificate, così può essere confrontata con il testo di ricerca indicizzato.\n\nExample: Ricerca\n```js\n'q:Search'.toJSONSchema().transform({ q: 'Hello Wörld' }).response;\n// { q: 'helo world' }\n```\n\n### name:{a|b|c}  or  { type: 'string', enum: [...] }\n\nType: `type`\n\nUn valore da un elenco fisso.\n\nIn uno schema inline, elenca i valori tra parentesi graffe, separati da `|` o `;`. In uno schema JSON, usa la parola chiave `enum` con un array. Un valore che non è nell'elenco è un errore; un valore vuoto è ammesso, a meno che il campo non sia obbligatorio.\n\nExample: Enum inline\n```js\n'*status:{draft|published|archived}'.toJSONSchema().transform({ status: 'published' }).response;\n```\n\nExample: Enum in uno schema JSON\n```js\nF.newjsonschema({\n\t$id: 'Task',\n\ttype: 'object',\n\tproperties: {\n\t\tpriority: { type: 'string', enum: ['low', 'normal', 'high'] }\n\t}\n});\n```\n\n### name:[Type]\n\nType: `type`\n\nUn array di valori di un tipo.\n\nIl valore deve essere un array; qualsiasi altra cosa fa omettere il campo (o fallire, quando il campo è obbligatorio). Ogni elemento viene convertito nel tipo, ad esempio `[Number]` trasforma `['1', 2]` in `[1, 2]`. `[{...}]` è un array di oggetti annidati e `[@name]` un array validato da uno schema registrato; i percorsi degli errori contengono l'indice, come `items[1].price`.\n\nExample: Array\n```js\nvar schema = 'tags:[String],scores:[Number],lines:[{sku:String,qty:Number}]'.toJSONSchema();\nschema.transform({ tags: ['a', ' b '], scores: ['1', 2], lines: [{ sku: 'A1', qty: '2' }] }).response;\n// { tags: ['a', 'b'], scores: [1, 2], lines: [{ sku: 'A1', qty: 2 }] }\n```\n\n### name:{field:Type,...}\n\nType: `type`\n\nUn oggetto annidato.\n\nLe parentesi graffe con dei campi (non un enum) creano un oggetto annidato con i propri campi, modificatori e tipi. L'oggetto annidato viene validato come quello principale e i suoi errori hanno percorsi come `address.city`. Un oggetto annidato può contenere ulteriori oggetti annidati e array, per esempio `order:{lines:[{sku:String,qty:Number}],shipping:{address:{city:String}}}`.\n\nExample: Oggetto annidato\n```js\nvar schema = '*name:String,address:{street:String,*city:String,zip:Zip}'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', address: { street: 'Main 1' } });\n// error: { name: 'city', path: 'address.city' }\n```\n\n### name:@Schema  name:[@Schema]\n\nType: `type`\n\nUn oggetto annidato validato da uno schema registrato.\n\nIl valore viene validato dallo schema registrato come `Schema` (con `NEWSCHEMA()`, `F.newjsonschema()` o la cartella `jsonschemas/`). `[@Schema]` valida ogni elemento di un array. Gli errori mantengono i percorsi dell'oggetto annidato.\n\nExample: Riutilizzare uno schema\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String');\nNEWSCHEMA('@Company', '*name:String,headquarters:@Address,branches:[@Address]');\n\nvar result = F.jsonschemas.Company.transform({ name: 'Acme', branches: [{ street: 'A 1', city: 'X' }, { street: 'B 2' }] });\n// error: { name: 'city', path: 'branches[1].city', index: 1 }\n```\n\n### required: ['field', ...]\n\nType: `property`\n\nI campi obbligatori di uno schema di oggetto.\n\nUn array di nomi di proprietà. Le regole per i valori vuoti sono le stesse di `*` negli schemi inline.\n\nExample: required\n```js\nF.newjsonschema({\n\t$id: 'Login',\n\ttype: 'object',\n\tproperties: {\n\t\temail: { type: 'string', subtype: 'email' },\n\t\tpassword: { type: 'string' }\n\t},\n\trequired: ['email', 'password']\n});\n```\n\n### { type: 'string', subtype: 'email' }\n\nType: `property`\n\nUna parola chiave di Total.js che seleziona una conversione speciale.\n\nPer le proprietà `string`, `subtype` usa la conversione di un tipo inline: `email`, `email2`, `phone`, `url`, `zip`, `uid`, `guid`, `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`, `color`, `icon`, `base64`, `datauri`, `datauri2`, `safestring`, `search`, `json` o `ip`. `ipaddress` è uguale a `ip` ed esiste solo negli schemi JSON. Per le proprietà `number`, `smallint` e `tinyint` controllano l'intervallo. Una stringa vuota resta `''`; aggiungi `nullable: true` per ottenere `null`.\n\nExample: subtype\n```js\nF.newjsonschema({\n\t$id: 'Server',\n\ttype: 'object',\n\tproperties: {\n\t\thost: { type: 'string', subtype: 'ip' },\n\t\tconfig: { type: 'string', subtype: 'json' },\n\t\tport: { type: 'number', subtype: 'smallint' }\n\t}\n});\n```\n\n### { type: 'string', nullable: true }\n\nType: `property`\n\nUna parola chiave di Total.js che trasforma una stringa vuota in null.\n\nPer una proprietà `string`, un valore vuoto diventa `null` invece di `''`. I tipi inline `String2`, `UID`, `GUID`, `Base64`, `DataURI` e `DataURI2` lo impostano automaticamente.\n\nExample: nullable\n```js\nvar schema = F.newjsonschema({ $id: 'Note', type: 'object', properties: { text: { type: 'string', nullable: true } } });\nschema.transform({ text: '' }).response;\n// { text: null }\n```\n\n### { type: 'string', minLength: 3, maxLength: 50 }\n\nType: `property`\n\nI limiti di lunghezza di una stringa.\n\n`minLength` e `maxLength` controllano il numero di caratteri di una stringa. `String(50)` in uno schema inline imposta `maxLength`.\n\nExample: Lunghezza\n```js\nF.newjsonschema({\n\t$id: 'Nick',\n\ttype: 'object',\n\tproperties: { nick: { type: 'string', minLength: 3, maxLength: 20 } }\n});\n```\n\n### { type: 'number', minimum: 1, maximum: 100 }\n\nType: `property`\n\nI limiti di un numero.\n\n`minimum` e `maximum` sono limiti inclusivi, `exclusiveMinimum` ed `exclusiveMaximum` esclusivi. `multipleOf` richiede un valore divisibile per il numero indicato.\n\nExample: Limiti numerici\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\tquantity: { type: 'number', minimum: 1, maximum: 100 },\n\t\tdiscount: { type: 'number', exclusiveMaximum: 50 },\n\t\tpack: { type: 'number', multipleOf: 6 }\n\t}\n});\n```\n\n### { type: 'array', items: { type: 'string' } }\n\nType: `property`\n\nLo schema degli elementi di un array.\n\n`items` è un unico schema per ogni elemento: un tipo con le sue parole chiave (`string`, `number`, `boolean`, `date`), un `object` con le sue `properties` e il suo `required`, o un `$ref`. Ogni elemento che è un oggetto viene validato e convertito come un oggetto annidato; un errore di un elemento ha il nome e il percorso `field.property` e la posizione dell'elemento in `index`. `minItems` imposta il numero minimo di elementi di un array non vuoto; un array vuoto fallisce solo quando il campo è obbligatorio. `uniqueItems: true` rimuove i valori duplicati.\n\nExample: Array di tag\n```js\nF.newjsonschema({\n\t$id: 'Article',\n\ttype: 'object',\n\tproperties: {\n\t\ttags: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true }\n\t}\n});\n\nF.jsonschemas.Article.transform({ tags: ['a', 'b', 'a'] }).response;\n// { tags: ['a', 'b'] }\n```\n\nExample: Array di oggetti\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\titems: { type: 'array', items: { type: 'object', properties: { sku: { type: 'string' }, qty: { type: 'number' } }, required: ['qty'] } }\n\t}\n});\n\nvar result = F.jsonschemas.Order.transform({ items: [{ sku: 'A', qty: '2' }, { sku: 'B' }] });\n// result.error.items[0]: name 'items.qty', path 'items.qty', index 1\n```\n\n### { type: 'object', $ref: '#/definitions/Name' }\n\nType: `property`\n\nUn riferimento a un altro schema.\n\n`$ref` valida un oggetto (o ogni elemento di un array, in `items`) con un altro schema. Un valore che inizia con `#/` punta alle `definitions` dello stesso schema, ad esempio `#/definitions/Address`. Qualsiasi altro valore è il nome o l'`$id` di uno schema registrato in `F.jsonschemas`.\n\nExample: Riferimenti locali e registrati\n```js\nF.newjsonschema({ $id: 'Address', type: 'object', properties: { city: { type: 'string' } }, required: ['city'] });\n\nF.newjsonschema({\n\t$id: 'Invoice',\n\ttype: 'object',\n\tproperties: {\n\t\tbilling: { type: 'object', $ref: 'Address' },\n\t\tlines: { type: 'array', items: { $ref: '#/definitions/Line' } }\n\t},\n\tdefinitions: {\n\t\tLine: { type: 'object', properties: { name: { type: 'string' }, price: { type: 'number' } } }\n\t}\n});\n```\n\n### new ErrorBuilder()\n\nType: `class`\n\nUn elenco di errori con uno stato HTTP.\n\nReturns: `ErrorBuilder`\n\nLa validazione restituisce i suoi errori in un `ErrorBuilder`, e azioni e controller rispondono con esso come array JSON. Puoi crearne uno per raccogliere i tuoi errori. Le sue proprietà: `items` (gli errori grezzi), `length` (il numero di errori), `status` (lo stato HTTP, `400` di default) e `prefix` (un testo messo prima dei nomi degli errori di campo).\n\nExample: Raccogliere errori\n```js\nvar err = new ErrorBuilder();\n\nif (!model.email)\n\terr.push2('email');\n\nif (model.age < 18)\n\terr.push('You must be 18 or older');\n\nif (err.length)\n\tconsole.log(err.output());\n```\n\n### err.push(error, [path], [index])\n\nType: `method`\n\nAggiunge un messaggio di errore o uno stato HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number` | yes |  | Un messaggio o un codice di stato HTTP. |\n| `path` | `String` | no |  | Il percorso del campo. |\n| `index` | `Number` | no |  | L'indice di un elemento di un array. |\n\nReturns: `ErrorBuilder` Lo stesso builder.\n\nUn numero da 400 in su imposta `status` e aggiunge il testo dello stato HTTP, ad esempio `404` aggiunge `404: Not Found`. Qualsiasi altro valore viene aggiunto come messaggio. Senza valore, viene inserito `401`. Un messaggio che inizia con `@(` viene tradotto da `output()`, ad esempio `err.push('@(Access denied)')`.\n\nExample: Messaggi e stati\n```js\nvar err = new ErrorBuilder();\nerr.push('The product is sold out');\nerr.push(409);\nerr.status;\t // 409\nerr.output();   // [{ error: 'The product is sold out' }, { error: '409: Conflict' }]\n```\n\n### err.push2(name, [path], [index], [error])\n\nType: `method`\n\nAggiunge un errore di un campo, con un messaggio facoltativo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del campo. |\n| `path` | `String` | no |  | Il percorso del campo. |\n| `index` | `Number` | no |  | L'indice di un elemento di un array. |\n\nReturns: `ErrorBuilder` Lo stesso builder.\n\nAggiunge un errore per il campo `name` (preceduto da `prefix`). Senza `error`, il messaggio viene risolto da `output()`: prima i messaggi `//` dello schema, poi la risorsa con il nome del campo nella lingua dell'output, poi `The field \"name\" is invalid`. Con `error`, quel testo è il messaggio.\n\nFirma: `err.push2(name, [path], [index], [error])`.\n\nExample: Errore di campo\n```js\nvar err = new ErrorBuilder();\nerr.push2('email', 'contact.email');\nerr.output();\n// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'contact.email' }]\n```\n\n### err.output([language])\n\nType: `method`\n\nRestituisce gli errori come array di oggetti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | La lingua per risorse e traduzioni. |\n\nReturns: `Array` L'elenco degli errori.\n\nOgni elemento è `{ name, error, path, index }` con il messaggio finale. I messaggi degli errori dei campi vengono letti dalle risorse di `language`, i testi `@(...)` vengono tradotti e vengono applicate le sostituzioni di `replace()`. Quando esiste un handler globale `ErrorBuilder.transform()`, viene restituito invece il suo risultato.\n\nExample: Output\n```js\nvar err = new ErrorBuilder();\nerr.push2('name');\nconsole.log(err.output('en'));\n```\n\n### err.toString([language], [divider])\n\nType: `method`\n\nRestituisce i messaggi come un unico testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | La lingua. |\n| `divider` | `String` | no | `'\\n'` | Il testo tra i messaggi. |\n\nReturns: `String`\n\nI messaggi di `output(language)` uniti da `divider`.\n\nExample: Testo\n```js\nvar err = new ErrorBuilder();\nerr.push('First');\nerr.push('Second');\nerr.toString();\t\t\t   // 'First\\nSecond'\nerr.toString('default', ', '); // 'First, Second'\n```\n\n### err.reject([language])\n\nType: `method`\n\nRestituisce gli errori come oggetto Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | La lingua. |\n\nReturns: `Error`\n\nCrea `new Error()` con tutti i messaggi uniti senza separatore. Utile per rifiutare una promise.\n\nExample: Rifiutare una promise\n```js\nreturn new Promise(function(resolve, reject) {\n\tvar err = new ErrorBuilder();\n\terr.push('Not allowed');\n\treject(err.reject());\n});\n```\n\n### err.throw()\n\nType: `method`\n\nFa lanciare al builder un'eccezione al prossimo errore.\n\nReturns: `ErrorBuilder` Lo stesso builder.\n\nDopo `throw()`, ogni `push()` o `push2()` lancia un `Error` con il messaggio del primo errore. `schema.validate()` lo usa.\n\nExample: Eccezione immediata\n```js\nvar err = new ErrorBuilder().throw();\ntry {\n\terr.push('Invalid token');\n} catch (e) {\n\tconsole.log(e.message); // Invalid token\n}\n```\n\n### err.replace(search, value)\n\nType: `method`\n\nSostituisce un testo in tutti i messaggi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String` | yes |  | Il testo da cercare. |\n| `value` | `String` | yes |  | Il nuovo testo. |\n\nReturns: `ErrorBuilder` Lo stesso builder.\n\nLa sostituzione viene applicata da `output()` a ogni messaggio, così puoi inserire un messaggio con un segnaposto e completarlo in seguito.\n\nExample: Segnaposto\n```js\nvar err = new ErrorBuilder();\nerr.push('The limit is {limit} items');\nerr.replace('{limit}', 10);\nerr.toString(); // 'The limit is 10 items'\n```\n\n### ErrorBuilder.assign(value)\n\nType: `method`\n\nCrea un builder da un output di errori, un messaggio o un Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Array|String|Number|Error` | yes |  | Gli errori. |\n\nReturns: `ErrorBuilder` Un nuovo builder.\n\nCon un array, viene aggiunto ogni elemento che ha `error` (ad esempio gli errori JSON restituiti da un'altra app Total.js). Un numero o una stringa viene inserito, e un `Error` viene inserito come suo testo.\n\nExample: Errori da un altro servizio\n```js\nvar err = ErrorBuilder.assign([{ name: 'email', error: 'Email is taken' }]);\nerr.length; // 1\n```\n\n### ErrorBuilder.transform(callback)\n\nType: `method`\n\nImposta un handler globale che modifica l'output di ogni ErrorBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(output, language)` che restituisce il nuovo output. |\n\n`callback(output, language)` riceve l'array creato da `output()` e restituisce ciò che `output()` restituirà al suo posto. Poiché azioni e controller inviano `output()` al client, questo cambia il formato di tutte le risposte di errore.\n\nExample: Un formato di errore personalizzato\n```js\nErrorBuilder.transform(function(output, language) {\n\treturn { success: false, errors: output };\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, schema)","since":"","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"'...'.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"F.newjsonschema()","signature":"F.newjsonschema(name, [schema])","since":"","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"jsonschemas/","signature":"jsonschemas/*.json","since":"","deprecated":false},{"type":"method","name":"schema.transform()","signature":"schema.transform(value, [partial], [error], [path])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(value, [partial], [path])","since":"","deprecated":false},{"type":"method","name":"schema.toAITool()","signature":"schema.toAITool(name)","since":"","deprecated":false},{"type":"method","name":"schema.toAIObject()","signature":"schema.toAIObject(name, [description])","since":"","deprecated":false},{"type":"type","name":"*field","signature":"*name:Type  or  !name:Type","since":"","deprecated":false},{"type":"type","name":"// message","signature":"name:Type // Message","since":"","deprecated":false},{"type":"type","name":"String","signature":"name:String  name:String(max)  name:Text  name:String2","since":"","deprecated":false},{"type":"type","name":"Number","signature":"name:Number  (Number2, Int, Integer, Float, Decimal)","since":"","deprecated":false},{"type":"type","name":"SmallInt","signature":"name:SmallInt","since":"","deprecated":false},{"type":"type","name":"TinyInt","signature":"name:TinyInt","since":"","deprecated":false},{"type":"type","name":"Boolean","signature":"name:Boolean  name:Bool","since":"","deprecated":false},{"type":"type","name":"Date","signature":"name:Date","since":"","deprecated":false},{"type":"type","name":"Email","signature":"name:Email","since":"","deprecated":false},{"type":"type","name":"Email2","signature":"name:Email2","since":"","deprecated":false},{"type":"type","name":"Phone","signature":"name:Phone","since":"","deprecated":false},{"type":"type","name":"URL","signature":"name:URL","since":"","deprecated":false},{"type":"type","name":"Zip","signature":"name:Zip","since":"","deprecated":false},{"type":"type","name":"UID","signature":"name:UID","since":"","deprecated":false},{"type":"type","name":"GUID","signature":"name:GUID","since":"","deprecated":false},{"type":"type","name":"Name","signature":"name:Name","since":"","deprecated":false},{"type":"type","name":"Lower / Upper","signature":"name:Lower  name:Lowercase  name:Upper  name:Uppercase","since":"","deprecated":false},{"type":"type","name":"Capitalize","signature":"name:Capitalize  name:Capitalize2","since":"","deprecated":false},{"type":"type","name":"Color","signature":"name:Color","since":"","deprecated":false},{"type":"type","name":"Icon","signature":"name:Icon","since":"","deprecated":false},{"type":"type","name":"Base64","signature":"name:Base64","since":"","deprecated":false},{"type":"type","name":"JSON","signature":"name:JSON","since":"","deprecated":false},{"type":"type","name":"DataURI","signature":"name:DataURI","since":"","deprecated":false},{"type":"type","name":"IP","signature":"name:IP","since":"","deprecated":false},{"type":"type","name":"DataURI2","signature":"name:DataURI2","since":"","deprecated":false},{"type":"type","name":"SafeString","signature":"name:SafeString","since":"","deprecated":false},{"type":"type","name":"Search","signature":"name:Search","since":"","deprecated":false},{"type":"type","name":"Enum","signature":"name:{a|b|c}  or  { type: 'string', enum: [...] }","since":"","deprecated":false},{"type":"type","name":"Array","signature":"name:[Type]","since":"","deprecated":false},{"type":"type","name":"Object","signature":"name:{field:Type,...}","since":"","deprecated":false},{"type":"type","name":"@name","signature":"name:@Schema  name:[@Schema]","since":"","deprecated":false},{"type":"property","name":"required","signature":"required: ['field', ...]","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"{ type: 'string', subtype: 'email' }","since":"","deprecated":false},{"type":"property","name":"nullable","signature":"{ type: 'string', nullable: true }","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"{ type: 'string', minLength: 3, maxLength: 50 }","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"{ type: 'number', minimum: 1, maximum: 100 }","since":"","deprecated":false},{"type":"property","name":"items","signature":"{ type: 'array', items: { type: 'string' } }","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"{ type: 'object', $ref: '#/definitions/Name' }","since":"","deprecated":false},{"type":"class","name":"ErrorBuilder","signature":"new ErrorBuilder()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push()","signature":"err.push(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push2()","signature":"err.push2(name, [path], [index], [error])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.output()","signature":"err.output([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.toString()","signature":"err.toString([language], [divider])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.reject()","signature":"err.reject([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.throw()","signature":"err.throw()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.replace()","signature":"err.replace(search, value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.assign()","signature":"ErrorBuilder.assign(value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.transform()","signature":"ErrorBuilder.transform(callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafwVXEVx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/json-schemas/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Schémy a validácia","summary":"Typy a modifikátory inline schém, kľúčové slová JSON schém, metódy schém a ErrorBuilder.","markdown":"---\ntitle: \"Schémy a validácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/json-schemas/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Schémy a validácia\n\n> Typy a modifikátory inline schém, kľúčové slová JSON schém, metódy schém a ErrorBuilder.\n\nTypy a modifikátory inline schém, kľúčové slová JSON schém, metódy na registráciu a spustenie schém a trieda `ErrorBuilder`. Úvod s príkladmi nájdeš v návode [Schémy a validácia](../../guides/json-schemas/).\n\n## API\n\n### NEWSCHEMA(name, schema)\n\nType: `method`\n\nZaregistruje inline schému pod menom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno schémy; úvodný `@` sa ignoruje. |\n| `schema` | `String|Function` | yes |  | Inline schéma alebo funkcia, ktorá definuje akcie. |\n\nReturns: `Object` Objekt JSON schémy, keď je `schema` reťazec.\n\nS reťazcom sa inline schéma sparsuje a uloží do `F.jsonschemas[name]`. Úvodný `@` v mene sa odstráni, takže `'@Address'` aj `'Address'` zaregistrujú rovnaké meno. Iné schémy a akcie ju používajú ako `@Address`.\n\nS funkciou dostane funkcia objekt s `name`, `actions` a `action(name, meta)`. `action()` vytvorí akciu s menom `<schema name>/<action name>` pomocou [NEWACTION](../../guides/actions/).\n\nExample: Registrácia a použitie schémy\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String,zip:Zip');\nNEWSCHEMA('@Customer', '*name:String,address:@Address');\n\nNEWACTION('Customers/save', {\n\tinput: '@Customer',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\nExample: Akcie v schéme\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('list', {\n\t\tquery: 'page:Number',\n\t\taction: function($) {\n\t\t\t$.callback([]);\n\t\t}\n\t});\n});\n// creates the action \"Orders/list\"\n```\n\n### '...'.toJSONSchema([name], [url])\n\nType: `method`\n\nSparsuje inline schému na objekt JSON schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Uloží schému do `F.jsonschemas` pod týmto menom a použije ho v `$id`. |\n| `url` | `String` | no | `CONF.url` | Základná URL pre `$id`. |\n\nReturns: `Object` Objekt JSON schémy.\n\nVráti objekt s `$id`, `$schema`, `type: 'object'`, `properties`, `required`, `errors` (správy `//`) a metódami `transform()` a `validate()`. S `name` sa schéma uloží aj do `F.jsonschemas[name]`.\n\n`$id` je `url + name + '.json'`. Bez `url` sa použije `CONF.url` alebo `https://schemas.totaljs.com/`. Bez `name` sa použije hash reťazca. `String.parseSchema()` je tá istá metóda.\n\nExample: Parsovanie a validácia\n```js\nvar schema = '*name:String(50),email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'peter@example.com' });\nconsole.log(result.response);\n```\n\nExample: Registrácia pod menom\n```js\n'*street:String,*city:String'.toJSONSchema('Address');\n// F.jsonschemas.Address exists now\n```\n\n### F.newjsonschema(name, [schema])\n\nType: `method`\n\nZaregistruje JSON schému alebo inline schému.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Meno schémy, inline schéma alebo objekt JSON schémy s `$id`. |\n| `schema` | `Object|String` | no |  | Objekt JSON schémy alebo inline schéma. |\n\nReturns: `Object` Zaregistrovaná schéma.\n\nSchéma sa uloží do `F.jsonschemas` pod menom a pod svojím `$id` a dostane metódu `transform()`. Tvary:\n\n- `F.newjsonschema(object)`: objekt JSON schémy; jeho `$id` je meno.\n- `F.newjsonschema(name, object)`: objekt JSON schémy pod menom `name`.\n- `F.newjsonschema(name, 'inline schema')`: inline schéma; `$id` sa nastaví na `name`.\n- `F.newjsonschema('inline schema')`: inline schéma zaregistrovaná pod vygenerovaným `$id`.\n\nSúbory priečinka `jsonschemas/` sa registrujú touto metódou.\n\nExample: Objekt JSON schémy\n```js\nF.newjsonschema({\n\t$id: 'Product',\n\ttype: 'object',\n\tproperties: {\n\t\tname: { type: 'string', maxLength: 100 },\n\t\tprice: { type: 'number', minimum: 1 }\n\t},\n\trequired: ['name']\n});\n\nvar result = F.jsonschemas.Product.transform({ name: 'Mug', price: '9.90' });\n```\n\nExample: Inline schéma\n```js\nF.newjsonschema('Contact', '*name:String,*email:Email');\n```\n\n### F.jsonschemas\n\nType: `property`\n\nVšetky zaregistrované schémy podľa mena.\n\nReturns: `Object`\n\nObjekt so všetkými schémami zaregistrovanými cez `NEWSCHEMA()`, `F.newjsonschema()`, `toJSONSchema(name)` a priečinok `jsonschemas/`. `@name` v inline schémach a akciách a `$ref` v JSON schémach hľadajú schémy tu.\n\nExample: Validácia so zaregistrovanou schémou\n```js\nNEWSCHEMA('@Contact', '*name:String,*email:Email');\n\nvar result = F.jsonschemas.Contact.transform({ name: 'Peter', email: 'bad' });\nif (result.error)\n\tconsole.log(result.error.output());\n```\n\n### jsonschemas/*.json\n\nType: `config`\n\nPriečinok so schémami načítanými pri štarte aplikácie.\n\nKaždý súbor `.json` sa sparsuje a zaregistruje cez `F.newjsonschema()`; meno súboru bez prípony je meno schémy. Priečinok sa načíta pred priečinkami s kódom, takže akcie môžu jeho schémy používať cez `@name`.\n\nExample: jsonschemas/Address.json\n```js\n{\n\t\"$id\": \"Address\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" },\n\t\t\"zip\": { \"type\": \"string\", \"subtype\": \"zip\" }\n\t},\n\t\"required\": [\"street\", \"city\"]\n}\n```\n\nExample: Použitie\n```js\nNEWACTION('Addresses/create', {\n\tinput: '@Address',\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n### schema.transform(value, [partial], [error], [path])\n\nType: `method`\n\nValiduje a konvertuje hodnotu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota na validáciu. |\n| `partial` | `Boolean` | no | `false` | Validuje len polia, ktoré v hodnote existujú. |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Builder, ktorý dostane chyby. |\n| `path` | `String` | no |  | Prefix cesty pre cesty chýb. |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nVráti `{ error, response }`. `response` je prevedená hodnota: pre objektovú schému nový objekt iba s poľami schémy, alebo `undefined`, keď žiadne pole nemá hodnotu. `error` je `ErrorBuilder` s chybami, alebo `null`, keď žiadne nie sú.\n\nS `partial` sa polia, ktoré sú v hodnote `undefined`, preskočia, takže chýbajúce povinné polia nezlyhajú. Odovzdaj vlastný `ErrorBuilder` ako `error`, aby si zozbieral chyby viacerých validácií v jednom builderi.\n\nExample: Validácia tela požiadavky\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', email: 'wrong' });\n\nif (result.error)\n\tconsole.log(result.error.output());\n\t// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'email' }]\nelse\n\tconsole.log(result.response);\n```\n\nExample: Čiastočná aktualizácia\n```js\nvar schema = '*name:String,*email:Email,age:Number'.toJSONSchema();\nvar result = schema.transform({ age: 40 }, true);\n// result.response === { age: 40 }, result.error === null\n```\n\n### schema.validate(value, [partial], [path])\n\nType: `method`\n\nValiduje hodnotu a pri prvej chybe vyhodí výnimku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota na validáciu. |\n| `partial` | `Boolean` | no | `false` | Validuje len polia, ktoré v hodnote existujú. |\n| `path` | `String` | no |  | Prefix cesty pre cesty chýb. |\n\nReturns: `Object` Konvertovaná hodnota.\n\nVráti konvertovanú hodnotu. Keď hodnota nie je platná, vyhodí `Error` so správou prvej chyby. Použi ju tam, kde je výnimka jednoduchšia ako kontrola `result.error`. Túto metódu majú len schémy vytvorené z inline schémy.\n\nExample: Výnimka pri neplatných dátach\n```js\nvar schema = '*name:String,*email:Email'.toJSONSchema();\n\ntry {\n\tvar model = schema.validate({ name: 'Peter' });\n} catch (e) {\n\tconsole.log(e.message); // The field \"email\" is invalid\n}\n```\n\n### schema.toAITool(name)\n\nType: `method`\n\nVytvorí definíciu AI nástroja z inline schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov nástroja. |\n\nReturns: `Object` Definícia nástroja.\n\nVráti objekt function-tool pre AI modely. Každé pole sa stane parametrom so svojím `type` a ako popis dostane správu `//` poľa (bez nej prázdny reťazec). Povinné polia schémy sú povinné parametre. Popis nástroja je `schema.summary` alebo `schema.description`, keď ho nastavíš. Existuje na schémach vytvorených z inline schémy (`toJSONSchema()`, `NEWSCHEMA()`), nie na objektoch JSON schém zaregistrovaných cez `F.newjsonschema()`. Pozri [AI modely](../../guides/ai-models/).\n\nExample: Nástroj zo schémy\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nschema.description = 'Returns the weather forecast';\n\nvar tool = schema.toAITool('weather');\n// {\n//\t type: 'function',\n//\t function: {\n//\t\t name: 'weather',\n//\t\t description: 'Returns the weather forecast',\n//\t\t parameters: {\n//\t\t\t type: 'object',\n//\t\t\t properties: {\n//\t\t\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t\t\t days: { type: 'number', description: 'Number of days' }\n//\t\t\t },\n//\t\t\t required: ['city'],\n//\t\t\t additionalProperties: false\n//\t\t }\n//\t }\n// }\n```\n\n### schema.toAIObject(name, [description])\n\nType: `method`\n\nSkonvertuje inline schému na pomenovaný objekt JSON Schema pre AI modely.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov objektu. |\n| `description` | `String` | no |  | Popis objektu. |\n\nReturns: `Object` Objekt JSON Schema.\n\nVráti `{ name, description, type: 'object', properties, required, additionalProperties: false }`. Vlastnosti používajú štandardnú JSON Schema: `Date` je `{ type: 'string', format: 'date-time' }`, `Email` má `format: 'email'`, enum má `enum`, pole má `items` a typ, ktorý môže byť `null` (napríklad `String2`, `UID`, `GUID`, `JSON`, `IP` alebo `Base64`), je `['string', 'null']`. Správa `//` poľa je jeho `description`. `required` sa vynechá, keď nie je povinné žiadne pole. Rovnako ako `toAITool()` existuje na schémach vytvorených z inline schémy.\n\nExample: Štruktúrovaná odpoveď\n```js\nvar schema = '*city:String // The name of the city,days:Number // Number of days'.toJSONSchema();\nvar obj = schema.toAIObject('forecast', 'The weather forecast for a city');\n// {\n//\t name: 'forecast',\n//\t description: 'The weather forecast for a city',\n//\t properties: {\n//\t\t city: { type: 'string', description: 'The name of the city' },\n//\t\t days: { type: 'number', description: 'Number of days' }\n//\t },\n//\t type: 'object',\n//\t additionalProperties: false,\n//\t required: ['city']\n// }\n```\n\n### *name:Type  or  !name:Type\n\nType: `type`\n\nOznačí pole inline schémy ako povinné.\n\nPovinné pole zlyhá, keď je jeho hodnota prázdna. Pre reťazce je to prázdna hodnota pred orezaním (text iba z medzier prejde a zmení sa na `''`); pre čísla chýbajúca alebo nečíselná hodnota (`0` prejde); pre booleany chýbajúca hodnota (`false` prejde); pre dátumy hodnota, ktorú nemožno sparsovať; pre polia prázdne pole alebo hodnota, ktorá nie je pole. Povinný vnorený objekt (`{...}` alebo `@name`) nezlyhá, keď chýba. `!` je to isté ako `*`.\n\nExample: Povinné polia\n```js\nvar schema = '*name:String,*email:Email,phone:Phone'.toJSONSchema();\nvar result = schema.transform({ name: '' });\n// errors for \"name\" and \"email\"\n```\n\n### name:Type // Message\n\nType: `type`\n\nNastaví vlastnú chybovú správu pre pole inline schémy.\n\nText za `//` je chybová správa poľa. Keďže čiarky oddeľujú polia, správa nemôže obsahovať čiarku; pri dlhých správach zapíš schému na viac riadkov (jedno pole na riadok). Správy sa ukladajú do `schema.errors`.\n\nExample: Vlastné správy\n```js\nvar schema = `*name:String // Enter your name\n\t*email:Email // Enter a valid email address`.toJSONSchema();\n\nvar result = schema.transform({ email: 'x' });\nconsole.log(result.error.output());\n// [{ name: 'name', error: 'Enter your name', ... }, { name: 'email', error: 'Enter a valid email address', ... }]\n```\n\n### name:String  name:String(max)  name:Text  name:String2\n\nType: `type`\n\nTextové hodnoty.\n\nAkákoľvek hodnota sa prevedie na reťazec, oreže sa a nezlomiteľné medzery sa zmenia na bežné medzery. Chýbajúca hodnota je `''`. `String(50)` nastaví maximálnu dĺžku; dlhší text je chyba. Dĺžka sa kontroluje pred orezaním, takže medzery okolo textu sa započítavajú. `Text` je to isté ako `String`. `String2` zmení prázdnu hodnotu na `null`.\n\nExample: Reťazce\n```js\nvar schema = '*title:String(100),note:Text,code:String2'.toJSONSchema();\nschema.transform({ title: '  Hello  ', code: '' }).response;\n// { title: 'Hello', note: '', code: null }\n```\n\n### name:Number  (Number2, Int, Integer, Float, Decimal)\n\nType: `type`\n\nČíselné hodnoty.\n\nČíslo zostane číslom; reťazec s číslicami sa sparsuje cez `String.parseFloat()` (`'33'` dá `33`, `'1,5'` dá `1.5`). Ostatné hodnoty sa považujú za chýbajúce a pole sa v odpovedi vynechá. `Number2`, `Int`, `Integer`, `Float` a `Decimal` sú mená toho istého typu.\n\nExample: Čísla\n```js\nvar schema = 'price:Number,count:Int'.toJSONSchema();\nschema.transform({ price: '9,90', count: '3' }).response;\n// { price: 9.9, count: 3 }\n```\n\n### name:SmallInt\n\nType: `type`\n\nČíslo od -32767 do 32767.\n\nParsuje sa ako `Number`; hodnota mimo rozsahu je chyba.\n\nExample: SmallInt\n```js\n'priority:SmallInt'.toJSONSchema().transform({ priority: 40000 }).error.output();\n// [{ name: 'priority', error: 'The field \"priority\" is invalid', path: 'priority' }]\n```\n\n### name:TinyInt\n\nType: `type`\n\nČíslo od 0 do 255.\n\nParsuje sa ako `Number`; hodnota mimo rozsahu je chyba.\n\nExample: TinyInt\n```js\n'level:TinyInt'.toJSONSchema().transform({ level: '12' }).response;\n// { level: 12 }\n```\n\n### name:Boolean  name:Bool\n\nType: `type`\n\nPravda alebo nepravda.\n\nBoolean zostane, ako je; ostatné hodnoty sa parsujú cez `String.parseBoolean()` (`'true'`, `'1'`, `'on'` dajú `true`). Pole je v odpovedi vždy: chýbajúca hodnota je `false`.\n\nExample: Checkbox\n```js\n'newsletter:Boolean,terms:Bool'.toJSONSchema().transform({ newsletter: 'on' }).response;\n// { newsletter: true, terms: false }\n```\n\n### name:Date\n\nType: `type`\n\nDátum.\n\n`Date` zostane tak, ako je; ostatné hodnoty sa sparsujú pomocou `String.parseDate()`. Hodnota, ktorú nemožno sparsovať, chýbajúca hodnota alebo dátum pred 1. januárom 1970 je `null`.\n\nExample: Dátum\n```js\n'birthday:Date'.toJSONSchema().transform({ birthday: '1990-05-20' }).response;\n// { birthday: Date }\n```\n\n### name:Email\n\nType: `type`\n\nE-mailová adresa.\n\nOdstránia sa všetky biele znaky a hodnota sa prevedie na malé písmená, potom sa skontroluje cez `String.isEmail()`. Prázdna hodnota je povolená, ak pole nie je povinné.\n\nExample: E-mail\n```js\n'*email:Email'.toJSONSchema().transform({ email: ' Peter@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Email2\n\nType: `type`\n\nE-mailová adresa bez svojho tagu.\n\nFunguje ako `Email` a navyše z adresy odstráni tag: časť od `+` po `@`, takže z `name+tag@domain.com` sa stane `name@domain.com`. Použi ho, keď sa jeden človek nesmie zaregistrovať dvakrát s adresami s tagom. V JSON schémach je to `subtype: 'email2'`; `toAIObject()` a MCP server ho opisujú ako `format: 'email'`.\n\nExample: Email2\n```js\n'*email:Email2'.toJSONSchema().transform({ email: ' Peter+News@Example.COM ' }).response;\n// { email: 'peter@example.com' }\n```\n\n### name:Phone\n\nType: `type`\n\nTelefónne číslo.\n\nOdstránia sa biele znaky, potom sa hodnota skontroluje cez `String.isPhone()`.\n\nExample: Telefón\n```js\n'phone:Phone'.toJSONSchema().transform({ phone: '+421 900 123 456' }).response;\n// { phone: '+421900123456' }\n```\n\n### name:URL\n\nType: `type`\n\nURL adresa.\n\nOreže sa a skontroluje cez `String.isURL()`.\n\nExample: URL\n```js\n'website:URL'.toJSONSchema().transform({ website: 'https://www.totaljs.com' }).response;\n```\n\n### name:Zip\n\nType: `type`\n\nPSČ.\n\nOreže sa a skontroluje cez `String.isZIP()`.\n\nExample: Zip\n```js\n'zip:Zip'.toJSONSchema().transform({ zip: '12345' }).response;\n```\n\n### name:UID\n\nType: `type`\n\nUnikátny identifikátor Total.js.\n\nOreže sa a skontroluje cez `String.isUID()`, formát vytváraný funkciou `UID()`. Prázdna hodnota sa zmení na `null`.\n\nExample: UID\n```js\n'*id:UID'.toJSONSchema().transform({ id: UID() }).response;\n```\n\n### name:GUID\n\nType: `type`\n\nGUID.\n\nOreže sa a skontroluje cez `String.isGUID()`. Prázdna hodnota sa zmení na `null`.\n\nExample: GUID\n```js\n'token:GUID'.toJSONSchema().transform({ token: GUID() }).response;\n```\n\n### name:Name\n\nType: `type`\n\nMeno osoby.\n\nHodnota sa naformátuje cez `String.toName()`: každé slovo začína veľkým písmenom.\n\nExample: Meno\n```js\n'fullname:Name'.toJSONSchema().transform({ fullname: 'peter sirka' }).response;\n// { fullname: 'Peter Sirka' }\n```\n\n### name:Lower  name:Lowercase  name:Upper  name:Uppercase\n\nType: `type`\n\nText malými alebo veľkými písmenami.\n\n`Lower` a `Lowercase` hodnotu orežú a prevedú na malé písmená. `Upper` a `Uppercase` ju prevedú na veľké písmená.\n\nExample: Veľkosť písmen\n```js\n'login:Lower,country:Upper'.toJSONSchema().transform({ login: 'PETER', country: 'sk' }).response;\n// { login: 'peter', country: 'SK' }\n```\n\n### name:Capitalize  name:Capitalize2\n\nType: `type`\n\nText s veľkými začiatočnými písmenami.\n\n`Capitalize` zmení prvé písmeno každého slova na veľké. `Capitalize2` zmení na veľké len prvé písmeno textu.\n\nExample: Capitalize\n```js\n'title:Capitalize,sentence:Capitalize2'.toJSONSchema().transform({ title: 'hello world', sentence: 'hello world' }).response;\n// { title: 'Hello World', sentence: 'Hello world' }\n```\n\n### name:Color\n\nType: `type`\n\nHex farba.\n\nHodnota musí byť `#RGB`, `#RRGGBB` alebo `#RRGGBBAA` (písmená v ľubovoľnej veľkosti).\n\nExample: Farba\n```js\n'color:Color'.toJSONSchema().transform({ color: '#4285F4' }).response;\n```\n\n### name:Icon\n\nType: `type`\n\nTrieda ikony.\n\nHodnota musí byť trieda ikony Total.js icons alebo Font Awesome: prefix (`ti`, `tic`, `fa`, `far`, `fab`, `fad`, `fal`, `fas`), medzera a názov ikony s prefixom `ti-`, `tic-` alebo `fa-`, napríklad `ti ti-home` alebo `fas fa-check`.\n\nExample: Ikona\n```js\n'icon:Icon'.toJSONSchema().transform({ icon: 'ti ti-home' }).response;\n```\n\n### name:Base64\n\nType: `type`\n\nBase64 reťazec.\n\nOreže sa a skontroluje cez `String.isBase64()`. Prázdna hodnota sa zmení na `null`.\n\nExample: Base64\n```js\n'file:Base64'.toJSONSchema().transform({ file: 'SGVsbG8=' }).response;\n```\n\n### name:JSON\n\nType: `type`\n\nJSON text.\n\nOreže sa a skontroluje cez `String.isJSON()`: hodnota musí začínať a končiť ako JSON objekt, pole alebo reťazec, alebo byť číslo. Obsah sa neparsuje a hodnota zostane reťazcom; keď potrebuješ objekt, sparsuj ju cez `String.parseJSON()`. Prázdna hodnota sa zmení na `null`.\n\nExample: JSON\n```js\n'settings:JSON'.toJSONSchema().transform({ settings: '{\"theme\":\"dark\"}' }).response;\n// { settings: '{\"theme\":\"dark\"}' }\n\n'settings:JSON'.toJSONSchema().transform({ settings: 'dark' }).error.output();\n// [{ name: 'settings', error: 'The field \"settings\" is invalid', path: 'settings' }]\n```\n\n### name:DataURI\n\nType: `type`\n\nData URI sparsované do buffera.\n\nHodnota musí byť Base64 data URI, napríklad `data:image/png;base64,...`. Sparsuje sa cez `String.parseDataURI()` na `{ type, buffer }`, kde `type` je content type a `buffer` dekódované dáta. Prázdna hodnota sa zmení na `null`.\n\nExample: Nahratie fotky ako JSON\n```js\nNEWACTION('Users/photo', {\n\tinput: '*photo:DataURI',\n\taction: function($, model) {\n\t\t// model.photo.type === 'image/png'\n\t\t// model.photo.buffer is a Buffer\n\t\t$.success();\n\t}\n});\n```\n\n### name:IP\n\nType: `type`\n\nIP adresa.\n\nOreže sa a skontroluje cez Node.js `net.isIP()`: kanonická IPv4 adresa (`10.0.0.1`) alebo IPv6 adresa (`::1`). Hostname alebo skrátený tvar ako `127.1` je neplatný. Prázdna hodnota sa zmení na `null`.\n\nExample: IP\n```js\n'server:IP'.toJSONSchema().transform({ server: ' 10.0.0.1 ' }).response;\n// { server: '10.0.0.1' }\n\n'server:IP'.toJSONSchema().transform({ server: '10.0.0.300' }).error.output();\n// [{ name: 'server', error: 'The field \"server\" is invalid', path: 'server' }]\n```\n\n### name:DataURI2\n\nType: `type`\n\nData URI ponechané ako text.\n\nHodnota musí byť Base64 data URI ako pri `DataURI`, ale nesparsuje sa: odpoveď obsahuje pôvodný text. Použi ho, keď data URI ukladáš tak, ako je. Prázdna hodnota sa zmení na `null`.\n\nExample: Ponechanie textu\n```js\n'avatar:DataURI2'.toJSONSchema().transform({ avatar: 'data:image/png;base64,iVBORw0KGgo=' }).response;\n// { avatar: 'data:image/png;base64,iVBORw0KGgo=' }\n```\n\n### name:SafeString\n\nType: `type`\n\nText bez vzorov XSS alebo SQL injection.\n\nOreže sa a odmietne, keď `String.isXSS()` alebo `String.isSQLInjection()` nájde nebezpečný vzor, napríklad HTML tag.\n\nExample: SafeString\n```js\n'comment:SafeString'.toJSONSchema().transform({ comment: '<script>alert(1)</script>' }).error.output();\n// [{ name: 'comment', error: 'The field \"comment\" is invalid', path: 'comment' }]\n```\n\n### name:Search\n\nType: `type`\n\nNormalizovaná vyhľadávacia fráza.\n\nOreže sa a konvertuje cez `String.toSearch()`: malé písmená, bez diakritiky a so zjednodušenými písmenami, takže sa dá porovnať s indexovaným vyhľadávacím textom.\n\nExample: Vyhľadávanie\n```js\n'q:Search'.toJSONSchema().transform({ q: 'Hello Wörld' }).response;\n// { q: 'helo world' }\n```\n\n### name:{a|b|c}  or  { type: 'string', enum: [...] }\n\nType: `type`\n\nHodnota z pevného zoznamu.\n\nV inline schéme uveď hodnoty v zložených zátvorkách, oddelené `|` alebo `;`. V JSON schéme použi kľúčové slovo `enum` s poľom. Hodnota, ktorá nie je v zozname, je chyba; prázdna hodnota je povolená, ak pole nie je povinné.\n\nExample: Inline enum\n```js\n'*status:{draft|published|archived}'.toJSONSchema().transform({ status: 'published' }).response;\n```\n\nExample: Enum v JSON schéme\n```js\nF.newjsonschema({\n\t$id: 'Task',\n\ttype: 'object',\n\tproperties: {\n\t\tpriority: { type: 'string', enum: ['low', 'normal', 'high'] }\n\t}\n});\n```\n\n### name:[Type]\n\nType: `type`\n\nPole hodnôt jedného typu.\n\nHodnota musí byť pole; čokoľvek iné pole z odpovede vynechá (alebo zlyhá, ak je pole povinné). Každá položka sa konvertuje na daný typ, napríklad `[Number]` zmení `['1', 2]` na `[1, 2]`. `[{...}]` je pole vnorených objektov a `[@name]` pole validované zaregistrovanou schémou; cesty chýb obsahujú index, napríklad `items[1].price`.\n\nExample: Polia\n```js\nvar schema = 'tags:[String],scores:[Number],lines:[{sku:String,qty:Number}]'.toJSONSchema();\nschema.transform({ tags: ['a', ' b '], scores: ['1', 2], lines: [{ sku: 'A1', qty: '2' }] }).response;\n// { tags: ['a', 'b'], scores: [1, 2], lines: [{ sku: 'A1', qty: 2 }] }\n```\n\n### name:{field:Type,...}\n\nType: `type`\n\nVnorený objekt.\n\nZložené zátvorky s poľami (nie enum) vytvoria vnorený objekt s vlastnými poľami, modifikátormi a typmi. Vnorený objekt sa overuje ako hlavný a jeho chyby majú cesty ako `address.city`. Vnorený objekt môže obsahovať ďalšie vnorené objekty a polia, napríklad `order:{lines:[{sku:String,qty:Number}],shipping:{address:{city:String}}}`.\n\nExample: Vnorený objekt\n```js\nvar schema = '*name:String,address:{street:String,*city:String,zip:Zip}'.toJSONSchema();\nvar result = schema.transform({ name: 'Peter', address: { street: 'Main 1' } });\n// error: { name: 'city', path: 'address.city' }\n```\n\n### name:@Schema  name:[@Schema]\n\nType: `type`\n\nVnorený objekt validovaný zaregistrovanou schémou.\n\nHodnota sa validuje schémou zaregistrovanou ako `Schema` (cez `NEWSCHEMA()`, `F.newjsonschema()` alebo priečinok `jsonschemas/`). `[@Schema]` validuje každú položku poľa. Chyby si zachovajú cesty vnoreného objektu.\n\nExample: Opätovné použitie schémy\n```js\nNEWSCHEMA('@Address', '*street:String,*city:String');\nNEWSCHEMA('@Company', '*name:String,headquarters:@Address,branches:[@Address]');\n\nvar result = F.jsonschemas.Company.transform({ name: 'Acme', branches: [{ street: 'A 1', city: 'X' }, { street: 'B 2' }] });\n// error: { name: 'city', path: 'branches[1].city', index: 1 }\n```\n\n### required: ['field', ...]\n\nType: `property`\n\nPovinné polia objektovej schémy.\n\nPole mien vlastností. Pravidlá pre prázdne hodnoty sú rovnaké ako pri `*` v inline schémach.\n\nExample: required\n```js\nF.newjsonschema({\n\t$id: 'Login',\n\ttype: 'object',\n\tproperties: {\n\t\temail: { type: 'string', subtype: 'email' },\n\t\tpassword: { type: 'string' }\n\t},\n\trequired: ['email', 'password']\n});\n```\n\n### { type: 'string', subtype: 'email' }\n\nType: `property`\n\nKľúčové slovo Total.js, ktoré vyberá špeciálnu konverziu.\n\nPre vlastnosti `string` používa `subtype` prevod inline typu: `email`, `email2`, `phone`, `url`, `zip`, `uid`, `guid`, `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`, `color`, `icon`, `base64`, `datauri`, `datauri2`, `safestring`, `search`, `json` alebo `ip`. `ipaddress` je to isté ako `ip` a existuje iba v JSON schémach. Pre vlastnosti `number` kontrolujú `smallint` a `tinyint` rozsah. Prázdny reťazec zostane `''`; pridaj `nullable: true`, aby si dostal `null`.\n\nExample: subtype\n```js\nF.newjsonschema({\n\t$id: 'Server',\n\ttype: 'object',\n\tproperties: {\n\t\thost: { type: 'string', subtype: 'ip' },\n\t\tconfig: { type: 'string', subtype: 'json' },\n\t\tport: { type: 'number', subtype: 'smallint' }\n\t}\n});\n```\n\n### { type: 'string', nullable: true }\n\nType: `property`\n\nKľúčové slovo Total.js, ktoré zmení prázdny reťazec na null.\n\nPri vlastnosti `string` sa prázdna hodnota zmení na `null` namiesto `''`. Inline typy `String2`, `UID`, `GUID`, `Base64`, `DataURI` a `DataURI2` ho nastavia za teba.\n\nExample: nullable\n```js\nvar schema = F.newjsonschema({ $id: 'Note', type: 'object', properties: { text: { type: 'string', nullable: true } } });\nschema.transform({ text: '' }).response;\n// { text: null }\n```\n\n### { type: 'string', minLength: 3, maxLength: 50 }\n\nType: `property`\n\nLimity dĺžky reťazca.\n\n`minLength` a `maxLength` kontrolujú počet znakov reťazca. `String(50)` v inline schéme nastaví `maxLength`.\n\nExample: Dĺžka\n```js\nF.newjsonschema({\n\t$id: 'Nick',\n\ttype: 'object',\n\tproperties: { nick: { type: 'string', minLength: 3, maxLength: 20 } }\n});\n```\n\n### { type: 'number', minimum: 1, maximum: 100 }\n\nType: `property`\n\nLimity čísla.\n\n`minimum` a `maximum` sú inkluzívne limity, `exclusiveMinimum` a `exclusiveMaximum` exkluzívne. `multipleOf` vyžaduje hodnotu deliteľnú zadaným číslom.\n\nExample: Limity čísla\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\tquantity: { type: 'number', minimum: 1, maximum: 100 },\n\t\tdiscount: { type: 'number', exclusiveMaximum: 50 },\n\t\tpack: { type: 'number', multipleOf: 6 }\n\t}\n});\n```\n\n### { type: 'array', items: { type: 'string' } }\n\nType: `property`\n\nSchéma položiek poľa.\n\n`items` je jedna schéma pre každú položku: typ s jeho kľúčovými slovami (`string`, `number`, `boolean`, `date`), `object` s vlastnými `properties` a `required`, alebo `$ref`. Každá položka typu objekt sa validuje a konvertuje ako vnorený objekt; chyba položky má názov a cestu `field.property` a pozíciu položky v `index`. `minItems` nastaví najmenší počet položiek neprázdneho poľa; prázdne pole zlyhá iba vtedy, keď je pole povinné. `uniqueItems: true` odstráni duplicitné hodnoty.\n\nExample: Pole tagov\n```js\nF.newjsonschema({\n\t$id: 'Article',\n\ttype: 'object',\n\tproperties: {\n\t\ttags: { type: 'array', items: { type: 'string' }, minItems: 1, uniqueItems: true }\n\t}\n});\n\nF.jsonschemas.Article.transform({ tags: ['a', 'b', 'a'] }).response;\n// { tags: ['a', 'b'] }\n```\n\nExample: Pole objektov\n```js\nF.newjsonschema({\n\t$id: 'Order',\n\ttype: 'object',\n\tproperties: {\n\t\titems: { type: 'array', items: { type: 'object', properties: { sku: { type: 'string' }, qty: { type: 'number' } }, required: ['qty'] } }\n\t}\n});\n\nvar result = F.jsonschemas.Order.transform({ items: [{ sku: 'A', qty: '2' }, { sku: 'B' }] });\n// result.error.items[0]: name 'items.qty', path 'items.qty', index 1\n```\n\n### { type: 'object', $ref: '#/definitions/Name' }\n\nType: `property`\n\nOdkaz na inú schému.\n\n`$ref` validuje objekt (alebo v `items` každú položku poľa) inou schémou. Hodnota začínajúca na `#/` ukazuje na `definitions` tej istej schémy, napríklad `#/definitions/Address`. Každá iná hodnota je meno alebo `$id` schémy zaregistrovanej v `F.jsonschemas`.\n\nExample: Lokálne a zaregistrované odkazy\n```js\nF.newjsonschema({ $id: 'Address', type: 'object', properties: { city: { type: 'string' } }, required: ['city'] });\n\nF.newjsonschema({\n\t$id: 'Invoice',\n\ttype: 'object',\n\tproperties: {\n\t\tbilling: { type: 'object', $ref: 'Address' },\n\t\tlines: { type: 'array', items: { $ref: '#/definitions/Line' } }\n\t},\n\tdefinitions: {\n\t\tLine: { type: 'object', properties: { name: { type: 'string' }, price: { type: 'number' } } }\n\t}\n});\n```\n\n### new ErrorBuilder()\n\nType: `class`\n\nZoznam chýb s HTTP statusom.\n\nReturns: `ErrorBuilder`\n\nValidácia vracia svoje chyby v `ErrorBuilder` a akcie a controllery ním odpovedajú ako JSON poľom. Môžeš si ho vytvoriť na zbieranie vlastných chýb. Jeho vlastnosti: `items` (surové chyby), `length` (počet chýb), `status` (HTTP status, predvolene `400`) a `prefix` (text vložený pred mená chýb polí).\n\nExample: Zbieranie chýb\n```js\nvar err = new ErrorBuilder();\n\nif (!model.email)\n\terr.push2('email');\n\nif (model.age < 18)\n\terr.push('You must be 18 or older');\n\nif (err.length)\n\tconsole.log(err.output());\n```\n\n### err.push(error, [path], [index])\n\nType: `method`\n\nPridá chybovú správu alebo HTTP status.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `String|Number` | yes |  | Správa alebo HTTP status kód. |\n| `path` | `String` | no |  | Cesta poľa. |\n| `index` | `Number` | no |  | Index položky poľa. |\n\nReturns: `ErrorBuilder` Ten istý builder.\n\nČíslo od 400 vyššie nastaví `status` a pridá text HTTP statusu, napríklad `404` pridá `404: Not Found`. Každá iná hodnota sa pridá ako správa. Bez hodnoty sa pridá `401`. Správu začínajúcu na `@(` preloží `output()`, napríklad `err.push('@(Access denied)')`.\n\nExample: Správy a statusy\n```js\nvar err = new ErrorBuilder();\nerr.push('The product is sold out');\nerr.push(409);\nerr.status;\t // 409\nerr.output();   // [{ error: 'The product is sold out' }, { error: '409: Conflict' }]\n```\n\n### err.push2(name, [path], [index], [error])\n\nType: `method`\n\nPridá chybu poľa s voliteľnou správou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno poľa. |\n| `path` | `String` | no |  | Cesta poľa. |\n| `index` | `Number` | no |  | Index položky poľa. |\n\nReturns: `ErrorBuilder` Ten istý builder.\n\nPridá chybu pre pole `name` (s `prefix` pred ním). Bez `error` správu určí `output()`: najprv správy `//` schémy, potom resource s názvom poľa v jazyku výstupu, potom `The field \"name\" is invalid`. S `error` je správou tento text.\n\nSignatúra: `err.push2(name, [path], [index], [error])`.\n\nExample: Chyba poľa\n```js\nvar err = new ErrorBuilder();\nerr.push2('email', 'contact.email');\nerr.output();\n// [{ name: 'email', error: 'The field \"email\" is invalid', path: 'contact.email' }]\n```\n\n### err.output([language])\n\nType: `method`\n\nVráti chyby ako pole objektov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Jazyk pre resources a preklady. |\n\nReturns: `Array` Zoznam chýb.\n\nKaždá položka je `{ name, error, path, index }` s výslednou správou. Správy chýb polí sa čítajú zo zdrojov jazyka `language`, texty `@(...)` sa preložia a použijú sa náhrady z `replace()`. Keď existuje globálny handler `ErrorBuilder.transform()`, vráti sa namiesto toho jeho výsledok.\n\nExample: Výstup\n```js\nvar err = new ErrorBuilder();\nerr.push2('name');\nconsole.log(err.output('en'));\n```\n\n### err.toString([language], [divider])\n\nType: `method`\n\nVráti správy ako jeden text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Jazyk. |\n| `divider` | `String` | no | `'\\n'` | Text medzi správami. |\n\nReturns: `String`\n\nSprávy z `output(language)` spojené oddeľovačom `divider`.\n\nExample: Text\n```js\nvar err = new ErrorBuilder();\nerr.push('First');\nerr.push('Second');\nerr.toString();\t\t\t   // 'First\\nSecond'\nerr.toString('default', ', '); // 'First, Second'\n```\n\n### err.reject([language])\n\nType: `method`\n\nVráti chyby ako objekt Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Jazyk. |\n\nReturns: `Error`\n\nVytvorí `new Error()` so všetkými správami spojenými bez oddeľovača. Hodí sa na rejectnutie promise.\n\nExample: Rejectnutie promise\n```js\nreturn new Promise(function(resolve, reject) {\n\tvar err = new ErrorBuilder();\n\terr.push('Not allowed');\n\treject(err.reject());\n});\n```\n\n### err.throw()\n\nType: `method`\n\nNastaví builder tak, aby pri ďalšej chybe vyhodil výnimku.\n\nReturns: `ErrorBuilder` Ten istý builder.\n\nPo `throw()` vyhodí každé `push()` alebo `push2()` `Error` so správou prvej chyby. Používa to `schema.validate()`.\n\nExample: Okamžitá výnimka\n```js\nvar err = new ErrorBuilder().throw();\ntry {\n\terr.push('Invalid token');\n} catch (e) {\n\tconsole.log(e.message); // Invalid token\n}\n```\n\n### err.replace(search, value)\n\nType: `method`\n\nNahradí text vo všetkých správach.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String` | yes |  | Hľadaný text. |\n| `value` | `String` | yes |  | Nový text. |\n\nReturns: `ErrorBuilder` Ten istý builder.\n\nNáhradu použije `output()` na každú správu, takže môžeš pridať správu so zástupným textom a doplniť ho neskôr.\n\nExample: Zástupný text\n```js\nvar err = new ErrorBuilder();\nerr.push('The limit is {limit} items');\nerr.replace('{limit}', 10);\nerr.toString(); // 'The limit is 10 items'\n```\n\n### ErrorBuilder.assign(value)\n\nType: `method`\n\nVytvorí builder z chybového výstupu, správy alebo objektu Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Array|String|Number|Error` | yes |  | Chyby. |\n\nReturns: `ErrorBuilder` Nový builder.\n\nS poľom sa pridá každá položka, ktorá má `error` (napríklad JSON chyby vrátené inou Total.js aplikáciou). Číslo alebo reťazec sa pridá a `Error` sa pridá ako jeho text.\n\nExample: Chyby z inej služby\n```js\nvar err = ErrorBuilder.assign([{ name: 'email', error: 'Email is taken' }]);\nerr.length; // 1\n```\n\n### ErrorBuilder.transform(callback)\n\nType: `method`\n\nNastaví globálny handler, ktorý mení výstup každého ErrorBuildera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(output, language)`, ktorá vráti nový výstup. |\n\n`callback(output, language)` dostane pole vytvorené cez `output()` a vráti to, čo namiesto neho vráti `output()`. Keďže akcie a controllery posielajú klientovi `output()`, zmení to formát všetkých chybových odpovedí.\n\nExample: Vlastný formát chýb\n```js\nErrorBuilder.transform(function(output, language) {\n\treturn { success: false, errors: output };\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, schema)","since":"","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"'...'.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"F.newjsonschema()","signature":"F.newjsonschema(name, [schema])","since":"","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"jsonschemas/","signature":"jsonschemas/*.json","since":"","deprecated":false},{"type":"method","name":"schema.transform()","signature":"schema.transform(value, [partial], [error], [path])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(value, [partial], [path])","since":"","deprecated":false},{"type":"method","name":"schema.toAITool()","signature":"schema.toAITool(name)","since":"","deprecated":false},{"type":"method","name":"schema.toAIObject()","signature":"schema.toAIObject(name, [description])","since":"","deprecated":false},{"type":"type","name":"*field","signature":"*name:Type  or  !name:Type","since":"","deprecated":false},{"type":"type","name":"// message","signature":"name:Type // Message","since":"","deprecated":false},{"type":"type","name":"String","signature":"name:String  name:String(max)  name:Text  name:String2","since":"","deprecated":false},{"type":"type","name":"Number","signature":"name:Number  (Number2, Int, Integer, Float, Decimal)","since":"","deprecated":false},{"type":"type","name":"SmallInt","signature":"name:SmallInt","since":"","deprecated":false},{"type":"type","name":"TinyInt","signature":"name:TinyInt","since":"","deprecated":false},{"type":"type","name":"Boolean","signature":"name:Boolean  name:Bool","since":"","deprecated":false},{"type":"type","name":"Date","signature":"name:Date","since":"","deprecated":false},{"type":"type","name":"Email","signature":"name:Email","since":"","deprecated":false},{"type":"type","name":"Email2","signature":"name:Email2","since":"","deprecated":false},{"type":"type","name":"Phone","signature":"name:Phone","since":"","deprecated":false},{"type":"type","name":"URL","signature":"name:URL","since":"","deprecated":false},{"type":"type","name":"Zip","signature":"name:Zip","since":"","deprecated":false},{"type":"type","name":"UID","signature":"name:UID","since":"","deprecated":false},{"type":"type","name":"GUID","signature":"name:GUID","since":"","deprecated":false},{"type":"type","name":"Name","signature":"name:Name","since":"","deprecated":false},{"type":"type","name":"Lower / Upper","signature":"name:Lower  name:Lowercase  name:Upper  name:Uppercase","since":"","deprecated":false},{"type":"type","name":"Capitalize","signature":"name:Capitalize  name:Capitalize2","since":"","deprecated":false},{"type":"type","name":"Color","signature":"name:Color","since":"","deprecated":false},{"type":"type","name":"Icon","signature":"name:Icon","since":"","deprecated":false},{"type":"type","name":"Base64","signature":"name:Base64","since":"","deprecated":false},{"type":"type","name":"JSON","signature":"name:JSON","since":"","deprecated":false},{"type":"type","name":"DataURI","signature":"name:DataURI","since":"","deprecated":false},{"type":"type","name":"IP","signature":"name:IP","since":"","deprecated":false},{"type":"type","name":"DataURI2","signature":"name:DataURI2","since":"","deprecated":false},{"type":"type","name":"SafeString","signature":"name:SafeString","since":"","deprecated":false},{"type":"type","name":"Search","signature":"name:Search","since":"","deprecated":false},{"type":"type","name":"Enum","signature":"name:{a|b|c}  or  { type: 'string', enum: [...] }","since":"","deprecated":false},{"type":"type","name":"Array","signature":"name:[Type]","since":"","deprecated":false},{"type":"type","name":"Object","signature":"name:{field:Type,...}","since":"","deprecated":false},{"type":"type","name":"@name","signature":"name:@Schema  name:[@Schema]","since":"","deprecated":false},{"type":"property","name":"required","signature":"required: ['field', ...]","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"{ type: 'string', subtype: 'email' }","since":"","deprecated":false},{"type":"property","name":"nullable","signature":"{ type: 'string', nullable: true }","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"{ type: 'string', minLength: 3, maxLength: 50 }","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"{ type: 'number', minimum: 1, maximum: 100 }","since":"","deprecated":false},{"type":"property","name":"items","signature":"{ type: 'array', items: { type: 'string' } }","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"{ type: 'object', $ref: '#/definitions/Name' }","since":"","deprecated":false},{"type":"class","name":"ErrorBuilder","signature":"new ErrorBuilder()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push()","signature":"err.push(error, [path], [index])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.push2()","signature":"err.push2(name, [path], [index], [error])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.output()","signature":"err.output([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.toString()","signature":"err.toString([language], [divider])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.reject()","signature":"err.reject([language])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.throw()","signature":"err.throw()","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.replace()","signature":"err.replace(search, value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.assign()","signature":"ErrorBuilder.assign(value)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.transform()","signature":"ErrorBuilder.transform(callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"Jafwth3Dx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/views/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Views","summary":"The view commands, the view object, helpers and TEMPLATE().","markdown":"---\ntitle: Views\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/views/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Views\n\n> The view commands, the view object, helpers and TEMPLATE().\n\nViews are HTML files in `/views/` with `@{...}` commands, rendered by `controller.view()` and `F.view()`. This page lists every command, the methods of the view object, the helpers and `TEMPLATE()`. The guide [Views](../../guides/views/) explains how they work together, with examples.\n\n## API\n\n### controller.view([name], [model])\n\nType: `method`\n\nRenders a view and sends it as the HTML response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The name of the view without `.html`, for example `products/detail`. |\n| `model` | `Object` | no |  | The model, available as `model` in the view. |\n\nReturns: `View` The view object.\n\nThe view is read from `/views/{name}.html`, or from `/plugins/` when the name starts with `#`. It is rendered into the layout that was set with `controller.layout()` (or `layout` by default) and sent with `controller.html()`. Without a name the method only returns a new view object, which you render yourself.\n\nExample: Render a view\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail($) {\n\tvar id = $.params.id;\n\t$.view('products/detail', { id: id });\n}\n```\n\nExample: Render it yourself\n```js\nfunction preview($) {\n\tvar view = $.view();\n\tview.layout('');\n\t$.html(view.render('preview', { name: 'Test' }));\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nSets the layout for the next `controller.view()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the layout view. |\n\nCall it before `controller.view()`. An empty string keeps the default layout; for a view without a layout use `@{layout('')}` in the view or `view.layout('')`. A view can still change it with `@{layout()}`.\n\nExample: Use another layout\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('admin/index');\n}\n```\n\n### F.view(name, [model], [prepare])\n\nType: `method`\n\nRenders a view outside of 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| `prepare` | `Function` | no |  | `function(view)` called before the rendering, to set `view.language`, `view.repository` or the layout. |\n\nReturns: `String` The rendered HTML.\n\nThe view has no controller, so `controller`, `user`, `query` and the other request values are empty. The view is rendered into its layout as usual; use `@{layout('')}` in the view, or `view.layout('')` in `prepare`, for a fragment without a layout.\n\nExample: Render an e-mail body\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n\tview.layout('');\n});\n```\n\n### new F.TViewEngine.View([controller])\n\nType: `class`\n\nThe object that renders a view; it is `self` inside the compiled view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | no |  | The controller of the request. |\n\n`controller.view()` and `F.view()` create it for you. Its properties are `controller`, `model`, `repository` (`{ layout: 'layout' }` at the start), `language`, `url` and `query`. Its methods are the view commands: `layout()`, `title()`, `description()`, `keywords()`, `meta()`, `json()`, `href()`, `import()`, `section()`, `helper()`, `hostname()` and `view()`.\n\nExample: Set values before rendering\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.repository.menu = 'products';\n\t$.html(view.render('products', { items: [] }));\n}\n```\n\n### view.render(name, [model])\n\nType: `method`\n\nRenders a view with its layout 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\nReturns: `String` The HTML.\n\nThe file is `/views/{name}.html` (or `/plugins/{name}.html` for a name with `#`). When `repository.layout` is not empty, the result is rendered into that layout.\n\nExample: Render\n```js\nvar view = new F.TViewEngine.View();\nview.layout('');\nvar html = view.render('fragments/card', { name: 'Pen' });\n```\n\n### view.repository\n\nType: `property`\n\nAn object shared by the view, its partial views and the layout.\n\nReturns: `Object`\n\nIt holds `layout`, `title`, `description`, `keywords`, the sections (`section_{name}`) and any values you add. In the view it is the variable `repository`. Use it to pass values from a view to its layout.\n\nExample: View to layout\n```html\n<!-- view -->\n@{repository.menu = 'products'}\n\n<!-- layout -->\n<nav class=\"@{repository.menu}\">...</nav>\n```\n\n### view.language\n\nType: `property`\n\nThe language used for `@(...)` translations.\n\nReturns: `String`\n\nIt is the language of the request in `controller.view()` and an empty string in `F.view()`. Set it before rendering; each language has its own compiled copy of the view, and `@{language}` prints it.\n\nExample: Language in F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{expression}\n\nType: `command`\n\nPrints the value of a JavaScript expression, HTML-encoded.\n\nAny expression works: properties, method calls, operators. `null` and `undefined` print as an empty string. An assignment (`=`, `+=`, `++`…) to `model`, `repository`, `config`, `query`, `user`, `session` or `controller` is evaluated and prints nothing. `@{print(...)}` and `@{console.log(...)}` print nothing in the HTML.\n\nExample: Values\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} items</p>\n<p>@{model.price.format(2)}</p>\n@{repository.count = model.items.length}\n```\n\n### @{!expression}\n\nType: `command`\n\nPrints the value of an expression without HTML encoding.\n\nUse it for HTML you trust, for example content of a CMS stored by your administrators.\n\nExample: Raw HTML\n```html\n<article>@{!model.body}</article>\n```\n\n### @{model}\n\nType: `command`\n\nThe model passed to the view.\n\nIt is the second argument of `controller.view()`, `F.view()`, `view.render()` or `@{view()}`. The layout does not receive the model.\n\nExample: Read the model\n```html\n<h1>@{model.title}</h1>\n@{if model.user}<p>@{model.user.name}</p>@{fi}\n```\n\n### @{repository}\n\nType: `command`\n\nThe shared object of the view, its partial views and the layout.\n\nSee `view.repository`. Assign values with `@{repository.key = value}`; the assignment prints nothing.\n\nExample: Set and read\n```html\n@{repository.menu = 'contact'}\n<li class=\"@{repository.menu === 'contact' ? 'active' : ''}\">Contact</li>\n```\n\n### @{config.key} / @{'%key'}\n\nType: `command`\n\nPrints a configuration value.\n\n`config` is `CONF`, read on every render. `@{'%key'}` reads the value once, when the view is compiled, and puts it into the view as text.\n\nExample: Configuration\n```html\n<title>@{config.name}</title>\n<footer>@{'%name'} @{config.version}</footer>\n```\n\n### @{query} / @{body} / @{files} / @{user} / @{session} / @{controller}\n\nType: `command`\n\nThe data of the current request.\n\n`query` is the parsed query string, `body` the parsed body, `files` the uploaded files, `user` and `session` the values of your authorization, and `controller` the controller itself. In `F.view()` they are empty. In a layout, `@{body}` without a property prints the HTML of the view instead.\n\nExample: Request values\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{else}\n\t<a href=\"/login/\">Sign in</a>\n@{fi}\n<input name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{body}\n\nType: `command`\n\nIn a layout, prints the HTML of the rendered view.\n\nThe output is not encoded. With a property (`@{body.name}`) it reads the body of the request instead.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>@{import('meta')}</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{language}\n\nType: `command`\n\nThe language of the view.\n\nThe language of the view (`view.language`): the language of the request (`controller.language`) in `controller.view()`, the value you set in the `prepare` function of `F.view()`, and an empty string by default.\n\nExample: Language attribute\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\nExample: In F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n// <html lang=\"de\">\n```\n\n### @{url}\n\nType: `command`\n\nThe URL path of the current request.\n\nIt is `controller.url`, the path as requested (the letter case is kept) with a trailing slash and without the query string. `url` also works inside expressions and conditions: `@{if url === '/'}`. In `F.view()` there is no request: `@{url}` prints an empty string and `url` in an expression is `undefined`.\n\nExample: Active link\n```html\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n### @{hostname([path])}\n\nType: `command`\n\nPrints the absolute URL of the current page or of another path.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | A path that starts with `/`. Without it, the path of the current request. |\n\nReturns: `String` The absolute URL.\n\n`@{hostname()}` prints the protocol, the host and the path of the current request, without the query string (`https://shop.example.com/products/`). `@{hostname('/img/share.png')}` prints the protocol and the host with the given path. It calls `controller.hostname()`, see [Controller](../controller/). Write the parentheses: `@{hostname}` alone does not call the function.\n\nIn `F.view()` there is no request, so it prints only `path` (or an empty string).\n\nExample: Canonical link and share image\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<meta property=\"og:image\" content=\"@{hostname('/img/share.png')}\" />\n```\n\n### @{cookie(name)}\n\nType: `command`\n\nPrints the value of a cookie of the request, HTML-encoded.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the cookie. |\n\nWithout a controller it prints an empty string.\n\nExample: Read a cookie\n```html\n<body class=\"theme-@{cookie('theme')}\">\n```\n\n### @{now}\n\nType: `command`\n\nA new `Date` with the current time.\n\nUse properties and methods of the date directly: `@{now.getFullYear()}`.\n\nExample: Copyright\n```html\n<footer>&copy; @{now.getFullYear()} @{config.name}</footer>\n```\n\n### @{root}\n\nType: `command`\n\nPrints `CONF.$root` without its trailing slash.\n\nUse it for links when the application runs under a sub-path. It prints an empty string when `CONF.$root` is not set.\n\nExample: Link under a sub-path\n```html\n<a href=\"@{root}/products/\">Products</a>\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\nThe condition is any JavaScript expression. `@{endif}` is the same as `@{fi}`. `@{if(condition)}` with parentheses works as well.\n\nExample: Condition\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRepeats a part of the view for every item of an array or an object.\n\nFor an object, each item is `{ key, value }`. An empty source renders nothing. `@{foreach var item in source}` works as well. Inside the loop, `@{index}` is the zero-based position, and `@{continue}` and `@{break}` skip an item or stop the loop. Loops can be nested.\n\nExample: Array\n```html\n<ul>\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n</ul>\n```\n\nExample: Object\n```html\n@{foreach prop in model.settings}\n\t<dt>@{prop.key}</dt><dd>@{prop.value}</dd>\n@{end}\n```\n\n### @{index}\n\nType: `command`\n\nThe zero-based position of the current item in `@{foreach}`.\n\nExample: Numbered rows\n```html\n@{foreach row in model.rows}\n\t<tr class=\"@{index % 2 ? 'odd' : 'even'}\"><td>@{index + 1}</td><td>@{row.name}</td></tr>\n@{end}\n```\n\n### @{layout(name)}\n\nType: `command`\n\nSets the layout of the view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the layout view, or an empty string. |\n\nThe default layout is `layout` (`/views/layout.html`). An empty string renders the view without a layout. The command prints nothing.\n\nExample: Another layout\n```html\n@{layout('layout-print')}\n<h1>@{model.title}</h1>\n```\n\nExample: No layout\n```html\n@{layout('')}\n<div class=\"card\">@{model.name}</div>\n```\n\n### @{view(name, [model])}\n\nType: `command`\n\nRenders another view in place (a partial view).\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\nThe partial view gets its own model and no layout. It shares `repository` and the sections with the view that renders it. A name that starts with `#` reads the file from `/plugins/`.\n\nExample: Partial views\n```html\n@{foreach item in model.items}\n\t@{view('partials/card', item)}\n@{end}\n@{view('#blog/sidebar')}\n```\n\n### @{section name} ... @{end} / @{section(name)}\n\nType: `command`\n\nCollects HTML in a view and prints it in another place, usually the layout.\n\n`@{section name}` … `@{end}` adds its HTML to the section; several blocks with the same name are joined. `@{section('name')}` prints the section, or nothing when it is empty. The section must be filled before it is printed, which is the case for a layout.\n\nExample: Scripts for the layout\n```html\n<!-- view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- layout, before </body> -->\n@{section('scripts')}\n```\n\n### view.section(name, [value], [replace])\n\nType: `method`\n\nReads or fills a section from JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the section. |\n| `value` | `String` | no |  | The HTML to add. |\n| `replace` | `Boolean` | no | `false` | Replace the current content. |\n\nReturns: `String|View` The section when reading; the view when writing.\n\nWithout `value` it returns the HTML of the section. With `value` it appends the HTML to the section, or replaces it when `replace` is `true`.\n\nExample: Fill a section\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.section('scripts', '<script src=\"/js/page.js\"></script>');\n\t$.html(view.render('page'));\n}\n```\n\n### @{title(value)} / @{title}\n\nType: `command`\n\nSets or prints the title of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The title. |\n\n`@{title('Text')}` stores the text in `repository.title` and prints nothing. `@{title}` prints it HTML-encoded, `@{!title}` without encoding.\n\nExample: Title\n```html\n@{title('Products / ' + model.category)}\n<h1>@{title}</h1>\n```\n\n### @{title2(value)}\n\nType: `command`\n\nAppends text to the title of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The text to append. |\n\nAdds `value` to the end of `repository.title` (or sets it when there is no title yet) and prints nothing. Like `title()`, the text is stored as it is and encoded once when it is printed. An empty value changes nothing.\n\nExample: Title in two steps\n```html\n@{title('Products')}\n@{if model}@{title2(' / ' + model.name)}@{fi}\n<h1>@{title}</h1>  <!-- Products / Pen &amp; paper -->\n```\n\n### @{description(value)} / @{description}\n\nType: `command`\n\nSets or prints the description of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The description. |\n\nThe value goes to `repository.description`; `@{import('meta')}` prints it as a `<meta name=\"description\">` tag.\n\nExample: Description\n```html\n@{description('Pens, pencils and paper for the office.')}\n```\n\n### @{keywords(value)} / @{keywords}\n\nType: `command`\n\nSets or prints the keywords of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | The keywords. |\n\nAn array is joined with `, `. The value goes to `repository.keywords`.\n\nExample: Keywords\n```html\n@{keywords(['pens', 'paper', 'office'])}\n```\n\n### @{meta([title], [description], [keywords], [image])} / @{meta}\n\nType: `command`\n\nSets the title, description, keywords and image at once, or prints the meta tags.\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 |  | The keywords. |\n| `image` | `String` | no |  | An absolute URL or a path of an image. |\n\nWith arguments it stores the values in `repository` as they are and prints nothing; they are HTML-encoded once, when the tags are printed. Without arguments it prints the same tags as `@{import('meta')}`: `<title>`, the description and keywords tags, and `og:image` and `twitter:image` for the image. A relative image gets the host name of the request; without a request no image tags are printed. The title gets ` - ` and `CONF.name` appended, except on the URL `/` and when `CONF.$customtitles` is `true`; without a title it is `CONF.name`.\n\nExample: Set and print\n```html\n<!-- view -->\n@{meta(model.name, model.summary, model.tags, model.photo)}\n\n<!-- layout -->\n<head>@{meta}</head>\n```\n\n### CONF.$customtitles\n\nType: `config`\n\nPrints the page title without the application name.\n\nReturns: `Boolean` Default `false`.\n\nBy default the title tag of `@{meta}` and `@{import('meta')}` is `Title - CONF.name`. With `true` the title is printed as you set it.\n\nExample: /config\n```text\n$customtitles : true\n```\n\n### @{import(name, [name2], ...)}\n\nType: `command`\n\nPrints the tags for static files, the meta tags or a favicon.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A file name, `meta` or a favicon name. |\n\nEach argument gives one tag:\n\n- `meta` prints the meta tags (see `@{meta}`).\n- `favicon.ico`, `favicon.png` or `favicon.gif` prints a `<link rel=\"icon\">` tag.\n- A name with `.css` prints a stylesheet link from `/css/`, other names a script from `/js/`. A path that starts with `/` (or a virtual route) is used as it is.\n- An `@` before the name appends `?ts=` with the start time of the application.\n- Names joined with `+` are merged into one minified file (see the next entry).\n\nThe tags are cached, so the command is cheap.\n\nExample: Head of a layout\n```html\n<head>\n\t@{import('meta', 'favicon.ico', '@default.css', 'ui.js', '/vendor/editor.js')}\n</head>\n```\n\n### @{import('a.css + b.css')}\n\nType: `command`\n\nMerges several CSS or JavaScript files into one minified file.\n\nThe names joined with `+` are merged with `MERGE()` into a file with a generated name, such as `/xkcqdmatno-min.css`, which the framework serves. A name with `.css` makes a stylesheet, otherwise a script. A file name is looked up in `/public/css/` or `/public/js/` by its extension, a path that starts with `/` in `/public/`, and a URL is downloaded. An `@` at the start appends `?ts=`.\n\nExample: One CSS and one JS file\n```html\n@{import('reset.css + layout.css + forms.css', '@ui.js + app.js')}\n<!-- <link rel=\"stylesheet\" href=\"/wqxjrnefjv-min.css\" /> -->\n<!-- <script src=\"/wbxyamtxmw-min.js?ts=mwi48bh6\"></script> -->\n```\n\n### @{json(value, [id], [beautify], [replacer])}\n\nType: `command`\n\nPrints a value as JSON, or in a `<script type=\"application/json\">` tag.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value. |\n| `id` | `String` | no |  | The id of the script tag. |\n| `beautify` | `Boolean` | no | `false` | Indent the JSON. |\n| `replacer` | `Function|Boolean` | no |  | A replacer for `JSON.stringify()`. |\n\nWith `id` the JSON is wrapped in a script tag with that `id`, which client code reads without a second request. `beautify` indents the JSON with four spaces. `replacer` is a function for `JSON.stringify()`, or `true` for the framework replacer. `@{json(value, true)}` is the same as `@{json(value, null, true)}`.\n\nExample: Data for the client\n```html\n@{json(model.products, 'products')}\n<script>\n\tvar products = JSON.parse(document.getElementById('products').innerHTML);\n</script>\n```\n\n### @{href([key], [value])}\n\nType: `command`\n\nPrints the current query string with one parameter changed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | The name of the parameter, or an object with the parameters to set. |\n| `value` | `Any` | no |  | The new value. |\n\nReturns: `String` The query string with `?`, or an empty string.\n\n`@{href}` prints the current query string (`?page=2&sort=name`). `@{href('page', 3)}` prints it with `page` set to `3`; without a value the current value is kept. More arguments after the value are names of parameters to remove. An array value writes the parameter once for each item (`tag=a&tag=b`) and an object value is written as JSON. `@{href({ page: 3, sort: 'price' })}` returns the URL of the request with the query string changed by the keys of the object. Use it for paging and sorting links.\n\nExample: Paging\n```html\n<a href=\"@{href('page', model.page - 1)}\">Previous</a>\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\nExample: Remove a parameter, or change several\n```html\n<!-- /products/?page=2&sort=name&q=pen -->\n<a href=\"@{href('page', 1, 'sort')}\">First page</a>  <!-- ?page=1&q=pen -->\n<a href=\"@{href({ page: 1, sort: 'price' })}\">By price</a>  <!-- /products/?page=1&sort=price&q=pen -->\n```\n\n### DEF.helpers\n\nType: `property`\n\nCustom functions you call from every view.\n\nReturns: `Object`\n\nAdd functions to the object; inside a helper `this` is the view (`this.model`, `this.repository`, `this.controller`). Call a helper by its name (`@{price(10)}`), with `@{helpers.price(10)}` or with `@{helper('price', 10)}`. The returned value is printed without encoding. Register the helpers before the views are compiled, for example in `/definitions/`.\n\nExample: Register and use\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\n// in a view: <span>@{price(model.price, 'USD')}</span>\n```\n\n### @{helper(name, [arg1], [arg2], ...)}\n\nType: `command`\n\nCalls a helper from `DEF.helpers` by its name.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the helper. |\n\nThe other arguments go to the helper. It prints an empty string when the helper does not exist.\n\nExample: Call a helper\n```html\n<span>@{helper('price', model.price, 'EUR')}</span>\n```\n\n### @(text)\n\nType: `command`\n\nTranslates a text into the language of the view.\n\nThe text is replaced by its translation from the resource files when the view is compiled; a text without a translation stays as it is. The [Localization](../../guides/localization/) guide explains the resources.\n\nExample: Translated text\n```html\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n### @{compile [name]} ... @{end}\n\nType: `command`\n\nPasses a part of the view to `DEF.onViewCompile` on every render.\n\nThe HTML between the tags, with the commands already evaluated, is passed to `DEF.onViewCompile(name, html, model)`, and its result is printed. Use it to run Markdown or another processor on a part of the view.\n\nExample: Markdown\n```html\n@{compile markdown}\n# @{model.title}\n\n@{model.text}\n@{end}\n```\n\n### DEF.onViewCompile = function(name, html, model)\n\nType: `delegate`\n\nProcesses the content of `@{compile}` blocks.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the block, or an empty string. |\n| `html` | `String` | yes |  | The content of the block. |\n| `model` | `Object` | yes |  | The model of the view. |\n\nReturns: `String` The HTML to print.\n\n`name` is the word after `@{compile`, `html` the rendered content of the block and `model` the model of the view. Return the HTML to print. By default it returns `html` unchanged.\n\nExample: Markdown blocks\n```js\nDEF.onViewCompile = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\n### ON('$view', function(meta) {})\n\nType: `event`\n\nChanges the source of a view before it is compiled.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, body, debug }`. |\n\n`meta.name` is the name of the view, `meta.body` its HTML source and `meta.debug` the debug mode. Change `meta.body` to change the view; the event runs every time a view is compiled.\n\nExample: Replace a placeholder\n```js\nON('$view', function(meta) {\n\tmeta.body = meta.body.replace(/\\{year\\}/g, new Date().getFullYear() + '');\n});\n```\n\n### @{nocompress html|js|css|all}\n\nType: `command`\n\nTurns off a compression step for the view.\n\nWhen a view is compiled, runs of spaces inside its text are collapsed (line breaks and indentation between tags are kept), and the CSS of `<style>` tags and the JavaScript of `<script>` tags are minified. `html` keeps the HTML as it is and also turns off the minification of the response; `js` (or `script`, `javascript`) and `css` (or `style`) keep the inline code; `all` turns off all three. HTML comments are always removed.\n\nExample: Keep whitespace\n```html\n@{nocompress html}\n<pre>\n  formatted\n    text\n</pre>\n```\n\n### @{{ text }}\n\nType: `command`\n\nPrints `@{{ ... }}` as it is, without running it.\n\nUse it to keep `@{{ }}` text for client-side templates.\n\nExample: Literal text\n```html\n<code>@{{ value }}</code>\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nRenders a Tangular template and returns a promise with the HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | The template, a URL, a path or a name of a file in `/templates/`. |\n| `model` | `Object` | no |  | The model, available as `value`. |\n| `$` | `Options` | no |  | The `$` of an action or a controller, for the language and error handling. |\n\nReturns: `Promise<String>` The rendered HTML.\n\n`body` is the template text when it contains `{{`. Otherwise it is a URL (`http://` or `https://`, downloaded), `~` and an absolute path, `#` and a path of a file in `/plugins/` (`.html` is added when missing), or a name of a file in `/templates/` (`.html` is added when missing). In the template the model is `value`.\n\nThe template can contain a `<script type=\"text/json\">` block with a default model, used when `model` is not given, and a `<script>` block that adds helpers to `Thelpers`. With `$` (the `$` of a route or an action) the template is translated into `$.language`, and errors go to `$.invalid()` instead of rejecting the promise. Templates read from files are cached in release mode.\n\nExample: Inline template\n```js\nvar html = await TEMPLATE('<p>Hello {{ value.name }}</p>', { name: 'Peter' });\n```\n\nExample: A file in a route\n```js\nexports.install = function() {\n\tROUTE('GET /invoice/{id}/', invoice);\n};\n\nfunction invoice($) {\n\tTEMPLATE('invoice', { number: $.params.id }, $).then(function(html) {\n\t\t$.html(html);\n\t});\n}\n```\n\n### {{ value }} / {{ if }} / {{ foreach }}\n\nType: `command`\n\nThe commands of Tangular templates used by `TEMPLATE()`.\n\n`{{ value.name }}` prints an HTML-encoded value. `{{ if condition }}` … `{{ else if condition }}` … `{{ else }}` … `{{ fi }}` is a condition. `{{ foreach item in value.items }}` … `{{ end }}` is a loop with `{{ $index }}`, `{{ continue }}` and `{{ break }}`. A value goes through helpers with `|`: `{{ value.html | raw }}`.\n\nExample: Invoice\n```html\n<h1>Invoice {{ value.number }}</h1>\n{{ if value.items.length }}\n<table>\n\t{{ foreach item in value.items }}\n\t<tr><td>{{ $index + 1 }}</td><td>{{ item.name }}</td><td>{{ item.price | format(2) }}</td></tr>\n\t{{ end }}\n</table>\n{{ else }}\n<p>No items</p>\n{{ fi }}\n```\n\n### Thelpers\n\nType: `property`\n\nThe helpers of Tangular templates.\n\nReturns: `Object`\n\nBuilt-in helpers: `encode` (the default for every value; `encode('json')`, `encode('url')` change the format), `raw` (no encoding), `format(...)` (numbers and dates, like `Number.format()` and `Date.format()`), `def(text)` or `empty(text)` (prints `text`, or `---`, for an empty value) and `pluralize(zero, one, few, other)`. Add your own in `Thelpers`, globally or in the `<script>` block of a template file; `this` is the object that holds the model in `value`.\n\nExample: A template file with a helper and a default model\n```html\n<script type=\"text/json\">{ \"name\": \"Guest\" }</script>\n<script>\nThelpers.upper = function(value) {\n\treturn (value || '').toUpperCase();\n};\n</script>\n<h1>{{ value.name | upper }}</h1>\n<p>{{ value.count | pluralize('# items', '# item', '# items', '# items') }}</p>\n<p>{{ value.date | format('yyyy-MM-dd') }} {{ value.note | def('none') }}</p>\n```\n","entries":[{"type":"method","name":"controller.view()","signature":"controller.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"F.view()","signature":"F.view(name, [model], [prepare])","since":"","deprecated":false},{"type":"class","name":"View","signature":"new F.TViewEngine.View([controller])","since":"","deprecated":false},{"type":"method","name":"view.render()","signature":"view.render(name, [model])","since":"","deprecated":false},{"type":"property","name":"view.repository","signature":"view.repository","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository}","since":"","deprecated":false},{"type":"command","name":"@{config}","signature":"@{config.key} / @{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{query}","signature":"@{query} / @{body} / @{files} / @{user} / @{session} / @{controller}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}","since":"","deprecated":false},{"type":"command","name":"@{hostname()}","signature":"@{hostname([path])}","since":"","deprecated":false},{"type":"command","name":"@{cookie()}","signature":"@{cookie(name)}","since":"","deprecated":false},{"type":"command","name":"@{now}","signature":"@{now}","since":"","deprecated":false},{"type":"command","name":"@{root}","signature":"@{root}","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":"@{index}","signature":"@{index}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end} / @{section(name)}","since":"","deprecated":false},{"type":"method","name":"view.section()","signature":"view.section(name, [value], [replace])","since":"","deprecated":false},{"type":"command","name":"@{title()}","signature":"@{title(value)} / @{title}","since":"","deprecated":false},{"type":"command","name":"@{title2()}","signature":"@{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} / @{description}","since":"","deprecated":false},{"type":"command","name":"@{keywords()}","signature":"@{keywords(value)} / @{keywords}","since":"","deprecated":false},{"type":"command","name":"@{meta()}","signature":"@{meta([title], [description], [keywords], [image])} / @{meta}","since":"","deprecated":false},{"type":"config","name":"CONF.$customtitles","signature":"CONF.$customtitles","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(name, [name2], ...)}","since":"","deprecated":false},{"type":"command","name":"Merging files","signature":"@{import('a.css + b.css')}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify], [replacer])}","since":"","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href([key], [value])}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers","since":"","deprecated":false},{"type":"command","name":"@{helper()}","signature":"@{helper(name, [arg1], [arg2], ...)}","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile [name]} ... @{end}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onViewCompile","signature":"DEF.onViewCompile = function(name, html, model)","since":"","deprecated":false},{"type":"event","name":"ON('$view')","signature":"ON('$view', function(meta) {})","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|js|css|all}","since":"","deprecated":false},{"type":"command","name":"@{{ }}","signature":"@{{ text }}","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"command","name":"Template commands","signature":"{{ value }} / {{ if }} / {{ foreach }}","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwth3Dx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/views/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Views","summary":"Die View-Befehle, das View-Objekt, Helper und TEMPLATE().","markdown":"---\ntitle: Views\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/views/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Views\n\n> Die View-Befehle, das View-Objekt, Helper und TEMPLATE().\n\nViews sind HTML-Dateien in `/views/` mit `@{...}`-Befehlen, gerendert von `controller.view()` und `F.view()`. Diese Seite listet jeden Befehl, die Methoden des View-Objekts, die Helper und `TEMPLATE()` auf. Die Anleitung [Views](../../guides/views/) erklärt mit Beispielen, wie sie zusammenspielen.\n\n## API\n\n### controller.view([name], [model])\n\nType: `method`\n\nRendert eine View und sendet sie als HTML-Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Der Name der View ohne `.html`, zum Beispiel `products/detail`. |\n| `model` | `Object` | no |  | Das Model, in der View als `model` verfügbar. |\n\nReturns: `View` Das View-Objekt.\n\nDie View wird aus `/views/{name}.html` gelesen, oder aus `/plugins/`, wenn der Name mit `#` beginnt. Sie wird in das Layout gerendert, das mit `controller.layout()` gesetzt wurde (standardmäßig `layout`), und mit `controller.html()` gesendet. Ohne Namen gibt die Methode nur ein neues View-Objekt zurück, das du selbst renderst.\n\nExample: Eine View rendern\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail($) {\n\tvar id = $.params.id;\n\t$.view('products/detail', { id: id });\n}\n```\n\nExample: Selbst rendern\n```js\nfunction preview($) {\n\tvar view = $.view();\n\tview.layout('');\n\t$.html(view.render('preview', { name: 'Test' }));\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nSetzt das Layout für das nächste `controller.view()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Layout-View. |\n\nRufe es vor `controller.view()` auf. Ein leerer String behält das Standardlayout bei; für eine View ohne Layout verwende `@{layout('')}` in der View oder `view.layout('')`. Eine View kann es trotzdem mit `@{layout()}` ändern.\n\nExample: Ein anderes Layout verwenden\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('admin/index');\n}\n```\n\n### F.view(name, [model], [prepare])\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| `prepare` | `Function` | no |  | `function(view)`, die vor dem Rendern aufgerufen wird, um `view.language`, `view.repository` oder das Layout zu setzen. |\n\nReturns: `String` Das gerenderte HTML.\n\nDie View hat keinen Controller, daher sind `controller`, `user`, `query` und die anderen Request-Werte leer. Die View wird wie gewohnt in ihr Layout gerendert; verwende `@{layout('')}` in der View oder `view.layout('')` in `prepare` für ein Fragment ohne Layout.\n\nExample: Den Body einer E-Mail rendern\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n\tview.layout('');\n});\n```\n\n### new F.TViewEngine.View([controller])\n\nType: `class`\n\nDas Objekt, das eine View rendert; in der kompilierten View ist es `self`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | no |  | Der Controller des Requests. |\n\n`controller.view()` und `F.view()` erstellen es für dich. Seine Eigenschaften sind `controller`, `model`, `repository` (zu Beginn `{ layout: 'layout' }`), `language`, `url` und `query`. Seine Methoden sind die View-Befehle: `layout()`, `title()`, `description()`, `keywords()`, `meta()`, `json()`, `href()`, `import()`, `section()`, `helper()`, `hostname()` und `view()`.\n\nExample: Werte vor dem Rendern setzen\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.repository.menu = 'products';\n\t$.html(view.render('products', { items: [] }));\n}\n```\n\n### view.render(name, [model])\n\nType: `method`\n\nRendert eine View mit ihrem Layout 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\nReturns: `String` Das HTML.\n\nDie Datei ist `/views/{name}.html` (oder `/plugins/{name}.html` für einen Namen mit `#`). Wenn `repository.layout` nicht leer ist, wird das Ergebnis in dieses Layout gerendert.\n\nExample: Rendern\n```js\nvar view = new F.TViewEngine.View();\nview.layout('');\nvar html = view.render('fragments/card', { name: 'Pen' });\n```\n\n### view.repository\n\nType: `property`\n\nEin Objekt, das sich die View, ihre Partial Views und das Layout teilen.\n\nReturns: `Object`\n\nEs enthält `layout`, `title`, `description`, `keywords`, die Abschnitte (`section_{name}`) und alle Werte, die du hinzufügst. In der View ist es die Variable `repository`. Verwende es, um Werte von einer View an ihr Layout zu übergeben.\n\nExample: Von der View zum Layout\n```html\n<!-- view -->\n@{repository.menu = 'products'}\n\n<!-- layout -->\n<nav class=\"@{repository.menu}\">...</nav>\n```\n\n### view.language\n\nType: `property`\n\nDie Sprache für `@(...)`-Übersetzungen.\n\nReturns: `String`\n\nSie ist die Sprache der Anfrage in `controller.view()` und ein leerer String in `F.view()`. Setze sie vor dem Rendern; jede Sprache hat ihre eigene kompilierte Kopie der View, und `@{language}` gibt sie aus.\n\nExample: Sprache in F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{expression}\n\nType: `command`\n\nGibt den Wert eines JavaScript-Ausdrucks HTML-kodiert aus.\n\nJeder Ausdruck funktioniert: Eigenschaften, Methodenaufrufe, Operatoren. `null` und `undefined` werden als leerer String ausgegeben. Eine Zuweisung (`=`, `+=`, `++`…) an `model`, `repository`, `config`, `query`, `user`, `session` oder `controller` wird ausgewertet und gibt nichts aus. `@{print(...)}` und `@{console.log(...)}` geben nichts im HTML aus.\n\nExample: Werte\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} items</p>\n<p>@{model.price.format(2)}</p>\n@{repository.count = model.items.length}\n```\n\n### @{!expression}\n\nType: `command`\n\nGibt den Wert eines Ausdrucks ohne HTML-Kodierung aus.\n\nVerwende es für HTML, dem du vertraust, zum Beispiel Inhalte eines CMS, die deine Administratoren gespeichert haben.\n\nExample: Rohes HTML\n```html\n<article>@{!model.body}</article>\n```\n\n### @{model}\n\nType: `command`\n\nDas an die View übergebene Model.\n\nEs ist das zweite Argument von `controller.view()`, `F.view()`, `view.render()` oder `@{view()}`. Das Layout erhält das Model nicht.\n\nExample: Das Model lesen\n```html\n<h1>@{model.title}</h1>\n@{if model.user}<p>@{model.user.name}</p>@{fi}\n```\n\n### @{repository}\n\nType: `command`\n\nDas gemeinsame Objekt der View, ihrer Teil-Views und des Layouts.\n\nSiehe `view.repository`. Weise Werte mit `@{repository.key = value}` zu; die Zuweisung gibt nichts aus.\n\nExample: Setzen und lesen\n```html\n@{repository.menu = 'contact'}\n<li class=\"@{repository.menu === 'contact' ? 'active' : ''}\">Contact</li>\n```\n\n### @{config.key} / @{'%key'}\n\nType: `command`\n\nGibt einen Konfigurationswert aus.\n\n`config` ist `CONF` und wird bei jedem Rendern gelesen. `@{'%key'}` liest den Wert einmal beim Kompilieren der View und fügt ihn als Text in die View ein.\n\nExample: Konfiguration\n```html\n<title>@{config.name}</title>\n<footer>@{'%name'} @{config.version}</footer>\n```\n\n### @{query} / @{body} / @{files} / @{user} / @{session} / @{controller}\n\nType: `command`\n\nDie Daten des aktuellen Requests.\n\n`query` ist der geparste Query-String, `body` der geparste Body, `files` die hochgeladenen Dateien, `user` und `session` die Werte deiner Autorisierung und `controller` der Controller selbst. In `F.view()` sind sie leer. In einem Layout gibt `@{body}` ohne Eigenschaft stattdessen das HTML der View aus.\n\nExample: Request-Werte\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{else}\n\t<a href=\"/login/\">Sign in</a>\n@{fi}\n<input name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{body}\n\nType: `command`\n\nGibt in einem Layout das HTML der gerenderten View aus.\n\nDie Ausgabe wird nicht kodiert. Mit einer Eigenschaft (`@{body.name}`) liest es stattdessen den Body des Requests.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>@{import('meta')}</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{language}\n\nType: `command`\n\nDie Sprache der View.\n\nDie Sprache der View (`view.language`): die Sprache der Anfrage (`controller.language`) in `controller.view()`, der Wert, den du in der Funktion `prepare` von `F.view()` setzt, und standardmäßig ein leerer String.\n\nExample: Sprachattribut\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\nExample: In F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n// <html lang=\"de\">\n```\n\n### @{url}\n\nType: `command`\n\nDer URL-Pfad des aktuellen Requests.\n\nEs ist `controller.url`, der Pfad wie angefordert (die Groß- und Kleinschreibung bleibt erhalten) mit einem abschließenden Schrägstrich und ohne Query String. `url` funktioniert auch in Ausdrücken und Bedingungen: `@{if url === '/'}`. In `F.view()` gibt es keine Anfrage: `@{url}` gibt einen leeren String aus, und `url` ist in einem Ausdruck `undefined`.\n\nExample: Aktiver Link\n```html\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n### @{hostname([path])}\n\nType: `command`\n\nGibt die absolute URL der aktuellen Seite oder eines anderen Pfads aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ein Pfad, der mit `/` beginnt. Ohne ihn der Pfad der aktuellen Anfrage. |\n\nReturns: `String` Die absolute URL.\n\n`@{hostname()}` gibt das Protokoll, den Host und den Pfad der aktuellen Anfrage aus, ohne Query String (`https://shop.example.com/products/`). `@{hostname('/img/share.png')}` gibt das Protokoll und den Host mit dem angegebenen Pfad aus. Es ruft `controller.hostname()` auf, siehe [Controller](../controller/). Schreib die Klammern: `@{hostname}` allein ruft die Funktion nicht auf.\n\nIn `F.view()` gibt es keine Anfrage, daher gibt es nur `path` aus (oder einen leeren String).\n\nExample: Kanonischer Link und Bild zum Teilen\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<meta property=\"og:image\" content=\"@{hostname('/img/share.png')}\" />\n```\n\n### @{cookie(name)}\n\nType: `command`\n\nGibt den Wert eines Cookies des Requests HTML-kodiert aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Cookies. |\n\nOhne Controller gibt es einen leeren String aus.\n\nExample: Ein Cookie lesen\n```html\n<body class=\"theme-@{cookie('theme')}\">\n```\n\n### @{now}\n\nType: `command`\n\nEin neues `Date` mit der aktuellen Zeit.\n\nVerwende Eigenschaften und Methoden des Datums direkt: `@{now.getFullYear()}`.\n\nExample: Copyright\n```html\n<footer>&copy; @{now.getFullYear()} @{config.name}</footer>\n```\n\n### @{root}\n\nType: `command`\n\nGibt `CONF.$root` ohne abschließenden Schrägstrich aus.\n\nVerwende es für Links, wenn die Anwendung unter einem Unterpfad läuft. Es gibt einen leeren String aus, wenn `CONF.$root` nicht gesetzt ist.\n\nExample: Link unter einem Unterpfad\n```html\n<a href=\"@{root}/products/\">Products</a>\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\nDie Bedingung ist ein beliebiger JavaScript-Ausdruck. `@{endif}` ist dasselbe wie `@{fi}`. `@{if(condition)}` mit Klammern funktioniert ebenfalls.\n\nExample: Bedingung\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nWiederholt einen Teil der View für jedes Element eines Arrays oder eines Objekts.\n\nBei einem Objekt ist jedes Element `{ key, value }`. Eine leere Quelle rendert nichts. `@{foreach var item in source}` funktioniert ebenfalls. Innerhalb der Schleife ist `@{index}` die nullbasierte Position, und `@{continue}` und `@{break}` überspringen ein Element oder beenden die Schleife. Schleifen können verschachtelt werden.\n\nExample: Array\n```html\n<ul>\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n</ul>\n```\n\nExample: Objekt\n```html\n@{foreach prop in model.settings}\n\t<dt>@{prop.key}</dt><dd>@{prop.value}</dd>\n@{end}\n```\n\n### @{index}\n\nType: `command`\n\nDie nullbasierte Position des aktuellen Elements in `@{foreach}`.\n\nExample: Nummerierte Zeilen\n```html\n@{foreach row in model.rows}\n\t<tr class=\"@{index % 2 ? 'odd' : 'even'}\"><td>@{index + 1}</td><td>@{row.name}</td></tr>\n@{end}\n```\n\n### @{layout(name)}\n\nType: `command`\n\nSetzt das Layout der View.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Layout-View oder ein leerer String. |\n\nDas Standard-Layout ist `layout` (`/views/layout.html`). Ein leerer String rendert die View ohne Layout. Der Befehl gibt nichts aus.\n\nExample: Ein anderes Layout\n```html\n@{layout('layout-print')}\n<h1>@{model.title}</h1>\n```\n\nExample: Kein Layout\n```html\n@{layout('')}\n<div class=\"card\">@{model.name}</div>\n```\n\n### @{view(name, [model])}\n\nType: `command`\n\nRendert an Ort und Stelle eine andere View (eine Teil-View).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der View. |\n| `model` | `Object` | no |  | Das Model der Teil-View. |\n\nDie Teil-View erhält ihr eigenes Model und kein Layout. Sie teilt sich `repository` und die Abschnitte mit der View, die sie rendert. Ein Name, der mit `#` beginnt, liest die Datei aus `/plugins/`.\n\nExample: Teil-Views\n```html\n@{foreach item in model.items}\n\t@{view('partials/card', item)}\n@{end}\n@{view('#blog/sidebar')}\n```\n\n### @{section name} ... @{end} / @{section(name)}\n\nType: `command`\n\nSammelt HTML in einer View und gibt es an anderer Stelle aus, meist im Layout.\n\n`@{section name}` … `@{end}` fügt sein HTML dem Abschnitt hinzu; mehrere Blöcke mit demselben Namen werden verbunden. `@{section('name')}` gibt den Abschnitt aus, oder nichts, wenn er leer ist. Der Abschnitt muss gefüllt sein, bevor er ausgegeben wird, was bei einem Layout der Fall ist.\n\nExample: Skripte für das Layout\n```html\n<!-- view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- layout, before </body> -->\n@{section('scripts')}\n```\n\n### view.section(name, [value], [replace])\n\nType: `method`\n\nLiest oder füllt einen Abschnitt aus JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Abschnitts. |\n| `value` | `String` | no |  | Das hinzuzufügende HTML. |\n| `replace` | `Boolean` | no | `false` | Den aktuellen Inhalt ersetzen. |\n\nReturns: `String|View` Der Abschnitt beim Lesen; die View beim Schreiben.\n\nOhne `value` gibt sie das HTML des Abschnitts zurück. Mit `value` hängt sie das HTML an den Abschnitt an oder ersetzt ihn, wenn `replace` gleich `true` ist.\n\nExample: Einen Abschnitt füllen\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.section('scripts', '<script src=\"/js/page.js\"></script>');\n\t$.html(view.render('page'));\n}\n```\n\n### @{title(value)} / @{title}\n\nType: `command`\n\nSetzt oder gibt den Titel der Seite aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der Titel. |\n\n`@{title('Text')}` speichert den Text in `repository.title` und gibt nichts aus. `@{title}` gibt ihn HTML-codiert aus, `@{!title}` ohne Codierung.\n\nExample: Titel\n```html\n@{title('Products / ' + model.category)}\n<h1>@{title}</h1>\n```\n\n### @{title2(value)}\n\nType: `command`\n\nHängt Text an den Titel der Seite an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der anzuhängende Text. |\n\nFügt `value` am Ende von `repository.title` hinzu (oder setzt ihn, wenn es noch keinen Titel gibt) und gibt nichts aus. Wie bei `title()` wird der Text so gespeichert, wie er ist, und einmal kodiert, wenn er ausgegeben wird. Ein leerer Wert ändert nichts.\n\nExample: Titel in zwei Schritten\n```html\n@{title('Products')}\n@{if model}@{title2(' / ' + model.name)}@{fi}\n<h1>@{title}</h1>  <!-- Products / Pen &amp; paper -->\n```\n\n### @{description(value)} / @{description}\n\nType: `command`\n\nSetzt oder gibt die Beschreibung der Seite aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Die Beschreibung. |\n\nDer Wert geht in `repository.description`; `@{import('meta')}` gibt ihn als `<meta name=\"description\">`-Tag aus.\n\nExample: Beschreibung\n```html\n@{description('Pens, pencils and paper for the office.')}\n```\n\n### @{keywords(value)} / @{keywords}\n\nType: `command`\n\nSetzt oder gibt die Keywords der Seite aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Die Schlüsselwörter. |\n\nEin Array wird mit `, ` verbunden. Der Wert geht in `repository.keywords`.\n\nExample: Keywords\n```html\n@{keywords(['pens', 'paper', 'office'])}\n```\n\n### @{meta([title], [description], [keywords], [image])} / @{meta}\n\nType: `command`\n\nSetzt Titel, Beschreibung, Keywords und Bild auf einmal oder gibt die Meta-Tags aus.\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 |  | Die Keywords. |\n| `image` | `String` | no |  | Eine absolute URL oder ein Pfad eines Bildes. |\n\nMit Argumenten speichert es die Werte so, wie sie sind, in `repository` und gibt nichts aus; sie werden einmal HTML-kodiert, wenn die Tags ausgegeben werden. Ohne Argumente gibt es dieselben Tags aus wie `@{import('meta')}`: `<title>`, die Tags für Beschreibung und Keywords sowie `og:image` und `twitter:image` für das Bild. Ein relatives Bild erhält den Hostnamen der Anfrage; ohne Anfrage werden keine Bild-Tags ausgegeben. An den Titel werden ` - ` und `CONF.name` angehängt, außer bei der URL `/` und wenn `CONF.$customtitles` `true` ist; ohne Titel ist er `CONF.name`.\n\nExample: Setzen und ausgeben\n```html\n<!-- view -->\n@{meta(model.name, model.summary, model.tags, model.photo)}\n\n<!-- layout -->\n<head>@{meta}</head>\n```\n\n### CONF.$customtitles\n\nType: `config`\n\nGibt den Seitentitel ohne den Namen der Anwendung aus.\n\nReturns: `Boolean` Standard `false`.\n\nStandardmäßig ist das Title-Tag von `@{meta}` und `@{import('meta')}` gleich `Title - CONF.name`. Mit `true` wird der Titel so ausgegeben, wie du ihn gesetzt hast.\n\nExample: /config\n```text\n$customtitles : true\n```\n\n### @{import(name, [name2], ...)}\n\nType: `command`\n\nGibt die Tags für statische Dateien, die Meta-Tags oder ein Favicon aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein Dateiname, `meta` oder ein Favicon-Name. |\n\nJedes Argument ergibt ein Tag:\n\n- `meta` gibt die Meta-Tags aus (siehe `@{meta}`).\n- `favicon.ico`, `favicon.png` oder `favicon.gif` gibt ein `<link rel=\"icon\">`-Tag aus.\n- Ein Name mit `.css` gibt einen Stylesheet-Link aus `/css/` aus, andere Namen ein Skript aus `/js/`. Ein Pfad, der mit `/` beginnt (oder eine virtuelle Route), wird unverändert verwendet.\n- Ein `@` vor dem Namen hängt `?ts=` mit der Startzeit der Anwendung an.\n- Mit `+` verbundene Namen werden zu einer minifizierten Datei zusammengeführt (siehe nächsten Eintrag).\n\nDie Tags werden gecacht, daher ist der Befehl günstig.\n\nExample: Head eines Layouts\n```html\n<head>\n\t@{import('meta', 'favicon.ico', '@default.css', 'ui.js', '/vendor/editor.js')}\n</head>\n```\n\n### @{import('a.css + b.css')}\n\nType: `command`\n\nFührt mehrere CSS- oder JavaScript-Dateien zu einer minifizierten Datei zusammen.\n\nDie mit `+` verbundenen Namen werden mit `MERGE()` zu einer Datei mit generiertem Namen zusammengeführt, etwa `/xkcqdmatno-min.css`, die das Framework ausliefert. Ein Name mit `.css` ergibt ein Stylesheet, andernfalls ein Skript. Ein Dateiname wird anhand seiner Endung in `/public/css/` oder `/public/js/` gesucht, ein Pfad, der mit `/` beginnt, in `/public/`, und eine URL wird heruntergeladen. Ein `@` am Anfang hängt `?ts=` an.\n\nExample: Eine CSS- und eine JS-Datei\n```html\n@{import('reset.css + layout.css + forms.css', '@ui.js + app.js')}\n<!-- <link rel=\"stylesheet\" href=\"/wqxjrnefjv-min.css\" /> -->\n<!-- <script src=\"/wbxyamtxmw-min.js?ts=mwi48bh6\"></script> -->\n```\n\n### @{json(value, [id], [beautify], [replacer])}\n\nType: `command`\n\nGibt einen Wert als JSON aus oder in einem `<script type=\"application/json\">`-Tag.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der Wert. |\n| `id` | `String` | no |  | Die id des Script-Tags. |\n| `beautify` | `Boolean` | no | `false` | Das JSON einrücken. |\n| `replacer` | `Function|Boolean` | no |  | Ein Replacer für `JSON.stringify()`. |\n\nMit `id` wird das JSON in ein Script-Tag mit dieser `id` gepackt, das Client-Code ohne zweiten Request liest. `beautify` rückt das JSON mit vier Leerzeichen ein. `replacer` ist eine Funktion für `JSON.stringify()` oder `true` für den Replacer des Frameworks. `@{json(value, true)}` ist dasselbe wie `@{json(value, null, true)}`.\n\nExample: Daten für den Client\n```html\n@{json(model.products, 'products')}\n<script>\n\tvar products = JSON.parse(document.getElementById('products').innerHTML);\n</script>\n```\n\n### @{href([key], [value])}\n\nType: `command`\n\nGibt den aktuellen Query-String mit einem geänderten Parameter aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | Der Name des Parameters oder ein Objekt mit den zu setzenden Parametern. |\n| `value` | `Any` | no |  | Der neue Wert. |\n\nReturns: `String` Der Query-String mit `?` oder ein leerer String.\n\n`@{href}` gibt den aktuellen Query-String aus (`?page=2&sort=name`). `@{href('page', 3)}` gibt ihn mit `page` auf `3` gesetzt aus; ohne Wert bleibt der aktuelle Wert erhalten. Weitere Argumente nach dem Wert sind Namen von Parametern, die entfernt werden. Ein Array als Wert schreibt den Parameter einmal für jedes Element (`tag=a&tag=b`), und ein Objekt als Wert wird als JSON geschrieben. `@{href({ page: 3, sort: 'price' })}` gibt die URL der Anfrage zurück, deren Query-String durch die Schlüssel des Objekts geändert ist. Verwende es für Links zum Blättern und Sortieren.\n\nExample: Blättern\n```html\n<a href=\"@{href('page', model.page - 1)}\">Previous</a>\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\nExample: Einen Parameter entfernen oder mehrere ändern\n```html\n<!-- /products/?page=2&sort=name&q=pen -->\n<a href=\"@{href('page', 1, 'sort')}\">First page</a>  <!-- ?page=1&q=pen -->\n<a href=\"@{href({ page: 1, sort: 'price' })}\">By price</a>  <!-- /products/?page=1&sort=price&q=pen -->\n```\n\n### DEF.helpers\n\nType: `property`\n\nEigene Funktionen, die du aus jeder View aufrufst.\n\nReturns: `Object`\n\nFüge dem Objekt Funktionen hinzu; in einem Helper ist `this` die View (`this.model`, `this.repository`, `this.controller`). Rufe einen Helper über seinen Namen auf (`@{price(10)}`), mit `@{helpers.price(10)}` oder mit `@{helper('price', 10)}`. Der zurückgegebene Wert wird ohne Kodierung ausgegeben. Registriere die Helper, bevor die Views kompiliert werden, zum Beispiel in `/definitions/`.\n\nExample: Registrieren und verwenden\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\n// in a view: <span>@{price(model.price, 'USD')}</span>\n```\n\n### @{helper(name, [arg1], [arg2], ...)}\n\nType: `command`\n\nRuft einen Helper aus `DEF.helpers` über seinen Namen auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Helpers. |\n\nDie übrigen Argumente gehen an den Helper. Gibt einen leeren String aus, wenn der Helper nicht existiert.\n\nExample: Einen Helper aufrufen\n```html\n<span>@{helper('price', model.price, 'EUR')}</span>\n```\n\n### @(text)\n\nType: `command`\n\nÜbersetzt einen Text in die Sprache der View.\n\nDer Text wird beim Kompilieren der View durch seine Übersetzung aus den Ressourcendateien ersetzt; ein Text ohne Übersetzung bleibt, wie er ist. Die Anleitung [Lokalisierung](../../guides/localization/) erklärt die Ressourcen.\n\nExample: Übersetzter Text\n```html\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n### @{compile [name]} ... @{end}\n\nType: `command`\n\nÜbergibt bei jedem Rendern einen Teil der View an `DEF.onViewCompile`.\n\nDas HTML zwischen den Tags, mit bereits ausgewerteten Befehlen, wird an `DEF.onViewCompile(name, html, model)` übergeben, und dessen Ergebnis wird ausgegeben. Verwende es, um Markdown oder einen anderen Prozessor auf einen Teil der View anzuwenden.\n\nExample: Markdown\n```html\n@{compile markdown}\n# @{model.title}\n\n@{model.text}\n@{end}\n```\n\n### DEF.onViewCompile = function(name, html, model)\n\nType: `delegate`\n\nVerarbeitet den Inhalt von `@{compile}`-Blöcken.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Blocks oder ein leerer String. |\n| `html` | `String` | yes |  | Der Inhalt des Blocks. |\n| `model` | `Object` | yes |  | Das Model der View. |\n\nReturns: `String` Das auszugebende HTML.\n\n`name` ist das Wort nach `@{compile`, `html` der gerenderte Inhalt des Blocks und `model` das Model der View. Gib das auszugebende HTML zurück. Standardmäßig gibt sie `html` unverändert zurück.\n\nExample: Markdown-Blöcke\n```js\nDEF.onViewCompile = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\n### ON('$view', function(meta) {})\n\nType: `event`\n\nÄndert den Quelltext einer View, bevor sie kompiliert wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, body, debug }`. |\n\n`meta.name` ist der Name der View, `meta.body` ihr HTML-Quelltext und `meta.debug` der Debug-Modus. Ändere `meta.body`, um die View zu ändern; das Event läuft jedes Mal, wenn eine View kompiliert wird.\n\nExample: Einen Platzhalter ersetzen\n```js\nON('$view', function(meta) {\n\tmeta.body = meta.body.replace(/\\{year\\}/g, new Date().getFullYear() + '');\n});\n```\n\n### @{nocompress html|js|css|all}\n\nType: `command`\n\nSchaltet einen Komprimierungsschritt für die View ab.\n\nBeim Kompilieren einer View werden Folgen von Leerzeichen in ihrem Text zusammengefasst (Zeilenumbrüche und Einrückungen zwischen Tags bleiben erhalten), und das CSS von `<style>`-Tags und das JavaScript von `<script>`-Tags werden minifiziert. `html` lässt das HTML unverändert und schaltet auch die Minifizierung der Antwort ab; `js` (oder `script`, `javascript`) und `css` (oder `style`) lassen den eingebetteten Code unverändert; `all` schaltet alle drei ab. HTML-Kommentare werden immer entfernt.\n\nExample: Leerraum behalten\n```html\n@{nocompress html}\n<pre>\n  formatted\n    text\n</pre>\n```\n\n### @{{ text }}\n\nType: `command`\n\nGibt `@{{ ... }}` unverändert aus, ohne es auszuführen.\n\nVerwende es, um `@{{ }}`-Text für clientseitige Templates zu behalten.\n\nExample: Wörtlicher Text\n```html\n<code>@{{ value }}</code>\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nRendert ein Tangular-Template und gibt ein Promise mit dem HTML zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Das Template, eine URL, ein Pfad oder ein Name einer Datei in `/templates/`. |\n| `model` | `Object` | no |  | Das Model, verfügbar als `value`. |\n| `$` | `Options` | no |  | Das `$` einer Aktion oder eines Controllers, für die Sprache und die Fehlerbehandlung. |\n\nReturns: `Promise<String>` Das gerenderte HTML.\n\n`body` ist der Template-Text, wenn er `{{` enthält. Andernfalls ist es eine URL (`http://` oder `https://`, wird heruntergeladen), `~` und ein absoluter Pfad, `#` und ein Pfad einer Datei in `/plugins/` (`.html` wird ergänzt, wenn es fehlt) oder ein Name einer Datei in `/templates/` (`.html` wird ergänzt, wenn es fehlt). Im Template ist das Modell `value`.\n\nDas Template kann einen Block `<script type=\"text/json\">` mit einem Standardmodell enthalten, das verwendet wird, wenn `model` nicht angegeben ist, und einen Block `<script>`, der Helfer zu `Thelpers` hinzufügt. Mit `$` (dem `$` einer Route oder einer Aktion) wird das Template in `$.language` übersetzt, und Fehler gehen an `$.invalid()`, statt das Promise abzulehnen. Aus Dateien gelesene Templates werden im Release-Modus gecacht.\n\nExample: Inline-Template\n```js\nvar html = await TEMPLATE('<p>Hello {{ value.name }}</p>', { name: 'Peter' });\n```\n\nExample: Eine Datei in einer Route\n```js\nexports.install = function() {\n\tROUTE('GET /invoice/{id}/', invoice);\n};\n\nfunction invoice($) {\n\tTEMPLATE('invoice', { number: $.params.id }, $).then(function(html) {\n\t\t$.html(html);\n\t});\n}\n```\n\n### {{ value }} / {{ if }} / {{ foreach }}\n\nType: `command`\n\nDie Befehle von Tangular-Templates, die `TEMPLATE()` verwendet.\n\n`{{ value.name }}` gibt einen HTML-kodierten Wert aus. `{{ if condition }}` … `{{ else if condition }}` … `{{ else }}` … `{{ fi }}` ist eine Bedingung. `{{ foreach item in value.items }}` … `{{ end }}` ist eine Schleife mit `{{ $index }}`, `{{ continue }}` und `{{ break }}`. Ein Wert läuft mit `|` durch Helper: `{{ value.html | raw }}`.\n\nExample: Rechnung\n```html\n<h1>Invoice {{ value.number }}</h1>\n{{ if value.items.length }}\n<table>\n\t{{ foreach item in value.items }}\n\t<tr><td>{{ $index + 1 }}</td><td>{{ item.name }}</td><td>{{ item.price | format(2) }}</td></tr>\n\t{{ end }}\n</table>\n{{ else }}\n<p>No items</p>\n{{ fi }}\n```\n\n### Thelpers\n\nType: `property`\n\nDie Helper von Tangular-Templates.\n\nReturns: `Object`\n\nEingebaute Helper: `encode` (der Standard für jeden Wert; `encode('json')`, `encode('url')` ändern das Format), `raw` (keine Codierung), `format(...)` (Zahlen und Datumswerte, wie `Number.format()` und `Date.format()`), `def(text)` oder `empty(text)` (gibt bei einem leeren Wert `text` oder `---` aus) und `pluralize(zero, one, few, other)`. Füge eigene in `Thelpers` hinzu, global oder im `<script>`-Block einer Template-Datei; `this` ist das Objekt, das das Modell in `value` hält.\n\nExample: Eine Template-Datei mit einem Helper und einem Standard-Model\n```html\n<script type=\"text/json\">{ \"name\": \"Guest\" }</script>\n<script>\nThelpers.upper = function(value) {\n\treturn (value || '').toUpperCase();\n};\n</script>\n<h1>{{ value.name | upper }}</h1>\n<p>{{ value.count | pluralize('# items', '# item', '# items', '# items') }}</p>\n<p>{{ value.date | format('yyyy-MM-dd') }} {{ value.note | def('none') }}</p>\n```\n","entries":[{"type":"method","name":"controller.view()","signature":"controller.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"F.view()","signature":"F.view(name, [model], [prepare])","since":"","deprecated":false},{"type":"class","name":"View","signature":"new F.TViewEngine.View([controller])","since":"","deprecated":false},{"type":"method","name":"view.render()","signature":"view.render(name, [model])","since":"","deprecated":false},{"type":"property","name":"view.repository","signature":"view.repository","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository}","since":"","deprecated":false},{"type":"command","name":"@{config}","signature":"@{config.key} / @{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{query}","signature":"@{query} / @{body} / @{files} / @{user} / @{session} / @{controller}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}","since":"","deprecated":false},{"type":"command","name":"@{hostname()}","signature":"@{hostname([path])}","since":"","deprecated":false},{"type":"command","name":"@{cookie()}","signature":"@{cookie(name)}","since":"","deprecated":false},{"type":"command","name":"@{now}","signature":"@{now}","since":"","deprecated":false},{"type":"command","name":"@{root}","signature":"@{root}","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":"@{index}","signature":"@{index}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end} / @{section(name)}","since":"","deprecated":false},{"type":"method","name":"view.section()","signature":"view.section(name, [value], [replace])","since":"","deprecated":false},{"type":"command","name":"@{title()}","signature":"@{title(value)} / @{title}","since":"","deprecated":false},{"type":"command","name":"@{title2()}","signature":"@{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} / @{description}","since":"","deprecated":false},{"type":"command","name":"@{keywords()}","signature":"@{keywords(value)} / @{keywords}","since":"","deprecated":false},{"type":"command","name":"@{meta()}","signature":"@{meta([title], [description], [keywords], [image])} / @{meta}","since":"","deprecated":false},{"type":"config","name":"CONF.$customtitles","signature":"CONF.$customtitles","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(name, [name2], ...)}","since":"","deprecated":false},{"type":"command","name":"Merging files","signature":"@{import('a.css + b.css')}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify], [replacer])}","since":"","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href([key], [value])}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers","since":"","deprecated":false},{"type":"command","name":"@{helper()}","signature":"@{helper(name, [arg1], [arg2], ...)}","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile [name]} ... @{end}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onViewCompile","signature":"DEF.onViewCompile = function(name, html, model)","since":"","deprecated":false},{"type":"event","name":"ON('$view')","signature":"ON('$view', function(meta) {})","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|js|css|all}","since":"","deprecated":false},{"type":"command","name":"@{{ }}","signature":"@{{ text }}","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"command","name":"Template commands","signature":"{{ value }} / {{ if }} / {{ foreach }}","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwth3Dx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/views/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Vistas","summary":"Los comandos de las vistas, el objeto de vista, los helpers y TEMPLATE().","markdown":"---\ntitle: Vistas\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/views/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Vistas\n\n> Los comandos de las vistas, el objeto de vista, los helpers y TEMPLATE().\n\nLas vistas son archivos HTML de `/views/` con comandos `@{...}`, que renderizan `controller.view()` y `F.view()`. Esta página enumera cada comando, los métodos del objeto de vista, los helpers y `TEMPLATE()`. La guía [Vistas](../../guides/views/) explica cómo funcionan juntos, con ejemplos.\n\n## API\n\n### controller.view([name], [model])\n\nType: `method`\n\nRenderiza una vista y la envía como respuesta HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | El nombre de la vista sin `.html`, por ejemplo `products/detail`. |\n| `model` | `Object` | no |  | El modelo, disponible como `model` en la vista. |\n\nReturns: `View` El objeto de vista.\n\nLa vista se lee de `/views/{name}.html`, o de `/plugins/` cuando el nombre empieza por `#`. Se renderiza dentro de la plantilla establecida con `controller.layout()` (o `layout` por defecto) y se envía con `controller.html()`. Sin nombre, el método solo devuelve un nuevo objeto de vista, que renderizas tú mismo.\n\nExample: Renderizar una vista\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail($) {\n\tvar id = $.params.id;\n\t$.view('products/detail', { id: id });\n}\n```\n\nExample: Renderizarla tú mismo\n```js\nfunction preview($) {\n\tvar view = $.view();\n\tview.layout('');\n\t$.html(view.render('preview', { name: 'Test' }));\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nEstablece la plantilla para el siguiente `controller.view()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la vista de plantilla (layout). |\n\nLlámalo antes de `controller.view()`. Un string vacío mantiene el layout por defecto; para una vista sin layout usa `@{layout('')}` en la vista o `view.layout('')`. Una vista aún puede cambiarlo con `@{layout()}`.\n\nExample: Usar otra plantilla\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('admin/index');\n}\n```\n\n### F.view(name, [model], [prepare])\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| `prepare` | `Function` | no |  | `function(view)` que se llama antes del renderizado, para establecer `view.language`, `view.repository` o la plantilla. |\n\nReturns: `String` El HTML renderizado.\n\nLa vista no tiene controlador, así que `controller`, `user`, `query` y los demás valores de la petición están vacíos. La vista se renderiza dentro de su plantilla como siempre; usa `@{layout('')}` en la vista, o `view.layout('')` en `prepare`, para un fragmento sin plantilla.\n\nExample: Renderizar el cuerpo de un e-mail\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n\tview.layout('');\n});\n```\n\n### new F.TViewEngine.View([controller])\n\nType: `class`\n\nEl objeto que renderiza una vista; es `self` dentro de la vista compilada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | no |  | El controlador de la petición. |\n\n`controller.view()` y `F.view()` lo crean por ti. Sus propiedades son `controller`, `model`, `repository` (`{ layout: 'layout' }` al principio), `language`, `url` y `query`. Sus métodos son los comandos de las vistas: `layout()`, `title()`, `description()`, `keywords()`, `meta()`, `json()`, `href()`, `import()`, `section()`, `helper()`, `hostname()` y `view()`.\n\nExample: Establecer valores antes de renderizar\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.repository.menu = 'products';\n\t$.html(view.render('products', { items: [] }));\n}\n```\n\n### view.render(name, [model])\n\nType: `method`\n\nRenderiza una vista con su plantilla 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\nReturns: `String` El HTML.\n\nEl archivo es `/views/{name}.html` (o `/plugins/{name}.html` para un nombre con `#`). Cuando `repository.layout` no está vacío, el resultado se renderiza dentro de esa plantilla.\n\nExample: Renderizar\n```js\nvar view = new F.TViewEngine.View();\nview.layout('');\nvar html = view.render('fragments/card', { name: 'Pen' });\n```\n\n### view.repository\n\nType: `property`\n\nUn objeto compartido por la vista, sus vistas parciales y la plantilla (layout).\n\nReturns: `Object`\n\nContiene `layout`, `title`, `description`, `keywords`, las secciones (`section_{name}`) y cualquier valor que añadas. En la vista es la variable `repository`. Úsalo para pasar valores de una vista a su plantilla.\n\nExample: De la vista a la plantilla\n```html\n<!-- view -->\n@{repository.menu = 'products'}\n\n<!-- layout -->\n<nav class=\"@{repository.menu}\">...</nav>\n```\n\n### view.language\n\nType: `property`\n\nEl idioma que se usa para las traducciones `@(...)`.\n\nReturns: `String`\n\nEs el idioma de la petición en `controller.view()` y un string vacío en `F.view()`. Establécelo antes de renderizar; cada idioma tiene su propia copia compilada de la vista, y `@{language}` lo imprime.\n\nExample: Idioma en F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{expression}\n\nType: `command`\n\nImprime el valor de una expresión JavaScript, codificado en HTML.\n\nFunciona cualquier expresión: propiedades, llamadas a métodos, operadores. `null` y `undefined` se imprimen como una cadena vacía. Una asignación (`=`, `+=`, `++`…) a `model`, `repository`, `config`, `query`, `user`, `session` o `controller` se evalúa y no imprime nada. `@{print(...)}` y `@{console.log(...)}` no imprimen nada en el HTML.\n\nExample: Valores\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} items</p>\n<p>@{model.price.format(2)}</p>\n@{repository.count = model.items.length}\n```\n\n### @{!expression}\n\nType: `command`\n\nImprime el valor de una expresión sin codificación HTML.\n\nÚsalo para HTML en el que confías, por ejemplo contenido de un CMS guardado por tus administradores.\n\nExample: HTML sin procesar\n```html\n<article>@{!model.body}</article>\n```\n\n### @{model}\n\nType: `command`\n\nEl modelo que se pasa a la vista.\n\nEs el segundo argumento de `controller.view()`, `F.view()`, `view.render()` o `@{view()}`. La plantilla no recibe el modelo.\n\nExample: Leer el modelo\n```html\n<h1>@{model.title}</h1>\n@{if model.user}<p>@{model.user.name}</p>@{fi}\n```\n\n### @{repository}\n\nType: `command`\n\nEl objeto compartido de la vista, sus vistas parciales y la plantilla.\n\nConsulta `view.repository`. Asigna valores con `@{repository.key = value}`; la asignación no imprime nada.\n\nExample: Establecer y leer\n```html\n@{repository.menu = 'contact'}\n<li class=\"@{repository.menu === 'contact' ? 'active' : ''}\">Contact</li>\n```\n\n### @{config.key} / @{'%key'}\n\nType: `command`\n\nImprime un valor de configuración.\n\n`config` es `CONF`, que se lee en cada renderizado. `@{'%key'}` lee el valor una sola vez, cuando se compila la vista, y lo pone en la vista como texto.\n\nExample: Configuración\n```html\n<title>@{config.name}</title>\n<footer>@{'%name'} @{config.version}</footer>\n```\n\n### @{query} / @{body} / @{files} / @{user} / @{session} / @{controller}\n\nType: `command`\n\nLos datos de la petición actual.\n\n`query` es la query string analizada, `body` el cuerpo analizado, `files` los archivos subidos, `user` y `session` los valores de tu autorización, y `controller` el propio controlador. En `F.view()` están vacíos. En una plantilla, `@{body}` sin propiedad imprime en su lugar el HTML de la vista.\n\nExample: Valores de la petición\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{else}\n\t<a href=\"/login/\">Sign in</a>\n@{fi}\n<input name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{body}\n\nType: `command`\n\nEn una plantilla, imprime el HTML de la vista renderizada.\n\nLa salida no se codifica. Con una propiedad (`@{body.name}`) lee en su lugar el cuerpo de la petición.\n\nExample: Plantilla\n```html\n<!DOCTYPE html>\n<html>\n<head>@{import('meta')}</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{language}\n\nType: `command`\n\nEl idioma de la vista.\n\nReturns: `undefined` Nada\n\nEl idioma de la vista (`view.language`): el idioma de la petición (`controller.language`) en `controller.view()`, el valor que estableces en la función `prepare` de `F.view()`, y un string vacío por defecto.\n\nExample: Atributo de idioma\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\nExample: En F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n// <html lang=\"de\">\n```\n\n### @{url}\n\nType: `command`\n\nLa ruta de la URL de la petición actual.\n\nEs `controller.url`, la ruta tal como se pidió (se conservan las mayúsculas y minúsculas) con una barra final y sin el query string. `url` también funciona dentro de expresiones y condiciones: `@{if url === '/'}`. En `F.view()` no hay petición: `@{url}` imprime un string vacío y `url` en una expresión es `undefined`.\n\nExample: Enlace activo\n```html\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n### @{hostname([path])}\n\nType: `command`\n\nImprime la URL absoluta de la página actual o de otra ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Una ruta que empieza por `/`. Sin ella, la ruta de la petición actual. |\n\nReturns: `String` La URL absoluta.\n\n`@{hostname()}` imprime el protocolo, el host y la ruta de la petición actual, sin el query string (`https://shop.example.com/products/`). `@{hostname('/img/share.png')}` imprime el protocolo y el host con la ruta indicada. Llama a `controller.hostname()`; consulta [Controlador](../controller/). Escribe los paréntesis: `@{hostname}` solo no llama a la función.\n\nEn `F.view()` no hay petición, así que solo imprime `path` (o un string vacío).\n\nExample: Enlace canónico e imagen para compartir\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<meta property=\"og:image\" content=\"@{hostname('/img/share.png')}\" />\n```\n\n### @{cookie(name)}\n\nType: `command`\n\nImprime el valor de una cookie de la petición, codificado en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la cookie. |\n\nSin controlador imprime una cadena vacía.\n\nExample: Leer una cookie\n```html\n<body class=\"theme-@{cookie('theme')}\">\n```\n\n### @{now}\n\nType: `command`\n\nUn nuevo `Date` con la hora actual.\n\nUsa directamente las propiedades y métodos de la fecha: `@{now.getFullYear()}`.\n\nExample: Copyright\n```html\n<footer>&copy; @{now.getFullYear()} @{config.name}</footer>\n```\n\n### @{root}\n\nType: `command`\n\nImprime `CONF.$root` sin su barra final.\n\nÚsalo en los enlaces cuando la aplicación se ejecuta bajo una subruta. Imprime una cadena vacía cuando `CONF.$root` no está establecido.\n\nExample: Enlace bajo una subruta\n```html\n<a href=\"@{root}/products/\">Products</a>\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\nLa condición es cualquier expresión de JavaScript. `@{endif}` es lo mismo que `@{fi}`. `@{if(condition)}` con paréntesis también funciona.\n\nExample: Condición\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRepite una parte de la vista para cada elemento de un array o de un objeto.\n\nPara un objeto, cada elemento es `{ key, value }`. Un origen vacío no renderiza nada. `@{foreach var item in source}` también funciona. Dentro del bucle, `@{index}` es la posición empezando por cero, y `@{continue}` y `@{break}` saltan un elemento o detienen el bucle. Los bucles se pueden anidar.\n\nExample: Array\n```html\n<ul>\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n</ul>\n```\n\nExample: Objeto\n```html\n@{foreach prop in model.settings}\n\t<dt>@{prop.key}</dt><dd>@{prop.value}</dd>\n@{end}\n```\n\n### @{index}\n\nType: `command`\n\nLa posición, empezando por cero, del elemento actual en `@{foreach}`.\n\nExample: Filas numeradas\n```html\n@{foreach row in model.rows}\n\t<tr class=\"@{index % 2 ? 'odd' : 'even'}\"><td>@{index + 1}</td><td>@{row.name}</td></tr>\n@{end}\n```\n\n### @{layout(name)}\n\nType: `command`\n\nEstablece la plantilla de la 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\nLa plantilla por defecto es `layout` (`/views/layout.html`). Una cadena vacía renderiza la vista sin plantilla. El comando no imprime nada.\n\nExample: Otra plantilla\n```html\n@{layout('layout-print')}\n<h1>@{model.title}</h1>\n```\n\nExample: Sin plantilla\n```html\n@{layout('')}\n<div class=\"card\">@{model.name}</div>\n```\n\n### @{view(name, [model])}\n\nType: `command`\n\nRenderiza otra vista en ese lugar (una vista parcial).\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\nLa vista parcial recibe su propio modelo y ninguna plantilla. Comparte `repository` y las secciones con la vista que la renderiza. Un nombre que empieza por `#` lee el archivo de `/plugins/`.\n\nExample: Vistas parciales\n```html\n@{foreach item in model.items}\n\t@{view('partials/card', item)}\n@{end}\n@{view('#blog/sidebar')}\n```\n\n### @{section name} ... @{end} / @{section(name)}\n\nType: `command`\n\nRecoge HTML en una vista y lo imprime en otro lugar, normalmente en la plantilla.\n\n`@{section name}` … `@{end}` añade su HTML a la sección; varios bloques con el mismo nombre se unen. `@{section('name')}` imprime la sección, o nada cuando está vacía. La sección debe rellenarse antes de imprimirse, que es lo que ocurre con una plantilla.\n\nExample: Scripts para la plantilla\n```html\n<!-- view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- layout, before </body> -->\n@{section('scripts')}\n```\n\n### view.section(name, [value], [replace])\n\nType: `method`\n\nLee o rellena una sección desde JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la sección. |\n| `value` | `String` | no |  | El HTML que se añade. |\n| `replace` | `Boolean` | no | `false` | Reemplaza el contenido actual. |\n\nReturns: `String|View` La sección al leer; la vista al escribir.\n\nSin `value` devuelve el HTML de la sección. Con `value` añade el HTML a la sección, o la reemplaza cuando `replace` es `true`.\n\nExample: Rellenar una sección\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.section('scripts', '<script src=\"/js/page.js\"></script>');\n\t$.html(view.render('page'));\n}\n```\n\n### @{title(value)} / @{title}\n\nType: `command`\n\nEstablece o imprime el título de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El título. |\n\n`@{title('Text')}` guarda el texto en `repository.title` y no imprime nada. `@{title}` lo imprime codificado en HTML, `@{!title}` sin codificar.\n\nExample: Título\n```html\n@{title('Products / ' + model.category)}\n<h1>@{title}</h1>\n```\n\n### @{title2(value)}\n\nType: `command`\n\nAñade texto al final del título de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El texto que se añade. |\n\nReturns: `undefined` Nada\n\nAñade `value` al final de `repository.title` (o lo establece cuando todavía no hay título) y no imprime nada. Como con `title()`, el texto se guarda tal cual y se codifica una sola vez cuando se imprime. Un valor vacío no cambia nada.\n\nExample: Título en dos pasos\n```html\n@{title('Products')}\n@{if model}@{title2(' / ' + model.name)}@{fi}\n<h1>@{title}</h1>  <!-- Products / Pen &amp; paper -->\n```\n\n### @{description(value)} / @{description}\n\nType: `command`\n\nEstablece o imprime la descripción de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La descripción. |\n\nEl valor va a `repository.description`; `@{import('meta')}` lo imprime como una etiqueta `<meta name=\"description\">`.\n\nExample: Descripción\n```html\n@{description('Pens, pencils and paper for the office.')}\n```\n\n### @{keywords(value)} / @{keywords}\n\nType: `command`\n\nEstablece o imprime las palabras clave de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Las palabras clave. |\n\nUn array se une con `, `. El valor va a `repository.keywords`.\n\nExample: Palabras clave\n```html\n@{keywords(['pens', 'paper', 'office'])}\n```\n\n### @{meta([title], [description], [keywords], [image])} / @{meta}\n\nType: `command`\n\nEstablece el título, la descripción, las palabras clave y la imagen a la vez, o imprime los meta tags.\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 |  | Las palabras clave. |\n| `image` | `String` | no |  | Una URL absoluta o una ruta de una imagen. |\n\nReturns: `undefined` Nada\n\nCon argumentos guarda los valores en `repository` tal cual y no imprime nada; se codifican en HTML una sola vez, cuando se imprimen las etiquetas. Sin argumentos imprime las mismas etiquetas que `@{import('meta')}`: `<title>`, las etiquetas de descripción y palabras clave, y `og:image` y `twitter:image` para la imagen. Una imagen relativa recibe el nombre de host de la petición; sin petición no se imprimen etiquetas de imagen. Al título se le añade ` - ` y `CONF.name`, salvo en la URL `/` y cuando `CONF.$customtitles` es `true`; sin título es `CONF.name`.\n\nExample: Establecer e imprimir\n```html\n<!-- view -->\n@{meta(model.name, model.summary, model.tags, model.photo)}\n\n<!-- layout -->\n<head>@{meta}</head>\n```\n\n### CONF.$customtitles\n\nType: `config`\n\nImprime el título de la página sin el nombre de la aplicación.\n\nReturns: `Boolean` Por defecto `false`.\n\nPor defecto, la etiqueta de título de `@{meta}` y `@{import('meta')}` es `Title - CONF.name`. Con `true` el título se imprime tal como lo estableces.\n\nExample: /config\n```text\n$customtitles : true\n```\n\n### @{import(name, [name2], ...)}\n\nType: `command`\n\nImprime las etiquetas de los archivos estáticos, los meta tags o un favicon.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre de archivo, `meta` o un nombre de favicon. |\n\nCada argumento genera una etiqueta:\n\n- `meta` imprime los meta tags (consulta `@{meta}`).\n- `favicon.ico`, `favicon.png` o `favicon.gif` imprime una etiqueta `<link rel=\"icon\">`.\n- Un nombre con `.css` imprime un enlace a una hoja de estilos de `/css/`, y los demás nombres un script de `/js/`. Una ruta que empieza por `/` (o una ruta virtual) se usa tal cual.\n- Una `@` delante del nombre añade `?ts=` con la hora de inicio de la aplicación.\n- Los nombres unidos con `+` se combinan en un único archivo minificado (consulta la siguiente entrada).\n\nLas etiquetas se guardan en caché, así que el comando es barato.\n\nExample: Head de una plantilla\n```html\n<head>\n\t@{import('meta', 'favicon.ico', '@default.css', 'ui.js', '/vendor/editor.js')}\n</head>\n```\n\n### @{import('a.css + b.css')}\n\nType: `command`\n\nCombina varios archivos CSS o JavaScript en un único archivo minificado.\n\nLos nombres unidos con `+` se combinan con `MERGE()` en un archivo con un nombre generado, como `/xkcqdmatno-min.css`, que sirve el framework. Un nombre con `.css` crea una hoja de estilos; si no, un script. Un nombre de archivo se busca en `/public/css/` o `/public/js/` según su extensión, una ruta que empieza por `/` en `/public/`, y una URL se descarga. Una `@` al principio añade `?ts=`.\n\nExample: Un archivo CSS y uno JS\n```html\n@{import('reset.css + layout.css + forms.css', '@ui.js + app.js')}\n<!-- <link rel=\"stylesheet\" href=\"/wqxjrnefjv-min.css\" /> -->\n<!-- <script src=\"/wbxyamtxmw-min.js?ts=mwi48bh6\"></script> -->\n```\n\n### @{json(value, [id], [beautify], [replacer])}\n\nType: `command`\n\nImprime un valor como JSON, o en una etiqueta `<script type=\"application/json\">`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor. |\n| `id` | `String` | no |  | El id de la etiqueta script. |\n| `beautify` | `Boolean` | no | `false` | Indenta el JSON. |\n| `replacer` | `Function|Boolean` | no |  | Un replacer para `JSON.stringify()`. |\n\nCon `id`, el JSON se envuelve en una etiqueta script con ese `id`, que el código del cliente lee sin una segunda petición. `beautify` indenta el JSON con cuatro espacios. `replacer` es una función para `JSON.stringify()`, o `true` para el replacer del framework. `@{json(value, true)}` es lo mismo que `@{json(value, null, true)}`.\n\nExample: Datos para el cliente\n```html\n@{json(model.products, 'products')}\n<script>\n\tvar products = JSON.parse(document.getElementById('products').innerHTML);\n</script>\n```\n\n### @{href([key], [value])}\n\nType: `command`\n\nImprime la query string actual con un parámetro cambiado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | El nombre del parámetro, o un objeto con los parámetros que se establecen. |\n| `value` | `Any` | no |  | El nuevo valor. |\n\nReturns: `String` La query string con `?`, o una cadena vacía.\n\n`@{href}` imprime la query string actual (`?page=2&sort=name`). `@{href('page', 3)}` la imprime con `page` establecido a `3`; sin valor se conserva el valor actual. Los argumentos que siguen al valor son nombres de parámetros que se eliminan. Un valor array escribe el parámetro una vez por cada elemento (`tag=a&tag=b`) y un valor objeto se escribe como JSON. `@{href({ page: 3, sort: 'price' })}` devuelve la URL de la petición con la query string cambiada según las claves del objeto. Úsalo para los enlaces de paginación y ordenación.\n\nExample: Paginación\n```html\n<a href=\"@{href('page', model.page - 1)}\">Previous</a>\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\nExample: Eliminar un parámetro, o cambiar varios\n```html\n<!-- /products/?page=2&sort=name&q=pen -->\n<a href=\"@{href('page', 1, 'sort')}\">First page</a>  <!-- ?page=1&q=pen -->\n<a href=\"@{href({ page: 1, sort: 'price' })}\">By price</a>  <!-- /products/?page=1&sort=price&q=pen -->\n```\n\n### DEF.helpers\n\nType: `property`\n\nFunciones personalizadas que llamas desde cualquier vista.\n\nReturns: `Object`\n\nAñade funciones al objeto; dentro de un helper `this` es la vista (`this.model`, `this.repository`, `this.controller`). Llama a un helper por su nombre (`@{price(10)}`), con `@{helpers.price(10)}` o con `@{helper('price', 10)}`. El valor devuelto se imprime sin codificar. Registra los helpers antes de que se compilen las vistas, por ejemplo en `/definitions/`.\n\nExample: Registrar y usar\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\n// in a view: <span>@{price(model.price, 'USD')}</span>\n```\n\n### @{helper(name, [arg1], [arg2], ...)}\n\nType: `command`\n\nLlama a un helper de `DEF.helpers` por su nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del helper. |\n\nLos demás argumentos van al helper. Imprime una cadena vacía cuando el helper no existe.\n\nExample: Llamar a un helper\n```html\n<span>@{helper('price', model.price, 'EUR')}</span>\n```\n\n### @(text)\n\nType: `command`\n\nTraduce un texto al idioma de la vista.\n\nEl texto se reemplaza por su traducción de los archivos de recursos cuando se compila la vista; un texto sin traducción se queda tal cual. La guía de [Localización](../../guides/localization/) explica los recursos.\n\nExample: Texto traducido\n```html\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n### @{compile [name]} ... @{end}\n\nType: `command`\n\nPasa una parte de la vista a `DEF.onViewCompile` en cada renderizado.\n\nEl HTML entre las etiquetas, con los comandos ya evaluados, se pasa a `DEF.onViewCompile(name, html, model)`, y se imprime su resultado. Úsalo para procesar con Markdown u otro procesador una parte de la vista.\n\nExample: Markdown\n```html\n@{compile markdown}\n# @{model.title}\n\n@{model.text}\n@{end}\n```\n\n### DEF.onViewCompile = function(name, html, model)\n\nType: `delegate`\n\nProcesa el contenido de los bloques `@{compile}`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del bloque, o una cadena vacía. |\n| `html` | `String` | yes |  | El contenido del bloque. |\n| `model` | `Object` | yes |  | El modelo de la vista. |\n\nReturns: `String` El HTML que se imprime.\n\n`name` es la palabra que sigue a `@{compile`, `html` el contenido renderizado del bloque y `model` el modelo de la vista. Devuelve el HTML que se imprime. Por defecto devuelve `html` sin cambios.\n\nExample: Bloques Markdown\n```js\nDEF.onViewCompile = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\n### ON('$view', function(meta) {})\n\nType: `event`\n\nCambia el código fuente de una vista antes de compilarla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, body, debug }`. |\n\n`meta.name` es el nombre de la vista, `meta.body` su código fuente HTML y `meta.debug` el modo debug. Cambia `meta.body` para cambiar la vista; el evento se ejecuta cada vez que se compila una vista.\n\nExample: Reemplazar un marcador\n```js\nON('$view', function(meta) {\n\tmeta.body = meta.body.replace(/\\{year\\}/g, new Date().getFullYear() + '');\n});\n```\n\n### @{nocompress html|js|css|all}\n\nType: `command`\n\nDesactiva un paso de compresión de la vista.\n\nCuando se compila una vista, se colapsan las secuencias de espacios dentro de su texto (se conservan los saltos de línea y la sangría entre etiquetas), y se minifican el CSS de las etiquetas `<style>` y el JavaScript de las etiquetas `<script>`. `html` mantiene el HTML tal cual y también desactiva la minificación de la respuesta; `js` (o `script`, `javascript`) y `css` (o `style`) mantienen el código en línea; `all` desactiva los tres. Los comentarios HTML siempre se eliminan.\n\nExample: Conservar los espacios en blanco\n```html\n@{nocompress html}\n<pre>\n  formatted\n    text\n</pre>\n```\n\n### @{{ text }}\n\nType: `command`\n\nImprime `@{{ ... }}` tal cual, sin ejecutarlo.\n\nÚsalo para conservar texto `@{{ }}` para templates del lado del cliente.\n\nExample: Texto literal\n```html\n<code>@{{ value }}</code>\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nRenderiza un template de Tangular y devuelve una promesa con el HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | El template, una URL, una ruta o un nombre de un archivo en `/templates/`. |\n| `model` | `Object` | no |  | El modelo, disponible como `value`. |\n| `$` | `Options` | no |  | El `$` de una acción o de un controlador, para el idioma y la gestión de errores. |\n\nReturns: `Promise<String>` El HTML renderizado.\n\n`body` es el texto de la plantilla cuando contiene `{{`. Si no, es una URL (`http://` o `https://`, que se descarga), `~` y una ruta absoluta, `#` y una ruta de un archivo en `/plugins/` (se añade `.html` si falta), o un nombre de archivo en `/templates/` (se añade `.html` si falta). En la plantilla el modelo es `value`.\n\nLa plantilla puede contener un bloque `<script type=\"text/json\">` con un modelo por defecto, que se usa cuando no se indica `model`, y un bloque `<script>` que añade helpers a `Thelpers`. Con `$` (el `$` de una ruta o de una acción) la plantilla se traduce a `$.language`, y los errores van a `$.invalid()` en lugar de rechazar la promesa. Las plantillas leídas de archivos se guardan en caché en modo release.\n\nExample: Template inline\n```js\nvar html = await TEMPLATE('<p>Hello {{ value.name }}</p>', { name: 'Peter' });\n```\n\nExample: Un archivo en una ruta\n```js\nexports.install = function() {\n\tROUTE('GET /invoice/{id}/', invoice);\n};\n\nfunction invoice($) {\n\tTEMPLATE('invoice', { number: $.params.id }, $).then(function(html) {\n\t\t$.html(html);\n\t});\n}\n```\n\n### {{ value }} / {{ if }} / {{ foreach }}\n\nType: `command`\n\nLos comandos de los templates de Tangular que usa `TEMPLATE()`.\n\n`{{ value.name }}` imprime un valor codificado en HTML. `{{ if condition }}` … `{{ else if condition }}` … `{{ else }}` … `{{ fi }}` es una condición. `{{ foreach item in value.items }}` … `{{ end }}` es un bucle con `{{ $index }}`, `{{ continue }}` y `{{ break }}`. Un valor pasa por helpers con `|`: `{{ value.html | raw }}`.\n\nExample: Factura\n```html\n<h1>Invoice {{ value.number }}</h1>\n{{ if value.items.length }}\n<table>\n\t{{ foreach item in value.items }}\n\t<tr><td>{{ $index + 1 }}</td><td>{{ item.name }}</td><td>{{ item.price | format(2) }}</td></tr>\n\t{{ end }}\n</table>\n{{ else }}\n<p>No items</p>\n{{ fi }}\n```\n\n### Thelpers\n\nType: `property`\n\nLos helpers de los templates de Tangular.\n\nReturns: `Object`\n\nHelpers integrados: `encode` (el valor por defecto para cada valor; `encode('json')`, `encode('url')` cambian el formato), `raw` (sin codificación), `format(...)` (números y fechas, como `Number.format()` y `Date.format()`), `def(text)` o `empty(text)` (imprime `text`, o `---`, para un valor vacío) y `pluralize(zero, one, few, other)`. Añade los tuyos en `Thelpers`, globalmente o en el bloque `<script>` de un archivo de plantilla; `this` es el objeto que contiene el modelo en `value`.\n\nExample: Un archivo de template con un helper y un modelo por defecto\n```html\n<script type=\"text/json\">{ \"name\": \"Guest\" }</script>\n<script>\nThelpers.upper = function(value) {\n\treturn (value || '').toUpperCase();\n};\n</script>\n<h1>{{ value.name | upper }}</h1>\n<p>{{ value.count | pluralize('# items', '# item', '# items', '# items') }}</p>\n<p>{{ value.date | format('yyyy-MM-dd') }} {{ value.note | def('none') }}</p>\n```\n","entries":[{"type":"method","name":"controller.view()","signature":"controller.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"F.view()","signature":"F.view(name, [model], [prepare])","since":"","deprecated":false},{"type":"class","name":"View","signature":"new F.TViewEngine.View([controller])","since":"","deprecated":false},{"type":"method","name":"view.render()","signature":"view.render(name, [model])","since":"","deprecated":false},{"type":"property","name":"view.repository","signature":"view.repository","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository}","since":"","deprecated":false},{"type":"command","name":"@{config}","signature":"@{config.key} / @{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{query}","signature":"@{query} / @{body} / @{files} / @{user} / @{session} / @{controller}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}","since":"","deprecated":false},{"type":"command","name":"@{hostname()}","signature":"@{hostname([path])}","since":"","deprecated":false},{"type":"command","name":"@{cookie()}","signature":"@{cookie(name)}","since":"","deprecated":false},{"type":"command","name":"@{now}","signature":"@{now}","since":"","deprecated":false},{"type":"command","name":"@{root}","signature":"@{root}","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":"@{index}","signature":"@{index}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end} / @{section(name)}","since":"","deprecated":false},{"type":"method","name":"view.section()","signature":"view.section(name, [value], [replace])","since":"","deprecated":false},{"type":"command","name":"@{title()}","signature":"@{title(value)} / @{title}","since":"","deprecated":false},{"type":"command","name":"@{title2()}","signature":"@{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} / @{description}","since":"","deprecated":false},{"type":"command","name":"@{keywords()}","signature":"@{keywords(value)} / @{keywords}","since":"","deprecated":false},{"type":"command","name":"@{meta()}","signature":"@{meta([title], [description], [keywords], [image])} / @{meta}","since":"","deprecated":false},{"type":"config","name":"CONF.$customtitles","signature":"CONF.$customtitles","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(name, [name2], ...)}","since":"","deprecated":false},{"type":"command","name":"Merging files","signature":"@{import('a.css + b.css')}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify], [replacer])}","since":"","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href([key], [value])}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers","since":"","deprecated":false},{"type":"command","name":"@{helper()}","signature":"@{helper(name, [arg1], [arg2], ...)}","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile [name]} ... @{end}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onViewCompile","signature":"DEF.onViewCompile = function(name, html, model)","since":"","deprecated":false},{"type":"event","name":"ON('$view')","signature":"ON('$view', function(meta) {})","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|js|css|all}","since":"","deprecated":false},{"type":"command","name":"@{{ }}","signature":"@{{ text }}","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"command","name":"Template commands","signature":"{{ value }} / {{ if }} / {{ foreach }}","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwth3Dx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/views/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Vues","summary":"Les commandes de vue, l'objet vue, les helpers et TEMPLATE().","markdown":"---\ntitle: Vues\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/views/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Vues\n\n> Les commandes de vue, l'objet vue, les helpers et TEMPLATE().\n\nLes vues sont des fichiers HTML de `/views/` contenant des commandes `@{...}`, rendus par `controller.view()` et `F.view()`. Cette page liste chaque commande, les méthodes de l'objet vue, les helpers et `TEMPLATE()`. Le guide [Vues](../../guides/views/) explique comment ils fonctionnent ensemble, avec des exemples.\n\n## API\n\n### controller.view([name], [model])\n\nType: `method`\n\nEffectue le rendu d'une vue et l'envoie comme réponse HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Le nom de la vue sans `.html`, par exemple `products/detail`. |\n| `model` | `Object` | no |  | Le modèle, disponible sous `model` dans la vue. |\n\nReturns: `View` L'objet vue.\n\nLa vue est lue depuis `/views/{name}.html`, ou depuis `/plugins/` lorsque le nom commence par `#`. Elle est rendue dans le layout défini avec `controller.layout()` (ou `layout` par défaut) et envoyée avec `controller.html()`. Sans nom, la méthode retourne seulement un nouvel objet vue, dont tu effectues toi-même le rendu.\n\nExample: Effectuer le rendu d'une vue\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail($) {\n\tvar id = $.params.id;\n\t$.view('products/detail', { id: id });\n}\n```\n\nExample: Effectuer le rendu toi-même\n```js\nfunction preview($) {\n\tvar view = $.view();\n\tview.layout('');\n\t$.html(view.render('preview', { name: 'Test' }));\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nDéfinit le layout du prochain `controller.view()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la vue de layout. |\n\nAppelle-la avant `controller.view()`. Une chaîne vide conserve le layout par défaut ; pour une vue sans layout, utilise `@{layout('')}` dans la vue ou `view.layout('')`. Une vue peut encore le changer avec `@{layout()}`.\n\nExample: Utiliser un autre layout\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('admin/index');\n}\n```\n\n### F.view(name, [model], [prepare])\n\nType: `method`\n\nEffectue le rendu d'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| `prepare` | `Function` | no |  | `function(view)` appelée avant le rendu, pour définir `view.language`, `view.repository` ou le layout. |\n\nReturns: `String` Le HTML rendu.\n\nLa vue n'a pas de contrôleur : `controller`, `user`, `query` et les autres valeurs de la requête sont donc vides. La vue est rendue dans son layout comme d'habitude ; utilise `@{layout('')}` dans la vue, ou `view.layout('')` dans `prepare`, pour un fragment sans layout.\n\nExample: Effectuer le rendu du corps d'un e-mail\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n\tview.layout('');\n});\n```\n\n### new F.TViewEngine.View([controller])\n\nType: `class`\n\nL'objet qui effectue le rendu d'une vue ; c'est `self` à l'intérieur de la vue compilée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | no |  | Le contrôleur de la requête. |\n\n`controller.view()` et `F.view()` le créent pour toi. Ses propriétés sont `controller`, `model`, `repository` (`{ layout: 'layout' }` au départ), `language`, `url` et `query`. Ses méthodes sont les commandes de vue : `layout()`, `title()`, `description()`, `keywords()`, `meta()`, `json()`, `href()`, `import()`, `section()`, `helper()`, `hostname()` et `view()`.\n\nExample: Définir des valeurs avant le rendu\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.repository.menu = 'products';\n\t$.html(view.render('products', { items: [] }));\n}\n```\n\n### view.render(name, [model])\n\nType: `method`\n\nEffectue le rendu d'une vue avec son layout 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\nReturns: `String` Le HTML.\n\nLe fichier est `/views/{name}.html` (ou `/plugins/{name}.html` pour un nom avec `#`). Lorsque `repository.layout` n'est pas vide, le résultat est rendu dans ce layout.\n\nExample: Rendu\n```js\nvar view = new F.TViewEngine.View();\nview.layout('');\nvar html = view.render('fragments/card', { name: 'Pen' });\n```\n\n### view.repository\n\nType: `property`\n\nUn objet partagé par la vue, ses vues partielles et le layout.\n\nReturns: `Object`\n\nIl contient `layout`, `title`, `description`, `keywords`, les sections (`section_{name}`) et toutes les valeurs que tu ajoutes. Dans la vue, c'est la variable `repository`. Utilise-le pour transmettre des valeurs d'une vue à son layout.\n\nExample: De la vue au layout\n```html\n<!-- view -->\n@{repository.menu = 'products'}\n\n<!-- layout -->\n<nav class=\"@{repository.menu}\">...</nav>\n```\n\n### view.language\n\nType: `property`\n\nLa langue utilisée pour les traductions `@(...)`.\n\nReturns: `String`\n\nC'est la langue de la requête dans `controller.view()` et une chaîne vide dans `F.view()`. Définis-la avant le rendu ; chaque langue a sa propre copie compilée de la vue, et `@{language}` l'affiche.\n\nExample: Langue dans F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{expression}\n\nType: `command`\n\nAffiche la valeur d'une expression JavaScript, encodée en HTML.\n\nN'importe quelle expression fonctionne : propriétés, appels de méthodes, opérateurs. `null` et `undefined` s'affichent comme une chaîne vide. Une affectation (`=`, `+=`, `++`…) à `model`, `repository`, `config`, `query`, `user`, `session` ou `controller` est évaluée et n'affiche rien. `@{print(...)}` et `@{console.log(...)}` n'affichent rien dans le HTML.\n\nExample: Valeurs\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} items</p>\n<p>@{model.price.format(2)}</p>\n@{repository.count = model.items.length}\n```\n\n### @{!expression}\n\nType: `command`\n\nAffiche la valeur d'une expression sans encodage HTML.\n\nUtilise-la pour du HTML de confiance, par exemple le contenu d'un CMS enregistré par tes administrateurs.\n\nExample: HTML brut\n```html\n<article>@{!model.body}</article>\n```\n\n### @{model}\n\nType: `command`\n\nLe modèle transmis à la vue.\n\nC'est le second argument de `controller.view()`, `F.view()`, `view.render()` ou `@{view()}`. Le layout ne reçoit pas le modèle.\n\nExample: Lire le modèle\n```html\n<h1>@{model.title}</h1>\n@{if model.user}<p>@{model.user.name}</p>@{fi}\n```\n\n### @{repository}\n\nType: `command`\n\nL'objet partagé par la vue, ses vues partielles et le layout.\n\nVoir `view.repository`. Assigne des valeurs avec `@{repository.key = value}` ; l'affectation n'affiche rien.\n\nExample: Définir et lire\n```html\n@{repository.menu = 'contact'}\n<li class=\"@{repository.menu === 'contact' ? 'active' : ''}\">Contact</li>\n```\n\n### @{config.key} / @{'%key'}\n\nType: `command`\n\nAffiche une valeur de configuration.\n\n`config` est `CONF`, lu à chaque rendu. `@{'%key'}` lit la valeur une seule fois, lors de la compilation de la vue, et l'insère dans la vue sous forme de texte.\n\nExample: Configuration\n```html\n<title>@{config.name}</title>\n<footer>@{'%name'} @{config.version}</footer>\n```\n\n### @{query} / @{body} / @{files} / @{user} / @{session} / @{controller}\n\nType: `command`\n\nLes données de la requête courante.\n\n`query` est la query string analysée, `body` le corps analysé, `files` les fichiers envoyés, `user` et `session` les valeurs de ton autorisation, et `controller` le contrôleur lui-même. Dans `F.view()`, ils sont vides. Dans un layout, `@{body}` sans propriété affiche à la place le HTML de la vue.\n\nExample: Valeurs de la requête\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{else}\n\t<a href=\"/login/\">Sign in</a>\n@{fi}\n<input name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{body}\n\nType: `command`\n\nDans un layout, affiche le HTML de la vue rendue.\n\nLa sortie n'est pas encodée. Avec une propriété (`@{body.name}`), elle lit à la place le corps de la requête.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>@{import('meta')}</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{language}\n\nType: `command`\n\nLa langue de la vue.\n\nLa langue de la vue (`view.language`) : la langue de la requête (`controller.language`) dans `controller.view()`, la valeur que tu définis dans la fonction `prepare` de `F.view()`, et une chaîne vide par défaut.\n\nExample: Attribut de langue\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\nExample: Dans F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n// <html lang=\"de\">\n```\n\n### @{url}\n\nType: `command`\n\nLe chemin d'URL de la requête courante.\n\nC'est `controller.url`, le chemin tel que demandé (la casse des lettres est conservée) avec une barre oblique finale et sans la query string. `url` fonctionne aussi dans les expressions et les conditions : `@{if url === '/'}`. Dans `F.view()`, il n'y a pas de requête : `@{url}` affiche une chaîne vide et `url` dans une expression vaut `undefined`.\n\nExample: Lien actif\n```html\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n### @{hostname([path])}\n\nType: `command`\n\nAffiche l'URL absolue de la page actuelle ou d'un autre chemin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un chemin qui commence par `/`. Sans lui, le chemin de la requête actuelle. |\n\nReturns: `String` L'URL absolue.\n\n`@{hostname()}` affiche le protocole, l'hôte et le chemin de la requête actuelle, sans la query string (`https://shop.example.com/products/`). `@{hostname('/img/share.png')}` affiche le protocole et l'hôte avec le chemin donné. Elle appelle `controller.hostname()`, voir [Contrôleur](../controller/). Écris les parenthèses : `@{hostname}` seul n'appelle pas la fonction.\n\nDans `F.view()`, il n'y a pas de requête, donc elle n'affiche que `path` (ou une chaîne vide).\n\nExample: Lien canonique et image de partage\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<meta property=\"og:image\" content=\"@{hostname('/img/share.png')}\" />\n```\n\n### @{cookie(name)}\n\nType: `command`\n\nAffiche la valeur d'un cookie de la requête, encodée en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du cookie. |\n\nSans contrôleur, elle affiche une chaîne vide.\n\nExample: Lire un cookie\n```html\n<body class=\"theme-@{cookie('theme')}\">\n```\n\n### @{now}\n\nType: `command`\n\nUne nouvelle `Date` avec l'heure courante.\n\nUtilise directement les propriétés et méthodes de la date : `@{now.getFullYear()}`.\n\nExample: Copyright\n```html\n<footer>&copy; @{now.getFullYear()} @{config.name}</footer>\n```\n\n### @{root}\n\nType: `command`\n\nAffiche `CONF.$root` sans sa barre oblique finale.\n\nUtilise-la pour les liens lorsque l'application s'exécute sous un sous-chemin. Elle affiche une chaîne vide lorsque `CONF.$root` n'est pas défini.\n\nExample: Lien sous un sous-chemin\n```html\n<a href=\"@{root}/products/\">Products</a>\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\nLa condition est n'importe quelle expression JavaScript. `@{endif}` équivaut à `@{fi}`. `@{if(condition)}` avec des parenthèses fonctionne également.\n\nExample: Condition\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRépète une partie de la vue pour chaque élément d'un tableau ou d'un objet.\n\nPour un objet, chaque élément est `{ key, value }`. Une source vide n'affiche rien. `@{foreach var item in source}` fonctionne également. À l'intérieur de la boucle, `@{index}` est la position à partir de zéro, et `@{continue}` et `@{break}` sautent un élément ou arrêtent la boucle. Les boucles peuvent être imbriquées.\n\nExample: Tableau\n```html\n<ul>\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n</ul>\n```\n\nExample: Objet\n```html\n@{foreach prop in model.settings}\n\t<dt>@{prop.key}</dt><dd>@{prop.value}</dd>\n@{end}\n```\n\n### @{index}\n\nType: `command`\n\nLa position à partir de zéro de l'élément courant dans `@{foreach}`.\n\nExample: Lignes numérotées\n```html\n@{foreach row in model.rows}\n\t<tr class=\"@{index % 2 ? 'odd' : 'even'}\"><td>@{index + 1}</td><td>@{row.name}</td></tr>\n@{end}\n```\n\n### @{layout(name)}\n\nType: `command`\n\nDéfinit le layout de la 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\nLe layout par défaut est `layout` (`/views/layout.html`). Une chaîne vide effectue le rendu de la vue sans layout. La commande n'affiche rien.\n\nExample: Un autre layout\n```html\n@{layout('layout-print')}\n<h1>@{model.title}</h1>\n```\n\nExample: Sans layout\n```html\n@{layout('')}\n<div class=\"card\">@{model.name}</div>\n```\n\n### @{view(name, [model])}\n\nType: `command`\n\nEffectue le rendu d'une autre vue sur place (une vue partielle).\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\nLa vue partielle reçoit son propre modèle et aucun layout. Elle partage `repository` et les sections avec la vue qui l'affiche. Un nom qui commence par `#` lit le fichier depuis `/plugins/`.\n\nExample: Vues partielles\n```html\n@{foreach item in model.items}\n\t@{view('partials/card', item)}\n@{end}\n@{view('#blog/sidebar')}\n```\n\n### @{section name} ... @{end} / @{section(name)}\n\nType: `command`\n\nCollecte du HTML dans une vue et l'affiche à un autre endroit, généralement le layout.\n\n`@{section name}` … `@{end}` ajoute son HTML à la section ; plusieurs blocs portant le même nom sont joints. `@{section('name')}` affiche la section, ou rien lorsqu'elle est vide. La section doit être remplie avant d'être affichée, ce qui est le cas pour un layout.\n\nExample: Scripts pour le layout\n```html\n<!-- view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- layout, before </body> -->\n@{section('scripts')}\n```\n\n### view.section(name, [value], [replace])\n\nType: `method`\n\nLit ou remplit une section depuis JavaScript.\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` | Remplacer le contenu actuel. |\n\nReturns: `String|View` La section en lecture ; la vue en écriture.\n\nSans `value`, elle retourne le HTML de la section. Avec `value`, elle ajoute le HTML à la section, ou le remplace lorsque `replace` vaut `true`.\n\nExample: Remplir une section\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.section('scripts', '<script src=\"/js/page.js\"></script>');\n\t$.html(view.render('page'));\n}\n```\n\n### @{title(value)} / @{title}\n\nType: `command`\n\nDéfinit ou affiche le titre de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le titre. |\n\n`@{title('Text')}` stocke le texte dans `repository.title` et n'affiche rien. `@{title}` l'affiche encodé en HTML, `@{!title}` sans encodage.\n\nExample: Titre\n```html\n@{title('Products / ' + model.category)}\n<h1>@{title}</h1>\n```\n\n### @{title2(value)}\n\nType: `command`\n\nAjoute du texte à la fin du titre de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le texte à ajouter. |\n\nAjoute `value` à la fin de `repository.title` (ou le définit quand il n'y a pas encore de titre) et n'affiche rien. Comme pour `title()`, le texte est stocké tel quel et encodé une seule fois quand il est affiché. Une valeur vide ne change rien.\n\nExample: Titre en deux étapes\n```html\n@{title('Products')}\n@{if model}@{title2(' / ' + model.name)}@{fi}\n<h1>@{title}</h1>  <!-- Products / Pen &amp; paper -->\n```\n\n### @{description(value)} / @{description}\n\nType: `command`\n\nDéfinit ou affiche la description de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La description. |\n\nLa valeur va dans `repository.description` ; `@{import('meta')}` l'affiche sous forme de balise `<meta name=\"description\">`.\n\nExample: Description\n```html\n@{description('Pens, pencils and paper for the office.')}\n```\n\n### @{keywords(value)} / @{keywords}\n\nType: `command`\n\nDéfinit ou affiche les mots-clés de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Les mots-clés. |\n\nUn tableau est joint avec `, `. La valeur va dans `repository.keywords`.\n\nExample: Mots-clés\n```html\n@{keywords(['pens', 'paper', 'office'])}\n```\n\n### @{meta([title], [description], [keywords], [image])} / @{meta}\n\nType: `command`\n\nDéfinit en une fois le titre, la description, les mots-clés et l'image, ou affiche les balises meta.\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 URL absolue ou un chemin d'image. |\n\nAvec des arguments, elle stocke les valeurs telles quelles dans `repository` et n'affiche rien ; elles sont encodées en HTML une seule fois, quand les balises sont affichées. Sans arguments, elle affiche les mêmes balises que `@{import('meta')}` : `<title>`, les balises description et keywords, ainsi que `og:image` et `twitter:image` pour l'image. Une image relative reçoit le nom d'hôte de la requête ; sans requête, aucune balise d'image n'est affichée. Le titre reçoit ` - ` et `CONF.name` à la fin, sauf sur l'URL `/` et quand `CONF.$customtitles` vaut `true` ; sans titre, c'est `CONF.name`.\n\nExample: Définir et afficher\n```html\n<!-- view -->\n@{meta(model.name, model.summary, model.tags, model.photo)}\n\n<!-- layout -->\n<head>@{meta}</head>\n```\n\n### CONF.$customtitles\n\nType: `config`\n\nAffiche le titre de la page sans le nom de l'application.\n\nReturns: `Boolean` Par défaut `false`.\n\nPar défaut, la balise title de `@{meta}` et `@{import('meta')}` est `Title - CONF.name`. Avec `true`, le titre est affiché tel que tu l'as défini.\n\nExample: /config\n```text\n$customtitles : true\n```\n\n### @{import(name, [name2], ...)}\n\nType: `command`\n\nAffiche les balises des fichiers statiques, les balises meta ou un favicon.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom de fichier, `meta` ou un nom de favicon. |\n\nChaque argument produit une balise :\n\n- `meta` affiche les balises meta (voir `@{meta}`).\n- `favicon.ico`, `favicon.png` ou `favicon.gif` affiche une balise `<link rel=\"icon\">`.\n- Un nom en `.css` affiche un lien vers une feuille de style de `/css/`, les autres noms un script de `/js/`. Un chemin qui commence par `/` (ou une route virtuelle) est utilisé tel quel.\n- Un `@` avant le nom ajoute `?ts=` avec l'heure de démarrage de l'application.\n- Les noms joints par `+` sont fusionnés en un seul fichier minifié (voir l'entrée suivante).\n\nLes balises sont mises en cache : la commande est donc peu coûteuse.\n\nExample: En-tête d'un layout\n```html\n<head>\n\t@{import('meta', 'favicon.ico', '@default.css', 'ui.js', '/vendor/editor.js')}\n</head>\n```\n\n### @{import('a.css + b.css')}\n\nType: `command`\n\nFusionne plusieurs fichiers CSS ou JavaScript en un seul fichier minifié.\n\nLes noms joints par `+` sont fusionnés avec `MERGE()` dans un fichier au nom généré, comme `/xkcqdmatno-min.css`, que le framework sert. Un nom avec `.css` produit une feuille de style, sinon un script. Un nom de fichier est recherché dans `/public/css/` ou `/public/js/` selon son extension, un chemin qui commence par `/` dans `/public/`, et une URL est téléchargée. Un `@` au début ajoute `?ts=`.\n\nExample: Un fichier CSS et un fichier JS\n```html\n@{import('reset.css + layout.css + forms.css', '@ui.js + app.js')}\n<!-- <link rel=\"stylesheet\" href=\"/wqxjrnefjv-min.css\" /> -->\n<!-- <script src=\"/wbxyamtxmw-min.js?ts=mwi48bh6\"></script> -->\n```\n\n### @{json(value, [id], [beautify], [replacer])}\n\nType: `command`\n\nAffiche une valeur en JSON, ou dans une balise `<script type=\"application/json\">`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur. |\n| `id` | `String` | no |  | L'id de la balise script. |\n| `beautify` | `Boolean` | no | `false` | Indenter le JSON. |\n| `replacer` | `Function|Boolean` | no |  | Un replacer pour `JSON.stringify()`. |\n\nAvec `id`, le JSON est enveloppé dans une balise script ayant cet `id`, que le code client lit sans seconde requête. `beautify` indente le JSON avec quatre espaces. `replacer` est une fonction pour `JSON.stringify()`, ou `true` pour le replacer du framework. `@{json(value, true)}` équivaut à `@{json(value, null, true)}`.\n\nExample: Données pour le client\n```html\n@{json(model.products, 'products')}\n<script>\n\tvar products = JSON.parse(document.getElementById('products').innerHTML);\n</script>\n```\n\n### @{href([key], [value])}\n\nType: `command`\n\nAffiche la query string courante avec un paramètre modifié.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | Le nom du paramètre, ou un objet avec les paramètres à définir. |\n| `value` | `Any` | no |  | La nouvelle valeur. |\n\nReturns: `String` La query string avec `?`, ou une chaîne vide.\n\n`@{href}` affiche la query string courante (`?page=2&sort=name`). `@{href('page', 3)}` l'affiche avec `page` défini à `3` ; sans valeur, la valeur actuelle est conservée. Les arguments supplémentaires après la valeur sont des noms de paramètres à supprimer. Une valeur tableau écrit le paramètre une fois pour chaque élément (`tag=a&tag=b`) et une valeur objet est écrite en JSON. `@{href({ page: 3, sort: 'price' })}` renvoie l'URL de la requête avec la query string modifiée par les clés de l'objet. Utilise-la pour les liens de pagination et de tri.\n\nExample: Pagination\n```html\n<a href=\"@{href('page', model.page - 1)}\">Previous</a>\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\nExample: Supprimer un paramètre, ou en modifier plusieurs\n```html\n<!-- /products/?page=2&sort=name&q=pen -->\n<a href=\"@{href('page', 1, 'sort')}\">First page</a>  <!-- ?page=1&q=pen -->\n<a href=\"@{href({ page: 1, sort: 'price' })}\">By price</a>  <!-- /products/?page=1&sort=price&q=pen -->\n```\n\n### DEF.helpers\n\nType: `property`\n\nFonctions personnalisées que tu appelles depuis chaque vue.\n\nReturns: `Object`\n\nAjoute des fonctions à l'objet ; à l'intérieur d'un helper, `this` est la vue (`this.model`, `this.repository`, `this.controller`). Appelle un helper par son nom (`@{price(10)}`), avec `@{helpers.price(10)}` ou avec `@{helper('price', 10)}`. La valeur retournée est affichée sans encodage. Enregistre les helpers avant la compilation des vues, par exemple dans `/definitions/`.\n\nExample: Enregistrer et utiliser\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\n// in a view: <span>@{price(model.price, 'USD')}</span>\n```\n\n### @{helper(name, [arg1], [arg2], ...)}\n\nType: `command`\n\nAppelle un helper de `DEF.helpers` par son nom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du helper. |\n\nLes autres arguments sont transmis au helper. Elle affiche une chaîne vide lorsque le helper n'existe pas.\n\nExample: Appeler un helper\n```html\n<span>@{helper('price', model.price, 'EUR')}</span>\n```\n\n### @(text)\n\nType: `command`\n\nTraduit un texte dans la langue de la vue.\n\nLe texte est remplacé par sa traduction issue des fichiers de ressources lors de la compilation de la vue ; un texte sans traduction reste tel quel. Le guide [Localisation](../../guides/localization/) explique les ressources.\n\nExample: Texte traduit\n```html\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n### @{compile [name]} ... @{end}\n\nType: `command`\n\nTransmet une partie de la vue à `DEF.onViewCompile` à chaque rendu.\n\nLe HTML entre les balises, avec les commandes déjà évaluées, est transmis à `DEF.onViewCompile(name, html, model)`, et son résultat est affiché. Utilise-la pour appliquer Markdown ou un autre processeur à une partie de la vue.\n\nExample: Markdown\n```html\n@{compile markdown}\n# @{model.title}\n\n@{model.text}\n@{end}\n```\n\n### DEF.onViewCompile = function(name, html, model)\n\nType: `delegate`\n\nTraite le contenu des blocs `@{compile}`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du bloc, ou une chaîne vide. |\n| `html` | `String` | yes |  | Le contenu du bloc. |\n| `model` | `Object` | yes |  | Le modèle de la vue. |\n\nReturns: `String` Le HTML à afficher.\n\n`name` est le mot après `@{compile`, `html` le contenu rendu du bloc et `model` le modèle de la vue. Retourne le HTML à afficher. Par défaut, elle retourne `html` inchangé.\n\nExample: Blocs Markdown\n```js\nDEF.onViewCompile = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\n### ON('$view', function(meta) {})\n\nType: `event`\n\nModifie la source d'une vue avant sa compilation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, body, debug }`. |\n\n`meta.name` est le nom de la vue, `meta.body` sa source HTML et `meta.debug` le mode debug. Modifie `meta.body` pour modifier la vue ; l'événement s'exécute à chaque compilation d'une vue.\n\nExample: Remplacer un placeholder\n```js\nON('$view', function(meta) {\n\tmeta.body = meta.body.replace(/\\{year\\}/g, new Date().getFullYear() + '');\n});\n```\n\n### @{nocompress html|js|css|all}\n\nType: `command`\n\nDésactive une étape de compression pour la vue.\n\nÀ la compilation d'une vue, les suites d'espaces dans son texte sont réduites (les retours à la ligne et l'indentation entre les balises sont conservés), et le CSS des balises `<style>` et le JavaScript des balises `<script>` sont minifiés. `html` garde le HTML tel quel et désactive aussi la minification de la réponse ; `js` (ou `script`, `javascript`) et `css` (ou `style`) conservent le code inline ; `all` désactive les trois. Les commentaires HTML sont toujours retirés.\n\nExample: Conserver les espaces\n```html\n@{nocompress html}\n<pre>\n  formatted\n    text\n</pre>\n```\n\n### @{{ text }}\n\nType: `command`\n\nAffiche `@{{ ... }}` tel quel, sans l'exécuter.\n\nUtilise-la pour conserver le texte `@{{ }}` destiné aux templates côté client.\n\nExample: Texte littéral\n```html\n<code>@{{ value }}</code>\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nEffectue le rendu d'un template Tangular et retourne une promesse avec le HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Le template, une URL, un chemin ou le nom d'un fichier dans `/templates/`. |\n| `model` | `Object` | no |  | Le modèle, disponible sous `value`. |\n| `$` | `Options` | no |  | Le `$` d'une action ou d'un contrôleur, pour la langue et la gestion des erreurs. |\n\nReturns: `Promise<String>` Le HTML rendu.\n\n`body` est le texte du template lorsqu'il contient `{{`. Sinon, c'est une URL (`http://` ou `https://`, téléchargée), `~` suivi d'un chemin absolu, `#` suivi du chemin d'un fichier dans `/plugins/` (`.html` est ajouté s'il manque), ou le nom d'un fichier dans `/templates/` (`.html` est ajouté s'il manque). Dans le template, le modèle est `value`.\n\nLe template peut contenir un bloc `<script type=\"text/json\">` avec un modèle par défaut, utilisé quand `model` n'est pas fourni, et un bloc `<script>` qui ajoute des helpers à `Thelpers`. Avec `$` (le `$` d'une route ou d'une action), le template est traduit dans `$.language`, et les erreurs vont à `$.invalid()` au lieu de rejeter la promesse. Les templates lus depuis des fichiers sont mis en cache en mode release.\n\nExample: Template inline\n```js\nvar html = await TEMPLATE('<p>Hello {{ value.name }}</p>', { name: 'Peter' });\n```\n\nExample: Un fichier dans une route\n```js\nexports.install = function() {\n\tROUTE('GET /invoice/{id}/', invoice);\n};\n\nfunction invoice($) {\n\tTEMPLATE('invoice', { number: $.params.id }, $).then(function(html) {\n\t\t$.html(html);\n\t});\n}\n```\n\n### {{ value }} / {{ if }} / {{ foreach }}\n\nType: `command`\n\nLes commandes des templates Tangular utilisés par `TEMPLATE()`.\n\n`{{ value.name }}` affiche une valeur encodée en HTML. `{{ if condition }}` … `{{ else if condition }}` … `{{ else }}` … `{{ fi }}` est une condition. `{{ foreach item in value.items }}` … `{{ end }}` est une boucle avec `{{ $index }}`, `{{ continue }}` et `{{ break }}`. Une valeur passe par des helpers avec `|` : `{{ value.html | raw }}`.\n\nExample: Facture\n```html\n<h1>Invoice {{ value.number }}</h1>\n{{ if value.items.length }}\n<table>\n\t{{ foreach item in value.items }}\n\t<tr><td>{{ $index + 1 }}</td><td>{{ item.name }}</td><td>{{ item.price | format(2) }}</td></tr>\n\t{{ end }}\n</table>\n{{ else }}\n<p>No items</p>\n{{ fi }}\n```\n\n### Thelpers\n\nType: `property`\n\nLes helpers des templates Tangular.\n\nReturns: `Object`\n\nHelpers intégrés : `encode` (la valeur par défaut pour chaque valeur ; `encode('json')`, `encode('url')` changent le format), `raw` (pas d'encodage), `format(...)` (nombres et dates, comme `Number.format()` et `Date.format()`), `def(text)` ou `empty(text)` (affiche `text`, ou `---`, pour une valeur vide) et `pluralize(zero, one, few, other)`. Ajoute les tiens dans `Thelpers`, globalement ou dans le bloc `<script>` d'un fichier de template ; `this` est l'objet qui contient le modèle dans `value`.\n\nExample: Un fichier template avec un helper et un modèle par défaut\n```html\n<script type=\"text/json\">{ \"name\": \"Guest\" }</script>\n<script>\nThelpers.upper = function(value) {\n\treturn (value || '').toUpperCase();\n};\n</script>\n<h1>{{ value.name | upper }}</h1>\n<p>{{ value.count | pluralize('# items', '# item', '# items', '# items') }}</p>\n<p>{{ value.date | format('yyyy-MM-dd') }} {{ value.note | def('none') }}</p>\n```\n","entries":[{"type":"method","name":"controller.view()","signature":"controller.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"F.view()","signature":"F.view(name, [model], [prepare])","since":"","deprecated":false},{"type":"class","name":"View","signature":"new F.TViewEngine.View([controller])","since":"","deprecated":false},{"type":"method","name":"view.render()","signature":"view.render(name, [model])","since":"","deprecated":false},{"type":"property","name":"view.repository","signature":"view.repository","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository}","since":"","deprecated":false},{"type":"command","name":"@{config}","signature":"@{config.key} / @{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{query}","signature":"@{query} / @{body} / @{files} / @{user} / @{session} / @{controller}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}","since":"","deprecated":false},{"type":"command","name":"@{hostname()}","signature":"@{hostname([path])}","since":"","deprecated":false},{"type":"command","name":"@{cookie()}","signature":"@{cookie(name)}","since":"","deprecated":false},{"type":"command","name":"@{now}","signature":"@{now}","since":"","deprecated":false},{"type":"command","name":"@{root}","signature":"@{root}","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":"@{index}","signature":"@{index}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end} / @{section(name)}","since":"","deprecated":false},{"type":"method","name":"view.section()","signature":"view.section(name, [value], [replace])","since":"","deprecated":false},{"type":"command","name":"@{title()}","signature":"@{title(value)} / @{title}","since":"","deprecated":false},{"type":"command","name":"@{title2()}","signature":"@{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} / @{description}","since":"","deprecated":false},{"type":"command","name":"@{keywords()}","signature":"@{keywords(value)} / @{keywords}","since":"","deprecated":false},{"type":"command","name":"@{meta()}","signature":"@{meta([title], [description], [keywords], [image])} / @{meta}","since":"","deprecated":false},{"type":"config","name":"CONF.$customtitles","signature":"CONF.$customtitles","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(name, [name2], ...)}","since":"","deprecated":false},{"type":"command","name":"Merging files","signature":"@{import('a.css + b.css')}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify], [replacer])}","since":"","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href([key], [value])}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers","since":"","deprecated":false},{"type":"command","name":"@{helper()}","signature":"@{helper(name, [arg1], [arg2], ...)}","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile [name]} ... @{end}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onViewCompile","signature":"DEF.onViewCompile = function(name, html, model)","since":"","deprecated":false},{"type":"event","name":"ON('$view')","signature":"ON('$view', function(meta) {})","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|js|css|all}","since":"","deprecated":false},{"type":"command","name":"@{{ }}","signature":"@{{ text }}","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"command","name":"Template commands","signature":"{{ value }} / {{ if }} / {{ foreach }}","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwth3Dx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/views/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Viste","summary":"I comandi delle viste, l'oggetto vista, gli helper e TEMPLATE().","markdown":"---\ntitle: Viste\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/views/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Viste\n\n> I comandi delle viste, l'oggetto vista, gli helper e TEMPLATE().\n\nLe viste sono file HTML in `/views/` con comandi `@{...}`, renderizzati da `controller.view()` e `F.view()`. Questa pagina elenca ogni comando, i metodi dell'oggetto vista, gli helper e `TEMPLATE()`. La guida [Viste](../../guides/views/) spiega come funzionano insieme, con esempi.\n\n## API\n\n### controller.view([name], [model])\n\nType: `method`\n\nRenderizza una vista e la invia come risposta HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Il nome della vista senza `.html`, ad esempio `products/detail`. |\n| `model` | `Object` | no |  | Il modello, disponibile come `model` nella vista. |\n\nReturns: `View` L'oggetto vista.\n\nLa vista viene letta da `/views/{name}.html`, o da `/plugins/` quando il nome inizia con `#`. Viene renderizzata nel layout impostato con `controller.layout()` (o `layout` di default) e inviata con `controller.html()`. Senza nome il metodo restituisce soltanto un nuovo oggetto vista, che renderizzi tu stesso.\n\nExample: Renderizzare una vista\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail($) {\n\tvar id = $.params.id;\n\t$.view('products/detail', { id: id });\n}\n```\n\nExample: Renderizzarla da sé\n```js\nfunction preview($) {\n\tvar view = $.view();\n\tview.layout('');\n\t$.html(view.render('preview', { name: 'Test' }));\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nImposta il layout per il prossimo `controller.view()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della vista di layout. |\n\nChiamalo prima di `controller.view()`. Una stringa vuota mantiene il layout predefinito; per una vista senza layout usa `@{layout('')}` nella vista o `view.layout('')`. Una vista può comunque cambiarlo con `@{layout()}`.\n\nExample: Usare un altro layout\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('admin/index');\n}\n```\n\n### F.view(name, [model], [prepare])\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| `prepare` | `Function` | no |  | `function(view)` chiamata prima del rendering, per impostare `view.language`, `view.repository` o il layout. |\n\nReturns: `String` L'HTML renderizzato.\n\nLa vista non ha un controller, quindi `controller`, `user`, `query` e gli altri valori della richiesta sono vuoti. La vista viene renderizzata nel suo layout come al solito; usa `@{layout('')}` nella vista, o `view.layout('')` in `prepare`, per un frammento senza layout.\n\nExample: Renderizzare il corpo di un'e-mail\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n\tview.layout('');\n});\n```\n\n### new F.TViewEngine.View([controller])\n\nType: `class`\n\nL'oggetto che renderizza una vista; è `self` all'interno della vista compilata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | no |  | Il controller della richiesta. |\n\n`controller.view()` e `F.view()` lo creano per te. Le sue proprietà sono `controller`, `model`, `repository` (`{ layout: 'layout' }` all'inizio), `language`, `url` e `query`. I suoi metodi sono i comandi della vista: `layout()`, `title()`, `description()`, `keywords()`, `meta()`, `json()`, `href()`, `import()`, `section()`, `helper()`, `hostname()` e `view()`.\n\nExample: Impostare valori prima del rendering\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.repository.menu = 'products';\n\t$.html(view.render('products', { items: [] }));\n}\n```\n\n### view.render(name, [model])\n\nType: `method`\n\nRenderizza una vista con il suo layout 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\nReturns: `String` L'HTML.\n\nIl file è `/views/{name}.html` (o `/plugins/{name}.html` per un nome con `#`). Quando `repository.layout` non è vuoto, il risultato viene renderizzato in quel layout.\n\nExample: Rendering\n```js\nvar view = new F.TViewEngine.View();\nview.layout('');\nvar html = view.render('fragments/card', { name: 'Pen' });\n```\n\n### view.repository\n\nType: `property`\n\nUn oggetto condiviso dalla vista, dalle sue viste parziali e dal layout.\n\nReturns: `Object`\n\nContiene `layout`, `title`, `description`, `keywords`, le sezioni (`section_{name}`) e tutti i valori che aggiungi. Nella vista è la variabile `repository`. Usalo per passare valori da una vista al suo layout.\n\nExample: Dalla vista al layout\n```html\n<!-- view -->\n@{repository.menu = 'products'}\n\n<!-- layout -->\n<nav class=\"@{repository.menu}\">...</nav>\n```\n\n### view.language\n\nType: `property`\n\nLa lingua usata per le traduzioni `@(...)`.\n\nReturns: `String`\n\nÈ la lingua della richiesta in `controller.view()` e una stringa vuota in `F.view()`. Impostala prima del rendering; ogni lingua ha la sua copia compilata della vista, e `@{language}` la stampa.\n\nExample: Lingua in F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{expression}\n\nType: `command`\n\nStampa il valore di un'espressione JavaScript, con codifica HTML.\n\nFunziona qualsiasi espressione: proprietà, chiamate di metodi, operatori. `null` e `undefined` vengono stampati come stringa vuota. Un'assegnazione (`=`, `+=`, `++`…) a `model`, `repository`, `config`, `query`, `user`, `session` o `controller` viene valutata e non stampa nulla. `@{print(...)}` e `@{console.log(...)}` non stampano nulla nell'HTML.\n\nExample: Valori\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} items</p>\n<p>@{model.price.format(2)}</p>\n@{repository.count = model.items.length}\n```\n\n### @{!expression}\n\nType: `command`\n\nStampa il valore di un'espressione senza codifica HTML.\n\nUsalo per HTML di cui ti fidi, ad esempio contenuti di un CMS salvati dai tuoi amministratori.\n\nExample: HTML grezzo\n```html\n<article>@{!model.body}</article>\n```\n\n### @{model}\n\nType: `command`\n\nIl modello passato alla vista.\n\nÈ il secondo argomento di `controller.view()`, `F.view()`, `view.render()` o `@{view()}`. Il layout non riceve il modello.\n\nExample: Leggere il modello\n```html\n<h1>@{model.title}</h1>\n@{if model.user}<p>@{model.user.name}</p>@{fi}\n```\n\n### @{repository}\n\nType: `command`\n\nL'oggetto condiviso della vista, delle sue viste parziali e del layout.\n\nVedi `view.repository`. Assegna valori con `@{repository.key = value}`; l'assegnazione non stampa nulla.\n\nExample: Impostare e leggere\n```html\n@{repository.menu = 'contact'}\n<li class=\"@{repository.menu === 'contact' ? 'active' : ''}\">Contact</li>\n```\n\n### @{config.key} / @{'%key'}\n\nType: `command`\n\nStampa un valore di configurazione.\n\n`config` è `CONF`, letto a ogni rendering. `@{'%key'}` legge il valore una sola volta, quando la vista viene compilata, e lo inserisce nella vista come testo.\n\nExample: Configurazione\n```html\n<title>@{config.name}</title>\n<footer>@{'%name'} @{config.version}</footer>\n```\n\n### @{query} / @{body} / @{files} / @{user} / @{session} / @{controller}\n\nType: `command`\n\nI dati della richiesta corrente.\n\n`query` è la query string interpretata, `body` il body interpretato, `files` i file caricati, `user` e `session` i valori della tua autorizzazione, e `controller` il controller stesso. In `F.view()` sono vuoti. In un layout, `@{body}` senza proprietà stampa invece l'HTML della vista.\n\nExample: Valori della richiesta\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{else}\n\t<a href=\"/login/\">Sign in</a>\n@{fi}\n<input name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{body}\n\nType: `command`\n\nIn un layout, stampa l'HTML della vista renderizzata.\n\nL'output non viene codificato. Con una proprietà (`@{body.name}`) legge invece il body della richiesta.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>@{import('meta')}</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{language}\n\nType: `command`\n\nLa lingua della vista.\n\nLa lingua della vista (`view.language`): la lingua della richiesta (`controller.language`) in `controller.view()`, il valore che imposti nella funzione `prepare` di `F.view()`, e una stringa vuota per impostazione predefinita.\n\nExample: Attributo lang\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\nExample: In F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n// <html lang=\"de\">\n```\n\n### @{url}\n\nType: `command`\n\nIl percorso URL della richiesta corrente.\n\nÈ `controller.url`, il percorso così come è stato richiesto (mantenendo maiuscole e minuscole) con una barra finale e senza la query string. `url` funziona anche dentro espressioni e condizioni: `@{if url === '/'}`. In `F.view()` non c'è una richiesta: `@{url}` stampa una stringa vuota e `url` in un'espressione è `undefined`.\n\nExample: Link attivo\n```html\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n### @{hostname([path])}\n\nType: `command`\n\nStampa l'URL assoluto della pagina corrente o di un altro percorso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un percorso che inizia con `/`. Senza di esso, il percorso della richiesta corrente. |\n\nReturns: `String` L'URL assoluto.\n\n`@{hostname()}` stampa il protocollo, l'host e il percorso della richiesta corrente, senza la query string (`https://shop.example.com/products/`). `@{hostname('/img/share.png')}` stampa il protocollo e l'host con il percorso indicato. Chiama `controller.hostname()`, vedi [Controller](../controller/). Scrivi le parentesi: `@{hostname}` da solo non chiama la funzione.\n\nIn `F.view()` non c'è una richiesta, quindi stampa solo `path` (oppure una stringa vuota).\n\nExample: Link canonico e immagine di condivisione\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<meta property=\"og:image\" content=\"@{hostname('/img/share.png')}\" />\n```\n\n### @{cookie(name)}\n\nType: `command`\n\nStampa il valore di un cookie della richiesta, con codifica HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del cookie. |\n\nSenza controller stampa una stringa vuota.\n\nExample: Leggere un cookie\n```html\n<body class=\"theme-@{cookie('theme')}\">\n```\n\n### @{now}\n\nType: `command`\n\nUna nuova `Date` con l'ora corrente.\n\nUsa direttamente proprietà e metodi della data: `@{now.getFullYear()}`.\n\nExample: Copyright\n```html\n<footer>&copy; @{now.getFullYear()} @{config.name}</footer>\n```\n\n### @{root}\n\nType: `command`\n\nStampa `CONF.$root` senza lo slash finale.\n\nUsalo per i link quando l'applicazione gira sotto un sottopercorso. Stampa una stringa vuota quando `CONF.$root` non è impostato.\n\nExample: Link sotto un sottopercorso\n```html\n<a href=\"@{root}/products/\">Products</a>\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\nLa condizione è una qualsiasi espressione JavaScript. `@{endif}` equivale a `@{fi}`. Funziona anche `@{if(condition)}` con le parentesi.\n\nExample: Condizione\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRipete una parte della vista per ogni elemento di un array o di un oggetto.\n\nPer un oggetto, ogni elemento è `{ key, value }`. Una sorgente vuota non renderizza nulla. Funziona anche `@{foreach var item in source}`. All'interno del ciclo, `@{index}` è la posizione a partire da zero, e `@{continue}` e `@{break}` saltano un elemento o interrompono il ciclo. I cicli possono essere annidati.\n\nExample: Array\n```html\n<ul>\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n</ul>\n```\n\nExample: Oggetto\n```html\n@{foreach prop in model.settings}\n\t<dt>@{prop.key}</dt><dd>@{prop.value}</dd>\n@{end}\n```\n\n### @{index}\n\nType: `command`\n\nLa posizione, a partire da zero, dell'elemento corrente in `@{foreach}`.\n\nExample: Righe numerate\n```html\n@{foreach row in model.rows}\n\t<tr class=\"@{index % 2 ? 'odd' : 'even'}\"><td>@{index + 1}</td><td>@{row.name}</td></tr>\n@{end}\n```\n\n### @{layout(name)}\n\nType: `command`\n\nImposta il layout della vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della vista di layout, oppure una stringa vuota. |\n\nIl layout predefinito è `layout` (`/views/layout.html`). Una stringa vuota renderizza la vista senza layout. Il comando non stampa nulla.\n\nExample: Un altro layout\n```html\n@{layout('layout-print')}\n<h1>@{model.title}</h1>\n```\n\nExample: Nessun layout\n```html\n@{layout('')}\n<div class=\"card\">@{model.name}</div>\n```\n\n### @{view(name, [model])}\n\nType: `command`\n\nRenderizza un'altra vista sul posto (una vista parziale).\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\nLa vista parziale riceve il proprio modello e nessun layout. Condivide `repository` e le sezioni con la vista che la renderizza. Un nome che inizia con `#` legge il file da `/plugins/`.\n\nExample: Viste parziali\n```html\n@{foreach item in model.items}\n\t@{view('partials/card', item)}\n@{end}\n@{view('#blog/sidebar')}\n```\n\n### @{section name} ... @{end} / @{section(name)}\n\nType: `command`\n\nRaccoglie HTML in una vista e lo stampa in un altro punto, di solito il layout.\n\n`@{section name}` … `@{end}` aggiunge il suo HTML alla sezione; più blocchi con lo stesso nome vengono uniti. `@{section('name')}` stampa la sezione, o nulla quando è vuota. La sezione deve essere riempita prima di essere stampata, come avviene per un layout.\n\nExample: Script per il layout\n```html\n<!-- view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- layout, before </body> -->\n@{section('scripts')}\n```\n\n### view.section(name, [value], [replace])\n\nType: `method`\n\nLegge o riempie una sezione da JavaScript.\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 corrente. |\n\nReturns: `String|View` La sezione in lettura; la vista in scrittura.\n\nSenza `value` restituisce l'HTML della sezione. Con `value` aggiunge l'HTML alla sezione, o lo sostituisce quando `replace` è `true`.\n\nExample: Riempire una sezione\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.section('scripts', '<script src=\"/js/page.js\"></script>');\n\t$.html(view.render('page'));\n}\n```\n\n### @{title(value)} / @{title}\n\nType: `command`\n\nImposta o stampa il titolo della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il titolo. |\n\n`@{title('Text')}` salva il testo in `repository.title` e non stampa nulla. `@{title}` lo stampa codificato in HTML, `@{!title}` senza codifica.\n\nExample: Titolo\n```html\n@{title('Products / ' + model.category)}\n<h1>@{title}</h1>\n```\n\n### @{title2(value)}\n\nType: `command`\n\nAggiunge del testo al titolo della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il testo da aggiungere. |\n\nAggiunge `value` alla fine di `repository.title` (o lo imposta quando non c'è ancora un titolo) e non stampa nulla. Come per `title()`, il testo viene salvato così com'è e codificato una sola volta quando viene stampato. Un valore vuoto non cambia nulla.\n\nExample: Titolo in due passaggi\n```html\n@{title('Products')}\n@{if model}@{title2(' / ' + model.name)}@{fi}\n<h1>@{title}</h1>  <!-- Products / Pen &amp; paper -->\n```\n\n### @{description(value)} / @{description}\n\nType: `command`\n\nImposta o stampa la descrizione della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La descrizione. |\n\nIl valore va in `repository.description`; `@{import('meta')}` lo stampa come tag `<meta name=\"description\">`.\n\nExample: Descrizione\n```html\n@{description('Pens, pencils and paper for the office.')}\n```\n\n### @{keywords(value)} / @{keywords}\n\nType: `command`\n\nImposta o stampa le parole chiave della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Le parole chiave. |\n\nUn array viene unito con `, `. Il valore va in `repository.keywords`.\n\nExample: Parole chiave\n```html\n@{keywords(['pens', 'paper', 'office'])}\n```\n\n### @{meta([title], [description], [keywords], [image])} / @{meta}\n\nType: `command`\n\nImposta insieme titolo, descrizione, parole chiave e immagine, o stampa i meta tag.\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 |  | Le parole chiave. |\n| `image` | `String` | no |  | Un URL assoluto o un percorso di un'immagine. |\n\nCon argomenti salva i valori in `repository` così come sono e non stampa nulla; vengono codificati in HTML una sola volta, quando i tag vengono stampati. Senza argomenti stampa gli stessi tag di `@{import('meta')}`: `<title>`, i tag della descrizione e delle parole chiave, e `og:image` e `twitter:image` per l'immagine. Un'immagine relativa riceve il nome host della richiesta; senza richiesta non viene stampato nessun tag dell'immagine. Al titolo vengono aggiunti ` - ` e `CONF.name`, tranne sull'URL `/` e quando `CONF.$customtitles` è `true`; senza titolo è `CONF.name`.\n\nExample: Impostare e stampare\n```html\n<!-- view -->\n@{meta(model.name, model.summary, model.tags, model.photo)}\n\n<!-- layout -->\n<head>@{meta}</head>\n```\n\n### CONF.$customtitles\n\nType: `config`\n\nStampa il titolo della pagina senza il nome dell'applicazione.\n\nReturns: `Boolean` Default `false`.\n\nDi default il tag title di `@{meta}` e `@{import('meta')}` è `Title - CONF.name`. Con `true` il titolo viene stampato così come lo imposti.\n\nExample: /config\n```text\n$customtitles : true\n```\n\n### @{import(name, [name2], ...)}\n\nType: `command`\n\nStampa i tag per i file statici, i meta tag o una favicon.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome di file, `meta` o il nome di una favicon. |\n\nOgni argomento produce un tag:\n\n- `meta` stampa i meta tag (vedi `@{meta}`).\n- `favicon.ico`, `favicon.png` o `favicon.gif` stampa un tag `<link rel=\"icon\">`.\n- Un nome con `.css` stampa un link a un foglio di stile da `/css/`, gli altri nomi uno script da `/js/`. Un percorso che inizia con `/` (o una route virtuale) viene usato così com'è.\n- Una `@` prima del nome aggiunge `?ts=` con l'orario di avvio dell'applicazione.\n- I nomi uniti con `+` vengono fusi in un unico file minificato (vedi la voce successiva).\n\nI tag sono in cache, quindi il comando è poco costoso.\n\nExample: Head di un layout\n```html\n<head>\n\t@{import('meta', 'favicon.ico', '@default.css', 'ui.js', '/vendor/editor.js')}\n</head>\n```\n\n### @{import('a.css + b.css')}\n\nType: `command`\n\nUnisce più file CSS o JavaScript in un unico file minificato.\n\nI nomi uniti con `+` vengono uniti con `MERGE()` in un file con un nome generato, come `/xkcqdmatno-min.css`, che il framework serve. Un nome con `.css` produce un foglio di stile, altrimenti uno script. Un nome di file viene cercato in `/public/css/` o `/public/js/` in base alla sua estensione, un percorso che inizia con `/` in `/public/`, e un URL viene scaricato. Una `@` all'inizio aggiunge `?ts=`.\n\nExample: Un file CSS e un file JS\n```html\n@{import('reset.css + layout.css + forms.css', '@ui.js + app.js')}\n<!-- <link rel=\"stylesheet\" href=\"/wqxjrnefjv-min.css\" /> -->\n<!-- <script src=\"/wbxyamtxmw-min.js?ts=mwi48bh6\"></script> -->\n```\n\n### @{json(value, [id], [beautify], [replacer])}\n\nType: `command`\n\nStampa un valore come JSON, o in un tag `<script type=\"application/json\">`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore. |\n| `id` | `String` | no |  | L'id del tag script. |\n| `beautify` | `Boolean` | no | `false` | Indenta il JSON. |\n| `replacer` | `Function|Boolean` | no |  | Un replacer per `JSON.stringify()`. |\n\nCon `id` il JSON viene racchiuso in un tag script con quell'`id`, che il codice client legge senza una seconda richiesta. `beautify` indenta il JSON con quattro spazi. `replacer` è una funzione per `JSON.stringify()`, oppure `true` per il replacer del framework. `@{json(value, true)}` equivale a `@{json(value, null, true)}`.\n\nExample: Dati per il client\n```html\n@{json(model.products, 'products')}\n<script>\n\tvar products = JSON.parse(document.getElementById('products').innerHTML);\n</script>\n```\n\n### @{href([key], [value])}\n\nType: `command`\n\nStampa la query string corrente con un parametro modificato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | Il nome del parametro, o un oggetto con i parametri da impostare. |\n| `value` | `Any` | no |  | Il nuovo valore. |\n\nReturns: `String` La query string con `?`, o una stringa vuota.\n\n`@{href}` stampa la query string corrente (`?page=2&sort=name`). `@{href('page', 3)}` la stampa con `page` impostato a `3`; senza valore viene mantenuto il valore attuale. Altri argomenti dopo il valore sono nomi di parametri da rimuovere. Un valore array scrive il parametro una volta per ogni elemento (`tag=a&tag=b`) e un valore oggetto viene scritto come JSON. `@{href({ page: 3, sort: 'price' })}` restituisce l'URL della richiesta con la query string modificata dalle chiavi dell'oggetto. Usalo per i link di paginazione e di ordinamento.\n\nExample: Paginazione\n```html\n<a href=\"@{href('page', model.page - 1)}\">Previous</a>\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\nExample: Rimuovere un parametro o modificarne diversi\n```html\n<!-- /products/?page=2&sort=name&q=pen -->\n<a href=\"@{href('page', 1, 'sort')}\">First page</a>  <!-- ?page=1&q=pen -->\n<a href=\"@{href({ page: 1, sort: 'price' })}\">By price</a>  <!-- /products/?page=1&sort=price&q=pen -->\n```\n\n### DEF.helpers\n\nType: `property`\n\nFunzioni personalizzate che chiami da ogni vista.\n\nReturns: `Object`\n\nAggiungi funzioni all'oggetto; all'interno di un helper `this` è la vista (`this.model`, `this.repository`, `this.controller`). Chiama un helper con il suo nome (`@{price(10)}`), con `@{helpers.price(10)}` o con `@{helper('price', 10)}`. Il valore restituito viene stampato senza codifica. Registra gli helper prima che le viste vengano compilate, ad esempio in `/definitions/`.\n\nExample: Registrare e usare\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\n// in a view: <span>@{price(model.price, 'USD')}</span>\n```\n\n### @{helper(name, [arg1], [arg2], ...)}\n\nType: `command`\n\nChiama un helper di `DEF.helpers` con il suo nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'helper. |\n\nGli altri argomenti vanno all'helper. Stampa una stringa vuota quando l'helper non esiste.\n\nExample: Chiamare un helper\n```html\n<span>@{helper('price', model.price, 'EUR')}</span>\n```\n\n### @(text)\n\nType: `command`\n\nTraduce un testo nella lingua della vista.\n\nIl testo viene sostituito dalla sua traduzione presa dai file di risorse quando la vista viene compilata; un testo senza traduzione resta com'è. La guida [Localizzazione](../../guides/localization/) spiega le risorse.\n\nExample: Testo tradotto\n```html\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n### @{compile [name]} ... @{end}\n\nType: `command`\n\nPassa una parte della vista a `DEF.onViewCompile` a ogni rendering.\n\nL'HTML tra i tag, con i comandi già valutati, viene passato a `DEF.onViewCompile(name, html, model)`, e il suo risultato viene stampato. Usalo per eseguire Markdown o un altro processore su una parte della vista.\n\nExample: Markdown\n```html\n@{compile markdown}\n# @{model.title}\n\n@{model.text}\n@{end}\n```\n\n### DEF.onViewCompile = function(name, html, model)\n\nType: `delegate`\n\nElabora il contenuto dei blocchi `@{compile}`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del blocco, o una stringa vuota. |\n| `html` | `String` | yes |  | Il contenuto del blocco. |\n| `model` | `Object` | yes |  | Il modello della vista. |\n\nReturns: `String` L'HTML da stampare.\n\n`name` è la parola dopo `@{compile`, `html` il contenuto renderizzato del blocco e `model` il modello della vista. Restituisci l'HTML da stampare. Di default restituisce `html` invariato.\n\nExample: Blocchi Markdown\n```js\nDEF.onViewCompile = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\n### ON('$view', function(meta) {})\n\nType: `event`\n\nModifica il sorgente di una vista prima che venga compilata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, body, debug }`. |\n\n`meta.name` è il nome della vista, `meta.body` il suo sorgente HTML e `meta.debug` la modalità debug. Modifica `meta.body` per modificare la vista; l'evento viene eseguito ogni volta che una vista viene compilata.\n\nExample: Sostituire un segnaposto\n```js\nON('$view', function(meta) {\n\tmeta.body = meta.body.replace(/\\{year\\}/g, new Date().getFullYear() + '');\n});\n```\n\n### @{nocompress html|js|css|all}\n\nType: `command`\n\nDisattiva un passaggio di compressione per la vista.\n\nQuando una vista viene compilata, le sequenze di spazi nel suo testo vengono ridotte (le interruzioni di riga e l'indentazione tra i tag vengono mantenute), e il CSS dei tag `<style>` e il JavaScript dei tag `<script>` vengono minificati. `html` mantiene l'HTML così com'è e disattiva anche la minificazione della risposta; `js` (o `script`, `javascript`) e `css` (o `style`) mantengono il codice inline; `all` li disattiva tutti e tre. I commenti HTML vengono sempre rimossi.\n\nExample: Mantenere gli spazi\n```html\n@{nocompress html}\n<pre>\n  formatted\n    text\n</pre>\n```\n\n### @{{ text }}\n\nType: `command`\n\nStampa `@{{ ... }}` così com'è, senza eseguirlo.\n\nUsalo per mantenere il testo `@{{ }}` per i template lato client.\n\nExample: Testo letterale\n```html\n<code>@{{ value }}</code>\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nRenderizza un template Tangular e restituisce una promise con l'HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Il template, un URL, un percorso o il nome di un file in `/templates/`. |\n| `model` | `Object` | no |  | Il modello, disponibile come `value`. |\n| `$` | `Options` | no |  | Il `$` di un'azione o di un controller, per la lingua e la gestione degli errori. |\n\nReturns: `Promise<String>` L'HTML renderizzato.\n\n`body` è il testo del template quando contiene `{{`. Altrimenti è un URL (`http://` o `https://`, scaricato), `~` e un percorso assoluto, `#` e un percorso di un file in `/plugins/` (`.html` viene aggiunto se manca), oppure il nome di un file in `/templates/` (`.html` viene aggiunto se manca). Nel template il modello è `value`.\n\nIl template può contenere un blocco `<script type=\"text/json\">` con un modello predefinito, usato quando `model` non è fornito, e un blocco `<script>` che aggiunge helper a `Thelpers`. Con `$` (il `$` di una route o di un'azione) il template viene tradotto in `$.language`, e gli errori vanno a `$.invalid()` invece di rifiutare la promise. I template letti da file vengono messi in cache in modalità release.\n\nExample: Template inline\n```js\nvar html = await TEMPLATE('<p>Hello {{ value.name }}</p>', { name: 'Peter' });\n```\n\nExample: Un file in una route\n```js\nexports.install = function() {\n\tROUTE('GET /invoice/{id}/', invoice);\n};\n\nfunction invoice($) {\n\tTEMPLATE('invoice', { number: $.params.id }, $).then(function(html) {\n\t\t$.html(html);\n\t});\n}\n```\n\n### {{ value }} / {{ if }} / {{ foreach }}\n\nType: `command`\n\nI comandi dei template Tangular usati da `TEMPLATE()`.\n\n`{{ value.name }}` stampa un valore con codifica HTML. `{{ if condition }}` … `{{ else if condition }}` … `{{ else }}` … `{{ fi }}` è una condizione. `{{ foreach item in value.items }}` … `{{ end }}` è un ciclo con `{{ $index }}`, `{{ continue }}` e `{{ break }}`. Un valore passa attraverso gli helper con `|`: `{{ value.html | raw }}`.\n\nExample: Fattura\n```html\n<h1>Invoice {{ value.number }}</h1>\n{{ if value.items.length }}\n<table>\n\t{{ foreach item in value.items }}\n\t<tr><td>{{ $index + 1 }}</td><td>{{ item.name }}</td><td>{{ item.price | format(2) }}</td></tr>\n\t{{ end }}\n</table>\n{{ else }}\n<p>No items</p>\n{{ fi }}\n```\n\n### Thelpers\n\nType: `property`\n\nGli helper dei template Tangular.\n\nReturns: `Object`\n\nHelper integrati: `encode` (il predefinito per ogni valore; `encode('json')`, `encode('url')` cambiano il formato), `raw` (nessuna codifica), `format(...)` (numeri e date, come `Number.format()` e `Date.format()`), `def(text)` o `empty(text)` (stampa `text`, o `---`, per un valore vuoto) e `pluralize(zero, one, few, other)`. Aggiungi i tuoi in `Thelpers`, globalmente o nel blocco `<script>` di un file template; `this` è l'oggetto che contiene il modello in `value`.\n\nExample: Un file di template con un helper e un modello predefinito\n```html\n<script type=\"text/json\">{ \"name\": \"Guest\" }</script>\n<script>\nThelpers.upper = function(value) {\n\treturn (value || '').toUpperCase();\n};\n</script>\n<h1>{{ value.name | upper }}</h1>\n<p>{{ value.count | pluralize('# items', '# item', '# items', '# items') }}</p>\n<p>{{ value.date | format('yyyy-MM-dd') }} {{ value.note | def('none') }}</p>\n```\n","entries":[{"type":"method","name":"controller.view()","signature":"controller.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"F.view()","signature":"F.view(name, [model], [prepare])","since":"","deprecated":false},{"type":"class","name":"View","signature":"new F.TViewEngine.View([controller])","since":"","deprecated":false},{"type":"method","name":"view.render()","signature":"view.render(name, [model])","since":"","deprecated":false},{"type":"property","name":"view.repository","signature":"view.repository","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository}","since":"","deprecated":false},{"type":"command","name":"@{config}","signature":"@{config.key} / @{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{query}","signature":"@{query} / @{body} / @{files} / @{user} / @{session} / @{controller}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}","since":"","deprecated":false},{"type":"command","name":"@{hostname()}","signature":"@{hostname([path])}","since":"","deprecated":false},{"type":"command","name":"@{cookie()}","signature":"@{cookie(name)}","since":"","deprecated":false},{"type":"command","name":"@{now}","signature":"@{now}","since":"","deprecated":false},{"type":"command","name":"@{root}","signature":"@{root}","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":"@{index}","signature":"@{index}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end} / @{section(name)}","since":"","deprecated":false},{"type":"method","name":"view.section()","signature":"view.section(name, [value], [replace])","since":"","deprecated":false},{"type":"command","name":"@{title()}","signature":"@{title(value)} / @{title}","since":"","deprecated":false},{"type":"command","name":"@{title2()}","signature":"@{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} / @{description}","since":"","deprecated":false},{"type":"command","name":"@{keywords()}","signature":"@{keywords(value)} / @{keywords}","since":"","deprecated":false},{"type":"command","name":"@{meta()}","signature":"@{meta([title], [description], [keywords], [image])} / @{meta}","since":"","deprecated":false},{"type":"config","name":"CONF.$customtitles","signature":"CONF.$customtitles","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(name, [name2], ...)}","since":"","deprecated":false},{"type":"command","name":"Merging files","signature":"@{import('a.css + b.css')}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify], [replacer])}","since":"","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href([key], [value])}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers","since":"","deprecated":false},{"type":"command","name":"@{helper()}","signature":"@{helper(name, [arg1], [arg2], ...)}","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile [name]} ... @{end}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onViewCompile","signature":"DEF.onViewCompile = function(name, html, model)","since":"","deprecated":false},{"type":"event","name":"ON('$view')","signature":"ON('$view', function(meta) {})","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|js|css|all}","since":"","deprecated":false},{"type":"command","name":"@{{ }}","signature":"@{{ text }}","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"command","name":"Template commands","signature":"{{ value }} / {{ if }} / {{ foreach }}","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwth3Dx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/views/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Views","summary":"Príkazy pohľadov, objekt pohľadu, helpery a TEMPLATE().","markdown":"---\ntitle: Views\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/views/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Views\n\n> Príkazy pohľadov, objekt pohľadu, helpery a TEMPLATE().\n\nPohľady sú HTML súbory v `/views/` s príkazmi `@{...}`, ktoré vykresľuje `controller.view()` a `F.view()`. Táto stránka uvádza všetky príkazy, metódy objektu pohľadu, helpery a `TEMPLATE()`. Ako spolu fungujú, vysvetľuje s príkladmi návod [Pohľady](../../guides/views/).\n\n## API\n\n### controller.view([name], [model])\n\nType: `method`\n\nVykreslí pohľad a pošle ho ako HTML odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Meno pohľadu bez `.html`, napríklad `products/detail`. |\n| `model` | `Object` | no |  | Model, v pohľade dostupný ako `model`. |\n\nReturns: `View` Objekt pohľadu.\n\nPohľad sa načíta z `/views/{name}.html` alebo z `/plugins/`, keď meno začína na `#`. Vykreslí sa do layoutu nastaveného cez `controller.layout()` (predvolene `layout`) a pošle sa cez `controller.html()`. Bez mena metóda len vráti nový objekt pohľadu, ktorý vykreslíš sám.\n\nExample: Vykreslenie pohľadu\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail($) {\n\tvar id = $.params.id;\n\t$.view('products/detail', { id: id });\n}\n```\n\nExample: Vlastné vykreslenie\n```js\nfunction preview($) {\n\tvar view = $.view();\n\tview.layout('');\n\t$.html(view.render('preview', { name: 'Test' }));\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nNastaví layout pre nasledujúce `controller.view()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov pohľadu layoutu. |\n\nZavolaj ju pred `controller.view()`. Prázdny reťazec ponechá predvolený layout; pre view bez layoutu použi `@{layout('')}` vo view alebo `view.layout('')`. View ho stále môže zmeniť cez `@{layout()}`.\n\nExample: Použitie iného layoutu\n```js\nfunction admin($) {\n\t$.layout('layout-admin');\n\t$.view('admin/index');\n}\n```\n\n### F.view(name, [model], [prepare])\n\nType: `method`\n\nVykreslí pohľad mimo požiadavky a vráti HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno pohľadu. |\n| `model` | `Object` | no |  | Model. |\n| `prepare` | `Function` | no |  | `function(view)` volaná pred vykreslením, na nastavenie `view.language`, `view.repository` alebo layoutu. |\n\nReturns: `String` Vyrenderované HTML.\n\nPohľad nemá controller, takže `controller`, `user`, `query` a ostatné hodnoty požiadavky sú prázdne. Pohľad sa ako obvykle vykreslí do svojho layoutu; pre fragment bez layoutu použi `@{layout('')}` v pohľade alebo `view.layout('')` v `prepare`.\n\nExample: Vykreslenie tela e-mailu\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'sk';\n\tview.layout('');\n});\n```\n\n### new F.TViewEngine.View([controller])\n\nType: `class`\n\nObjekt, ktorý vykresľuje pohľad; v skompilovanom pohľade je to `self`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | no |  | Controller požiadavky. |\n\n`controller.view()` a `F.view()` ho vytvoria za teba. Jeho vlastnosti sú `controller`, `model`, `repository` (na začiatku `{ layout: 'layout' }`), `language`, `url` a `query`. Jeho metódy sú príkazy pohľadu: `layout()`, `title()`, `description()`, `keywords()`, `meta()`, `json()`, `href()`, `import()`, `section()`, `helper()`, `hostname()` a `view()`.\n\nExample: Nastavenie hodnôt pred vykreslením\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.repository.menu = 'products';\n\t$.html(view.render('products', { items: [] }));\n}\n```\n\n### view.render(name, [model])\n\nType: `method`\n\nVykreslí pohľad s jeho layoutom a vráti HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno pohľadu. |\n| `model` | `Object` | no |  | Model. |\n\nReturns: `String` HTML.\n\nSúbor je `/views/{name}.html` (alebo `/plugins/{name}.html` pre meno s `#`). Keď `repository.layout` nie je prázdne, výsledok sa vykreslí do tohto layoutu.\n\nExample: Vykreslenie\n```js\nvar view = new F.TViewEngine.View();\nview.layout('');\nvar html = view.render('fragments/card', { name: 'Pen' });\n```\n\n### view.repository\n\nType: `property`\n\nObjekt, ktorý zdieľa pohľad, jeho čiastkové pohľady a layout.\n\nReturns: `Object`\n\nObsahuje `layout`, `title`, `description`, `keywords`, sekcie (`section_{name}`) a akékoľvek hodnoty, ktoré pridáš. V pohľade je to premenná `repository`. Použi ju na odovzdanie hodnôt z pohľadu do jeho layoutu.\n\nExample: Z pohľadu do layoutu\n```html\n<!-- view -->\n@{repository.menu = 'products'}\n\n<!-- layout -->\n<nav class=\"@{repository.menu}\">...</nav>\n```\n\n### view.language\n\nType: `property`\n\nJazyk použitý pre preklady `@(...)`.\n\nReturns: `String`\n\nV `controller.view()` je to jazyk požiadavky a v `F.view()` prázdny reťazec. Nastav ho pred vykreslením; každý jazyk má vlastnú skompilovanú kópiu pohľadu a `@{language}` ho vypíše.\n\nExample: Jazyk v F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{expression}\n\nType: `command`\n\nVypíše hodnotu JavaScript výrazu, zakódovanú pre HTML.\n\nFunguje akýkoľvek výraz: vlastnosti, volania metód, operátory. `null` a `undefined` sa vypíšu ako prázdny reťazec. Priradenie (`=`, `+=`, `++`…) do `model`, `repository`, `config`, `query`, `user`, `session` alebo `controller` sa vyhodnotí a nevypíše nič. `@{print(...)}` a `@{console.log(...)}` do HTML nevypíšu nič.\n\nExample: Hodnoty\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} items</p>\n<p>@{model.price.format(2)}</p>\n@{repository.count = model.items.length}\n```\n\n### @{!expression}\n\nType: `command`\n\nVypíše hodnotu výrazu bez HTML kódovania.\n\nPouži ho pre HTML, ktorému dôveruješ, napríklad obsah CMS uložený tvojimi administrátormi.\n\nExample: Surové HTML\n```html\n<article>@{!model.body}</article>\n```\n\n### @{model}\n\nType: `command`\n\nModel odovzdaný pohľadu.\n\nJe to druhý argument `controller.view()`, `F.view()`, `view.render()` alebo `@{view()}`. Layout model nedostáva.\n\nExample: Čítanie modelu\n```html\n<h1>@{model.title}</h1>\n@{if model.user}<p>@{model.user.name}</p>@{fi}\n```\n\n### @{repository}\n\nType: `command`\n\nZdieľaný objekt pohľadu, jeho čiastkových pohľadov a layoutu.\n\nPozri `view.repository`. Hodnoty priraď cez `@{repository.key = value}`; priradenie nevypíše nič.\n\nExample: Nastavenie a čítanie\n```html\n@{repository.menu = 'contact'}\n<li class=\"@{repository.menu === 'contact' ? 'active' : ''}\">Contact</li>\n```\n\n### @{config.key} / @{'%key'}\n\nType: `command`\n\nVypíše konfiguračnú hodnotu.\n\n`config` je `CONF`, číta sa pri každom vykreslení. `@{'%key'}` načíta hodnotu raz, pri kompilácii pohľadu, a vloží ju do pohľadu ako text.\n\nExample: Konfigurácia\n```html\n<title>@{config.name}</title>\n<footer>@{'%name'} @{config.version}</footer>\n```\n\n### @{query} / @{body} / @{files} / @{user} / @{session} / @{controller}\n\nType: `command`\n\nDáta aktuálnej požiadavky.\n\n`query` je sparsovaný query string, `body` sparsované telo, `files` nahraté súbory, `user` a `session` hodnoty tvojej autorizácie a `controller` samotný controller. V `F.view()` sú prázdne. V layoute vypíše `@{body}` bez vlastnosti namiesto toho HTML pohľadu.\n\nExample: Hodnoty požiadavky\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{else}\n\t<a href=\"/login/\">Sign in</a>\n@{fi}\n<input name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{body}\n\nType: `command`\n\nV layoute vypíše HTML vykresleného pohľadu.\n\nVýstup sa neenkóduje. S vlastnosťou (`@{body.name}`) namiesto toho číta telo požiadavky.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>@{import('meta')}</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{language}\n\nType: `command`\n\nJazyk pohľadu.\n\nJazyk pohľadu (`view.language`): jazyk požiadavky (`controller.language`) v `controller.view()`, hodnota, ktorú nastavíš vo funkcii `prepare` v `F.view()`, a predvolene prázdny reťazec.\n\nExample: Atribút jazyka\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\nExample: V F.view()\n```js\nvar html = F.view('mail/welcome', model, function(view) {\n\tview.language = 'de';\n});\n// <html lang=\"de\">\n```\n\n### @{url}\n\nType: `command`\n\nURL cesta aktuálnej požiadavky.\n\nJe to `controller.url`, cesta tak, ako bola požadovaná (veľkosť písmen sa zachová), s lomkou na konci a bez query stringu. `url` funguje aj vo výrazoch a podmienkach: `@{if url === '/'}`. V `F.view()` nie je žiadna požiadavka: `@{url}` vypíše prázdny reťazec a `url` vo výraze je `undefined`.\n\nExample: Aktívny odkaz\n```html\n<a href=\"/products/\" class=\"@{url === '/products/' ? 'active' : ''}\">Products</a>\n```\n\n### @{hostname([path])}\n\nType: `command`\n\nVypíše absolútnu URL aktuálnej stránky alebo inej cesty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Cesta, ktorá začína na `/`. Bez nej cesta aktuálnej požiadavky. |\n\nReturns: `String` Absolútna URL.\n\n`@{hostname()}` vypíše protokol, hosta a cestu aktuálnej požiadavky bez query stringu (`https://shop.example.com/products/`). `@{hostname('/img/share.png')}` vypíše protokol a hosta so zadanou cestou. Volá `controller.hostname()`, pozri [Controller](../controller/). Píš zátvorky: samotné `@{hostname}` funkciu nezavolá.\n\nV `F.view()` nie je žiadna požiadavka, takže vypíše iba `path` (alebo prázdny reťazec).\n\nExample: Kanonický odkaz a obrázok na zdieľanie\n```html\n<link rel=\"canonical\" href=\"@{hostname()}\" />\n<meta property=\"og:image\" content=\"@{hostname('/img/share.png')}\" />\n```\n\n### @{cookie(name)}\n\nType: `command`\n\nVypíše hodnotu cookie požiadavky, HTML-enkódovanú.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie. |\n\nBez controllera vypíše prázdny reťazec.\n\nExample: Čítanie cookie\n```html\n<body class=\"theme-@{cookie('theme')}\">\n```\n\n### @{now}\n\nType: `command`\n\nNový `Date` s aktuálnym časom.\n\nVlastnosti a metódy dátumu používaj priamo: `@{now.getFullYear()}`.\n\nExample: Copyright\n```html\n<footer>&copy; @{now.getFullYear()} @{config.name}</footer>\n```\n\n### @{root}\n\nType: `command`\n\nVypíše `CONF.$root` bez lomky na konci.\n\nPouži ho pre odkazy, keď aplikácia beží pod podcestou. Keď `CONF.$root` nie je nastavené, vypíše prázdny reťazec.\n\nExample: Odkaz pod podcestou\n```html\n<a href=\"@{root}/products/\">Products</a>\n```\n\n### @{if condition} ... @{else if condition} ... @{else} ... @{fi}\n\nType: `command`\n\nRenderuje časť pohľadu, iba keď je podmienka splnená.\n\nPodmienka je ľubovoľný JavaScript výraz. `@{endif}` je to isté ako `@{fi}`. Funguje aj `@{if(condition)}` so zátvorkami.\n\nExample: Podmienka\n```html\n@{if model.stock > 10}\n\t<b>In stock</b>\n@{else if model.stock > 0}\n\t<b>Last pieces</b>\n@{else}\n\t<b>Sold out</b>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nZopakuje časť pohľadu pre každú položku poľa alebo objektu.\n\nPri objekte je každá položka `{ key, value }`. Prázdny zdroj nevykreslí nič. Funguje aj `@{foreach var item in source}`. Vnútri cyklu je `@{index}` pozícia od nuly a `@{continue}` a `@{break}` preskočia položku alebo ukončia cyklus. Cykly sa dajú vnárať.\n\nExample: Pole\n```html\n<ul>\n@{foreach item in model.items}\n\t@{if item.hidden}@{continue}@{fi}\n\t<li>@{index + 1}. @{item.name}</li>\n@{end}\n</ul>\n```\n\nExample: Objekt\n```html\n@{foreach prop in model.settings}\n\t<dt>@{prop.key}</dt><dd>@{prop.value}</dd>\n@{end}\n```\n\n### @{index}\n\nType: `command`\n\nPozícia aktuálnej položky v `@{foreach}` od nuly.\n\nExample: Číslované riadky\n```html\n@{foreach row in model.rows}\n\t<tr class=\"@{index % 2 ? 'odd' : 'even'}\"><td>@{index + 1}</td><td>@{row.name}</td></tr>\n@{end}\n```\n\n### @{layout(name)}\n\nType: `command`\n\nNastaví layout pohľadu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov view layoutu alebo prázdny reťazec. |\n\nPredvolený layout je `layout` (`/views/layout.html`). Prázdny reťazec vykreslí pohľad bez layoutu. Príkaz nevypíše nič.\n\nExample: Iný layout\n```html\n@{layout('layout-print')}\n<h1>@{model.title}</h1>\n```\n\nExample: Bez layoutu\n```html\n@{layout('')}\n<div class=\"card\">@{model.name}</div>\n```\n\n### @{view(name, [model])}\n\nType: `command`\n\nVykreslí na danom mieste iný pohľad (čiastkový pohľad).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno pohľadu. |\n| `model` | `Object` | no |  | Model čiastkového pohľadu. |\n\nČiastkový pohľad dostane vlastný model a žiadny layout. S pohľadom, ktorý ho vykresľuje, zdieľa `repository` a sekcie. Meno začínajúce na `#` načíta súbor z `/plugins/`.\n\nExample: Čiastkové pohľady\n```html\n@{foreach item in model.items}\n\t@{view('partials/card', item)}\n@{end}\n@{view('#blog/sidebar')}\n```\n\n### @{section name} ... @{end} / @{section(name)}\n\nType: `command`\n\nZbiera HTML v pohľade a vypíše ho na inom mieste, zvyčajne v layoute.\n\n`@{section name}` … `@{end}` pridá svoje HTML do sekcie; viac blokov s rovnakým menom sa spojí. `@{section('name')}` vypíše sekciu, alebo nič, keď je prázdna. Sekcia musí byť naplnená pred vypísaním, čo pri layoute platí.\n\nExample: Skripty pre layout\n```html\n<!-- view -->\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<!-- layout, before </body> -->\n@{section('scripts')}\n```\n\n### view.section(name, [value], [replace])\n\nType: `method`\n\nČíta alebo plní sekciu z JavaScriptu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno sekcie. |\n| `value` | `String` | no |  | HTML na pridanie. |\n| `replace` | `Boolean` | no | `false` | Nahradí aktuálny obsah. |\n\nReturns: `String|View` Pri čítaní sekcia; pri zápise pohľad.\n\nBez `value` vráti HTML sekcie. S `value` pripojí HTML do sekcie, alebo ju nahradí, keď je `replace` `true`.\n\nExample: Naplnenie sekcie\n```js\nfunction page($) {\n\tvar view = $.view();\n\tview.section('scripts', '<script src=\"/js/page.js\"></script>');\n\t$.html(view.render('page'));\n}\n```\n\n### @{title(value)} / @{title}\n\nType: `command`\n\nNastaví alebo vypíše titulok stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Titulok. |\n\n`@{title('Text')}` uloží text do `repository.title` a nič nevypíše. `@{title}` ho vypíše HTML-zakódovaný, `@{!title}` bez kódovania.\n\nExample: Titulok\n```html\n@{title('Products / ' + model.category)}\n<h1>@{title}</h1>\n```\n\n### @{title2(value)}\n\nType: `command`\n\nPripojí text k titulku stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Text na pripojenie. |\n\nPridá `value` na koniec `repository.title` (alebo ho nastaví, keď ešte žiadny titulok nie je) a nič nevypíše. Ako pri `title()` sa text uloží tak, ako je, a zakóduje sa raz, keď sa vypíše. Prázdna hodnota nič nezmení.\n\nExample: Titulok v dvoch krokoch\n```html\n@{title('Products')}\n@{if model}@{title2(' / ' + model.name)}@{fi}\n<h1>@{title}</h1>  <!-- Products / Pen &amp; paper -->\n```\n\n### @{description(value)} / @{description}\n\nType: `command`\n\nNastaví alebo vypíše popis stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Popis. |\n\nHodnota ide do `repository.description`; `@{import('meta')}` ju vypíše ako tag `<meta name=\"description\">`.\n\nExample: Popis\n```html\n@{description('Pens, pencils and paper for the office.')}\n```\n\n### @{keywords(value)} / @{keywords}\n\nType: `command`\n\nNastaví alebo vypíše kľúčové slová stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Kľúčové slová. |\n\nPole sa spojí cez `, `. Hodnota ide do `repository.keywords`.\n\nExample: Kľúčové slová\n```html\n@{keywords(['pens', 'paper', 'office'])}\n```\n\n### @{meta([title], [description], [keywords], [image])} / @{meta}\n\nType: `command`\n\nNastaví titulok, popis, kľúčové slová a obrázok naraz, alebo vypíše meta tagy.\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 |  | Absolútna URL alebo cesta k obrázku. |\n\nS argumentmi uloží hodnoty do `repository` tak, ako sú, a nič nevypíše; HTML-zakódujú sa raz, keď sa tagy vypisujú. Bez argumentov vypíše tie isté tagy ako `@{import('meta')}`: `<title>`, tagy description a keywords a pre obrázok `og:image` a `twitter:image`. Relatívny obrázok dostane hostname požiadavky; bez požiadavky sa žiadne tagy obrázka nevypíšu. K titulku sa pripojí ` - ` a `CONF.name`, okrem URL `/` a okrem prípadu, keď je `CONF.$customtitles` nastavené na `true`; bez titulku je to `CONF.name`.\n\nExample: Nastavenie a vypísanie\n```html\n<!-- view -->\n@{meta(model.name, model.summary, model.tags, model.photo)}\n\n<!-- layout -->\n<head>@{meta}</head>\n```\n\n### CONF.$customtitles\n\nType: `config`\n\nVypíše titulok stránky bez mena aplikácie.\n\nReturns: `Boolean` Predvolene `false`.\n\nPredvolene je tag title v `@{meta}` a `@{import('meta')}` `Title - CONF.name`. S `true` sa titulok vypíše tak, ako ho nastavíš.\n\nExample: /config\n```text\n$customtitles : true\n```\n\n### @{import(name, [name2], ...)}\n\nType: `command`\n\nVypíše tagy pre statické súbory, meta tagy alebo favicon.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno súboru, `meta` alebo meno faviconu. |\n\nKaždý argument dá jeden tag:\n\n- `meta` vypíše meta tagy (pozri `@{meta}`).\n- `favicon.ico`, `favicon.png` alebo `favicon.gif` vypíše tag `<link rel=\"icon\">`.\n- Meno s `.css` vypíše odkaz na stylesheet z `/css/`, ostatné mená skript z `/js/`. Cesta začínajúca na `/` (alebo virtuálna routa) sa použije tak, ako je.\n- `@` pred menom pripojí `?ts=` s časom štartu aplikácie.\n- Mená spojené cez `+` sa zlúčia do jedného minifikovaného súboru (pozri ďalšiu položku).\n\nTagy sa cachujú, takže príkaz je lacný.\n\nExample: Hlavička layoutu\n```html\n<head>\n\t@{import('meta', 'favicon.ico', '@default.css', 'ui.js', '/vendor/editor.js')}\n</head>\n```\n\n### @{import('a.css + b.css')}\n\nType: `command`\n\nZlúči viac CSS alebo JavaScript súborov do jedného minifikovaného súboru.\n\nNázvy spojené `+` sa zlúčia cez `MERGE()` do súboru s vygenerovaným názvom, napríklad `/xkcqdmatno-min.css`, ktorý framework obsluhuje. Názov s `.css` vytvorí štýl, inak skript. Názov súboru sa hľadá v `/public/css/` alebo `/public/js/` podľa prípony, cesta, ktorá začína `/`, v `/public/` a URL sa stiahne. `@` na začiatku pripojí `?ts=`.\n\nExample: Jeden CSS a jeden JS súbor\n```html\n@{import('reset.css + layout.css + forms.css', '@ui.js + app.js')}\n<!-- <link rel=\"stylesheet\" href=\"/wqxjrnefjv-min.css\" /> -->\n<!-- <script src=\"/wbxyamtxmw-min.js?ts=mwi48bh6\"></script> -->\n```\n\n### @{json(value, [id], [beautify], [replacer])}\n\nType: `command`\n\nVypíše hodnotu ako JSON alebo v tagu `<script type=\"application/json\">`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n| `id` | `String` | no |  | Id script tagu. |\n| `beautify` | `Boolean` | no | `false` | Odsadí JSON. |\n| `replacer` | `Function|Boolean` | no |  | Replacer pre `JSON.stringify()`. |\n\nS `id` sa JSON zabalí do script tagu s týmto `id`, ktorý klientsky kód prečíta bez druhej požiadavky. `beautify` odsadí JSON štyrmi medzerami. `replacer` je funkcia pre `JSON.stringify()` alebo `true` pre replacer frameworku. `@{json(value, true)}` je to isté ako `@{json(value, null, true)}`.\n\nExample: Dáta pre klienta\n```html\n@{json(model.products, 'products')}\n<script>\n\tvar products = JSON.parse(document.getElementById('products').innerHTML);\n</script>\n```\n\n### @{href([key], [value])}\n\nType: `command`\n\nVypíše aktuálny query string so zmeneným jedným parametrom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | no |  | Názov parametra alebo objekt s parametrami, ktoré sa majú nastaviť. |\n| `value` | `Any` | no |  | Nová hodnota. |\n\nReturns: `String` Query string s `?` alebo prázdny reťazec.\n\n`@{href}` vypíše aktuálny query string (`?page=2&sort=name`). `@{href('page', 3)}` ho vypíše s `page` nastaveným na `3`; bez hodnoty sa ponechá aktuálna hodnota. Ďalšie argumenty za hodnotou sú názvy parametrov, ktoré sa majú odstrániť. Hodnota typu pole zapíše parameter raz pre každú položku (`tag=a&tag=b`) a hodnota typu objekt sa zapíše ako JSON. `@{href({ page: 3, sort: 'price' })}` vráti URL požiadavky s query stringom zmeneným podľa kľúčov objektu. Používaj ho na odkazy stránkovania a zoradenia.\n\nExample: Stránkovanie\n```html\n<a href=\"@{href('page', model.page - 1)}\">Previous</a>\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\nExample: Odstránenie parametra alebo zmena viacerých\n```html\n<!-- /products/?page=2&sort=name&q=pen -->\n<a href=\"@{href('page', 1, 'sort')}\">First page</a>  <!-- ?page=1&q=pen -->\n<a href=\"@{href({ page: 1, sort: 'price' })}\">By price</a>  <!-- /products/?page=1&sort=price&q=pen -->\n```\n\n### DEF.helpers\n\nType: `property`\n\nVlastné funkcie, ktoré voláš z každého pohľadu.\n\nReturns: `Object`\n\nPridaj funkcie do objektu; vnútri helpera je `this` pohľad (`this.model`, `this.repository`, `this.controller`). Helper zavoláš jeho menom (`@{price(10)}`), cez `@{helpers.price(10)}` alebo cez `@{helper('price', 10)}`. Vrátená hodnota sa vypíše bez enkódovania. Helpery zaregistruj pred kompiláciou pohľadov, napríklad v `/definitions/`.\n\nExample: Registrácia a použitie\n```js\n// /definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\n// in a view: <span>@{price(model.price, 'USD')}</span>\n```\n\n### @{helper(name, [arg1], [arg2], ...)}\n\nType: `command`\n\nZavolá helper z `DEF.helpers` podľa mena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno helpera. |\n\nOstatné argumenty idú do helpera. Keď helper neexistuje, vypíše prázdny reťazec.\n\nExample: Volanie helpera\n```html\n<span>@{helper('price', model.price, 'EUR')}</span>\n```\n\n### @(text)\n\nType: `command`\n\nPreloží text do jazyka pohľadu.\n\nText sa pri kompilácii pohľadu nahradí prekladom zo súborov resources; text bez prekladu zostane, ako je. Resources vysvetľuje návod [Lokalizácia](../../guides/localization/).\n\nExample: Preložený text\n```html\n<h1>@(Welcome)</h1>\n<button>@(Add to cart)</button>\n```\n\n### @{compile [name]} ... @{end}\n\nType: `command`\n\nPri každom vykreslení odovzdá časť pohľadu do `DEF.onViewCompile`.\n\nHTML medzi tagmi, s už vyhodnotenými príkazmi, sa odovzdá do `DEF.onViewCompile(name, html, model)` a vypíše sa jeho výsledok. Použi ho na spracovanie časti pohľadu Markdownom alebo iným procesorom.\n\nExample: Markdown\n```html\n@{compile markdown}\n# @{model.title}\n\n@{model.text}\n@{end}\n```\n\n### DEF.onViewCompile = function(name, html, model)\n\nType: `delegate`\n\nSpracuje obsah blokov `@{compile}`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno bloku alebo prázdny reťazec. |\n| `html` | `String` | yes |  | Obsah bloku. |\n| `model` | `Object` | yes |  | Model pohľadu. |\n\nReturns: `String` HTML na vypísanie.\n\n`name` je slovo za `@{compile`, `html` vykreslený obsah bloku a `model` model pohľadu. Vráť HTML na vypísanie. Predvolene vráti `html` nezmenené.\n\nExample: Markdown bloky\n```js\nDEF.onViewCompile = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\n### ON('$view', function(meta) {})\n\nType: `event`\n\nZmení zdroj pohľadu pred jeho kompiláciou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, body, debug }`. |\n\n`meta.name` je meno pohľadu, `meta.body` jeho HTML zdroj a `meta.debug` debug režim. Pohľad zmeníš zmenou `meta.body`; udalosť sa spustí pri každej kompilácii pohľadu.\n\nExample: Nahradenie zástupného textu\n```js\nON('$view', function(meta) {\n\tmeta.body = meta.body.replace(/\\{year\\}/g, new Date().getFullYear() + '');\n});\n```\n\n### @{nocompress html|js|css|all}\n\nType: `command`\n\nVypne krok kompresie pre pohľad.\n\nPri kompilácii view sa viacnásobné medzery v jeho texte zlúčia (zalomenia riadkov a odsadenie medzi tagmi sa zachovajú) a CSS tagov `<style>` a JavaScript tagov `<script>` sa minifikujú. `html` ponechá HTML tak, ako je, a vypne aj minifikáciu odpovede; `js` (alebo `script`, `javascript`) a `css` (alebo `style`) ponechajú inline kód; `all` vypne všetky tri. HTML komentáre sa odstraňujú vždy.\n\nExample: Zachovanie bielych znakov\n```html\n@{nocompress html}\n<pre>\n  formatted\n    text\n</pre>\n```\n\n### @{{ text }}\n\nType: `command`\n\nVypíše `@{{ ... }}` tak, ako je, bez spustenia.\n\nPouži ho na zachovanie textu `@{{ }}` pre klientske šablóny.\n\nExample: Doslovný text\n```html\n<code>@{{ value }}</code>\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nVykreslí Tangular šablónu a vráti promise s HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Šablóna, URL, cesta alebo meno súboru v `/templates/`. |\n| `model` | `Object` | no |  | Model, dostupný ako `value`. |\n| `$` | `Options` | no |  | `$` akcie alebo controllera, pre jazyk a spracovanie chýb. |\n\nReturns: `Promise<String>` Vykreslené HTML.\n\n`body` je text šablóny, keď obsahuje `{{`. Inak je to URL (`http://` alebo `https://`, stiahne sa), `~` a absolútna cesta, `#` a cesta k súboru v `/plugins/` (`.html` sa doplní, keď chýba), alebo názov súboru v `/templates/` (`.html` sa doplní, keď chýba). V šablóne je model `value`.\n\nŠablóna môže obsahovať blok `<script type=\"text/json\">` s predvoleným modelom, ktorý sa použije, keď `model` nie je zadaný, a blok `<script>`, ktorý pridá pomocné funkcie do `Thelpers`. S `$` (`$` routy alebo akcie) sa šablóna preloží do `$.language` a chyby idú do `$.invalid()` namiesto zamietnutia promisu. Šablóny čítané zo súborov sa v release režime cachujú.\n\nExample: Inline šablóna\n```js\nvar html = await TEMPLATE('<p>Hello {{ value.name }}</p>', { name: 'Peter' });\n```\n\nExample: Súbor v route\n```js\nexports.install = function() {\n\tROUTE('GET /invoice/{id}/', invoice);\n};\n\nfunction invoice($) {\n\tTEMPLATE('invoice', { number: $.params.id }, $).then(function(html) {\n\t\t$.html(html);\n\t});\n}\n```\n\n### {{ value }} / {{ if }} / {{ foreach }}\n\nType: `command`\n\nPríkazy Tangular šablón, ktoré používa `TEMPLATE()`.\n\n`{{ value.name }}` vypíše HTML-enkódovanú hodnotu. `{{ if condition }}` … `{{ else if condition }}` … `{{ else }}` … `{{ fi }}` je podmienka. `{{ foreach item in value.items }}` … `{{ end }}` je cyklus s `{{ $index }}`, `{{ continue }}` a `{{ break }}`. Hodnota prechádza helpermi cez `|`: `{{ value.html | raw }}`.\n\nExample: Faktúra\n```html\n<h1>Invoice {{ value.number }}</h1>\n{{ if value.items.length }}\n<table>\n\t{{ foreach item in value.items }}\n\t<tr><td>{{ $index + 1 }}</td><td>{{ item.name }}</td><td>{{ item.price | format(2) }}</td></tr>\n\t{{ end }}\n</table>\n{{ else }}\n<p>No items</p>\n{{ fi }}\n```\n\n### Thelpers\n\nType: `property`\n\nHelpery Tangular šablón.\n\nReturns: `Object`\n\nVstavané pomocníky: `encode` (predvolený pre každú hodnotu; `encode('json')`, `encode('url')` menia formát), `raw` (bez kódovania), `format(...)` (čísla a dátumy, ako `Number.format()` a `Date.format()`), `def(text)` alebo `empty(text)` (vypíše `text` alebo `---` pre prázdnu hodnotu) a `pluralize(zero, one, few, other)`. Vlastné pridaj do `Thelpers`, globálne alebo v bloku `<script>` súboru šablóny; `this` je objekt, ktorý drží model vo `value`.\n\nExample: Súbor šablóny s helperom a predvoleným modelom\n```html\n<script type=\"text/json\">{ \"name\": \"Guest\" }</script>\n<script>\nThelpers.upper = function(value) {\n\treturn (value || '').toUpperCase();\n};\n</script>\n<h1>{{ value.name | upper }}</h1>\n<p>{{ value.count | pluralize('# items', '# item', '# items', '# items') }}</p>\n<p>{{ value.date | format('yyyy-MM-dd') }} {{ value.note | def('none') }}</p>\n```\n","entries":[{"type":"method","name":"controller.view()","signature":"controller.view([name], [model])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"F.view()","signature":"F.view(name, [model], [prepare])","since":"","deprecated":false},{"type":"class","name":"View","signature":"new F.TViewEngine.View([controller])","since":"","deprecated":false},{"type":"method","name":"view.render()","signature":"view.render(name, [model])","since":"","deprecated":false},{"type":"property","name":"view.repository","signature":"view.repository","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository}","since":"","deprecated":false},{"type":"command","name":"@{config}","signature":"@{config.key} / @{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{query}","signature":"@{query} / @{body} / @{files} / @{user} / @{session} / @{controller}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}","since":"","deprecated":false},{"type":"command","name":"@{hostname()}","signature":"@{hostname([path])}","since":"","deprecated":false},{"type":"command","name":"@{cookie()}","signature":"@{cookie(name)}","since":"","deprecated":false},{"type":"command","name":"@{now}","signature":"@{now}","since":"","deprecated":false},{"type":"command","name":"@{root}","signature":"@{root}","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":"@{index}","signature":"@{index}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end} / @{section(name)}","since":"","deprecated":false},{"type":"method","name":"view.section()","signature":"view.section(name, [value], [replace])","since":"","deprecated":false},{"type":"command","name":"@{title()}","signature":"@{title(value)} / @{title}","since":"","deprecated":false},{"type":"command","name":"@{title2()}","signature":"@{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} / @{description}","since":"","deprecated":false},{"type":"command","name":"@{keywords()}","signature":"@{keywords(value)} / @{keywords}","since":"","deprecated":false},{"type":"command","name":"@{meta()}","signature":"@{meta([title], [description], [keywords], [image])} / @{meta}","since":"","deprecated":false},{"type":"config","name":"CONF.$customtitles","signature":"CONF.$customtitles","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(name, [name2], ...)}","since":"","deprecated":false},{"type":"command","name":"Merging files","signature":"@{import('a.css + b.css')}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify], [replacer])}","since":"","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href([key], [value])}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers","since":"","deprecated":false},{"type":"command","name":"@{helper()}","signature":"@{helper(name, [arg1], [arg2], ...)}","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile [name]} ... @{end}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onViewCompile","signature":"DEF.onViewCompile = function(name, html, model)","since":"","deprecated":false},{"type":"event","name":"ON('$view')","signature":"ON('$view', function(meta) {})","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|js|css|all}","since":"","deprecated":false},{"type":"command","name":"@{{ }}","signature":"@{{ text }}","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"command","name":"Template commands","signature":"{{ value }} / {{ if }} / {{ foreach }}","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwW5GSx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/configuration/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Configuration","summary":"CONF, LOADCONFIG(), DEBUG and every $ key of the framework with its default.","markdown":"---\ntitle: Configuration\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/configuration/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Configuration\n\n> CONF, LOADCONFIG(), DEBUG and every $ key of the framework with its default.\n\nEvery key the framework reads from `CONF`, with its type and default, plus `CONF`, `LOADCONFIG()`, `DEBUG` and the `$reconfigure` event. The guide [Configuration](../../guides/configuration/) explains the format of the `config` file, the types, `.env` and the loading order.\n\n## API\n\n### CONF\n\nType: `property`\n\nThe global object with the configuration of the application.\n\nReturns: `Object`\n\nHolds the defaults of the framework and every key loaded from the options of `F.http()`, the `config` file, plugin config files and `LOADCONFIG()`. `F.config` is the same object. Read it anywhere; write to it with `LOADCONFIG()` when the change must refresh derived settings.\n\nExample: Read values\n```js\nexports.install = function() {\n\tROUTE('GET /about/', function($) {\n\t\t$.json({ name: CONF.name, version: CONF.version });\n\t});\n};\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nApplies configuration values at runtime.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object|Array` | yes |  | The text of a config file, an object of keys and values, or an array of `{ id, type, value }` items (`key`/`name` and `val`/`body` are accepted too). |\n\nParses `value` like the `config` file and copies the keys into `CONF`. In an object or an array, the values `false`, `0` and `''` are stored as `undefined`. Special keys are processed: `$root` is normalized and prefixes `$api`, `$timezone` sets `process.env.TZ`, `$port` becomes a number, `$httpfiles` adds extensions, `$cryptoiv` becomes a `Buffer`, `smtp`/`mail`/`mail_smtp`/`mail_smtp_options` build `CONF.smtp`, `totalapi` sets the Total API token. Then it refreshes the directories, the logger (`$logger`), the CORS list and TMS, and emits `$reconfigure`. The framework calls it for the `config` file itself.\n\nExample: Text\n```js\nLOADCONFIG('$httptimeout (number) : 15\\nmaintenance : true');\n```\n\nExample: Array with types\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '25' },\n\t{ id: 'tags', type: 'array', value: 'a, b, c' }\n]);\n```\n\nExample: Object\n```js\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n```\n\n### DEBUG\n\nType: `property`\n\ntrue in debug mode, false in release mode.\n\nReturns: `Boolean`\n\nA global boolean. It starts as `process.env.NODE_ENV !== 'production'`. The debug runner sets it to `true` and the release runner sets it to `false` before the application loads, so `NODE_ENV` decides the mode when the application calls `F.http()` or `F.load()` without a runner. The framework uses it for caching of views and static files, minification and the source map (`$sourcemap` follows it).\n\nExample: Conditional code\n```js\nif (DEBUG)\n\tconsole.log('Debug mode');\n```\n\n### ON('$reconfigure', function() {})\n\nType: `event`\n\nEmitted after LOADCONFIG() applies new values.\n\nEmitted at the end of every `LOADCONFIG()` call, including the load of the `config` file at start. Use it to refresh your own objects that depend on configuration values.\n\nExample: Refresh a client\n```js\nON('$reconfigure', function() {\n\tMAIN.client = createclient(CONF.service_url);\n});\n```\n\n### totalapi : String|Boolean\n\nType: `config` · Since: `0.0.16`\n\nSets the Total API token or turns Total API on or off.\n\nReturns: `String|Boolean`\n\nA string longer than five characters is stored as `CONF.secret_totalapi`, the token for `API('TAPI', ...)` and `TotalAPI()` calls. Any other value is stored as `$tapi`.\n\nExample: In the config file\n```text\ntotalapi : your-total-api-token\n```\n\n### $root : String\n\nType: `config`\n\nA URL prefix for the whole application.\n\nReturns: `String`\n\nNormalized to start and end with `/`. Route URLs get the prefix (API routes through `$api`), static files are served under it and `F.virtualpath()` adds it. Use it when the application runs under a sub-path behind a proxy.\n\nDefault: `''`.\n\nExample: In the config file\n```text\n$root : /app/\n```\n\n### $api : String\n\nType: `config`\n\nThe default API endpoint.\n\nReturns: `String`\n\nA `?` in a route URL is replaced with this value, so `ROUTE('API ?/users/ ...')` listens on `/api/users/`. With `$root`, the prefix is added to it.\n\nDefault: `'/api/'`.\n\nExample: In the config file\n```text\n$api : /v1/\n```\n\n### $mcp : Boolean\n\nType: `config`\n\nTurns on the MCP server.\n\nReturns: `Boolean`\n\n`true` creates the route `POST /$mcp/`, where AI clients list and call the actions that have `mcp: true`. The route is created when the application is ready, so set the key in the `config` file or before the start. See [MCP server](../../guides/mcp-server/).\n\nDefault: `false`.\n\nExample: In the config file\n```text\n$mcp : true\n```\n\n### $cors : String\n\nType: `config`\n\nOrigins allowed for cross-origin requests.\n\nReturns: `String`\n\n`*` allows every origin. Otherwise a list of origins separated by `,`, `;` or `|`, compared with the `Origin` header (for example `https://app.example.com`). An item that starts with `*` matches every origin that contains the rest (`*example.com`). Requests from the same host are always allowed; other origins get the error 400. `CORS()` changes the value in code; see [Routing](../../guides/routing/#cors).\n\nDefault: `''`.\n\nExample: In the config file\n```text\n$cors : https://app.example.com, *example.org\n```\n\n### $port : Number\n\nType: `config`\n\nThe port of the HTTP server.\n\nReturns: `Number`\n\nThe value is converted to a number. Leave the key out for the automatic port: the `port` option of `F.http()`, the `PORT` environment variable, the first 3-5 digit number in the command line arguments, or 8000.\n\nDefault: `'auto'`.\n\nExample: In the config file\n```text\n$port : 8000\n```\n\n### $ip : String\n\nType: `config`\n\nThe IP address the HTTP server listens on.\n\nReturns: `String`\n\nThe `ip` option of `F.http()` overrides it. Use `127.0.0.1` to accept only local connections.\n\nDefault: `'0.0.0.0'`.\n\nExample: In the config file\n```text\n$ip : 127.0.0.1\n```\n\n### $unixsocket : String\n\nType: `config`\n\nA Unix socket path for the HTTP server.\n\nReturns: `String`\n\nWhen set (or when `F.http()` gets the `unixsocket` option), the server listens on the socket instead of a port.\n\nDefault: `''`.\n\nExample: In the config file\n```text\n$unixsocket : /var/run/app.sock\n```\n\n### $timezone : String\n\nType: `config`\n\nThe time zone of the process.\n\nReturns: `String`\n\nCopied into `process.env.TZ`, so all `Date` values of the process use it.\n\nDefault: `'utc'`.\n\nExample: In the config file\n```text\n$timezone : Europe/Bratislava\n```\n\n### $insecure : Boolean\n\nType: `config`\n\nAccepts invalid TLS certificates in outgoing requests.\n\nReturns: `Boolean`\n\nSets `process.env.NODE_TLS_REJECT_UNAUTHORIZED` to `0` when `true` and `1` otherwise. Use it only for development against self-signed servers.\n\nDefault: `false`.\n\nExample: In the config file\n```text\n$insecure : true\n```\n\n### $performance : Boolean\n\nType: `config`\n\nTunes the HTTP sockets for many connections.\n\nReturns: `Boolean`\n\nSets `maxSockets` of the global HTTP agent to 9999 and turns on `setNoDelay` and keep-alive for incoming connections.\n\nDefault: `false`.\n\nExample: In the config file\n```text\n$performance : true\n```\n\n### $httpreqlimit : Number\n\nType: `config`\n\nThe maximum number of requests per IP address per minute.\n\nReturns: `Number`\n\n`0` turns the limit off. Above the limit, requests get the error 503 until the counters are cleared at the next minute.\n\nDefault: `0`.\n\nExample: In the config file\n```text\n$httpreqlimit (number) : 300\n```\n\n### $blacklist : String\n\nType: `config`\n\nBlocked IP addresses.\n\nReturns: `String`\n\nA string of IP addresses, for example separated by commas. HTTP requests from an IP address found in it get the error 400, and WebSocket connections from it are closed.\n\nDefault: `''`.\n\nExample: In the config file\n```text\n$blacklist : 10.0.0.5, 10.0.0.6\n```\n\n### $httpcompress : Boolean\n\nType: `config`\n\nCompresses responses with gzip.\n\nReturns: `Boolean`\n\nWhen the client accepts gzip, text responses larger than 256 bytes and compressible static files are compressed.\n\nDefault: `true`.\n\nExample: In the config file\n```text\n$httpcompress : false\n```\n\n### $httpetag : String\n\nType: `config`\n\nA value added to the ETag of static files and cached responses.\n\nReturns: `String`\n\nWhen empty, it is created from `CONF.version` without dots and spaces, so a new version invalidates browser caches.\n\nDefault: `''`.\n\nExample: In the config file\n```text\n$httpetag : build42\n```\n\n### $httpmaxsize : Number\n\nType: `config`\n\nThe maximum size of a request body in kB.\n\nReturns: `Number`\n\nThe default limit of every HTTP route without its own limit.\n\nDefault: `256`.\n\nExample: In the config file\n```text\n$httpmaxsize (number) : 1024\n```\n\n### $httprangebuffer : Number\n\nType: `config`\n\nThe size of one chunk of a range response in kB.\n\nReturns: `Number`\n\nUsed for `Range` requests of static files (video, audio) when the client does not give the end.\n\nDefault: `5120`.\n\nExample: In the config file\n```text\n$httprangebuffer (number) : 2048\n```\n\n### $httptimeout : Number\n\nType: `config`\n\nThe request timeout in seconds.\n\nReturns: `Number`\n\nA route can set its own timeout. Requests are checked every five seconds.\n\nDefault: `5`.\n\nExample: In the config file\n```text\n$httptimeout (number) : 10\n```\n\n### $httpfiles : String\n\nType: `config`\n\nFile extensions served as static files.\n\nReturns: `String`\n\nIn the config file, a comma-separated list of extensions that are added to the defaults (`jpg`, `png`, `css`, `js`, `json`, `pdf`, `mp4` and many more). In code it is an object with `true` for every allowed extension.\n\nDefault: `common web extensions`.\n\nExample: In the config file\n```text\n$httpfiles : glb, gltf\n```\n\n### $httpchecktypes : Boolean\n\nType: `config`\n\nChecks the content type of uploaded files.\n\nReturns: `Boolean`\n\nFor `multipart/form-data` only. `false` skips the check.\n\nDefault: `true`.\n\nExample: In the config file\n```text\n$httpchecktypes : false\n```\n\n### $httpmaxage : Number\n\nType: `config`\n\nThe max-age of cached responses in seconds.\n\nReturns: `Number`\n\nUsed in the `Cache-Control` header of static files and of responses cached with `controller.httpcache()`.\n\nDefault: `60`.\n\nExample: In the config file\n```text\n$httpmaxage (number) : 300\n```\n\n### $httpmaxkeys : Number\n\nType: `config`\n\nLimits of URL-encoded data.\n\nReturns: `Number`\n\n`$httpmaxkeys` is the maximum number of keys parsed from a query string or URL-encoded body. `$httpmaxkey` (default `25`) is the maximum length of one key; longer keys are dropped.\n\nDefault: `33`.\n\nExample: In the config file\n```text\n$httpmaxkeys (number) : 100\n$httpmaxkey (number)  : 50\n```\n\n### $httpcacheoffset : String\n\nType: `config` · Since: `0.0.16`\n\nMoves the Last-Modified date of static files.\n\nReturns: `String`\n\nA time offset in the format of `Date.add()`, for example `1 minute` or `-5 minutes`. It is added to the modification time of the file in the `Last-Modified` header.\n\nDefault: `''`.\n\nExample: In the config file\n```text\n$httpcacheoffset : 1 minute\n```\n\n### $xpoweredby : String\n\nType: `config`\n\nThe value of the X-Powered-By header.\n\nReturns: `String`\n\nAn empty value removes the header.\n\nDefault: `'Total.js'`.\n\nExample: In the config file\n```text\n$xpoweredby :\n```\n\n### $minify* : Boolean\n\nType: `config`\n\nMinification of JavaScript, CSS and HTML.\n\nReturns: `Boolean`\n\n`$minifyjs`, `$minifycss` and `$minifyhtml` (all `true` by default) turn the minification of static `.js` and `.css` files, inline code and rendered HTML on or off.\n\nExample: In the config file\n```text\n$minifyhtml : false\n$minifyjs   : true\n$minifycss  : true\n```\n\n### $filtererrors : Boolean\n\nType: `config`\n\nIgnores harmless uncaught errors.\n\nReturns: `Boolean`\n\nUncaught `EPIPE`, `invalid distance` and `ERR_IPC_CHANNEL_CLOSED` errors are not logged.\n\nDefault: `true`.\n\nExample: In the config file\n```text\n$filtererrors : false\n```\n\n### $cleartemp : Boolean\n\nType: `config`\n\nClears the tmp directory at start.\n\nReturns: `Boolean`\n\nDeletes the `.js`, `.css`, `.html`, `.htm`, `.tmp` and `.upload` files of the `tmp` directory when the application loads.\n\nDefault: `true`.\n\nExample: In the config file\n```text\n$cleartemp : false\n```\n\n### $customtitles : Boolean\n\nType: `config`\n\nTurns off the automatic suffix of page titles.\n\nReturns: `Boolean`\n\nBy default a view title on pages other than `/` gets ` - ` and `CONF.name` appended. `true` keeps the title as you set it.\n\nDefault: `false`.\n\nExample: In the config file\n```text\n$customtitles : true\n```\n\n### $clearcache : Number\n\nType: `config`\n\nHow often internal caches are cleared, in minutes.\n\nReturns: `Number`\n\nClears the caches of actions, paths, views, images, templates, query builders and file storages.\n\nDefault: `10`.\n\nExample: In the config file\n```text\n$clearcache (number) : 30\n```\n\n### $imageconverter : String\n\nType: `config`\n\nThe program used by the image module.\n\nReturns: `String`\n\n`gm` for GraphicsMagick, `im` for the ImageMagick `convert` command or `magick` for ImageMagick 7. See [Images](../../guides/images/).\n\nDefault: `'gm'`.\n\nExample: In the config file\n```text\n$imageconverter : magick\n```\n\n### $stats : Boolean\n\nType: `config`\n\nWrites the statistics file of the application.\n\nReturns: `Boolean`\n\nEvery minute the framework writes the usage statistics to `<main script>.json` (for example `index.js.json`). `F.load()` with a list of types without `stats` turns it off.\n\nDefault: `true`.\n\nExample: In the config file\n```text\n$stats : false\n```\n\n### $sourcemap : Boolean\n\nType: `config`\n\nWrites the source map of the application.\n\nReturns: `Boolean`\n\nWrites routes, actions, schemas and plugins to `<main script>.map` for tools. The framework sets it to the value of `DEBUG` when it loads all parts, and to `false` when `F.load()` gets a list of types without `stats`.\n\nExample: Turn off\n```text\n$sourcemap : false\n```\n\n### $npmcache : String\n\nType: `config`\n\nThe npm cache directory for NPMINSTALL().\n\nReturns: `String`\n\nPassed to npm as `NPM_CONFIG_CACHE`.\n\nDefault: `'/var/www/.npm'`.\n\nExample: In the config file\n```text\n$npmcache : /tmp/.npm\n```\n\n### $nodemodules : String\n\nType: `config`\n\nThe directory of installed npm modules.\n\nReturns: `String`\n\n`NPMINSTALL()` installs into it and `REQUIRE()` loads from it when a normal `require()` fails.\n\nDefault: `'<root>/node_modules'`.\n\nExample: In the config file\n```text\n$nodemodules : /www/shared/node_modules\n```\n\n### $python : String\n\nType: `config`\n\nThe Python command.\n\nReturns: `String`\n\nUsed by `F.python()` and `F.pipinstall()`. `PYPELINE()` always runs `python3`.\n\nDefault: `'python3'`.\n\nExample: In the config file\n```text\n$python : /usr/bin/python3.12\n```\n\n### $shell : String\n\nType: `config`\n\nThe shell for SHELL().\n\nReturns: `String`\n\nWhen set, `SHELL()` runs commands in this shell instead of the default one.\n\nDefault: `''`.\n\nExample: In the config file\n```text\n$shell : /bin/bash\n```\n\n### $wsmaxsize : Number\n\nType: `config`\n\nThe maximum size of a WebSocket message in kB.\n\nReturns: `Number`\n\nThe default limit of every WebSocket route without its own limit.\n\nDefault: `256`.\n\nExample: In the config file\n```text\n$wsmaxsize (number) : 1024\n```\n\n### $wscompress : Boolean\n\nType: `config`\n\nCompresses WebSocket messages.\n\nReturns: `Boolean`\n\nUses `permessage-deflate` when the client supports it.\n\nDefault: `true`.\n\nExample: In the config file\n```text\n$wscompress : false\n```\n\n### $wsencodedecode : Boolean\n\nType: `config`\n\nURL-encodes WebSocket messages.\n\nReturns: `Boolean`\n\n`true` encodes outgoing messages with `encodeURIComponent` and decodes incoming ones.\n\nDefault: `false`.\n\nExample: In the config file\n```text\n$wsencodedecode : true\n```\n\n### $wsmaxlatency : Number\n\nType: `config`\n\nThe maximum ping latency of a WebSocket client in milliseconds.\n\nReturns: `Number`\n\nWhen the framework pings the connections, clients without an answer or with a higher latency are closed.\n\nDefault: `2000`.\n\nExample: In the config file\n```text\n$wsmaxlatency (number) : 5000\n```\n\n### $proxytimeout : Number\n\nType: `config`\n\nThe timeout of proxied requests in seconds.\n\nReturns: `Number`\n\nUsed by `PROXY()` routes without their own timeout.\n\nDefault: `5`.\n\nExample: In the config file\n```text\n$proxytimeout (number) : 30\n```\n\n### $proxyrequest : String\n\nType: `config`\n\nA proxy server for outgoing requests.\n\nReturns: `String`\n\n`REQUEST()` and the builders that use it send requests through this proxy (`host:port`, `http://host:port`). Requests to `localhost` and `127.0.0.1` go directly.\n\nDefault: `not set`.\n\nExample: In the config file\n```text\n$proxyrequest : http://proxy.local:3128\n```\n\n### $cookie* : String|Boolean\n\nType: `config`\n\nDefaults of cookies.\n\nReturns: `String|Boolean`\n\n`$cookiesamesite` (default `Lax`) is the `SameSite` value of cookies without their own. `$cookiesecure` (default `false`) adds `Secure` to cookies that do not set `secure`.\n\nExample: In the config file\n```text\n$cookiesamesite : Strict\n$cookiesecure   : true\n```\n\n### $csrfexpiration : String\n\nType: `config`\n\nThe lifetime of CSRF tokens.\n\nReturns: `String`\n\nA time in the format of `Date.add()`. Tokens are created only when `secret_csrf` is set.\n\nDefault: `'30 minutes'`.\n\nExample: In the config file\n```text\n$csrfexpiration : 2 hours\n```\n\n### $crypto : String\n\nType: `config`\n\nA Node.js cipher for ENCRYPT() and DECRYPT().\n\nReturns: `String`\n\nWhen set (for example `aes-256-cbc`), `ENCRYPT()` and `DECRYPT()` use `crypto.createCipheriv()` with the key you pass and `$cryptoiv` as the IV; the key must have the length the cipher needs. `$cryptoiv` is created from a hash of the system; in the config file give it as hex or base64 and it becomes a `Buffer`.\n\nDefault: `not set`.\n\nExample: In the config file\n```text\n$crypto   : aes-256-cbc\n$cryptoiv : 000102030405060708090a0b0c0d0e0f\n```\n\n### $tapi* : Boolean|String\n\nType: `config`\n\nTotal API settings.\n\nReturns: `Boolean|String`\n\n`$tapi` (default `true`) allows `API('TAPI', ...)` calls; with `false` every operation except `check` fails with `totalapi_inactive`. `$tapiurl` (default `eu`) is the region in `https://<region>.api.totaljs.com/`. The token is `secret_totalapi`; `$tapisecret` is read as a fallback. `$tapimail : true` sends the e-mails through the Total API instead of SMTP (see [Sending email](../../guides/mail/)) and `$tapilogger : true` sends the audit records there (see [Audit logs](../../guides/audit-logs/)); both are `false` by default.\n\nExample: In the config file\n```text\nsecret_totalapi : your-token\n$tapiurl        : eu\n```\n\n### $tms* : Boolean|String|Number\n\nType: `config`\n\nTotal.js Message Service settings.\n\nReturns: `Boolean|String|Number`\n\n`$tms` (default `false`) opens the TMS WebSocket endpoint `$tmsurl` (default `/$tms/`). `$tmsmaxsize` (default `256`) is the message limit in kB, `$tmsclearblocked` (default `60`) clears blocked clients every N minutes, and `secret_tms` is the token clients must send. See [Message Service (TMS)](../../guides/message-service-and-apis/).\n\nExample: In the config file\n```text\n$tms       : true\nsecret_tms : my-secret\n```\n\n### $imprint : Boolean\n\nType: `config`\n\nPrints the start screen.\n\nReturns: `Boolean`\n\n`false` hides the information block (name, version, Node.js, URL) printed when the application starts.\n\nDefault: `true`.\n\nExample: In the config file\n```text\n$imprint : false\n```\n\n### $logger : Boolean\n\nType: `config`\n\nWrites console output to logs/debug.log.\n\nReturns: `Boolean`\n\n`true` redirects `console.log`, `console.warn`, `console.error`, `console.time` and `console.timeEnd` to the file `logs/debug.log`.\n\nDefault: `false`.\n\nExample: In the config file\n```text\n$logger : true\n```\n\n### $dir* : String\n\nType: `config`\n\nCustom paths of the application directories.\n\nReturns: `String`\n\n`$dir` + the name of a directory sets its absolute path: `$dirpublic`, `$dirtmp`, `$dirlogs`, `$dirdatabases`, `$dirviews`, `$dirplugins`, `$dirmodules`, `$dirresources`, `$dirtemplates`, `$dirprivate` and the others. `PATH.public()`, `PATH.databases()` and the loaders use them.\n\nExample: In the config file\n```text\n$dirpublic    : /www/cdn/public\n$dirdatabases : /data/app\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG()","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"event","name":"$reconfigure","signature":"ON('$reconfigure', function() {})","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : String|Boolean","since":"0.0.16","deprecated":false},{"type":"config","name":"$root","signature":"$root : String","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : String","since":"","deprecated":false},{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : String","since":"","deprecated":false},{"type":"config","name":"$port","signature":"$port : Number","since":"","deprecated":false},{"type":"config","name":"$ip","signature":"$ip : String","since":"","deprecated":false},{"type":"config","name":"$unixsocket","signature":"$unixsocket : String","since":"","deprecated":false},{"type":"config","name":"$timezone","signature":"$timezone : String","since":"","deprecated":false},{"type":"config","name":"$insecure","signature":"$insecure : Boolean","since":"","deprecated":false},{"type":"config","name":"$performance","signature":"$performance : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpreqlimit","signature":"$httpreqlimit : Number","since":"","deprecated":false},{"type":"config","name":"$blacklist","signature":"$blacklist : String","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag : String","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer : Number","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : Number","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles : String","since":"","deprecated":false},{"type":"config","name":"$httpchecktypes","signature":"$httpchecktypes : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage : Number","since":"","deprecated":false},{"type":"config","name":"$httpmaxkeys","signature":"$httpmaxkeys : Number","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset : String","since":"0.0.16","deprecated":false},{"type":"config","name":"$xpoweredby","signature":"$xpoweredby : String","since":"","deprecated":false},{"type":"config","name":"$minify*","signature":"$minify* : Boolean","since":"","deprecated":false},{"type":"config","name":"$filtererrors","signature":"$filtererrors : Boolean","since":"","deprecated":false},{"type":"config","name":"$cleartemp","signature":"$cleartemp : Boolean","since":"","deprecated":false},{"type":"config","name":"$customtitles","signature":"$customtitles : Boolean","since":"","deprecated":false},{"type":"config","name":"$clearcache","signature":"$clearcache : Number","since":"","deprecated":false},{"type":"config","name":"$imageconverter","signature":"$imageconverter : String","since":"","deprecated":false},{"type":"config","name":"$stats","signature":"$stats : Boolean","since":"","deprecated":false},{"type":"config","name":"$sourcemap","signature":"$sourcemap : Boolean","since":"","deprecated":false},{"type":"config","name":"$npmcache","signature":"$npmcache : String","since":"","deprecated":false},{"type":"config","name":"$nodemodules","signature":"$nodemodules : String","since":"","deprecated":false},{"type":"config","name":"$python","signature":"$python : String","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : String","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"$wsmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"$wscompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"$wsencodedecode : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"$wsmaxlatency : Number","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : Number","since":"","deprecated":false},{"type":"config","name":"$proxyrequest","signature":"$proxyrequest : String","since":"","deprecated":false},{"type":"config","name":"$cookie*","signature":"$cookie* : String|Boolean","since":"","deprecated":false},{"type":"config","name":"$csrfexpiration","signature":"$csrfexpiration : String","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : String","since":"","deprecated":false},{"type":"config","name":"$tapi*","signature":"$tapi* : Boolean|String","since":"","deprecated":false},{"type":"config","name":"$tms*","signature":"$tms* : Boolean|String|Number","since":"","deprecated":false},{"type":"config","name":"$imprint","signature":"$imprint : Boolean","since":"","deprecated":false},{"type":"config","name":"$logger","signature":"$logger : Boolean","since":"","deprecated":false},{"type":"config","name":"$dir*","signature":"$dir* : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwW5GSx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/configuration/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Konfiguration","summary":"CONF, LOADCONFIG(), DEBUG und jeder $-Schlüssel des Frameworks mit seinem Standardwert.","markdown":"---\ntitle: Konfiguration\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/configuration/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Konfiguration\n\n> CONF, LOADCONFIG(), DEBUG und jeder $-Schlüssel des Frameworks mit seinem Standardwert.\n\nJeder Schlüssel, den das Framework aus `CONF` liest, mit Typ und Standardwert, dazu `CONF`, `LOADCONFIG()`, `DEBUG` und das Event `$reconfigure`. Die Anleitung [Konfiguration](../../guides/configuration/) erklärt das Format der Datei `config`, die Typen, `.env` und die Ladereihenfolge.\n\n## API\n\n### CONF\n\nType: `property`\n\nDas globale Objekt mit der Konfiguration der Anwendung.\n\nReturns: `Object`\n\nEnthält die Standardwerte des Frameworks und jeden Schlüssel, der aus den Optionen von `F.http()`, der Datei `config`, Konfigurationsdateien von Plugins und `LOADCONFIG()` geladen wurde. `F.config` ist dasselbe Objekt. Lies es überall; schreib mit `LOADCONFIG()` hinein, wenn die Änderung abgeleitete Einstellungen aktualisieren muss.\n\nExample: Werte lesen\n```js\nexports.install = function() {\n\tROUTE('GET /about/', function($) {\n\t\t$.json({ name: CONF.name, version: CONF.version });\n\t});\n};\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nWendet Konfigurationswerte zur Laufzeit an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object|Array` | yes |  | Der Text einer Konfigurationsdatei, ein Objekt mit Schlüsseln und Werten oder ein Array von `{ id, type, value }`-Elementen (`key`/`name` und `val`/`body` werden ebenfalls akzeptiert). |\n\nParst `value` wie die Datei `config` und kopiert die Schlüssel in `CONF`. In einem Objekt oder einem Array werden die Werte `false`, `0` und `''` als `undefined` gespeichert. Spezielle Schlüssel werden verarbeitet: `$root` wird normalisiert und `$api` vorangestellt, `$timezone` setzt `process.env.TZ`, `$port` wird zu einer Zahl, `$httpfiles` fügt Endungen hinzu, `$cryptoiv` wird zu einem `Buffer`, `smtp`/`mail`/`mail_smtp`/`mail_smtp_options` bauen `CONF.smtp` auf, `totalapi` setzt das Total-API-Token. Danach aktualisiert es die Verzeichnisse, den Logger (`$logger`), die CORS-Liste und TMS und löst `$reconfigure` aus. Das Framework ruft es selbst für die Datei `config` auf.\n\nExample: Text\n```js\nLOADCONFIG('$httptimeout (number) : 15\\nmaintenance : true');\n```\n\nExample: Array mit Typen\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '25' },\n\t{ id: 'tags', type: 'array', value: 'a, b, c' }\n]);\n```\n\nExample: Objekt\n```js\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n```\n\n### DEBUG\n\nType: `property`\n\ntrue im Debug-Modus, false im Release-Modus.\n\nReturns: `Boolean`\n\nEin globaler Boolean. Er beginnt als `process.env.NODE_ENV !== 'production'`. Der Debug-Runner setzt ihn auf `true` und der Release-Runner auf `false`, bevor die Anwendung lädt, daher entscheidet `NODE_ENV` über den Modus, wenn die Anwendung `F.http()` oder `F.load()` ohne Runner aufruft. Das Framework verwendet ihn für das Caching von Views und statischen Dateien, die Minifizierung und die Source Map (`$sourcemap` folgt ihm).\n\nExample: Bedingter Code\n```js\nif (DEBUG)\n\tconsole.log('Debug mode');\n```\n\n### ON('$reconfigure', function() {})\n\nType: `event`\n\nWird ausgelöst, nachdem LOADCONFIG() neue Werte angewendet hat.\n\nWird am Ende jedes Aufrufs von `LOADCONFIG()` ausgelöst, einschließlich des Ladens der Datei `config` beim Start. Verwende es, um eigene Objekte zu aktualisieren, die von Konfigurationswerten abhängen.\n\nExample: Einen Client aktualisieren\n```js\nON('$reconfigure', function() {\n\tMAIN.client = createclient(CONF.service_url);\n});\n```\n\n### totalapi : String|Boolean\n\nType: `config` · Since: `0.0.16`\n\nSetzt das Total-API-Token oder schaltet Total API ein oder aus.\n\nReturns: `String|Boolean`\n\nEin String mit mehr als fünf Zeichen wird als `CONF.secret_totalapi` gespeichert, das Token für Aufrufe von `API('TAPI', ...)` und `TotalAPI()`. Jeder andere Wert wird als `$tapi` gespeichert.\n\nExample: In der Konfigurationsdatei\n```text\ntotalapi : your-total-api-token\n```\n\n### $root : String\n\nType: `config`\n\nEin URL-Präfix für die gesamte Anwendung.\n\nReturns: `String`\n\nWird so normalisiert, dass es mit `/` beginnt und endet. Route-URLs erhalten das Präfix (API-Routen über `$api`), statische Dateien werden darunter ausgeliefert, und `F.virtualpath()` fügt es hinzu. Verwende es, wenn die Anwendung hinter einem Proxy unter einem Unterpfad läuft.\n\nStandard: `''`.\n\nExample: In der Konfigurationsdatei\n```text\n$root : /app/\n```\n\n### $api : String\n\nType: `config`\n\nDer Standard-API-Endpunkt.\n\nReturns: `String`\n\nEin `?` in einer Route-URL wird durch diesen Wert ersetzt, sodass `ROUTE('API ?/users/ ...')` auf `/api/users/` lauscht. Mit `$root` wird das Präfix hinzugefügt.\n\nStandard: `'/api/'`.\n\nExample: In der Konfigurationsdatei\n```text\n$api : /v1/\n```\n\n### $mcp : Boolean\n\nType: `config`\n\nSchaltet den MCP-Server ein.\n\nReturns: `Boolean`\n\n`true` erstellt die Route `POST /$mcp/`, unter der KI-Clients die Aktionen mit `mcp: true` auflisten und aufrufen. Die Route wird erstellt, sobald die Anwendung bereit ist, also setze den Schlüssel in der Datei `config` oder vor dem Start. Siehe [MCP-Server](../../guides/mcp-server/).\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\n$mcp : true\n```\n\n### $cors : String\n\nType: `config`\n\nFür Cross-Origin-Requests erlaubte Origins.\n\nReturns: `String`\n\n`*` erlaubt jede Origin. Andernfalls eine Liste von Origins, getrennt durch `,`, `;` oder `|`, die mit dem Header `Origin` verglichen wird (zum Beispiel `https://app.example.com`). Ein Eintrag, der mit `*` beginnt, passt auf jede Origin, die den Rest enthält (`*example.com`). Requests vom selben Host sind immer erlaubt; andere Origins erhalten den Fehler 400. `CORS()` ändert den Wert im Code; siehe [Routing](../../guides/routing/#cors).\n\nStandard: `''`.\n\nExample: In der Konfigurationsdatei\n```text\n$cors : https://app.example.com, *example.org\n```\n\n### $port : Number\n\nType: `config`\n\nDer Port des HTTP-Servers.\n\nReturns: `Number`\n\nDer Wert wird in eine Zahl konvertiert. Lass den Schlüssel für den automatischen Port weg: die Option `port` von `F.http()`, die Umgebungsvariable `PORT`, die erste 3- bis 5-stellige Zahl in den Kommandozeilenargumenten oder 8000.\n\nStandard: `'auto'`.\n\nExample: In der Konfigurationsdatei\n```text\n$port : 8000\n```\n\n### $ip : String\n\nType: `config`\n\nDie IP-Adresse, auf der der HTTP-Server lauscht.\n\nReturns: `String`\n\nDie Option `ip` von `F.http()` überschreibt sie. Verwende `127.0.0.1`, um nur lokale Verbindungen anzunehmen.\n\nStandard: `'0.0.0.0'`.\n\nExample: In der Konfigurationsdatei\n```text\n$ip : 127.0.0.1\n```\n\n### $unixsocket : String\n\nType: `config`\n\nEin Unix-Socket-Pfad für den HTTP-Server.\n\nReturns: `String`\n\nWenn er gesetzt ist (oder wenn `F.http()` die Option `unixsocket` erhält), lauscht der Server auf dem Socket statt auf einem Port.\n\nStandard: `''`.\n\nExample: In der Konfigurationsdatei\n```text\n$unixsocket : /var/run/app.sock\n```\n\n### $timezone : String\n\nType: `config`\n\nDie Zeitzone des Prozesses.\n\nReturns: `String`\n\nWird in `process.env.TZ` kopiert, sodass alle `Date`-Werte des Prozesses sie verwenden.\n\nStandard: `'utc'`.\n\nExample: In der Konfigurationsdatei\n```text\n$timezone : Europe/Bratislava\n```\n\n### $insecure : Boolean\n\nType: `config`\n\nAkzeptiert ungültige TLS-Zertifikate bei ausgehenden Requests.\n\nReturns: `Boolean`\n\nSetzt `process.env.NODE_TLS_REJECT_UNAUTHORIZED` bei `true` auf `0` und sonst auf `1`. Verwende es nur in der Entwicklung mit Servern mit selbstsignierten Zertifikaten.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\n$insecure : true\n```\n\n### $performance : Boolean\n\nType: `config`\n\nOptimiert die HTTP-Sockets für viele Verbindungen.\n\nReturns: `Boolean`\n\nSetzt `maxSockets` des globalen HTTP-Agents auf 9999 und schaltet `setNoDelay` und Keep-Alive für eingehende Verbindungen ein.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\n$performance : true\n```\n\n### $httpreqlimit : Number\n\nType: `config`\n\nDie maximale Anzahl an Requests pro IP-Adresse und Minute.\n\nReturns: `Number`\n\n`0` schaltet das Limit ab. Oberhalb des Limits erhalten Requests den Fehler 503, bis die Zähler in der nächsten Minute zurückgesetzt werden.\n\nStandard: `0`.\n\nExample: In der Konfigurationsdatei\n```text\n$httpreqlimit (number) : 300\n```\n\n### $blacklist : String\n\nType: `config`\n\nBlockierte IP-Adressen.\n\nReturns: `String`\n\nEin String mit IP-Adressen, zum Beispiel durch Kommas getrennt. HTTP-Anfragen von einer darin gefundenen IP-Adresse erhalten den Fehler 400, und WebSocket-Verbindungen von ihr werden geschlossen.\n\nStandard: `''`.\n\nExample: In der Konfigurationsdatei\n```text\n$blacklist : 10.0.0.5, 10.0.0.6\n```\n\n### $httpcompress : Boolean\n\nType: `config`\n\nKomprimiert Responses mit gzip.\n\nReturns: `Boolean`\n\nWenn der Client gzip akzeptiert, werden Textantworten über 256 Bytes und komprimierbare statische Dateien komprimiert.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\n$httpcompress : false\n```\n\n### $httpetag : String\n\nType: `config`\n\nEin Wert, der dem ETag statischer Dateien und gecachter Antworten hinzugefügt wird.\n\nReturns: `String`\n\nIst er leer, wird er aus `CONF.version` ohne Punkte und Leerzeichen erzeugt, sodass eine neue Version die Browser-Caches ungültig macht.\n\nStandard: `''`.\n\nExample: In der Konfigurationsdatei\n```text\n$httpetag : build42\n```\n\n### $httpmaxsize : Number\n\nType: `config`\n\nDie maximale Größe eines Request-Bodys in kB.\n\nReturns: `Number`\n\nDas Standardlimit jeder HTTP-Route ohne eigenes Limit.\n\nStandard: `256`.\n\nExample: In der Konfigurationsdatei\n```text\n$httpmaxsize (number) : 1024\n```\n\n### $httprangebuffer : Number\n\nType: `config`\n\nDie Größe eines Chunks einer Range-Antwort in kB.\n\nReturns: `Number`\n\nWird für `Range`-Requests auf statische Dateien (Video, Audio) verwendet, wenn der Client das Ende nicht angibt.\n\nStandard: `5120`.\n\nExample: In der Konfigurationsdatei\n```text\n$httprangebuffer (number) : 2048\n```\n\n### $httptimeout : Number\n\nType: `config`\n\nDas Request-Timeout in Sekunden.\n\nReturns: `Number`\n\nEine Route kann ihr eigenes Timeout setzen. Requests werden alle fünf Sekunden geprüft.\n\nStandard: `5`.\n\nExample: In der Konfigurationsdatei\n```text\n$httptimeout (number) : 10\n```\n\n### $httpfiles : String\n\nType: `config`\n\nDateiendungen, die als statische Dateien ausgeliefert werden.\n\nReturns: `String`\n\nIn der Konfigurationsdatei eine kommagetrennte Liste von Endungen, die zu den Standardwerten hinzugefügt werden (`jpg`, `png`, `css`, `js`, `json`, `pdf`, `mp4` und viele mehr). Im Code ist es ein Objekt mit `true` für jede erlaubte Endung.\n\nStandard: `common web extensions`.\n\nExample: In der Konfigurationsdatei\n```text\n$httpfiles : glb, gltf\n```\n\n### $httpchecktypes : Boolean\n\nType: `config`\n\nPrüft den Content-Type hochgeladener Dateien.\n\nReturns: `Boolean`\n\nNur für `multipart/form-data`. `false` überspringt die Prüfung.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\n$httpchecktypes : false\n```\n\n### $httpmaxage : Number\n\nType: `config`\n\nDas max-age gecachter Antworten in Sekunden.\n\nReturns: `Number`\n\nWird im Header `Cache-Control` statischer Dateien und von mit `controller.httpcache()` gecachten Antworten verwendet.\n\nStandard: `60`.\n\nExample: In der Konfigurationsdatei\n```text\n$httpmaxage (number) : 300\n```\n\n### $httpmaxkeys : Number\n\nType: `config`\n\nLimits für URL-kodierte Daten.\n\nReturns: `Number`\n\n`$httpmaxkeys` ist die maximale Anzahl an Schlüsseln, die aus einem Query-String oder einem URL-kodierten Body geparst werden. `$httpmaxkey` (Standard `25`) ist die maximale Länge eines Schlüssels; längere Schlüssel werden verworfen.\n\nStandard: `33`.\n\nExample: In der Konfigurationsdatei\n```text\n$httpmaxkeys (number) : 100\n$httpmaxkey (number)  : 50\n```\n\n### $httpcacheoffset : String\n\nType: `config` · Since: `0.0.16`\n\nVerschiebt das Last-Modified-Datum statischer Dateien.\n\nReturns: `String`\n\nEin Zeitversatz im Format von `Date.add()`, zum Beispiel `1 minute` oder `-5 minutes`. Er wird im `Last-Modified`-Header zur Änderungszeit der Datei addiert.\n\nStandard: `''`.\n\nExample: In der Konfigurationsdatei\n```text\n$httpcacheoffset : 1 minute\n```\n\n### $xpoweredby : String\n\nType: `config`\n\nDer Wert des Headers X-Powered-By.\n\nReturns: `String`\n\nEin leerer Wert entfernt den Header.\n\nStandard: `'Total.js'`.\n\nExample: In der Konfigurationsdatei\n```text\n$xpoweredby :\n```\n\n### $minify* : Boolean\n\nType: `config`\n\nMinifizierung von JavaScript, CSS und HTML.\n\nReturns: `Boolean`\n\n`$minifyjs`, `$minifycss` und `$minifyhtml` (alle standardmäßig `true`) schalten die Minifizierung statischer `.js`- und `.css`-Dateien, von Inline-Code und gerendertem HTML ein oder aus.\n\nExample: In der Konfigurationsdatei\n```text\n$minifyhtml : false\n$minifyjs   : true\n$minifycss  : true\n```\n\n### $filtererrors : Boolean\n\nType: `config`\n\nIgnoriert harmlose nicht abgefangene Fehler.\n\nReturns: `Boolean`\n\nNicht abgefangene Fehler `EPIPE`, `invalid distance` und `ERR_IPC_CHANNEL_CLOSED` werden nicht protokolliert.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\n$filtererrors : false\n```\n\n### $cleartemp : Boolean\n\nType: `config`\n\nLeert das tmp-Verzeichnis beim Start.\n\nReturns: `Boolean`\n\nLöscht beim Laden der Anwendung die Dateien `.js`, `.css`, `.html`, `.htm`, `.tmp` und `.upload` im Verzeichnis `tmp`.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\n$cleartemp : false\n```\n\n### $customtitles : Boolean\n\nType: `config`\n\nSchaltet das automatische Suffix der Seitentitel ab.\n\nReturns: `Boolean`\n\nStandardmäßig werden an einen View-Titel auf anderen Seiten als `/` ` - ` und `CONF.name` angehängt. `true` lässt den Titel so, wie du ihn gesetzt hast.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\n$customtitles : true\n```\n\n### $clearcache : Number\n\nType: `config`\n\nWie oft interne Caches geleert werden, in Minuten.\n\nReturns: `Number`\n\nLeert die Caches von Aktionen, Pfaden, Views, Bildern, Templates, Query-Buildern und Dateispeichern.\n\nStandard: `10`.\n\nExample: In der Konfigurationsdatei\n```text\n$clearcache (number) : 30\n```\n\n### $imageconverter : String\n\nType: `config`\n\nDas Programm, das das Bildmodul verwendet.\n\nReturns: `String`\n\n`gm` für GraphicsMagick, `im` für den ImageMagick-Befehl `convert` oder `magick` für ImageMagick 7. Siehe [Bilder](../../guides/images/).\n\nStandard: `'gm'`.\n\nExample: In der Konfigurationsdatei\n```text\n$imageconverter : magick\n```\n\n### $stats : Boolean\n\nType: `config`\n\nSchreibt die Statistikdatei der Anwendung.\n\nReturns: `Boolean`\n\nJede Minute schreibt das Framework die Nutzungsstatistiken nach `<main script>.json` (zum Beispiel `index.js.json`). `F.load()` mit einer Liste von Typen ohne `stats` schaltet es ab.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\n$stats : false\n```\n\n### $sourcemap : Boolean\n\nType: `config`\n\nSchreibt die Source Map der Anwendung.\n\nReturns: `Boolean`\n\nSchreibt Routen, Aktionen, Schemas und Plugins für Tools nach `<main script>.map`. Das Framework setzt es auf den Wert von `DEBUG`, wenn es alle Teile lädt, und auf `false`, wenn `F.load()` eine Liste von Typen ohne `stats` erhält.\n\nExample: Abschalten\n```text\n$sourcemap : false\n```\n\n### $npmcache : String\n\nType: `config`\n\nDas npm-Cache-Verzeichnis für NPMINSTALL().\n\nReturns: `String`\n\nWird an npm als `NPM_CONFIG_CACHE` übergeben.\n\nStandard: `'/var/www/.npm'`.\n\nExample: In der Konfigurationsdatei\n```text\n$npmcache : /tmp/.npm\n```\n\n### $nodemodules : String\n\nType: `config`\n\nDas Verzeichnis der installierten npm-Module.\n\nReturns: `String`\n\n`NPMINSTALL()` installiert dorthin, und `REQUIRE()` lädt von dort, wenn ein normales `require()` fehlschlägt.\n\nStandard: `'<root>/node_modules'`.\n\nExample: In der Konfigurationsdatei\n```text\n$nodemodules : /www/shared/node_modules\n```\n\n### $python : String\n\nType: `config`\n\nDer Python-Befehl.\n\nReturns: `String`\n\nWird von `F.python()` und `F.pipinstall()` verwendet. `PYPELINE()` führt immer `python3` aus.\n\nStandard: `'python3'`.\n\nExample: In der Konfigurationsdatei\n```text\n$python : /usr/bin/python3.12\n```\n\n### $shell : String\n\nType: `config`\n\nDie Shell für SHELL().\n\nReturns: `String`\n\nWenn sie gesetzt ist, führt `SHELL()` Befehle in dieser Shell statt in der Standard-Shell aus.\n\nStandard: `''`.\n\nExample: In der Konfigurationsdatei\n```text\n$shell : /bin/bash\n```\n\n### $wsmaxsize : Number\n\nType: `config`\n\nDie maximale Größe einer WebSocket-Nachricht in kB.\n\nReturns: `Number`\n\nDas Standardlimit jeder WebSocket-Route ohne eigenes Limit.\n\nStandard: `256`.\n\nExample: In der Konfigurationsdatei\n```text\n$wsmaxsize (number) : 1024\n```\n\n### $wscompress : Boolean\n\nType: `config`\n\nKomprimiert WebSocket-Nachrichten.\n\nReturns: `Boolean`\n\nVerwendet `permessage-deflate`, wenn der Client es unterstützt.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\n$wscompress : false\n```\n\n### $wsencodedecode : Boolean\n\nType: `config`\n\nURL-kodiert WebSocket-Nachrichten.\n\nReturns: `Boolean`\n\n`true` kodiert ausgehende Nachrichten mit `encodeURIComponent` und dekodiert eingehende.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\n$wsencodedecode : true\n```\n\n### $wsmaxlatency : Number\n\nType: `config`\n\nDie maximale Ping-Latenz eines WebSocket-Clients in Millisekunden.\n\nReturns: `Number`\n\nWenn das Framework die Verbindungen anpingt, werden Clients ohne Antwort oder mit höherer Latenz geschlossen.\n\nStandard: `2000`.\n\nExample: In der Konfigurationsdatei\n```text\n$wsmaxlatency (number) : 5000\n```\n\n### $proxytimeout : Number\n\nType: `config`\n\nDas Timeout weitergeleiteter Requests in Sekunden.\n\nReturns: `Number`\n\nWird von `PROXY()`-Routen ohne eigenes Timeout verwendet.\n\nStandard: `5`.\n\nExample: In der Konfigurationsdatei\n```text\n$proxytimeout (number) : 30\n```\n\n### $proxyrequest : String\n\nType: `config`\n\nEin Proxy-Server für ausgehende Requests.\n\nReturns: `String`\n\n`REQUEST()` und die Builder, die es verwenden, senden Requests über diesen Proxy (`host:port`, `http://host:port`). Requests an `localhost` und `127.0.0.1` gehen direkt.\n\nStandard: `not set`.\n\nExample: In der Konfigurationsdatei\n```text\n$proxyrequest : http://proxy.local:3128\n```\n\n### $cookie* : String|Boolean\n\nType: `config`\n\nStandardwerte von Cookies.\n\nReturns: `String|Boolean`\n\n`$cookiesamesite` (Standard `Lax`) ist der `SameSite`-Wert von Cookies ohne eigenen Wert. `$cookiesecure` (Standard `false`) fügt `Secure` zu Cookies hinzu, die `secure` nicht setzen.\n\nExample: In der Konfigurationsdatei\n```text\n$cookiesamesite : Strict\n$cookiesecure   : true\n```\n\n### $csrfexpiration : String\n\nType: `config`\n\nDie Lebensdauer von CSRF-Tokens.\n\nReturns: `String`\n\nEine Zeitangabe im Format von `Date.add()`. Tokens werden nur erzeugt, wenn `secret_csrf` gesetzt ist.\n\nStandard: `'30 minutes'`.\n\nExample: In der Konfigurationsdatei\n```text\n$csrfexpiration : 2 hours\n```\n\n### $crypto : String\n\nType: `config`\n\nEine Node.js-Chiffre für ENCRYPT() und DECRYPT().\n\nReturns: `String`\n\nWenn sie gesetzt ist (zum Beispiel `aes-256-cbc`), verwenden `ENCRYPT()` und `DECRYPT()` `crypto.createCipheriv()` mit dem übergebenen Schlüssel und `$cryptoiv` als IV; der Schlüssel muss die Länge haben, die die Chiffre benötigt. `$cryptoiv` wird aus einem Hash des Systems erzeugt; gib ihn in der Konfigurationsdatei als Hex oder Base64 an, dann wird er zu einem `Buffer`.\n\nStandard: `not set`.\n\nExample: In der Konfigurationsdatei\n```text\n$crypto   : aes-256-cbc\n$cryptoiv : 000102030405060708090a0b0c0d0e0f\n```\n\n### $tapi* : Boolean|String\n\nType: `config`\n\nEinstellungen der Total API.\n\nReturns: `Boolean|String`\n\n`$tapi` (Standard `true`) erlaubt Aufrufe von `API('TAPI', ...)`; mit `false` schlägt jede Operation außer `check` mit `totalapi_inactive` fehl. `$tapiurl` (Standard `eu`) ist die Region in `https://<region>.api.totaljs.com/`. Das Token ist `secret_totalapi`; `$tapisecret` wird als Ersatz gelesen. `$tapimail : true` sendet die E-Mails über die Total API statt über SMTP (siehe [E-Mails senden](../../guides/mail/)), und `$tapilogger : true` sendet die Audit-Einträge dorthin (siehe [Audit-Logs](../../guides/audit-logs/)); beide sind standardmäßig `false`.\n\nExample: In der Konfigurationsdatei\n```text\nsecret_totalapi : your-token\n$tapiurl        : eu\n```\n\n### $tms* : Boolean|String|Number\n\nType: `config`\n\nEinstellungen des Total.js Message Service.\n\nReturns: `Boolean|String|Number`\n\n`$tms` (Standard `false`) öffnet den TMS-WebSocket-Endpunkt `$tmsurl` (Standard `/$tms/`). `$tmsmaxsize` (Standard `256`) ist das Nachrichtenlimit in kB, `$tmsclearblocked` (Standard `60`) entsperrt blockierte Clients alle N Minuten, und `secret_tms` ist das Token, das Clients senden müssen. Siehe [Message Service (TMS)](../../guides/message-service-and-apis/).\n\nExample: In der Konfigurationsdatei\n```text\n$tms       : true\nsecret_tms : my-secret\n```\n\n### $imprint : Boolean\n\nType: `config`\n\nGibt den Startbildschirm aus.\n\nReturns: `Boolean`\n\n`false` blendet den Informationsblock aus (Name, Version, Node.js, URL), der beim Start der Anwendung ausgegeben wird.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\n$imprint : false\n```\n\n### $logger : Boolean\n\nType: `config`\n\nSchreibt die Konsolenausgabe nach logs/debug.log.\n\nReturns: `Boolean`\n\n`true` leitet `console.log`, `console.warn`, `console.error`, `console.time` und `console.timeEnd` in die Datei `logs/debug.log` um.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\n$logger : true\n```\n\n### $dir* : String\n\nType: `config`\n\nEigene Pfade der Anwendungsverzeichnisse.\n\nReturns: `String`\n\n`$dir` + der Name eines Verzeichnisses setzt dessen absoluten Pfad: `$dirpublic`, `$dirtmp`, `$dirlogs`, `$dirdatabases`, `$dirviews`, `$dirplugins`, `$dirmodules`, `$dirresources`, `$dirtemplates`, `$dirprivate` und die übrigen. `PATH.public()`, `PATH.databases()` und die Loader verwenden sie.\n\nExample: In der Konfigurationsdatei\n```text\n$dirpublic    : /www/cdn/public\n$dirdatabases : /data/app\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG()","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"event","name":"$reconfigure","signature":"ON('$reconfigure', function() {})","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : String|Boolean","since":"0.0.16","deprecated":false},{"type":"config","name":"$root","signature":"$root : String","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : String","since":"","deprecated":false},{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : String","since":"","deprecated":false},{"type":"config","name":"$port","signature":"$port : Number","since":"","deprecated":false},{"type":"config","name":"$ip","signature":"$ip : String","since":"","deprecated":false},{"type":"config","name":"$unixsocket","signature":"$unixsocket : String","since":"","deprecated":false},{"type":"config","name":"$timezone","signature":"$timezone : String","since":"","deprecated":false},{"type":"config","name":"$insecure","signature":"$insecure : Boolean","since":"","deprecated":false},{"type":"config","name":"$performance","signature":"$performance : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpreqlimit","signature":"$httpreqlimit : Number","since":"","deprecated":false},{"type":"config","name":"$blacklist","signature":"$blacklist : String","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag : String","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer : Number","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : Number","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles : String","since":"","deprecated":false},{"type":"config","name":"$httpchecktypes","signature":"$httpchecktypes : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage : Number","since":"","deprecated":false},{"type":"config","name":"$httpmaxkeys","signature":"$httpmaxkeys : Number","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset : String","since":"0.0.16","deprecated":false},{"type":"config","name":"$xpoweredby","signature":"$xpoweredby : String","since":"","deprecated":false},{"type":"config","name":"$minify*","signature":"$minify* : Boolean","since":"","deprecated":false},{"type":"config","name":"$filtererrors","signature":"$filtererrors : Boolean","since":"","deprecated":false},{"type":"config","name":"$cleartemp","signature":"$cleartemp : Boolean","since":"","deprecated":false},{"type":"config","name":"$customtitles","signature":"$customtitles : Boolean","since":"","deprecated":false},{"type":"config","name":"$clearcache","signature":"$clearcache : Number","since":"","deprecated":false},{"type":"config","name":"$imageconverter","signature":"$imageconverter : String","since":"","deprecated":false},{"type":"config","name":"$stats","signature":"$stats : Boolean","since":"","deprecated":false},{"type":"config","name":"$sourcemap","signature":"$sourcemap : Boolean","since":"","deprecated":false},{"type":"config","name":"$npmcache","signature":"$npmcache : String","since":"","deprecated":false},{"type":"config","name":"$nodemodules","signature":"$nodemodules : String","since":"","deprecated":false},{"type":"config","name":"$python","signature":"$python : String","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : String","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"$wsmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"$wscompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"$wsencodedecode : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"$wsmaxlatency : Number","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : Number","since":"","deprecated":false},{"type":"config","name":"$proxyrequest","signature":"$proxyrequest : String","since":"","deprecated":false},{"type":"config","name":"$cookie*","signature":"$cookie* : String|Boolean","since":"","deprecated":false},{"type":"config","name":"$csrfexpiration","signature":"$csrfexpiration : String","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : String","since":"","deprecated":false},{"type":"config","name":"$tapi*","signature":"$tapi* : Boolean|String","since":"","deprecated":false},{"type":"config","name":"$tms*","signature":"$tms* : Boolean|String|Number","since":"","deprecated":false},{"type":"config","name":"$imprint","signature":"$imprint : Boolean","since":"","deprecated":false},{"type":"config","name":"$logger","signature":"$logger : Boolean","since":"","deprecated":false},{"type":"config","name":"$dir*","signature":"$dir* : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwW5GSx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/configuration/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Configuración","summary":"CONF, LOADCONFIG(), DEBUG y cada clave $ del framework con su valor por defecto.","markdown":"---\ntitle: \"Configuración\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/configuration/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Configuración\n\n> CONF, LOADCONFIG(), DEBUG y cada clave $ del framework con su valor por defecto.\n\nCada clave que el framework lee de `CONF`, con su tipo y su valor por defecto, además de `CONF`, `LOADCONFIG()`, `DEBUG` y el evento `$reconfigure`. La guía [Configuración](../../guides/configuration/) explica el formato del archivo `config`, los tipos, `.env` y el orden de carga.\n\n## API\n\n### CONF\n\nType: `property`\n\nEl objeto global con la configuración de la aplicación.\n\nReturns: `Object`\n\nContiene los valores por defecto del framework y cada clave cargada desde las opciones de `F.http()`, el archivo `config`, los archivos config de los plugins y `LOADCONFIG()`. `F.config` es el mismo objeto. Léelo en cualquier lugar; escribe en él con `LOADCONFIG()` cuando el cambio deba actualizar los ajustes derivados.\n\nExample: Leer valores\n```js\nexports.install = function() {\n\tROUTE('GET /about/', function($) {\n\t\t$.json({ name: CONF.name, version: CONF.version });\n\t});\n};\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nAplica valores de configuración en tiempo de ejecución.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object|Array` | yes |  | El texto de un archivo config, un objeto de claves y valores, o un array de elementos `{ id, type, value }` (también se aceptan `key`/`name` y `val`/`body`). |\n\nAnaliza `value` como el archivo `config` y copia las claves en `CONF`. En un objeto o un array, los valores `false`, `0` y `''` se guardan como `undefined`. Las claves especiales se procesan: `$root` se normaliza y se antepone a `$api`, `$timezone` establece `process.env.TZ`, `$port` se convierte en número, `$httpfiles` añade extensiones, `$cryptoiv` se convierte en un `Buffer`, `smtp`/`mail`/`mail_smtp`/`mail_smtp_options` construyen `CONF.smtp` y `totalapi` establece el token de Total API. Después actualiza los directorios, el logger (`$logger`), la lista CORS y TMS, y emite `$reconfigure`. El framework lo llama para el propio archivo `config`.\n\nExample: Texto\n```js\nLOADCONFIG('$httptimeout (number) : 15\\nmaintenance : true');\n```\n\nExample: Array con tipos\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '25' },\n\t{ id: 'tags', type: 'array', value: 'a, b, c' }\n]);\n```\n\nExample: Objeto\n```js\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n```\n\n### DEBUG\n\nType: `property`\n\ntrue en modo debug, false en modo release.\n\nReturns: `Boolean`\n\nUn booleano global. Empieza como `process.env.NODE_ENV !== 'production'`. El runner de debug lo establece a `true` y el runner de release lo establece a `false` antes de cargar la aplicación, así `NODE_ENV` decide el modo cuando la aplicación llama a `F.http()` o `F.load()` sin un runner. El framework lo usa para la caché de vistas y archivos estáticos, la minificación y el mapa de código fuente (`$sourcemap` lo sigue).\n\nExample: Código condicional\n```js\nif (DEBUG)\n\tconsole.log('Debug mode');\n```\n\n### ON('$reconfigure', function() {})\n\nType: `event`\n\nSe emite después de que LOADCONFIG() aplica nuevos valores.\n\nSe emite al final de cada llamada a `LOADCONFIG()`, incluida la carga del archivo `config` al arrancar. Úsalo para actualizar tus propios objetos que dependen de valores de configuración.\n\nExample: Actualizar un cliente\n```js\nON('$reconfigure', function() {\n\tMAIN.client = createclient(CONF.service_url);\n});\n```\n\n### totalapi : String|Boolean\n\nType: `config` · Since: `0.0.16`\n\nEstablece el token de Total API o activa o desactiva Total API.\n\nReturns: `String|Boolean`\n\nUn string de más de cinco caracteres se guarda como `CONF.secret_totalapi`, el token para las llamadas `API('TAPI', ...)` y `TotalAPI()`. Cualquier otro valor se guarda como `$tapi`.\n\nExample: En el archivo de configuración\n```text\ntotalapi : your-total-api-token\n```\n\n### $root : String\n\nType: `config`\n\nUn prefijo de URL para toda la aplicación.\n\nReturns: `String`\n\nSe normaliza para que empiece y termine por `/`. Las URLs de las rutas reciben el prefijo (las rutas de API a través de `$api`), los archivos estáticos se sirven bajo él y `F.virtualpath()` lo añade. Úsalo cuando la aplicación se ejecute bajo una subruta detrás de un proxy.\n\nValor por defecto: `''`.\n\nExample: En el archivo config\n```text\n$root : /app/\n```\n\n### $api : String\n\nType: `config`\n\nEl endpoint de API por defecto.\n\nReturns: `String`\n\nUn `?` en la URL de una ruta se reemplaza por este valor, así que `ROUTE('API ?/users/ ...')` escucha en `/api/users/`. Con `$root`, se le añade el prefijo.\n\nValor por defecto: `'/api/'`.\n\nExample: En el archivo config\n```text\n$api : /v1/\n```\n\n### $mcp : Boolean\n\nType: `config`\n\nActiva el servidor MCP.\n\nReturns: `Boolean`\n\n`true` crea la ruta `POST /$mcp/`, donde los clientes de IA listan y llaman a las acciones que tienen `mcp: true`. La ruta se crea cuando la aplicación está lista, así que establece la clave en el archivo `config` o antes del arranque. Consulta [Servidor MCP](../../guides/mcp-server/).\n\nPor defecto: `false`.\n\nExample: En el archivo config\n```text\n$mcp : true\n```\n\n### $cors : String\n\nType: `config`\n\nOrígenes permitidos para peticiones de origen cruzado.\n\nReturns: `String`\n\n`*` permite todos los orígenes. Si no, una lista de orígenes separados por `,`, `;` o `|`, que se compara con la cabecera `Origin` (por ejemplo `https://app.example.com`). Un elemento que empieza por `*` coincide con todos los orígenes que contienen el resto (`*example.com`). Las peticiones desde el mismo host siempre se permiten; los demás orígenes reciben el error 400. `CORS()` cambia el valor desde el código; consulta [Enrutamiento](../../guides/routing/#cors).\n\nValor por defecto: `''`.\n\nExample: En el archivo config\n```text\n$cors : https://app.example.com, *example.org\n```\n\n### $port : Number\n\nType: `config`\n\nEl puerto del servidor HTTP.\n\nReturns: `Number`\n\nEl valor se convierte en número. No indiques la clave para usar el puerto automático: la opción `port` de `F.http()`, la variable de entorno `PORT`, el primer número de 3 a 5 dígitos de los argumentos de la línea de comandos, o 8000.\n\nValor por defecto: `'auto'`.\n\nExample: En el archivo config\n```text\n$port : 8000\n```\n\n### $ip : String\n\nType: `config`\n\nLa dirección IP en la que escucha el servidor HTTP.\n\nReturns: `String`\n\nLa opción `ip` de `F.http()` la sobrescribe. Usa `127.0.0.1` para aceptar solo conexiones locales.\n\nValor por defecto: `'0.0.0.0'`.\n\nExample: En el archivo config\n```text\n$ip : 127.0.0.1\n```\n\n### $unixsocket : String\n\nType: `config`\n\nUna ruta de socket Unix para el servidor HTTP.\n\nReturns: `String`\n\nCuando se establece (o cuando `F.http()` recibe la opción `unixsocket`), el servidor escucha en el socket en lugar de en un puerto.\n\nValor por defecto: `''`.\n\nExample: En el archivo config\n```text\n$unixsocket : /var/run/app.sock\n```\n\n### $timezone : String\n\nType: `config`\n\nLa zona horaria del proceso.\n\nReturns: `String`\n\nSe copia en `process.env.TZ`, así que todos los valores `Date` del proceso la usan.\n\nValor por defecto: `'utc'`.\n\nExample: En el archivo config\n```text\n$timezone : Europe/Bratislava\n```\n\n### $insecure : Boolean\n\nType: `config`\n\nAcepta certificados TLS no válidos en las peticiones salientes.\n\nReturns: `Boolean`\n\nEstablece `process.env.NODE_TLS_REJECT_UNAUTHORIZED` en `0` cuando es `true` y en `1` en caso contrario. Úsalo solo en desarrollo contra servidores autofirmados.\n\nValor por defecto: `false`.\n\nExample: En el archivo config\n```text\n$insecure : true\n```\n\n### $performance : Boolean\n\nType: `config`\n\nAjusta los sockets HTTP para muchas conexiones.\n\nReturns: `Boolean`\n\nEstablece `maxSockets` del agente HTTP global en 9999 y activa `setNoDelay` y keep-alive para las conexiones entrantes.\n\nValor por defecto: `false`.\n\nExample: En el archivo config\n```text\n$performance : true\n```\n\n### $httpreqlimit : Number\n\nType: `config`\n\nEl número máximo de peticiones por dirección IP y minuto.\n\nReturns: `Number`\n\n`0` desactiva el límite. Por encima del límite, las peticiones reciben el error 503 hasta que los contadores se borran en el minuto siguiente.\n\nValor por defecto: `0`.\n\nExample: En el archivo config\n```text\n$httpreqlimit (number) : 300\n```\n\n### $blacklist : String\n\nType: `config`\n\nDirecciones IP bloqueadas.\n\nReturns: `String`\n\nUn string de direcciones IP, por ejemplo separadas por comas. Las peticiones HTTP desde una dirección IP que aparece en él reciben el error 400, y las conexiones WebSocket desde ella se cierran.\n\nPor defecto: `''`.\n\nExample: En el archivo config\n```text\n$blacklist : 10.0.0.5, 10.0.0.6\n```\n\n### $httpcompress : Boolean\n\nType: `config`\n\nComprime las respuestas con gzip.\n\nReturns: `Boolean`\n\nCuando el cliente acepta gzip, se comprimen las respuestas de texto de más de 256 bytes y los archivos estáticos comprimibles.\n\nValor por defecto: `true`.\n\nExample: En el archivo config\n```text\n$httpcompress : false\n```\n\n### $httpetag : String\n\nType: `config`\n\nUn valor que se añade al ETag de los archivos estáticos y de las respuestas en caché.\n\nReturns: `String`\n\nCuando está vacío, se crea a partir de `CONF.version` sin puntos ni espacios, así que una nueva versión invalida las cachés del navegador.\n\nValor por defecto: `''`.\n\nExample: En el archivo config\n```text\n$httpetag : build42\n```\n\n### $httpmaxsize : Number\n\nType: `config`\n\nEl tamaño máximo del cuerpo de una petición en kB.\n\nReturns: `Number`\n\nEl límite por defecto de cada ruta HTTP que no tiene su propio límite.\n\nValor por defecto: `256`.\n\nExample: En el archivo config\n```text\n$httpmaxsize (number) : 1024\n```\n\n### $httprangebuffer : Number\n\nType: `config`\n\nEl tamaño de un fragmento de una respuesta por rangos en kB.\n\nReturns: `Number`\n\nSe usa en las peticiones `Range` de archivos estáticos (vídeo, audio) cuando el cliente no indica el final.\n\nValor por defecto: `5120`.\n\nExample: En el archivo config\n```text\n$httprangebuffer (number) : 2048\n```\n\n### $httptimeout : Number\n\nType: `config`\n\nEl timeout de las peticiones en segundos.\n\nReturns: `Number`\n\nUna ruta puede establecer su propio timeout. Las peticiones se comprueban cada cinco segundos.\n\nValor por defecto: `5`.\n\nExample: En el archivo config\n```text\n$httptimeout (number) : 10\n```\n\n### $httpfiles : String\n\nType: `config`\n\nExtensiones de archivo que se sirven como archivos estáticos.\n\nReturns: `String`\n\nEn el archivo config, una lista de extensiones separadas por comas que se añaden a las predeterminadas (`jpg`, `png`, `css`, `js`, `json`, `pdf`, `mp4` y muchas más). En el código es un objeto con `true` para cada extensión permitida.\n\nValor por defecto: `common web extensions`.\n\nExample: En el archivo config\n```text\n$httpfiles : glb, gltf\n```\n\n### $httpchecktypes : Boolean\n\nType: `config`\n\nComprueba el tipo de contenido de los archivos subidos.\n\nReturns: `Boolean`\n\nSolo para `multipart/form-data`. `false` omite la comprobación.\n\nValor por defecto: `true`.\n\nExample: En el archivo config\n```text\n$httpchecktypes : false\n```\n\n### $httpmaxage : Number\n\nType: `config`\n\nEl max-age de las respuestas en caché en segundos.\n\nReturns: `Number`\n\nSe usa en la cabecera `Cache-Control` de los archivos estáticos y de las respuestas guardadas en caché con `controller.httpcache()`.\n\nValor por defecto: `60`.\n\nExample: En el archivo config\n```text\n$httpmaxage (number) : 300\n```\n\n### $httpmaxkeys : Number\n\nType: `config`\n\nLímites de los datos URL-encoded.\n\nReturns: `Number`\n\n`$httpmaxkeys` es el número máximo de claves que se analizan de una query string o de un cuerpo URL-encoded. `$httpmaxkey` (por defecto `25`) es la longitud máxima de una clave; las claves más largas se descartan.\n\nValor por defecto: `33`.\n\nExample: En el archivo config\n```text\n$httpmaxkeys (number) : 100\n$httpmaxkey (number)  : 50\n```\n\n### $httpcacheoffset : String\n\nType: `config` · Since: `0.0.16`\n\nDesplaza la fecha Last-Modified de los archivos estáticos.\n\nReturns: `String`\n\nUn desplazamiento de tiempo en el formato de `Date.add()`, por ejemplo `1 minute` o `-5 minutes`. Se suma a la fecha de modificación del archivo en la cabecera `Last-Modified`.\n\nPor defecto: `''`.\n\nExample: En el archivo de configuración\n```text\n$httpcacheoffset : 1 minute\n```\n\n### $xpoweredby : String\n\nType: `config`\n\nEl valor de la cabecera X-Powered-By.\n\nReturns: `String`\n\nUn valor vacío elimina la cabecera.\n\nValor por defecto: `'Total.js'`.\n\nExample: En el archivo config\n```text\n$xpoweredby :\n```\n\n### $minify* : Boolean\n\nType: `config`\n\nMinificación de JavaScript, CSS y HTML.\n\nReturns: `Boolean`\n\n`$minifyjs`, `$minifycss` y `$minifyhtml` (todos `true` por defecto) activan o desactivan la minificación de los archivos estáticos `.js` y `.css`, del código inline y del HTML renderizado.\n\nExample: En el archivo config\n```text\n$minifyhtml : false\n$minifyjs   : true\n$minifycss  : true\n```\n\n### $filtererrors : Boolean\n\nType: `config`\n\nIgnora los errores no capturados inofensivos.\n\nReturns: `Boolean`\n\nLos errores no capturados `EPIPE`, `invalid distance` y `ERR_IPC_CHANNEL_CLOSED` no se registran en el log.\n\nValor por defecto: `true`.\n\nExample: En el archivo config\n```text\n$filtererrors : false\n```\n\n### $cleartemp : Boolean\n\nType: `config`\n\nVacía el directorio tmp al arrancar.\n\nReturns: `Boolean`\n\nBorra los archivos `.js`, `.css`, `.html`, `.htm`, `.tmp` y `.upload` del directorio `tmp` cuando se carga la aplicación.\n\nPor defecto: `true`.\n\nExample: En el archivo config\n```text\n$cleartemp : false\n```\n\n### $customtitles : Boolean\n\nType: `config`\n\nDesactiva el sufijo automático de los títulos de página.\n\nReturns: `Boolean`\n\nPor defecto, al título de una vista en las páginas distintas de `/` se le añade ` - ` y `CONF.name`. `true` conserva el título tal como lo estableces.\n\nValor por defecto: `false`.\n\nExample: En el archivo config\n```text\n$customtitles : true\n```\n\n### $clearcache : Number\n\nType: `config`\n\nCada cuánto se vacían las cachés internas, en minutos.\n\nReturns: `Number`\n\nVacía las cachés de acciones, rutas, vistas, imágenes, templates, query builders y almacenamientos de archivos.\n\nValor por defecto: `10`.\n\nExample: En el archivo config\n```text\n$clearcache (number) : 30\n```\n\n### $imageconverter : String\n\nType: `config`\n\nEl programa que usa el módulo de imágenes.\n\nReturns: `String`\n\n`gm` para GraphicsMagick, `im` para el comando `convert` de ImageMagick o `magick` para ImageMagick 7. Consulta [Imágenes](../../guides/images/).\n\nValor por defecto: `'gm'`.\n\nExample: En el archivo config\n```text\n$imageconverter : magick\n```\n\n### $stats : Boolean\n\nType: `config`\n\nEscribe el archivo de estadísticas de la aplicación.\n\nReturns: `Boolean`\n\nCada minuto, el framework escribe las estadísticas de uso en `<main script>.json` (por ejemplo `index.js.json`). `F.load()` con una lista de tipos sin `stats` lo desactiva.\n\nValor por defecto: `true`.\n\nExample: En el archivo config\n```text\n$stats : false\n```\n\n### $sourcemap : Boolean\n\nType: `config`\n\nEscribe el source map de la aplicación.\n\nReturns: `Boolean`\n\nEscribe las rutas, acciones, esquemas y plugins en `<main script>.map` para las herramientas. El framework lo establece en el valor de `DEBUG` cuando carga todas las partes, y en `false` cuando `F.load()` recibe una lista de tipos sin `stats`.\n\nExample: Desactivar\n```text\n$sourcemap : false\n```\n\n### $npmcache : String\n\nType: `config`\n\nEl directorio de caché de npm para NPMINSTALL().\n\nReturns: `String`\n\nSe pasa a npm como `NPM_CONFIG_CACHE`.\n\nValor por defecto: `'/var/www/.npm'`.\n\nExample: En el archivo config\n```text\n$npmcache : /tmp/.npm\n```\n\n### $nodemodules : String\n\nType: `config`\n\nEl directorio de los módulos de npm instalados.\n\nReturns: `String`\n\n`NPMINSTALL()` instala en él y `REQUIRE()` carga desde él cuando falla un `require()` normal.\n\nValor por defecto: `'<root>/node_modules'`.\n\nExample: En el archivo config\n```text\n$nodemodules : /www/shared/node_modules\n```\n\n### $python : String\n\nType: `config`\n\nEl comando de Python.\n\nReturns: `String`\n\nLo usan `F.python()` y `F.pipinstall()`. `PYPELINE()` siempre ejecuta `python3`.\n\nPor defecto: `'python3'`.\n\nExample: En el archivo config\n```text\n$python : /usr/bin/python3.12\n```\n\n### $shell : String\n\nType: `config`\n\nLa shell para SHELL().\n\nReturns: `String`\n\nCuando se establece, `SHELL()` ejecuta los comandos en esta shell en lugar de la predeterminada.\n\nValor por defecto: `''`.\n\nExample: En el archivo config\n```text\n$shell : /bin/bash\n```\n\n### $wsmaxsize : Number\n\nType: `config`\n\nEl tamaño máximo de un mensaje WebSocket en kB.\n\nReturns: `Number`\n\nEl límite por defecto de cada ruta WebSocket que no tiene su propio límite.\n\nValor por defecto: `256`.\n\nExample: En el archivo config\n```text\n$wsmaxsize (number) : 1024\n```\n\n### $wscompress : Boolean\n\nType: `config`\n\nComprime los mensajes WebSocket.\n\nReturns: `Boolean`\n\nUsa `permessage-deflate` cuando el cliente lo admite.\n\nValor por defecto: `true`.\n\nExample: En el archivo config\n```text\n$wscompress : false\n```\n\n### $wsencodedecode : Boolean\n\nType: `config`\n\nCodifica en URL los mensajes WebSocket.\n\nReturns: `Boolean`\n\n`true` codifica los mensajes salientes con `encodeURIComponent` y decodifica los entrantes.\n\nValor por defecto: `false`.\n\nExample: En el archivo config\n```text\n$wsencodedecode : true\n```\n\n### $wsmaxlatency : Number\n\nType: `config`\n\nLa latencia máxima de ping de un cliente WebSocket en milisegundos.\n\nReturns: `Number`\n\nCuando el framework hace ping a las conexiones, se cierran los clientes que no responden o que tienen una latencia mayor.\n\nValor por defecto: `2000`.\n\nExample: En el archivo config\n```text\n$wsmaxlatency (number) : 5000\n```\n\n### $proxytimeout : Number\n\nType: `config`\n\nEl timeout de las peticiones a través del proxy en segundos.\n\nReturns: `Number`\n\nLo usan las rutas `PROXY()` que no tienen su propio timeout.\n\nValor por defecto: `5`.\n\nExample: En el archivo config\n```text\n$proxytimeout (number) : 30\n```\n\n### $proxyrequest : String\n\nType: `config`\n\nUn servidor proxy para las peticiones salientes.\n\nReturns: `String`\n\n`REQUEST()` y los builders que lo usan envían las peticiones a través de este proxy (`host:port`, `http://host:port`). Las peticiones a `localhost` y `127.0.0.1` van directamente.\n\nValor por defecto: `not set`.\n\nExample: En el archivo config\n```text\n$proxyrequest : http://proxy.local:3128\n```\n\n### $cookie* : String|Boolean\n\nType: `config`\n\nValores por defecto de las cookies.\n\nReturns: `String|Boolean`\n\n`$cookiesamesite` (por defecto `Lax`) es el valor `SameSite` de las cookies que no tienen uno propio. `$cookiesecure` (por defecto `false`) añade `Secure` a las cookies que no establecen `secure`.\n\nExample: En el archivo config\n```text\n$cookiesamesite : Strict\n$cookiesecure   : true\n```\n\n### $csrfexpiration : String\n\nType: `config`\n\nLa duración de los tokens CSRF.\n\nReturns: `String`\n\nUn tiempo en el formato de `Date.add()`. Los tokens solo se crean cuando `secret_csrf` está establecido.\n\nValor por defecto: `'30 minutes'`.\n\nExample: En el archivo config\n```text\n$csrfexpiration : 2 hours\n```\n\n### $crypto : String\n\nType: `config`\n\nUn cifrado de Node.js para ENCRYPT() y DECRYPT().\n\nReturns: `String`\n\nCuando se establece (por ejemplo `aes-256-cbc`), `ENCRYPT()` y `DECRYPT()` usan `crypto.createCipheriv()` con la clave que pasas y `$cryptoiv` como IV; la clave debe tener la longitud que necesita el cifrado. `$cryptoiv` se crea a partir de un hash del sistema; en el archivo config indícalo en hex o base64 y se convierte en un `Buffer`.\n\nValor por defecto: `not set`.\n\nExample: En el archivo config\n```text\n$crypto   : aes-256-cbc\n$cryptoiv : 000102030405060708090a0b0c0d0e0f\n```\n\n### $tapi* : Boolean|String\n\nType: `config`\n\nAjustes de Total API.\n\nReturns: `Boolean|String`\n\n`$tapi` (por defecto `true`) permite las llamadas `API('TAPI', ...)`; con `false` todas las operaciones salvo `check` fallan con `totalapi_inactive`. `$tapiurl` (por defecto `eu`) es la región en `https://<region>.api.totaljs.com/`. El token es `secret_totalapi`; `$tapisecret` se lee como alternativa. `$tapimail : true` envía los correos a través de Total API en lugar de SMTP (consulta [Enviar correos](../../guides/mail/)) y `$tapilogger : true` envía allí los registros de auditoría (consulta [Registros de auditoría](../../guides/audit-logs/)); los dos son `false` por defecto.\n\nExample: En el archivo config\n```text\nsecret_totalapi : your-token\n$tapiurl        : eu\n```\n\n### $tms* : Boolean|String|Number\n\nType: `config`\n\nAjustes de Total.js Message Service.\n\nReturns: `Boolean|String|Number`\n\n`$tms` (por defecto `false`) abre el endpoint WebSocket de TMS `$tmsurl` (por defecto `/$tms/`). `$tmsmaxsize` (por defecto `256`) es el límite de los mensajes en kB, `$tmsclearblocked` (por defecto `60`) desbloquea los clientes bloqueados cada N minutos y `secret_tms` es el token que deben enviar los clientes. Consulta [Message Service (TMS)](../../guides/message-service-and-apis/).\n\nExample: En el archivo config\n```text\n$tms       : true\nsecret_tms : my-secret\n```\n\n### $imprint : Boolean\n\nType: `config`\n\nImprime la pantalla de inicio.\n\nReturns: `Boolean`\n\n`false` oculta el bloque de información (nombre, versión, Node.js, URL) que se imprime cuando arranca la aplicación.\n\nValor por defecto: `true`.\n\nExample: En el archivo config\n```text\n$imprint : false\n```\n\n### $logger : Boolean\n\nType: `config`\n\nEscribe la salida de la consola en logs/debug.log.\n\nReturns: `Boolean`\n\n`true` redirige `console.log`, `console.warn`, `console.error`, `console.time` y `console.timeEnd` al archivo `logs/debug.log`.\n\nValor por defecto: `false`.\n\nExample: En el archivo config\n```text\n$logger : true\n```\n\n### $dir* : String\n\nType: `config`\n\nRutas personalizadas de los directorios de la aplicación.\n\nReturns: `String`\n\n`$dir` + el nombre de un directorio establece su ruta absoluta: `$dirpublic`, `$dirtmp`, `$dirlogs`, `$dirdatabases`, `$dirviews`, `$dirplugins`, `$dirmodules`, `$dirresources`, `$dirtemplates`, `$dirprivate` y los demás. `PATH.public()`, `PATH.databases()` y los cargadores los usan.\n\nExample: En el archivo config\n```text\n$dirpublic    : /www/cdn/public\n$dirdatabases : /data/app\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG()","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"event","name":"$reconfigure","signature":"ON('$reconfigure', function() {})","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : String|Boolean","since":"0.0.16","deprecated":false},{"type":"config","name":"$root","signature":"$root : String","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : String","since":"","deprecated":false},{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : String","since":"","deprecated":false},{"type":"config","name":"$port","signature":"$port : Number","since":"","deprecated":false},{"type":"config","name":"$ip","signature":"$ip : String","since":"","deprecated":false},{"type":"config","name":"$unixsocket","signature":"$unixsocket : String","since":"","deprecated":false},{"type":"config","name":"$timezone","signature":"$timezone : String","since":"","deprecated":false},{"type":"config","name":"$insecure","signature":"$insecure : Boolean","since":"","deprecated":false},{"type":"config","name":"$performance","signature":"$performance : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpreqlimit","signature":"$httpreqlimit : Number","since":"","deprecated":false},{"type":"config","name":"$blacklist","signature":"$blacklist : String","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag : String","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer : Number","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : Number","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles : String","since":"","deprecated":false},{"type":"config","name":"$httpchecktypes","signature":"$httpchecktypes : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage : Number","since":"","deprecated":false},{"type":"config","name":"$httpmaxkeys","signature":"$httpmaxkeys : Number","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset : String","since":"0.0.16","deprecated":false},{"type":"config","name":"$xpoweredby","signature":"$xpoweredby : String","since":"","deprecated":false},{"type":"config","name":"$minify*","signature":"$minify* : Boolean","since":"","deprecated":false},{"type":"config","name":"$filtererrors","signature":"$filtererrors : Boolean","since":"","deprecated":false},{"type":"config","name":"$cleartemp","signature":"$cleartemp : Boolean","since":"","deprecated":false},{"type":"config","name":"$customtitles","signature":"$customtitles : Boolean","since":"","deprecated":false},{"type":"config","name":"$clearcache","signature":"$clearcache : Number","since":"","deprecated":false},{"type":"config","name":"$imageconverter","signature":"$imageconverter : String","since":"","deprecated":false},{"type":"config","name":"$stats","signature":"$stats : Boolean","since":"","deprecated":false},{"type":"config","name":"$sourcemap","signature":"$sourcemap : Boolean","since":"","deprecated":false},{"type":"config","name":"$npmcache","signature":"$npmcache : String","since":"","deprecated":false},{"type":"config","name":"$nodemodules","signature":"$nodemodules : String","since":"","deprecated":false},{"type":"config","name":"$python","signature":"$python : String","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : String","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"$wsmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"$wscompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"$wsencodedecode : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"$wsmaxlatency : Number","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : Number","since":"","deprecated":false},{"type":"config","name":"$proxyrequest","signature":"$proxyrequest : String","since":"","deprecated":false},{"type":"config","name":"$cookie*","signature":"$cookie* : String|Boolean","since":"","deprecated":false},{"type":"config","name":"$csrfexpiration","signature":"$csrfexpiration : String","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : String","since":"","deprecated":false},{"type":"config","name":"$tapi*","signature":"$tapi* : Boolean|String","since":"","deprecated":false},{"type":"config","name":"$tms*","signature":"$tms* : Boolean|String|Number","since":"","deprecated":false},{"type":"config","name":"$imprint","signature":"$imprint : Boolean","since":"","deprecated":false},{"type":"config","name":"$logger","signature":"$logger : Boolean","since":"","deprecated":false},{"type":"config","name":"$dir*","signature":"$dir* : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwW5GSx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/configuration/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Configuration","summary":"CONF, LOADCONFIG(), DEBUG et chaque clé $ du framework avec sa valeur par défaut.","markdown":"---\ntitle: Configuration\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/configuration/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Configuration\n\n> CONF, LOADCONFIG(), DEBUG et chaque clé $ du framework avec sa valeur par défaut.\n\nChaque clé que le framework lit depuis `CONF`, avec son type et sa valeur par défaut, ainsi que `CONF`, `LOADCONFIG()`, `DEBUG` et l'événement `$reconfigure`. Le guide [Configuration](../../guides/configuration/) explique le format du fichier `config`, les types, `.env` et l'ordre de chargement.\n\n## API\n\n### CONF\n\nType: `property`\n\nL'objet global contenant la configuration de l'application.\n\nReturns: `Object`\n\nContient les valeurs par défaut du framework et chaque clé chargée depuis les options de `F.http()`, le fichier `config`, les fichiers config des plugins et `LOADCONFIG()`. `F.config` est le même objet. Lis-le n'importe où ; écris-y avec `LOADCONFIG()` lorsque la modification doit actualiser les paramètres dérivés.\n\nExample: Lire des valeurs\n```js\nexports.install = function() {\n\tROUTE('GET /about/', function($) {\n\t\t$.json({ name: CONF.name, version: CONF.version });\n\t});\n};\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nApplique des valeurs de configuration à l'exécution.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object|Array` | yes |  | Le texte d'un fichier config, un objet de clés et de valeurs, ou un tableau d'éléments `{ id, type, value }` (`key`/`name` et `val`/`body` sont aussi acceptés). |\n\nAnalyse `value` comme le fichier `config` et copie les clés dans `CONF`. Dans un objet ou un tableau, les valeurs `false`, `0` et `''` sont stockées comme `undefined`. Les clés spéciales sont traitées : `$root` est normalisé et préfixe `$api`, `$timezone` définit `process.env.TZ`, `$port` devient un nombre, `$httpfiles` ajoute des extensions, `$cryptoiv` devient un `Buffer`, `smtp`/`mail`/`mail_smtp`/`mail_smtp_options` construisent `CONF.smtp`, `totalapi` définit le jeton Total API. Ensuite, elle actualise les répertoires, le logger (`$logger`), la liste CORS et TMS, et émet `$reconfigure`. Le framework l'appelle lui-même pour le fichier `config`.\n\nExample: Texte\n```js\nLOADCONFIG('$httptimeout (number) : 15\\nmaintenance : true');\n```\n\nExample: Tableau avec types\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '25' },\n\t{ id: 'tags', type: 'array', value: 'a, b, c' }\n]);\n```\n\nExample: Objet\n```js\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n```\n\n### DEBUG\n\nType: `property`\n\ntrue en mode debug, false en mode release.\n\nReturns: `Boolean`\n\nUn booléen global. Il vaut au départ `process.env.NODE_ENV !== 'production'`. Le runner de debug le définit sur `true` et le runner de release le définit sur `false` avant le chargement de l'application : c'est donc `NODE_ENV` qui décide du mode lorsque l'application appelle `F.http()` ou `F.load()` sans runner. Le framework l'utilise pour le cache des vues et des fichiers statiques, la minification et la source map (`$sourcemap` le suit).\n\nExample: Code conditionnel\n```js\nif (DEBUG)\n\tconsole.log('Debug mode');\n```\n\n### ON('$reconfigure', function() {})\n\nType: `event`\n\nÉmis après que LOADCONFIG() a appliqué de nouvelles valeurs.\n\nÉmis à la fin de chaque appel à `LOADCONFIG()`, y compris le chargement du fichier `config` au démarrage. Utilise-le pour actualiser tes propres objets qui dépendent de valeurs de configuration.\n\nExample: Actualiser un client\n```js\nON('$reconfigure', function() {\n\tMAIN.client = createclient(CONF.service_url);\n});\n```\n\n### totalapi : String|Boolean\n\nType: `config` · Since: `0.0.16`\n\nDéfinit le jeton de Total API ou active ou désactive Total API.\n\nReturns: `String|Boolean`\n\nUne chaîne de plus de cinq caractères est stockée comme `CONF.secret_totalapi`, le jeton pour les appels `API('TAPI', ...)` et `TotalAPI()`. Toute autre valeur est stockée comme `$tapi`.\n\nExample: Dans le fichier de configuration\n```text\ntotalapi : your-total-api-token\n```\n\n### $root : String\n\nType: `config`\n\nUn préfixe d'URL pour toute l'application.\n\nReturns: `String`\n\nNormalisé pour commencer et se terminer par `/`. Les URL des routes reçoivent le préfixe (les routes d'API via `$api`), les fichiers statiques sont servis sous celui-ci et `F.virtualpath()` l'ajoute. Utilise-le lorsque l'application s'exécute sous un sous-chemin derrière un proxy.\n\nPar défaut : `''`.\n\nExample: Dans le fichier de configuration\n```text\n$root : /app/\n```\n\n### $api : String\n\nType: `config`\n\nL'endpoint d'API par défaut.\n\nReturns: `String`\n\nUn `?` dans une URL de route est remplacé par cette valeur : `ROUTE('API ?/users/ ...')` écoute donc sur `/api/users/`. Avec `$root`, le préfixe y est ajouté.\n\nPar défaut : `'/api/'`.\n\nExample: Dans le fichier de configuration\n```text\n$api : /v1/\n```\n\n### $mcp : Boolean\n\nType: `config`\n\nActive le serveur MCP.\n\nReturns: `Boolean`\n\n`true` crée la route `POST /$mcp/`, où les clients d'IA listent et appellent les actions qui ont `mcp: true`. La route est créée quand l'application est prête, donc définis la clé dans le fichier `config` ou avant le démarrage. Voir [Serveur MCP](../../guides/mcp-server/).\n\nPar défaut : `false`.\n\nExample: Dans le fichier config\n```text\n$mcp : true\n```\n\n### $cors : String\n\nType: `config`\n\nOrigines autorisées pour les requêtes cross-origin.\n\nReturns: `String`\n\n`*` autorise toutes les origines. Sinon, une liste d'origines séparées par `,`, `;` ou `|`, comparée à l'en-tête `Origin` (par exemple `https://app.example.com`). Un élément qui commence par `*` correspond à toute origine contenant le reste (`*example.com`). Les requêtes provenant du même hôte sont toujours autorisées ; les autres origines reçoivent l'erreur 400. `CORS()` modifie la valeur dans le code ; voir [Routage](../../guides/routing/#cors).\n\nPar défaut : `''`.\n\nExample: Dans le fichier de configuration\n```text\n$cors : https://app.example.com, *example.org\n```\n\n### $port : Number\n\nType: `config`\n\nLe port du serveur HTTP.\n\nReturns: `Number`\n\nLa valeur est convertie en nombre. Omets la clé pour le port automatique : l'option `port` de `F.http()`, la variable d'environnement `PORT`, le premier nombre de 3 à 5 chiffres dans les arguments de la ligne de commande, ou 8000.\n\nPar défaut : `'auto'`.\n\nExample: Dans le fichier de configuration\n```text\n$port : 8000\n```\n\n### $ip : String\n\nType: `config`\n\nL'adresse IP sur laquelle le serveur HTTP écoute.\n\nReturns: `String`\n\nL'option `ip` de `F.http()` la remplace. Utilise `127.0.0.1` pour n'accepter que les connexions locales.\n\nPar défaut : `'0.0.0.0'`.\n\nExample: Dans le fichier de configuration\n```text\n$ip : 127.0.0.1\n```\n\n### $unixsocket : String\n\nType: `config`\n\nUn chemin de socket Unix pour le serveur HTTP.\n\nReturns: `String`\n\nLorsqu'il est défini (ou lorsque `F.http()` reçoit l'option `unixsocket`), le serveur écoute sur le socket au lieu d'un port.\n\nPar défaut : `''`.\n\nExample: Dans le fichier de configuration\n```text\n$unixsocket : /var/run/app.sock\n```\n\n### $timezone : String\n\nType: `config`\n\nLe fuseau horaire du processus.\n\nReturns: `String`\n\nCopié dans `process.env.TZ` : toutes les valeurs `Date` du processus l'utilisent donc.\n\nPar défaut : `'utc'`.\n\nExample: Dans le fichier de configuration\n```text\n$timezone : Europe/Bratislava\n```\n\n### $insecure : Boolean\n\nType: `config`\n\nAccepte les certificats TLS invalides dans les requêtes sortantes.\n\nReturns: `Boolean`\n\nDéfinit `process.env.NODE_TLS_REJECT_UNAUTHORIZED` à `0` lorsqu'il vaut `true` et à `1` sinon. Utilise-le uniquement en développement, avec des serveurs auto-signés.\n\nPar défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\n$insecure : true\n```\n\n### $performance : Boolean\n\nType: `config`\n\nOptimise les sockets HTTP pour de nombreuses connexions.\n\nReturns: `Boolean`\n\nDéfinit `maxSockets` de l'agent HTTP global à 9999 et active `setNoDelay` et le keep-alive pour les connexions entrantes.\n\nPar défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\n$performance : true\n```\n\n### $httpreqlimit : Number\n\nType: `config`\n\nLe nombre maximal de requêtes par adresse IP et par minute.\n\nReturns: `Number`\n\n`0` désactive la limite. Au-delà de la limite, les requêtes reçoivent l'erreur 503 jusqu'à la remise à zéro des compteurs à la minute suivante.\n\nPar défaut : `0`.\n\nExample: Dans le fichier de configuration\n```text\n$httpreqlimit (number) : 300\n```\n\n### $blacklist : String\n\nType: `config`\n\nAdresses IP bloquées.\n\nReturns: `String`\n\nUne chaîne d'adresses IP, par exemple séparées par des virgules. Les requêtes HTTP provenant d'une adresse IP qui s'y trouve reçoivent l'erreur 400, et les connexions WebSocket qui en proviennent sont fermées.\n\nPar défaut : `''`.\n\nExample: Dans le fichier de configuration\n```text\n$blacklist : 10.0.0.5, 10.0.0.6\n```\n\n### $httpcompress : Boolean\n\nType: `config`\n\nCompresse les réponses avec gzip.\n\nReturns: `Boolean`\n\nLorsque le client accepte gzip, les réponses texte de plus de 256 octets et les fichiers statiques compressibles sont compressés.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\n$httpcompress : false\n```\n\n### $httpetag : String\n\nType: `config`\n\nUne valeur ajoutée à l'ETag des fichiers statiques et des réponses en cache.\n\nReturns: `String`\n\nLorsqu'elle est vide, elle est créée à partir de `CONF.version` sans points ni espaces : une nouvelle version invalide donc les caches des navigateurs.\n\nPar défaut : `''`.\n\nExample: Dans le fichier de configuration\n```text\n$httpetag : build42\n```\n\n### $httpmaxsize : Number\n\nType: `config`\n\nLa taille maximale du corps d'une requête en ko.\n\nReturns: `Number`\n\nLa limite par défaut de chaque route HTTP sans limite propre.\n\nPar défaut : `256`.\n\nExample: Dans le fichier de configuration\n```text\n$httpmaxsize (number) : 1024\n```\n\n### $httprangebuffer : Number\n\nType: `config`\n\nLa taille d'un fragment d'une réponse partielle (range) en ko.\n\nReturns: `Number`\n\nUtilisée pour les requêtes `Range` de fichiers statiques (vidéo, audio) lorsque le client ne donne pas la fin.\n\nPar défaut : `5120`.\n\nExample: Dans le fichier de configuration\n```text\n$httprangebuffer (number) : 2048\n```\n\n### $httptimeout : Number\n\nType: `config`\n\nLe timeout des requêtes en secondes.\n\nReturns: `Number`\n\nUne route peut définir son propre timeout. Les requêtes sont vérifiées toutes les cinq secondes.\n\nPar défaut : `5`.\n\nExample: Dans le fichier de configuration\n```text\n$httptimeout (number) : 10\n```\n\n### $httpfiles : String\n\nType: `config`\n\nExtensions de fichiers servies comme fichiers statiques.\n\nReturns: `String`\n\nDans le fichier de configuration, une liste d'extensions séparées par des virgules qui sont ajoutées aux valeurs par défaut (`jpg`, `png`, `css`, `js`, `json`, `pdf`, `mp4` et bien d'autres). Dans le code, c'est un objet avec `true` pour chaque extension autorisée.\n\nPar défaut : `common web extensions`.\n\nExample: Dans le fichier de configuration\n```text\n$httpfiles : glb, gltf\n```\n\n### $httpchecktypes : Boolean\n\nType: `config`\n\nVérifie le content type des fichiers envoyés.\n\nReturns: `Boolean`\n\nUniquement pour `multipart/form-data`. `false` ignore la vérification.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\n$httpchecktypes : false\n```\n\n### $httpmaxage : Number\n\nType: `config`\n\nLe max-age des réponses en cache, en secondes.\n\nReturns: `Number`\n\nUtilisé dans l'en-tête `Cache-Control` des fichiers statiques et des réponses mises en cache avec `controller.httpcache()`.\n\nPar défaut : `60`.\n\nExample: Dans le fichier de configuration\n```text\n$httpmaxage (number) : 300\n```\n\n### $httpmaxkeys : Number\n\nType: `config`\n\nLimites des données URL-encoded.\n\nReturns: `Number`\n\n`$httpmaxkeys` est le nombre maximal de clés analysées depuis une query string ou un corps URL-encoded. `$httpmaxkey` (par défaut `25`) est la longueur maximale d'une clé ; les clés plus longues sont supprimées.\n\nPar défaut : `33`.\n\nExample: Dans le fichier de configuration\n```text\n$httpmaxkeys (number) : 100\n$httpmaxkey (number)  : 50\n```\n\n### $httpcacheoffset : String\n\nType: `config` · Since: `0.0.16`\n\nDécale la date Last-Modified des fichiers statiques.\n\nReturns: `String`\n\nUn décalage de temps au format de `Date.add()`, par exemple `1 minute` ou `-5 minutes`. Il est ajouté à la date de modification du fichier dans l'en-tête `Last-Modified`.\n\nValeur par défaut : `''`.\n\nExample: Dans le fichier de configuration\n```text\n$httpcacheoffset : 1 minute\n```\n\n### $xpoweredby : String\n\nType: `config`\n\nLa valeur de l'en-tête X-Powered-By.\n\nReturns: `String`\n\nUne valeur vide supprime l'en-tête.\n\nPar défaut : `'Total.js'`.\n\nExample: Dans le fichier de configuration\n```text\n$xpoweredby :\n```\n\n### $minify* : Boolean\n\nType: `config`\n\nMinification de JavaScript, CSS et HTML.\n\nReturns: `Boolean`\n\n`$minifyjs`, `$minifycss` et `$minifyhtml` (tous à `true` par défaut) activent ou désactivent la minification des fichiers statiques `.js` et `.css`, du code inline et du HTML rendu.\n\nExample: Dans le fichier de configuration\n```text\n$minifyhtml : false\n$minifyjs   : true\n$minifycss  : true\n```\n\n### $filtererrors : Boolean\n\nType: `config`\n\nIgnore les erreurs non interceptées sans gravité.\n\nReturns: `Boolean`\n\nLes erreurs non interceptées `EPIPE`, `invalid distance` et `ERR_IPC_CHANNEL_CLOSED` ne sont pas journalisées.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\n$filtererrors : false\n```\n\n### $cleartemp : Boolean\n\nType: `config`\n\nVide le répertoire tmp au démarrage.\n\nReturns: `Boolean`\n\nSupprime les fichiers `.js`, `.css`, `.html`, `.htm`, `.tmp` et `.upload` du répertoire `tmp` au chargement de l'application.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\n$cleartemp : false\n```\n\n### $customtitles : Boolean\n\nType: `config`\n\nDésactive le suffixe automatique des titres de page.\n\nReturns: `Boolean`\n\nPar défaut, le titre d'une vue sur les pages autres que `/` est suivi de ` - ` et de `CONF.name`. `true` conserve le titre tel que tu l'as défini.\n\nPar défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\n$customtitles : true\n```\n\n### $clearcache : Number\n\nType: `config`\n\nLa fréquence de vidage des caches internes, en minutes.\n\nReturns: `Number`\n\nVide les caches des actions, des chemins, des vues, des images, des templates, des query builders et des stockages de fichiers.\n\nPar défaut : `10`.\n\nExample: Dans le fichier de configuration\n```text\n$clearcache (number) : 30\n```\n\n### $imageconverter : String\n\nType: `config`\n\nLe programme utilisé par le module d'images.\n\nReturns: `String`\n\n`gm` pour GraphicsMagick, `im` pour la commande `convert` d'ImageMagick ou `magick` pour ImageMagick 7. Voir [Images](../../guides/images/).\n\nPar défaut : `'gm'`.\n\nExample: Dans le fichier de configuration\n```text\n$imageconverter : magick\n```\n\n### $stats : Boolean\n\nType: `config`\n\nÉcrit le fichier de statistiques de l'application.\n\nReturns: `Boolean`\n\nChaque minute, le framework écrit les statistiques d'utilisation dans `<main script>.json` (par exemple `index.js.json`). `F.load()` avec une liste de types sans `stats` le désactive.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\n$stats : false\n```\n\n### $sourcemap : Boolean\n\nType: `config`\n\nÉcrit la source map de l'application.\n\nReturns: `Boolean`\n\nÉcrit les routes, les actions, les schémas et les plugins dans `<main script>.map` pour les outils. Le framework le définit à la valeur de `DEBUG` lorsqu'il charge toutes les parties, et à `false` lorsque `F.load()` reçoit une liste de types sans `stats`.\n\nExample: Désactiver\n```text\n$sourcemap : false\n```\n\n### $npmcache : String\n\nType: `config`\n\nLe répertoire de cache npm pour NPMINSTALL().\n\nReturns: `String`\n\nTransmis à npm sous la forme `NPM_CONFIG_CACHE`.\n\nPar défaut : `'/var/www/.npm'`.\n\nExample: Dans le fichier de configuration\n```text\n$npmcache : /tmp/.npm\n```\n\n### $nodemodules : String\n\nType: `config`\n\nLe répertoire des modules npm installés.\n\nReturns: `String`\n\n`NPMINSTALL()` y installe les modules et `REQUIRE()` les y charge lorsqu'un `require()` normal échoue.\n\nPar défaut : `'<root>/node_modules'`.\n\nExample: Dans le fichier de configuration\n```text\n$nodemodules : /www/shared/node_modules\n```\n\n### $python : String\n\nType: `config`\n\nLa commande Python.\n\nReturns: `String`\n\nUtilisé par `F.python()` et `F.pipinstall()`. `PYPELINE()` exécute toujours `python3`.\n\nPar défaut : `'python3'`.\n\nExample: Dans le fichier config\n```text\n$python : /usr/bin/python3.12\n```\n\n### $shell : String\n\nType: `config`\n\nLe shell pour SHELL().\n\nReturns: `String`\n\nLorsqu'il est défini, `SHELL()` exécute les commandes dans ce shell au lieu du shell par défaut.\n\nPar défaut : `''`.\n\nExample: Dans le fichier de configuration\n```text\n$shell : /bin/bash\n```\n\n### $wsmaxsize : Number\n\nType: `config`\n\nLa taille maximale d'un message WebSocket en ko.\n\nReturns: `Number`\n\nLa limite par défaut de chaque route WebSocket sans limite propre.\n\nPar défaut : `256`.\n\nExample: Dans le fichier de configuration\n```text\n$wsmaxsize (number) : 1024\n```\n\n### $wscompress : Boolean\n\nType: `config`\n\nCompresse les messages WebSocket.\n\nReturns: `Boolean`\n\nUtilise `permessage-deflate` lorsque le client le prend en charge.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\n$wscompress : false\n```\n\n### $wsencodedecode : Boolean\n\nType: `config`\n\nEncode les messages WebSocket au format URL.\n\nReturns: `Boolean`\n\n`true` encode les messages sortants avec `encodeURIComponent` et décode les messages entrants.\n\nPar défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\n$wsencodedecode : true\n```\n\n### $wsmaxlatency : Number\n\nType: `config`\n\nLa latence de ping maximale d'un client WebSocket en millisecondes.\n\nReturns: `Number`\n\nLorsque le framework envoie un ping aux connexions, les clients sans réponse ou avec une latence supérieure sont fermés.\n\nPar défaut : `2000`.\n\nExample: Dans le fichier de configuration\n```text\n$wsmaxlatency (number) : 5000\n```\n\n### $proxytimeout : Number\n\nType: `config`\n\nLe timeout des requêtes proxifiées en secondes.\n\nReturns: `Number`\n\nUtilisé par les routes `PROXY()` sans timeout propre.\n\nPar défaut : `5`.\n\nExample: Dans le fichier de configuration\n```text\n$proxytimeout (number) : 30\n```\n\n### $proxyrequest : String\n\nType: `config`\n\nUn serveur proxy pour les requêtes sortantes.\n\nReturns: `String`\n\n`REQUEST()` et les builders qui l'utilisent envoient les requêtes via ce proxy (`host:port`, `http://host:port`). Les requêtes vers `localhost` et `127.0.0.1` passent directement.\n\nPar défaut : `not set`.\n\nExample: Dans le fichier de configuration\n```text\n$proxyrequest : http://proxy.local:3128\n```\n\n### $cookie* : String|Boolean\n\nType: `config`\n\nValeurs par défaut des cookies.\n\nReturns: `String|Boolean`\n\n`$cookiesamesite` (par défaut `Lax`) est la valeur `SameSite` des cookies qui n'en définissent pas. `$cookiesecure` (par défaut `false`) ajoute `Secure` aux cookies qui ne définissent pas `secure`.\n\nExample: Dans le fichier de configuration\n```text\n$cookiesamesite : Strict\n$cookiesecure   : true\n```\n\n### $csrfexpiration : String\n\nType: `config`\n\nLa durée de vie des jetons CSRF.\n\nReturns: `String`\n\nUne durée au format de `Date.add()`. Les jetons ne sont créés que lorsque `secret_csrf` est défini.\n\nPar défaut : `'30 minutes'`.\n\nExample: Dans le fichier de configuration\n```text\n$csrfexpiration : 2 hours\n```\n\n### $crypto : String\n\nType: `config`\n\nUn algorithme de chiffrement Node.js pour ENCRYPT() et DECRYPT().\n\nReturns: `String`\n\nLorsqu'il est défini (par exemple `aes-256-cbc`), `ENCRYPT()` et `DECRYPT()` utilisent `crypto.createCipheriv()` avec la clé que tu passes et `$cryptoiv` comme IV ; la clé doit avoir la longueur requise par l'algorithme. `$cryptoiv` est créé à partir d'un hash du système ; dans le fichier de configuration, donne-le en hexadécimal ou en base64 et il devient un `Buffer`.\n\nPar défaut : `not set`.\n\nExample: Dans le fichier de configuration\n```text\n$crypto   : aes-256-cbc\n$cryptoiv : 000102030405060708090a0b0c0d0e0f\n```\n\n### $tapi* : Boolean|String\n\nType: `config`\n\nParamètres de Total API.\n\nReturns: `Boolean|String`\n\n`$tapi` (par défaut `true`) autorise les appels `API('TAPI', ...)` ; avec `false`, chaque opération sauf `check` échoue avec `totalapi_inactive`. `$tapiurl` (par défaut `eu`) est la région dans `https://<region>.api.totaljs.com/`. Le token est `secret_totalapi` ; `$tapisecret` est lu en solution de repli. `$tapimail : true` envoie les e-mails via Total API au lieu de SMTP (voir [Envoyer des e-mails](../../guides/mail/)) et `$tapilogger : true` y envoie les enregistrements d'audit (voir [Journaux d'audit](../../guides/audit-logs/)) ; les deux valent `false` par défaut.\n\nExample: Dans le fichier config\n```text\nsecret_totalapi : your-token\n$tapiurl        : eu\n```\n\n### $tms* : Boolean|String|Number\n\nType: `config`\n\nParamètres de Total.js Message Service.\n\nReturns: `Boolean|String|Number`\n\n`$tms` (par défaut `false`) ouvre l'endpoint WebSocket TMS `$tmsurl` (par défaut `/$tms/`). `$tmsmaxsize` (par défaut `256`) est la limite des messages en ko, `$tmsclearblocked` (par défaut `60`) débloque les clients bloqués toutes les N minutes, et `secret_tms` est le jeton que les clients doivent envoyer. Voir [Message Service (TMS)](../../guides/message-service-and-apis/).\n\nExample: Dans le fichier de configuration\n```text\n$tms       : true\nsecret_tms : my-secret\n```\n\n### $imprint : Boolean\n\nType: `config`\n\nAffiche l'écran de démarrage.\n\nReturns: `Boolean`\n\n`false` masque le bloc d'informations (nom, version, Node.js, URL) affiché au démarrage de l'application.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\n$imprint : false\n```\n\n### $logger : Boolean\n\nType: `config`\n\nÉcrit la sortie de la console dans logs/debug.log.\n\nReturns: `Boolean`\n\n`true` redirige `console.log`, `console.warn`, `console.error`, `console.time` et `console.timeEnd` vers le fichier `logs/debug.log`.\n\nPar défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\n$logger : true\n```\n\n### $dir* : String\n\nType: `config`\n\nChemins personnalisés des répertoires de l'application.\n\nReturns: `String`\n\n`$dir` + le nom d'un répertoire définit son chemin absolu : `$dirpublic`, `$dirtmp`, `$dirlogs`, `$dirdatabases`, `$dirviews`, `$dirplugins`, `$dirmodules`, `$dirresources`, `$dirtemplates`, `$dirprivate` et les autres. `PATH.public()`, `PATH.databases()` et les chargeurs les utilisent.\n\nExample: Dans le fichier de configuration\n```text\n$dirpublic    : /www/cdn/public\n$dirdatabases : /data/app\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG()","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"event","name":"$reconfigure","signature":"ON('$reconfigure', function() {})","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : String|Boolean","since":"0.0.16","deprecated":false},{"type":"config","name":"$root","signature":"$root : String","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : String","since":"","deprecated":false},{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : String","since":"","deprecated":false},{"type":"config","name":"$port","signature":"$port : Number","since":"","deprecated":false},{"type":"config","name":"$ip","signature":"$ip : String","since":"","deprecated":false},{"type":"config","name":"$unixsocket","signature":"$unixsocket : String","since":"","deprecated":false},{"type":"config","name":"$timezone","signature":"$timezone : String","since":"","deprecated":false},{"type":"config","name":"$insecure","signature":"$insecure : Boolean","since":"","deprecated":false},{"type":"config","name":"$performance","signature":"$performance : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpreqlimit","signature":"$httpreqlimit : Number","since":"","deprecated":false},{"type":"config","name":"$blacklist","signature":"$blacklist : String","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag : String","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer : Number","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : Number","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles : String","since":"","deprecated":false},{"type":"config","name":"$httpchecktypes","signature":"$httpchecktypes : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage : Number","since":"","deprecated":false},{"type":"config","name":"$httpmaxkeys","signature":"$httpmaxkeys : Number","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset : String","since":"0.0.16","deprecated":false},{"type":"config","name":"$xpoweredby","signature":"$xpoweredby : String","since":"","deprecated":false},{"type":"config","name":"$minify*","signature":"$minify* : Boolean","since":"","deprecated":false},{"type":"config","name":"$filtererrors","signature":"$filtererrors : Boolean","since":"","deprecated":false},{"type":"config","name":"$cleartemp","signature":"$cleartemp : Boolean","since":"","deprecated":false},{"type":"config","name":"$customtitles","signature":"$customtitles : Boolean","since":"","deprecated":false},{"type":"config","name":"$clearcache","signature":"$clearcache : Number","since":"","deprecated":false},{"type":"config","name":"$imageconverter","signature":"$imageconverter : String","since":"","deprecated":false},{"type":"config","name":"$stats","signature":"$stats : Boolean","since":"","deprecated":false},{"type":"config","name":"$sourcemap","signature":"$sourcemap : Boolean","since":"","deprecated":false},{"type":"config","name":"$npmcache","signature":"$npmcache : String","since":"","deprecated":false},{"type":"config","name":"$nodemodules","signature":"$nodemodules : String","since":"","deprecated":false},{"type":"config","name":"$python","signature":"$python : String","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : String","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"$wsmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"$wscompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"$wsencodedecode : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"$wsmaxlatency : Number","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : Number","since":"","deprecated":false},{"type":"config","name":"$proxyrequest","signature":"$proxyrequest : String","since":"","deprecated":false},{"type":"config","name":"$cookie*","signature":"$cookie* : String|Boolean","since":"","deprecated":false},{"type":"config","name":"$csrfexpiration","signature":"$csrfexpiration : String","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : String","since":"","deprecated":false},{"type":"config","name":"$tapi*","signature":"$tapi* : Boolean|String","since":"","deprecated":false},{"type":"config","name":"$tms*","signature":"$tms* : Boolean|String|Number","since":"","deprecated":false},{"type":"config","name":"$imprint","signature":"$imprint : Boolean","since":"","deprecated":false},{"type":"config","name":"$logger","signature":"$logger : Boolean","since":"","deprecated":false},{"type":"config","name":"$dir*","signature":"$dir* : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwW5GSx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/configuration/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Configurazione","summary":"CONF, LOADCONFIG(), DEBUG e ogni chiave $ del framework con il suo valore predefinito.","markdown":"---\ntitle: Configurazione\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/configuration/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Configurazione\n\n> CONF, LOADCONFIG(), DEBUG e ogni chiave $ del framework con il suo valore predefinito.\n\nOgni chiave che il framework legge da `CONF`, con il suo tipo e il valore predefinito, più `CONF`, `LOADCONFIG()`, `DEBUG` e l'evento `$reconfigure`. La guida [Configurazione](../../guides/configuration/) spiega il formato del file `config`, i tipi, `.env` e l'ordine di caricamento.\n\n## API\n\n### CONF\n\nType: `property`\n\nL'oggetto globale con la configurazione dell'applicazione.\n\nReturns: `Object`\n\nContiene i valori predefiniti del framework e ogni chiave caricata dalle opzioni di `F.http()`, dal file `config`, dai file config dei plugin e da `LOADCONFIG()`. `F.config` è lo stesso oggetto. Leggilo ovunque; scrivici con `LOADCONFIG()` quando la modifica deve aggiornare le impostazioni derivate.\n\nExample: Leggere i valori\n```js\nexports.install = function() {\n\tROUTE('GET /about/', function($) {\n\t\t$.json({ name: CONF.name, version: CONF.version });\n\t});\n};\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nApplica valori di configurazione a runtime.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object|Array` | yes |  | Il testo di un file config, un oggetto di chiavi e valori, o un array di elementi `{ id, type, value }` (sono accettati anche `key`/`name` e `val`/`body`). |\n\nInterpreta `value` come il file `config` e copia le chiavi in `CONF`. In un oggetto o in un array, i valori `false`, `0` e `''` vengono salvati come `undefined`. Le chiavi speciali vengono elaborate: `$root` viene normalizzato e fa da prefisso a `$api`, `$timezone` imposta `process.env.TZ`, `$port` diventa un numero, `$httpfiles` aggiunge estensioni, `$cryptoiv` diventa un `Buffer`, `smtp`/`mail`/`mail_smtp`/`mail_smtp_options` costruiscono `CONF.smtp`, `totalapi` imposta il token di Total API. Poi aggiorna le directory, il logger (`$logger`), l'elenco CORS e TMS, ed emette `$reconfigure`. Il framework lo chiama per il file `config` stesso.\n\nExample: Testo\n```js\nLOADCONFIG('$httptimeout (number) : 15\\nmaintenance : true');\n```\n\nExample: Array con tipi\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '25' },\n\t{ id: 'tags', type: 'array', value: 'a, b, c' }\n]);\n```\n\nExample: Oggetto\n```js\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n```\n\n### DEBUG\n\nType: `property`\n\ntrue in modalità debug, false in modalità release.\n\nReturns: `Boolean`\n\nUn booleano globale. Parte come `process.env.NODE_ENV !== 'production'`. Il runner di debug lo imposta a `true` e il runner di release lo imposta a `false` prima che l'applicazione si carichi, quindi `NODE_ENV` decide la modalità quando l'applicazione chiama `F.http()` o `F.load()` senza un runner. Il framework lo usa per la cache delle viste e dei file statici, la minificazione e la source map (`$sourcemap` lo segue).\n\nExample: Codice condizionale\n```js\nif (DEBUG)\n\tconsole.log('Debug mode');\n```\n\n### ON('$reconfigure', function() {})\n\nType: `event`\n\nEmesso dopo che LOADCONFIG() ha applicato nuovi valori.\n\nEmesso alla fine di ogni chiamata a `LOADCONFIG()`, compreso il caricamento del file `config` all'avvio. Usalo per aggiornare i tuoi oggetti che dipendono da valori di configurazione.\n\nExample: Aggiornare un client\n```js\nON('$reconfigure', function() {\n\tMAIN.client = createclient(CONF.service_url);\n});\n```\n\n### totalapi : String|Boolean\n\nType: `config` · Since: `0.0.16`\n\nImposta il token di Total API o attiva/disattiva Total API.\n\nReturns: `String|Boolean`\n\nUna stringa più lunga di cinque caratteri viene salvata come `CONF.secret_totalapi`, il token per le chiamate `API('TAPI', ...)` e `TotalAPI()`. Qualsiasi altro valore viene salvato come `$tapi`.\n\nExample: Nel file di configurazione\n```text\ntotalapi : your-total-api-token\n```\n\n### $root : String\n\nType: `config`\n\nUn prefisso URL per l'intera applicazione.\n\nReturns: `String`\n\nNormalizzato in modo che inizi e finisca con `/`. Gli URL delle route ricevono il prefisso (le route API tramite `$api`), i file statici vengono serviti sotto di esso e `F.virtualpath()` lo aggiunge. Usalo quando l'applicazione gira sotto un sottopercorso dietro un proxy.\n\nDefault: `''`.\n\nExample: Nel file config\n```text\n$root : /app/\n```\n\n### $api : String\n\nType: `config`\n\nL'endpoint API predefinito.\n\nReturns: `String`\n\nUn `?` nell'URL di una route viene sostituito con questo valore, quindi `ROUTE('API ?/users/ ...')` resta in ascolto su `/api/users/`. Con `$root`, il prefisso viene aggiunto a esso.\n\nDefault: `'/api/'`.\n\nExample: Nel file config\n```text\n$api : /v1/\n```\n\n### $mcp : Boolean\n\nType: `config`\n\nAttiva il server MCP.\n\nReturns: `Boolean`\n\n`true` crea la route `POST /$mcp/`, dove i client AI elencano e chiamano le azioni che hanno `mcp: true`. La route viene creata quando l'applicazione è pronta, quindi imposta la chiave nel file `config` o prima dell'avvio. Vedi [Server MCP](../../guides/mcp-server/).\n\nPredefinito: `false`.\n\nExample: Nel file config\n```text\n$mcp : true\n```\n\n### $cors : String\n\nType: `config`\n\nOrigini consentite per le richieste cross-origin.\n\nReturns: `String`\n\n`*` consente ogni origine. Altrimenti un elenco di origini separate da `,`, `;` o `|`, confrontate con l'header `Origin` (ad esempio `https://app.example.com`). Un elemento che inizia con `*` corrisponde a ogni origine che contiene il resto (`*example.com`). Le richieste dallo stesso host sono sempre consentite; le altre origini ricevono l'errore 400. `CORS()` modifica il valore nel codice; vedi [Routing](../../guides/routing/#cors).\n\nDefault: `''`.\n\nExample: Nel file config\n```text\n$cors : https://app.example.com, *example.org\n```\n\n### $port : Number\n\nType: `config`\n\nLa porta del server HTTP.\n\nReturns: `Number`\n\nIl valore viene convertito in numero. Ometti la chiave per la porta automatica: l'opzione `port` di `F.http()`, la variabile d'ambiente `PORT`, il primo numero di 3-5 cifre negli argomenti della riga di comando, oppure 8000.\n\nDefault: `'auto'`.\n\nExample: Nel file config\n```text\n$port : 8000\n```\n\n### $ip : String\n\nType: `config`\n\nL'indirizzo IP su cui resta in ascolto il server HTTP.\n\nReturns: `String`\n\nL'opzione `ip` di `F.http()` la sovrascrive. Usa `127.0.0.1` per accettare solo connessioni locali.\n\nDefault: `'0.0.0.0'`.\n\nExample: Nel file config\n```text\n$ip : 127.0.0.1\n```\n\n### $unixsocket : String\n\nType: `config`\n\nIl percorso di un socket Unix per il server HTTP.\n\nReturns: `String`\n\nQuando è impostato (o quando `F.http()` riceve l'opzione `unixsocket`), il server resta in ascolto sul socket invece che su una porta.\n\nDefault: `''`.\n\nExample: Nel file config\n```text\n$unixsocket : /var/run/app.sock\n```\n\n### $timezone : String\n\nType: `config`\n\nIl fuso orario del processo.\n\nReturns: `String`\n\nCopiato in `process.env.TZ`, quindi tutti i valori `Date` del processo lo usano.\n\nDefault: `'utc'`.\n\nExample: Nel file config\n```text\n$timezone : Europe/Bratislava\n```\n\n### $insecure : Boolean\n\nType: `config`\n\nAccetta certificati TLS non validi nelle richieste in uscita.\n\nReturns: `Boolean`\n\nImposta `process.env.NODE_TLS_REJECT_UNAUTHORIZED` a `0` quando è `true` e a `1` altrimenti. Usalo solo in sviluppo con server dai certificati autofirmati.\n\nDefault: `false`.\n\nExample: Nel file config\n```text\n$insecure : true\n```\n\n### $performance : Boolean\n\nType: `config`\n\nOttimizza i socket HTTP per molte connessioni.\n\nReturns: `Boolean`\n\nImposta `maxSockets` dell'agent HTTP globale a 9999 e attiva `setNoDelay` e il keep-alive per le connessioni in entrata.\n\nDefault: `false`.\n\nExample: Nel file config\n```text\n$performance : true\n```\n\n### $httpreqlimit : Number\n\nType: `config`\n\nIl numero massimo di richieste per indirizzo IP al minuto.\n\nReturns: `Number`\n\n`0` disattiva il limite. Oltre il limite, le richieste ricevono l'errore 503 finché i contatori non vengono azzerati al minuto successivo.\n\nDefault: `0`.\n\nExample: Nel file config\n```text\n$httpreqlimit (number) : 300\n```\n\n### $blacklist : String\n\nType: `config`\n\nIndirizzi IP bloccati.\n\nReturns: `String`\n\nUna stringa di indirizzi IP, ad esempio separati da virgole. Le richieste HTTP da un indirizzo IP presente in essa ricevono l'errore 400, e le connessioni WebSocket da esso vengono chiuse.\n\nPredefinito: `''`.\n\nExample: Nel file config\n```text\n$blacklist : 10.0.0.5, 10.0.0.6\n```\n\n### $httpcompress : Boolean\n\nType: `config`\n\nComprime le risposte con gzip.\n\nReturns: `Boolean`\n\nQuando il client accetta gzip, le risposte testuali più grandi di 256 byte e i file statici comprimibili vengono compressi.\n\nDefault: `true`.\n\nExample: Nel file config\n```text\n$httpcompress : false\n```\n\n### $httpetag : String\n\nType: `config`\n\nUn valore aggiunto all'ETag dei file statici e delle risposte in cache.\n\nReturns: `String`\n\nQuando è vuoto, viene creato da `CONF.version` senza punti e spazi, quindi una nuova versione invalida le cache dei browser.\n\nDefault: `''`.\n\nExample: Nel file config\n```text\n$httpetag : build42\n```\n\n### $httpmaxsize : Number\n\nType: `config`\n\nLa dimensione massima del body di una richiesta in kB.\n\nReturns: `Number`\n\nIl limite predefinito di ogni route HTTP senza un proprio limite.\n\nDefault: `256`.\n\nExample: Nel file config\n```text\n$httpmaxsize (number) : 1024\n```\n\n### $httprangebuffer : Number\n\nType: `config`\n\nLa dimensione di un blocco di una risposta range in kB.\n\nReturns: `Number`\n\nUsato per le richieste `Range` di file statici (video, audio) quando il client non indica la fine.\n\nDefault: `5120`.\n\nExample: Nel file config\n```text\n$httprangebuffer (number) : 2048\n```\n\n### $httptimeout : Number\n\nType: `config`\n\nIl timeout della richiesta in secondi.\n\nReturns: `Number`\n\nUna route può impostare il proprio timeout. Le richieste vengono controllate ogni cinque secondi.\n\nDefault: `5`.\n\nExample: Nel file config\n```text\n$httptimeout (number) : 10\n```\n\n### $httpfiles : String\n\nType: `config`\n\nEstensioni di file servite come file statici.\n\nReturns: `String`\n\nNel file config, un elenco di estensioni separate da virgole che vengono aggiunte a quelle predefinite (`jpg`, `png`, `css`, `js`, `json`, `pdf`, `mp4` e molte altre). Nel codice è un oggetto con `true` per ogni estensione consentita.\n\nDefault: `common web extensions`.\n\nExample: Nel file config\n```text\n$httpfiles : glb, gltf\n```\n\n### $httpchecktypes : Boolean\n\nType: `config`\n\nControlla il content type dei file caricati.\n\nReturns: `Boolean`\n\nSolo per `multipart/form-data`. `false` salta il controllo.\n\nDefault: `true`.\n\nExample: Nel file config\n```text\n$httpchecktypes : false\n```\n\n### $httpmaxage : Number\n\nType: `config`\n\nIl max-age delle risposte in cache in secondi.\n\nReturns: `Number`\n\nUsato nell'header `Cache-Control` dei file statici e delle risposte messe in cache con `controller.httpcache()`.\n\nDefault: `60`.\n\nExample: Nel file config\n```text\n$httpmaxage (number) : 300\n```\n\n### $httpmaxkeys : Number\n\nType: `config`\n\nLimiti dei dati URL-encoded.\n\nReturns: `Number`\n\n`$httpmaxkeys` è il numero massimo di chiavi interpretate da una query string o da un body URL-encoded. `$httpmaxkey` (default `25`) è la lunghezza massima di una chiave; le chiavi più lunghe vengono scartate.\n\nDefault: `33`.\n\nExample: Nel file config\n```text\n$httpmaxkeys (number) : 100\n$httpmaxkey (number)  : 50\n```\n\n### $httpcacheoffset : String\n\nType: `config` · Since: `0.0.16`\n\nSposta la data Last-Modified dei file statici.\n\nReturns: `String`\n\nUno scostamento temporale nel formato di `Date.add()`, per esempio `1 minute` o `-5 minutes`. Viene aggiunto alla data di modifica del file nell'header `Last-Modified`.\n\nPredefinito: `''`.\n\nExample: Nel file di configurazione\n```text\n$httpcacheoffset : 1 minute\n```\n\n### $xpoweredby : String\n\nType: `config`\n\nIl valore dell'header X-Powered-By.\n\nReturns: `String`\n\nUn valore vuoto rimuove l'header.\n\nDefault: `'Total.js'`.\n\nExample: Nel file config\n```text\n$xpoweredby :\n```\n\n### $minify* : Boolean\n\nType: `config`\n\nMinificazione di JavaScript, CSS e HTML.\n\nReturns: `Boolean`\n\n`$minifyjs`, `$minifycss` e `$minifyhtml` (tutti `true` di default) attivano o disattivano la minificazione dei file statici `.js` e `.css`, del codice inline e dell'HTML renderizzato.\n\nExample: Nel file config\n```text\n$minifyhtml : false\n$minifyjs   : true\n$minifycss  : true\n```\n\n### $filtererrors : Boolean\n\nType: `config`\n\nIgnora gli errori non gestiti innocui.\n\nReturns: `Boolean`\n\nGli errori non gestiti `EPIPE`, `invalid distance` ed `ERR_IPC_CHANNEL_CLOSED` non vengono registrati nel log.\n\nDefault: `true`.\n\nExample: Nel file config\n```text\n$filtererrors : false\n```\n\n### $cleartemp : Boolean\n\nType: `config`\n\nSvuota la directory tmp all'avvio.\n\nReturns: `Boolean`\n\nElimina i file `.js`, `.css`, `.html`, `.htm`, `.tmp` e `.upload` della directory `tmp` quando l'applicazione viene caricata.\n\nPredefinito: `true`.\n\nExample: Nel file config\n```text\n$cleartemp : false\n```\n\n### $customtitles : Boolean\n\nType: `config`\n\nDisattiva il suffisso automatico dei titoli delle pagine.\n\nReturns: `Boolean`\n\nDi default al titolo di una vista sulle pagine diverse da `/` vengono aggiunti ` - ` e `CONF.name`. `true` mantiene il titolo così come lo imposti.\n\nDefault: `false`.\n\nExample: Nel file config\n```text\n$customtitles : true\n```\n\n### $clearcache : Number\n\nType: `config`\n\nOgni quanto vengono svuotate le cache interne, in minuti.\n\nReturns: `Number`\n\nSvuota le cache di azioni, percorsi, viste, immagini, template, query builder e file storage.\n\nDefault: `10`.\n\nExample: Nel file config\n```text\n$clearcache (number) : 30\n```\n\n### $imageconverter : String\n\nType: `config`\n\nIl programma usato dal modulo delle immagini.\n\nReturns: `String`\n\n`gm` per GraphicsMagick, `im` per il comando `convert` di ImageMagick o `magick` per ImageMagick 7. Vedi [Immagini](../../guides/images/).\n\nDefault: `'gm'`.\n\nExample: Nel file config\n```text\n$imageconverter : magick\n```\n\n### $stats : Boolean\n\nType: `config`\n\nScrive il file delle statistiche dell'applicazione.\n\nReturns: `Boolean`\n\nOgni minuto il framework scrive le statistiche di utilizzo in `<main script>.json` (ad esempio `index.js.json`). `F.load()` con un elenco di tipi senza `stats` lo disattiva.\n\nDefault: `true`.\n\nExample: Nel file config\n```text\n$stats : false\n```\n\n### $sourcemap : Boolean\n\nType: `config`\n\nScrive la source map dell'applicazione.\n\nReturns: `Boolean`\n\nScrive route, azioni, schemi e plugin in `<main script>.map` per gli strumenti. Il framework lo imposta al valore di `DEBUG` quando carica tutte le parti, e a `false` quando `F.load()` riceve un elenco di tipi senza `stats`.\n\nExample: Disattivare\n```text\n$sourcemap : false\n```\n\n### $npmcache : String\n\nType: `config`\n\nLa directory della cache npm per NPMINSTALL().\n\nReturns: `String`\n\nPassata a npm come `NPM_CONFIG_CACHE`.\n\nDefault: `'/var/www/.npm'`.\n\nExample: Nel file config\n```text\n$npmcache : /tmp/.npm\n```\n\n### $nodemodules : String\n\nType: `config`\n\nLa directory dei moduli npm installati.\n\nReturns: `String`\n\n`NPMINSTALL()` installa al suo interno e `REQUIRE()` carica da essa quando un normale `require()` fallisce.\n\nDefault: `'<root>/node_modules'`.\n\nExample: Nel file config\n```text\n$nodemodules : /www/shared/node_modules\n```\n\n### $python : String\n\nType: `config`\n\nIl comando Python.\n\nReturns: `String`\n\nUsato da `F.python()` e `F.pipinstall()`. `PYPELINE()` esegue sempre `python3`.\n\nPredefinito: `'python3'`.\n\nExample: Nel file config\n```text\n$python : /usr/bin/python3.12\n```\n\n### $shell : String\n\nType: `config`\n\nLa shell per SHELL().\n\nReturns: `String`\n\nQuando è impostata, `SHELL()` esegue i comandi in questa shell invece che in quella predefinita.\n\nDefault: `''`.\n\nExample: Nel file config\n```text\n$shell : /bin/bash\n```\n\n### $wsmaxsize : Number\n\nType: `config`\n\nLa dimensione massima di un messaggio WebSocket in kB.\n\nReturns: `Number`\n\nIl limite predefinito di ogni route WebSocket senza un proprio limite.\n\nDefault: `256`.\n\nExample: Nel file config\n```text\n$wsmaxsize (number) : 1024\n```\n\n### $wscompress : Boolean\n\nType: `config`\n\nComprime i messaggi WebSocket.\n\nReturns: `Boolean`\n\nUsa `permessage-deflate` quando il client lo supporta.\n\nDefault: `true`.\n\nExample: Nel file config\n```text\n$wscompress : false\n```\n\n### $wsencodedecode : Boolean\n\nType: `config`\n\nCodifica in URL i messaggi WebSocket.\n\nReturns: `Boolean`\n\n`true` codifica i messaggi in uscita con `encodeURIComponent` e decodifica quelli in entrata.\n\nDefault: `false`.\n\nExample: Nel file config\n```text\n$wsencodedecode : true\n```\n\n### $wsmaxlatency : Number\n\nType: `config`\n\nLa latenza massima di ping di un client WebSocket in millisecondi.\n\nReturns: `Number`\n\nQuando il framework invia un ping alle connessioni, i client che non rispondono o con una latenza maggiore vengono chiusi.\n\nDefault: `2000`.\n\nExample: Nel file config\n```text\n$wsmaxlatency (number) : 5000\n```\n\n### $proxytimeout : Number\n\nType: `config`\n\nIl timeout delle richieste in proxy in secondi.\n\nReturns: `Number`\n\nUsato dalle route `PROXY()` senza un proprio timeout.\n\nDefault: `5`.\n\nExample: Nel file config\n```text\n$proxytimeout (number) : 30\n```\n\n### $proxyrequest : String\n\nType: `config`\n\nUn server proxy per le richieste in uscita.\n\nReturns: `String`\n\n`REQUEST()` e i builder che lo usano inviano le richieste tramite questo proxy (`host:port`, `http://host:port`). Le richieste a `localhost` e `127.0.0.1` vanno direttamente.\n\nDefault: `not set`.\n\nExample: Nel file config\n```text\n$proxyrequest : http://proxy.local:3128\n```\n\n### $cookie* : String|Boolean\n\nType: `config`\n\nValori predefiniti dei cookie.\n\nReturns: `String|Boolean`\n\n`$cookiesamesite` (default `Lax`) è il valore `SameSite` dei cookie che non ne hanno uno proprio. `$cookiesecure` (default `false`) aggiunge `Secure` ai cookie che non impostano `secure`.\n\nExample: Nel file config\n```text\n$cookiesamesite : Strict\n$cookiesecure   : true\n```\n\n### $csrfexpiration : String\n\nType: `config`\n\nLa durata dei token CSRF.\n\nReturns: `String`\n\nUn tempo nel formato di `Date.add()`. I token vengono creati solo quando `secret_csrf` è impostato.\n\nDefault: `'30 minutes'`.\n\nExample: Nel file config\n```text\n$csrfexpiration : 2 hours\n```\n\n### $crypto : String\n\nType: `config`\n\nUn cifrario Node.js per ENCRYPT() e DECRYPT().\n\nReturns: `String`\n\nQuando è impostato (ad esempio `aes-256-cbc`), `ENCRYPT()` e `DECRYPT()` usano `crypto.createCipheriv()` con la chiave che passi e `$cryptoiv` come IV; la chiave deve avere la lunghezza richiesta dal cifrario. `$cryptoiv` viene creato da un hash del sistema; nel file config indicalo in hex o base64 e diventa un `Buffer`.\n\nDefault: `not set`.\n\nExample: Nel file config\n```text\n$crypto   : aes-256-cbc\n$cryptoiv : 000102030405060708090a0b0c0d0e0f\n```\n\n### $tapi* : Boolean|String\n\nType: `config`\n\nImpostazioni di Total API.\n\nReturns: `Boolean|String`\n\n`$tapi` (predefinito `true`) consente le chiamate `API('TAPI', ...)`; con `false` ogni operazione tranne `check` fallisce con `totalapi_inactive`. `$tapiurl` (predefinito `eu`) è la regione in `https://<region>.api.totaljs.com/`. Il token è `secret_totalapi`; `$tapisecret` viene letto come alternativa. `$tapimail : true` invia le e-mail tramite Total API invece che via SMTP (vedi [Invio di e-mail](../../guides/mail/)) e `$tapilogger : true` vi invia i record di audit (vedi [Log di audit](../../guides/audit-logs/)); entrambi sono `false` per impostazione predefinita.\n\nExample: Nel file config\n```text\nsecret_totalapi : your-token\n$tapiurl        : eu\n```\n\n### $tms* : Boolean|String|Number\n\nType: `config`\n\nImpostazioni di Total.js Message Service.\n\nReturns: `Boolean|String|Number`\n\n`$tms` (default `false`) apre l'endpoint WebSocket di TMS `$tmsurl` (default `/$tms/`). `$tmsmaxsize` (default `256`) è il limite dei messaggi in kB, `$tmsclearblocked` (default `60`) sblocca i client bloccati ogni N minuti, e `secret_tms` è il token che i client devono inviare. Vedi [Message Service (TMS)](../../guides/message-service-and-apis/).\n\nExample: Nel file config\n```text\n$tms       : true\nsecret_tms : my-secret\n```\n\n### $imprint : Boolean\n\nType: `config`\n\nStampa la schermata di avvio.\n\nReturns: `Boolean`\n\n`false` nasconde il blocco informativo (nome, versione, Node.js, URL) stampato all'avvio dell'applicazione.\n\nDefault: `true`.\n\nExample: Nel file config\n```text\n$imprint : false\n```\n\n### $logger : Boolean\n\nType: `config`\n\nScrive l'output della console in logs/debug.log.\n\nReturns: `Boolean`\n\n`true` reindirizza `console.log`, `console.warn`, `console.error`, `console.time` e `console.timeEnd` al file `logs/debug.log`.\n\nDefault: `false`.\n\nExample: Nel file config\n```text\n$logger : true\n```\n\n### $dir* : String\n\nType: `config`\n\nPercorsi personalizzati delle directory dell'applicazione.\n\nReturns: `String`\n\n`$dir` + il nome di una directory ne imposta il percorso assoluto: `$dirpublic`, `$dirtmp`, `$dirlogs`, `$dirdatabases`, `$dirviews`, `$dirplugins`, `$dirmodules`, `$dirresources`, `$dirtemplates`, `$dirprivate` e le altre. `PATH.public()`, `PATH.databases()` e i loader li usano.\n\nExample: Nel file config\n```text\n$dirpublic    : /www/cdn/public\n$dirdatabases : /data/app\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG()","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"event","name":"$reconfigure","signature":"ON('$reconfigure', function() {})","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : String|Boolean","since":"0.0.16","deprecated":false},{"type":"config","name":"$root","signature":"$root : String","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : String","since":"","deprecated":false},{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : String","since":"","deprecated":false},{"type":"config","name":"$port","signature":"$port : Number","since":"","deprecated":false},{"type":"config","name":"$ip","signature":"$ip : String","since":"","deprecated":false},{"type":"config","name":"$unixsocket","signature":"$unixsocket : String","since":"","deprecated":false},{"type":"config","name":"$timezone","signature":"$timezone : String","since":"","deprecated":false},{"type":"config","name":"$insecure","signature":"$insecure : Boolean","since":"","deprecated":false},{"type":"config","name":"$performance","signature":"$performance : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpreqlimit","signature":"$httpreqlimit : Number","since":"","deprecated":false},{"type":"config","name":"$blacklist","signature":"$blacklist : String","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag : String","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer : Number","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : Number","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles : String","since":"","deprecated":false},{"type":"config","name":"$httpchecktypes","signature":"$httpchecktypes : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage : Number","since":"","deprecated":false},{"type":"config","name":"$httpmaxkeys","signature":"$httpmaxkeys : Number","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset : String","since":"0.0.16","deprecated":false},{"type":"config","name":"$xpoweredby","signature":"$xpoweredby : String","since":"","deprecated":false},{"type":"config","name":"$minify*","signature":"$minify* : Boolean","since":"","deprecated":false},{"type":"config","name":"$filtererrors","signature":"$filtererrors : Boolean","since":"","deprecated":false},{"type":"config","name":"$cleartemp","signature":"$cleartemp : Boolean","since":"","deprecated":false},{"type":"config","name":"$customtitles","signature":"$customtitles : Boolean","since":"","deprecated":false},{"type":"config","name":"$clearcache","signature":"$clearcache : Number","since":"","deprecated":false},{"type":"config","name":"$imageconverter","signature":"$imageconverter : String","since":"","deprecated":false},{"type":"config","name":"$stats","signature":"$stats : Boolean","since":"","deprecated":false},{"type":"config","name":"$sourcemap","signature":"$sourcemap : Boolean","since":"","deprecated":false},{"type":"config","name":"$npmcache","signature":"$npmcache : String","since":"","deprecated":false},{"type":"config","name":"$nodemodules","signature":"$nodemodules : String","since":"","deprecated":false},{"type":"config","name":"$python","signature":"$python : String","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : String","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"$wsmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"$wscompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"$wsencodedecode : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"$wsmaxlatency : Number","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : Number","since":"","deprecated":false},{"type":"config","name":"$proxyrequest","signature":"$proxyrequest : String","since":"","deprecated":false},{"type":"config","name":"$cookie*","signature":"$cookie* : String|Boolean","since":"","deprecated":false},{"type":"config","name":"$csrfexpiration","signature":"$csrfexpiration : String","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : String","since":"","deprecated":false},{"type":"config","name":"$tapi*","signature":"$tapi* : Boolean|String","since":"","deprecated":false},{"type":"config","name":"$tms*","signature":"$tms* : Boolean|String|Number","since":"","deprecated":false},{"type":"config","name":"$imprint","signature":"$imprint : Boolean","since":"","deprecated":false},{"type":"config","name":"$logger","signature":"$logger : Boolean","since":"","deprecated":false},{"type":"config","name":"$dir*","signature":"$dir* : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwW5GSx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/configuration/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Konfigurácia","summary":"CONF, LOADCONFIG(), DEBUG a každý $ kľúč frameworku s predvolenou hodnotou.","markdown":"---\ntitle: \"Konfigurácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/configuration/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Konfigurácia\n\n> CONF, LOADCONFIG(), DEBUG a každý $ kľúč frameworku s predvolenou hodnotou.\n\nKaždý kľúč, ktorý framework číta z `CONF`, s jeho typom a predvolenou hodnotou, plus `CONF`, `LOADCONFIG()`, `DEBUG` a udalosť `$reconfigure`. Formát súboru `config`, typy, `.env` a poradie načítania vysvetľuje návod [Konfigurácia](../../guides/configuration/).\n\n## API\n\n### CONF\n\nType: `property`\n\nGlobálny objekt s konfiguráciou aplikácie.\n\nReturns: `Object`\n\nObsahuje predvolené hodnoty frameworku a každý kľúč načítaný z volieb `F.http()`, zo súboru `config`, z konfiguračných súborov pluginov a z `LOADCONFIG()`. `F.config` je ten istý objekt. Čítaj ho kdekoľvek; zapisuj doň cez `LOADCONFIG()`, keď zmena musí obnoviť odvodené nastavenia.\n\nExample: Čítanie hodnôt\n```js\nexports.install = function() {\n\tROUTE('GET /about/', function($) {\n\t\t$.json({ name: CONF.name, version: CONF.version });\n\t});\n};\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nAplikuje konfiguračné hodnoty za behu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object|Array` | yes |  | Text konfiguračného súboru, objekt kľúčov a hodnôt alebo pole položiek `{ id, type, value }` (prijímajú sa aj `key`/`name` a `val`/`body`). |\n\nSparsuje `value` ako súbor `config` a skopíruje kľúče do `CONF`. V objekte alebo poli sa hodnoty `false`, `0` a `''` uložia ako `undefined`. Špeciálne kľúče sa spracujú: `$root` sa normalizuje a pridá sa ako prefix k `$api`, `$timezone` nastaví `process.env.TZ`, `$port` sa zmení na číslo, `$httpfiles` pridá prípony, `$cryptoiv` sa zmení na `Buffer`, `smtp`/`mail`/`mail_smtp`/`mail_smtp_options` zostavia `CONF.smtp`, `totalapi` nastaví token Total API. Potom obnoví adresáre, logger (`$logger`), zoznam CORS a TMS a vyvolá `$reconfigure`. Framework ho volá aj pre samotný súbor `config`.\n\nExample: Text\n```js\nLOADCONFIG('$httptimeout (number) : 15\\nmaintenance : true');\n```\n\nExample: Pole s typmi\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '25' },\n\t{ id: 'tags', type: 'array', value: 'a, b, c' }\n]);\n```\n\nExample: Objekt\n```js\nLOADCONFIG({ name: 'Shop', $cors: 'https://shop.example.com' });\n```\n\n### DEBUG\n\nType: `property`\n\ntrue v debug režime, false v release režime.\n\nReturns: `Boolean`\n\nGlobálny boolean. Začína ako `process.env.NODE_ENV !== 'production'`. Debug runner ho nastaví na `true` a release runner ho pred načítaním aplikácie nastaví na `false`, takže `NODE_ENV` rozhoduje o režime, keď aplikácia volá `F.http()` alebo `F.load()` bez runnera. Framework ho používa pre cache pohľadov a statických súborov, minifikáciu a source mapu (`$sourcemap` sa ním riadi).\n\nExample: Podmienený kód\n```js\nif (DEBUG)\n\tconsole.log('Debug mode');\n```\n\n### ON('$reconfigure', function() {})\n\nType: `event`\n\nVyvolá sa, keď LOADCONFIG() aplikuje nové hodnoty.\n\nVyvolá sa na konci každého volania `LOADCONFIG()`, vrátane načítania súboru `config` pri štarte. Použi ju na obnovenie vlastných objektov, ktoré závisia od konfiguračných hodnôt.\n\nExample: Obnovenie klienta\n```js\nON('$reconfigure', function() {\n\tMAIN.client = createclient(CONF.service_url);\n});\n```\n\n### totalapi : String|Boolean\n\nType: `config` · Since: `0.0.16`\n\nNastaví token Total API alebo zapne či vypne Total API.\n\nReturns: `String|Boolean`\n\nReťazec dlhší ako päť znakov sa uloží ako `CONF.secret_totalapi`, token pre volania `API('TAPI', ...)` a `TotalAPI()`. Akákoľvek iná hodnota sa uloží ako `$tapi`.\n\nExample: V konfiguračnom súbore\n```text\ntotalapi : your-total-api-token\n```\n\n### $root : String\n\nType: `config`\n\nURL prefix pre celú aplikáciu.\n\nReturns: `String`\n\nNormalizuje sa tak, aby začínal aj končil na `/`. URL rout dostanú prefix (API routy cez `$api`), statické súbory sa servírujú pod ním a `F.virtualpath()` ho pridáva. Použi ho, keď aplikácia beží pod podcestou za proxy.\n\nPredvolene: `''`.\n\nExample: V konfiguračnom súbore\n```text\n$root : /app/\n```\n\n### $api : String\n\nType: `config`\n\nPredvolený API endpoint.\n\nReturns: `String`\n\n`?` v URL routy sa nahradí touto hodnotou, takže `ROUTE('API ?/users/ ...')` počúva na `/api/users/`. S `$root` sa k nej pridá prefix.\n\nPredvolene: `'/api/'`.\n\nExample: V konfiguračnom súbore\n```text\n$api : /v1/\n```\n\n### $mcp : Boolean\n\nType: `config`\n\nZapne MCP server.\n\nReturns: `Boolean`\n\n`true` vytvorí routu `POST /$mcp/`, kde AI klienti vypisujú a volajú akcie, ktoré majú `mcp: true`. Routa sa vytvorí, keď je aplikácia pripravená, takže kľúč nastav v súbore `config` alebo pred štartom. Pozri [MCP server](../../guides/mcp-server/).\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\n$mcp : true\n```\n\n### $cors : String\n\nType: `config`\n\nOriginy povolené pre cross-origin požiadavky.\n\nReturns: `String`\n\n`*` povolí každý origin. Inak je to zoznam originov oddelených `,`, `;` alebo `|`, porovnávaný s hlavičkou `Origin` (napríklad `https://app.example.com`). Položka začínajúca na `*` zodpovedá každému originu, ktorý obsahuje zvyšok (`*example.com`). Požiadavky z rovnakého hosta sú povolené vždy; ostatné originy dostanú chybu 400. `CORS()` mení hodnotu v kóde; pozri [Smerovanie](../../guides/routing/#cors).\n\nPredvolene: `''`.\n\nExample: V konfiguračnom súbore\n```text\n$cors : https://app.example.com, *example.org\n```\n\n### $port : Number\n\nType: `config`\n\nPort HTTP servera.\n\nReturns: `Number`\n\nHodnota sa konvertuje na číslo. Pre automatický port kľúč vynechaj: voľba `port` z `F.http()`, premenná prostredia `PORT`, prvé 3- až 5-ciferné číslo v argumentoch príkazového riadka alebo 8000.\n\nPredvolene: `'auto'`.\n\nExample: V konfiguračnom súbore\n```text\n$port : 8000\n```\n\n### $ip : String\n\nType: `config`\n\nIP adresa, na ktorej HTTP server počúva.\n\nReturns: `String`\n\nVoľba `ip` z `F.http()` ju prepíše. Použi `127.0.0.1`, ak chceš prijímať len lokálne spojenia.\n\nPredvolene: `'0.0.0.0'`.\n\nExample: V konfiguračnom súbore\n```text\n$ip : 127.0.0.1\n```\n\n### $unixsocket : String\n\nType: `config`\n\nCesta k Unix socketu pre HTTP server.\n\nReturns: `String`\n\nKeď je nastavená (alebo keď `F.http()` dostane voľbu `unixsocket`), server počúva na sockete namiesto portu.\n\nPredvolene: `''`.\n\nExample: V konfiguračnom súbore\n```text\n$unixsocket : /var/run/app.sock\n```\n\n### $timezone : String\n\nType: `config`\n\nČasové pásmo procesu.\n\nReturns: `String`\n\nSkopíruje sa do `process.env.TZ`, takže ho používajú všetky hodnoty `Date` procesu.\n\nPredvolene: `'utc'`.\n\nExample: V konfiguračnom súbore\n```text\n$timezone : Europe/Bratislava\n```\n\n### $insecure : Boolean\n\nType: `config`\n\nPrijíma neplatné TLS certifikáty v odchádzajúcich požiadavkách.\n\nReturns: `Boolean`\n\nNastaví `process.env.NODE_TLS_REJECT_UNAUTHORIZED` na `0`, keď je `true`, inak na `1`. Používaj ho len pri vývoji proti serverom so self-signed certifikátmi.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\n$insecure : true\n```\n\n### $performance : Boolean\n\nType: `config`\n\nVyladí HTTP sockety pre veľa spojení.\n\nReturns: `Boolean`\n\nNastaví `maxSockets` globálneho HTTP agenta na 9999 a zapne `setNoDelay` a keep-alive pre prichádzajúce spojenia.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\n$performance : true\n```\n\n### $httpreqlimit : Number\n\nType: `config`\n\nMaximálny počet požiadaviek z jednej IP adresy za minútu.\n\nReturns: `Number`\n\n`0` limit vypne. Nad limitom dostávajú požiadavky chybu 503, kým sa počítadlá v nasledujúcej minúte nevynulujú.\n\nPredvolene: `0`.\n\nExample: V konfiguračnom súbore\n```text\n$httpreqlimit (number) : 300\n```\n\n### $blacklist : String\n\nType: `config`\n\nBlokované IP adresy.\n\nReturns: `String`\n\nReťazec IP adries, napríklad oddelených čiarkami. HTTP požiadavky z IP adresy, ktorá sa v ňom nachádza, dostanú chybu 400 a WebSocket spojenia z nej sa zatvoria.\n\nPredvolene: `''`.\n\nExample: V konfiguračnom súbore\n```text\n$blacklist : 10.0.0.5, 10.0.0.6\n```\n\n### $httpcompress : Boolean\n\nType: `config`\n\nKomprimuje odpovede pomocou gzip.\n\nReturns: `Boolean`\n\nKeď klient prijíma gzip, komprimujú sa textové odpovede väčšie ako 256 bajtov a komprimovateľné statické súbory.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\n$httpcompress : false\n```\n\n### $httpetag : String\n\nType: `config`\n\nHodnota pridaná do ETagu statických súborov a cachovaných odpovedí.\n\nReturns: `String`\n\nKeď je prázdna, vytvorí sa z `CONF.version` bez bodiek a medzier, takže nová verzia zneplatní cache prehliadačov.\n\nPredvolene: `''`.\n\nExample: V konfiguračnom súbore\n```text\n$httpetag : build42\n```\n\n### $httpmaxsize : Number\n\nType: `config`\n\nMaximálna veľkosť tela požiadavky v kB.\n\nReturns: `Number`\n\nPredvolený limit každej HTTP routy bez vlastného limitu.\n\nPredvolene: `256`.\n\nExample: V konfiguračnom súbore\n```text\n$httpmaxsize (number) : 1024\n```\n\n### $httprangebuffer : Number\n\nType: `config`\n\nVeľkosť jedného bloku range odpovede v kB.\n\nReturns: `Number`\n\nPoužíva sa pre požiadavky `Range` na statické súbory (video, audio), keď klient neuvedie koniec.\n\nPredvolene: `5120`.\n\nExample: V konfiguračnom súbore\n```text\n$httprangebuffer (number) : 2048\n```\n\n### $httptimeout : Number\n\nType: `config`\n\nTimeout požiadavky v sekundách.\n\nReturns: `Number`\n\nRouta si môže nastaviť vlastný timeout. Požiadavky sa kontrolujú každých päť sekúnd.\n\nPredvolene: `5`.\n\nExample: V konfiguračnom súbore\n```text\n$httptimeout (number) : 10\n```\n\n### $httpfiles : String\n\nType: `config`\n\nPrípony súborov, ktoré sa servírujú ako statické súbory.\n\nReturns: `String`\n\nV konfiguračnom súbore zoznam prípon oddelených čiarkami, ktoré sa pridajú k predvoleným (`jpg`, `png`, `css`, `js`, `json`, `pdf`, `mp4` a mnoho ďalších). V kóde je to objekt s `true` pre každú povolenú príponu.\n\nPredvolene: `common web extensions`.\n\nExample: V konfiguračnom súbore\n```text\n$httpfiles : glb, gltf\n```\n\n### $httpchecktypes : Boolean\n\nType: `config`\n\nKontroluje content type nahratých súborov.\n\nReturns: `Boolean`\n\nLen pre `multipart/form-data`. `false` kontrolu preskočí.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\n$httpchecktypes : false\n```\n\n### $httpmaxage : Number\n\nType: `config`\n\nMax-age cachovaných odpovedí v sekundách.\n\nReturns: `Number`\n\nPoužíva sa v hlavičke `Cache-Control` statických súborov a odpovedí cachovaných cez `controller.httpcache()`.\n\nPredvolene: `60`.\n\nExample: V konfiguračnom súbore\n```text\n$httpmaxage (number) : 300\n```\n\n### $httpmaxkeys : Number\n\nType: `config`\n\nLimity URL-enkódovaných dát.\n\nReturns: `Number`\n\n`$httpmaxkeys` je maximálny počet kľúčov sparsovaných z query stringu alebo URL-enkódovaného tela. `$httpmaxkey` (predvolene `25`) je maximálna dĺžka jedného kľúča; dlhšie kľúče sa zahodia.\n\nPredvolene: `33`.\n\nExample: V konfiguračnom súbore\n```text\n$httpmaxkeys (number) : 100\n$httpmaxkey (number)  : 50\n```\n\n### $httpcacheoffset : String\n\nType: `config` · Since: `0.0.16`\n\nPosunie dátum Last-Modified statických súborov.\n\nReturns: `String`\n\nČasový posun vo formáte `Date.add()`, napríklad `1 minute` alebo `-5 minutes`. Pripočíta sa k času úpravy súboru v hlavičke `Last-Modified`.\n\nPredvolene: `''`.\n\nExample: V konfiguračnom súbore\n```text\n$httpcacheoffset : 1 minute\n```\n\n### $xpoweredby : String\n\nType: `config`\n\nHodnota hlavičky X-Powered-By.\n\nReturns: `String`\n\nPrázdna hodnota hlavičku odstráni.\n\nPredvolene: `'Total.js'`.\n\nExample: V konfiguračnom súbore\n```text\n$xpoweredby :\n```\n\n### $minify* : Boolean\n\nType: `config`\n\nMinifikácia JavaScriptu, CSS a HTML.\n\nReturns: `Boolean`\n\n`$minifyjs`, `$minifycss` a `$minifyhtml` (všetky predvolene `true`) zapínajú alebo vypínajú minifikáciu statických súborov `.js` a `.css`, inline kódu a vykresleného HTML.\n\nExample: V konfiguračnom súbore\n```text\n$minifyhtml : false\n$minifyjs   : true\n$minifycss  : true\n```\n\n### $filtererrors : Boolean\n\nType: `config`\n\nIgnoruje neškodné nezachytené chyby.\n\nReturns: `Boolean`\n\nNezachytené chyby `EPIPE`, `invalid distance` a `ERR_IPC_CHANNEL_CLOSED` sa nelogujú.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\n$filtererrors : false\n```\n\n### $cleartemp : Boolean\n\nType: `config`\n\nPri štarte vyčistí adresár tmp.\n\nReturns: `Boolean`\n\nPri načítaní aplikácie zmaže súbory `.js`, `.css`, `.html`, `.htm`, `.tmp` a `.upload` v adresári `tmp`.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\n$cleartemp : false\n```\n\n### $customtitles : Boolean\n\nType: `config`\n\nVypne automatickú príponu titulkov stránok.\n\nReturns: `Boolean`\n\nPredvolene sa k titulku pohľadu na iných stránkach ako `/` pripojí ` - ` a `CONF.name`. `true` ponechá titulok tak, ako ho nastavíš.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\n$customtitles : true\n```\n\n### $clearcache : Number\n\nType: `config`\n\nAko často sa čistia interné cache, v minútach.\n\nReturns: `Number`\n\nVyčistí cache akcií, ciest, pohľadov, obrázkov, šablón, query builderov a úložísk súborov.\n\nPredvolene: `10`.\n\nExample: V konfiguračnom súbore\n```text\n$clearcache (number) : 30\n```\n\n### $imageconverter : String\n\nType: `config`\n\nProgram, ktorý používa modul obrázkov.\n\nReturns: `String`\n\n`gm` pre GraphicsMagick, `im` pre príkaz `convert` z ImageMagick alebo `magick` pre ImageMagick 7. Pozri [Obrázky](../../guides/images/).\n\nPredvolene: `'gm'`.\n\nExample: V konfiguračnom súbore\n```text\n$imageconverter : magick\n```\n\n### $stats : Boolean\n\nType: `config`\n\nZapisuje súbor so štatistikami aplikácie.\n\nReturns: `Boolean`\n\nFramework každú minútu zapíše štatistiky využitia do `<main script>.json` (napríklad `index.js.json`). `F.load()` so zoznamom typov bez `stats` to vypne.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\n$stats : false\n```\n\n### $sourcemap : Boolean\n\nType: `config`\n\nZapisuje source map aplikácie.\n\nReturns: `Boolean`\n\nZapíše routy, akcie, schémy a pluginy do `<main script>.map` pre nástroje. Framework ho nastaví na hodnotu `DEBUG`, keď načítava všetky časti, a na `false`, keď `F.load()` dostane zoznam typov bez `stats`.\n\nExample: Vypnutie\n```text\n$sourcemap : false\n```\n\n### $npmcache : String\n\nType: `config`\n\nAdresár npm cache pre NPMINSTALL().\n\nReturns: `String`\n\nOdovzdá sa npm ako `NPM_CONFIG_CACHE`.\n\nPredvolene: `'/var/www/.npm'`.\n\nExample: V konfiguračnom súbore\n```text\n$npmcache : /tmp/.npm\n```\n\n### $nodemodules : String\n\nType: `config`\n\nAdresár nainštalovaných npm modulov.\n\nReturns: `String`\n\n`NPMINSTALL()` doň inštaluje a `REQUIRE()` z neho načítava, keď bežný `require()` zlyhá.\n\nPredvolene: `'<root>/node_modules'`.\n\nExample: V konfiguračnom súbore\n```text\n$nodemodules : /www/shared/node_modules\n```\n\n### $python : String\n\nType: `config`\n\nPríkaz Pythonu.\n\nReturns: `String`\n\nPoužíva ho `F.python()` a `F.pipinstall()`. `PYPELINE()` vždy spúšťa `python3`.\n\nPredvolene: `'python3'`.\n\nExample: V konfiguračnom súbore\n```text\n$python : /usr/bin/python3.12\n```\n\n### $shell : String\n\nType: `config`\n\nShell pre SHELL().\n\nReturns: `String`\n\nKeď je nastavený, `SHELL()` spúšťa príkazy v tomto shelli namiesto predvoleného.\n\nPredvolene: `''`.\n\nExample: V konfiguračnom súbore\n```text\n$shell : /bin/bash\n```\n\n### $wsmaxsize : Number\n\nType: `config`\n\nMaximálna veľkosť WebSocket správy v kB.\n\nReturns: `Number`\n\nPredvolený limit každej WebSocket routy bez vlastného limitu.\n\nPredvolene: `256`.\n\nExample: V konfiguračnom súbore\n```text\n$wsmaxsize (number) : 1024\n```\n\n### $wscompress : Boolean\n\nType: `config`\n\nKomprimuje WebSocket správy.\n\nReturns: `Boolean`\n\nPoužíva `permessage-deflate`, keď ho klient podporuje.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\n$wscompress : false\n```\n\n### $wsencodedecode : Boolean\n\nType: `config`\n\nURL-enkóduje WebSocket správy.\n\nReturns: `Boolean`\n\n`true` enkóduje odchádzajúce správy cez `encodeURIComponent` a dekóduje prichádzajúce.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\n$wsencodedecode : true\n```\n\n### $wsmaxlatency : Number\n\nType: `config`\n\nMaximálna latencia pingu WebSocket klienta v milisekundách.\n\nReturns: `Number`\n\nKeď framework pinguje spojenia, klienti bez odpovede alebo s vyššou latenciou sa zatvoria.\n\nPredvolene: `2000`.\n\nExample: V konfiguračnom súbore\n```text\n$wsmaxlatency (number) : 5000\n```\n\n### $proxytimeout : Number\n\nType: `config`\n\nTimeout proxovaných požiadaviek v sekundách.\n\nReturns: `Number`\n\nPoužívajú ho routy `PROXY()` bez vlastného timeoutu.\n\nPredvolene: `5`.\n\nExample: V konfiguračnom súbore\n```text\n$proxytimeout (number) : 30\n```\n\n### $proxyrequest : String\n\nType: `config`\n\nProxy server pre odchádzajúce požiadavky.\n\nReturns: `String`\n\n`REQUEST()` a buildery, ktoré ho používajú, posielajú požiadavky cez túto proxy (`host:port`, `http://host:port`). Požiadavky na `localhost` a `127.0.0.1` idú priamo.\n\nPredvolene: `not set`.\n\nExample: V konfiguračnom súbore\n```text\n$proxyrequest : http://proxy.local:3128\n```\n\n### $cookie* : String|Boolean\n\nType: `config`\n\nPredvolené hodnoty cookies.\n\nReturns: `String|Boolean`\n\n`$cookiesamesite` (predvolene `Lax`) je hodnota `SameSite` pre cookies bez vlastnej. `$cookiesecure` (predvolene `false`) pridá `Secure` do cookies, ktoré nenastavujú `secure`.\n\nExample: V konfiguračnom súbore\n```text\n$cookiesamesite : Strict\n$cookiesecure   : true\n```\n\n### $csrfexpiration : String\n\nType: `config`\n\nŽivotnosť CSRF tokenov.\n\nReturns: `String`\n\nČas vo formáte `Date.add()`. Tokeny sa vytvárajú, len keď je nastavené `secret_csrf`.\n\nPredvolene: `'30 minutes'`.\n\nExample: V konfiguračnom súbore\n```text\n$csrfexpiration : 2 hours\n```\n\n### $crypto : String\n\nType: `config`\n\nNode.js šifra pre ENCRYPT() a DECRYPT().\n\nReturns: `String`\n\nKeď je nastavená (napríklad `aes-256-cbc`), `ENCRYPT()` a `DECRYPT()` použijú `crypto.createCipheriv()` s kľúčom, ktorý odovzdáš, a s `$cryptoiv` ako IV; kľúč musí mať dĺžku, ktorú šifra vyžaduje. `$cryptoiv` sa vytvorí z hashu systému; v konfiguračnom súbore ho zadaj ako hex alebo base64 a zmení sa na `Buffer`.\n\nPredvolene: `not set`.\n\nExample: V konfiguračnom súbore\n```text\n$crypto   : aes-256-cbc\n$cryptoiv : 000102030405060708090a0b0c0d0e0f\n```\n\n### $tapi* : Boolean|String\n\nType: `config`\n\nNastavenia Total API.\n\nReturns: `Boolean|String`\n\n`$tapi` (predvolene `true`) povolí volania `API('TAPI', ...)`; s `false` zlyhá každá operácia okrem `check` s chybou `totalapi_inactive`. `$tapiurl` (predvolene `eu`) je región v `https://<region>.api.totaljs.com/`. Token je `secret_totalapi`; `$tapisecret` sa číta ako náhrada. `$tapimail : true` posiela e-maily cez Total API namiesto SMTP (pozri [Posielanie e-mailov](../../guides/mail/)) a `$tapilogger : true` tam posiela auditné záznamy (pozri [Auditné logy](../../guides/audit-logs/)); obe sú predvolene `false`.\n\nExample: V konfiguračnom súbore\n```text\nsecret_totalapi : your-token\n$tapiurl        : eu\n```\n\n### $tms* : Boolean|String|Number\n\nType: `config`\n\nNastavenia Total.js Message Service.\n\nReturns: `Boolean|String|Number`\n\n`$tms` (predvolene `false`) otvorí TMS WebSocket endpoint `$tmsurl` (predvolene `/$tms/`). `$tmsmaxsize` (predvolene `256`) je limit správy v kB, `$tmsclearblocked` (predvolene `60`) čistí blokovaných klientov každých N minút a `secret_tms` je token, ktorý musia klienti poslať. Pozri [Message Service (TMS)](../../guides/message-service-and-apis/).\n\nExample: V konfiguračnom súbore\n```text\n$tms       : true\nsecret_tms : my-secret\n```\n\n### $imprint : Boolean\n\nType: `config`\n\nVypíše úvodnú obrazovku.\n\nReturns: `Boolean`\n\n`false` skryje informačný blok (meno, verzia, Node.js, URL) vypisovaný pri štarte aplikácie.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\n$imprint : false\n```\n\n### $logger : Boolean\n\nType: `config`\n\nZapisuje výstup konzoly do logs/debug.log.\n\nReturns: `Boolean`\n\n`true` presmeruje `console.log`, `console.warn`, `console.error`, `console.time` a `console.timeEnd` do súboru `logs/debug.log`.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\n$logger : true\n```\n\n### $dir* : String\n\nType: `config`\n\nVlastné cesty k adresárom aplikácie.\n\nReturns: `String`\n\n`$dir` + meno adresára nastaví jeho absolútnu cestu: `$dirpublic`, `$dirtmp`, `$dirlogs`, `$dirdatabases`, `$dirviews`, `$dirplugins`, `$dirmodules`, `$dirresources`, `$dirtemplates`, `$dirprivate` a ďalšie. Používajú ich `PATH.public()`, `PATH.databases()` a loadery.\n\nExample: V konfiguračnom súbore\n```text\n$dirpublic    : /www/cdn/public\n$dirdatabases : /data/app\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG()","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"event","name":"$reconfigure","signature":"ON('$reconfigure', function() {})","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : String|Boolean","since":"0.0.16","deprecated":false},{"type":"config","name":"$root","signature":"$root : String","since":"","deprecated":false},{"type":"config","name":"$api","signature":"$api : String","since":"","deprecated":false},{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"$cors","signature":"$cors : String","since":"","deprecated":false},{"type":"config","name":"$port","signature":"$port : Number","since":"","deprecated":false},{"type":"config","name":"$ip","signature":"$ip : String","since":"","deprecated":false},{"type":"config","name":"$unixsocket","signature":"$unixsocket : String","since":"","deprecated":false},{"type":"config","name":"$timezone","signature":"$timezone : String","since":"","deprecated":false},{"type":"config","name":"$insecure","signature":"$insecure : Boolean","since":"","deprecated":false},{"type":"config","name":"$performance","signature":"$performance : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpreqlimit","signature":"$httpreqlimit : Number","since":"","deprecated":false},{"type":"config","name":"$blacklist","signature":"$blacklist : String","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag : String","since":"","deprecated":false},{"type":"config","name":"$httpmaxsize","signature":"$httpmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer : Number","since":"","deprecated":false},{"type":"config","name":"$httptimeout","signature":"$httptimeout : Number","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles : String","since":"","deprecated":false},{"type":"config","name":"$httpchecktypes","signature":"$httpchecktypes : Boolean","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage : Number","since":"","deprecated":false},{"type":"config","name":"$httpmaxkeys","signature":"$httpmaxkeys : Number","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset : String","since":"0.0.16","deprecated":false},{"type":"config","name":"$xpoweredby","signature":"$xpoweredby : String","since":"","deprecated":false},{"type":"config","name":"$minify*","signature":"$minify* : Boolean","since":"","deprecated":false},{"type":"config","name":"$filtererrors","signature":"$filtererrors : Boolean","since":"","deprecated":false},{"type":"config","name":"$cleartemp","signature":"$cleartemp : Boolean","since":"","deprecated":false},{"type":"config","name":"$customtitles","signature":"$customtitles : Boolean","since":"","deprecated":false},{"type":"config","name":"$clearcache","signature":"$clearcache : Number","since":"","deprecated":false},{"type":"config","name":"$imageconverter","signature":"$imageconverter : String","since":"","deprecated":false},{"type":"config","name":"$stats","signature":"$stats : Boolean","since":"","deprecated":false},{"type":"config","name":"$sourcemap","signature":"$sourcemap : Boolean","since":"","deprecated":false},{"type":"config","name":"$npmcache","signature":"$npmcache : String","since":"","deprecated":false},{"type":"config","name":"$nodemodules","signature":"$nodemodules : String","since":"","deprecated":false},{"type":"config","name":"$python","signature":"$python : String","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : String","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"$wsmaxsize : Number","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"$wscompress : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"$wsencodedecode : Boolean","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"$wsmaxlatency : Number","since":"","deprecated":false},{"type":"config","name":"$proxytimeout","signature":"$proxytimeout : Number","since":"","deprecated":false},{"type":"config","name":"$proxyrequest","signature":"$proxyrequest : String","since":"","deprecated":false},{"type":"config","name":"$cookie*","signature":"$cookie* : String|Boolean","since":"","deprecated":false},{"type":"config","name":"$csrfexpiration","signature":"$csrfexpiration : String","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : String","since":"","deprecated":false},{"type":"config","name":"$tapi*","signature":"$tapi* : Boolean|String","since":"","deprecated":false},{"type":"config","name":"$tms*","signature":"$tms* : Boolean|String|Number","since":"","deprecated":false},{"type":"config","name":"$imprint","signature":"$imprint : Boolean","since":"","deprecated":false},{"type":"config","name":"$logger","signature":"$logger : Boolean","since":"","deprecated":false},{"type":"config","name":"$dir*","signature":"$dir* : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwWIIEx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/authorization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Authorization","summary":"AUTH(), route flags, permissions, sessions and BLOCKED().","markdown":"---\ntitle: Authorization\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/authorization/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Authorization\n\n> AUTH(), route flags, permissions, sessions and BLOCKED().\n\nEverything that decides and checks the user of a request: the `AUTH()` delegate and its built-in sessions, the `+` and `-` route flags, `UNAUTHORIZED()` and action permissions, and `BLOCKED()`. The guide [Authorization](../../guides/authorization/) explains how they work together with examples.\n\nEncryption and audit logs have their own pages: [Encryption](../encryption/) and [Audit logs](../audit-logs/).\n\n## API\n\n### AUTH(callback)\n\nType: `delegate`\n\nRegisters the authorization delegate that decides who the user of a request is.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)`; call `$.success(user)` or `$.invalid()`. |\n\nReturns: `undefined`\n\nThe delegate runs for each HTTP request and WebSocket connection that matches a route, after the body is parsed and before the route action. `$` has `headers`, `query`, `body`, `ip`, `ua`, `url`, `cookie(name)`, `controller` and, for WebSocket, `iswebsocket: true`. Call `$.success(user)` to authorize the request or `$.invalid()` to refuse it; the delegate can be asynchronous. A second call replaces the delegate. `F.auth()` is the same function.\n\nExample: Token in a header\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\tDATA.read('tbl_user').where('token', token).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\n### AUTH(options)\n\nType: `method`\n\nInstalls the built-in cookie session system.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.secret` | `String` | yes |  | The secret that signs the session tokens. |\n| `options.cookie` | `String` | no |  | The name of the session cookie. |\n| `options.header` | `String` | no |  | A lower-case header name to read the token from when there is no cookie. |\n| `options.options` | `Object` | no |  | Cookie options used by `authcookie()` and when the cookie is removed (`httponly`, `security`, `domain`...). |\n| `options.expire` | `String` | no | `'5 minutes'` | How long loaded user data stays in memory. |\n| `options.cleaner` | `Number` | no | `5` | How often, in minutes, expired sessions are removed. |\n| `options.strict` | `Boolean` | no | `true` | A cached session is valid only for the same user agent. |\n| `options.ddos` | `Number` | no |  | How many invalid tokens one IP address may send before it is refused until the next cleaning. |\n| `options.onread` | `Function` | yes |  | `function(meta, callback, $)` loads the user; see `opt.onread`. |\n\nReturns: `undefined`\n\nWith an object, `AUTH()` turns it into a session manager and registers its `auth` function as the delegate. The object gets the methods `authcookie()`, `sign()`, `logout()`, `update()`, `refresh()` and the in-memory `sessions`, so keep a reference to it (for example in `MAIN`). The token is read from the cookie `cookie`, or from the header `header`. Its signature is checked with `secret`, the session is taken from memory, and `onread()` is called when it is not there.\n\nExample: Session setup\n```js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').id(meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.session = opt;\n```\n\n### opt.onread = function(meta, callback, $)\n\nType: `delegate`\n\nLoads the user of a session that is not in memory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `callback` | `Function` | yes |  | `function(err, data)`. |\n| `$` | `Object` | yes |  | The options of the request. |\n\n`meta` is `{ sessionid, userid, ip, ua }` from the verified token. Call `callback(err, data)`; `data` becomes the user and is cached for `expire`. An error or empty `data` refuses the request and removes the cookie. Parallel requests with the same session wait for the first `onread()`.\n\nExample: Read from the database\n```js\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n```\n\n### opt.onsession = function(session, $, [isnew])\n\nType: `delegate`\n\nRuns for each authorized request before the user is accepted.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | The session. |\n| `$` | `Object` | yes |  | The options of the request. |\n| `isnew` | `Boolean` | no |  | `true` when the data was just read. |\n\nReturns: `Boolean` `true` to stop the default success.\n\n`session` is `{ sessionid, userid, data, ua, expire }`; `isnew` is `true` right after `onread()`. Return `true` to take over: the framework does not call `$.success()`, so you call `$.success()` or `$.invalid()` yourself.\n\nExample: Count requests\n```js\nopt.onsession = function(session, $) {\n\tsession.data.requests = (session.data.requests || 0) + 1;\n};\n```\n\n### opt.onauthorize = function($)\n\nType: `delegate`\n\nRuns first in the session delegate; return true to handle the request yourself.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The options of the request. |\n\nReturns: `Boolean` `true` to skip the session check.\n\nUse it to accept other credentials (an API key, for example) before the cookie is read. When it returns `true` you must call `$.success()` or `$.invalid()`.\n\nExample: API key\n```js\nopt.onauthorize = function($) {\n\tif ($.headers['x-apikey'] === CONF.apikey) {\n\t\t$.success({ id: 'api', sa: true });\n\t\treturn true;\n\t}\n};\n```\n\n### opt.onfree = function(meta)\n\nType: `delegate`\n\nRuns after expired sessions are removed from memory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessions: Array, users: Array }`. |\n\n`meta.sessions` is an array of removed session IDs, `meta.users` the IDs of users that have no live session left.\n\nExample: Log it\n```js\nopt.onfree = function(meta) {\n\tconsole.log('Released', meta.sessions.length, 'sessions');\n};\n```\n\n### opt.onlogout = function(session)\n\nType: `delegate`\n\nRuns when logout() removes a session from memory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | The removed session. |\n\nGets the removed session object `{ sessionid, userid, data, ua, expire }`. When the session is not in memory, `opt.onremove(sessionid)` is called instead.\n\nExample: Store the time\n```js\nopt.onlogout = function(session) {\n\tDATA.modify('tbl_user', { dtlogout: NOW }).id(session.userid);\n};\n```\n\n### opt.onddos = function($)\n\nType: `delegate`\n\nRuns when an IP address exceeded the ddos limit of invalid tokens.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The options of the request. |\n\nThe request is refused right after this call. The counters are cleared every `cleaner` minutes.\n\nExample: Log it\n```js\nopt.ddos = 10;\nopt.onddos = function($) {\n\tconsole.warn('Too many invalid tokens from', $.ip);\n};\n```\n\n### opt.localize = function(user, controller)\n\nType: `delegate`\n\nReturns the language of the request from the user data.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | The user data or `null`. |\n| `controller` | `Controller` | yes |  | The controller. |\n\nReturns: `String` A language code.\n\nCalled with the user data, or with `null` when the request has no token or the cached session belongs to another user agent; the returned value becomes `controller.language`. `opt.locale` is accepted as the same option.\n\nExample: User language\n```js\nopt.localize = function(user, ctrl) {\n\treturn user ? user.language : (ctrl.headers['accept-language'] || '').substring(0, 2);\n};\n```\n\n### opt.authcookie($, sessionid, userid, [expire], [options])\n\nType: `method`\n\nSigns a token and sets the session cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action or a controller. |\n| `sessionid` | `String` | yes |  | A new unique ID, for example `UID()`. |\n| `userid` | `String` | yes |  | The user ID passed later to `onread()`. |\n| `expire` | `String|Date` | no |  | The cookie expiration, for example `'1 month'`. |\n| `options` | `Object` | no |  | Cookie options. |\n\nReturns: `String` The token.\n\nCall it after a successful login. It creates the token with `sign()` and writes the cookie `opt.cookie` with `options` (default `opt.options`). The session itself is created on the next request through `onread()`.\n\nExample: Login\n```js\nMAIN.session.authcookie($, UID(), user.id, '1 month');\n$.success();\n```\n\n### opt.sign(sessionid, userid)\n\nType: `method`\n\nCreates a signed session token without setting a cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | A unique session ID. |\n| `userid` | `String` | yes |  | The user ID. |\n\nReturns: `String` The token.\n\nUse it for clients that send the token in the `header` option instead of a cookie.\n\nExample: Token for a mobile app\n```js\nopt.header = 'x-token';\n// in the login action\n$.success(MAIN.session.sign(UID(), user.id));\n```\n\n### opt.logout($)\n\nType: `method`\n\nRemoves the session of the request and its cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object|String` | yes |  | The request or a session ID. |\n\nReturns: `Boolean` `true` when a session was removed.\n\n`$` is the `$` of an action: the session in memory and the cookie are removed. With a controller or a session ID string only the session in memory is removed; the cookie stays and the next request reads the user again. It returns `true` when the session was in memory.\n\nExample: Logout action\n```js\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n### opt.update(userid, fn)\n\nType: `method`\n\nChanges the cached data of every session of a user.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | The user ID. |\n| `fn` | `Function` | yes |  | `function(data, session)`. |\n\nReturns: `Number` How many sessions were updated.\n\nCalls `fn(data, session)` for each session of `userid` in memory.\n\nExample: Rename\n```js\nMAIN.session.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### opt.refresh(userid, [exceptsessionid])\n\nType: `method`\n\nDrops the cached sessions of a user so the next request reads the user again.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | The user ID. |\n| `exceptsessionid` | `String` | no |  | A session to keep. |\n\nReturns: `Number` How many sessions were dropped.\n\nThe cookies stay valid; `onread()` loads fresh data on the next request. Pass `exceptsessionid` to keep one session in memory.\n\nExample: After a permission change\n```js\nMAIN.session.refresh(model.userid);\n```\n\n### opt.sessions\n\nType: `property`\n\nThe sessions in memory, keyed by session ID.\n\nReturns: `Object`\n\nEach item is `{ sessionid, userid, data, ua, expire }`.\n\nExample: Online users\n```js\nvar count = Object.keys(MAIN.session.sessions).length;\n```\n\n### DEF.onAuthorize\n\nType: `property`\n\nThe registered authorization delegate.\n\nReturns: `Function`\n\n`AUTH()` sets it. When it is empty, `$.user` is never set and the `+` and `-` flags of routes are not checked, so `+` routes are open to everybody.\n\nExample: Check\n```js\nif (!DEF.onAuthorize)\n\tconsole.warn('No AUTH() delegate');\n```\n\n### ROUTE('+METHOD /url/ ...')\n\nType: `type`\n\nThe route is only for authorized requests.\n\nThe flag goes in front of the method. When the delegate refuses the request, the framework looks for another route with the same URL that fits (a `-` route or one without a flag); if there is none, an HTTP request gets `401` and a WebSocket connection is refused during the handshake, so a browser client receives the close code `1006`. For `API` routes the flag of the line is checked for each endpoint.\n\nExample: Admin area\n```js\nROUTE('+GET /admin/', dashboard);\nROUTE('+API /api/ orders_list --> Orders/list');\nROUTE('+SOCKET /chat/', chat);\n```\n\n### ROUTE('-METHOD /url/ ...')\n\nType: `type`\n\nThe route is only for unauthorized requests.\n\nTypical for login and registration pages. With a `+` route on the same URL you serve visitors and users differently.\n\nExample: Same URL for both\n```js\nROUTE('+GET /', 'app');\nROUTE('-GET /', 'login');\n```\n\n### controller.user\n\nType: `property`\n\nThe user accepted by the AUTH() delegate.\n\nReturns: `Object`\n\n`undefined` when the request is not authorized. It is set for every route when a delegate exists, including routes without a flag, and is passed to actions as `$.user`.\n\nExample: Read it\n```js\nfunction dashboard($) {\n\t$.json({ name: $.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nThe user of the request inside an action.\n\nReturns: `Object`\n\nTaken from the controller that called the action, or from `ACTION().user(obj)` when you call an action from code.\n\nExample: Owner filter\n```js\naction: function($) {\n\tDATA.find('tbl_order').where('userid', $.user.id).callback($);\n}\n```\n\n### controller.authorize([callback])\n\nType: `method`\n\nRuns the AUTH() delegate on demand.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, user)`. |\n\nReturns: `Promise` When `callback` is not given.\n\nSets `controller.user` when the delegate accepts the request. Without `callback` it returns a `Promise` that resolves with the user or `undefined`; it never rejects.\n\nExample: Inside a route\n```js\nasync function detail($) {\n\tvar user = await $.authorize();\n\t$.json({ logged: !!user });\n}\n```\n\n### controller.session\n\nType: `property`\n\nThe built-in session of the request.\n\nReturns: `Object`\n\nSet by `AUTH(options)`: `{ sessionid, userid, data, ua, expire }`. `controller.sessionid` holds the session ID and `$.sessionid` reads it in actions.\n\nExample: Session ID\n```js\nfunction info($) {\n\t$.json({ sessionid: $.sessionid });\n}\n```\n\n### UNAUTHORIZED($, [permission1], [permission2], [...])\n\nType: `method`\n\nChecks the permissions of the user and responds with 401 when they are missing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action or a controller. |\n| `permission` | `String` | no |  | One or more permission names; any of them is enough. |\n\nReturns: `Boolean` `true` when the user is not allowed and the request was answered.\n\nReturns `false` when the user has `sa` or `su`, or one of the permissions in `user.permissions` (or `user.roles`), which can be an array or an object. Otherwise it calls `$.invalid(401)` and returns `true`. Without a user it always returns `true`. `F.unauthorized()` is the same function.\n\nExample: Guard an action\n```js\naction: function($) {\n\tif (UNAUTHORIZED($, 'orders'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.unauthorized([permission1], [permission2], [...])\n\nType: `method`\n\nUNAUTHORIZED() for the current $.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | no |  | One or more permission names. |\n\nReturns: `Boolean` `true` when the user is not allowed.\n\nThe same check with `$` taken from the action.\n\nExample: Short form\n```js\nif ($.unauthorized('orders'))\n\treturn;\n```\n\n### user.permissions\n\nType: `property`\n\nThe permissions of the user, read by UNAUTHORIZED() and the permissions of actions.\n\nReturns: `Array|Object`\n\nAn array of names or an object with names as keys. `user.roles` is used when `permissions` is missing.\n\nExample: Accept with roles\n```js\n$.success({ id: '1', name: 'Anna', roles: ['orders', 'products'] });\n```\n\n### user.sa\n\nType: `property`\n\nMarks a super admin.\n\nReturns: `Boolean`\n\nA user with `sa` or `su` passes `UNAUTHORIZED()`, action `permissions` and is the only user allowed by actions with `sa: true`.\n\nExample: Admin\n```js\n$.success({ id: '1', name: 'Root', sa: true });\n```\n\n### new User([obj])\n\nType: `class`\n\nA class for user objects.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | The keys of the user. |\n\nReturns: `User`\n\nA global class. The constructor copies every key of `obj` to the new instance, so `new User({ id: '1', sa: true })` has `id` and `sa`. Use it for the identity of code that is not a request, such as a job or a script, and check it with `instanceof User`. The framework does not change the users that your `AUTH()` delegate returns into `User` instances.\n\nExample: A user for a job\n```js\nNEWACTION('reports_daily', {\n\tsa: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n\nvar scheduler = new User({ id: 'cron', name: 'Scheduler', sa: true });\nACTION('reports_daily').user(scheduler).callback(console.log);\n// { success: true, value: 'Scheduler' }\n```\n\n### NEWACTION({ user: true })\n\nType: `config`\n\nLimits an action to authorized (true) or unauthorized (false) requests.\n\nWhen the condition fails, the action responds with `401`.\n\nExample: Only users\n```js\nNEWACTION({\n\tid: 'Account/profile',\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### NEWACTION({ sa: true })\n\nType: `config`\n\nLimits an action to super admins.\n\nThe user must have `sa` or `su`, otherwise the action responds with `401`. `su: true` works the same.\n\nExample: Admin action\n```js\nNEWACTION({\n\tid: 'Users/remove',\n\tsa: true,\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### NEWACTION({ permissions: 'name1,name2' })\n\nType: `config`\n\nLimits an action to users with any of the permissions.\n\nA string separated by commas or semicolons, or an array. The check is `UNAUTHORIZED()`, so super admins always pass.\n\nExample: Permissions\n```js\nNEWACTION({\n\tid: 'Orders/list',\n\tpermissions: 'orders,admin',\n\taction: function($) {\n\t\t$.success([]);\n\t}\n});\n```\n\n### BLOCKED($, [limit], [expire])\n\nType: `method`\n\nCounts attempts per IP address and tells when the address is blocked.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action or a controller. |\n| `limit` | `Number|null` | no | `5` | Allowed attempts; `null` or `-1` resets the counter. |\n| `expire` | `String` | no | `'15 minutes'` | How long the counter lives. |\n\nReturns: `Boolean` `true` when blocked.\n\nEach call counts one attempt for `$.ip`. It returns `true` when the address was counted more than `limit` times. The counter starts with the first call and is removed after `expire` (checked every minute). `BLOCKED($, null)` or `BLOCKED($, -1)` removes it at once.\n\nExample: Login guard\n```js\nif (BLOCKED($, 10)) {\n\t$.invalid(401);\n\treturn;\n}\n// ... the password is correct\nBLOCKED($, null);\n```\n","entries":[{"type":"delegate","name":"AUTH(callback)","signature":"AUTH(callback)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"opt.onread","signature":"opt.onread = function(meta, callback, $)","since":"","deprecated":false},{"type":"delegate","name":"opt.onsession","signature":"opt.onsession = function(session, $, [isnew])","since":"","deprecated":false},{"type":"delegate","name":"opt.onauthorize","signature":"opt.onauthorize = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.onfree","signature":"opt.onfree = function(meta)","since":"","deprecated":false},{"type":"delegate","name":"opt.onlogout","signature":"opt.onlogout = function(session)","since":"","deprecated":false},{"type":"delegate","name":"opt.onddos","signature":"opt.onddos = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.localize","signature":"opt.localize = function(user, controller)","since":"","deprecated":false},{"type":"method","name":"opt.authcookie($, sessionid, userid, [expire], [options])","signature":"opt.authcookie($, sessionid, userid, [expire], [options])","since":"","deprecated":false},{"type":"method","name":"opt.sign(sessionid, userid)","signature":"opt.sign(sessionid, userid)","since":"","deprecated":false},{"type":"method","name":"opt.logout($)","signature":"opt.logout($)","since":"","deprecated":false},{"type":"method","name":"opt.update(userid, fn)","signature":"opt.update(userid, fn)","since":"","deprecated":false},{"type":"method","name":"opt.refresh(userid, [exceptsessionid])","signature":"opt.refresh(userid, [exceptsessionid])","since":"","deprecated":false},{"type":"property","name":"opt.sessions","signature":"opt.sessions","since":"","deprecated":false},{"type":"property","name":"DEF.onAuthorize","signature":"DEF.onAuthorize","since":"","deprecated":false},{"type":"type","name":"Route flag +","signature":"ROUTE('+METHOD /url/ ...')","since":"","deprecated":false},{"type":"type","name":"Route flag -","signature":"ROUTE('-METHOD /url/ ...')","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"method","name":"controller.authorize([callback])","signature":"controller.authorize([callback])","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED($, [permission...])","signature":"UNAUTHORIZED($, [permission1], [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized([permission...])","signature":"$.unauthorized([permission1], [permission2], [...])","since":"","deprecated":false},{"type":"property","name":"user.permissions","signature":"user.permissions","since":"","deprecated":false},{"type":"property","name":"user.sa","signature":"user.sa","since":"","deprecated":false},{"type":"class","name":"User","signature":"new User([obj])","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ user })","signature":"NEWACTION({ user: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ sa })","signature":"NEWACTION({ sa: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ permissions })","signature":"NEWACTION({ permissions: 'name1,name2' })","since":"","deprecated":false},{"type":"method","name":"BLOCKED($, [limit], [expire])","signature":"BLOCKED($, [limit], [expire])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwWIIEx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/authorization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Autorisierung","summary":"AUTH(), Route-Flags, Berechtigungen, Sessions und BLOCKED().","markdown":"---\ntitle: Autorisierung\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/authorization/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Autorisierung\n\n> AUTH(), Route-Flags, Berechtigungen, Sessions und BLOCKED().\n\nAlles, was den Benutzer eines Requests festlegt und prüft: der `AUTH()`-Delegate und seine eingebauten Sessions, die Route-Flags `+` und `-`, `UNAUTHORIZED()` und Berechtigungen von Aktionen sowie `BLOCKED()`. Die Anleitung [Autorisierung](../../guides/authorization/) erklärt mit Beispielen, wie sie zusammenspielen.\n\nVerschlüsselung und Audit-Logs haben eigene Seiten: [Verschlüsselung](../encryption/) und [Audit-Logs](../audit-logs/).\n\n## API\n\n### AUTH(callback)\n\nType: `delegate`\n\nRegistriert den Autorisierungs-Delegate, der festlegt, wer der Benutzer eines Requests ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)`; rufe `$.success(user)` oder `$.invalid()` auf. |\n\nReturns: `undefined`\n\nDer Delegate läuft für jeden HTTP-Request und jede WebSocket-Verbindung, die zu einer Route passt, nachdem der Body geparst wurde und vor der Aktion der Route. `$` hat `headers`, `query`, `body`, `ip`, `ua`, `url`, `cookie(name)`, `controller` und bei WebSocket `iswebsocket: true`. Rufe `$.success(user)` auf, um den Request zu autorisieren, oder `$.invalid()`, um ihn abzulehnen; der Delegate kann asynchron sein. Ein zweiter Aufruf ersetzt den Delegate. `F.auth()` ist dieselbe Funktion.\n\nExample: Token in einem Header\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\tDATA.read('tbl_user').where('token', token).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\n### AUTH(options)\n\nType: `method`\n\nInstalliert das eingebaute Cookie-Session-System.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.secret` | `String` | yes |  | Das Secret, das die Session-Tokens signiert. |\n| `options.cookie` | `String` | no |  | Der Name des Session-Cookies. |\n| `options.header` | `String` | no |  | Ein Header-Name in Kleinbuchstaben, aus dem das Token gelesen wird, wenn es kein Cookie gibt. |\n| `options.options` | `Object` | no |  | Cookie-Optionen, die von `authcookie()` und beim Entfernen des Cookies verwendet werden (`httponly`, `security`, `domain`...). |\n| `options.expire` | `String` | no | `'5 minutes'` | Wie lange geladene Benutzerdaten im Speicher bleiben. |\n| `options.cleaner` | `Number` | no | `5` | Wie oft, in Minuten, abgelaufene Sessions entfernt werden. |\n| `options.strict` | `Boolean` | no | `true` | Eine gecachte Session ist nur für denselben User-Agent gültig. |\n| `options.ddos` | `Number` | no |  | Wie viele ungültige Tokens eine IP-Adresse senden darf, bevor sie bis zur nächsten Bereinigung abgewiesen wird. |\n| `options.onread` | `Function` | yes |  | `function(meta, callback, $)` lädt den Benutzer; siehe `opt.onread`. |\n\nReturns: `undefined`\n\nMit einem Objekt macht `AUTH()` daraus einen Session-Manager und registriert seine Funktion `auth` als Delegate. Das Objekt erhält die Methoden `authcookie()`, `sign()`, `logout()`, `update()`, `refresh()` und die im Speicher gehaltenen `sessions`, also behalte eine Referenz darauf (zum Beispiel in `MAIN`). Das Token wird aus dem Cookie `cookie` gelesen oder aus dem Header `header`. Seine Signatur wird mit `secret` geprüft, die Session wird aus dem Speicher genommen, und `onread()` wird aufgerufen, wenn sie dort nicht ist.\n\nExample: Session einrichten\n```js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').id(meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.session = opt;\n```\n\n### opt.onread = function(meta, callback, $)\n\nType: `delegate`\n\nLädt den Benutzer einer Session, die nicht im Speicher ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `callback` | `Function` | yes |  | `function(err, data)`. |\n| `$` | `Object` | yes |  | Die Optionen des Requests. |\n\n`meta` ist `{ sessionid, userid, ip, ua }` aus dem geprüften Token. Rufe `callback(err, data)` auf; `data` wird zum Benutzer und für `expire` gecacht. Ein Fehler oder leere `data` lehnt den Request ab und entfernt das Cookie. Parallele Requests mit derselben Session warten auf das erste `onread()`.\n\nExample: Aus der Datenbank lesen\n```js\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n```\n\n### opt.onsession = function(session, $, [isnew])\n\nType: `delegate`\n\nLäuft für jeden autorisierten Request, bevor der Benutzer akzeptiert wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | Die Session. |\n| `$` | `Object` | yes |  | Die Optionen des Requests. |\n| `isnew` | `Boolean` | no |  | `true`, wenn die Daten gerade gelesen wurden. |\n\nReturns: `Boolean` `true`, um den Standarderfolg zu unterbinden.\n\n`session` ist `{ sessionid, userid, data, ua, expire }`; `isnew` ist direkt nach `onread()` gleich `true`. Gib `true` zurück, um selbst zu übernehmen: Das Framework ruft `$.success()` nicht auf, also rufst du `$.success()` oder `$.invalid()` selbst auf.\n\nExample: Requests zählen\n```js\nopt.onsession = function(session, $) {\n\tsession.data.requests = (session.data.requests || 0) + 1;\n};\n```\n\n### opt.onauthorize = function($)\n\nType: `delegate`\n\nLäuft als Erstes im Session-Delegate; gib true zurück, um den Request selbst zu behandeln.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Die Optionen des Requests. |\n\nReturns: `Boolean` `true`, um die Session-Prüfung zu überspringen.\n\nVerwende es, um andere Zugangsdaten zu akzeptieren (zum Beispiel einen API-Schlüssel), bevor das Cookie gelesen wird. Wenn es `true` zurückgibt, musst du `$.success()` oder `$.invalid()` aufrufen.\n\nExample: API-Schlüssel\n```js\nopt.onauthorize = function($) {\n\tif ($.headers['x-apikey'] === CONF.apikey) {\n\t\t$.success({ id: 'api', sa: true });\n\t\treturn true;\n\t}\n};\n```\n\n### opt.onfree = function(meta)\n\nType: `delegate`\n\nLäuft, nachdem abgelaufene Sessions aus dem Speicher entfernt wurden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessions: Array, users: Array }`. |\n\n`meta.sessions` ist ein Array der entfernten Session-IDs, `meta.users` die IDs der Benutzer, die keine aktive Session mehr haben.\n\nExample: Protokollieren\n```js\nopt.onfree = function(meta) {\n\tconsole.log('Released', meta.sessions.length, 'sessions');\n};\n```\n\n### opt.onlogout = function(session)\n\nType: `delegate`\n\nLäuft, wenn logout() eine Session aus dem Speicher entfernt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | Die entfernte Session. |\n\nErhält das entfernte Session-Objekt `{ sessionid, userid, data, ua, expire }`. Ist die Session nicht im Speicher, wird stattdessen `opt.onremove(sessionid)` aufgerufen.\n\nExample: Die Zeit speichern\n```js\nopt.onlogout = function(session) {\n\tDATA.modify('tbl_user', { dtlogout: NOW }).id(session.userid);\n};\n```\n\n### opt.onddos = function($)\n\nType: `delegate`\n\nLäuft, wenn eine IP-Adresse das ddos-Limit für ungültige Tokens überschritten hat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Die Optionen des Requests. |\n\nDer Request wird direkt nach diesem Aufruf abgelehnt. Die Zähler werden alle `cleaner` Minuten zurückgesetzt.\n\nExample: Protokollieren\n```js\nopt.ddos = 10;\nopt.onddos = function($) {\n\tconsole.warn('Too many invalid tokens from', $.ip);\n};\n```\n\n### opt.localize = function(user, controller)\n\nType: `delegate`\n\nGibt die Sprache des Requests aus den Benutzerdaten zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Die Benutzerdaten oder `null`. |\n| `controller` | `Controller` | yes |  | Der Controller. |\n\nReturns: `String` Ein Sprachcode.\n\nWird mit den Benutzerdaten aufgerufen oder mit `null`, wenn die Anfrage kein Token hat oder die gecachte Session zu einem anderen User-Agent gehört; der zurückgegebene Wert wird zu `controller.language`. `opt.locale` wird als dieselbe Option akzeptiert.\n\nExample: Sprache des Benutzers\n```js\nopt.localize = function(user, ctrl) {\n\treturn user ? user.language : (ctrl.headers['accept-language'] || '').substring(0, 2);\n};\n```\n\n### opt.authcookie($, sessionid, userid, [expire], [options])\n\nType: `method`\n\nSigniert ein Token und setzt das Session-Cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$` einer Aktion oder eines Controllers. |\n| `sessionid` | `String` | yes |  | Eine neue eindeutige ID, zum Beispiel `UID()`. |\n| `userid` | `String` | yes |  | Die Benutzer-ID, die später an `onread()` übergeben wird. |\n| `expire` | `String|Date` | no |  | Das Ablaufdatum des Cookies, zum Beispiel `'1 month'`. |\n| `options` | `Object` | no |  | Cookie-Optionen. |\n\nReturns: `String` Das Token.\n\nRufe sie nach einem erfolgreichen Login auf. Sie erstellt das Token mit `sign()` und schreibt das Cookie `opt.cookie` mit `options` (Standard `opt.options`). Die Session selbst wird beim nächsten Request über `onread()` erstellt.\n\nExample: Login\n```js\nMAIN.session.authcookie($, UID(), user.id, '1 month');\n$.success();\n```\n\n### opt.sign(sessionid, userid)\n\nType: `method`\n\nErstellt ein signiertes Session-Token, ohne ein Cookie zu setzen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Eine eindeutige Session-ID. |\n| `userid` | `String` | yes |  | Die Benutzer-ID. |\n\nReturns: `String` Das Token.\n\nVerwende sie für Clients, die das Token im Header aus der Option `header` statt in einem Cookie senden.\n\nExample: Token für eine mobile App\n```js\nopt.header = 'x-token';\n// in the login action\n$.success(MAIN.session.sign(UID(), user.id));\n```\n\n### opt.logout($)\n\nType: `method`\n\nEntfernt die Session des Requests und ihr Cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object|String` | yes |  | Der Request oder eine Session-ID. |\n\nReturns: `Boolean` `true`, wenn eine Session entfernt wurde.\n\n`$` ist das `$` einer Aktion: Die Session im Speicher und das Cookie werden entfernt. Mit einem Controller oder einem Session-ID-String wird nur die Session im Speicher entfernt; das Cookie bleibt, und die nächste Anfrage liest den Benutzer erneut. Gibt `true` zurück, wenn die Session im Speicher war.\n\nExample: Logout-Aktion\n```js\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n### opt.update(userid, fn)\n\nType: `method`\n\nÄndert die gecachten Daten jeder Session eines Benutzers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | Die Benutzer-ID. |\n| `fn` | `Function` | yes |  | `function(data, session)`. |\n\nReturns: `Number` Wie viele Sessions aktualisiert wurden.\n\nRuft `fn(data, session)` für jede Session von `userid` im Speicher auf.\n\nExample: Umbenennen\n```js\nMAIN.session.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### opt.refresh(userid, [exceptsessionid])\n\nType: `method`\n\nVerwirft die gecachten Sessions eines Benutzers, sodass der nächste Request den Benutzer erneut liest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | Die Benutzer-ID. |\n| `exceptsessionid` | `String` | no |  | Eine Session, die behalten wird. |\n\nReturns: `Number` Wie viele Sessions verworfen wurden.\n\nDie Cookies bleiben gültig; `onread()` lädt beim nächsten Request frische Daten. Übergib `exceptsessionid`, um eine Session im Speicher zu behalten.\n\nExample: Nach einer Änderung der Berechtigungen\n```js\nMAIN.session.refresh(model.userid);\n```\n\n### opt.sessions\n\nType: `property`\n\nDie Sessions im Speicher, nach Session-ID.\n\nReturns: `Object`\n\nJedes Element ist `{ sessionid, userid, data, ua, expire }`.\n\nExample: Online-Benutzer\n```js\nvar count = Object.keys(MAIN.session.sessions).length;\n```\n\n### DEF.onAuthorize\n\nType: `property`\n\nDer registrierte Autorisierungs-Delegate.\n\nReturns: `Function`\n\n`AUTH()` setzt es. Ist es leer, wird `$.user` nie gesetzt, und die Flags `+` und `-` der Routen werden nicht geprüft, sodass `+`-Routen für alle offen sind.\n\nExample: Prüfung\n```js\nif (!DEF.onAuthorize)\n\tconsole.warn('No AUTH() delegate');\n```\n\n### ROUTE('+METHOD /url/ ...')\n\nType: `type`\n\nDie Route ist nur für autorisierte Requests.\n\nDas Flag steht vor der Methode. Lehnt der Delegate den Request ab, sucht das Framework eine andere passende Route mit derselben URL (eine `-`-Route oder eine ohne Flag); gibt es keine, erhält ein HTTP-Request `401` und eine WebSocket-Verbindung wird beim Handshake abgelehnt, sodass ein Browser-Client den Schließcode `1006` erhält. Bei `API`-Routen wird das Flag der Zeile für jeden Endpunkt geprüft.\n\nExample: Admin-Bereich\n```js\nROUTE('+GET /admin/', dashboard);\nROUTE('+API /api/ orders_list --> Orders/list');\nROUTE('+SOCKET /chat/', chat);\n```\n\n### ROUTE('-METHOD /url/ ...')\n\nType: `type`\n\nDie Route ist nur für nicht autorisierte Requests.\n\nTypisch für Login- und Registrierungsseiten. Mit einer `+`-Route auf derselben URL bedienst du Besucher und Benutzer unterschiedlich.\n\nExample: Dieselbe URL für beide\n```js\nROUTE('+GET /', 'app');\nROUTE('-GET /', 'login');\n```\n\n### controller.user\n\nType: `property`\n\nDer vom AUTH()-Delegate akzeptierte Benutzer.\n\nReturns: `Object`\n\n`undefined`, wenn der Request nicht autorisiert ist. Er wird für jede Route gesetzt, wenn ein Delegate existiert, auch für Routen ohne Flag, und an Aktionen als `$.user` übergeben.\n\nExample: Auslesen\n```js\nfunction dashboard($) {\n\t$.json({ name: $.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nDer Benutzer des Requests innerhalb einer Aktion.\n\nReturns: `Object`\n\nWird vom Controller übernommen, der die Aktion aufgerufen hat, oder von `ACTION().user(obj)`, wenn du eine Aktion aus dem Code aufrufst.\n\nExample: Filter nach Besitzer\n```js\naction: function($) {\n\tDATA.find('tbl_order').where('userid', $.user.id).callback($);\n}\n```\n\n### controller.authorize([callback])\n\nType: `method`\n\nFührt den AUTH()-Delegate bei Bedarf aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, user)`. |\n\nReturns: `Promise` Wenn `callback` nicht angegeben ist.\n\nSetzt `controller.user`, wenn der Delegate den Request akzeptiert. Ohne `callback` gibt sie ein `Promise` zurück, das mit dem Benutzer oder `undefined` auflöst; es wird nie abgelehnt.\n\nExample: Innerhalb einer Route\n```js\nasync function detail($) {\n\tvar user = await $.authorize();\n\t$.json({ logged: !!user });\n}\n```\n\n### controller.session\n\nType: `property`\n\nDie eingebaute Session des Requests.\n\nReturns: `Object`\n\nWird von `AUTH(options)` gesetzt: `{ sessionid, userid, data, ua, expire }`. `controller.sessionid` enthält die Session-ID, und `$.sessionid` liest sie in Aktionen.\n\nExample: Session-ID\n```js\nfunction info($) {\n\t$.json({ sessionid: $.sessionid });\n}\n```\n\n### UNAUTHORIZED($, [permission1], [permission2], [...])\n\nType: `method`\n\nPrüft die Berechtigungen des Benutzers und antwortet mit 401, wenn sie fehlen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$` einer Aktion oder eines Controllers. |\n| `permission` | `String` | no |  | Ein oder mehrere Berechtigungsnamen; einer davon genügt. |\n\nReturns: `Boolean` `true`, wenn der Benutzer keine Berechtigung hat und der Request beantwortet wurde.\n\nGibt `false` zurück, wenn der Benutzer `sa` oder `su` hat oder eine der Berechtigungen in `user.permissions` (oder `user.roles`), was ein Array oder ein Objekt sein kann. Andernfalls ruft sie `$.invalid(401)` auf und gibt `true` zurück. Ohne Benutzer gibt sie immer `true` zurück. `F.unauthorized()` ist dieselbe Funktion.\n\nExample: Eine Aktion absichern\n```js\naction: function($) {\n\tif (UNAUTHORIZED($, 'orders'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.unauthorized([permission1], [permission2], [...])\n\nType: `method`\n\nUNAUTHORIZED() für das aktuelle $.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | no |  | Ein oder mehrere Berechtigungsnamen. |\n\nReturns: `Boolean` `true`, wenn der Benutzer keine Berechtigung hat.\n\nDieselbe Prüfung, wobei `$` von der Aktion übernommen wird.\n\nExample: Kurzform\n```js\nif ($.unauthorized('orders'))\n\treturn;\n```\n\n### user.permissions\n\nType: `property`\n\nDie Berechtigungen des Benutzers, gelesen von UNAUTHORIZED() und den Berechtigungen von Aktionen.\n\nReturns: `Array|Object`\n\nEin Array von Namen oder ein Objekt mit Namen als Schlüsseln. `user.roles` wird verwendet, wenn `permissions` fehlt.\n\nExample: Mit Rollen akzeptieren\n```js\n$.success({ id: '1', name: 'Anna', roles: ['orders', 'products'] });\n```\n\n### user.sa\n\nType: `property`\n\nKennzeichnet einen Super-Admin.\n\nReturns: `Boolean`\n\nEin Benutzer mit `sa` oder `su` besteht `UNAUTHORIZED()` und die `permissions` von Aktionen und ist der einzige Benutzer, den Aktionen mit `sa: true` zulassen.\n\nExample: Admin\n```js\n$.success({ id: '1', name: 'Root', sa: true });\n```\n\n### new User([obj])\n\nType: `class`\n\nEine Klasse für Benutzerobjekte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Die Schlüssel des Benutzers. |\n\nReturns: `User`\n\nEine globale Klasse. Der Konstruktor kopiert jeden Schlüssel von `obj` in die neue Instanz, daher hat `new User({ id: '1', sa: true })` die Schlüssel `id` und `sa`. Verwende sie für die Identität von Code, der keine Anfrage ist, etwa einem Job oder einem Skript, und prüfe sie mit `instanceof User`. Das Framework macht aus den Benutzern, die dein `AUTH()`-Delegate zurückgibt, keine `User`-Instanzen.\n\nExample: Ein Benutzer für einen Job\n```js\nNEWACTION('reports_daily', {\n\tsa: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n\nvar scheduler = new User({ id: 'cron', name: 'Scheduler', sa: true });\nACTION('reports_daily').user(scheduler).callback(console.log);\n// { success: true, value: 'Scheduler' }\n```\n\n### NEWACTION({ user: true })\n\nType: `config`\n\nBeschränkt eine Aktion auf autorisierte (true) oder nicht autorisierte (false) Requests.\n\nIst die Bedingung nicht erfüllt, antwortet die Aktion mit `401`.\n\nExample: Nur Benutzer\n```js\nNEWACTION({\n\tid: 'Account/profile',\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### NEWACTION({ sa: true })\n\nType: `config`\n\nBeschränkt eine Aktion auf Super-Admins.\n\nDer Benutzer muss `sa` oder `su` haben, sonst antwortet die Aktion mit `401`. `su: true` funktioniert genauso.\n\nExample: Admin-Aktion\n```js\nNEWACTION({\n\tid: 'Users/remove',\n\tsa: true,\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### NEWACTION({ permissions: 'name1,name2' })\n\nType: `config`\n\nBeschränkt eine Aktion auf Benutzer mit einer der Berechtigungen.\n\nEin durch Kommas oder Semikolons getrennter String oder ein Array. Die Prüfung ist `UNAUTHORIZED()`, daher kommen Super-Admins immer durch.\n\nExample: Berechtigungen\n```js\nNEWACTION({\n\tid: 'Orders/list',\n\tpermissions: 'orders,admin',\n\taction: function($) {\n\t\t$.success([]);\n\t}\n});\n```\n\n### BLOCKED($, [limit], [expire])\n\nType: `method`\n\nZählt Versuche pro IP-Adresse und meldet, wann die Adresse blockiert ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$` einer Aktion oder eines Controllers. |\n| `limit` | `Number|null` | no | `5` | Erlaubte Versuche; `null` oder `-1` setzt den Zähler zurück. |\n| `expire` | `String` | no | `'15 minutes'` | Wie lange der Zähler besteht. |\n\nReturns: `Boolean` `true`, wenn blockiert.\n\nJeder Aufruf zählt einen Versuch für `$.ip`. Sie gibt `true` zurück, wenn die Adresse mehr als `limit`-mal gezählt wurde. Der Zähler startet mit dem ersten Aufruf und wird nach `expire` entfernt (jede Minute geprüft). `BLOCKED($, null)` oder `BLOCKED($, -1)` entfernt ihn sofort.\n\nExample: Login absichern\n```js\nif (BLOCKED($, 10)) {\n\t$.invalid(401);\n\treturn;\n}\n// ... the password is correct\nBLOCKED($, null);\n```\n","entries":[{"type":"delegate","name":"AUTH(callback)","signature":"AUTH(callback)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"opt.onread","signature":"opt.onread = function(meta, callback, $)","since":"","deprecated":false},{"type":"delegate","name":"opt.onsession","signature":"opt.onsession = function(session, $, [isnew])","since":"","deprecated":false},{"type":"delegate","name":"opt.onauthorize","signature":"opt.onauthorize = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.onfree","signature":"opt.onfree = function(meta)","since":"","deprecated":false},{"type":"delegate","name":"opt.onlogout","signature":"opt.onlogout = function(session)","since":"","deprecated":false},{"type":"delegate","name":"opt.onddos","signature":"opt.onddos = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.localize","signature":"opt.localize = function(user, controller)","since":"","deprecated":false},{"type":"method","name":"opt.authcookie($, sessionid, userid, [expire], [options])","signature":"opt.authcookie($, sessionid, userid, [expire], [options])","since":"","deprecated":false},{"type":"method","name":"opt.sign(sessionid, userid)","signature":"opt.sign(sessionid, userid)","since":"","deprecated":false},{"type":"method","name":"opt.logout($)","signature":"opt.logout($)","since":"","deprecated":false},{"type":"method","name":"opt.update(userid, fn)","signature":"opt.update(userid, fn)","since":"","deprecated":false},{"type":"method","name":"opt.refresh(userid, [exceptsessionid])","signature":"opt.refresh(userid, [exceptsessionid])","since":"","deprecated":false},{"type":"property","name":"opt.sessions","signature":"opt.sessions","since":"","deprecated":false},{"type":"property","name":"DEF.onAuthorize","signature":"DEF.onAuthorize","since":"","deprecated":false},{"type":"type","name":"Route flag +","signature":"ROUTE('+METHOD /url/ ...')","since":"","deprecated":false},{"type":"type","name":"Route flag -","signature":"ROUTE('-METHOD /url/ ...')","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"method","name":"controller.authorize([callback])","signature":"controller.authorize([callback])","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED($, [permission...])","signature":"UNAUTHORIZED($, [permission1], [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized([permission...])","signature":"$.unauthorized([permission1], [permission2], [...])","since":"","deprecated":false},{"type":"property","name":"user.permissions","signature":"user.permissions","since":"","deprecated":false},{"type":"property","name":"user.sa","signature":"user.sa","since":"","deprecated":false},{"type":"class","name":"User","signature":"new User([obj])","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ user })","signature":"NEWACTION({ user: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ sa })","signature":"NEWACTION({ sa: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ permissions })","signature":"NEWACTION({ permissions: 'name1,name2' })","since":"","deprecated":false},{"type":"method","name":"BLOCKED($, [limit], [expire])","signature":"BLOCKED($, [limit], [expire])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwWIIEx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/authorization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Autorización","summary":"AUTH(), flags de ruta, permisos, sesiones y BLOCKED().","markdown":"---\ntitle: \"Autorización\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/authorization/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Autorización\n\n> AUTH(), flags de ruta, permisos, sesiones y BLOCKED().\n\nTodo lo que decide y comprueba el usuario de una petición: el delegado `AUTH()` y sus sesiones integradas, los flags de ruta `+` y `-`, `UNAUTHORIZED()` y los permisos de las acciones, y `BLOCKED()`. La guía [Autorización](../../guides/authorization/) explica cómo funcionan juntos, con ejemplos.\n\nEl cifrado y los registros de auditoría tienen sus propias páginas: [Cifrado](../encryption/) y [Registros de auditoría](../audit-logs/).\n\n## API\n\n### AUTH(callback)\n\nType: `delegate`\n\nRegistra el delegado de autorización que decide quién es el usuario de una petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)`; llama a `$.success(user)` o a `$.invalid()`. |\n\nReturns: `undefined`\n\nEl delegado se ejecuta para cada petición HTTP y cada conexión WebSocket que coincide con una ruta, después de analizar el cuerpo y antes de la acción de la ruta. `$` tiene `headers`, `query`, `body`, `ip`, `ua`, `url`, `cookie(name)`, `controller` y, para WebSocket, `iswebsocket: true`. Llama a `$.success(user)` para autorizar la petición o a `$.invalid()` para rechazarla; el delegado puede ser asíncrono. Una segunda llamada reemplaza el delegado. `F.auth()` es la misma función.\n\nExample: Token en una cabecera\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\tDATA.read('tbl_user').where('token', token).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\n### AUTH(options)\n\nType: `method`\n\nInstala el sistema integrado de sesiones basado en cookies.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.secret` | `String` | yes |  | El secreto que firma los tokens de sesión. |\n| `options.cookie` | `String` | no |  | El nombre de la cookie de sesión. |\n| `options.header` | `String` | no |  | Un nombre de cabecera en minúsculas del que se lee el token cuando no hay cookie. |\n| `options.options` | `Object` | no |  | Opciones de la cookie que usa `authcookie()` y que se usan al eliminar la cookie (`httponly`, `security`, `domain`...). |\n| `options.expire` | `String` | no | `'5 minutes'` | Cuánto tiempo permanecen en memoria los datos de usuario cargados. |\n| `options.cleaner` | `Number` | no | `5` | Cada cuánto, en minutos, se eliminan las sesiones caducadas. |\n| `options.strict` | `Boolean` | no | `true` | Una sesión en caché solo es válida para el mismo user agent. |\n| `options.ddos` | `Number` | no |  | Cuántos tokens no válidos puede enviar una dirección IP antes de ser rechazada hasta la siguiente limpieza. |\n| `options.onread` | `Function` | yes |  | `function(meta, callback, $)` carga el usuario; consulta `opt.onread`. |\n\nReturns: `undefined`\n\nCon un objeto, `AUTH()` lo convierte en un gestor de sesiones y registra su función `auth` como delegado. El objeto recibe los métodos `authcookie()`, `sign()`, `logout()`, `update()`, `refresh()` y las `sessions` en memoria, así que guarda una referencia a él (por ejemplo en `MAIN`). El token se lee de la cookie `cookie`, o de la cabecera `header`. Su firma se comprueba con `secret`, la sesión se toma de la memoria y se llama a `onread()` cuando no está ahí.\n\nExample: Configuración de las sesiones\n```js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').id(meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.session = opt;\n```\n\n### opt.onread = function(meta, callback, $)\n\nType: `delegate`\n\nCarga el usuario de una sesión que no está en memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `callback` | `Function` | yes |  | `function(err, data)`. |\n| `$` | `Object` | yes |  | Las opciones de la petición. |\n\n`meta` es `{ sessionid, userid, ip, ua }` del token verificado. Llama a `callback(err, data)`; `data` pasa a ser el usuario y se guarda en caché durante `expire`. Un error o un `data` vacío rechaza la petición y elimina la cookie. Las peticiones paralelas con la misma sesión esperan al primer `onread()`.\n\nExample: Leer de la base de datos\n```js\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n```\n\n### opt.onsession = function(session, $, [isnew])\n\nType: `delegate`\n\nSe ejecuta para cada petición autorizada antes de aceptar al usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | La sesión. |\n| `$` | `Object` | yes |  | Las opciones de la petición. |\n| `isnew` | `Boolean` | no |  | `true` cuando los datos se acaban de leer. |\n\nReturns: `Boolean` `true` para detener el éxito por defecto.\n\n`session` es `{ sessionid, userid, data, ua, expire }`; `isnew` es `true` justo después de `onread()`. Devuelve `true` para tomar el control: el framework no llama a `$.success()`, así que llamas tú a `$.success()` o a `$.invalid()`.\n\nExample: Contar peticiones\n```js\nopt.onsession = function(session, $) {\n\tsession.data.requests = (session.data.requests || 0) + 1;\n};\n```\n\n### opt.onauthorize = function($)\n\nType: `delegate`\n\nSe ejecuta primero en el delegado de sesiones; devuelve true para gestionar la petición tú mismo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Las opciones de la petición. |\n\nReturns: `Boolean` `true` para omitir la comprobación de la sesión.\n\nÚsalo para aceptar otras credenciales (una clave de API, por ejemplo) antes de leer la cookie. Cuando devuelve `true` debes llamar a `$.success()` o a `$.invalid()`.\n\nExample: Clave de API\n```js\nopt.onauthorize = function($) {\n\tif ($.headers['x-apikey'] === CONF.apikey) {\n\t\t$.success({ id: 'api', sa: true });\n\t\treturn true;\n\t}\n};\n```\n\n### opt.onfree = function(meta)\n\nType: `delegate`\n\nSe ejecuta después de eliminar de la memoria las sesiones caducadas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessions: Array, users: Array }`. |\n\n`meta.sessions` es un array con los ID de las sesiones eliminadas y `meta.users` los ID de los usuarios que ya no tienen ninguna sesión activa.\n\nExample: Registrarlo en el log\n```js\nopt.onfree = function(meta) {\n\tconsole.log('Released', meta.sessions.length, 'sessions');\n};\n```\n\n### opt.onlogout = function(session)\n\nType: `delegate`\n\nSe ejecuta cuando logout() elimina una sesión de la memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | La sesión eliminada. |\n\nRecibe el objeto de la sesión eliminada `{ sessionid, userid, data, ua, expire }`. Cuando la sesión no está en memoria, se llama en su lugar a `opt.onremove(sessionid)`.\n\nExample: Guardar la hora\n```js\nopt.onlogout = function(session) {\n\tDATA.modify('tbl_user', { dtlogout: NOW }).id(session.userid);\n};\n```\n\n### opt.onddos = function($)\n\nType: `delegate`\n\nSe ejecuta cuando una dirección IP supera el límite ddos de tokens no válidos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Las opciones de la petición. |\n\nLa petición se rechaza justo después de esta llamada. Los contadores se borran cada `cleaner` minutos.\n\nExample: Registrarlo en el log\n```js\nopt.ddos = 10;\nopt.onddos = function($) {\n\tconsole.warn('Too many invalid tokens from', $.ip);\n};\n```\n\n### opt.localize = function(user, controller)\n\nType: `delegate`\n\nDevuelve el idioma de la petición a partir de los datos del usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Los datos del usuario o `null`. |\n| `controller` | `Controller` | yes |  | El controlador. |\n\nReturns: `String` Un código de idioma.\n\nSe llama con los datos del usuario, o con `null` cuando la petición no tiene token o la sesión en caché pertenece a otro user agent; el valor devuelto se convierte en `controller.language`. `opt.locale` se acepta como la misma opción.\n\nExample: Idioma del usuario\n```js\nopt.localize = function(user, ctrl) {\n\treturn user ? user.language : (ctrl.headers['accept-language'] || '').substring(0, 2);\n};\n```\n\n### opt.authcookie($, sessionid, userid, [expire], [options])\n\nType: `method`\n\nFirma un token y establece la cookie de sesión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción o de un controlador. |\n| `sessionid` | `String` | yes |  | Un nuevo ID único, por ejemplo `UID()`. |\n| `userid` | `String` | yes |  | El ID de usuario que se pasa después a `onread()`. |\n| `expire` | `String|Date` | no |  | La caducidad de la cookie, por ejemplo `'1 month'`. |\n| `options` | `Object` | no |  | Opciones de la cookie. |\n\nReturns: `String` El token.\n\nLlámalo después de un inicio de sesión correcto. Crea el token con `sign()` y escribe la cookie `opt.cookie` con `options` (por defecto `opt.options`). La sesión en sí se crea en la siguiente petición a través de `onread()`.\n\nExample: Inicio de sesión\n```js\nMAIN.session.authcookie($, UID(), user.id, '1 month');\n$.success();\n```\n\n### opt.sign(sessionid, userid)\n\nType: `method`\n\nCrea un token de sesión firmado sin establecer una cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Un ID de sesión único. |\n| `userid` | `String` | yes |  | El ID de usuario. |\n\nReturns: `String` El token.\n\nÚsalo para clientes que envían el token en la opción `header` en lugar de en una cookie.\n\nExample: Token para una aplicación móvil\n```js\nopt.header = 'x-token';\n// in the login action\n$.success(MAIN.session.sign(UID(), user.id));\n```\n\n### opt.logout($)\n\nType: `method`\n\nElimina la sesión de la petición y su cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object|String` | yes |  | La petición o un ID de sesión. |\n\nReturns: `Boolean` `true` cuando se eliminó una sesión.\n\n`$` es el `$` de una acción: se eliminan la sesión en memoria y la cookie. Con un controlador o un string de ID de sesión solo se elimina la sesión en memoria; la cookie se queda y la siguiente petición vuelve a leer el usuario. Devuelve `true` cuando la sesión estaba en memoria.\n\nExample: Acción de cierre de sesión\n```js\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n### opt.update(userid, fn)\n\nType: `method`\n\nCambia los datos en caché de todas las sesiones de un usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | El ID de usuario. |\n| `fn` | `Function` | yes |  | `function(data, session)`. |\n\nReturns: `Number` Cuántas sesiones se actualizaron.\n\nLlama a `fn(data, session)` para cada sesión de `userid` en memoria.\n\nExample: Renombrar\n```js\nMAIN.session.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### opt.refresh(userid, [exceptsessionid])\n\nType: `method`\n\nDescarta las sesiones en caché de un usuario para que la siguiente petición vuelva a leer el usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | El ID de usuario. |\n| `exceptsessionid` | `String` | no |  | Una sesión que se conserva. |\n\nReturns: `Number` Cuántas sesiones se descartaron.\n\nLas cookies siguen siendo válidas; `onread()` carga datos nuevos en la siguiente petición. Pasa `exceptsessionid` para conservar una sesión en memoria.\n\nExample: Después de un cambio de permisos\n```js\nMAIN.session.refresh(model.userid);\n```\n\n### opt.sessions\n\nType: `property`\n\nLas sesiones en memoria, indexadas por ID de sesión.\n\nReturns: `Object`\n\nCada elemento es `{ sessionid, userid, data, ua, expire }`.\n\nExample: Usuarios conectados\n```js\nvar count = Object.keys(MAIN.session.sessions).length;\n```\n\n### DEF.onAuthorize\n\nType: `property`\n\nEl delegado de autorización registrado.\n\nReturns: `Function`\n\n`AUTH()` lo establece. Cuando está vacío, `$.user` nunca se establece y los flags `+` y `-` de las rutas no se comprueban, así que las rutas `+` están abiertas a todo el mundo.\n\nExample: Comprobar\n```js\nif (!DEF.onAuthorize)\n\tconsole.warn('No AUTH() delegate');\n```\n\n### ROUTE('+METHOD /url/ ...')\n\nType: `type`\n\nLa ruta es solo para peticiones autorizadas.\n\nEl flag va delante del método. Cuando el delegado rechaza la petición, el framework busca otra ruta con la misma URL que encaje (una ruta `-` o una sin flag); si no hay ninguna, una petición HTTP recibe `401` y una conexión WebSocket se rechaza durante el handshake, así que el cliente del navegador recibe el código de cierre `1006`. En las rutas `API`, el flag de la línea se comprueba para cada endpoint.\n\nExample: Zona de administración\n```js\nROUTE('+GET /admin/', dashboard);\nROUTE('+API /api/ orders_list --> Orders/list');\nROUTE('+SOCKET /chat/', chat);\n```\n\n### ROUTE('-METHOD /url/ ...')\n\nType: `type`\n\nLa ruta es solo para peticiones no autorizadas.\n\nTípico de las páginas de inicio de sesión y registro. Con una ruta `+` en la misma URL, atiendes de forma distinta a los visitantes y a los usuarios.\n\nExample: La misma URL para ambos\n```js\nROUTE('+GET /', 'app');\nROUTE('-GET /', 'login');\n```\n\n### controller.user\n\nType: `property`\n\nEl usuario aceptado por el delegado AUTH().\n\nReturns: `Object`\n\n`undefined` cuando la petición no está autorizada. Se establece en todas las rutas cuando existe un delegado, incluidas las rutas sin flag, y se pasa a las acciones como `$.user`.\n\nExample: Leerlo\n```js\nfunction dashboard($) {\n\t$.json({ name: $.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nEl usuario de la petición dentro de una acción.\n\nReturns: `Object`\n\nSe toma del controlador que llamó a la acción, o de `ACTION().user(obj)` cuando llamas a una acción desde el código.\n\nExample: Filtro por propietario\n```js\naction: function($) {\n\tDATA.find('tbl_order').where('userid', $.user.id).callback($);\n}\n```\n\n### controller.authorize([callback])\n\nType: `method`\n\nEjecuta el delegado AUTH() bajo demanda.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, user)`. |\n\nReturns: `Promise` Cuando no se pasa `callback`.\n\nEstablece `controller.user` cuando el delegado acepta la petición. Sin `callback` devuelve una `Promise` que se resuelve con el usuario o con `undefined`; nunca se rechaza.\n\nExample: Dentro de una ruta\n```js\nasync function detail($) {\n\tvar user = await $.authorize();\n\t$.json({ logged: !!user });\n}\n```\n\n### controller.session\n\nType: `property`\n\nLa sesión integrada de la petición.\n\nReturns: `Object`\n\nLa establece `AUTH(options)`: `{ sessionid, userid, data, ua, expire }`. `controller.sessionid` contiene el ID de sesión y `$.sessionid` lo lee en las acciones.\n\nExample: ID de sesión\n```js\nfunction info($) {\n\t$.json({ sessionid: $.sessionid });\n}\n```\n\n### UNAUTHORIZED($, [permission1], [permission2], [...])\n\nType: `method`\n\nComprueba los permisos del usuario y responde con 401 cuando faltan.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción o de un controlador. |\n| `permission` | `String` | no |  | Uno o varios nombres de permisos; basta con cualquiera de ellos. |\n\nReturns: `Boolean` `true` cuando el usuario no tiene permiso y ya se respondió a la petición.\n\nDevuelve `false` cuando el usuario tiene `sa` o `su`, o uno de los permisos de `user.permissions` (o `user.roles`), que puede ser un array o un objeto. En caso contrario, llama a `$.invalid(401)` y devuelve `true`. Sin usuario siempre devuelve `true`. `F.unauthorized()` es la misma función.\n\nExample: Proteger una acción\n```js\naction: function($) {\n\tif (UNAUTHORIZED($, 'orders'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.unauthorized([permission1], [permission2], [...])\n\nType: `method`\n\nUNAUTHORIZED() para el $ actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | no |  | Uno o varios nombres de permisos. |\n\nReturns: `Boolean` `true` cuando el usuario no tiene permiso.\n\nLa misma comprobación con el `$` tomado de la acción.\n\nExample: Forma abreviada\n```js\nif ($.unauthorized('orders'))\n\treturn;\n```\n\n### user.permissions\n\nType: `property`\n\nLos permisos del usuario, que leen UNAUTHORIZED() y los permisos de las acciones.\n\nReturns: `Array|Object`\n\nUn array de nombres o un objeto con los nombres como claves. Se usa `user.roles` cuando falta `permissions`.\n\nExample: Aceptar con roles\n```js\n$.success({ id: '1', name: 'Anna', roles: ['orders', 'products'] });\n```\n\n### user.sa\n\nType: `property`\n\nMarca a un superadministrador.\n\nReturns: `Boolean`\n\nUn usuario con `sa` o `su` pasa `UNAUTHORIZED()` y los `permissions` de las acciones, y es el único usuario permitido por las acciones con `sa: true`.\n\nExample: Administrador\n```js\n$.success({ id: '1', name: 'Root', sa: true });\n```\n\n### new User([obj])\n\nType: `class`\n\nUna clase para objetos de usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Las claves del usuario. |\n\nReturns: `User`\n\nUna clase global. El constructor copia cada clave de `obj` en la nueva instancia, así que `new User({ id: '1', sa: true })` tiene `id` y `sa`. Úsala para la identidad de código que no es una petición, como un job o un script, y compruébala con `instanceof User`. El framework no convierte en instancias de `User` los usuarios que devuelve tu delegado `AUTH()`.\n\nExample: Un usuario para un job\n```js\nNEWACTION('reports_daily', {\n\tsa: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n\nvar scheduler = new User({ id: 'cron', name: 'Scheduler', sa: true });\nACTION('reports_daily').user(scheduler).callback(console.log);\n// { success: true, value: 'Scheduler' }\n```\n\n### NEWACTION({ user: true })\n\nType: `config`\n\nLimita una acción a peticiones autorizadas (true) o no autorizadas (false).\n\nCuando la condición no se cumple, la acción responde con `401`.\n\nExample: Solo usuarios\n```js\nNEWACTION({\n\tid: 'Account/profile',\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### NEWACTION({ sa: true })\n\nType: `config`\n\nLimita una acción a los superadministradores.\n\nEl usuario debe tener `sa` o `su`; si no, la acción responde con `401`. `su: true` funciona igual.\n\nExample: Acción de administración\n```js\nNEWACTION({\n\tid: 'Users/remove',\n\tsa: true,\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### NEWACTION({ permissions: 'name1,name2' })\n\nType: `config`\n\nLimita una acción a los usuarios con cualquiera de los permisos.\n\nUna cadena separada por comas o puntos y comas, o un array. La comprobación es `UNAUTHORIZED()`, así que los superadministradores siempre pasan.\n\nExample: Permisos\n```js\nNEWACTION({\n\tid: 'Orders/list',\n\tpermissions: 'orders,admin',\n\taction: function($) {\n\t\t$.success([]);\n\t}\n});\n```\n\n### BLOCKED($, [limit], [expire])\n\nType: `method`\n\nCuenta los intentos por dirección IP e indica cuándo la dirección está bloqueada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción o de un controlador. |\n| `limit` | `Number|null` | no | `5` | Intentos permitidos; `null` o `-1` reinicia el contador. |\n| `expire` | `String` | no | `'15 minutes'` | Cuánto tiempo vive el contador. |\n\nReturns: `Boolean` `true` cuando está bloqueada.\n\nCada llamada cuenta un intento para `$.ip`. Devuelve `true` cuando la dirección se ha contado más de `limit` veces. El contador empieza con la primera llamada y se elimina después de `expire` (se comprueba cada minuto). `BLOCKED($, null)` o `BLOCKED($, -1)` lo elimina de inmediato.\n\nExample: Protección del inicio de sesión\n```js\nif (BLOCKED($, 10)) {\n\t$.invalid(401);\n\treturn;\n}\n// ... the password is correct\nBLOCKED($, null);\n```\n","entries":[{"type":"delegate","name":"AUTH(callback)","signature":"AUTH(callback)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"opt.onread","signature":"opt.onread = function(meta, callback, $)","since":"","deprecated":false},{"type":"delegate","name":"opt.onsession","signature":"opt.onsession = function(session, $, [isnew])","since":"","deprecated":false},{"type":"delegate","name":"opt.onauthorize","signature":"opt.onauthorize = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.onfree","signature":"opt.onfree = function(meta)","since":"","deprecated":false},{"type":"delegate","name":"opt.onlogout","signature":"opt.onlogout = function(session)","since":"","deprecated":false},{"type":"delegate","name":"opt.onddos","signature":"opt.onddos = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.localize","signature":"opt.localize = function(user, controller)","since":"","deprecated":false},{"type":"method","name":"opt.authcookie($, sessionid, userid, [expire], [options])","signature":"opt.authcookie($, sessionid, userid, [expire], [options])","since":"","deprecated":false},{"type":"method","name":"opt.sign(sessionid, userid)","signature":"opt.sign(sessionid, userid)","since":"","deprecated":false},{"type":"method","name":"opt.logout($)","signature":"opt.logout($)","since":"","deprecated":false},{"type":"method","name":"opt.update(userid, fn)","signature":"opt.update(userid, fn)","since":"","deprecated":false},{"type":"method","name":"opt.refresh(userid, [exceptsessionid])","signature":"opt.refresh(userid, [exceptsessionid])","since":"","deprecated":false},{"type":"property","name":"opt.sessions","signature":"opt.sessions","since":"","deprecated":false},{"type":"property","name":"DEF.onAuthorize","signature":"DEF.onAuthorize","since":"","deprecated":false},{"type":"type","name":"Route flag +","signature":"ROUTE('+METHOD /url/ ...')","since":"","deprecated":false},{"type":"type","name":"Route flag -","signature":"ROUTE('-METHOD /url/ ...')","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"method","name":"controller.authorize([callback])","signature":"controller.authorize([callback])","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED($, [permission...])","signature":"UNAUTHORIZED($, [permission1], [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized([permission...])","signature":"$.unauthorized([permission1], [permission2], [...])","since":"","deprecated":false},{"type":"property","name":"user.permissions","signature":"user.permissions","since":"","deprecated":false},{"type":"property","name":"user.sa","signature":"user.sa","since":"","deprecated":false},{"type":"class","name":"User","signature":"new User([obj])","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ user })","signature":"NEWACTION({ user: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ sa })","signature":"NEWACTION({ sa: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ permissions })","signature":"NEWACTION({ permissions: 'name1,name2' })","since":"","deprecated":false},{"type":"method","name":"BLOCKED($, [limit], [expire])","signature":"BLOCKED($, [limit], [expire])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwWIIEx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/authorization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Autorisation","summary":"AUTH(), flags de route, permissions, sessions et BLOCKED().","markdown":"---\ntitle: Autorisation\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/authorization/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Autorisation\n\n> AUTH(), flags de route, permissions, sessions et BLOCKED().\n\nTout ce qui détermine et vérifie l'utilisateur d'une requête : le délégué `AUTH()` et ses sessions intégrées, les flags de route `+` et `-`, `UNAUTHORIZED()` et les permissions des actions, et `BLOCKED()`. Le guide [Autorisation](../../guides/authorization/) explique comment ils fonctionnent ensemble, avec des exemples.\n\nLe chiffrement et les journaux d'audit ont leurs propres pages : [Chiffrement](../encryption/) et [Journaux d'audit](../audit-logs/).\n\n## API\n\n### AUTH(callback)\n\nType: `delegate`\n\nEnregistre le délégué d'autorisation qui détermine qui est l'utilisateur d'une requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)` ; appelle `$.success(user)` ou `$.invalid()`. |\n\nReturns: `undefined`\n\nLe délégué s'exécute pour chaque requête HTTP et chaque connexion WebSocket qui correspond à une route, après l'analyse du corps et avant l'action de la route. `$` possède `headers`, `query`, `body`, `ip`, `ua`, `url`, `cookie(name)`, `controller` et, pour WebSocket, `iswebsocket: true`. Appelle `$.success(user)` pour autoriser la requête ou `$.invalid()` pour la refuser ; le délégué peut être asynchrone. Un second appel remplace le délégué. `F.auth()` est la même fonction.\n\nExample: Jeton dans un en-tête\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\tDATA.read('tbl_user').where('token', token).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\n### AUTH(options)\n\nType: `method`\n\nInstalle le système intégré de sessions par cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.secret` | `String` | yes |  | Le secret qui signe les jetons de session. |\n| `options.cookie` | `String` | no |  | Le nom du cookie de session. |\n| `options.header` | `String` | no |  | Un nom d'en-tête en minuscules depuis lequel lire le jeton lorsqu'il n'y a pas de cookie. |\n| `options.options` | `Object` | no |  | Options de cookie utilisées par `authcookie()` et lors de la suppression du cookie (`httponly`, `security`, `domain`...). |\n| `options.expire` | `String` | no | `'5 minutes'` | Durée pendant laquelle les données utilisateur chargées restent en mémoire. |\n| `options.cleaner` | `Number` | no | `5` | Fréquence, en minutes, de suppression des sessions expirées. |\n| `options.strict` | `Boolean` | no | `true` | Une session en cache n'est valide que pour le même user agent. |\n| `options.ddos` | `Number` | no |  | Nombre de jetons invalides qu'une adresse IP peut envoyer avant d'être refusée jusqu'au prochain nettoyage. |\n| `options.onread` | `Function` | yes |  | `function(meta, callback, $)` charge l'utilisateur ; voir `opt.onread`. |\n\nReturns: `undefined`\n\nAvec un objet, `AUTH()` le transforme en gestionnaire de sessions et enregistre sa fonction `auth` comme délégué. L'objet reçoit les méthodes `authcookie()`, `sign()`, `logout()`, `update()`, `refresh()` et les `sessions` en mémoire : conserve donc une référence vers celui-ci (par exemple dans `MAIN`). Le jeton est lu depuis le cookie `cookie`, ou depuis l'en-tête `header`. Sa signature est vérifiée avec `secret`, la session est prise en mémoire, et `onread()` est appelée lorsqu'elle n'y est pas.\n\nExample: Configuration des sessions\n```js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').id(meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.session = opt;\n```\n\n### opt.onread = function(meta, callback, $)\n\nType: `delegate`\n\nCharge l'utilisateur d'une session absente de la mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `callback` | `Function` | yes |  | `function(err, data)`. |\n| `$` | `Object` | yes |  | Les options de la requête. |\n\n`meta` vaut `{ sessionid, userid, ip, ua }`, issu du jeton vérifié. Appelle `callback(err, data)` ; `data` devient l'utilisateur et est mis en cache pendant `expire`. Une erreur ou un `data` vide refuse la requête et supprime le cookie. Les requêtes parallèles ayant la même session attendent le premier `onread()`.\n\nExample: Lire depuis la base de données\n```js\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n```\n\n### opt.onsession = function(session, $, [isnew])\n\nType: `delegate`\n\nS'exécute pour chaque requête autorisée avant que l'utilisateur soit accepté.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | La session. |\n| `$` | `Object` | yes |  | Les options de la requête. |\n| `isnew` | `Boolean` | no |  | `true` lorsque les données viennent d'être lues. |\n\nReturns: `Boolean` `true` pour empêcher le succès par défaut.\n\n`session` vaut `{ sessionid, userid, data, ua, expire }` ; `isnew` vaut `true` juste après `onread()`. Retourne `true` pour prendre la main : le framework n'appelle pas `$.success()`, c'est donc à toi d'appeler `$.success()` ou `$.invalid()`.\n\nExample: Compter les requêtes\n```js\nopt.onsession = function(session, $) {\n\tsession.data.requests = (session.data.requests || 0) + 1;\n};\n```\n\n### opt.onauthorize = function($)\n\nType: `delegate`\n\nS'exécute en premier dans le délégué de session ; retourne true pour traiter toi-même la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Les options de la requête. |\n\nReturns: `Boolean` `true` pour ignorer la vérification de session.\n\nUtilise-la pour accepter d'autres identifiants (une clé d'API, par exemple) avant la lecture du cookie. Lorsqu'elle retourne `true`, tu dois appeler `$.success()` ou `$.invalid()`.\n\nExample: Clé d'API\n```js\nopt.onauthorize = function($) {\n\tif ($.headers['x-apikey'] === CONF.apikey) {\n\t\t$.success({ id: 'api', sa: true });\n\t\treturn true;\n\t}\n};\n```\n\n### opt.onfree = function(meta)\n\nType: `delegate`\n\nS'exécute après la suppression des sessions expirées de la mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessions: Array, users: Array }`. |\n\n`meta.sessions` est un tableau des ID de sessions supprimées, `meta.users` les ID des utilisateurs qui n'ont plus aucune session active.\n\nExample: Journaliser\n```js\nopt.onfree = function(meta) {\n\tconsole.log('Released', meta.sessions.length, 'sessions');\n};\n```\n\n### opt.onlogout = function(session)\n\nType: `delegate`\n\nS'exécute lorsque logout() supprime une session de la mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | La session supprimée. |\n\nReçoit l'objet de session supprimé `{ sessionid, userid, data, ua, expire }`. Lorsque la session n'est pas en mémoire, `opt.onremove(sessionid)` est appelée à la place.\n\nExample: Enregistrer l'heure\n```js\nopt.onlogout = function(session) {\n\tDATA.modify('tbl_user', { dtlogout: NOW }).id(session.userid);\n};\n```\n\n### opt.onddos = function($)\n\nType: `delegate`\n\nS'exécute lorsqu'une adresse IP a dépassé la limite ddos de jetons invalides.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Les options de la requête. |\n\nLa requête est refusée juste après cet appel. Les compteurs sont remis à zéro toutes les `cleaner` minutes.\n\nExample: Journaliser\n```js\nopt.ddos = 10;\nopt.onddos = function($) {\n\tconsole.warn('Too many invalid tokens from', $.ip);\n};\n```\n\n### opt.localize = function(user, controller)\n\nType: `delegate`\n\nRetourne la langue de la requête à partir des données de l'utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Les données de l'utilisateur ou `null`. |\n| `controller` | `Controller` | yes |  | Le contrôleur. |\n\nReturns: `String` Un code de langue.\n\nAppelée avec les données de l'utilisateur, ou avec `null` lorsque la requête n'a pas de jeton ou que la session en cache appartient à un autre user agent ; la valeur renvoyée devient `controller.language`. `opt.locale` est acceptée comme la même option.\n\nExample: Langue de l'utilisateur\n```js\nopt.localize = function(user, ctrl) {\n\treturn user ? user.language : (ctrl.headers['accept-language'] || '').substring(0, 2);\n};\n```\n\n### opt.authcookie($, sessionid, userid, [expire], [options])\n\nType: `method`\n\nSigne un jeton et définit le cookie de session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action ou d'un contrôleur. |\n| `sessionid` | `String` | yes |  | Un nouvel ID unique, par exemple `UID()`. |\n| `userid` | `String` | yes |  | L'ID de l'utilisateur transmis ensuite à `onread()`. |\n| `expire` | `String|Date` | no |  | L'expiration du cookie, par exemple `'1 month'`. |\n| `options` | `Object` | no |  | Options du cookie. |\n\nReturns: `String` Le jeton.\n\nAppelle-la après une connexion réussie. Elle crée le jeton avec `sign()` et écrit le cookie `opt.cookie` avec `options` (par défaut `opt.options`). La session elle-même est créée lors de la requête suivante via `onread()`.\n\nExample: Connexion\n```js\nMAIN.session.authcookie($, UID(), user.id, '1 month');\n$.success();\n```\n\n### opt.sign(sessionid, userid)\n\nType: `method`\n\nCrée un jeton de session signé sans définir de cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Un ID de session unique. |\n| `userid` | `String` | yes |  | L'ID de l'utilisateur. |\n\nReturns: `String` Le jeton.\n\nUtilise-la pour les clients qui envoient le jeton dans l'en-tête de l'option `header` au lieu d'un cookie.\n\nExample: Jeton pour une application mobile\n```js\nopt.header = 'x-token';\n// in the login action\n$.success(MAIN.session.sign(UID(), user.id));\n```\n\n### opt.logout($)\n\nType: `method`\n\nSupprime la session de la requête et son cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object|String` | yes |  | La requête ou un ID de session. |\n\nReturns: `Boolean` `true` quand une session a été supprimée.\n\n`$` est le `$` d'une action : la session en mémoire et le cookie sont supprimés. Avec un contrôleur ou une chaîne d'ID de session, seule la session en mémoire est supprimée ; le cookie reste et la requête suivante relit l'utilisateur. Elle renvoie `true` lorsque la session était en mémoire.\n\nExample: Action de déconnexion\n```js\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n### opt.update(userid, fn)\n\nType: `method`\n\nModifie les données en cache de chaque session d'un utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | L'ID de l'utilisateur. |\n| `fn` | `Function` | yes |  | `function(data, session)`. |\n\nReturns: `Number` Le nombre de sessions mises à jour.\n\nAppelle `fn(data, session)` pour chaque session de `userid` en mémoire.\n\nExample: Renommer\n```js\nMAIN.session.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### opt.refresh(userid, [exceptsessionid])\n\nType: `method`\n\nSupprime les sessions en cache d'un utilisateur afin que la requête suivante relise l'utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | L'ID de l'utilisateur. |\n| `exceptsessionid` | `String` | no |  | Une session à conserver. |\n\nReturns: `Number` Le nombre de sessions supprimées.\n\nLes cookies restent valides ; `onread()` charge des données à jour lors de la requête suivante. Passe `exceptsessionid` pour conserver une session en mémoire.\n\nExample: Après une modification des permissions\n```js\nMAIN.session.refresh(model.userid);\n```\n\n### opt.sessions\n\nType: `property`\n\nLes sessions en mémoire, indexées par ID de session.\n\nReturns: `Object`\n\nChaque élément est `{ sessionid, userid, data, ua, expire }`.\n\nExample: Utilisateurs en ligne\n```js\nvar count = Object.keys(MAIN.session.sessions).length;\n```\n\n### DEF.onAuthorize\n\nType: `property`\n\nLe délégué d'autorisation enregistré.\n\nReturns: `Function`\n\n`AUTH()` la définit. Lorsqu'elle est vide, `$.user` n'est jamais défini et les flags `+` et `-` des routes ne sont pas vérifiés : les routes `+` sont donc ouvertes à tout le monde.\n\nExample: Vérification\n```js\nif (!DEF.onAuthorize)\n\tconsole.warn('No AUTH() delegate');\n```\n\n### ROUTE('+METHOD /url/ ...')\n\nType: `type`\n\nLa route est réservée aux requêtes autorisées.\n\nLe flag se place devant la méthode. Lorsque le délégué refuse la requête, le framework cherche une autre route avec la même URL qui correspond (une route `-` ou une route sans flag) ; s'il n'y en a aucune, une requête HTTP reçoit `401` et une connexion WebSocket est refusée pendant le handshake, et le client du navigateur reçoit donc le code de fermeture `1006`. Pour les routes `API`, le flag de la ligne est vérifié pour chaque endpoint.\n\nExample: Espace d'administration\n```js\nROUTE('+GET /admin/', dashboard);\nROUTE('+API /api/ orders_list --> Orders/list');\nROUTE('+SOCKET /chat/', chat);\n```\n\n### ROUTE('-METHOD /url/ ...')\n\nType: `type`\n\nLa route est réservée aux requêtes non autorisées.\n\nTypique pour les pages de connexion et d'inscription. Avec une route `+` sur la même URL, tu sers différemment les visiteurs et les utilisateurs.\n\nExample: Même URL pour les deux\n```js\nROUTE('+GET /', 'app');\nROUTE('-GET /', 'login');\n```\n\n### controller.user\n\nType: `property`\n\nL'utilisateur accepté par le délégué AUTH().\n\nReturns: `Object`\n\n`undefined` lorsque la requête n'est pas autorisée. Il est défini pour chaque route lorsqu'un délégué existe, y compris les routes sans flag, et il est transmis aux actions sous `$.user`.\n\nExample: La lire\n```js\nfunction dashboard($) {\n\t$.json({ name: $.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nL'utilisateur de la requête à l'intérieur d'une action.\n\nReturns: `Object`\n\nPris depuis le contrôleur qui a appelé l'action, ou depuis `ACTION().user(obj)` lorsque tu appelles une action depuis le code.\n\nExample: Filtre par propriétaire\n```js\naction: function($) {\n\tDATA.find('tbl_order').where('userid', $.user.id).callback($);\n}\n```\n\n### controller.authorize([callback])\n\nType: `method`\n\nExécute le délégué AUTH() à la demande.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, user)`. |\n\nReturns: `Promise` Lorsque `callback` n'est pas fourni.\n\nDéfinit `controller.user` lorsque le délégué accepte la requête. Sans `callback`, elle retourne une `Promise` qui se résout avec l'utilisateur ou `undefined` ; elle n'est jamais rejetée.\n\nExample: Dans une route\n```js\nasync function detail($) {\n\tvar user = await $.authorize();\n\t$.json({ logged: !!user });\n}\n```\n\n### controller.session\n\nType: `property`\n\nLa session intégrée de la requête.\n\nReturns: `Object`\n\nDéfinie par `AUTH(options)` : `{ sessionid, userid, data, ua, expire }`. `controller.sessionid` contient l'ID de session et `$.sessionid` le lit dans les actions.\n\nExample: ID de session\n```js\nfunction info($) {\n\t$.json({ sessionid: $.sessionid });\n}\n```\n\n### UNAUTHORIZED($, [permission1], [permission2], [...])\n\nType: `method`\n\nVérifie les permissions de l'utilisateur et répond avec 401 lorsqu'elles manquent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action ou d'un contrôleur. |\n| `permission` | `String` | no |  | Un ou plusieurs noms de permissions ; l'une d'elles suffit. |\n\nReturns: `Boolean` `true` lorsque l'utilisateur n'est pas autorisé et que la requête a reçu une réponse.\n\nRetourne `false` lorsque l'utilisateur possède `sa` ou `su`, ou l'une des permissions de `user.permissions` (ou `user.roles`), qui peut être un tableau ou un objet. Sinon, elle appelle `$.invalid(401)` et retourne `true`. Sans utilisateur, elle retourne toujours `true`. `F.unauthorized()` est la même fonction.\n\nExample: Protéger une action\n```js\naction: function($) {\n\tif (UNAUTHORIZED($, 'orders'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.unauthorized([permission1], [permission2], [...])\n\nType: `method`\n\nUNAUTHORIZED() pour le $ courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | no |  | Un ou plusieurs noms de permissions. |\n\nReturns: `Boolean` `true` lorsque l'utilisateur n'est pas autorisé.\n\nLa même vérification, avec `$` pris depuis l'action.\n\nExample: Forme courte\n```js\nif ($.unauthorized('orders'))\n\treturn;\n```\n\n### user.permissions\n\nType: `property`\n\nLes permissions de l'utilisateur, lues par UNAUTHORIZED() et par les permissions des actions.\n\nReturns: `Array|Object`\n\nUn tableau de noms ou un objet avec les noms comme clés. `user.roles` est utilisé lorsque `permissions` manque.\n\nExample: Accepter avec des rôles\n```js\n$.success({ id: '1', name: 'Anna', roles: ['orders', 'products'] });\n```\n\n### user.sa\n\nType: `property`\n\nIdentifie un super admin.\n\nReturns: `Boolean`\n\nUn utilisateur avec `sa` ou `su` passe `UNAUTHORIZED()` et les `permissions` des actions, et c'est le seul utilisateur autorisé par les actions avec `sa: true`.\n\nExample: Admin\n```js\n$.success({ id: '1', name: 'Root', sa: true });\n```\n\n### new User([obj])\n\nType: `class`\n\nUne classe pour les objets utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Les clés de l'utilisateur. |\n\nReturns: `User`\n\nUne classe globale. Le constructeur copie chaque clé de `obj` dans la nouvelle instance, donc `new User({ id: '1', sa: true })` a `id` et `sa`. Utilise-la pour l'identité d'un code qui n'est pas une requête, comme un job ou un script, et vérifie-la avec `instanceof User`. Le framework ne transforme pas en instances de `User` les utilisateurs que renvoie ton délégué `AUTH()`.\n\nExample: Un utilisateur pour un job\n```js\nNEWACTION('reports_daily', {\n\tsa: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n\nvar scheduler = new User({ id: 'cron', name: 'Scheduler', sa: true });\nACTION('reports_daily').user(scheduler).callback(console.log);\n// { success: true, value: 'Scheduler' }\n```\n\n### NEWACTION({ user: true })\n\nType: `config`\n\nLimite une action aux requêtes autorisées (true) ou non autorisées (false).\n\nLorsque la condition échoue, l'action répond avec `401`.\n\nExample: Utilisateurs uniquement\n```js\nNEWACTION({\n\tid: 'Account/profile',\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### NEWACTION({ sa: true })\n\nType: `config`\n\nLimite une action aux super admins.\n\nL'utilisateur doit posséder `sa` ou `su`, sinon l'action répond avec `401`. `su: true` fonctionne de la même manière.\n\nExample: Action d'administration\n```js\nNEWACTION({\n\tid: 'Users/remove',\n\tsa: true,\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### NEWACTION({ permissions: 'name1,name2' })\n\nType: `config`\n\nLimite une action aux utilisateurs possédant l'une des permissions.\n\nUne chaîne séparée par des virgules ou des points-virgules, ou un tableau. La vérification est `UNAUTHORIZED()` : les super admins passent donc toujours.\n\nExample: Permissions\n```js\nNEWACTION({\n\tid: 'Orders/list',\n\tpermissions: 'orders,admin',\n\taction: function($) {\n\t\t$.success([]);\n\t}\n});\n```\n\n### BLOCKED($, [limit], [expire])\n\nType: `method`\n\nCompte les tentatives par adresse IP et indique quand l'adresse est bloquée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action ou d'un contrôleur. |\n| `limit` | `Number|null` | no | `5` | Tentatives autorisées ; `null` ou `-1` réinitialise le compteur. |\n| `expire` | `String` | no | `'15 minutes'` | La durée de vie du compteur. |\n\nReturns: `Boolean` `true` lorsque l'adresse est bloquée.\n\nChaque appel compte une tentative pour `$.ip`. Elle retourne `true` lorsque l'adresse a été comptée plus de `limit` fois. Le compteur démarre au premier appel et est supprimé après `expire` (vérifié chaque minute). `BLOCKED($, null)` ou `BLOCKED($, -1)` le supprime immédiatement.\n\nExample: Protection de la connexion\n```js\nif (BLOCKED($, 10)) {\n\t$.invalid(401);\n\treturn;\n}\n// ... the password is correct\nBLOCKED($, null);\n```\n","entries":[{"type":"delegate","name":"AUTH(callback)","signature":"AUTH(callback)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"opt.onread","signature":"opt.onread = function(meta, callback, $)","since":"","deprecated":false},{"type":"delegate","name":"opt.onsession","signature":"opt.onsession = function(session, $, [isnew])","since":"","deprecated":false},{"type":"delegate","name":"opt.onauthorize","signature":"opt.onauthorize = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.onfree","signature":"opt.onfree = function(meta)","since":"","deprecated":false},{"type":"delegate","name":"opt.onlogout","signature":"opt.onlogout = function(session)","since":"","deprecated":false},{"type":"delegate","name":"opt.onddos","signature":"opt.onddos = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.localize","signature":"opt.localize = function(user, controller)","since":"","deprecated":false},{"type":"method","name":"opt.authcookie($, sessionid, userid, [expire], [options])","signature":"opt.authcookie($, sessionid, userid, [expire], [options])","since":"","deprecated":false},{"type":"method","name":"opt.sign(sessionid, userid)","signature":"opt.sign(sessionid, userid)","since":"","deprecated":false},{"type":"method","name":"opt.logout($)","signature":"opt.logout($)","since":"","deprecated":false},{"type":"method","name":"opt.update(userid, fn)","signature":"opt.update(userid, fn)","since":"","deprecated":false},{"type":"method","name":"opt.refresh(userid, [exceptsessionid])","signature":"opt.refresh(userid, [exceptsessionid])","since":"","deprecated":false},{"type":"property","name":"opt.sessions","signature":"opt.sessions","since":"","deprecated":false},{"type":"property","name":"DEF.onAuthorize","signature":"DEF.onAuthorize","since":"","deprecated":false},{"type":"type","name":"Route flag +","signature":"ROUTE('+METHOD /url/ ...')","since":"","deprecated":false},{"type":"type","name":"Route flag -","signature":"ROUTE('-METHOD /url/ ...')","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"method","name":"controller.authorize([callback])","signature":"controller.authorize([callback])","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED($, [permission...])","signature":"UNAUTHORIZED($, [permission1], [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized([permission...])","signature":"$.unauthorized([permission1], [permission2], [...])","since":"","deprecated":false},{"type":"property","name":"user.permissions","signature":"user.permissions","since":"","deprecated":false},{"type":"property","name":"user.sa","signature":"user.sa","since":"","deprecated":false},{"type":"class","name":"User","signature":"new User([obj])","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ user })","signature":"NEWACTION({ user: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ sa })","signature":"NEWACTION({ sa: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ permissions })","signature":"NEWACTION({ permissions: 'name1,name2' })","since":"","deprecated":false},{"type":"method","name":"BLOCKED($, [limit], [expire])","signature":"BLOCKED($, [limit], [expire])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwWIIEx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/authorization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Autorizzazione","summary":"AUTH(), flag delle route, permessi, sessioni e BLOCKED().","markdown":"---\ntitle: Autorizzazione\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/authorization/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Autorizzazione\n\n> AUTH(), flag delle route, permessi, sessioni e BLOCKED().\n\nTutto ciò che stabilisce e controlla l'utente di una richiesta: il delegato `AUTH()` e le sue sessioni integrate, i flag delle route `+` e `-`, `UNAUTHORIZED()` e i permessi delle azioni e `BLOCKED()`. La guida [Autorizzazione](../../guides/authorization/) spiega come funzionano insieme, con esempi.\n\nLa cifratura e gli audit log hanno pagine proprie: [Cifratura](../encryption/) e [Audit log](../audit-logs/).\n\n## API\n\n### AUTH(callback)\n\nType: `delegate`\n\nRegistra il delegato di autorizzazione che stabilisce chi è l'utente di una richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)`; chiama `$.success(user)` o `$.invalid()`. |\n\nReturns: `undefined`\n\nIl delegato viene eseguito per ogni richiesta HTTP e connessione WebSocket che corrisponde a una route, dopo l'interpretazione del body e prima dell'azione della route. `$` contiene `headers`, `query`, `body`, `ip`, `ua`, `url`, `cookie(name)`, `controller` e, per WebSocket, `iswebsocket: true`. Chiama `$.success(user)` per autorizzare la richiesta o `$.invalid()` per rifiutarla; il delegato può essere asincrono. Una seconda chiamata sostituisce il delegato. `F.auth()` è la stessa funzione.\n\nExample: Token in un header\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\tDATA.read('tbl_user').where('token', token).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\n### AUTH(options)\n\nType: `method`\n\nInstalla il sistema integrato di sessioni basato su cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.secret` | `String` | yes |  | Il segreto che firma i token di sessione. |\n| `options.cookie` | `String` | no |  | Il nome del cookie di sessione. |\n| `options.header` | `String` | no |  | Il nome di un header in minuscolo da cui leggere il token quando non c'è il cookie. |\n| `options.options` | `Object` | no |  | Opzioni del cookie usate da `authcookie()` e quando il cookie viene rimosso (`httponly`, `security`, `domain`...). |\n| `options.expire` | `String` | no | `'5 minutes'` | Per quanto tempo i dati utente caricati restano in memoria. |\n| `options.cleaner` | `Number` | no | `5` | Ogni quanti minuti vengono rimosse le sessioni scadute. |\n| `options.strict` | `Boolean` | no | `true` | Una sessione in cache è valida solo per lo stesso user agent. |\n| `options.ddos` | `Number` | no |  | Quanti token non validi può inviare un indirizzo IP prima di essere rifiutato fino alla pulizia successiva. |\n| `options.onread` | `Function` | yes |  | `function(meta, callback, $)` carica l'utente; vedi `opt.onread`. |\n\nReturns: `undefined`\n\nCon un oggetto, `AUTH()` lo trasforma in un gestore di sessioni e registra la sua funzione `auth` come delegato. L'oggetto riceve i metodi `authcookie()`, `sign()`, `logout()`, `update()`, `refresh()` e le `sessions` in memoria, quindi conservane un riferimento (ad esempio in `MAIN`). Il token viene letto dal cookie `cookie`, o dall'header `header`. La sua firma viene verificata con `secret`, la sessione viene presa dalla memoria e `onread()` viene chiamato quando non c'è.\n\nExample: Configurazione delle sessioni\n```js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').id(meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.session = opt;\n```\n\n### opt.onread = function(meta, callback, $)\n\nType: `delegate`\n\nCarica l'utente di una sessione che non è in memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `callback` | `Function` | yes |  | `function(err, data)`. |\n| `$` | `Object` | yes |  | Le opzioni della richiesta. |\n\n`meta` è `{ sessionid, userid, ip, ua }` dal token verificato. Chiama `callback(err, data)`; `data` diventa l'utente e viene messo in cache per `expire`. Un errore o `data` vuoto rifiuta la richiesta e rimuove il cookie. Le richieste parallele con la stessa sessione attendono il primo `onread()`.\n\nExample: Leggere dal database\n```js\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n```\n\n### opt.onsession = function(session, $, [isnew])\n\nType: `delegate`\n\nViene eseguito per ogni richiesta autorizzata prima che l'utente venga accettato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | La sessione. |\n| `$` | `Object` | yes |  | Le opzioni della richiesta. |\n| `isnew` | `Boolean` | no |  | `true` quando i dati sono appena stati letti. |\n\nReturns: `Boolean` `true` per fermare il successo predefinito.\n\n`session` è `{ sessionid, userid, data, ua, expire }`; `isnew` è `true` subito dopo `onread()`. Restituisci `true` per prendere il controllo: il framework non chiama `$.success()`, quindi chiami tu `$.success()` o `$.invalid()`.\n\nExample: Contare le richieste\n```js\nopt.onsession = function(session, $) {\n\tsession.data.requests = (session.data.requests || 0) + 1;\n};\n```\n\n### opt.onauthorize = function($)\n\nType: `delegate`\n\nViene eseguito per primo nel delegato di sessione; restituisci true per gestire tu la richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le opzioni della richiesta. |\n\nReturns: `Boolean` `true` per saltare il controllo della sessione.\n\nUsalo per accettare altre credenziali (ad esempio una API key) prima che il cookie venga letto. Quando restituisce `true` devi chiamare `$.success()` o `$.invalid()`.\n\nExample: API key\n```js\nopt.onauthorize = function($) {\n\tif ($.headers['x-apikey'] === CONF.apikey) {\n\t\t$.success({ id: 'api', sa: true });\n\t\treturn true;\n\t}\n};\n```\n\n### opt.onfree = function(meta)\n\nType: `delegate`\n\nViene eseguito dopo che le sessioni scadute sono state rimosse dalla memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessions: Array, users: Array }`. |\n\n`meta.sessions` è un array degli ID delle sessioni rimosse, `meta.users` gli ID degli utenti che non hanno più sessioni attive.\n\nExample: Registrarlo nel log\n```js\nopt.onfree = function(meta) {\n\tconsole.log('Released', meta.sessions.length, 'sessions');\n};\n```\n\n### opt.onlogout = function(session)\n\nType: `delegate`\n\nViene eseguito quando logout() rimuove una sessione dalla memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | La sessione rimossa. |\n\nRiceve l'oggetto della sessione rimossa `{ sessionid, userid, data, ua, expire }`. Quando la sessione non è in memoria, viene invece chiamato `opt.onremove(sessionid)`.\n\nExample: Salvare l'orario\n```js\nopt.onlogout = function(session) {\n\tDATA.modify('tbl_user', { dtlogout: NOW }).id(session.userid);\n};\n```\n\n### opt.onddos = function($)\n\nType: `delegate`\n\nViene eseguito quando un indirizzo IP ha superato il limite ddos di token non validi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le opzioni della richiesta. |\n\nLa richiesta viene rifiutata subito dopo questa chiamata. I contatori vengono azzerati ogni `cleaner` minuti.\n\nExample: Registrarlo nel log\n```js\nopt.ddos = 10;\nopt.onddos = function($) {\n\tconsole.warn('Too many invalid tokens from', $.ip);\n};\n```\n\n### opt.localize = function(user, controller)\n\nType: `delegate`\n\nRestituisce la lingua della richiesta dai dati dell'utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | I dati dell'utente o `null`. |\n| `controller` | `Controller` | yes |  | Il controller. |\n\nReturns: `String` Un codice di lingua.\n\nChiamata con i dati dell'utente, oppure con `null` quando la richiesta non ha un token o la sessione in cache appartiene a un altro user agent; il valore restituito diventa `controller.language`. `opt.locale` è accettata come la stessa opzione.\n\nExample: Lingua dell'utente\n```js\nopt.localize = function(user, ctrl) {\n\treturn user ? user.language : (ctrl.headers['accept-language'] || '').substring(0, 2);\n};\n```\n\n### opt.authcookie($, sessionid, userid, [expire], [options])\n\nType: `method`\n\nFirma un token e imposta il cookie di sessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione o di un controller. |\n| `sessionid` | `String` | yes |  | Un nuovo ID univoco, ad esempio `UID()`. |\n| `userid` | `String` | yes |  | L'ID utente passato in seguito a `onread()`. |\n| `expire` | `String|Date` | no |  | La scadenza del cookie, ad esempio `'1 month'`. |\n| `options` | `Object` | no |  | Opzioni del cookie. |\n\nReturns: `String` Il token.\n\nChiamalo dopo un login riuscito. Crea il token con `sign()` e scrive il cookie `opt.cookie` con `options` (default `opt.options`). La sessione vera e propria viene creata alla richiesta successiva tramite `onread()`.\n\nExample: Login\n```js\nMAIN.session.authcookie($, UID(), user.id, '1 month');\n$.success();\n```\n\n### opt.sign(sessionid, userid)\n\nType: `method`\n\nCrea un token di sessione firmato senza impostare un cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Un ID di sessione univoco. |\n| `userid` | `String` | yes |  | L'ID utente. |\n\nReturns: `String` Il token.\n\nUsalo per i client che inviano il token nell'opzione `header` invece che in un cookie.\n\nExample: Token per un'app mobile\n```js\nopt.header = 'x-token';\n// in the login action\n$.success(MAIN.session.sign(UID(), user.id));\n```\n\n### opt.logout($)\n\nType: `method`\n\nRimuove la sessione della richiesta e il suo cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object|String` | yes |  | La richiesta o un ID di sessione. |\n\nReturns: `Boolean` `true` quando una sessione è stata rimossa.\n\n`$` è il `$` di un'azione: la sessione in memoria e il cookie vengono rimossi. Con un controller o una stringa di ID sessione viene rimossa solo la sessione in memoria; il cookie resta e la richiesta successiva legge di nuovo l'utente. Restituisce `true` quando la sessione era in memoria.\n\nExample: Azione di logout\n```js\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n### opt.update(userid, fn)\n\nType: `method`\n\nModifica i dati in cache di ogni sessione di un utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | L'ID utente. |\n| `fn` | `Function` | yes |  | `function(data, session)`. |\n\nReturns: `Number` Quante sessioni sono state aggiornate.\n\nChiama `fn(data, session)` per ogni sessione di `userid` in memoria.\n\nExample: Rinominare\n```js\nMAIN.session.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### opt.refresh(userid, [exceptsessionid])\n\nType: `method`\n\nScarta le sessioni in cache di un utente, così la richiesta successiva legge di nuovo l'utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | L'ID utente. |\n| `exceptsessionid` | `String` | no |  | Una sessione da mantenere. |\n\nReturns: `Number` Quante sessioni sono state scartate.\n\nI cookie restano validi; `onread()` carica dati aggiornati alla richiesta successiva. Passa `exceptsessionid` per mantenere una sessione in memoria.\n\nExample: Dopo una modifica dei permessi\n```js\nMAIN.session.refresh(model.userid);\n```\n\n### opt.sessions\n\nType: `property`\n\nLe sessioni in memoria, indicizzate per ID di sessione.\n\nReturns: `Object`\n\nOgni elemento è `{ sessionid, userid, data, ua, expire }`.\n\nExample: Utenti online\n```js\nvar count = Object.keys(MAIN.session.sessions).length;\n```\n\n### DEF.onAuthorize\n\nType: `property`\n\nIl delegato di autorizzazione registrato.\n\nReturns: `Function`\n\n`AUTH()` la imposta. Quando è vuota, `$.user` non viene mai impostato e i flag `+` e `-` delle route non vengono controllati, quindi le route `+` sono aperte a tutti.\n\nExample: Controllo\n```js\nif (!DEF.onAuthorize)\n\tconsole.warn('No AUTH() delegate');\n```\n\n### ROUTE('+METHOD /url/ ...')\n\nType: `type`\n\nLa route è riservata alle richieste autorizzate.\n\nIl flag va davanti al metodo. Quando il delegato rifiuta la richiesta, il framework cerca un'altra route con lo stesso URL che corrisponda (una route `-` o una senza flag); se non c'è, una richiesta HTTP riceve `401` e una connessione WebSocket viene rifiutata durante l'handshake, quindi il client del browser riceve il codice di chiusura `1006`. Per le route `API` il flag della riga viene controllato per ogni endpoint.\n\nExample: Area di amministrazione\n```js\nROUTE('+GET /admin/', dashboard);\nROUTE('+API /api/ orders_list --> Orders/list');\nROUTE('+SOCKET /chat/', chat);\n```\n\n### ROUTE('-METHOD /url/ ...')\n\nType: `type`\n\nLa route è riservata alle richieste non autorizzate.\n\nTipico per le pagine di login e registrazione. Con una route `+` sullo stesso URL servi in modo diverso visitatori e utenti.\n\nExample: Stesso URL per entrambi\n```js\nROUTE('+GET /', 'app');\nROUTE('-GET /', 'login');\n```\n\n### controller.user\n\nType: `property`\n\nL'utente accettato dal delegato AUTH().\n\nReturns: `Object`\n\n`undefined` quando la richiesta non è autorizzata. Viene impostato per ogni route quando esiste un delegato, comprese le route senza flag, e viene passato alle azioni come `$.user`.\n\nExample: Leggerla\n```js\nfunction dashboard($) {\n\t$.json({ name: $.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nL'utente della richiesta all'interno di un'azione.\n\nReturns: `Object`\n\nPreso dal controller che ha chiamato l'azione, o da `ACTION().user(obj)` quando chiami un'azione dal codice.\n\nExample: Filtro per proprietario\n```js\naction: function($) {\n\tDATA.find('tbl_order').where('userid', $.user.id).callback($);\n}\n```\n\n### controller.authorize([callback])\n\nType: `method`\n\nEsegue il delegato AUTH() su richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, user)`. |\n\nReturns: `Promise` Quando `callback` non viene passata.\n\nImposta `controller.user` quando il delegato accetta la richiesta. Senza `callback` restituisce una `Promise` che si risolve con l'utente o `undefined`; non viene mai rifiutata.\n\nExample: All'interno di una route\n```js\nasync function detail($) {\n\tvar user = await $.authorize();\n\t$.json({ logged: !!user });\n}\n```\n\n### controller.session\n\nType: `property`\n\nLa sessione integrata della richiesta.\n\nReturns: `Object`\n\nImpostata da `AUTH(options)`: `{ sessionid, userid, data, ua, expire }`. `controller.sessionid` contiene l'ID di sessione e `$.sessionid` lo legge nelle azioni.\n\nExample: ID sessione\n```js\nfunction info($) {\n\t$.json({ sessionid: $.sessionid });\n}\n```\n\n### UNAUTHORIZED($, [permission1], [permission2], [...])\n\nType: `method`\n\nControlla i permessi dell'utente e risponde con 401 quando mancano.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione o di un controller. |\n| `permission` | `String` | no |  | Uno o più nomi di permessi; ne basta uno qualsiasi. |\n\nReturns: `Boolean` `true` quando l'utente non è autorizzato e alla richiesta è stata data risposta.\n\nRestituisce `false` quando l'utente ha `sa` o `su`, oppure uno dei permessi in `user.permissions` (o `user.roles`), che può essere un array o un oggetto. Altrimenti chiama `$.invalid(401)` e restituisce `true`. Senza utente restituisce sempre `true`. `F.unauthorized()` è la stessa funzione.\n\nExample: Proteggere un'azione\n```js\naction: function($) {\n\tif (UNAUTHORIZED($, 'orders'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.unauthorized([permission1], [permission2], [...])\n\nType: `method`\n\nUNAUTHORIZED() per il $ corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | no |  | Uno o più nomi di permessi. |\n\nReturns: `Boolean` `true` quando l'utente non è autorizzato.\n\nLo stesso controllo con `$` preso dall'azione.\n\nExample: Forma breve\n```js\nif ($.unauthorized('orders'))\n\treturn;\n```\n\n### user.permissions\n\nType: `property`\n\nI permessi dell'utente, letti da UNAUTHORIZED() e dai permessi delle azioni.\n\nReturns: `Array|Object`\n\nUn array di nomi o un oggetto con i nomi come chiavi. `user.roles` viene usato quando `permissions` manca.\n\nExample: Accettare con i ruoli\n```js\n$.success({ id: '1', name: 'Anna', roles: ['orders', 'products'] });\n```\n\n### user.sa\n\nType: `property`\n\nContrassegna un super admin.\n\nReturns: `Boolean`\n\nUn utente con `sa` o `su` supera `UNAUTHORIZED()` e i `permissions` delle azioni, ed è l'unico utente consentito dalle azioni con `sa: true`.\n\nExample: Admin\n```js\n$.success({ id: '1', name: 'Root', sa: true });\n```\n\n### new User([obj])\n\nType: `class`\n\nUna classe per gli oggetti utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Le chiavi dell'utente. |\n\nReturns: `User`\n\nUna classe globale. Il costruttore copia ogni chiave di `obj` nella nuova istanza, quindi `new User({ id: '1', sa: true })` ha `id` e `sa`. Usala per l'identità di codice che non è una richiesta, come un job o uno script, e verificala con `instanceof User`. Il framework non trasforma in istanze di `User` gli utenti che il tuo delegate `AUTH()` restituisce.\n\nExample: Un utente per un job\n```js\nNEWACTION('reports_daily', {\n\tsa: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n\nvar scheduler = new User({ id: 'cron', name: 'Scheduler', sa: true });\nACTION('reports_daily').user(scheduler).callback(console.log);\n// { success: true, value: 'Scheduler' }\n```\n\n### NEWACTION({ user: true })\n\nType: `config`\n\nLimita un'azione alle richieste autorizzate (true) o non autorizzate (false).\n\nQuando la condizione non è soddisfatta, l'azione risponde con `401`.\n\nExample: Solo utenti\n```js\nNEWACTION({\n\tid: 'Account/profile',\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### NEWACTION({ sa: true })\n\nType: `config`\n\nLimita un'azione ai super admin.\n\nL'utente deve avere `sa` o `su`, altrimenti l'azione risponde con `401`. `su: true` funziona allo stesso modo.\n\nExample: Azione di amministrazione\n```js\nNEWACTION({\n\tid: 'Users/remove',\n\tsa: true,\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### NEWACTION({ permissions: 'name1,name2' })\n\nType: `config`\n\nLimita un'azione agli utenti con uno qualsiasi dei permessi.\n\nUna stringa separata da virgole o punti e virgola, oppure un array. Il controllo è `UNAUTHORIZED()`, quindi i super admin passano sempre.\n\nExample: Permessi\n```js\nNEWACTION({\n\tid: 'Orders/list',\n\tpermissions: 'orders,admin',\n\taction: function($) {\n\t\t$.success([]);\n\t}\n});\n```\n\n### BLOCKED($, [limit], [expire])\n\nType: `method`\n\nConta i tentativi per indirizzo IP e indica quando l'indirizzo è bloccato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione o di un controller. |\n| `limit` | `Number|null` | no | `5` | Tentativi consentiti; `null` o `-1` azzera il contatore. |\n| `expire` | `String` | no | `'15 minutes'` | Per quanto tempo vive il contatore. |\n\nReturns: `Boolean` `true` quando è bloccato.\n\nOgni chiamata conta un tentativo per `$.ip`. Restituisce `true` quando l'indirizzo è stato contato più di `limit` volte. Il contatore parte con la prima chiamata e viene rimosso dopo `expire` (controllato ogni minuto). `BLOCKED($, null)` o `BLOCKED($, -1)` lo rimuove subito.\n\nExample: Protezione del login\n```js\nif (BLOCKED($, 10)) {\n\t$.invalid(401);\n\treturn;\n}\n// ... the password is correct\nBLOCKED($, null);\n```\n","entries":[{"type":"delegate","name":"AUTH(callback)","signature":"AUTH(callback)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"opt.onread","signature":"opt.onread = function(meta, callback, $)","since":"","deprecated":false},{"type":"delegate","name":"opt.onsession","signature":"opt.onsession = function(session, $, [isnew])","since":"","deprecated":false},{"type":"delegate","name":"opt.onauthorize","signature":"opt.onauthorize = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.onfree","signature":"opt.onfree = function(meta)","since":"","deprecated":false},{"type":"delegate","name":"opt.onlogout","signature":"opt.onlogout = function(session)","since":"","deprecated":false},{"type":"delegate","name":"opt.onddos","signature":"opt.onddos = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.localize","signature":"opt.localize = function(user, controller)","since":"","deprecated":false},{"type":"method","name":"opt.authcookie($, sessionid, userid, [expire], [options])","signature":"opt.authcookie($, sessionid, userid, [expire], [options])","since":"","deprecated":false},{"type":"method","name":"opt.sign(sessionid, userid)","signature":"opt.sign(sessionid, userid)","since":"","deprecated":false},{"type":"method","name":"opt.logout($)","signature":"opt.logout($)","since":"","deprecated":false},{"type":"method","name":"opt.update(userid, fn)","signature":"opt.update(userid, fn)","since":"","deprecated":false},{"type":"method","name":"opt.refresh(userid, [exceptsessionid])","signature":"opt.refresh(userid, [exceptsessionid])","since":"","deprecated":false},{"type":"property","name":"opt.sessions","signature":"opt.sessions","since":"","deprecated":false},{"type":"property","name":"DEF.onAuthorize","signature":"DEF.onAuthorize","since":"","deprecated":false},{"type":"type","name":"Route flag +","signature":"ROUTE('+METHOD /url/ ...')","since":"","deprecated":false},{"type":"type","name":"Route flag -","signature":"ROUTE('-METHOD /url/ ...')","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"method","name":"controller.authorize([callback])","signature":"controller.authorize([callback])","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED($, [permission...])","signature":"UNAUTHORIZED($, [permission1], [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized([permission...])","signature":"$.unauthorized([permission1], [permission2], [...])","since":"","deprecated":false},{"type":"property","name":"user.permissions","signature":"user.permissions","since":"","deprecated":false},{"type":"property","name":"user.sa","signature":"user.sa","since":"","deprecated":false},{"type":"class","name":"User","signature":"new User([obj])","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ user })","signature":"NEWACTION({ user: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ sa })","signature":"NEWACTION({ sa: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ permissions })","signature":"NEWACTION({ permissions: 'name1,name2' })","since":"","deprecated":false},{"type":"method","name":"BLOCKED($, [limit], [expire])","signature":"BLOCKED($, [limit], [expire])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwWIIEx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/authorization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Autorizácia","summary":"AUTH(), príznaky rout, oprávnenia, sessions a BLOCKED().","markdown":"---\ntitle: \"Autorizácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/authorization/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Autorizácia\n\n> AUTH(), príznaky rout, oprávnenia, sessions a BLOCKED().\n\nVšetko, čo určuje a kontroluje používateľa požiadavky: delegát `AUTH()` a jeho vstavané sessions, príznaky rout `+` a `-`, `UNAUTHORIZED()` a oprávnenia akcií a `BLOCKED()`. Ako spolu fungujú, vysvetľuje s príkladmi návod [Autorizácia](../../guides/authorization/).\n\nŠifrovanie a auditné logy majú vlastné stránky: [Šifrovanie](../encryption/) a [Auditné logy](../audit-logs/).\n\n## API\n\n### AUTH(callback)\n\nType: `delegate`\n\nZaregistruje autorizačný delegát, ktorý určuje, kto je používateľ požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function($)`; zavolaj `$.success(user)` alebo `$.invalid()`. |\n\nReturns: `undefined`\n\nDelegát sa spustí pre každú HTTP požiadavku a WebSocket spojenie, ktoré zodpovedá route, po sparsovaní tela a pred akciou routy. `$` obsahuje `headers`, `query`, `body`, `ip`, `ua`, `url`, `cookie(name)`, `controller` a pri WebSockete `iswebsocket: true`. Zavolaj `$.success(user)` na autorizovanie požiadavky alebo `$.invalid()` na jej odmietnutie; delegát môže byť asynchrónny. Druhé volanie delegát nahradí. `F.auth()` je tá istá funkcia.\n\nExample: Token v hlavičke\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\tDATA.read('tbl_user').where('token', token).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\n### AUTH(options)\n\nType: `method`\n\nNainštaluje vstavaný systém cookie sessions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.secret` | `String` | yes |  | Tajomstvo, ktorým sa podpisujú tokeny sessions. |\n| `options.cookie` | `String` | no |  | Meno cookie session. |\n| `options.header` | `String` | no |  | Meno hlavičky malými písmenami, z ktorej sa číta token, keď nie je cookie. |\n| `options.options` | `Object` | no |  | Voľby cookie, ktoré používa `authcookie()` a ktoré sa použijú pri odstránení cookie (`httponly`, `security`, `domain`...). |\n| `options.expire` | `String` | no | `'5 minutes'` | Ako dlho zostanú načítané dáta používateľa v pamäti. |\n| `options.cleaner` | `Number` | no | `5` | Ako často, v minútach, sa odstraňujú expirované sessions. |\n| `options.strict` | `Boolean` | no | `true` | Cachovaná session je platná len pre rovnakého user agenta. |\n| `options.ddos` | `Number` | no |  | Koľko neplatných tokenov smie poslať jedna IP adresa, kým bude odmietaná až do ďalšieho čistenia. |\n| `options.onread` | `Function` | yes |  | `function(meta, callback, $)` načíta používateľa; pozri `opt.onread`. |\n\nReturns: `undefined`\n\nS objektom ho `AUTH()` zmení na správcu sessions a jeho funkciu `auth` zaregistruje ako delegát. Objekt dostane metódy `authcookie()`, `sign()`, `logout()`, `update()`, `refresh()` a `sessions` v pamäti, takže si naň uchovaj referenciu (napríklad v `MAIN`). Token sa číta z cookie `cookie` alebo z hlavičky `header`. Jeho podpis sa overí pomocou `secret`, session sa vezme z pamäte a `onread()` sa zavolá, keď tam nie je.\n\nExample: Nastavenie sessions\n```js\nvar opt = {};\nopt.secret = 'a-long-random-string';\nopt.cookie = '__user';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').id(meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.session = opt;\n```\n\n### opt.onread = function(meta, callback, $)\n\nType: `delegate`\n\nNačíta používateľa session, ktorá nie je v pamäti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `callback` | `Function` | yes |  | `function(err, data)`. |\n| `$` | `Object` | yes |  | Voľby požiadavky. |\n\n`meta` je `{ sessionid, userid, ip, ua }` z overeného tokenu. Zavolaj `callback(err, data)`; `data` sa stanú používateľom a cachujú sa počas `expire`. Chyba alebo prázdne `data` požiadavku odmietnu a odstránia cookie. Paralelné požiadavky s rovnakou session čakajú na prvé `onread()`.\n\nExample: Načítanie z databázy\n```js\nopt.onread = function(meta, next) {\n\tDATA.read('tbl_user').fields('id,name,sa,permissions').id(meta.userid).where('isdisabled', false).callback(next);\n};\n```\n\n### opt.onsession = function(session, $, [isnew])\n\nType: `delegate`\n\nSpustí sa pre každú autorizovanú požiadavku pred prijatím používateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | Session. |\n| `$` | `Object` | yes |  | Voľby požiadavky. |\n| `isnew` | `Boolean` | no |  | `true`, keď boli dáta práve načítané. |\n\nReturns: `Boolean` `true` na zastavenie predvoleného úspechu.\n\n`session` je `{ sessionid, userid, data, ua, expire }`; `isnew` je `true` hneď po `onread()`. Vráť `true`, ak chceš prevziať kontrolu: framework nezavolá `$.success()`, takže `$.success()` alebo `$.invalid()` zavoláš sám.\n\nExample: Počítanie požiadaviek\n```js\nopt.onsession = function(session, $) {\n\tsession.data.requests = (session.data.requests || 0) + 1;\n};\n```\n\n### opt.onauthorize = function($)\n\nType: `delegate`\n\nSpustí sa v delegáte sessions ako prvá; vráť true, ak chceš požiadavku spracovať sám.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Voľby požiadavky. |\n\nReturns: `Boolean` `true` na preskočenie kontroly session.\n\nPouži ju na prijatie iných prihlasovacích údajov (napríklad API kľúča) pred prečítaním cookie. Keď vráti `true`, musíš zavolať `$.success()` alebo `$.invalid()`.\n\nExample: API kľúč\n```js\nopt.onauthorize = function($) {\n\tif ($.headers['x-apikey'] === CONF.apikey) {\n\t\t$.success({ id: 'api', sa: true });\n\t\treturn true;\n\t}\n};\n```\n\n### opt.onfree = function(meta)\n\nType: `delegate`\n\nSpustí sa po odstránení expirovaných sessions z pamäte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessions: Array, users: Array }`. |\n\n`meta.sessions` je pole ID odstránených sessions, `meta.users` ID používateľov, ktorým nezostala žiadna živá session.\n\nExample: Zalogovanie\n```js\nopt.onfree = function(meta) {\n\tconsole.log('Released', meta.sessions.length, 'sessions');\n};\n```\n\n### opt.onlogout = function(session)\n\nType: `delegate`\n\nSpustí sa, keď logout() odstráni session z pamäte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `session` | `Object` | yes |  | Odstránená session. |\n\nDostane odstránený objekt session `{ sessionid, userid, data, ua, expire }`. Keď session nie je v pamäti, zavolá sa namiesto toho `opt.onremove(sessionid)`.\n\nExample: Uloženie času\n```js\nopt.onlogout = function(session) {\n\tDATA.modify('tbl_user', { dtlogout: NOW }).id(session.userid);\n};\n```\n\n### opt.onddos = function($)\n\nType: `delegate`\n\nSpustí sa, keď IP adresa prekročila ddos limit neplatných tokenov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Voľby požiadavky. |\n\nPožiadavka sa odmietne hneď po tomto volaní. Počítadlá sa čistia každých `cleaner` minút.\n\nExample: Zalogovanie\n```js\nopt.ddos = 10;\nopt.onddos = function($) {\n\tconsole.warn('Too many invalid tokens from', $.ip);\n};\n```\n\n### opt.localize = function(user, controller)\n\nType: `delegate`\n\nVráti jazyk požiadavky z dát používateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Dáta používateľa alebo `null`. |\n| `controller` | `Controller` | yes |  | Controller. |\n\nReturns: `String` Kód jazyka.\n\nVolá sa s dátami používateľa, alebo s `null`, keď požiadavka nemá token alebo session v cache patrí inému user agentovi; vrátená hodnota sa stane `controller.language`. `opt.locale` sa prijíma ako tá istá voľba.\n\nExample: Jazyk používateľa\n```js\nopt.localize = function(user, ctrl) {\n\treturn user ? user.language : (ctrl.headers['accept-language'] || '').substring(0, 2);\n};\n```\n\n### opt.authcookie($, sessionid, userid, [expire], [options])\n\nType: `method`\n\nPodpíše token a nastaví cookie session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie alebo controllera. |\n| `sessionid` | `String` | yes |  | Nové unikátne ID, napríklad `UID()`. |\n| `userid` | `String` | yes |  | ID používateľa, neskôr odovzdané do `onread()`. |\n| `expire` | `String|Date` | no |  | Expirácia cookie, napríklad `'1 month'`. |\n| `options` | `Object` | no |  | Voľby cookie. |\n\nReturns: `String` Token.\n\nZavolaj ju po úspešnom prihlásení. Vytvorí token cez `sign()` a zapíše cookie `opt.cookie` s `options` (predvolene `opt.options`). Samotná session sa vytvorí pri nasledujúcej požiadavke cez `onread()`.\n\nExample: Prihlásenie\n```js\nMAIN.session.authcookie($, UID(), user.id, '1 month');\n$.success();\n```\n\n### opt.sign(sessionid, userid)\n\nType: `method`\n\nVytvorí podpísaný token session bez nastavenia cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Unikátne ID session. |\n| `userid` | `String` | yes |  | ID používateľa. |\n\nReturns: `String` Token.\n\nPouži ju pre klientov, ktorí posielajú token v hlavičke z voľby `header` namiesto cookie.\n\nExample: Token pre mobilnú aplikáciu\n```js\nopt.header = 'x-token';\n// in the login action\n$.success(MAIN.session.sign(UID(), user.id));\n```\n\n### opt.logout($)\n\nType: `method`\n\nOdstráni session požiadavky a jej cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object|String` | yes |  | Požiadavka alebo ID session. |\n\nReturns: `Boolean` `true`, keď sa relácia odstránila.\n\n`$` je `$` akcie: odstráni sa session v pamäti aj cookie. S controllerom alebo reťazcom ID session sa odstráni iba session v pamäti; cookie zostane a ďalšia požiadavka používateľa znova načíta. Vráti `true`, keď bola session v pamäti.\n\nExample: Akcia odhlásenia\n```js\nNEWACTION({\n\tid: 'Account/logout',\n\taction: function($) {\n\t\tMAIN.session.logout($);\n\t\t$.success();\n\t}\n});\n```\n\n### opt.update(userid, fn)\n\nType: `method`\n\nZmení cachované dáta každej session používateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | ID používateľa. |\n| `fn` | `Function` | yes |  | `function(data, session)`. |\n\nReturns: `Number` Koľko sessions sa aktualizovalo.\n\nZavolá `fn(data, session)` pre každú session používateľa `userid` v pamäti.\n\nExample: Premenovanie\n```js\nMAIN.session.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### opt.refresh(userid, [exceptsessionid])\n\nType: `method`\n\nZahodí cachované sessions používateľa, takže nasledujúca požiadavka načíta používateľa znova.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | ID používateľa. |\n| `exceptsessionid` | `String` | no |  | Session, ktorá sa ponechá. |\n\nReturns: `Number` Koľko sessions sa zahodilo.\n\nCookies zostanú platné; `onread()` pri nasledujúcej požiadavke načíta čerstvé dáta. Odovzdaj `exceptsessionid`, ak chceš jednu session ponechať v pamäti.\n\nExample: Po zmene oprávnení\n```js\nMAIN.session.refresh(model.userid);\n```\n\n### opt.sessions\n\nType: `property`\n\nSessions v pamäti, podľa ID session.\n\nReturns: `Object`\n\nKaždá položka je `{ sessionid, userid, data, ua, expire }`.\n\nExample: Online používatelia\n```js\nvar count = Object.keys(MAIN.session.sessions).length;\n```\n\n### DEF.onAuthorize\n\nType: `property`\n\nZaregistrovaný autorizačný delegát.\n\nReturns: `Function`\n\nNastavuje ho `AUTH()`. Keď je prázdny, `$.user` sa nikdy nenastaví a flagy `+` a `-` trás sa nekontrolujú, takže trasy `+` sú otvorené pre každého.\n\nExample: Kontrola\n```js\nif (!DEF.onAuthorize)\n\tconsole.warn('No AUTH() delegate');\n```\n\n### ROUTE('+METHOD /url/ ...')\n\nType: `type`\n\nRouta je len pre autorizované požiadavky.\n\nPríznak sa píše pred metódu. Keď delegát požiadavku odmietne, framework hľadá inú routu s rovnakou URL, ktorá zodpovedá (routu `-` alebo routu bez príznaku); ak žiadna nie je, HTTP požiadavka dostane `401` a WebSocket spojenie sa odmietne počas handshaku, takže klient v prehliadači dostane kód zatvorenia `1006`. Pri routách `API` sa príznak riadka kontroluje pre každý endpoint.\n\nExample: Administrácia\n```js\nROUTE('+GET /admin/', dashboard);\nROUTE('+API /api/ orders_list --> Orders/list');\nROUTE('+SOCKET /chat/', chat);\n```\n\n### ROUTE('-METHOD /url/ ...')\n\nType: `type`\n\nRouta je len pre neautorizované požiadavky.\n\nTypické pre stránky prihlásenia a registrácie. S routou `+` na rovnakej URL obslúžiš návštevníkov a používateľov rozdielne.\n\nExample: Rovnaká URL pre oboch\n```js\nROUTE('+GET /', 'app');\nROUTE('-GET /', 'login');\n```\n\n### controller.user\n\nType: `property`\n\nPoužívateľ prijatý delegátom AUTH().\n\nReturns: `Object`\n\n`undefined`, keď požiadavka nie je autorizovaná. Nastavuje sa pre každú routu, keď delegát existuje, vrátane rout bez príznaku, a do akcií sa odovzdáva ako `$.user`.\n\nExample: Čítanie\n```js\nfunction dashboard($) {\n\t$.json({ name: $.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nPoužívateľ požiadavky vnútri akcie.\n\nReturns: `Object`\n\nBerie sa z controllera, ktorý akciu zavolal, alebo z `ACTION().user(obj)`, keď akciu voláš z kódu.\n\nExample: Filter podľa vlastníka\n```js\naction: function($) {\n\tDATA.find('tbl_order').where('userid', $.user.id).callback($);\n}\n```\n\n### controller.authorize([callback])\n\nType: `method`\n\nSpustí delegát AUTH() na požiadanie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, user)`. |\n\nReturns: `Promise` Keď `callback` nie je zadaný.\n\nNastaví `controller.user`, keď delegát požiadavku prijme. Bez `callback` vráti `Promise`, ktorý sa resolvne s používateľom alebo `undefined`; nikdy sa nerejectne.\n\nExample: Vnútri routy\n```js\nasync function detail($) {\n\tvar user = await $.authorize();\n\t$.json({ logged: !!user });\n}\n```\n\n### controller.session\n\nType: `property`\n\nVstavaná session požiadavky.\n\nReturns: `Object`\n\nNastavuje ju `AUTH(options)`: `{ sessionid, userid, data, ua, expire }`. `controller.sessionid` obsahuje ID session a `$.sessionid` ho číta v akciách.\n\nExample: ID session\n```js\nfunction info($) {\n\t$.json({ sessionid: $.sessionid });\n}\n```\n\n### UNAUTHORIZED($, [permission1], [permission2], [...])\n\nType: `method`\n\nSkontroluje oprávnenia používateľa a odpovie 401, keď chýbajú.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie alebo controllera. |\n| `permission` | `String` | no |  | Jedno alebo viac mien oprávnení; stačí ktorékoľvek z nich. |\n\nReturns: `Boolean` `true`, keď používateľ nemá povolenie a požiadavka bola zodpovedaná.\n\nVráti `false`, keď má používateľ `sa` alebo `su`, alebo jedno z oprávnení v `user.permissions` (alebo `user.roles`), čo môže byť pole alebo objekt. Inak zavolá `$.invalid(401)` a vráti `true`. Bez používateľa vráti vždy `true`. `F.unauthorized()` je tá istá funkcia.\n\nExample: Ochrana akcie\n```js\naction: function($) {\n\tif (UNAUTHORIZED($, 'orders'))\n\t\treturn;\n\t$.success();\n}\n```\n\n### $.unauthorized([permission1], [permission2], [...])\n\nType: `method`\n\nUNAUTHORIZED() pre aktuálny $.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `permission` | `String` | no |  | Jedno alebo viac mien oprávnení. |\n\nReturns: `Boolean` `true`, keď používateľ nemá povolenie.\n\nRovnaká kontrola s `$` prevzatým z akcie.\n\nExample: Krátky zápis\n```js\nif ($.unauthorized('orders'))\n\treturn;\n```\n\n### user.permissions\n\nType: `property`\n\nOprávnenia používateľa, ktoré číta UNAUTHORIZED() a oprávnenia akcií.\n\nReturns: `Array|Object`\n\nPole mien alebo objekt s menami ako kľúčmi. Keď `permissions` chýba, použije sa `user.roles`.\n\nExample: Prijatie s rolami\n```js\n$.success({ id: '1', name: 'Anna', roles: ['orders', 'products'] });\n```\n\n### user.sa\n\nType: `property`\n\nOznačí super admina.\n\nReturns: `Boolean`\n\nPoužívateľ s `sa` alebo `su` prejde `UNAUTHORIZED()` aj `permissions` akcií a je jediný používateľ povolený akciami so `sa: true`.\n\nExample: Admin\n```js\n$.success({ id: '1', name: 'Root', sa: true });\n```\n\n### new User([obj])\n\nType: `class`\n\nTrieda pre objekty používateľov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Kľúče používateľa. |\n\nReturns: `User`\n\nGlobálna trieda. Konštruktor skopíruje každý kľúč `obj` do novej inštancie, takže `new User({ id: '1', sa: true })` má `id` a `sa`. Použi ju pre identitu kódu, ktorý nie je požiadavka, napríklad jobu alebo skriptu, a over ju cez `instanceof User`. Framework nemení používateľov, ktorých vracia tvoj delegát `AUTH()`, na inštancie `User`.\n\nExample: Používateľ pre job\n```js\nNEWACTION('reports_daily', {\n\tsa: true,\n\taction: function($) {\n\t\t$.success($.user.name);\n\t}\n});\n\nvar scheduler = new User({ id: 'cron', name: 'Scheduler', sa: true });\nACTION('reports_daily').user(scheduler).callback(console.log);\n// { success: true, value: 'Scheduler' }\n```\n\n### NEWACTION({ user: true })\n\nType: `config`\n\nObmedzí akciu na autorizované (true) alebo neautorizované (false) požiadavky.\n\nKeď podmienka zlyhá, akcia odpovie `401`.\n\nExample: Len používatelia\n```js\nNEWACTION({\n\tid: 'Account/profile',\n\tuser: true,\n\taction: function($) {\n\t\t$.success($.user);\n\t}\n});\n```\n\n### NEWACTION({ sa: true })\n\nType: `config`\n\nObmedzí akciu na super adminov.\n\nPoužívateľ musí mať `sa` alebo `su`, inak akcia odpovie `401`. `su: true` funguje rovnako.\n\nExample: Akcia admina\n```js\nNEWACTION({\n\tid: 'Users/remove',\n\tsa: true,\n\tparams: '*id:UID',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### NEWACTION({ permissions: 'name1,name2' })\n\nType: `config`\n\nObmedzí akciu na používateľov s ktorýmkoľvek z oprávnení.\n\nReťazec oddelený čiarkami alebo bodkočiarkami, alebo pole. Kontrolu robí `UNAUTHORIZED()`, takže super admini prejdú vždy.\n\nExample: Oprávnenia\n```js\nNEWACTION({\n\tid: 'Orders/list',\n\tpermissions: 'orders,admin',\n\taction: function($) {\n\t\t$.success([]);\n\t}\n});\n```\n\n### BLOCKED($, [limit], [expire])\n\nType: `method`\n\nPočíta pokusy na IP adresu a oznámi, kedy je adresa zablokovaná.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie alebo controllera. |\n| `limit` | `Number|null` | no | `5` | Povolené pokusy; `null` alebo `-1` resetne počítadlo. |\n| `expire` | `String` | no | `'15 minutes'` | Ako dlho počítadlo žije. |\n\nReturns: `Boolean` `true`, keď je zablokovaná.\n\nKaždé volanie započíta jeden pokus pre `$.ip`. Vráti `true`, keď bola adresa započítaná viac ako `limit`-krát. Počítadlo začína prvým volaním a odstráni sa po `expire` (kontroluje sa každú minútu). `BLOCKED($, null)` alebo `BLOCKED($, -1)` ho odstráni okamžite.\n\nExample: Ochrana prihlásenia\n```js\nif (BLOCKED($, 10)) {\n\t$.invalid(401);\n\treturn;\n}\n// ... the password is correct\nBLOCKED($, null);\n```\n","entries":[{"type":"delegate","name":"AUTH(callback)","signature":"AUTH(callback)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"opt.onread","signature":"opt.onread = function(meta, callback, $)","since":"","deprecated":false},{"type":"delegate","name":"opt.onsession","signature":"opt.onsession = function(session, $, [isnew])","since":"","deprecated":false},{"type":"delegate","name":"opt.onauthorize","signature":"opt.onauthorize = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.onfree","signature":"opt.onfree = function(meta)","since":"","deprecated":false},{"type":"delegate","name":"opt.onlogout","signature":"opt.onlogout = function(session)","since":"","deprecated":false},{"type":"delegate","name":"opt.onddos","signature":"opt.onddos = function($)","since":"","deprecated":false},{"type":"delegate","name":"opt.localize","signature":"opt.localize = function(user, controller)","since":"","deprecated":false},{"type":"method","name":"opt.authcookie($, sessionid, userid, [expire], [options])","signature":"opt.authcookie($, sessionid, userid, [expire], [options])","since":"","deprecated":false},{"type":"method","name":"opt.sign(sessionid, userid)","signature":"opt.sign(sessionid, userid)","since":"","deprecated":false},{"type":"method","name":"opt.logout($)","signature":"opt.logout($)","since":"","deprecated":false},{"type":"method","name":"opt.update(userid, fn)","signature":"opt.update(userid, fn)","since":"","deprecated":false},{"type":"method","name":"opt.refresh(userid, [exceptsessionid])","signature":"opt.refresh(userid, [exceptsessionid])","since":"","deprecated":false},{"type":"property","name":"opt.sessions","signature":"opt.sessions","since":"","deprecated":false},{"type":"property","name":"DEF.onAuthorize","signature":"DEF.onAuthorize","since":"","deprecated":false},{"type":"type","name":"Route flag +","signature":"ROUTE('+METHOD /url/ ...')","since":"","deprecated":false},{"type":"type","name":"Route flag -","signature":"ROUTE('-METHOD /url/ ...')","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"method","name":"controller.authorize([callback])","signature":"controller.authorize([callback])","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED($, [permission...])","signature":"UNAUTHORIZED($, [permission1], [permission2], [...])","since":"","deprecated":false},{"type":"method","name":"$.unauthorized([permission...])","signature":"$.unauthorized([permission1], [permission2], [...])","since":"","deprecated":false},{"type":"property","name":"user.permissions","signature":"user.permissions","since":"","deprecated":false},{"type":"property","name":"user.sa","signature":"user.sa","since":"","deprecated":false},{"type":"class","name":"User","signature":"new User([obj])","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ user })","signature":"NEWACTION({ user: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ sa })","signature":"NEWACTION({ sa: true })","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ permissions })","signature":"NEWACTION({ permissions: 'name1,name2' })","since":"","deprecated":false},{"type":"method","name":"BLOCKED($, [limit], [expire])","signature":"BLOCKED($, [limit], [expire])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafJPN2iD61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/encryption/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Encryption","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() and the keys $crypto, $cryptoiv and secret.","markdown":"---\ntitle: Encryption\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/encryption/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Encryption\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() and the keys $crypto, $cryptoiv and secret.\n\nThe functions that encrypt and decrypt values, and the keys that choose the cipher. The guide [Encryption](../../guides/encryption/) explains how they work together with examples.\n\n## API\n\n### ENCRYPT(value, key, [unique])\n\nType: `method`\n\nEncrypts a value into a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Any JSON-serializable value. |\n| `key` | `String` | yes |  | A key that must also be used to decrypt. |\n| `unique` | `Boolean` | no |  | A random output for the same input. |\n\nReturns: `String` The encrypted value.\n\n`value` is serialized to JSON; `null` or `undefined` gives an empty string. The built-in algorithm uses `CONF.secret` together with `key`; with `unique` the output differs on every call. When `CONF.$crypto` is set, the value is encrypted with that Node.js cipher and `CONF.$cryptoiv`, and `key` must have the byte length of the cipher (`unique` is not used). `F.encrypt()` is the same function.\n\nExample: Reset link\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n$.success(token);\n```\n\n### DECRYPT(value, key, [tojson])\n\nType: `method`\n\nDecrypts a string made by ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The encrypted string. |\n| `key` | `String` | yes |  | The key used by `ENCRYPT()`. |\n| `tojson` | `Boolean` | no | `true` | Parse the result as JSON. |\n\nReturns: `Object|String` The value, or `null`.\n\nDecrypts a string made by `ENCRYPT()` with the same `key`. With `tojson` (default) the result is parsed as JSON; a string that is not valid, was made with another key or does not contain JSON returns `null`. With `tojson: false` you get the decrypted text. When `CONF.$crypto` is set, the value is decrypted with that Node.js cipher, and a value with an odd number of hex characters returns `null` at once. `F.decrypt()` is the same function.\n\nExample: Verify a token\n```js\nvar data = DECRYPT($.query.token, 'reset');\nif (!data || data.expire < NOW) {\n\t$.invalid(400);\n\treturn;\n}\n```\n\n### ENCRYPTREQ($, value, key, [strict])\n\nType: `method`\n\nEncrypts a value bound to the client of the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action or a controller. |\n| `value` | `Object` | yes |  | Any JSON-serializable value. |\n| `key` | `String` | yes |  | The key. |\n| `strict` | `Boolean` | no |  | Bind the value to the IP address too. |\n\nReturns: `String` The encrypted value.\n\nStores a hash of the `User-Agent` header with the value, and with `strict` also the IP address. `DECRYPTREQ()` returns the value only for the same client. `F.encryptreq()` is the same function.\n\nExample: Download token\n```js\nvar token = ENCRYPTREQ($, { file: model.id }, 'download', true);\n$.success(token);\n```\n\n### DECRYPTREQ($, value, key)\n\nType: `method`\n\nDecrypts a value made by ENCRYPTREQ() for the same client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action or a controller. |\n| `value` | `String` | yes |  | The encrypted string. |\n| `key` | `String` | yes |  | The key used by `ENCRYPTREQ()`. |\n\nReturns: `Object` The value, or `undefined`.\n\nReturns `undefined` when the value is empty, invalid, or comes from another browser (or another IP address for a strict value). `F.decryptreq()` is the same function.\n\nExample: Check the token\n```js\nvar data = DECRYPTREQ($, $.query.token, 'download');\nif (!data) {\n\t$.invalid(401);\n\treturn;\n}\n```\n\n### $crypto : aes-256-cbc\n\nType: `config`\n\nA Node.js cipher for ENCRYPT() and DECRYPT().\n\nReturns: `String`\n\nAny algorithm of `crypto.createCipheriv()`. Without it the built-in algorithm is used. Keys must then have the byte length of the cipher (32 characters for `aes-256-cbc`).\n\nExample: Config\n```js\n// /config\n$crypto      : aes-256-cbc\n$cryptoiv    : 00112233445566778899aabbccddeeff\n```\n\n### $cryptoiv : <hex or base64>\n\nType: `config`\n\nThe initialization vector for $crypto.\n\nReturns: `Buffer`\n\nRead as base64 when it contains upper-case letters, `=`, `/` or `+`, otherwise as hex. The default is the first 16 bytes of the application hash.\n\nExample: Config\n```js\n$cryptoiv : 00112233445566778899aabbccddeeff\n```\n\n### secret : <string>\n\nType: `config`\n\nThe application secret used by ENCRYPT() and DECRYPT().\n\nReturns: `String`\n\nIt is mixed into the key of the built-in algorithm, so values encrypted with another secret do not decrypt. It has no default (`CONF.secret` is `undefined`), so set your own; the same secret keeps tokens valid across servers.\n\nExample: Config\n```js\nsecret : a-long-random-string\n```\n","entries":[{"type":"method","name":"ENCRYPT(value, key, [unique])","signature":"ENCRYPT(value, key, [unique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT(value, key, [tojson])","signature":"DECRYPT(value, key, [tojson])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ($, value, key, [strict])","signature":"ENCRYPTREQ($, value, key, [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ($, value, key)","signature":"DECRYPTREQ($, value, key)","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : aes-256-cbc","since":"","deprecated":false},{"type":"config","name":"$cryptoiv","signature":"$cryptoiv : <hex or base64>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <string>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJPN2iD61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/encryption/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Verschlüsselung","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() und die Schlüssel $crypto, $cryptoiv und secret.","markdown":"---\ntitle: \"Verschlüsselung\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/encryption/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Verschlüsselung\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() und die Schlüssel $crypto, $cryptoiv und secret.\n\nDie Funktionen, die Werte ver- und entschlüsseln, und die Schlüssel, die die Chiffre wählen. Die Anleitung [Verschlüsselung](../../guides/encryption/) erklärt mit Beispielen, wie sie zusammenspielen.\n\n## API\n\n### ENCRYPT(value, key, [unique])\n\nType: `method`\n\nVerschlüsselt einen Wert in einen String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Ein beliebiger JSON-serialisierbarer Wert. |\n| `key` | `String` | yes |  | Ein Schlüssel, der auch zum Entschlüsseln verwendet werden muss. |\n| `unique` | `Boolean` | no |  | Eine zufällige Ausgabe für dieselbe Eingabe. |\n\nReturns: `String` Der verschlüsselte Wert.\n\n`value` wird zu JSON serialisiert; `null` oder `undefined` ergibt einen leeren String. Der eingebaute Algorithmus verwendet `CONF.secret` zusammen mit `key`; mit `unique` unterscheidet sich die Ausgabe bei jedem Aufruf. Wenn `CONF.$crypto` gesetzt ist, wird der Wert mit dieser Node.js-Chiffre und `CONF.$cryptoiv` verschlüsselt, und `key` muss die Bytelänge der Chiffre haben (`unique` wird nicht verwendet). `F.encrypt()` ist dieselbe Funktion.\n\nExample: Link zum Zurücksetzen\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n$.success(token);\n```\n\n### DECRYPT(value, key, [tojson])\n\nType: `method`\n\nEntschlüsselt einen von ENCRYPT() erzeugten String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der verschlüsselte String. |\n| `key` | `String` | yes |  | Der von `ENCRYPT()` verwendete Schlüssel. |\n| `tojson` | `Boolean` | no | `true` | Das Ergebnis als JSON parsen. |\n\nReturns: `Object|String` Der Wert oder `null`.\n\nEntschlüsselt einen von `ENCRYPT()` erzeugten String mit demselben `key`. Mit `tojson` (Standard) wird das Ergebnis als JSON geparst; ein String, der ungültig ist, mit einem anderen Schlüssel erzeugt wurde oder kein JSON enthält, gibt `null` zurück. Mit `tojson: false` erhältst du den entschlüsselten Text. Wenn `CONF.$crypto` gesetzt ist, wird der Wert mit dieser Node.js-Chiffre entschlüsselt, und ein Wert mit einer ungeraden Anzahl von Hex-Zeichen gibt sofort `null` zurück. `F.decrypt()` ist dieselbe Funktion.\n\nExample: Ein Token prüfen\n```js\nvar data = DECRYPT($.query.token, 'reset');\nif (!data || data.expire < NOW) {\n\t$.invalid(400);\n\treturn;\n}\n```\n\n### ENCRYPTREQ($, value, key, [strict])\n\nType: `method`\n\nVerschlüsselt einen Wert, der an den Client des Requests gebunden ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$` einer Aktion oder eines Controllers. |\n| `value` | `Object` | yes |  | Ein beliebiger JSON-serialisierbarer Wert. |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `strict` | `Boolean` | no |  | Den Wert auch an die IP-Adresse binden. |\n\nReturns: `String` Der verschlüsselte Wert.\n\nSpeichert mit dem Wert einen Hash des Headers `User-Agent` und mit `strict` zusätzlich die IP-Adresse. `DECRYPTREQ()` gibt den Wert nur für denselben Client zurück. `F.encryptreq()` ist dieselbe Funktion.\n\nExample: Download-Token\n```js\nvar token = ENCRYPTREQ($, { file: model.id }, 'download', true);\n$.success(token);\n```\n\n### DECRYPTREQ($, value, key)\n\nType: `method`\n\nEntschlüsselt einen von ENCRYPTREQ() erzeugten Wert für denselben Client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$` einer Aktion oder eines Controllers. |\n| `value` | `String` | yes |  | Der verschlüsselte String. |\n| `key` | `String` | yes |  | Der von `ENCRYPTREQ()` verwendete Schlüssel. |\n\nReturns: `Object` Der Wert oder `undefined`.\n\nGibt `undefined` zurück, wenn der Wert leer oder ungültig ist oder von einem anderen Browser stammt (bzw. bei einem strikten Wert von einer anderen IP-Adresse). `F.decryptreq()` ist dieselbe Funktion.\n\nExample: Das Token prüfen\n```js\nvar data = DECRYPTREQ($, $.query.token, 'download');\nif (!data) {\n\t$.invalid(401);\n\treturn;\n}\n```\n\n### $crypto : aes-256-cbc\n\nType: `config`\n\nEine Node.js-Chiffre für ENCRYPT() und DECRYPT().\n\nReturns: `String`\n\nEin beliebiger Algorithmus von `crypto.createCipheriv()`. Ohne ihn wird der eingebaute Algorithmus verwendet. Schlüssel müssen dann die Bytelänge der Chiffre haben (32 Zeichen für `aes-256-cbc`).\n\nExample: Config\n```js\n// /config\n$crypto      : aes-256-cbc\n$cryptoiv    : 00112233445566778899aabbccddeeff\n```\n\n### $cryptoiv : <hex or base64>\n\nType: `config`\n\nDer Initialisierungsvektor für $crypto.\n\nReturns: `Buffer`\n\nWird als Base64 gelesen, wenn er Großbuchstaben, `=`, `/` oder `+` enthält, sonst als Hex. Standard sind die ersten 16 Bytes des Anwendungs-Hashes.\n\nExample: Config\n```js\n$cryptoiv : 00112233445566778899aabbccddeeff\n```\n\n### secret : <string>\n\nType: `config`\n\nDas Secret der Anwendung, das ENCRYPT() und DECRYPT() verwenden.\n\nReturns: `String`\n\nEs fließt in den Schlüssel des eingebauten Algorithmus ein, daher lassen sich mit einem anderen Secret verschlüsselte Werte nicht entschlüsseln. Es hat keinen Standardwert (`CONF.secret` ist `undefined`), setze also dein eigenes; dasselbe Secret hält Tokens über Server hinweg gültig.\n\nExample: Konfiguration\n```js\nsecret : a-long-random-string\n```\n","entries":[{"type":"method","name":"ENCRYPT(value, key, [unique])","signature":"ENCRYPT(value, key, [unique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT(value, key, [tojson])","signature":"DECRYPT(value, key, [tojson])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ($, value, key, [strict])","signature":"ENCRYPTREQ($, value, key, [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ($, value, key)","signature":"DECRYPTREQ($, value, key)","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : aes-256-cbc","since":"","deprecated":false},{"type":"config","name":"$cryptoiv","signature":"$cryptoiv : <hex or base64>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <string>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJPN2iD61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/encryption/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Cifrado","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() y las claves $crypto, $cryptoiv y secret.","markdown":"---\ntitle: Cifrado\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/encryption/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Cifrado\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() y las claves $crypto, $cryptoiv y secret.\n\nLas funciones que cifran y descifran valores, y las claves que eligen el cifrador. La guía [Cifrado](../../guides/encryption/) explica cómo funcionan juntas, con ejemplos.\n\n## API\n\n### ENCRYPT(value, key, [unique])\n\nType: `method`\n\nCifra un valor en una cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Cualquier valor serializable en JSON. |\n| `key` | `String` | yes |  | Una clave que también se debe usar para descifrar. |\n| `unique` | `Boolean` | no |  | Una salida aleatoria para la misma entrada. |\n\nReturns: `String` El valor cifrado.\n\n`value` se serializa a JSON; `null` o `undefined` da una cadena vacía. El algoritmo integrado usa `CONF.secret` junto con `key`; con `unique` la salida es distinta en cada llamada. Cuando `CONF.$crypto` está establecido, el valor se cifra con ese cifrado de Node.js y `CONF.$cryptoiv`, y `key` debe tener la longitud en bytes del cifrado (`unique` no se usa). `F.encrypt()` es la misma función.\n\nExample: Enlace de restablecimiento\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n$.success(token);\n```\n\n### DECRYPT(value, key, [tojson])\n\nType: `method`\n\nDescifra un string creado por ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El string cifrado. |\n| `key` | `String` | yes |  | La clave usada por `ENCRYPT()`. |\n| `tojson` | `Boolean` | no | `true` | Parsear el resultado como JSON. |\n\nReturns: `Object|String` El valor, o `null`.\n\nDescifra un string creado por `ENCRYPT()` con la misma `key`. Con `tojson` (por defecto) el resultado se parsea como JSON; un string que no es válido, se creó con otra clave o no contiene JSON devuelve `null`. Con `tojson: false` obtienes el texto descifrado. Cuando `CONF.$crypto` está establecido, el valor se descifra con ese cifrado de Node.js, y un valor con un número impar de caracteres hexadecimales devuelve `null` de inmediato. `F.decrypt()` es la misma función.\n\nExample: Verificar un token\n```js\nvar data = DECRYPT($.query.token, 'reset');\nif (!data || data.expire < NOW) {\n\t$.invalid(400);\n\treturn;\n}\n```\n\n### ENCRYPTREQ($, value, key, [strict])\n\nType: `method`\n\nCifra un valor vinculado al cliente de la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción o de un controlador. |\n| `value` | `Object` | yes |  | Cualquier valor serializable en JSON. |\n| `key` | `String` | yes |  | La clave. |\n| `strict` | `Boolean` | no |  | Vincula el valor también a la dirección IP. |\n\nReturns: `String` El valor cifrado.\n\nGuarda un hash de la cabecera `User-Agent` junto con el valor y, con `strict`, también la dirección IP. `DECRYPTREQ()` devuelve el valor solo para el mismo cliente. `F.encryptreq()` es la misma función.\n\nExample: Token de descarga\n```js\nvar token = ENCRYPTREQ($, { file: model.id }, 'download', true);\n$.success(token);\n```\n\n### DECRYPTREQ($, value, key)\n\nType: `method`\n\nDescifra un valor generado por ENCRYPTREQ() para el mismo cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción o de un controlador. |\n| `value` | `String` | yes |  | La cadena cifrada. |\n| `key` | `String` | yes |  | La clave que usó `ENCRYPTREQ()`. |\n\nReturns: `Object` El valor, o `undefined`.\n\nDevuelve `undefined` cuando el valor está vacío, no es válido o viene de otro navegador (o de otra dirección IP en el caso de un valor strict). `F.decryptreq()` es la misma función.\n\nExample: Comprobar el token\n```js\nvar data = DECRYPTREQ($, $.query.token, 'download');\nif (!data) {\n\t$.invalid(401);\n\treturn;\n}\n```\n\n### $crypto : aes-256-cbc\n\nType: `config`\n\nUn cifrado de Node.js para ENCRYPT() y DECRYPT().\n\nReturns: `String`\n\nCualquier algoritmo de `crypto.createCipheriv()`. Sin él se usa el algoritmo integrado. En ese caso, las claves deben tener la longitud en bytes del cifrado (32 caracteres para `aes-256-cbc`).\n\nExample: Config\n```js\n// /config\n$crypto      : aes-256-cbc\n$cryptoiv    : 00112233445566778899aabbccddeeff\n```\n\n### $cryptoiv : <hex or base64>\n\nType: `config`\n\nEl vector de inicialización para $crypto.\n\nReturns: `Buffer`\n\nSe lee como base64 cuando contiene letras mayúsculas, `=`, `/` o `+`; si no, como hex. El valor por defecto son los primeros 16 bytes del hash de la aplicación.\n\nExample: Config\n```js\n$cryptoiv : 00112233445566778899aabbccddeeff\n```\n\n### secret : <string>\n\nType: `config`\n\nEl secreto de la aplicación que usan ENCRYPT() y DECRYPT().\n\nReturns: `String`\n\nSe mezcla con la clave del algoritmo integrado, así que los valores cifrados con otro secreto no se descifran. No tiene valor por defecto (`CONF.secret` es `undefined`), así que establece el tuyo; el mismo secreto mantiene los tokens válidos entre servidores.\n\nExample: Config\n```js\nsecret : a-long-random-string\n```\n","entries":[{"type":"method","name":"ENCRYPT(value, key, [unique])","signature":"ENCRYPT(value, key, [unique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT(value, key, [tojson])","signature":"DECRYPT(value, key, [tojson])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ($, value, key, [strict])","signature":"ENCRYPTREQ($, value, key, [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ($, value, key)","signature":"DECRYPTREQ($, value, key)","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : aes-256-cbc","since":"","deprecated":false},{"type":"config","name":"$cryptoiv","signature":"$cryptoiv : <hex or base64>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <string>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJPN2iD61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/encryption/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Chiffrement","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() et les clés $crypto, $cryptoiv et secret.","markdown":"---\ntitle: Chiffrement\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/encryption/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Chiffrement\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() et les clés $crypto, $cryptoiv et secret.\n\nLes fonctions qui chiffrent et déchiffrent des valeurs, et les clés qui choisissent l'algorithme de chiffrement. Le guide [Chiffrement](../../guides/encryption/) explique comment elles fonctionnent ensemble, avec des exemples.\n\n## API\n\n### ENCRYPT(value, key, [unique])\n\nType: `method`\n\nChiffre une valeur en chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | N'importe quelle valeur sérialisable en JSON. |\n| `key` | `String` | yes |  | Une clé qui doit aussi être utilisée pour déchiffrer. |\n| `unique` | `Boolean` | no |  | Une sortie aléatoire pour la même entrée. |\n\nReturns: `String` La valeur chiffrée.\n\n`value` est sérialisée en JSON ; `null` ou `undefined` donne une chaîne vide. L'algorithme intégré utilise `CONF.secret` avec `key` ; avec `unique`, la sortie diffère à chaque appel. Lorsque `CONF.$crypto` est défini, la valeur est chiffrée avec cet algorithme Node.js et `CONF.$cryptoiv`, et `key` doit avoir la longueur en octets de l'algorithme (`unique` n'est pas utilisé). `F.encrypt()` est la même fonction.\n\nExample: Lien de réinitialisation\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n$.success(token);\n```\n\n### DECRYPT(value, key, [tojson])\n\nType: `method`\n\nDéchiffre une chaîne produite par ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La chaîne chiffrée. |\n| `key` | `String` | yes |  | La clé utilisée par `ENCRYPT()`. |\n| `tojson` | `Boolean` | no | `true` | Analyser le résultat comme JSON. |\n\nReturns: `Object|String` La valeur, ou `null`.\n\nDéchiffre une chaîne produite par `ENCRYPT()` avec la même `key`. Avec `tojson` (par défaut), le résultat est analysé comme JSON ; une chaîne invalide, produite avec une autre clé ou ne contenant pas de JSON renvoie `null`. Avec `tojson: false`, tu obtiens le texte déchiffré. Quand `CONF.$crypto` est défini, la valeur est déchiffrée avec ce chiffrement Node.js, et une valeur avec un nombre impair de caractères hexadécimaux renvoie immédiatement `null`. `F.decrypt()` est la même fonction.\n\nExample: Vérifier un token\n```js\nvar data = DECRYPT($.query.token, 'reset');\nif (!data || data.expire < NOW) {\n\t$.invalid(400);\n\treturn;\n}\n```\n\n### ENCRYPTREQ($, value, key, [strict])\n\nType: `method`\n\nChiffre une valeur liée au client de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action ou d'un contrôleur. |\n| `value` | `Object` | yes |  | N'importe quelle valeur sérialisable en JSON. |\n| `key` | `String` | yes |  | La clé. |\n| `strict` | `Boolean` | no |  | Lier aussi la valeur à l'adresse IP. |\n\nReturns: `String` La valeur chiffrée.\n\nStocke avec la valeur un hash de l'en-tête `User-Agent`, et avec `strict` également l'adresse IP. `DECRYPTREQ()` ne retourne la valeur que pour le même client. `F.encryptreq()` est la même fonction.\n\nExample: Jeton de téléchargement\n```js\nvar token = ENCRYPTREQ($, { file: model.id }, 'download', true);\n$.success(token);\n```\n\n### DECRYPTREQ($, value, key)\n\nType: `method`\n\nDéchiffre une valeur produite par ENCRYPTREQ() pour le même client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action ou d'un contrôleur. |\n| `value` | `String` | yes |  | La chaîne chiffrée. |\n| `key` | `String` | yes |  | La clé utilisée par `ENCRYPTREQ()`. |\n\nReturns: `Object` La valeur, ou `undefined`.\n\nRetourne `undefined` lorsque la valeur est vide, invalide, ou provient d'un autre navigateur (ou d'une autre adresse IP pour une valeur stricte). `F.decryptreq()` est la même fonction.\n\nExample: Vérifier le jeton\n```js\nvar data = DECRYPTREQ($, $.query.token, 'download');\nif (!data) {\n\t$.invalid(401);\n\treturn;\n}\n```\n\n### $crypto : aes-256-cbc\n\nType: `config`\n\nUn algorithme de chiffrement Node.js pour ENCRYPT() et DECRYPT().\n\nReturns: `String`\n\nN'importe quel algorithme de `crypto.createCipheriv()`. Sans lui, l'algorithme intégré est utilisé. Les clés doivent alors avoir la longueur en octets de l'algorithme (32 caractères pour `aes-256-cbc`).\n\nExample: Config\n```js\n// /config\n$crypto      : aes-256-cbc\n$cryptoiv    : 00112233445566778899aabbccddeeff\n```\n\n### $cryptoiv : <hex or base64>\n\nType: `config`\n\nLe vecteur d'initialisation pour $crypto.\n\nReturns: `Buffer`\n\nLu en base64 lorsqu'il contient des majuscules, `=`, `/` ou `+`, sinon en hexadécimal. La valeur par défaut est constituée des 16 premiers octets du hash de l'application.\n\nExample: Config\n```js\n$cryptoiv : 00112233445566778899aabbccddeeff\n```\n\n### secret : <string>\n\nType: `config`\n\nLe secret de l'application utilisé par ENCRYPT() et DECRYPT().\n\nReturns: `String`\n\nIl est mélangé à la clé de l'algorithme intégré : les valeurs chiffrées avec un autre secret ne se déchiffrent donc pas. Il n'a pas de valeur par défaut (`CONF.secret` vaut `undefined`), définis donc le tien ; le même secret garde les jetons valides d'un serveur à l'autre.\n\nExample: Config\n```js\nsecret : a-long-random-string\n```\n","entries":[{"type":"method","name":"ENCRYPT(value, key, [unique])","signature":"ENCRYPT(value, key, [unique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT(value, key, [tojson])","signature":"DECRYPT(value, key, [tojson])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ($, value, key, [strict])","signature":"ENCRYPTREQ($, value, key, [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ($, value, key)","signature":"DECRYPTREQ($, value, key)","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : aes-256-cbc","since":"","deprecated":false},{"type":"config","name":"$cryptoiv","signature":"$cryptoiv : <hex or base64>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <string>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJPN2iD61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/encryption/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Cifratura","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() e le chiavi $crypto, $cryptoiv e secret.","markdown":"---\ntitle: Cifratura\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/encryption/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Cifratura\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() e le chiavi $crypto, $cryptoiv e secret.\n\nLe funzioni che cifrano e decifrano i valori e le chiavi che scelgono il cifrario. La guida [Cifratura](../../guides/encryption/) spiega come funzionano insieme, con esempi.\n\n## API\n\n### ENCRYPT(value, key, [unique])\n\nType: `method`\n\nCifra un valore in una stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Qualsiasi valore serializzabile in JSON. |\n| `key` | `String` | yes |  | Una chiave che deve essere usata anche per decifrare. |\n| `unique` | `Boolean` | no |  | Un output casuale per lo stesso input. |\n\nReturns: `String` Il valore cifrato.\n\n`value` viene serializzato in JSON; `null` o `undefined` dà una stringa vuota. L'algoritmo integrato usa `CONF.secret` insieme a `key`; con `unique` l'output è diverso a ogni chiamata. Quando `CONF.$crypto` è impostato, il valore viene cifrato con quel cifrario Node.js e `CONF.$cryptoiv`, e `key` deve avere la lunghezza in byte del cifrario (`unique` non viene usato). `F.encrypt()` è la stessa funzione.\n\nExample: Link di reset\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n$.success(token);\n```\n\n### DECRYPT(value, key, [tojson])\n\nType: `method`\n\nDecifra una stringa creata da ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La stringa cifrata. |\n| `key` | `String` | yes |  | La chiave usata da `ENCRYPT()`. |\n| `tojson` | `Boolean` | no | `true` | Analizza il risultato come JSON. |\n\nReturns: `Object|String` Il valore, oppure `null`.\n\nDecifra una stringa creata da `ENCRYPT()` con la stessa `key`. Con `tojson` (predefinito) il risultato viene analizzato come JSON; una stringa non valida, creata con un'altra chiave o che non contiene JSON restituisce `null`. Con `tojson: false` ottieni il testo decifrato. Quando `CONF.$crypto` è impostato, il valore viene decifrato con quel cipher di Node.js, e un valore con un numero dispari di caratteri esadecimali restituisce subito `null`. `F.decrypt()` è la stessa funzione.\n\nExample: Verificare un token\n```js\nvar data = DECRYPT($.query.token, 'reset');\nif (!data || data.expire < NOW) {\n\t$.invalid(400);\n\treturn;\n}\n```\n\n### ENCRYPTREQ($, value, key, [strict])\n\nType: `method`\n\nCifra un valore legato al client della richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione o di un controller. |\n| `value` | `Object` | yes |  | Qualsiasi valore serializzabile in JSON. |\n| `key` | `String` | yes |  | La chiave. |\n| `strict` | `Boolean` | no |  | Lega il valore anche all'indirizzo IP. |\n\nReturns: `String` Il valore cifrato.\n\nSalva un hash dell'header `User-Agent` insieme al valore, e con `strict` anche l'indirizzo IP. `DECRYPTREQ()` restituisce il valore solo per lo stesso client. `F.encryptreq()` è la stessa funzione.\n\nExample: Token di download\n```js\nvar token = ENCRYPTREQ($, { file: model.id }, 'download', true);\n$.success(token);\n```\n\n### DECRYPTREQ($, value, key)\n\nType: `method`\n\nDecifra un valore creato da ENCRYPTREQ() per lo stesso client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione o di un controller. |\n| `value` | `String` | yes |  | La stringa cifrata. |\n| `key` | `String` | yes |  | La chiave usata da `ENCRYPTREQ()`. |\n\nReturns: `Object` Il valore, oppure `undefined`.\n\nRestituisce `undefined` quando il valore è vuoto, non valido, o proviene da un altro browser (o da un altro indirizzo IP per un valore strict). `F.decryptreq()` è la stessa funzione.\n\nExample: Controllare il token\n```js\nvar data = DECRYPTREQ($, $.query.token, 'download');\nif (!data) {\n\t$.invalid(401);\n\treturn;\n}\n```\n\n### $crypto : aes-256-cbc\n\nType: `config`\n\nUn cifrario Node.js per ENCRYPT() e DECRYPT().\n\nReturns: `String`\n\nQualsiasi algoritmo di `crypto.createCipheriv()`. Senza di esso viene usato l'algoritmo integrato. Le chiavi devono allora avere la lunghezza in byte del cifrario (32 caratteri per `aes-256-cbc`).\n\nExample: Config\n```js\n// /config\n$crypto      : aes-256-cbc\n$cryptoiv    : 00112233445566778899aabbccddeeff\n```\n\n### $cryptoiv : <hex or base64>\n\nType: `config`\n\nIl vettore di inizializzazione per $crypto.\n\nReturns: `Buffer`\n\nLetto come base64 quando contiene lettere maiuscole, `=`, `/` o `+`, altrimenti come hex. Il valore predefinito sono i primi 16 byte dell'hash dell'applicazione.\n\nExample: Config\n```js\n$cryptoiv : 00112233445566778899aabbccddeeff\n```\n\n### secret : <string>\n\nType: `config`\n\nIl segreto dell'applicazione usato da ENCRYPT() e DECRYPT().\n\nReturns: `String`\n\nViene mescolato nella chiave dell'algoritmo integrato, quindi i valori cifrati con un altro segreto non vengono decifrati. Non ha un valore predefinito (`CONF.secret` è `undefined`), quindi imposta il tuo; lo stesso segreto mantiene validi i token tra server diversi.\n\nExample: Config\n```js\nsecret : a-long-random-string\n```\n","entries":[{"type":"method","name":"ENCRYPT(value, key, [unique])","signature":"ENCRYPT(value, key, [unique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT(value, key, [tojson])","signature":"DECRYPT(value, key, [tojson])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ($, value, key, [strict])","signature":"ENCRYPTREQ($, value, key, [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ($, value, key)","signature":"DECRYPTREQ($, value, key)","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : aes-256-cbc","since":"","deprecated":false},{"type":"config","name":"$cryptoiv","signature":"$cryptoiv : <hex or base64>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <string>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJPN2iD61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/encryption/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Šifrovanie","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() a kľúče $crypto, $cryptoiv a secret.","markdown":"---\ntitle: \"Šifrovanie\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/encryption/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Šifrovanie\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() a kľúče $crypto, $cryptoiv a secret.\n\nFunkcie, ktoré šifrujú a dešifrujú hodnoty, a kľúče, ktoré vyberajú šifru. Ako spolu fungujú, vysvetľuje s príkladmi návod [Šifrovanie](../../guides/encryption/).\n\n## API\n\n### ENCRYPT(value, key, [unique])\n\nType: `method`\n\nZašifruje hodnotu do reťazca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Ľubovoľná hodnota serializovateľná do JSON. |\n| `key` | `String` | yes |  | Kľúč, ktorý sa musí použiť aj na dešifrovanie. |\n| `unique` | `Boolean` | no |  | Náhodný výstup pre rovnaký vstup. |\n\nReturns: `String` Zašifrovaná hodnota.\n\n`value` sa serializuje do JSON; `null` alebo `undefined` dá prázdny reťazec. Vstavaný algoritmus používa `CONF.secret` spolu s `key`; s `unique` sa výstup líši pri každom volaní. Keď je nastavené `CONF.$crypto`, hodnota sa zašifruje touto Node.js šifrou a `CONF.$cryptoiv` a `key` musí mať bajtovú dĺžku šifry (`unique` sa nepoužíva). `F.encrypt()` je tá istá funkcia.\n\nExample: Odkaz na reset\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n$.success(token);\n```\n\n### DECRYPT(value, key, [tojson])\n\nType: `method`\n\nDešifruje reťazec vytvorený cez ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Zašifrovaný reťazec. |\n| `key` | `String` | yes |  | Kľúč použitý v `ENCRYPT()`. |\n| `tojson` | `Boolean` | no | `true` | Sparsovať výsledok ako JSON. |\n\nReturns: `Object|String` Hodnota alebo `null`.\n\nDešifruje reťazec vytvorený cez `ENCRYPT()` s rovnakým `key`. S `tojson` (predvolene) sa výsledok sparsuje ako JSON; reťazec, ktorý nie je platný, bol vytvorený iným kľúčom alebo neobsahuje JSON, vráti `null`. S `tojson: false` dostaneš dešifrovaný text. Keď je nastavené `CONF.$crypto`, hodnota sa dešifruje touto šifrou Node.js a hodnota s nepárnym počtom hex znakov hneď vráti `null`. `F.decrypt()` je tá istá funkcia.\n\nExample: Overenie tokenu\n```js\nvar data = DECRYPT($.query.token, 'reset');\nif (!data || data.expire < NOW) {\n\t$.invalid(400);\n\treturn;\n}\n```\n\n### ENCRYPTREQ($, value, key, [strict])\n\nType: `method`\n\nZašifruje hodnotu naviazanú na klienta požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie alebo controllera. |\n| `value` | `Object` | yes |  | Ľubovoľná hodnota serializovateľná do JSON. |\n| `key` | `String` | yes |  | Kľúč. |\n| `strict` | `Boolean` | no |  | Naviaže hodnotu aj na IP adresu. |\n\nReturns: `String` Zašifrovaná hodnota.\n\nS hodnotou uloží hash hlavičky `User-Agent` a so `strict` aj IP adresu. `DECRYPTREQ()` vráti hodnotu len pre toho istého klienta. `F.encryptreq()` je tá istá funkcia.\n\nExample: Token na stiahnutie\n```js\nvar token = ENCRYPTREQ($, { file: model.id }, 'download', true);\n$.success(token);\n```\n\n### DECRYPTREQ($, value, key)\n\nType: `method`\n\nDešifruje hodnotu vytvorenú cez ENCRYPTREQ() pre toho istého klienta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie alebo controllera. |\n| `value` | `String` | yes |  | Zašifrovaný reťazec. |\n| `key` | `String` | yes |  | Kľúč použitý v `ENCRYPTREQ()`. |\n\nReturns: `Object` Hodnota alebo `undefined`.\n\nVráti `undefined`, keď je hodnota prázdna, neplatná alebo pochádza z iného prehliadača (alebo pri strict hodnote z inej IP adresy). `F.decryptreq()` je tá istá funkcia.\n\nExample: Kontrola tokenu\n```js\nvar data = DECRYPTREQ($, $.query.token, 'download');\nif (!data) {\n\t$.invalid(401);\n\treturn;\n}\n```\n\n### $crypto : aes-256-cbc\n\nType: `config`\n\nNode.js šifra pre ENCRYPT() a DECRYPT().\n\nReturns: `String`\n\nĽubovoľný algoritmus `crypto.createCipheriv()`. Bez nej sa použije vstavaný algoritmus. Kľúče potom musia mať bajtovú dĺžku šifry (32 znakov pre `aes-256-cbc`).\n\nExample: Config\n```js\n// /config\n$crypto      : aes-256-cbc\n$cryptoiv    : 00112233445566778899aabbccddeeff\n```\n\n### $cryptoiv : <hex or base64>\n\nType: `config`\n\nInicializačný vektor pre $crypto.\n\nReturns: `Buffer`\n\nČíta sa ako base64, keď obsahuje veľké písmená, `=`, `/` alebo `+`, inak ako hex. Predvolene je to prvých 16 bajtov hashu aplikácie.\n\nExample: Config\n```js\n$cryptoiv : 00112233445566778899aabbccddeeff\n```\n\n### secret : <string>\n\nType: `config`\n\nTajomstvo aplikácie, ktoré používajú ENCRYPT() a DECRYPT().\n\nReturns: `String`\n\nPrimieša sa do kľúča vstavaného algoritmu, takže hodnoty zašifrované iným tajomstvom sa nedešifrujú. Nemá predvolenú hodnotu (`CONF.secret` je `undefined`), preto si nastav vlastné; rovnaké tajomstvo udrží tokeny platné naprieč servermi.\n\nExample: Konfigurácia\n```js\nsecret : a-long-random-string\n```\n","entries":[{"type":"method","name":"ENCRYPT(value, key, [unique])","signature":"ENCRYPT(value, key, [unique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT(value, key, [tojson])","signature":"DECRYPT(value, key, [tojson])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ($, value, key, [strict])","signature":"ENCRYPTREQ($, value, key, [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ($, value, key)","signature":"DECRYPTREQ($, value, key)","since":"","deprecated":false},{"type":"config","name":"$crypto","signature":"$crypto : aes-256-cbc","since":"","deprecated":false},{"type":"config","name":"$cryptoiv","signature":"$cryptoiv : <hex or base64>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <string>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJU54UD61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Audit logs","summary":"AUDIT(), $.audit(), DEF.onAudit and the audit option of NEWACTION().","markdown":"---\ntitle: Audit logs\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/audit-logs/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Audit logs\n\n> AUDIT(), $.audit(), DEF.onAudit and the audit option of NEWACTION().\n\nThe functions that write audit records and the option that audits actions. The guide [Audit logs](../../guides/audit-logs/) explains how they work together with examples.\n\n## API\n\n### AUDIT([name], $, [message], [type])\n\nType: `method`\n\nWrites an audit record about the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'audit'` | The log name. |\n| `$` | `Object` | yes |  | The `$` of an action or a controller. |\n| `message` | `String` | no |  | A message. |\n| `type` | `String` | no |  | A type, for example `info` or `warning`. |\n\nReturns: `undefined`\n\nBuilds an audit record from `$` (an action's `$` or a controller) and passes it to `DEF.onAudit`, which appends it as a line of JSON to `/logs/<name>.log` (default `audit`). The record has `userid`, `createdby`, `sessionid` (from `user.sessionid`, `$.sessionid` or the controller), `ip`, `ua`, `url`, `action` (the action ID), `type`, `message`, `instance` (cluster ID), `app` (`CONF.url` or `CONF.name`) and `dtcreated`. `data` holds `{ params, query, model, files }` as JSON, where `files` lists the uploaded files with `name`, `filename`, `size`, `width` and `height`; the fields `password`, `token`, `accesstoken`, `access_token` and `pin` are left out. With `CONF.$tapilogger`, `CONF.$tapi` and `CONF.secret_totalapi` the record goes to the Total.js API logger instead. `F.audit()` is the same function.\n\nExample: Log a removal\n```js\nAUDIT('orders', $, 'Order removed', 'warning');\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nAUDIT() for the current $ with variables in the message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | A message with optional variables. |\n| `type` | `String` | no |  | A type. |\n\nReturns: `undefined`\n\nThe message can contain `{user.name}`, `{model.field}`, `{value.field}`, `{query.key}` and `{params.key}`; they are replaced with the values of the request. The record goes to `/logs/audit.log`.\n\nExample: With variables\n```js\n$.audit('Updated product {model.name} by {user.name}');\n```\n\n### DEF.onAudit = function(name, data, $)\n\nType: `delegate`\n\nStores audit records.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The log name, or `null`. |\n| `data` | `Object` | yes |  | The record. |\n| `$` | `Object` | yes |  | The request. |\n\nThe default appends `data` with `dtcreated` as a line of JSON to `/logs/<name>.log` (`name` defaults to `audit`). Replace it to write records into a database.\n\nExample: Into a table\n```js\nDEF.onAudit = function(name, data) {\n\tdata.id = UID();\n\tdata.name = name;\n\tdata.dtcreated = NOW;\n\tDATA.insert('tbl_auditlog', data);\n};\n```\n\n### NEWACTION({ audit: true })\n\nType: `config`\n\nAudits an action after it succeeds.\n\n`true` writes a record without a message; a string is a Tangular template rendered with `$` (`{{ $.user.name }}`, `{{ $.model.name }}`). Records go to `/logs/actions.log`.\n\nExample: Audited action\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taudit: 'Removed order {{ $.params.id }}',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### $tapilogger : true\n\nType: `config`\n\nSends audit records to the Total.js API logger.\n\nReturns: `Boolean`\n\nWorks together with `$tapi` (default `true`) and `secret_totalapi`; then `DEF.onAudit` is not called. Default `false`.\n\nExample: Config\n```js\n$tapilogger     : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"AUDIT([name], $, [message], [type])","signature":"AUDIT([name], $, [message], [type])","since":"","deprecated":false},{"type":"method","name":"$.audit([message], [type])","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onAudit","signature":"DEF.onAudit = function(name, data, $)","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ audit })","signature":"NEWACTION({ audit: true })","since":"","deprecated":false},{"type":"config","name":"$tapilogger","signature":"$tapilogger : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJU54UD61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Audit-Logs","summary":"AUDIT(), $.audit(), DEF.onAudit und die Option audit von NEWACTION().","markdown":"---\ntitle: Audit-Logs\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/audit-logs/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Audit-Logs\n\n> AUDIT(), $.audit(), DEF.onAudit und die Option audit von NEWACTION().\n\nDie Funktionen, die Audit-Einträge schreiben, und die Option, die Aktionen auditiert. Die Anleitung [Audit-Logs](../../guides/audit-logs/) erklärt mit Beispielen, wie sie zusammenspielen.\n\n## API\n\n### AUDIT([name], $, [message], [type])\n\nType: `method`\n\nSchreibt einen Audit-Eintrag über den Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'audit'` | Der Name des Logs. |\n| `$` | `Object` | yes |  | Das `$` einer Aktion oder eines Controllers. |\n| `message` | `String` | no |  | Eine Nachricht. |\n| `type` | `String` | no |  | Ein Typ, zum Beispiel `info` oder `warning`. |\n\nReturns: `undefined`\n\nErstellt einen Audit-Eintrag aus `$` (dem `$` einer Aktion oder einem Controller) und übergibt ihn an `DEF.onAudit`, der ihn als JSON-Zeile an `/logs/<name>.log` anhängt (Standard `audit`). Der Eintrag hat `userid`, `createdby`, `sessionid` (aus `user.sessionid`, `$.sessionid` oder dem Controller), `ip`, `ua`, `url`, `action` (die ID der Aktion), `type`, `message`, `instance` (Cluster-ID), `app` (`CONF.url` oder `CONF.name`) und `dtcreated`. `data` enthält `{ params, query, model, files }` als JSON, wobei `files` die hochgeladenen Dateien mit `name`, `filename`, `size`, `width` und `height` auflistet; die Felder `password`, `token`, `accesstoken`, `access_token` und `pin` werden weggelassen. Mit `CONF.$tapilogger`, `CONF.$tapi` und `CONF.secret_totalapi` geht der Eintrag stattdessen an den Total.js-API-Logger. `F.audit()` ist dieselbe Funktion.\n\nExample: Ein Entfernen protokollieren\n```js\nAUDIT('orders', $, 'Order removed', 'warning');\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nAUDIT() für das aktuelle $ mit Variablen in der Nachricht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Eine Nachricht mit optionalen Variablen. |\n| `type` | `String` | no |  | Ein Typ. |\n\nReturns: `undefined`\n\nDie Nachricht kann `{user.name}`, `{model.field}`, `{value.field}`, `{query.key}` und `{params.key}` enthalten; sie werden durch die Werte des Requests ersetzt. Der Eintrag geht nach `/logs/audit.log`.\n\nExample: Mit Variablen\n```js\n$.audit('Updated product {model.name} by {user.name}');\n```\n\n### DEF.onAudit = function(name, data, $)\n\nType: `delegate`\n\nSpeichert Audit-Einträge.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Logs oder `null`. |\n| `data` | `Object` | yes |  | Der Eintrag. |\n| `$` | `Object` | yes |  | Der Request. |\n\nStandardmäßig hängt sie `data` mit `dtcreated` als JSON-Zeile an `/logs/<name>.log` an (`name` ist standardmäßig `audit`). Ersetze sie, um Einträge in eine Datenbank zu schreiben.\n\nExample: In eine Tabelle\n```js\nDEF.onAudit = function(name, data) {\n\tdata.id = UID();\n\tdata.name = name;\n\tdata.dtcreated = NOW;\n\tDATA.insert('tbl_auditlog', data);\n};\n```\n\n### NEWACTION({ audit: true })\n\nType: `config`\n\nProtokolliert eine Aktion nach ihrem Erfolg im Audit-Log.\n\n`true` schreibt einen Eintrag ohne Nachricht; ein String ist ein Tangular-Template, das mit `$` gerendert wird (`{{ $.user.name }}`, `{{ $.model.name }}`). Die Einträge gehen nach `/logs/actions.log`.\n\nExample: Protokollierte Aktion\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taudit: 'Removed order {{ $.params.id }}',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### $tapilogger : true\n\nType: `config`\n\nSendet Audit-Einträge an den Logger der Total.js API.\n\nReturns: `Boolean`\n\nFunktioniert zusammen mit `$tapi` (Standard `true`) und `secret_totalapi`; dann wird `DEF.onAudit` nicht aufgerufen. Standard `false`.\n\nExample: Config\n```js\n$tapilogger     : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"AUDIT([name], $, [message], [type])","signature":"AUDIT([name], $, [message], [type])","since":"","deprecated":false},{"type":"method","name":"$.audit([message], [type])","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onAudit","signature":"DEF.onAudit = function(name, data, $)","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ audit })","signature":"NEWACTION({ audit: true })","since":"","deprecated":false},{"type":"config","name":"$tapilogger","signature":"$tapilogger : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJU54UD61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Registros de auditoría","summary":"AUDIT(), $.audit(), DEF.onAudit y la opción audit de NEWACTION().","markdown":"---\ntitle: \"Registros de auditoría\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/audit-logs/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Registros de auditoría\n\n> AUDIT(), $.audit(), DEF.onAudit y la opción audit de NEWACTION().\n\nLas funciones que escriben registros de auditoría y la opción que audita las acciones. La guía [Registros de auditoría](../../guides/audit-logs/) explica cómo funcionan juntas, con ejemplos.\n\n## API\n\n### AUDIT([name], $, [message], [type])\n\nType: `method`\n\nEscribe un registro de auditoría sobre la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'audit'` | El nombre del log. |\n| `$` | `Object` | yes |  | El `$` de una acción o de un controlador. |\n| `message` | `String` | no |  | Un mensaje. |\n| `type` | `String` | no |  | Un tipo, por ejemplo `info` o `warning`. |\n\nReturns: `undefined`\n\nConstruye un registro de auditoría a partir de `$` (el `$` de una acción o un controlador) y lo pasa a `DEF.onAudit`, que lo añade como una línea de JSON a `/logs/<name>.log` (por defecto `audit`). El registro tiene `userid`, `createdby`, `sessionid` (de `user.sessionid`, `$.sessionid` o el controlador), `ip`, `ua`, `url`, `action` (el ID de la acción), `type`, `message`, `instance` (ID del clúster), `app` (`CONF.url` o `CONF.name`) y `dtcreated`. `data` contiene `{ params, query, model, files }` como JSON, donde `files` lista los archivos subidos con `name`, `filename`, `size`, `width` y `height`; los campos `password`, `token`, `accesstoken`, `access_token` y `pin` se dejan fuera. Con `CONF.$tapilogger`, `CONF.$tapi` y `CONF.secret_totalapi`, el registro va en su lugar al logger de Total.js API. `F.audit()` es la misma función.\n\nExample: Registrar una eliminación\n```js\nAUDIT('orders', $, 'Order removed', 'warning');\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nAUDIT() para el $ actual con variables en el mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Un mensaje con variables opcionales. |\n| `type` | `String` | no |  | Un tipo. |\n\nReturns: `undefined`\n\nEl mensaje puede contener `{user.name}`, `{model.field}`, `{value.field}`, `{query.key}` y `{params.key}`; se reemplazan por los valores de la petición. El registro va a `/logs/audit.log`.\n\nExample: Con variables\n```js\n$.audit('Updated product {model.name} by {user.name}');\n```\n\n### DEF.onAudit = function(name, data, $)\n\nType: `delegate`\n\nGuarda los registros de auditoría.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del log, o `null`. |\n| `data` | `Object` | yes |  | El registro. |\n| `$` | `Object` | yes |  | La petición. |\n\nLa función por defecto añade `data` con `dtcreated` como una línea de JSON a `/logs/<name>.log` (`name` es `audit` por defecto). Reemplázala para escribir los registros en una base de datos.\n\nExample: En una tabla\n```js\nDEF.onAudit = function(name, data) {\n\tdata.id = UID();\n\tdata.name = name;\n\tdata.dtcreated = NOW;\n\tDATA.insert('tbl_auditlog', data);\n};\n```\n\n### NEWACTION({ audit: true })\n\nType: `config`\n\nAudita una acción después de que se complete con éxito.\n\n`true` escribe un registro sin mensaje; una cadena es un template de Tangular renderizado con `$` (`{{ $.user.name }}`, `{{ $.model.name }}`). Los registros van a `/logs/actions.log`.\n\nExample: Acción auditada\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taudit: 'Removed order {{ $.params.id }}',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### $tapilogger : true\n\nType: `config`\n\nEnvía los registros de auditoría al logger de la API de Total.js.\n\nReturns: `Boolean`\n\nFunciona junto con `$tapi` (por defecto `true`) y `secret_totalapi`; en ese caso no se llama a `DEF.onAudit`. Por defecto `false`.\n\nExample: Config\n```js\n$tapilogger     : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"AUDIT([name], $, [message], [type])","signature":"AUDIT([name], $, [message], [type])","since":"","deprecated":false},{"type":"method","name":"$.audit([message], [type])","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onAudit","signature":"DEF.onAudit = function(name, data, $)","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ audit })","signature":"NEWACTION({ audit: true })","since":"","deprecated":false},{"type":"config","name":"$tapilogger","signature":"$tapilogger : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJU54UD61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Journaux d'audit","summary":"AUDIT(), $.audit(), DEF.onAudit et l'option audit de NEWACTION().","markdown":"---\ntitle: \"Journaux d'audit\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/audit-logs/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Journaux d'audit\n\n> AUDIT(), $.audit(), DEF.onAudit et l'option audit de NEWACTION().\n\nLes fonctions qui écrivent des enregistrements d'audit et l'option qui audite les actions. Le guide [Journaux d'audit](../../guides/audit-logs/) explique comment elles fonctionnent ensemble, avec des exemples.\n\n## API\n\n### AUDIT([name], $, [message], [type])\n\nType: `method`\n\nÉcrit un enregistrement d'audit concernant la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'audit'` | Le nom du journal. |\n| `$` | `Object` | yes |  | Le `$` d'une action ou d'un contrôleur. |\n| `message` | `String` | no |  | Un message. |\n| `type` | `String` | no |  | Un type, par exemple `info` ou `warning`. |\n\nReturns: `undefined`\n\nConstruit un enregistrement d'audit à partir de `$` (le `$` d'une action ou un contrôleur) et le transmet à `DEF.onAudit`, qui l'ajoute sous forme de ligne JSON à `/logs/<name>.log` (`audit` par défaut). L'enregistrement contient `userid`, `createdby`, `sessionid` (issu de `user.sessionid`, `$.sessionid` ou du contrôleur), `ip`, `ua`, `url`, `action` (l'ID de l'action), `type`, `message`, `instance` (l'ID du cluster), `app` (`CONF.url` ou `CONF.name`) et `dtcreated`. `data` contient `{ params, query, model, files }` en JSON, où `files` liste les fichiers envoyés avec `name`, `filename`, `size`, `width` et `height` ; les champs `password`, `token`, `accesstoken`, `access_token` et `pin` sont omis. Avec `CONF.$tapilogger`, `CONF.$tapi` et `CONF.secret_totalapi`, l'enregistrement est plutôt envoyé au logger de Total.js API. `F.audit()` est la même fonction.\n\nExample: Journaliser une suppression\n```js\nAUDIT('orders', $, 'Order removed', 'warning');\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nAUDIT() pour le $ courant, avec des variables dans le message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Un message avec des variables facultatives. |\n| `type` | `String` | no |  | Un type. |\n\nReturns: `undefined`\n\nLe message peut contenir `{user.name}`, `{model.field}`, `{value.field}`, `{query.key}` et `{params.key}` ; ils sont remplacés par les valeurs de la requête. L'enregistrement va dans `/logs/audit.log`.\n\nExample: Avec des variables\n```js\n$.audit('Updated product {model.name} by {user.name}');\n```\n\n### DEF.onAudit = function(name, data, $)\n\nType: `delegate`\n\nStocke les enregistrements d'audit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du journal, ou `null`. |\n| `data` | `Object` | yes |  | L'enregistrement. |\n| `$` | `Object` | yes |  | La requête. |\n\nPar défaut, elle ajoute `data` avec `dtcreated` sous forme de ligne JSON à `/logs/<name>.log` (`name` vaut `audit` par défaut). Remplace-la pour écrire les enregistrements dans une base de données.\n\nExample: Dans une table\n```js\nDEF.onAudit = function(name, data) {\n\tdata.id = UID();\n\tdata.name = name;\n\tdata.dtcreated = NOW;\n\tDATA.insert('tbl_auditlog', data);\n};\n```\n\n### NEWACTION({ audit: true })\n\nType: `config`\n\nAudite une action après sa réussite.\n\n`true` écrit un enregistrement sans message ; une chaîne est un template Tangular rendu avec `$` (`{{ $.user.name }}`, `{{ $.model.name }}`). Les enregistrements vont dans `/logs/actions.log`.\n\nExample: Action auditée\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taudit: 'Removed order {{ $.params.id }}',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### $tapilogger : true\n\nType: `config`\n\nEnvoie les enregistrements d'audit au logger de Total.js API.\n\nReturns: `Boolean`\n\nFonctionne avec `$tapi` (par défaut `true`) et `secret_totalapi` ; `DEF.onAudit` n'est alors pas appelé. Par défaut `false`.\n\nExample: Config\n```js\n$tapilogger     : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"AUDIT([name], $, [message], [type])","signature":"AUDIT([name], $, [message], [type])","since":"","deprecated":false},{"type":"method","name":"$.audit([message], [type])","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onAudit","signature":"DEF.onAudit = function(name, data, $)","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ audit })","signature":"NEWACTION({ audit: true })","since":"","deprecated":false},{"type":"config","name":"$tapilogger","signature":"$tapilogger : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJU54UD61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Audit log","summary":"AUDIT(), $.audit(), DEF.onAudit e l'opzione audit di NEWACTION().","markdown":"---\ntitle: Audit log\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/audit-logs/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Audit log\n\n> AUDIT(), $.audit(), DEF.onAudit e l'opzione audit di NEWACTION().\n\nLe funzioni che scrivono i record di audit e l'opzione che esegue l'audit delle azioni. La guida [Audit log](../../guides/audit-logs/) spiega come funzionano insieme, con esempi.\n\n## API\n\n### AUDIT([name], $, [message], [type])\n\nType: `method`\n\nScrive un record di audit sulla richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'audit'` | Il nome del log. |\n| `$` | `Object` | yes |  | Il `$` di un'azione o di un controller. |\n| `message` | `String` | no |  | Un messaggio. |\n| `type` | `String` | no |  | Un tipo, ad esempio `info` o `warning`. |\n\nReturns: `undefined`\n\nCostruisce un record di audit da `$` (il `$` di un'azione o un controller) e lo passa a `DEF.onAudit`, che lo accoda come riga di JSON a `/logs/<name>.log` (predefinito `audit`). Il record ha `userid`, `createdby`, `sessionid` (da `user.sessionid`, `$.sessionid` o dal controller), `ip`, `ua`, `url`, `action` (l'ID dell'azione), `type`, `message`, `instance` (ID del cluster), `app` (`CONF.url` o `CONF.name`) e `dtcreated`. `data` contiene `{ params, query, model, files }` come JSON, dove `files` elenca i file caricati con `name`, `filename`, `size`, `width` e `height`; i campi `password`, `token`, `accesstoken`, `access_token` e `pin` vengono omessi. Con `CONF.$tapilogger`, `CONF.$tapi` e `CONF.secret_totalapi` il record va invece al logger di Total.js API. `F.audit()` è la stessa funzione.\n\nExample: Registrare una rimozione\n```js\nAUDIT('orders', $, 'Order removed', 'warning');\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nAUDIT() per il $ corrente con variabili nel messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Un messaggio con variabili opzionali. |\n| `type` | `String` | no |  | Un tipo. |\n\nReturns: `undefined`\n\nIl messaggio può contenere `{user.name}`, `{model.field}`, `{value.field}`, `{query.key}` e `{params.key}`; vengono sostituite con i valori della richiesta. Il record va in `/logs/audit.log`.\n\nExample: Con variabili\n```js\n$.audit('Updated product {model.name} by {user.name}');\n```\n\n### DEF.onAudit = function(name, data, $)\n\nType: `delegate`\n\nSalva i record di audit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del log, oppure `null`. |\n| `data` | `Object` | yes |  | Il record. |\n| `$` | `Object` | yes |  | La richiesta. |\n\nL'implementazione predefinita aggiunge `data` con `dtcreated` come riga di JSON a `/logs/<name>.log` (`name` vale `audit` di default). Sostituiscila per scrivere i record in un database.\n\nExample: In una tabella\n```js\nDEF.onAudit = function(name, data) {\n\tdata.id = UID();\n\tdata.name = name;\n\tdata.dtcreated = NOW;\n\tDATA.insert('tbl_auditlog', data);\n};\n```\n\n### NEWACTION({ audit: true })\n\nType: `config`\n\nRegistra l'audit di un'azione dopo che è andata a buon fine.\n\n`true` scrive un record senza messaggio; una stringa è un template Tangular renderizzato con `$` (`{{ $.user.name }}`, `{{ $.model.name }}`). I record vanno in `/logs/actions.log`.\n\nExample: Azione con audit\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taudit: 'Removed order {{ $.params.id }}',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### $tapilogger : true\n\nType: `config`\n\nInvia i record di audit al logger di Total.js API.\n\nReturns: `Boolean`\n\nFunziona insieme a `$tapi` (default `true`) e `secret_totalapi`; in quel caso `DEF.onAudit` non viene chiamato. Default `false`.\n\nExample: Config\n```js\n$tapilogger     : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"AUDIT([name], $, [message], [type])","signature":"AUDIT([name], $, [message], [type])","since":"","deprecated":false},{"type":"method","name":"$.audit([message], [type])","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onAudit","signature":"DEF.onAudit = function(name, data, $)","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ audit })","signature":"NEWACTION({ audit: true })","since":"","deprecated":false},{"type":"config","name":"$tapilogger","signature":"$tapilogger : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafJU54UD61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/audit-logs/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Auditné logy","summary":"AUDIT(), $.audit(), DEF.onAudit a voľba audit v NEWACTION().","markdown":"---\ntitle: \"Auditné logy\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/audit-logs/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Auditné logy\n\n> AUDIT(), $.audit(), DEF.onAudit a voľba audit v NEWACTION().\n\nFunkcie, ktoré zapisujú auditné záznamy, a voľba, ktorá audituje akcie. Ako spolu fungujú, vysvetľuje s príkladmi návod [Auditné logy](../../guides/audit-logs/).\n\n## API\n\n### AUDIT([name], $, [message], [type])\n\nType: `method`\n\nZapíše auditný záznam o požiadavke.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'audit'` | Meno logu. |\n| `$` | `Object` | yes |  | `$` akcie alebo controllera. |\n| `message` | `String` | no |  | Správa. |\n| `type` | `String` | no |  | Typ, napríklad `info` alebo `warning`. |\n\nReturns: `undefined`\n\nZostaví auditný záznam z `$` (`$` akcie alebo controllera) a odovzdá ho do `DEF.onAudit`, ktorý ho pripojí ako riadok JSON do `/logs/<name>.log` (predvolene `audit`). Záznam má `userid`, `createdby`, `sessionid` (z `user.sessionid`, `$.sessionid` alebo controllera), `ip`, `ua`, `url`, `action` (ID akcie), `type`, `message`, `instance` (ID clustera), `app` (`CONF.url` alebo `CONF.name`) a `dtcreated`. `data` obsahuje `{ params, query, model, files }` ako JSON, kde `files` uvádza nahrané súbory s `name`, `filename`, `size`, `width` a `height`; polia `password`, `token`, `accesstoken`, `access_token` a `pin` sa vynechajú. S `CONF.$tapilogger`, `CONF.$tapi` a `CONF.secret_totalapi` ide záznam namiesto toho do loggera Total.js API. `F.audit()` je tá istá funkcia.\n\nExample: Zalogovanie odstránenia\n```js\nAUDIT('orders', $, 'Order removed', 'warning');\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nAUDIT() pre aktuálny $ s premennými v správe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Správa s voliteľnými premennými. |\n| `type` | `String` | no |  | Typ. |\n\nReturns: `undefined`\n\nSpráva môže obsahovať `{user.name}`, `{model.field}`, `{value.field}`, `{query.key}` a `{params.key}`; nahradia sa hodnotami požiadavky. Záznam ide do `/logs/audit.log`.\n\nExample: S premennými\n```js\n$.audit('Updated product {model.name} by {user.name}');\n```\n\n### DEF.onAudit = function(name, data, $)\n\nType: `delegate`\n\nUkladá auditné záznamy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno logu alebo `null`. |\n| `data` | `Object` | yes |  | Záznam. |\n| `$` | `Object` | yes |  | Požiadavka. |\n\nPredvolene pripojí `data` s `dtcreated` ako riadok JSON do `/logs/<name>.log` (`name` je predvolene `audit`). Nahraď ho, ak chceš zapisovať záznamy do databázy.\n\nExample: Do tabuľky\n```js\nDEF.onAudit = function(name, data) {\n\tdata.id = UID();\n\tdata.name = name;\n\tdata.dtcreated = NOW;\n\tDATA.insert('tbl_auditlog', data);\n};\n```\n\n### NEWACTION({ audit: true })\n\nType: `config`\n\nZaaudituje akciu po jej úspechu.\n\n`true` zapíše záznam bez správy; reťazec je Tangular šablóna vykreslená s `$` (`{{ $.user.name }}`, `{{ $.model.name }}`). Záznamy idú do `/logs/actions.log`.\n\nExample: Auditovaná akcia\n```js\nNEWACTION({\n\tid: 'Orders/remove',\n\tparams: '*id:UID',\n\taudit: 'Removed order {{ $.params.id }}',\n\taction: function($) {\n\t\t$.success();\n\t}\n});\n```\n\n### $tapilogger : true\n\nType: `config`\n\nPosiela auditné záznamy do loggera Total.js API.\n\nReturns: `Boolean`\n\nFunguje spolu s `$tapi` (predvolene `true`) a `secret_totalapi`; vtedy sa `DEF.onAudit` nevolá. Predvolene `false`.\n\nExample: Config\n```js\n$tapilogger     : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"AUDIT([name], $, [message], [type])","signature":"AUDIT([name], $, [message], [type])","since":"","deprecated":false},{"type":"method","name":"$.audit([message], [type])","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onAudit","signature":"DEF.onAudit = function(name, data, $)","since":"","deprecated":false},{"type":"config","name":"NEWACTION({ audit })","signature":"NEWACTION({ audit: true })","since":"","deprecated":false},{"type":"config","name":"$tapilogger","signature":"$tapilogger : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"Jafiy14k861f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/middleware/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Middleware","summary":"NEWMIDDLEWARE(), the middleware handler, the #name route flag and the middleware option of actions.","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/middleware/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Middleware\n\n> NEWMIDDLEWARE(), the middleware handler, the #name route flag and the middleware option of actions.\n\n## API\n\n### NEWMIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nRegisters a named middleware, or removes it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the middleware, used as `#name` in routes. Letters, digits and `_`. |\n| `fn` | `Function` | no |  | `function($, next)`. Without it, the middleware is removed. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` or `websockets`, separated by commas. |\n\nReturns: `undefined`\n\nThe function runs as `fn($, next)` for every route that lists the name. For HTTP and socket routes `$` is the controller; for actions it is the action's `$`. Call `next()` to continue, or answer the request to stop it.\n\n`assign` adds the middleware to routes that already exist: `'routes'` or `'dynamic'` for HTTP routes, `'websockets'` for socket routes, several values separated by commas or as an array. Routes registered later do not get it.\n\nCalled with only `name`, it removes the middleware from the registry and from every route.\n\nExample: API key check\n```js\nNEWMIDDLEWARE('apikey', function($, next) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nROUTE('GET /api/orders/ #apikey', function($) {\n\t$.json([]);\n});\n```\n\nExample: Remove a middleware\n```js\nNEWMIDDLEWARE('apikey');\n```\n\n### MIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nThe same function as `NEWMIDDLEWARE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the middleware. |\n| `fn` | `Function` | no |  | `function($, next)`. Without it, the middleware is removed. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` or `websockets`. |\n\nReturns: `undefined`\n\n`MIDDLEWARE` and `NEWMIDDLEWARE` are two names for one function; the arguments and the behaviour are the same.\n\nExample: Register\n```js\nMIDDLEWARE('timing', function($, next) {\n\t$.started = Date.now();\n\tnext();\n});\n```\n\n### function($, next)\n\nType: `delegate`\n\nThe function of a middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Options` | yes |  | The controller of the request, or the action's `$`. |\n| `next` | `Function` | yes |  | Continues with the next middleware or the action. |\n\nIt receives the controller (or, inside an action, the action's `$`) and the `next` callback. Calling `next()` runs the next middleware of the route, and after the last one the action. Not calling `next()` stops the chain; then the middleware must answer the request itself, for example with `$.invalid(401)`, `$.redirect(url)` or `$.json(data)`.\n\nFor HTTP routes, the body, the query, the URL parameters and `$.user` are already set when the middleware runs.\n\nExample: Redirect anonymous users\n```js\nNEWMIDDLEWARE('login', function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse\n\t\t$.redirect('/login/');\n});\n```\n\n### ROUTE('METHOD /url/ #name', action)\n\nType: `property`\n\nLists a middleware in a route declaration.\n\nEach `#name` in the route string adds that middleware to the route; they run in the written order. The flag works for HTTP routes, `API` routes and `SOCKET` routes. The name may contain letters, digits and `_`. A name that is not registered is skipped; in a `SOCKET` route, the middleware after it are skipped too.\n\nExample: Two middleware\n```js\nROUTE('POST /api/upload/ #apikey #ratelimit', upload);\nROUTE('SOCKET /live/ #apikey', live);\n```\n\n### NEWACTION({ middleware: 'name1, name2' })\n\nType: `property`\n\nMiddleware that runs before an action.\n\nThe `middleware` option of `NEWACTION()` is a list of middleware names separated by commas, spaces or `|`. They run with the action's `$` every time the action is called, before the `action` function. A name that is not registered is reported with `Total.error()` and skipped.\n\nExample: Action with middleware\n```js\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\n### middleware/*.js\n\nType: `type`\n\nFolder with files that register middleware.\n\n`.js` files in `middleware/` and in `plugins/<name>/middleware/` are loaded at start; their `install()` function runs. Use it to keep middleware apart from controllers.\n\nExample: middleware/auth.js\n```js\nexports.install = function() {\n\tNEWMIDDLEWARE('admin', function($, next) {\n\t\tif ($.user && $.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWMIDDLEWARE(name, fn, [assign])","signature":"NEWMIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"method","name":"MIDDLEWARE(name, fn, [assign])","signature":"MIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"delegate","name":"middleware handler","signature":"function($, next)","since":"","deprecated":false},{"type":"property","name":"#name route flag","signature":"ROUTE('METHOD /url/ #name', action)","since":"","deprecated":false},{"type":"property","name":"NEWACTION middleware","signature":"NEWACTION({ middleware: 'name1, name2' })","since":"","deprecated":false},{"type":"type","name":"middleware folder","signature":"middleware/*.js","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafiy14k861f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/middleware/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Middleware","summary":"NEWMIDDLEWARE(), der Middleware-Handler, das Route-Flag #name und die Option middleware von Aktionen.","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/middleware/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Middleware\n\n> NEWMIDDLEWARE(), der Middleware-Handler, das Route-Flag #name und die Option middleware von Aktionen.\n\n## API\n\n### NEWMIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nRegistriert eine benannte Middleware oder entfernt sie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Middleware, in Routen als `#name` verwendet. Buchstaben, Ziffern und `_`. |\n| `fn` | `Function` | no |  | `function($, next)`. Ohne sie wird die Middleware entfernt. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` oder `websockets`, durch Kommas getrennt. |\n\nReturns: `undefined`\n\nDie Funktion läuft als `fn($, next)` für jede Route, die den Namen auflistet. Bei HTTP- und Socket-Routen ist `$` der Controller; bei Aktionen ist es das `$` der Aktion. Rufe `next()` auf, um fortzufahren, oder beantworte die Anfrage, um sie zu stoppen.\n\n`assign` fügt die Middleware zu bereits existierenden Routen hinzu: `'routes'` oder `'dynamic'` für HTTP-Routen, `'websockets'` für Socket-Routen, mehrere Werte durch Kommas getrennt oder als Array. Später registrierte Routen erhalten sie nicht.\n\nNur mit `name` aufgerufen, entfernt sie die Middleware aus der Registry und aus jeder Route.\n\nExample: Prüfung des API-Schlüssels\n```js\nNEWMIDDLEWARE('apikey', function($, next) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nROUTE('GET /api/orders/ #apikey', function($) {\n\t$.json([]);\n});\n```\n\nExample: Eine Middleware entfernen\n```js\nNEWMIDDLEWARE('apikey');\n```\n\n### MIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nDieselbe Funktion wie `NEWMIDDLEWARE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Middleware. |\n| `fn` | `Function` | no |  | `function($, next)`. Ohne sie wird die Middleware entfernt. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` oder `websockets`. |\n\nReturns: `undefined`\n\n`MIDDLEWARE` und `NEWMIDDLEWARE` sind zwei Namen für eine Funktion; die Argumente und das Verhalten sind dieselben.\n\nExample: Registrieren\n```js\nMIDDLEWARE('timing', function($, next) {\n\t$.started = Date.now();\n\tnext();\n});\n```\n\n### function($, next)\n\nType: `delegate`\n\nDie Funktion einer Middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Options` | yes |  | Der Controller der Anfrage oder das `$` der Aktion. |\n| `next` | `Function` | yes |  | Fährt mit der nächsten Middleware oder der Aktion fort. |\n\nSie erhält den Controller (oder innerhalb einer Aktion das `$` der Aktion) und den Callback `next`. Der Aufruf von `next()` führt die nächste Middleware der Route aus und nach der letzten die Aktion. Wird `next()` nicht aufgerufen, stoppt die Kette; dann muss die Middleware die Anfrage selbst beantworten, zum Beispiel mit `$.invalid(401)`, `$.redirect(url)` oder `$.json(data)`.\n\nBei HTTP-Routen sind der Body, die Query, die URL-Parameter und `$.user` bereits gesetzt, wenn die Middleware läuft.\n\nExample: Anonyme Benutzer weiterleiten\n```js\nNEWMIDDLEWARE('login', function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse\n\t\t$.redirect('/login/');\n});\n```\n\n### ROUTE('METHOD /url/ #name', action)\n\nType: `property`\n\nListet eine Middleware in der Deklaration einer Route auf.\n\nJedes `#name` im Routen-String fügt der Route diese Middleware hinzu; sie laufen in der geschriebenen Reihenfolge. Das Flag funktioniert für HTTP-Routen, `API`-Routen und `SOCKET`-Routen. Der Name darf Buchstaben, Ziffern und `_` enthalten. Ein nicht registrierter Name wird übersprungen; in einer `SOCKET`-Route werden auch die Middlewares danach übersprungen.\n\nExample: Zwei Middlewares\n```js\nROUTE('POST /api/upload/ #apikey #ratelimit', upload);\nROUTE('SOCKET /live/ #apikey', live);\n```\n\n### NEWACTION({ middleware: 'name1, name2' })\n\nType: `property`\n\nMiddleware, die vor einer Aktion läuft.\n\nDie Option `middleware` von `NEWACTION()` ist eine Liste von Middleware-Namen, getrennt durch Kommas, Leerzeichen oder `|`. Sie laufen bei jedem Aufruf der Aktion mit dem `$` der Aktion, vor der Funktion `action`. Ein nicht registrierter Name wird mit `Total.error()` gemeldet und übersprungen.\n\nExample: Aktion mit Middleware\n```js\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\n### middleware/*.js\n\nType: `type`\n\nOrdner mit Dateien, die Middleware registrieren.\n\n`.js`-Dateien in `middleware/` und in `plugins/<name>/middleware/` werden beim Start geladen; ihre Funktion `install()` wird ausgeführt. Verwende ihn, um Middleware von Controllern getrennt zu halten.\n\nExample: middleware/auth.js\n```js\nexports.install = function() {\n\tNEWMIDDLEWARE('admin', function($, next) {\n\t\tif ($.user && $.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWMIDDLEWARE(name, fn, [assign])","signature":"NEWMIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"method","name":"MIDDLEWARE(name, fn, [assign])","signature":"MIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"delegate","name":"middleware handler","signature":"function($, next)","since":"","deprecated":false},{"type":"property","name":"#name route flag","signature":"ROUTE('METHOD /url/ #name', action)","since":"","deprecated":false},{"type":"property","name":"NEWACTION middleware","signature":"NEWACTION({ middleware: 'name1, name2' })","since":"","deprecated":false},{"type":"type","name":"middleware folder","signature":"middleware/*.js","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafiy14k861f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/middleware/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Middleware","summary":"NEWMIDDLEWARE(), el handler del middleware, el flag de ruta #name y la opción middleware de las acciones.","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/middleware/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Middleware\n\n> NEWMIDDLEWARE(), el handler del middleware, el flag de ruta #name y la opción middleware de las acciones.\n\n## API\n\n### NEWMIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nRegistra un middleware con nombre, o lo elimina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del middleware, usado como `#name` en las rutas. Letras, dígitos y `_`. |\n| `fn` | `Function` | no |  | `function($, next)`. Sin ella, el middleware se elimina. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` o `websockets`, separados por comas. |\n\nReturns: `undefined`\n\nLa función se ejecuta como `fn($, next)` en cada ruta que incluye el nombre. En las rutas HTTP y de socket `$` es el controlador; en las acciones es el `$` de la acción. Llama a `next()` para continuar, o responde a la petición para detenerla.\n\n`assign` añade el middleware a rutas que ya existen: `'routes'` o `'dynamic'` para las rutas HTTP, `'websockets'` para las rutas de socket; varios valores separados por comas o como array. Las rutas registradas después no lo reciben.\n\nSi se llama solo con `name`, elimina el middleware del registro y de todas las rutas.\n\nExample: Comprobación de la clave de API\n```js\nNEWMIDDLEWARE('apikey', function($, next) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nROUTE('GET /api/orders/ #apikey', function($) {\n\t$.json([]);\n});\n```\n\nExample: Eliminar un middleware\n```js\nNEWMIDDLEWARE('apikey');\n```\n\n### MIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nLa misma función que `NEWMIDDLEWARE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del middleware. |\n| `fn` | `Function` | no |  | `function($, next)`. Sin ella, el middleware se elimina. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` o `websockets`. |\n\nReturns: `undefined`\n\n`MIDDLEWARE` y `NEWMIDDLEWARE` son dos nombres para una misma función; los argumentos y el comportamiento son iguales.\n\nExample: Registrar\n```js\nMIDDLEWARE('timing', function($, next) {\n\t$.started = Date.now();\n\tnext();\n});\n```\n\n### function($, next)\n\nType: `delegate`\n\nLa función de un middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Options` | yes |  | El controlador de la petición, o el `$` de la acción. |\n| `next` | `Function` | yes |  | Continúa con el siguiente middleware o con la acción. |\n\nRecibe el controlador (o, dentro de una acción, el `$` de la acción) y el callback `next`. Llamar a `next()` ejecuta el siguiente middleware de la ruta y, después del último, la acción. No llamar a `next()` detiene la cadena; entonces el middleware debe responder él mismo a la petición, por ejemplo con `$.invalid(401)`, `$.redirect(url)` o `$.json(data)`.\n\nEn las rutas HTTP, el cuerpo, la query, los parámetros de la URL y `$.user` ya están establecidos cuando se ejecuta el middleware.\n\nExample: Redirigir a los usuarios anónimos\n```js\nNEWMIDDLEWARE('login', function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse\n\t\t$.redirect('/login/');\n});\n```\n\n### ROUTE('METHOD /url/ #name', action)\n\nType: `property`\n\nIncluye un middleware en la declaración de una ruta.\n\nCada `#name` en el string de la ruta añade ese middleware a la ruta; se ejecutan en el orden escrito. El flag funciona para rutas HTTP, rutas `API` y rutas `SOCKET`. El nombre puede contener letras, dígitos y `_`. Un nombre que no está registrado se omite; en una ruta `SOCKET`, también se omiten los middleware que van después de él.\n\nExample: Dos middleware\n```js\nROUTE('POST /api/upload/ #apikey #ratelimit', upload);\nROUTE('SOCKET /live/ #apikey', live);\n```\n\n### NEWACTION({ middleware: 'name1, name2' })\n\nType: `property`\n\nMiddleware que se ejecuta antes de una acción.\n\nLa opción `middleware` de `NEWACTION()` es una lista de nombres de middleware separados por comas, espacios o `|`. Se ejecutan con el `$` de la acción cada vez que se llama a la acción, antes de la función `action`. Un nombre que no está registrado se notifica con `Total.error()` y se omite.\n\nExample: Acción con middleware\n```js\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\n### middleware/*.js\n\nType: `type`\n\nCarpeta con archivos que registran middleware.\n\nLos archivos `.js` de `middleware/` y de `plugins/<name>/middleware/` se cargan al inicio; se ejecuta su función `install()`. Úsala para mantener los middleware separados de los controladores.\n\nExample: middleware/auth.js\n```js\nexports.install = function() {\n\tNEWMIDDLEWARE('admin', function($, next) {\n\t\tif ($.user && $.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWMIDDLEWARE(name, fn, [assign])","signature":"NEWMIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"method","name":"MIDDLEWARE(name, fn, [assign])","signature":"MIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"delegate","name":"middleware handler","signature":"function($, next)","since":"","deprecated":false},{"type":"property","name":"#name route flag","signature":"ROUTE('METHOD /url/ #name', action)","since":"","deprecated":false},{"type":"property","name":"NEWACTION middleware","signature":"NEWACTION({ middleware: 'name1, name2' })","since":"","deprecated":false},{"type":"type","name":"middleware folder","signature":"middleware/*.js","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafiy14k861f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/middleware/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Middleware","summary":"NEWMIDDLEWARE(), le handler du middleware, le flag de route #name et l'option middleware des actions.","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/middleware/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Middleware\n\n> NEWMIDDLEWARE(), le handler du middleware, le flag de route #name et l'option middleware des actions.\n\n## API\n\n### NEWMIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nEnregistre un middleware nommé, ou le supprime.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du middleware, utilisé comme `#name` dans les routes. Lettres, chiffres et `_`. |\n| `fn` | `Function` | no |  | `function($, next)`. Sans elle, le middleware est supprimé. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` ou `websockets`, séparés par des virgules. |\n\nReturns: `undefined`\n\nLa fonction s'exécute sous la forme `fn($, next)` pour chaque route qui indique le nom. Pour les routes HTTP et de socket, `$` est le contrôleur ; pour les actions, c'est le `$` de l'action. Appelle `next()` pour continuer, ou réponds à la requête pour l'arrêter.\n\n`assign` ajoute le middleware aux routes qui existent déjà : `'routes'` ou `'dynamic'` pour les routes HTTP, `'websockets'` pour les routes de socket, plusieurs valeurs séparées par des virgules ou sous forme de tableau. Les routes enregistrées plus tard ne le reçoivent pas.\n\nAppelée avec seulement `name`, elle supprime le middleware du registre et de chaque route.\n\nExample: Vérification d'une clé d'API\n```js\nNEWMIDDLEWARE('apikey', function($, next) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nROUTE('GET /api/orders/ #apikey', function($) {\n\t$.json([]);\n});\n```\n\nExample: Supprimer un middleware\n```js\nNEWMIDDLEWARE('apikey');\n```\n\n### MIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nLa même fonction que `NEWMIDDLEWARE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du middleware. |\n| `fn` | `Function` | no |  | `function($, next)`. Sans elle, le middleware est supprimé. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` ou `websockets`. |\n\nReturns: `undefined`\n\n`MIDDLEWARE` et `NEWMIDDLEWARE` sont deux noms pour une seule fonction ; les arguments et le comportement sont identiques.\n\nExample: Enregistrer\n```js\nMIDDLEWARE('timing', function($, next) {\n\t$.started = Date.now();\n\tnext();\n});\n```\n\n### function($, next)\n\nType: `delegate`\n\nLa fonction d'un middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Options` | yes |  | Le contrôleur de la requête, ou le `$` de l'action. |\n| `next` | `Function` | yes |  | Continue avec le middleware suivant ou l'action. |\n\nElle reçoit le contrôleur (ou, dans une action, le `$` de l'action) et le callback `next`. Appeler `next()` exécute le middleware suivant de la route, et après le dernier, l'action. Ne pas appeler `next()` arrête la chaîne ; le middleware doit alors répondre lui-même à la requête, par exemple avec `$.invalid(401)`, `$.redirect(url)` ou `$.json(data)`.\n\nPour les routes HTTP, le corps, la query, les paramètres de l'URL et `$.user` sont déjà définis quand le middleware s'exécute.\n\nExample: Rediriger les utilisateurs anonymes\n```js\nNEWMIDDLEWARE('login', function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse\n\t\t$.redirect('/login/');\n});\n```\n\n### ROUTE('METHOD /url/ #name', action)\n\nType: `property`\n\nIndique un middleware dans la déclaration d'une route.\n\nChaque `#name` dans la chaîne de la route ajoute ce middleware à la route ; ils s'exécutent dans l'ordre d'écriture. Le flag fonctionne pour les routes HTTP, les routes `API` et les routes `SOCKET`. Le nom peut contenir des lettres, des chiffres et `_`. Un nom qui n'est pas enregistré est ignoré ; dans une route `SOCKET`, les middlewares qui le suivent sont aussi ignorés.\n\nExample: Deux middlewares\n```js\nROUTE('POST /api/upload/ #apikey #ratelimit', upload);\nROUTE('SOCKET /live/ #apikey', live);\n```\n\n### NEWACTION({ middleware: 'name1, name2' })\n\nType: `property`\n\nMiddleware qui s'exécute avant une action.\n\nL'option `middleware` de `NEWACTION()` est une liste de noms de middlewares séparés par des virgules, des espaces ou `|`. Ils s'exécutent avec le `$` de l'action à chaque appel de l'action, avant la fonction `action`. Un nom qui n'est pas enregistré est signalé avec `Total.error()` et ignoré.\n\nExample: Action avec middleware\n```js\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\n### middleware/*.js\n\nType: `type`\n\nDossier contenant les fichiers qui enregistrent des middlewares.\n\nLes fichiers `.js` de `middleware/` et de `plugins/<name>/middleware/` sont chargés au démarrage ; leur fonction `install()` s'exécute. Utilise-le pour séparer les middlewares des contrôleurs.\n\nExample: middleware/auth.js\n```js\nexports.install = function() {\n\tNEWMIDDLEWARE('admin', function($, next) {\n\t\tif ($.user && $.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWMIDDLEWARE(name, fn, [assign])","signature":"NEWMIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"method","name":"MIDDLEWARE(name, fn, [assign])","signature":"MIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"delegate","name":"middleware handler","signature":"function($, next)","since":"","deprecated":false},{"type":"property","name":"#name route flag","signature":"ROUTE('METHOD /url/ #name', action)","since":"","deprecated":false},{"type":"property","name":"NEWACTION middleware","signature":"NEWACTION({ middleware: 'name1, name2' })","since":"","deprecated":false},{"type":"type","name":"middleware folder","signature":"middleware/*.js","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafiy14k861f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/middleware/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Middleware","summary":"NEWMIDDLEWARE(), l'handler del middleware, il flag di route #name e l'opzione middleware delle azioni.","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/middleware/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Middleware\n\n> NEWMIDDLEWARE(), l'handler del middleware, il flag di route #name e l'opzione middleware delle azioni.\n\n## API\n\n### NEWMIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nRegistra un middleware con nome, oppure lo rimuove.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del middleware, usato come `#name` nelle route. Lettere, cifre e `_`. |\n| `fn` | `Function` | no |  | `function($, next)`. Senza di essa, il middleware viene rimosso. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` o `websockets`, separati da virgole. |\n\nReturns: `undefined`\n\nLa funzione viene eseguita come `fn($, next)` per ogni route che elenca il nome. Per le route HTTP e socket `$` è il controller; per le azioni è il `$` dell'azione. Chiama `next()` per proseguire, oppure rispondi alla richiesta per fermarla.\n\n`assign` aggiunge il middleware a route che esistono già: `'routes'` o `'dynamic'` per le route HTTP, `'websockets'` per le route socket, più valori separati da virgole o come array. Le route registrate dopo non lo ricevono.\n\nChiamata con il solo `name`, rimuove il middleware dal registro e da ogni route.\n\nExample: Controllo della chiave API\n```js\nNEWMIDDLEWARE('apikey', function($, next) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nROUTE('GET /api/orders/ #apikey', function($) {\n\t$.json([]);\n});\n```\n\nExample: Rimuovere un middleware\n```js\nNEWMIDDLEWARE('apikey');\n```\n\n### MIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nLa stessa funzione di `NEWMIDDLEWARE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del middleware. |\n| `fn` | `Function` | no |  | `function($, next)`. Senza di essa, il middleware viene rimosso. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` o `websockets`. |\n\nReturns: `undefined`\n\n`MIDDLEWARE` e `NEWMIDDLEWARE` sono due nomi per un'unica funzione; gli argomenti e il comportamento sono gli stessi.\n\nExample: Registrazione\n```js\nMIDDLEWARE('timing', function($, next) {\n\t$.started = Date.now();\n\tnext();\n});\n```\n\n### function($, next)\n\nType: `delegate`\n\nLa funzione di un middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Options` | yes |  | Il controller della richiesta, oppure il `$` dell'azione. |\n| `next` | `Function` | yes |  | Prosegue con il middleware successivo o con l'azione. |\n\nRiceve il controller (o, all'interno di un'azione, il `$` dell'azione) e la callback `next`. Chiamare `next()` esegue il middleware successivo della route, e dopo l'ultimo l'azione. Non chiamare `next()` interrompe la catena; allora il middleware deve rispondere da sé alla richiesta, per esempio con `$.invalid(401)`, `$.redirect(url)` o `$.json(data)`.\n\nPer le route HTTP, il body, la query, i parametri dell'URL e `$.user` sono già impostati quando il middleware viene eseguito.\n\nExample: Reindirizzare gli utenti anonimi\n```js\nNEWMIDDLEWARE('login', function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse\n\t\t$.redirect('/login/');\n});\n```\n\n### ROUTE('METHOD /url/ #name', action)\n\nType: `property`\n\nElenca un middleware nella dichiarazione di una route.\n\nOgni `#name` nella stringa della route aggiunge quel middleware alla route; vengono eseguiti nell'ordine in cui sono scritti. Il flag funziona per le route HTTP, le route `API` e le route `SOCKET`. Il nome può contenere lettere, cifre e `_`. Un nome non registrato viene saltato; in una route `SOCKET` vengono saltati anche i middleware successivi.\n\nExample: Due middleware\n```js\nROUTE('POST /api/upload/ #apikey #ratelimit', upload);\nROUTE('SOCKET /live/ #apikey', live);\n```\n\n### NEWACTION({ middleware: 'name1, name2' })\n\nType: `property`\n\nMiddleware eseguito prima di un'azione.\n\nL'opzione `middleware` di `NEWACTION()` è un elenco di nomi di middleware separati da virgole, spazi o `|`. Vengono eseguiti con il `$` dell'azione ogni volta che l'azione viene chiamata, prima della funzione `action`. Un nome non registrato viene segnalato con `Total.error()` e saltato.\n\nExample: Azione con middleware\n```js\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\n### middleware/*.js\n\nType: `type`\n\nCartella con i file che registrano i middleware.\n\nI file `.js` in `middleware/` e in `plugins/<name>/middleware/` vengono caricati all'avvio; viene eseguita la loro funzione `install()`. Usala per tenere i middleware separati dai controller.\n\nExample: middleware/auth.js\n```js\nexports.install = function() {\n\tNEWMIDDLEWARE('admin', function($, next) {\n\t\tif ($.user && $.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWMIDDLEWARE(name, fn, [assign])","signature":"NEWMIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"method","name":"MIDDLEWARE(name, fn, [assign])","signature":"MIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"delegate","name":"middleware handler","signature":"function($, next)","since":"","deprecated":false},{"type":"property","name":"#name route flag","signature":"ROUTE('METHOD /url/ #name', action)","since":"","deprecated":false},{"type":"property","name":"NEWACTION middleware","signature":"NEWACTION({ middleware: 'name1, name2' })","since":"","deprecated":false},{"type":"type","name":"middleware folder","signature":"middleware/*.js","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafiy14k861f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/middleware/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Middleware","summary":"NEWMIDDLEWARE(), handler middleware, príznak routy #name a voľba middleware v akciách.","markdown":"---\ntitle: Middleware\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/middleware/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Middleware\n\n> NEWMIDDLEWARE(), handler middleware, príznak routy #name a voľba middleware v akciách.\n\n## API\n\n### NEWMIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nZaregistruje pomenovaný middleware alebo ho odstráni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov middleware, používa sa ako `#name` v trasách. Písmená, číslice a `_`. |\n| `fn` | `Function` | no |  | `function($, next)`. Bez nej sa middleware odstráni. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` alebo `websockets`, oddelené čiarkami. |\n\nReturns: `undefined`\n\nFunkcia sa spustí ako `fn($, next)` pre každú trasu, ktorá uvádza daný názov. Pri HTTP a socket trasách je `$` kontrolér; pri akciách je to `$` akcie. Zavolaj `next()`, ak chceš pokračovať, alebo odpovedz na požiadavku, ak ju chceš zastaviť.\n\n`assign` pridá middleware k trasám, ktoré už existujú: `'routes'` alebo `'dynamic'` pre HTTP trasy, `'websockets'` pre socket trasy, viacero hodnôt oddelených čiarkami alebo ako pole. Trasy zaregistrované neskôr ho nedostanú.\n\nAk sa zavolá len s `name`, odstráni middleware z registra a zo všetkých trás.\n\nExample: Kontrola API kľúča\n```js\nNEWMIDDLEWARE('apikey', function($, next) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\tnext();\n\telse\n\t\t$.invalid(401);\n});\n\nROUTE('GET /api/orders/ #apikey', function($) {\n\t$.json([]);\n});\n```\n\nExample: Odstránenie middleware\n```js\nNEWMIDDLEWARE('apikey');\n```\n\n### MIDDLEWARE(name, fn, [assign])\n\nType: `method`\n\nTá istá funkcia ako `NEWMIDDLEWARE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov middleware. |\n| `fn` | `Function` | no |  | `function($, next)`. Bez nej sa middleware odstráni. |\n| `assign` | `String|Array` | no |  | `routes`, `dynamic` alebo `websockets`. |\n\nReturns: `undefined`\n\n`MIDDLEWARE` a `NEWMIDDLEWARE` sú dva názvy jednej funkcie; argumenty aj správanie sú rovnaké.\n\nExample: Registrácia\n```js\nMIDDLEWARE('timing', function($, next) {\n\t$.started = Date.now();\n\tnext();\n});\n```\n\n### function($, next)\n\nType: `delegate`\n\nFunkcia middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Options` | yes |  | Kontrolér požiadavky, alebo `$` akcie. |\n| `next` | `Function` | yes |  | Pokračuje ďalším middleware alebo akciou. |\n\nDostane kontrolér (alebo vo vnútri akcie `$` akcie) a callback `next`. Volanie `next()` spustí ďalší middleware trasy a po poslednom akciu. Ak `next()` nezavoláš, reťazec sa zastaví; vtedy musí middleware odpovedať na požiadavku sám, napríklad pomocou `$.invalid(401)`, `$.redirect(url)` alebo `$.json(data)`.\n\nPri HTTP trasách sú telo, query, parametre URL a `$.user` už nastavené, keď sa middleware spustí.\n\nExample: Presmerovanie anonymných používateľov\n```js\nNEWMIDDLEWARE('login', function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse\n\t\t$.redirect('/login/');\n});\n```\n\n### ROUTE('METHOD /url/ #name', action)\n\nType: `property`\n\nUvedie middleware v deklarácii trasy.\n\nKaždé `#name` v reťazci routy pridá daný middleware k route; spúšťajú sa v zapísanom poradí. Flag funguje pre HTTP routy, routy `API` a routy `SOCKET`. Názov môže obsahovať písmená, číslice a `_`. Názov, ktorý nie je zaregistrovaný, sa preskočí; v route `SOCKET` sa preskočia aj middleware za ním.\n\nExample: Dva middleware\n```js\nROUTE('POST /api/upload/ #apikey #ratelimit', upload);\nROUTE('SOCKET /live/ #apikey', live);\n```\n\n### NEWACTION({ middleware: 'name1, name2' })\n\nType: `property`\n\nMiddleware, ktorý sa spustí pred akciou.\n\nVoľba `middleware` v `NEWACTION()` je zoznam názvov middleware oddelených čiarkami, medzerami alebo `|`. Spúšťajú sa s `$` akcie pri každom volaní akcie, pred funkciou `action`. Názov, ktorý nie je zaregistrovaný, sa nahlási pomocou `Total.error()` a preskočí sa.\n\nExample: Akcia s middleware\n```js\nNEWACTION({\n\tname: 'Orders/list',\n\tmiddleware: 'tenant',\n\taction: function($) {\n\t\t$.callback([]);\n\t}\n});\n```\n\n### middleware/*.js\n\nType: `type`\n\nPriečinok so súbormi, ktoré registrujú middleware.\n\nSúbory `.js` v `middleware/` a v `plugins/<name>/middleware/` sa načítajú pri štarte; spustí sa ich funkcia `install()`. Použi ho, ak chceš mať middleware oddelene od kontrolérov.\n\nExample: middleware/auth.js\n```js\nexports.install = function() {\n\tNEWMIDDLEWARE('admin', function($, next) {\n\t\tif ($.user && $.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\t$.invalid(401);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWMIDDLEWARE(name, fn, [assign])","signature":"NEWMIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"method","name":"MIDDLEWARE(name, fn, [assign])","signature":"MIDDLEWARE(name, fn, [assign])","since":"","deprecated":false},{"type":"delegate","name":"middleware handler","signature":"function($, next)","since":"","deprecated":false},{"type":"property","name":"#name route flag","signature":"ROUTE('METHOD /url/ #name', action)","since":"","deprecated":false},{"type":"property","name":"NEWACTION middleware","signature":"NEWACTION({ middleware: 'name1, name2' })","since":"","deprecated":false},{"type":"type","name":"middleware folder","signature":"middleware/*.js","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafj4b4pu60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/static-files/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Static files","summary":"The public folder, cache headers, compression, ranges, MERGE(), TOUCH() and their configuration.","markdown":"---\ntitle: Static files\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/static-files/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Static files\n\n> The public folder, cache headers, compression, ranges, MERGE(), TOUCH() and their configuration.\n\n## API\n\n### public/\n\nType: `type`\n\nThe folder of static files.\n\nA request whose URL has an extension is served from `public/`: `/img/logo.png` is `public/img/logo.png`. The folder can be changed with `CONF.$dirpublic`. Only extensions listed in `CONF.$httpfiles` are served. File requests with `POST`, `PUT`, `PATCH` or `DELETE` are closed; `HEAD` returns the headers only.\n\nExample: Structure\n```text\npublic/\n\tcss/default.css\n\tjs/app.js\n\timg/logo.png\n\tfavicon.ico\n\tmanifest.webmanifest\n```\n\n### /_<plugin>/<path>\n\nType: `type`\n\nURLs that read static files from a plugin.\n\nA file URL that starts with `/_` and a plugin name reads from the `public/` folder of that plugin: `/_shop/css/shop.css` is `plugins/shop/public/css/shop.css`. The files get the same minification and caching as files of the app.\n\nExample: Link a plugin file\n```html\n<link rel=\"stylesheet\" href=\"/_shop/css/shop.css\" />\n```\n\n### *.min.js, *-min.css, *@min.js\n\nType: `type`\n\nFiles that are sent without minification.\n\nA `.js`, `.css` or `.html` file whose path contains `.min`, `-min` or `@min` is streamed as it is. Other files of these types are minified when the matching `$minify*` option is on.\n\nExample: Sent unchanged\n```text\n/js/jquery.min.js\n/css/bootstrap-min.css\n/js/spa@min.js\n```\n\n### Expires, Cache-Control, Last-Modified, ETag\n\nType: `type`\n\nHTTP cache headers of static files.\n\nStatic files get `Expires` (`CONF.$httpexpire`, one year ahead), `Cache-Control: public, must-revalidate, max-age=<CONF.$httpmaxage>`, `Last-Modified` with the file date and `ETag: 858<CONF.$httpetag>`. When the browser sends the same `If-Modified-Since` date, the answer is `304 Not Modified`.\n\n`.zip` and `.rar` files, and `.js`, `.css` and `.html` files in debug mode, are sent with `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: Response headers\n```text\nCache-Control: public, must-revalidate, max-age=60\nLast-Modified: Mon, 02 Nov 2026 10:00:00 GMT\nETag: 858100\n```\n\n### Content-Encoding: gzip\n\nType: `type`\n\nGzip compression of static files.\n\nWith `CONF.$httpcompress` on and `Accept-Encoding: gzip` in the request, text files are compressed: `text/plain`, JavaScript, `text/css`, `text/jsx`, `text/html`, JSON, XML, `image/svg+xml`, Markdown and notebook files. Text types are sent with `charset=utf-8`. Other types are not compressed.\n\n### Range: bytes=<start>-<end>\n\nType: `type`\n\nPartial responses for large files.\n\nA request with a `Range` header gets `206 Partial Content` with `Content-Range`. When the range has no end, at most `CONF.$httprangebuffer` kB are sent. Players use this to stream video and audio. A range that starts after the end of the file closes the connection; an end after the end of the file is cut to the last byte.\n\nExample: Request\n```text\nGET /video/intro.mp4\nRange: bytes=0-\n```\n\n### application/manifest+json\n\nType: `type`\n\nWeb app manifest files.\n\n`webmanifest` is in the default `CONF.$httpfiles`, so `public/manifest.webmanifest` is served with the content type `application/manifest+json`.\n\nExample: Link the manifest\n```html\n<link rel=\"manifest\" href=\"/manifest.webmanifest\" />\n```\n\n### $.resume()\n\nType: `method`\n\nSends the static file of the request the normal way.\n\nIn a `FILE` route, `$.resume()` hands the request back to static file handling: the matching file from `public/` (or from a plugin) is sent with minification, caching and compression.\n\nExample: Check before sending\n```js\nROUTE('FILE /docs/*.pdf', function($) {\n\tif ($.query.key === CONF.docskey)\n\t\t$.resume();\n\telse\n\t\t$.fallback(401);\n});\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nAnswers 304 when the browser already has this version.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | A UTC date string, the same value you send in `Last-Modified`. |\n\nReturns: `Boolean` `true` when the 304 response was sent.\n\nCompares `date` with the `If-Modified-Since` header. When they are equal, it sends `304 Not Modified` with the cache headers and returns `true`; otherwise it returns `undefined` and you send the response.\n\nExample: Cache a generated file\n```js\nROUTE('GET /feed/', function($) {\n\tvar date = MAIN.feeddate.toUTCString();\n\tif ($.notmodified(date))\n\t\treturn;\n\t$.httpcache(date);\n\t$.plain(MAIN.feed);\n});\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nAdds the static cache headers to the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | The date of the content. |\n\nSets `Expires` and `Cache-Control` (unless already set), `Last-Modified` to `date` and `ETag`, the same headers static files get. Use it with `$.notmodified()` for generated content.\n\nExample: Generated content\n```js\n$.httpcache(new Date(2026, 0, 1));\n$.plain('Hello');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nClears the cached state of static files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | URL of the file, for example `/css/default.css`. |\n\nRemoves the stored minified file, the stored date and size and the not-found mark of one URL, or of all static files when `url` is missing. The next request reads the file again. Use the URL as the browser requests it, with the case of the file name and with `CONF.$root` when it is set. Static HTML translated by `LOCALIZE()` is cached per language, so for it call `TOUCH()` without an argument.\n\nExample: After writing a file\n```js\nTotal.Fs.writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### MERGE(url, file1, [file2], [...])\n\nType: `method`\n\nCreates a virtual file made of several files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL of the merged file, for example `/css/all.css`. |\n| `files` | `String|Array` | yes |  | Files to merge, as more arguments. |\n\nReturns: `String` The URL of the merged file.\n\nRegisters `url` as a file built from the listed files and returns the URL. Each file argument is a string (several names joined with `+`) or an array of absolute file paths or URLs, used as they are. In a string, a name without a slash is taken from `public/js/` for `.js` and `public/css/` otherwise; a path with `/` is relative to `public/`; `~` starts an absolute path; `http://` and `https://` are downloaded. Each local file is minified by its type setting unless its name marks it as minified; downloaded files are added as they are. In release mode the result is built once and saved to `tmp/`; in debug mode it is built on every request. With `CONF.$root`, the returned URL contains the root.\n\nExample: CSS and JS bundles\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/app.js + /js/forms.js');\n};\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nSets the delegate that picks the language of a request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)` that returns the language. |\n\n`fn($)` returns a language code. It is called for routes, sockets and static `.html` files; static HTML is translated into that language and cached per language. The full topic is in [Localization](../../guides/localization/).\n\nExample: Language from the header\n```js\nLOCALIZE(function($) {\n\treturn ($.headers['accept-language'] || 'en').substring(0, 2);\n});\n```\n\n### PATH.public([path])\n\nType: `method`\n\nReturns the path of a file in the public folder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Relative path. |\n\nReturns: `String` Absolute path.\n\nJoins `path` to the `public/` folder (or `CONF.$dirpublic`). Without `path`, it returns the folder.\n\nExample: Write a public file\n```js\nTotal.Fs.writeFile(PATH.public('robots.txt'), 'User-agent: *', NOOP);\n```\n\n### $dirpublic\n\nType: `config`\n\nFolder of static files.\n\nReturns: `String`\n\nAn absolute path to use instead of `public/` in the app folder.\n\nDefault: `'' (public/)`.\n\nExample: Config file\n```text\n$dirpublic : /www/static\n```\n\n### $httpfiles\n\nType: `config`\n\nExtensions served as static files.\n\nReturns: `Object`\n\nIn the config file, list extensions separated by commas; they are added to the default list, which contains among others `jpg`, `png`, `gif`, `webp`, `svg`, `ico`, `js`, `mjs`, `css`, `html`, `json`, `txt`, `xml`, `md`, `map`, `woff`, `woff2`, `ttf`, `pdf`, `zip`, `mp3`, `mp4`, `webm`, `wasm` and `webmanifest`.\n\nDefault: `a list of common web types`.\n\nExample: Config file\n```text\n$httpfiles : avif, glb\n```\n\n### $httpcompress\n\nType: `config`\n\nGzip compression of responses.\n\nReturns: `Boolean`\n\nWhen on, text static files and text responses are compressed for clients that accept gzip.\n\nDefault: `true`.\n\nExample: Config file\n```text\n$httpcompress : false\n```\n\n### $httpmaxage\n\nType: `config`\n\nThe max-age of static files, in seconds.\n\nReturns: `Number`\n\nUsed in `Cache-Control: public, must-revalidate, max-age=<value>`. After this time the browser asks again and usually gets 304.\n\nDefault: `60`.\n\nExample: Config file\n```text\n$httpmaxage : 300\n```\n\n### CONF.$httpexpire\n\nType: `config`\n\nThe Expires header of static files.\n\nReturns: `String`\n\nA UTC date one year ahead. Total.js sets it at start and refreshes it every hour; do not set it in the config file.\n\n### $httpetag\n\nType: `config`\n\nSuffix of the ETag header.\n\nReturns: `String`\n\nThe ETag of static files is `858` + this value. When it is empty, the app `version` without dots and spaces is used, so a new version changes the ETag.\n\nDefault: `'' (from version)`.\n\nExample: Config file\n```text\n$httpetag : build42\n```\n\n### $httprangebuffer\n\nType: `config`\n\nMaximum size of an open range, in kB.\n\nReturns: `Number`\n\nFor a `Range` header without an end, this many kB are sent.\n\nDefault: `5120`.\n\nExample: Config file\n```text\n$httprangebuffer : 10240\n```\n\n### $minifyjs\n\nType: `config`\n\nMinifies JavaScript files.\n\nReturns: `Boolean`\n\nMinifies static `.js` files, files sent with `$.file()` and merged files. Files with `.min`, `-min` or `@min` are not minified.\n\nDefault: `true`.\n\nExample: Config file\n```text\n$minifyjs : false\n```\n\n### $minifycss\n\nType: `config`\n\nMinifies CSS files.\n\nReturns: `Boolean`\n\nMinifies static `.css` files, files sent with `$.file()` and merged files.\n\nDefault: `true`.\n\nExample: Config file\n```text\n$minifycss : false\n```\n\n### $minifyhtml\n\nType: `config`\n\nMinifies HTML.\n\nReturns: `Boolean`\n\nMinifies static `.html` files and HTML responses.\n\nDefault: `true`.\n\nExample: Config file\n```text\n$minifyhtml : false\n```\n\n### $root\n\nType: `config`\n\nRoot path of the app.\n\nReturns: `String`\n\nWhen the app runs under a path, for example `/app/`, the root is removed from static URLs before the file is looked up, and `MERGE()` returns URLs with the root. Details in [Configuration](../../guides/configuration/).\n\nDefault: `''`.\n\nExample: Config file\n```text\n$root : /app/\n```\n\n### $httpcacheoffset\n\nType: `config` · Since: `0.0.16`\n\nMoves the Last-Modified date of static files.\n\nReturns: `String`\n\nA time such as `1 minute` added to the file date in the `Last-Modified` header of static files. See [Configuration](../../guides/configuration/).\n\nDefault: `''`.\n\nExample: Config file\n```text\n$httpcacheoffset : 1 minute\n```\n","entries":[{"type":"type","name":"public folder","signature":"public/","since":"","deprecated":false},{"type":"type","name":"plugin public files","signature":"/_<plugin>/<path>","since":"","deprecated":false},{"type":"type","name":"minified file names","signature":"*.min.js, *-min.css, *@min.js","since":"","deprecated":false},{"type":"type","name":"static cache headers","signature":"Expires, Cache-Control, Last-Modified, ETag","since":"","deprecated":false},{"type":"type","name":"static compression","signature":"Content-Encoding: gzip","since":"","deprecated":false},{"type":"type","name":"Range requests","signature":"Range: bytes=<start>-<end>","since":"","deprecated":false},{"type":"type","name":".webmanifest","signature":"application/manifest+json","since":"","deprecated":false},{"type":"method","name":"controller.resume()","signature":"$.resume()","since":"","deprecated":false},{"type":"method","name":"controller.notmodified(date)","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"controller.httpcache(date)","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"TOUCH([url])","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"MERGE(url, files...)","signature":"MERGE(url, file1, [file2], [...])","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(fn)","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"PATH.public([path])","signature":"PATH.public([path])","since":"","deprecated":false},{"type":"config","name":"$dirpublic","signature":"$dirpublic","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage","since":"","deprecated":false},{"type":"config","name":"$httpexpire","signature":"CONF.$httpexpire","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer","since":"","deprecated":false},{"type":"config","name":"$minifyjs","signature":"$minifyjs","since":"","deprecated":false},{"type":"config","name":"$minifycss","signature":"$minifycss","since":"","deprecated":false},{"type":"config","name":"$minifyhtml","signature":"$minifyhtml","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafj4b4pu60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/static-files/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Statische Dateien","summary":"Der öffentliche Ordner, Cache-Header, Kompression, Ranges, MERGE(), TOUCH() und ihre Konfiguration.","markdown":"---\ntitle: Statische Dateien\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/static-files/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Statische Dateien\n\n> Der öffentliche Ordner, Cache-Header, Kompression, Ranges, MERGE(), TOUCH() und ihre Konfiguration.\n\n## API\n\n### public/\n\nType: `type`\n\nDer Ordner der statischen Dateien.\n\nEine Anfrage, deren URL eine Endung hat, wird aus `public/` ausgeliefert: `/img/logo.png` ist `public/img/logo.png`. Der Ordner kann mit `CONF.$dirpublic` geändert werden. Nur Endungen, die in `CONF.$httpfiles` aufgeführt sind, werden ausgeliefert. Dateianfragen mit `POST`, `PUT`, `PATCH` oder `DELETE` werden geschlossen; `HEAD` liefert nur die Header.\n\nExample: Struktur\n```text\npublic/\n\tcss/default.css\n\tjs/app.js\n\timg/logo.png\n\tfavicon.ico\n\tmanifest.webmanifest\n```\n\n### /_<plugin>/<path>\n\nType: `type`\n\nURLs, die statische Dateien aus einem Plugin lesen.\n\nEine Datei-URL, die mit `/_` und einem Plugin-Namen beginnt, liest aus dem Ordner `public/` dieses Plugins: `/_shop/css/shop.css` ist `plugins/shop/public/css/shop.css`. Die Dateien erhalten dieselbe Minifizierung und dasselbe Caching wie die Dateien der App.\n\nExample: Eine Plugin-Datei verlinken\n```html\n<link rel=\"stylesheet\" href=\"/_shop/css/shop.css\" />\n```\n\n### *.min.js, *-min.css, *@min.js\n\nType: `type`\n\nDateien, die ohne Minifizierung gesendet werden.\n\nEine `.js`-, `.css`- oder `.html`-Datei, deren Pfad `.min`, `-min` oder `@min` enthält, wird unverändert gestreamt. Andere Dateien dieser Typen werden minifiziert, wenn die passende `$minify*`-Option aktiviert ist.\n\nExample: Unverändert gesendet\n```text\n/js/jquery.min.js\n/css/bootstrap-min.css\n/js/spa@min.js\n```\n\n### Expires, Cache-Control, Last-Modified, ETag\n\nType: `type`\n\nHTTP-Cache-Header statischer Dateien.\n\nStatische Dateien erhalten `Expires` (`CONF.$httpexpire`, ein Jahr in der Zukunft), `Cache-Control: public, must-revalidate, max-age=<CONF.$httpmaxage>`, `Last-Modified` mit dem Datum der Datei und `ETag: 858<CONF.$httpetag>`. Wenn der Browser dasselbe `If-Modified-Since`-Datum sendet, lautet die Antwort `304 Not Modified`.\n\n`.zip`- und `.rar`-Dateien sowie im Debug-Modus `.js`-, `.css`- und `.html`-Dateien werden mit `Cache-Control: private, no-cache, no-store, max-age=0` gesendet.\n\nExample: Antwort-Header\n```text\nCache-Control: public, must-revalidate, max-age=60\nLast-Modified: Mon, 02 Nov 2026 10:00:00 GMT\nETag: 858100\n```\n\n### Content-Encoding: gzip\n\nType: `type`\n\nGzip-Komprimierung statischer Dateien.\n\nMit aktiviertem `CONF.$httpcompress` und `Accept-Encoding: gzip` in der Anfrage werden Textdateien komprimiert: `text/plain`, JavaScript, `text/css`, `text/jsx`, `text/html`, JSON, XML, `image/svg+xml`, Markdown und Notebook-Dateien. Text-Typen werden mit `charset=utf-8` gesendet. Andere Typen werden nicht komprimiert.\n\n### Range: bytes=<start>-<end>\n\nType: `type`\n\nTeilantworten für große Dateien.\n\nEine Anfrage mit einem `Range`-Header erhält `206 Partial Content` mit `Content-Range`. Hat der Range kein Ende, werden höchstens `CONF.$httprangebuffer` kB gesendet. Player nutzen das, um Video und Audio zu streamen. Ein Range, der nach dem Ende der Datei beginnt, schließt die Verbindung; ein Ende nach dem Ende der Datei wird auf das letzte Byte gekürzt.\n\nExample: Anfrage\n```text\nGET /video/intro.mp4\nRange: bytes=0-\n```\n\n### application/manifest+json\n\nType: `type`\n\nWeb-App-Manifest-Dateien.\n\n`webmanifest` ist im Standardwert von `CONF.$httpfiles` enthalten, sodass `public/manifest.webmanifest` mit dem Content-Type `application/manifest+json` ausgeliefert wird.\n\nExample: Das Manifest verlinken\n```html\n<link rel=\"manifest\" href=\"/manifest.webmanifest\" />\n```\n\n### $.resume()\n\nType: `method`\n\nSendet die statische Datei der Anfrage auf normalem Weg.\n\nIn einer `FILE`-Route gibt `$.resume()` die Anfrage an die Behandlung statischer Dateien zurück: Die passende Datei aus `public/` (oder aus einem Plugin) wird mit Minifizierung, Caching und Komprimierung gesendet.\n\nExample: Vor dem Senden prüfen\n```js\nROUTE('FILE /docs/*.pdf', function($) {\n\tif ($.query.key === CONF.docskey)\n\t\t$.resume();\n\telse\n\t\t$.fallback(401);\n});\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nAntwortet mit 304, wenn der Browser diese Version bereits hat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Ein UTC-Datumsstring, derselbe Wert, den du in `Last-Modified` sendest. |\n\nReturns: `Boolean` `true`, wenn die 304-Antwort gesendet wurde.\n\nVergleicht `date` mit dem Header `If-Modified-Since`. Wenn beide gleich sind, sendet sie `304 Not Modified` mit den Cache-Headern und gibt `true` zurück; andernfalls gibt sie `undefined` zurück, und du sendest die Antwort.\n\nExample: Eine erzeugte Datei cachen\n```js\nROUTE('GET /feed/', function($) {\n\tvar date = MAIN.feeddate.toUTCString();\n\tif ($.notmodified(date))\n\t\treturn;\n\t$.httpcache(date);\n\t$.plain(MAIN.feed);\n});\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nFügt der Antwort die statischen Cache-Header hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | Das Datum des Inhalts. |\n\nSetzt `Expires` und `Cache-Control` (sofern nicht bereits gesetzt), `Last-Modified` auf `date` und `ETag`, also dieselben Header, die statische Dateien erhalten. Verwende sie mit `$.notmodified()` für erzeugte Inhalte.\n\nExample: Erzeugter Inhalt\n```js\n$.httpcache(new Date(2026, 0, 1));\n$.plain('Hello');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nLeert den gecachten Zustand statischer Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | URL der Datei, zum Beispiel `/css/default.css`. |\n\nEntfernt die gespeicherte minifizierte Datei, das gespeicherte Datum und die Größe sowie die Markierung „nicht gefunden“ einer URL oder aller statischen Dateien, wenn `url` fehlt. Die nächste Anfrage liest die Datei erneut. Verwende die URL so, wie der Browser sie anfragt, mit der Groß- und Kleinschreibung des Dateinamens und mit `CONF.$root`, wenn es gesetzt ist. Von `LOCALIZE()` übersetztes statisches HTML wird pro Sprache gecacht; rufe dafür `TOUCH()` ohne Argument auf.\n\nExample: Nach dem Schreiben einer Datei\n```js\nTotal.Fs.writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### MERGE(url, file1, [file2], [...])\n\nType: `method`\n\nErstellt eine virtuelle Datei aus mehreren Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL der zusammengeführten Datei, zum Beispiel `/css/all.css`. |\n| `files` | `String|Array` | yes |  | Zusammenzuführende Dateien, als weitere Argumente. |\n\nReturns: `String` Die URL der zusammengeführten Datei.\n\nRegistriert `url` als eine aus den aufgeführten Dateien gebaute Datei und gibt die URL zurück. Jedes Dateiargument ist ein String (mehrere mit `+` verbundene Namen) oder ein Array absoluter Dateipfade oder URLs, die unverändert verwendet werden. In einem String wird ein Name ohne Schrägstrich aus `public/js/` für `.js` und sonst aus `public/css/` genommen; ein Pfad mit `/` ist relativ zu `public/`; `~` leitet einen absoluten Pfad ein; `http://` und `https://` werden heruntergeladen. Jede lokale Datei wird gemäß der Einstellung ihres Typs minifiziert, außer ihr Name kennzeichnet sie als minifiziert; heruntergeladene Dateien werden unverändert hinzugefügt. Im Release-Modus wird das Ergebnis einmal gebaut und in `tmp/` gespeichert; im Debug-Modus wird es bei jeder Anfrage gebaut. Mit `CONF.$root` enthält die zurückgegebene URL das Stammverzeichnis.\n\nExample: CSS- und JS-Bundles\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/app.js + /js/forms.js');\n};\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nSetzt den Delegate, der die Sprache einer Anfrage wählt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)`, die die Sprache zurückgibt. |\n\n`fn($)` gibt einen Sprachcode zurück. Er wird für Routen, Sockets und statische `.html`-Dateien aufgerufen; statisches HTML wird in diese Sprache übersetzt und pro Sprache gecacht. Das vollständige Thema findest du unter [Lokalisierung](../../guides/localization/).\n\nExample: Sprache aus dem Header\n```js\nLOCALIZE(function($) {\n\treturn ($.headers['accept-language'] || 'en').substring(0, 2);\n});\n```\n\n### PATH.public([path])\n\nType: `method`\n\nGibt den Pfad einer Datei im Ordner public zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Relativer Pfad. |\n\nReturns: `String` Absoluter Pfad.\n\nVerbindet `path` mit dem Ordner `public/` (oder `CONF.$dirpublic`). Ohne `path` gibt sie den Ordner zurück.\n\nExample: Eine öffentliche Datei schreiben\n```js\nTotal.Fs.writeFile(PATH.public('robots.txt'), 'User-agent: *', NOOP);\n```\n\n### $dirpublic\n\nType: `config`\n\nOrdner der statischen Dateien.\n\nReturns: `String`\n\nEin absoluter Pfad, der statt `public/` im App-Ordner verwendet wird.\n\nStandard: `'' (public/)`.\n\nExample: Konfigurationsdatei\n```text\n$dirpublic : /www/static\n```\n\n### $httpfiles\n\nType: `config`\n\nEndungen, die als statische Dateien ausgeliefert werden.\n\nReturns: `Object`\n\nListe in der Konfigurationsdatei Endungen durch Kommas getrennt auf; sie werden zur Standardliste hinzugefügt, die unter anderem `jpg`, `png`, `gif`, `webp`, `svg`, `ico`, `js`, `mjs`, `css`, `html`, `json`, `txt`, `xml`, `md`, `map`, `woff`, `woff2`, `ttf`, `pdf`, `zip`, `mp3`, `mp4`, `webm`, `wasm` und `webmanifest` enthält.\n\nStandard: `a list of common web types`.\n\nExample: Konfigurationsdatei\n```text\n$httpfiles : avif, glb\n```\n\n### $httpcompress\n\nType: `config`\n\nGzip-Komprimierung von Antworten.\n\nReturns: `Boolean`\n\nWenn aktiviert, werden statische Textdateien und Textantworten für Clients komprimiert, die gzip akzeptieren.\n\nStandard: `true`.\n\nExample: Konfigurationsdatei\n```text\n$httpcompress : false\n```\n\n### $httpmaxage\n\nType: `config`\n\nDas max-age statischer Dateien, in Sekunden.\n\nReturns: `Number`\n\nWird in `Cache-Control: public, must-revalidate, max-age=<value>` verwendet. Nach dieser Zeit fragt der Browser erneut und erhält in der Regel 304.\n\nStandard: `60`.\n\nExample: Konfigurationsdatei\n```text\n$httpmaxage : 300\n```\n\n### CONF.$httpexpire\n\nType: `config`\n\nDer Header Expires statischer Dateien.\n\nReturns: `String`\n\nEin UTC-Datum ein Jahr in der Zukunft. Total.js setzt es beim Start und aktualisiert es stündlich; setze es nicht in der Konfigurationsdatei.\n\n### $httpetag\n\nType: `config`\n\nSuffix des Headers ETag.\n\nReturns: `String`\n\nDas ETag statischer Dateien ist `858` + dieser Wert. Ist er leer, wird die `version` der App ohne Punkte und Leerzeichen verwendet, sodass eine neue Version das ETag ändert.\n\nStandard: `'' (from version)`.\n\nExample: Konfigurationsdatei\n```text\n$httpetag : build42\n```\n\n### $httprangebuffer\n\nType: `config`\n\nMaximale Größe eines offenen Ranges, in kB.\n\nReturns: `Number`\n\nBei einem Header `Range` ohne Ende werden so viele kB gesendet.\n\nStandard: `5120`.\n\nExample: Konfigurationsdatei\n```text\n$httprangebuffer : 10240\n```\n\n### $minifyjs\n\nType: `config`\n\nMinifiziert JavaScript-Dateien.\n\nReturns: `Boolean`\n\nMinifiziert statische `.js`-Dateien, mit `$.file()` gesendete Dateien und zusammengeführte Dateien. Dateien mit `.min`, `-min` oder `@min` werden nicht minifiziert.\n\nStandard: `true`.\n\nExample: Konfigurationsdatei\n```text\n$minifyjs : false\n```\n\n### $minifycss\n\nType: `config`\n\nMinifiziert CSS-Dateien.\n\nReturns: `Boolean`\n\nMinifiziert statische `.css`-Dateien, mit `$.file()` gesendete Dateien und zusammengeführte Dateien.\n\nStandard: `true`.\n\nExample: Konfigurationsdatei\n```text\n$minifycss : false\n```\n\n### $minifyhtml\n\nType: `config`\n\nMinifiziert HTML.\n\nReturns: `Boolean`\n\nMinifiziert statische `.html`-Dateien und HTML-Antworten.\n\nStandard: `true`.\n\nExample: Konfigurationsdatei\n```text\n$minifyhtml : false\n```\n\n### $root\n\nType: `config`\n\nRoot-Pfad der App.\n\nReturns: `String`\n\nWenn die App unter einem Pfad läuft, zum Beispiel `/app/`, wird der Root aus statischen URLs entfernt, bevor die Datei gesucht wird, und `MERGE()` gibt URLs mit dem Root zurück. Details unter [Konfiguration](../../guides/configuration/).\n\nStandard: `''`.\n\nExample: Konfigurationsdatei\n```text\n$root : /app/\n```\n\n### $httpcacheoffset\n\nType: `config` · Since: `0.0.16`\n\nVerschiebt das Last-Modified-Datum statischer Dateien.\n\nReturns: `String`\n\nEine Zeitangabe wie `1 minute`, die im `Last-Modified`-Header statischer Dateien zum Dateidatum addiert wird. Siehe [Konfiguration](../../guides/configuration/).\n\nStandard: `''`.\n\nExample: Konfigurationsdatei\n```text\n$httpcacheoffset : 1 minute\n```\n","entries":[{"type":"type","name":"public folder","signature":"public/","since":"","deprecated":false},{"type":"type","name":"plugin public files","signature":"/_<plugin>/<path>","since":"","deprecated":false},{"type":"type","name":"minified file names","signature":"*.min.js, *-min.css, *@min.js","since":"","deprecated":false},{"type":"type","name":"static cache headers","signature":"Expires, Cache-Control, Last-Modified, ETag","since":"","deprecated":false},{"type":"type","name":"static compression","signature":"Content-Encoding: gzip","since":"","deprecated":false},{"type":"type","name":"Range requests","signature":"Range: bytes=<start>-<end>","since":"","deprecated":false},{"type":"type","name":".webmanifest","signature":"application/manifest+json","since":"","deprecated":false},{"type":"method","name":"controller.resume()","signature":"$.resume()","since":"","deprecated":false},{"type":"method","name":"controller.notmodified(date)","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"controller.httpcache(date)","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"TOUCH([url])","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"MERGE(url, files...)","signature":"MERGE(url, file1, [file2], [...])","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(fn)","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"PATH.public([path])","signature":"PATH.public([path])","since":"","deprecated":false},{"type":"config","name":"$dirpublic","signature":"$dirpublic","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage","since":"","deprecated":false},{"type":"config","name":"$httpexpire","signature":"CONF.$httpexpire","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer","since":"","deprecated":false},{"type":"config","name":"$minifyjs","signature":"$minifyjs","since":"","deprecated":false},{"type":"config","name":"$minifycss","signature":"$minifycss","since":"","deprecated":false},{"type":"config","name":"$minifyhtml","signature":"$minifyhtml","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafj4b4pu60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/static-files/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Archivos estáticos","summary":"La carpeta pública, las cabeceras de caché, la compresión, los rangos, MERGE(), TOUCH() y su configuración.","markdown":"---\ntitle: \"Archivos estáticos\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/static-files/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Archivos estáticos\n\n> La carpeta pública, las cabeceras de caché, la compresión, los rangos, MERGE(), TOUCH() y su configuración.\n\n## API\n\n### public/\n\nType: `type`\n\nLa carpeta de archivos estáticos.\n\nUna petición cuya URL tiene una extensión se sirve desde `public/`: `/img/logo.png` es `public/img/logo.png`. La carpeta se puede cambiar con `CONF.$dirpublic`. Solo se sirven las extensiones de `CONF.$httpfiles`. Las peticiones de archivo con `POST`, `PUT`, `PATCH` o `DELETE` se cierran; `HEAD` solo devuelve las cabeceras.\n\nExample: Estructura\n```text\npublic/\n\tcss/default.css\n\tjs/app.js\n\timg/logo.png\n\tfavicon.ico\n\tmanifest.webmanifest\n```\n\n### /_<plugin>/<path>\n\nType: `type`\n\nURL que leen archivos estáticos de un plugin.\n\nUna URL de archivo que empieza por `/_` y el nombre de un plugin lee de la carpeta `public/` de ese plugin: `/_shop/css/shop.css` es `plugins/shop/public/css/shop.css`. Los archivos reciben la misma minificación y caché que los archivos de la app.\n\nExample: Enlazar un archivo de un plugin\n```html\n<link rel=\"stylesheet\" href=\"/_shop/css/shop.css\" />\n```\n\n### *.min.js, *-min.css, *@min.js\n\nType: `type`\n\nArchivos que se envían sin minificar.\n\nUn archivo `.js`, `.css` o `.html` cuya ruta contiene `.min`, `-min` o `@min` se envía como stream tal cual. Los demás archivos de estos tipos se minifican cuando la opción `$minify*` correspondiente está activada.\n\nExample: Enviado sin cambios\n```text\n/js/jquery.min.js\n/css/bootstrap-min.css\n/js/spa@min.js\n```\n\n### Expires, Cache-Control, Last-Modified, ETag\n\nType: `type`\n\nCabeceras de caché HTTP de los archivos estáticos.\n\nLos archivos estáticos reciben `Expires` (`CONF.$httpexpire`, un año en el futuro), `Cache-Control: public, must-revalidate, max-age=<CONF.$httpmaxage>`, `Last-Modified` con la fecha del archivo y `ETag: 858<CONF.$httpetag>`. Cuando el navegador envía la misma fecha `If-Modified-Since`, la respuesta es `304 Not Modified`.\n\nLos archivos `.zip` y `.rar`, y los archivos `.js`, `.css` y `.html` en modo debug, se envían con `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: Cabeceras de la respuesta\n```text\nCache-Control: public, must-revalidate, max-age=60\nLast-Modified: Mon, 02 Nov 2026 10:00:00 GMT\nETag: 858100\n```\n\n### Content-Encoding: gzip\n\nType: `type`\n\nCompresión gzip de los archivos estáticos.\n\nCon `CONF.$httpcompress` activado y `Accept-Encoding: gzip` en la petición, se comprimen los archivos de texto: `text/plain`, JavaScript, `text/css`, `text/jsx`, `text/html`, JSON, XML, `image/svg+xml`, Markdown y archivos de notebook. Los tipos de texto se envían con `charset=utf-8`. Los demás tipos no se comprimen.\n\n### Range: bytes=<start>-<end>\n\nType: `type`\n\nRespuestas parciales para archivos grandes.\n\nUna petición con una cabecera `Range` recibe `206 Partial Content` con `Content-Range`. Cuando el rango no tiene final, se envían como máximo `CONF.$httprangebuffer` kB. Los reproductores lo usan para transmitir vídeo y audio. Un rango que empieza después del final del archivo cierra la conexión; un final posterior al final del archivo se recorta al último byte.\n\nExample: Petición\n```text\nGET /video/intro.mp4\nRange: bytes=0-\n```\n\n### application/manifest+json\n\nType: `type`\n\nArchivos de manifiesto de aplicaciones web.\n\n`webmanifest` está en el `CONF.$httpfiles` por defecto, así que `public/manifest.webmanifest` se sirve con el content type `application/manifest+json`.\n\nExample: Enlazar el manifiesto\n```html\n<link rel=\"manifest\" href=\"/manifest.webmanifest\" />\n```\n\n### $.resume()\n\nType: `method`\n\nEnvía de la forma normal el archivo estático de la petición.\n\nEn una ruta `FILE`, `$.resume()` devuelve la petición a la gestión de archivos estáticos: el archivo correspondiente de `public/` (o de un plugin) se envía con minificación, caché y compresión.\n\nExample: Comprobar antes de enviar\n```js\nROUTE('FILE /docs/*.pdf', function($) {\n\tif ($.query.key === CONF.docskey)\n\t\t$.resume();\n\telse\n\t\t$.fallback(401);\n});\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nResponde 304 cuando el navegador ya tiene esta versión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Una cadena de fecha UTC, el mismo valor que envías en `Last-Modified`. |\n\nReturns: `Boolean` `true` cuando se envió la respuesta 304.\n\nCompara `date` con la cabecera `If-Modified-Since`. Cuando son iguales, envía `304 Not Modified` con las cabeceras de caché y devuelve `true`; si no, devuelve `undefined` y tú envías la respuesta.\n\nExample: Guardar en caché un archivo generado\n```js\nROUTE('GET /feed/', function($) {\n\tvar date = MAIN.feeddate.toUTCString();\n\tif ($.notmodified(date))\n\t\treturn;\n\t$.httpcache(date);\n\t$.plain(MAIN.feed);\n});\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nAñade a la respuesta las cabeceras de caché de los archivos estáticos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | La fecha del contenido. |\n\nEstablece `Expires` y `Cache-Control` (salvo que ya estén establecidas), `Last-Modified` a `date` y `ETag`, las mismas cabeceras que reciben los archivos estáticos. Úsalo con `$.notmodified()` para contenido generado.\n\nExample: Contenido generado\n```js\n$.httpcache(new Date(2026, 0, 1));\n$.plain('Hello');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nBorra el estado en caché de los archivos estáticos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | URL del archivo, por ejemplo `/css/default.css`. |\n\nElimina el archivo minificado guardado, la fecha y el tamaño guardados y la marca de no encontrado de una URL, o de todos los archivos estáticos cuando falta `url`. La siguiente petición vuelve a leer el archivo. Usa la URL tal como la pide el navegador, con las mayúsculas y minúsculas del nombre del archivo y con `CONF.$root` cuando está establecido. El HTML estático traducido por `LOCALIZE()` se guarda en caché por idioma, así que en ese caso llama a `TOUCH()` sin argumento.\n\nExample: Después de escribir un archivo\n```js\nTotal.Fs.writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### MERGE(url, file1, [file2], [...])\n\nType: `method`\n\nCrea un archivo virtual formado por varios archivos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL del archivo combinado, por ejemplo `/css/all.css`. |\n| `files` | `String|Array` | yes |  | Archivos que se combinan, como argumentos adicionales. |\n\nReturns: `String` La URL del archivo combinado.\n\nRegistra `url` como un archivo construido a partir de los archivos indicados y devuelve la URL. Cada argumento de archivo es un string (varios nombres unidos con `+`) o un array de rutas absolutas de archivos o URLs, que se usan tal cual. En un string, un nombre sin barra se toma de `public/js/` para `.js` y de `public/css/` en los demás casos; una ruta con `/` es relativa a `public/`; `~` inicia una ruta absoluta; `http://` y `https://` se descargan. Cada archivo local se minifica según el ajuste de su tipo, salvo que su nombre lo marque como minificado; los archivos descargados se añaden tal cual. En modo release el resultado se construye una vez y se guarda en `tmp/`; en modo debug se construye en cada petición. Con `CONF.$root`, la URL devuelta contiene la raíz.\n\nExample: Bundles de CSS y JS\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/app.js + /js/forms.js');\n};\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nEstablece el delegado que elige el idioma de una petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)` que devuelve el idioma. |\n\n`fn($)` devuelve un código de idioma. Se llama para las rutas, los sockets y los archivos `.html` estáticos; el HTML estático se traduce a ese idioma y se guarda en caché por idioma. El tema completo está en [Localización](../../guides/localization/).\n\nExample: Idioma desde la cabecera\n```js\nLOCALIZE(function($) {\n\treturn ($.headers['accept-language'] || 'en').substring(0, 2);\n});\n```\n\n### PATH.public([path])\n\nType: `method`\n\nDevuelve la ruta de un archivo de la carpeta pública.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ruta relativa. |\n\nReturns: `String` Ruta absoluta.\n\nUne `path` a la carpeta `public/` (o a `CONF.$dirpublic`). Sin `path`, devuelve la carpeta.\n\nExample: Escribir un archivo público\n```js\nTotal.Fs.writeFile(PATH.public('robots.txt'), 'User-agent: *', NOOP);\n```\n\n### $dirpublic\n\nType: `config`\n\nCarpeta de archivos estáticos.\n\nReturns: `String`\n\nUna ruta absoluta que se usa en lugar de `public/` en la carpeta de la app.\n\nPor defecto: `'' (public/)`.\n\nExample: Archivo de configuración\n```text\n$dirpublic : /www/static\n```\n\n### $httpfiles\n\nType: `config`\n\nExtensiones que se sirven como archivos estáticos.\n\nReturns: `Object`\n\nEn el archivo de configuración, indica las extensiones separadas por comas; se añaden a la lista por defecto, que contiene entre otras `jpg`, `png`, `gif`, `webp`, `svg`, `ico`, `js`, `mjs`, `css`, `html`, `json`, `txt`, `xml`, `md`, `map`, `woff`, `woff2`, `ttf`, `pdf`, `zip`, `mp3`, `mp4`, `webm`, `wasm` y `webmanifest`.\n\nPor defecto: `a list of common web types`.\n\nExample: Archivo de configuración\n```text\n$httpfiles : avif, glb\n```\n\n### $httpcompress\n\nType: `config`\n\nCompresión gzip de las respuestas.\n\nReturns: `Boolean`\n\nCuando está activada, los archivos estáticos de texto y las respuestas de texto se comprimen para los clientes que aceptan gzip.\n\nPor defecto: `true`.\n\nExample: Archivo de configuración\n```text\n$httpcompress : false\n```\n\n### $httpmaxage\n\nType: `config`\n\nEl max-age de los archivos estáticos, en segundos.\n\nReturns: `Number`\n\nSe usa en `Cache-Control: public, must-revalidate, max-age=<value>`. Pasado este tiempo el navegador vuelve a preguntar y normalmente recibe 304.\n\nPor defecto: `60`.\n\nExample: Archivo de configuración\n```text\n$httpmaxage : 300\n```\n\n### CONF.$httpexpire\n\nType: `config`\n\nLa cabecera Expires de los archivos estáticos.\n\nReturns: `String`\n\nUna fecha UTC un año en el futuro. Total.js la establece al inicio y la actualiza cada hora; no la establezcas en el archivo de configuración.\n\n### $httpetag\n\nType: `config`\n\nSufijo de la cabecera ETag.\n\nReturns: `String`\n\nEl ETag de los archivos estáticos es `858` + este valor. Cuando está vacío, se usa la `version` de la app sin puntos ni espacios, así que una versión nueva cambia el ETag.\n\nPor defecto: `'' (from version)`.\n\nExample: Archivo de configuración\n```text\n$httpetag : build42\n```\n\n### $httprangebuffer\n\nType: `config`\n\nTamaño máximo de un rango abierto, en kB.\n\nReturns: `Number`\n\nPara una cabecera `Range` sin final, se envían esta cantidad de kB.\n\nPor defecto: `5120`.\n\nExample: Archivo de configuración\n```text\n$httprangebuffer : 10240\n```\n\n### $minifyjs\n\nType: `config`\n\nMinifica los archivos JavaScript.\n\nReturns: `Boolean`\n\nMinifica los archivos `.js` estáticos, los archivos enviados con `$.file()` y los archivos combinados. Los archivos con `.min`, `-min` o `@min` no se minifican.\n\nPor defecto: `true`.\n\nExample: Archivo de configuración\n```text\n$minifyjs : false\n```\n\n### $minifycss\n\nType: `config`\n\nMinifica los archivos CSS.\n\nReturns: `Boolean`\n\nMinifica los archivos `.css` estáticos, los archivos enviados con `$.file()` y los archivos combinados.\n\nPor defecto: `true`.\n\nExample: Archivo de configuración\n```text\n$minifycss : false\n```\n\n### $minifyhtml\n\nType: `config`\n\nMinifica el HTML.\n\nReturns: `Boolean`\n\nMinifica los archivos `.html` estáticos y las respuestas HTML.\n\nPor defecto: `true`.\n\nExample: Archivo de configuración\n```text\n$minifyhtml : false\n```\n\n### $root\n\nType: `config`\n\nRuta raíz de la app.\n\nReturns: `String`\n\nCuando la app se ejecuta bajo una ruta, por ejemplo `/app/`, la raíz se elimina de las URL estáticas antes de buscar el archivo, y `MERGE()` devuelve URL con la raíz. Detalles en [Configuración](../../guides/configuration/).\n\nPor defecto: `''`.\n\nExample: Archivo de configuración\n```text\n$root : /app/\n```\n\n### $httpcacheoffset\n\nType: `config` · Since: `0.0.16`\n\nDesplaza la fecha Last-Modified de los archivos estáticos.\n\nReturns: `String`\n\nUn tiempo como `1 minute` que se suma a la fecha del archivo en la cabecera `Last-Modified` de los archivos estáticos. Consulta [Configuración](../../guides/configuration/).\n\nPor defecto: `''`.\n\nExample: Archivo de configuración\n```text\n$httpcacheoffset : 1 minute\n```\n","entries":[{"type":"type","name":"public folder","signature":"public/","since":"","deprecated":false},{"type":"type","name":"plugin public files","signature":"/_<plugin>/<path>","since":"","deprecated":false},{"type":"type","name":"minified file names","signature":"*.min.js, *-min.css, *@min.js","since":"","deprecated":false},{"type":"type","name":"static cache headers","signature":"Expires, Cache-Control, Last-Modified, ETag","since":"","deprecated":false},{"type":"type","name":"static compression","signature":"Content-Encoding: gzip","since":"","deprecated":false},{"type":"type","name":"Range requests","signature":"Range: bytes=<start>-<end>","since":"","deprecated":false},{"type":"type","name":".webmanifest","signature":"application/manifest+json","since":"","deprecated":false},{"type":"method","name":"controller.resume()","signature":"$.resume()","since":"","deprecated":false},{"type":"method","name":"controller.notmodified(date)","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"controller.httpcache(date)","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"TOUCH([url])","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"MERGE(url, files...)","signature":"MERGE(url, file1, [file2], [...])","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(fn)","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"PATH.public([path])","signature":"PATH.public([path])","since":"","deprecated":false},{"type":"config","name":"$dirpublic","signature":"$dirpublic","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage","since":"","deprecated":false},{"type":"config","name":"$httpexpire","signature":"CONF.$httpexpire","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer","since":"","deprecated":false},{"type":"config","name":"$minifyjs","signature":"$minifyjs","since":"","deprecated":false},{"type":"config","name":"$minifycss","signature":"$minifycss","since":"","deprecated":false},{"type":"config","name":"$minifyhtml","signature":"$minifyhtml","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafj4b4pu60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/static-files/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Fichiers statiques","summary":"Le dossier public, les en-têtes de cache, la compression, les plages, MERGE(), TOUCH() et leur configuration.","markdown":"---\ntitle: Fichiers statiques\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/static-files/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Fichiers statiques\n\n> Le dossier public, les en-têtes de cache, la compression, les plages, MERGE(), TOUCH() et leur configuration.\n\n## API\n\n### public/\n\nType: `type`\n\nLe dossier des fichiers statiques.\n\nUne requête dont l'URL a une extension est servie depuis `public/` : `/img/logo.png` correspond à `public/img/logo.png`. Le dossier peut être changé avec `CONF.$dirpublic`. Seules les extensions listées dans `CONF.$httpfiles` sont servies. Les requêtes de fichiers avec `POST`, `PUT`, `PATCH` ou `DELETE` sont fermées ; `HEAD` ne renvoie que les en-têtes.\n\nExample: Structure\n```text\npublic/\n\tcss/default.css\n\tjs/app.js\n\timg/logo.png\n\tfavicon.ico\n\tmanifest.webmanifest\n```\n\n### /_<plugin>/<path>\n\nType: `type`\n\nURL qui lisent des fichiers statiques depuis un plugin.\n\nUne URL de fichier qui commence par `/_` suivi d'un nom de plugin lit depuis le dossier `public/` de ce plugin : `/_shop/css/shop.css` correspond à `plugins/shop/public/css/shop.css`. Les fichiers bénéficient de la même minification et du même cache que les fichiers de l'application.\n\nExample: Lier un fichier de plugin\n```html\n<link rel=\"stylesheet\" href=\"/_shop/css/shop.css\" />\n```\n\n### *.min.js, *-min.css, *@min.js\n\nType: `type`\n\nFichiers envoyés sans minification.\n\nUn fichier `.js`, `.css` ou `.html` dont le chemin contient `.min`, `-min` ou `@min` est envoyé en flux tel quel. Les autres fichiers de ces types sont minifiés quand l'option `$minify*` correspondante est activée.\n\nExample: Envoyé sans modification\n```text\n/js/jquery.min.js\n/css/bootstrap-min.css\n/js/spa@min.js\n```\n\n### Expires, Cache-Control, Last-Modified, ETag\n\nType: `type`\n\nEn-têtes de cache HTTP des fichiers statiques.\n\nLes fichiers statiques reçoivent `Expires` (`CONF.$httpexpire`, un an plus tard), `Cache-Control: public, must-revalidate, max-age=<CONF.$httpmaxage>`, `Last-Modified` avec la date du fichier et `ETag: 858<CONF.$httpetag>`. Quand le navigateur envoie la même date `If-Modified-Since`, la réponse est `304 Not Modified`.\n\nLes fichiers `.zip` et `.rar`, ainsi que les fichiers `.js`, `.css` et `.html` en mode debug, sont envoyés avec `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: En-têtes de réponse\n```text\nCache-Control: public, must-revalidate, max-age=60\nLast-Modified: Mon, 02 Nov 2026 10:00:00 GMT\nETag: 858100\n```\n\n### Content-Encoding: gzip\n\nType: `type`\n\nCompression gzip des fichiers statiques.\n\nAvec `CONF.$httpcompress` activé et `Accept-Encoding: gzip` dans la requête, les fichiers texte sont compressés : `text/plain`, JavaScript, `text/css`, `text/jsx`, `text/html`, JSON, XML, `image/svg+xml`, Markdown et les fichiers notebook. Les types texte sont envoyés avec `charset=utf-8`. Les autres types ne sont pas compressés.\n\n### Range: bytes=<start>-<end>\n\nType: `type`\n\nRéponses partielles pour les gros fichiers.\n\nUne requête avec un en-tête `Range` reçoit `206 Partial Content` avec `Content-Range`. Quand la plage n'a pas de fin, au plus `CONF.$httprangebuffer` ko sont envoyés. Les lecteurs l'utilisent pour lire la vidéo et l'audio en streaming. Une plage qui commence après la fin du fichier ferme la connexion ; une fin située après la fin du fichier est ramenée au dernier octet.\n\nExample: Requête\n```text\nGET /video/intro.mp4\nRange: bytes=0-\n```\n\n### application/manifest+json\n\nType: `type`\n\nFichiers de manifeste d'application web.\n\n`webmanifest` fait partie de la valeur par défaut de `CONF.$httpfiles`, donc `public/manifest.webmanifest` est servi avec le type de contenu `application/manifest+json`.\n\nExample: Lier le manifeste\n```html\n<link rel=\"manifest\" href=\"/manifest.webmanifest\" />\n```\n\n### $.resume()\n\nType: `method`\n\nEnvoie normalement le fichier statique de la requête.\n\nDans une route `FILE`, `$.resume()` rend la requête à la gestion des fichiers statiques : le fichier correspondant de `public/` (ou d'un plugin) est envoyé avec minification, cache et compression.\n\nExample: Vérifier avant l'envoi\n```js\nROUTE('FILE /docs/*.pdf', function($) {\n\tif ($.query.key === CONF.docskey)\n\t\t$.resume();\n\telse\n\t\t$.fallback(401);\n});\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nRépond 304 quand le navigateur possède déjà cette version.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Une chaîne de date UTC, la même valeur que celle envoyée dans `Last-Modified`. |\n\nReturns: `Boolean` `true` quand la réponse 304 a été envoyée.\n\nCompare `date` avec l'en-tête `If-Modified-Since`. Quand elles sont égales, elle envoie `304 Not Modified` avec les en-têtes de cache et renvoie `true` ; sinon elle renvoie `undefined` et c'est toi qui envoies la réponse.\n\nExample: Mettre en cache un fichier généré\n```js\nROUTE('GET /feed/', function($) {\n\tvar date = MAIN.feeddate.toUTCString();\n\tif ($.notmodified(date))\n\t\treturn;\n\t$.httpcache(date);\n\t$.plain(MAIN.feed);\n});\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nAjoute les en-têtes de cache statique à la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | La date du contenu. |\n\nDéfinit `Expires` et `Cache-Control` (s'ils ne sont pas déjà définis), `Last-Modified` à `date` et `ETag`, les mêmes en-têtes que ceux des fichiers statiques. Utilise-la avec `$.notmodified()` pour du contenu généré.\n\nExample: Contenu généré\n```js\n$.httpcache(new Date(2026, 0, 1));\n$.plain('Hello');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nVide l'état en cache des fichiers statiques.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | URL du fichier, par exemple `/css/default.css`. |\n\nSupprime le fichier minifié enregistré, la date et la taille enregistrées et la marque « introuvable » d'une URL, ou de tous les fichiers statiques quand `url` est absent. La requête suivante relit le fichier. Utilise l'URL telle que le navigateur la demande, avec la casse du nom de fichier et avec `CONF.$root` quand il est défini. Le HTML statique traduit par `LOCALIZE()` est mis en cache par langue ; pour lui, appelle donc `TOUCH()` sans argument.\n\nExample: Après l'écriture d'un fichier\n```js\nTotal.Fs.writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### MERGE(url, file1, [file2], [...])\n\nType: `method`\n\nCrée un fichier virtuel composé de plusieurs fichiers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL du fichier fusionné, par exemple `/css/all.css`. |\n| `files` | `String|Array` | yes |  | Fichiers à fusionner, sous forme d'arguments supplémentaires. |\n\nReturns: `String` L'URL du fichier fusionné.\n\nEnregistre `url` comme un fichier construit à partir des fichiers listés et renvoie l'URL. Chaque argument de fichier est une chaîne (plusieurs noms joints par `+`) ou un tableau de chemins de fichiers absolus ou d'URL, utilisés tels quels. Dans une chaîne, un nom sans barre oblique est pris dans `public/js/` pour `.js` et dans `public/css/` sinon ; un chemin avec `/` est relatif à `public/` ; `~` commence un chemin absolu ; `http://` et `https://` sont téléchargés. Chaque fichier local est minifié selon le réglage de son type, sauf si son nom le marque comme minifié ; les fichiers téléchargés sont ajoutés tels quels. En mode release, le résultat est construit une fois et enregistré dans `tmp/` ; en mode debug, il est construit à chaque requête. Avec `CONF.$root`, l'URL renvoyée contient la racine.\n\nExample: Bundles CSS et JS\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/app.js + /js/forms.js');\n};\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nDéfinit le délégué qui choisit la langue d'une requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)` qui renvoie la langue. |\n\n`fn($)` renvoie un code de langue. Il est appelé pour les routes, les sockets et les fichiers `.html` statiques ; le HTML statique est traduit dans cette langue et mis en cache par langue. Le sujet complet se trouve dans [Localisation](../../guides/localization/).\n\nExample: Langue issue de l'en-tête\n```js\nLOCALIZE(function($) {\n\treturn ($.headers['accept-language'] || 'en').substring(0, 2);\n});\n```\n\n### PATH.public([path])\n\nType: `method`\n\nRenvoie le chemin d'un fichier du dossier public.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Chemin relatif. |\n\nReturns: `String` Chemin absolu.\n\nJoint `path` au dossier `public/` (ou `CONF.$dirpublic`). Sans `path`, elle renvoie le dossier.\n\nExample: Écrire un fichier public\n```js\nTotal.Fs.writeFile(PATH.public('robots.txt'), 'User-agent: *', NOOP);\n```\n\n### $dirpublic\n\nType: `config`\n\nDossier des fichiers statiques.\n\nReturns: `String`\n\nUn chemin absolu à utiliser à la place de `public/` dans le dossier de l'application.\n\nPar défaut : `'' (public/)`.\n\nExample: Fichier de configuration\n```text\n$dirpublic : /www/static\n```\n\n### $httpfiles\n\nType: `config`\n\nExtensions servies comme fichiers statiques.\n\nReturns: `Object`\n\nDans le fichier de configuration, liste les extensions séparées par des virgules ; elles sont ajoutées à la liste par défaut, qui contient entre autres `jpg`, `png`, `gif`, `webp`, `svg`, `ico`, `js`, `mjs`, `css`, `html`, `json`, `txt`, `xml`, `md`, `map`, `woff`, `woff2`, `ttf`, `pdf`, `zip`, `mp3`, `mp4`, `webm`, `wasm` et `webmanifest`.\n\nPar défaut : `a list of common web types`.\n\nExample: Fichier de configuration\n```text\n$httpfiles : avif, glb\n```\n\n### $httpcompress\n\nType: `config`\n\nCompression gzip des réponses.\n\nReturns: `Boolean`\n\nQuand elle est activée, les fichiers statiques texte et les réponses texte sont compressés pour les clients qui acceptent gzip.\n\nPar défaut : `true`.\n\nExample: Fichier de configuration\n```text\n$httpcompress : false\n```\n\n### $httpmaxage\n\nType: `config`\n\nLe max-age des fichiers statiques, en secondes.\n\nReturns: `Number`\n\nUtilisé dans `Cache-Control: public, must-revalidate, max-age=<value>`. Après ce délai, le navigateur redemande et reçoit généralement 304.\n\nPar défaut : `60`.\n\nExample: Fichier de configuration\n```text\n$httpmaxage : 300\n```\n\n### CONF.$httpexpire\n\nType: `config`\n\nL'en-tête Expires des fichiers statiques.\n\nReturns: `String`\n\nUne date UTC un an plus tard. Total.js la définit au démarrage et l'actualise toutes les heures ; ne la définis pas dans le fichier de configuration.\n\n### $httpetag\n\nType: `config`\n\nSuffixe de l'en-tête ETag.\n\nReturns: `String`\n\nL'ETag des fichiers statiques est `858` + cette valeur. Quand elle est vide, la `version` de l'application sans points ni espaces est utilisée, donc une nouvelle version change l'ETag.\n\nPar défaut : `'' (from version)`.\n\nExample: Fichier de configuration\n```text\n$httpetag : build42\n```\n\n### $httprangebuffer\n\nType: `config`\n\nTaille maximale d'une plage ouverte, en kB.\n\nReturns: `Number`\n\nPour un en-tête `Range` sans fin, ce nombre de kB est envoyé.\n\nPar défaut : `5120`.\n\nExample: Fichier de configuration\n```text\n$httprangebuffer : 10240\n```\n\n### $minifyjs\n\nType: `config`\n\nMinifie les fichiers JavaScript.\n\nReturns: `Boolean`\n\nMinifie les fichiers `.js` statiques, les fichiers envoyés avec `$.file()` et les fichiers fusionnés. Les fichiers avec `.min`, `-min` ou `@min` ne sont pas minifiés.\n\nPar défaut : `true`.\n\nExample: Fichier de configuration\n```text\n$minifyjs : false\n```\n\n### $minifycss\n\nType: `config`\n\nMinifie les fichiers CSS.\n\nReturns: `Boolean`\n\nMinifie les fichiers `.css` statiques, les fichiers envoyés avec `$.file()` et les fichiers fusionnés.\n\nPar défaut : `true`.\n\nExample: Fichier de configuration\n```text\n$minifycss : false\n```\n\n### $minifyhtml\n\nType: `config`\n\nMinifie le HTML.\n\nReturns: `Boolean`\n\nMinifie les fichiers `.html` statiques et les réponses HTML.\n\nPar défaut : `true`.\n\nExample: Fichier de configuration\n```text\n$minifyhtml : false\n```\n\n### $root\n\nType: `config`\n\nChemin racine de l'application.\n\nReturns: `String`\n\nQuand l'application tourne sous un chemin, par exemple `/app/`, la racine est retirée des URL statiques avant la recherche du fichier, et `MERGE()` renvoie des URL avec la racine. Détails dans [Configuration](../../guides/configuration/).\n\nPar défaut : `''`.\n\nExample: Fichier de configuration\n```text\n$root : /app/\n```\n\n### $httpcacheoffset\n\nType: `config` · Since: `0.0.16`\n\nDécale la date Last-Modified des fichiers statiques.\n\nReturns: `String`\n\nUne durée comme `1 minute` ajoutée à la date du fichier dans l'en-tête `Last-Modified` des fichiers statiques. Voir [Configuration](../../guides/configuration/).\n\nValeur par défaut : `''`.\n\nExample: Fichier de configuration\n```text\n$httpcacheoffset : 1 minute\n```\n","entries":[{"type":"type","name":"public folder","signature":"public/","since":"","deprecated":false},{"type":"type","name":"plugin public files","signature":"/_<plugin>/<path>","since":"","deprecated":false},{"type":"type","name":"minified file names","signature":"*.min.js, *-min.css, *@min.js","since":"","deprecated":false},{"type":"type","name":"static cache headers","signature":"Expires, Cache-Control, Last-Modified, ETag","since":"","deprecated":false},{"type":"type","name":"static compression","signature":"Content-Encoding: gzip","since":"","deprecated":false},{"type":"type","name":"Range requests","signature":"Range: bytes=<start>-<end>","since":"","deprecated":false},{"type":"type","name":".webmanifest","signature":"application/manifest+json","since":"","deprecated":false},{"type":"method","name":"controller.resume()","signature":"$.resume()","since":"","deprecated":false},{"type":"method","name":"controller.notmodified(date)","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"controller.httpcache(date)","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"TOUCH([url])","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"MERGE(url, files...)","signature":"MERGE(url, file1, [file2], [...])","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(fn)","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"PATH.public([path])","signature":"PATH.public([path])","since":"","deprecated":false},{"type":"config","name":"$dirpublic","signature":"$dirpublic","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage","since":"","deprecated":false},{"type":"config","name":"$httpexpire","signature":"CONF.$httpexpire","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer","since":"","deprecated":false},{"type":"config","name":"$minifyjs","signature":"$minifyjs","since":"","deprecated":false},{"type":"config","name":"$minifycss","signature":"$minifycss","since":"","deprecated":false},{"type":"config","name":"$minifyhtml","signature":"$minifyhtml","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafj4b4pu60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/static-files/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"File statici","summary":"La cartella public, gli header di cache, la compressione, i range, MERGE(), TOUCH() e la loro configurazione.","markdown":"---\ntitle: File statici\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/static-files/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# File statici\n\n> La cartella public, gli header di cache, la compressione, i range, MERGE(), TOUCH() e la loro configurazione.\n\n## API\n\n### public/\n\nType: `type`\n\nLa cartella dei file statici.\n\nUna richiesta il cui URL ha un'estensione viene servita da `public/`: `/img/logo.png` è `public/img/logo.png`. La cartella può essere cambiata con `CONF.$dirpublic`. Vengono servite solo le estensioni elencate in `CONF.$httpfiles`. Le richieste di file con `POST`, `PUT`, `PATCH` o `DELETE` vengono chiuse; `HEAD` restituisce solo gli header.\n\nExample: Struttura\n```text\npublic/\n\tcss/default.css\n\tjs/app.js\n\timg/logo.png\n\tfavicon.ico\n\tmanifest.webmanifest\n```\n\n### /_<plugin>/<path>\n\nType: `type`\n\nURL che leggono file statici da un plugin.\n\nUn URL di file che inizia con `/_` e il nome di un plugin legge dalla cartella `public/` di quel plugin: `/_shop/css/shop.css` è `plugins/shop/public/css/shop.css`. I file ricevono la stessa minificazione e la stessa cache dei file dell'app.\n\nExample: Collegare un file di un plugin\n```html\n<link rel=\"stylesheet\" href=\"/_shop/css/shop.css\" />\n```\n\n### *.min.js, *-min.css, *@min.js\n\nType: `type`\n\nFile inviati senza minificazione.\n\nUn file `.js`, `.css` o `.html` il cui percorso contiene `.min`, `-min` o `@min` viene inviato come stream così com'è. Gli altri file di questi tipi vengono minificati quando l'opzione `$minify*` corrispondente è attiva.\n\nExample: Inviato invariato\n```text\n/js/jquery.min.js\n/css/bootstrap-min.css\n/js/spa@min.js\n```\n\n### Expires, Cache-Control, Last-Modified, ETag\n\nType: `type`\n\nHeader di cache HTTP dei file statici.\n\nI file statici ricevono `Expires` (`CONF.$httpexpire`, un anno avanti), `Cache-Control: public, must-revalidate, max-age=<CONF.$httpmaxage>`, `Last-Modified` con la data del file e `ETag: 858<CONF.$httpetag>`. Quando il browser invia la stessa data `If-Modified-Since`, la risposta è `304 Not Modified`.\n\nI file `.zip` e `.rar`, e i file `.js`, `.css` e `.html` in modalità debug, vengono inviati con `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: Header della risposta\n```text\nCache-Control: public, must-revalidate, max-age=60\nLast-Modified: Mon, 02 Nov 2026 10:00:00 GMT\nETag: 858100\n```\n\n### Content-Encoding: gzip\n\nType: `type`\n\nCompressione gzip dei file statici.\n\nCon `CONF.$httpcompress` attivo e `Accept-Encoding: gzip` nella richiesta, i file di testo vengono compressi: `text/plain`, JavaScript, `text/css`, `text/jsx`, `text/html`, JSON, XML, `image/svg+xml`, Markdown e i file notebook. I tipi testuali vengono inviati con `charset=utf-8`. Gli altri tipi non vengono compressi.\n\n### Range: bytes=<start>-<end>\n\nType: `type`\n\nRisposte parziali per file grandi.\n\nUna richiesta con un header `Range` riceve `206 Partial Content` con `Content-Range`. Quando il range non ha una fine, vengono inviati al massimo `CONF.$httprangebuffer` kB. I lettori lo usano per riprodurre in streaming video e audio. Un range che inizia dopo la fine del file chiude la connessione; una fine oltre la fine del file viene troncata all'ultimo byte.\n\nExample: Richiesta\n```text\nGET /video/intro.mp4\nRange: bytes=0-\n```\n\n### application/manifest+json\n\nType: `type`\n\nFile manifest delle web app.\n\n`webmanifest` è nel `CONF.$httpfiles` predefinito, quindi `public/manifest.webmanifest` viene servito con il content type `application/manifest+json`.\n\nExample: Collegare il manifest\n```html\n<link rel=\"manifest\" href=\"/manifest.webmanifest\" />\n```\n\n### $.resume()\n\nType: `method`\n\nInvia nel modo normale il file statico della richiesta.\n\nIn una route `FILE`, `$.resume()` restituisce la richiesta alla gestione dei file statici: il file corrispondente da `public/` (o da un plugin) viene inviato con minificazione, cache e compressione.\n\nExample: Controllo prima dell'invio\n```js\nROUTE('FILE /docs/*.pdf', function($) {\n\tif ($.query.key === CONF.docskey)\n\t\t$.resume();\n\telse\n\t\t$.fallback(401);\n});\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nRisponde 304 quando il browser ha già questa versione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Una stringa di data UTC, lo stesso valore che invii in `Last-Modified`. |\n\nReturns: `Boolean` `true` quando la risposta 304 è stata inviata.\n\nConfronta `date` con l'header `If-Modified-Since`. Quando sono uguali, invia `304 Not Modified` con gli header di cache e restituisce `true`; altrimenti restituisce `undefined` e la risposta la invii tu.\n\nExample: Mettere in cache un file generato\n```js\nROUTE('GET /feed/', function($) {\n\tvar date = MAIN.feeddate.toUTCString();\n\tif ($.notmodified(date))\n\t\treturn;\n\t$.httpcache(date);\n\t$.plain(MAIN.feed);\n});\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nAggiunge alla risposta gli header di cache statici.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | La data del contenuto. |\n\nImposta `Expires` e `Cache-Control` (se non già impostati), `Last-Modified` a `date` e `ETag`, gli stessi header che ricevono i file statici. Usalo con `$.notmodified()` per i contenuti generati.\n\nExample: Contenuto generato\n```js\n$.httpcache(new Date(2026, 0, 1));\n$.plain('Hello');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nSvuota lo stato in cache dei file statici.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | URL del file, per esempio `/css/default.css`. |\n\nRimuove il file minificato salvato, la data e la dimensione salvate e il segno di file non trovato di un URL, oppure di tutti i file statici quando `url` manca. La richiesta successiva legge di nuovo il file. Usa l'URL così come lo richiede il browser, con le maiuscole e minuscole del nome del file e con `CONF.$root` quando è impostato. L'HTML statico tradotto da `LOCALIZE()` viene messo in cache per lingua, quindi in quel caso chiama `TOUCH()` senza argomenti.\n\nExample: Dopo aver scritto un file\n```js\nTotal.Fs.writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### MERGE(url, file1, [file2], [...])\n\nType: `method`\n\nCrea un file virtuale composto da più file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL del file unito, ad esempio `/css/all.css`. |\n| `files` | `String|Array` | yes |  | File da unire, come argomenti aggiuntivi. |\n\nReturns: `String` L'URL del file unito.\n\nRegistra `url` come file costruito dai file elencati e restituisce l'URL. Ogni argomento file è una stringa (più nomi uniti con `+`) o un array di percorsi di file assoluti o di URL, usati così come sono. In una stringa, un nome senza barra viene preso da `public/js/` per `.js` e da `public/css/` negli altri casi; un percorso con `/` è relativo a `public/`; `~` inizia un percorso assoluto; `http://` e `https://` vengono scaricati. Ogni file locale viene minificato in base all'impostazione del suo tipo, a meno che il suo nome non lo indichi come minificato; i file scaricati vengono aggiunti così come sono. In modalità release il risultato viene costruito una volta e salvato in `tmp/`; in modalità debug viene costruito a ogni richiesta. Con `CONF.$root`, l'URL restituito contiene la root.\n\nExample: Bundle CSS e JS\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/app.js + /js/forms.js');\n};\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nImposta il delegate che sceglie la lingua di una richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)` che restituisce la lingua. |\n\n`fn($)` restituisce un codice di lingua. Viene chiamato per le route, i socket e i file `.html` statici; l'HTML statico viene tradotto in quella lingua e messo in cache per lingua. L'argomento completo è in [Localizzazione](../../guides/localization/).\n\nExample: Lingua dall'header\n```js\nLOCALIZE(function($) {\n\treturn ($.headers['accept-language'] || 'en').substring(0, 2);\n});\n```\n\n### PATH.public([path])\n\nType: `method`\n\nRestituisce il percorso di un file nella cartella public.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Percorso relativo. |\n\nReturns: `String` Percorso assoluto.\n\nUnisce `path` alla cartella `public/` (o `CONF.$dirpublic`). Senza `path`, restituisce la cartella.\n\nExample: Scrivere un file pubblico\n```js\nTotal.Fs.writeFile(PATH.public('robots.txt'), 'User-agent: *', NOOP);\n```\n\n### $dirpublic\n\nType: `config`\n\nCartella dei file statici.\n\nReturns: `String`\n\nUn percorso assoluto da usare al posto di `public/` nella cartella dell'app.\n\nPredefinito: `'' (public/)`.\n\nExample: File di configurazione\n```text\n$dirpublic : /www/static\n```\n\n### $httpfiles\n\nType: `config`\n\nEstensioni servite come file statici.\n\nReturns: `Object`\n\nNel file di configurazione, elenca le estensioni separate da virgole; vengono aggiunte all'elenco predefinito, che contiene tra le altre `jpg`, `png`, `gif`, `webp`, `svg`, `ico`, `js`, `mjs`, `css`, `html`, `json`, `txt`, `xml`, `md`, `map`, `woff`, `woff2`, `ttf`, `pdf`, `zip`, `mp3`, `mp4`, `webm`, `wasm` e `webmanifest`.\n\nPredefinito: `a list of common web types`.\n\nExample: File di configurazione\n```text\n$httpfiles : avif, glb\n```\n\n### $httpcompress\n\nType: `config`\n\nCompressione gzip delle risposte.\n\nReturns: `Boolean`\n\nQuando è attiva, i file statici di testo e le risposte testuali vengono compressi per i client che accettano gzip.\n\nPredefinito: `true`.\n\nExample: File di configurazione\n```text\n$httpcompress : false\n```\n\n### $httpmaxage\n\nType: `config`\n\nIl max-age dei file statici, in secondi.\n\nReturns: `Number`\n\nUsato in `Cache-Control: public, must-revalidate, max-age=<value>`. Trascorso questo tempo il browser chiede di nuovo e di solito riceve 304.\n\nPredefinito: `60`.\n\nExample: File di configurazione\n```text\n$httpmaxage : 300\n```\n\n### CONF.$httpexpire\n\nType: `config`\n\nL'header Expires dei file statici.\n\nReturns: `String`\n\nUna data UTC un anno avanti. Total.js la imposta all'avvio e la aggiorna ogni ora; non impostarla nel file di configurazione.\n\n### $httpetag\n\nType: `config`\n\nSuffisso dell'header ETag.\n\nReturns: `String`\n\nL'ETag dei file statici è `858` + questo valore. Quando è vuoto, viene usata la `version` dell'app senza punti e spazi, quindi una nuova versione cambia l'ETag.\n\nPredefinito: `'' (from version)`.\n\nExample: File di configurazione\n```text\n$httpetag : build42\n```\n\n### $httprangebuffer\n\nType: `config`\n\nDimensione massima di un range aperto, in kB.\n\nReturns: `Number`\n\nPer un header `Range` senza fine, vengono inviati questi kB.\n\nPredefinito: `5120`.\n\nExample: File di configurazione\n```text\n$httprangebuffer : 10240\n```\n\n### $minifyjs\n\nType: `config`\n\nMinifica i file JavaScript.\n\nReturns: `Boolean`\n\nMinifica i file `.js` statici, i file inviati con `$.file()` e i file uniti. I file con `.min`, `-min` o `@min` non vengono minificati.\n\nPredefinito: `true`.\n\nExample: File di configurazione\n```text\n$minifyjs : false\n```\n\n### $minifycss\n\nType: `config`\n\nMinifica i file CSS.\n\nReturns: `Boolean`\n\nMinifica i file `.css` statici, i file inviati con `$.file()` e i file uniti.\n\nPredefinito: `true`.\n\nExample: File di configurazione\n```text\n$minifycss : false\n```\n\n### $minifyhtml\n\nType: `config`\n\nMinifica l'HTML.\n\nReturns: `Boolean`\n\nMinifica i file `.html` statici e le risposte HTML.\n\nPredefinito: `true`.\n\nExample: File di configurazione\n```text\n$minifyhtml : false\n```\n\n### $root\n\nType: `config`\n\nPercorso radice dell'app.\n\nReturns: `String`\n\nQuando l'app è in esecuzione sotto un percorso, per esempio `/app/`, la radice viene rimossa dagli URL statici prima di cercare il file, e `MERGE()` restituisce URL con la radice. Dettagli in [Configurazione](../../guides/configuration/).\n\nPredefinito: `''`.\n\nExample: File di configurazione\n```text\n$root : /app/\n```\n\n### $httpcacheoffset\n\nType: `config` · Since: `0.0.16`\n\nSposta la data Last-Modified dei file statici.\n\nReturns: `String`\n\nUn intervallo come `1 minute` aggiunto alla data del file nell'header `Last-Modified` dei file statici. Vedi [Configurazione](../../guides/configuration/).\n\nPredefinito: `''`.\n\nExample: File di configurazione\n```text\n$httpcacheoffset : 1 minute\n```\n","entries":[{"type":"type","name":"public folder","signature":"public/","since":"","deprecated":false},{"type":"type","name":"plugin public files","signature":"/_<plugin>/<path>","since":"","deprecated":false},{"type":"type","name":"minified file names","signature":"*.min.js, *-min.css, *@min.js","since":"","deprecated":false},{"type":"type","name":"static cache headers","signature":"Expires, Cache-Control, Last-Modified, ETag","since":"","deprecated":false},{"type":"type","name":"static compression","signature":"Content-Encoding: gzip","since":"","deprecated":false},{"type":"type","name":"Range requests","signature":"Range: bytes=<start>-<end>","since":"","deprecated":false},{"type":"type","name":".webmanifest","signature":"application/manifest+json","since":"","deprecated":false},{"type":"method","name":"controller.resume()","signature":"$.resume()","since":"","deprecated":false},{"type":"method","name":"controller.notmodified(date)","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"controller.httpcache(date)","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"TOUCH([url])","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"MERGE(url, files...)","signature":"MERGE(url, file1, [file2], [...])","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(fn)","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"PATH.public([path])","signature":"PATH.public([path])","since":"","deprecated":false},{"type":"config","name":"$dirpublic","signature":"$dirpublic","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage","since":"","deprecated":false},{"type":"config","name":"$httpexpire","signature":"CONF.$httpexpire","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer","since":"","deprecated":false},{"type":"config","name":"$minifyjs","signature":"$minifyjs","since":"","deprecated":false},{"type":"config","name":"$minifycss","signature":"$minifycss","since":"","deprecated":false},{"type":"config","name":"$minifyhtml","signature":"$minifyhtml","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"Jafj4b4pu60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/static-files/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Statické súbory","summary":"Priečinok public, hlavičky cache, kompresia, rozsahy, MERGE(), TOUCH() a ich konfigurácia.","markdown":"---\ntitle: \"Statické súbory\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/static-files/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Statické súbory\n\n> Priečinok public, hlavičky cache, kompresia, rozsahy, MERGE(), TOUCH() a ich konfigurácia.\n\n## API\n\n### public/\n\nType: `type`\n\nPriečinok statických súborov.\n\nPožiadavka, ktorej URL má príponu, sa obsluhuje z `public/`: `/img/logo.png` je `public/img/logo.png`. Priečinok sa dá zmeniť pomocou `CONF.$dirpublic`. Obsluhujú sa len prípony uvedené v `CONF.$httpfiles`. Požiadavky na súbory s `POST`, `PUT`, `PATCH` alebo `DELETE` sa zatvoria; `HEAD` vráti len hlavičky.\n\nExample: Štruktúra\n```text\npublic/\n\tcss/default.css\n\tjs/app.js\n\timg/logo.png\n\tfavicon.ico\n\tmanifest.webmanifest\n```\n\n### /_<plugin>/<path>\n\nType: `type`\n\nURL, ktoré čítajú statické súbory z pluginu.\n\nURL súboru, ktorá začína `/_` a názvom pluginu, číta z priečinka `public/` daného pluginu: `/_shop/css/shop.css` je `plugins/shop/public/css/shop.css`. Súbory dostanú rovnakú minifikáciu a cache ako súbory aplikácie.\n\nExample: Odkaz na súbor pluginu\n```html\n<link rel=\"stylesheet\" href=\"/_shop/css/shop.css\" />\n```\n\n### *.min.js, *-min.css, *@min.js\n\nType: `type`\n\nSúbory, ktoré sa posielajú bez minifikácie.\n\nSúbor `.js`, `.css` alebo `.html`, ktorého cesta obsahuje `.min`, `-min` alebo `@min`, sa streamuje tak, ako je. Ostatné súbory týchto typov sa minifikujú, keď je zapnutá príslušná voľba `$minify*`.\n\nExample: Posiela sa nezmenené\n```text\n/js/jquery.min.js\n/css/bootstrap-min.css\n/js/spa@min.js\n```\n\n### Expires, Cache-Control, Last-Modified, ETag\n\nType: `type`\n\nHlavičky HTTP cache statických súborov.\n\nStatické súbory dostanú `Expires` (`CONF.$httpexpire`, o rok dopredu), `Cache-Control: public, must-revalidate, max-age=<CONF.$httpmaxage>`, `Last-Modified` s dátumom súboru a `ETag: 858<CONF.$httpetag>`. Keď prehliadač pošle rovnaký dátum `If-Modified-Since`, odpoveď je `304 Not Modified`.\n\nSúbory `.zip` a `.rar` a v režime debug aj súbory `.js`, `.css` a `.html` sa posielajú s `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: Hlavičky odpovede\n```text\nCache-Control: public, must-revalidate, max-age=60\nLast-Modified: Mon, 02 Nov 2026 10:00:00 GMT\nETag: 858100\n```\n\n### Content-Encoding: gzip\n\nType: `type`\n\nGzip kompresia statických súborov.\n\nSo zapnutým `CONF.$httpcompress` a `Accept-Encoding: gzip` v požiadavke sa komprimujú textové súbory: `text/plain`, JavaScript, `text/css`, `text/jsx`, `text/html`, JSON, XML, `image/svg+xml`, Markdown a súbory notebookov. Textové typy sa posielajú s `charset=utf-8`. Ostatné typy sa nekomprimujú.\n\n### Range: bytes=<start>-<end>\n\nType: `type`\n\nČiastočné odpovede pre veľké súbory.\n\nPožiadavka s hlavičkou `Range` dostane `206 Partial Content` s `Content-Range`. Keď rozsah nemá koniec, pošle sa najviac `CONF.$httprangebuffer` kB. Prehrávače to používajú na streamovanie videa a audia. Rozsah, ktorý začína za koncom súboru, zatvorí spojenie; koniec za koncom súboru sa skráti na posledný bajt.\n\nExample: Požiadavka\n```text\nGET /video/intro.mp4\nRange: bytes=0-\n```\n\n### application/manifest+json\n\nType: `type`\n\nSúbory manifestu webovej aplikácie.\n\n`webmanifest` je v predvolenom `CONF.$httpfiles`, takže `public/manifest.webmanifest` sa obsluhuje s typom obsahu `application/manifest+json`.\n\nExample: Odkaz na manifest\n```html\n<link rel=\"manifest\" href=\"/manifest.webmanifest\" />\n```\n\n### $.resume()\n\nType: `method`\n\nPošle statický súbor požiadavky bežným spôsobom.\n\nV trase `FILE` vráti `$.resume()` požiadavku späť spracovaniu statických súborov: zodpovedajúci súbor z `public/` (alebo z pluginu) sa pošle s minifikáciou, cache a kompresiou.\n\nExample: Kontrola pred odoslaním\n```js\nROUTE('FILE /docs/*.pdf', function($) {\n\tif ($.query.key === CONF.docskey)\n\t\t$.resume();\n\telse\n\t\t$.fallback(401);\n});\n```\n\n### $.notmodified(date)\n\nType: `method`\n\nOdpovie 304, keď prehliadač už má túto verziu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | UTC reťazec dátumu, rovnaká hodnota, akú posielaš v `Last-Modified`. |\n\nReturns: `Boolean` `true`, keď sa odoslala odpoveď 304.\n\nPorovná `date` s hlavičkou `If-Modified-Since`. Keď sú rovnaké, pošle `304 Not Modified` s hlavičkami cache a vráti `true`; inak vráti `undefined` a odpoveď pošleš ty.\n\nExample: Cache vygenerovaného súboru\n```js\nROUTE('GET /feed/', function($) {\n\tvar date = MAIN.feeddate.toUTCString();\n\tif ($.notmodified(date))\n\t\treturn;\n\t$.httpcache(date);\n\t$.plain(MAIN.feed);\n});\n```\n\n### $.httpcache(date)\n\nType: `method`\n\nPridá do odpovede statické hlavičky cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String` | yes |  | Dátum obsahu. |\n\nNastaví `Expires` a `Cache-Control` (ak ešte nie sú nastavené), `Last-Modified` na `date` a `ETag`, teda rovnaké hlavičky, aké dostávajú statické súbory. Používaj ju s `$.notmodified()` pre generovaný obsah.\n\nExample: Generovaný obsah\n```js\n$.httpcache(new Date(2026, 0, 1));\n$.plain('Hello');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nVymaže stav statických súborov v cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | URL súboru, napríklad `/css/default.css`. |\n\nOdstráni uložený minifikovaný súbor, uložený dátum a veľkosť a označenie „nenájdené“ jednej URL, alebo všetkých statických súborov, keď `url` chýba. Ďalšia požiadavka súbor načíta znova. Použi URL tak, ako ju žiada prehliadač, s veľkosťou písmen názvu súboru a s `CONF.$root`, keď je nastavené. Statické HTML preložené pomocou `LOCALIZE()` sa ukladá do cache pre každý jazyk zvlášť, preto preň volaj `TOUCH()` bez argumentu.\n\nExample: Po zápise súboru\n```js\nTotal.Fs.writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### MERGE(url, file1, [file2], [...])\n\nType: `method`\n\nVytvorí virtuálny súbor zložený z viacerých súborov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL zlúčeného súboru, napríklad `/css/all.css`. |\n| `files` | `String|Array` | yes |  | Súbory na zlúčenie, ako ďalšie argumenty. |\n\nReturns: `String` URL zlúčeného súboru.\n\nZaregistruje `url` ako súbor zostavený z uvedených súborov a vráti URL. Každý argument súboru je reťazec (viac názvov spojených `+`) alebo pole absolútnych ciest k súborom alebo URL, ktoré sa použijú tak, ako sú. V reťazci sa názov bez lomky berie z `public/js/` pre `.js` a inak z `public/css/`; cesta s `/` je relatívna k `public/`; `~` začína absolútnu cestu; `http://` a `https://` sa stiahnu. Každý lokálny súbor sa minifikuje podľa nastavenia svojho typu, ak ho jeho názov neoznačuje ako minifikovaný; stiahnuté súbory sa pridajú tak, ako sú. V release režime sa výsledok zostaví raz a uloží do `tmp/`; v debug režime sa zostavuje pri každej požiadavke. S `CONF.$root` obsahuje vrátená URL koreň.\n\nExample: CSS a JS bundly\n```js\nexports.install = function() {\n\tMERGE('/css/all.css', 'bootstrap.min.css + default.css');\n\tMERGE('/js/all.js', '/js/app.js + /js/forms.js');\n};\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nNastaví delegáta, ktorý vyberá jazyk požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)`, ktorá vráti jazyk. |\n\n`fn($)` vráti kód jazyka. Volá sa pre trasy, sockety a statické súbory `.html`; statické HTML sa preloží do daného jazyka a uloží do cache pre každý jazyk zvlášť. Celá téma je v [Lokalizácia](../../guides/localization/).\n\nExample: Jazyk z hlavičky\n```js\nLOCALIZE(function($) {\n\treturn ($.headers['accept-language'] || 'en').substring(0, 2);\n});\n```\n\n### PATH.public([path])\n\nType: `method`\n\nVráti cestu k súboru v priečinku public.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Relatívna cesta. |\n\nReturns: `String` Absolútna cesta.\n\nSpojí `path` s priečinkom `public/` (alebo `CONF.$dirpublic`). Bez `path` vráti priečinok.\n\nExample: Zápis verejného súboru\n```js\nTotal.Fs.writeFile(PATH.public('robots.txt'), 'User-agent: *', NOOP);\n```\n\n### $dirpublic\n\nType: `config`\n\nPriečinok statických súborov.\n\nReturns: `String`\n\nAbsolútna cesta, ktorá sa použije namiesto `public/` v priečinku aplikácie.\n\nPredvolene: `'' (public/)`.\n\nExample: Konfiguračný súbor\n```text\n$dirpublic : /www/static\n```\n\n### $httpfiles\n\nType: `config`\n\nPrípony obsluhované ako statické súbory.\n\nReturns: `Object`\n\nV konfiguračnom súbore uveď prípony oddelené čiarkami; pridajú sa k predvolenému zoznamu, ktorý obsahuje okrem iného `jpg`, `png`, `gif`, `webp`, `svg`, `ico`, `js`, `mjs`, `css`, `html`, `json`, `txt`, `xml`, `md`, `map`, `woff`, `woff2`, `ttf`, `pdf`, `zip`, `mp3`, `mp4`, `webm`, `wasm` a `webmanifest`.\n\nPredvolene: `a list of common web types`.\n\nExample: Konfiguračný súbor\n```text\n$httpfiles : avif, glb\n```\n\n### $httpcompress\n\nType: `config`\n\nGzip kompresia odpovedí.\n\nReturns: `Boolean`\n\nKeď je zapnutá, textové statické súbory a textové odpovede sa komprimujú pre klientov, ktorí prijímajú gzip.\n\nPredvolene: `true`.\n\nExample: Konfiguračný súbor\n```text\n$httpcompress : false\n```\n\n### $httpmaxage\n\nType: `config`\n\nmax-age statických súborov v sekundách.\n\nReturns: `Number`\n\nPoužíva sa v `Cache-Control: public, must-revalidate, max-age=<value>`. Po uplynutí tohto času sa prehliadač opýta znova a zvyčajne dostane 304.\n\nPredvolene: `60`.\n\nExample: Konfiguračný súbor\n```text\n$httpmaxage : 300\n```\n\n### CONF.$httpexpire\n\nType: `config`\n\nHlavička Expires statických súborov.\n\nReturns: `String`\n\nUTC dátum o rok dopredu. Total.js ho nastaví pri štarte a obnovuje každú hodinu; nenastavuj ho v konfiguračnom súbore.\n\n### $httpetag\n\nType: `config`\n\nPrípona hlavičky ETag.\n\nReturns: `String`\n\nETag statických súborov je `858` + táto hodnota. Keď je prázdna, použije sa `version` aplikácie bez bodiek a medzier, takže nová verzia zmení ETag.\n\nPredvolene: `'' (from version)`.\n\nExample: Konfiguračný súbor\n```text\n$httpetag : build42\n```\n\n### $httprangebuffer\n\nType: `config`\n\nMaximálna veľkosť otvoreného rozsahu v kB.\n\nReturns: `Number`\n\nPri hlavičke `Range` bez konca sa pošle toľkoto kB.\n\nPredvolene: `5120`.\n\nExample: Konfiguračný súbor\n```text\n$httprangebuffer : 10240\n```\n\n### $minifyjs\n\nType: `config`\n\nMinifikuje súbory JavaScript.\n\nReturns: `Boolean`\n\nMinifikuje statické súbory `.js`, súbory posielané pomocou `$.file()` a zlúčené súbory. Súbory s `.min`, `-min` alebo `@min` sa neminifikujú.\n\nPredvolene: `true`.\n\nExample: Konfiguračný súbor\n```text\n$minifyjs : false\n```\n\n### $minifycss\n\nType: `config`\n\nMinifikuje súbory CSS.\n\nReturns: `Boolean`\n\nMinifikuje statické súbory `.css`, súbory posielané pomocou `$.file()` a zlúčené súbory.\n\nPredvolene: `true`.\n\nExample: Konfiguračný súbor\n```text\n$minifycss : false\n```\n\n### $minifyhtml\n\nType: `config`\n\nMinifikuje HTML.\n\nReturns: `Boolean`\n\nMinifikuje statické súbory `.html` a HTML odpovede.\n\nPredvolene: `true`.\n\nExample: Konfiguračný súbor\n```text\n$minifyhtml : false\n```\n\n### $root\n\nType: `config`\n\nKoreňová cesta aplikácie.\n\nReturns: `String`\n\nKeď aplikácia beží pod cestou, napríklad `/app/`, koreň sa pred hľadaním súboru odstráni zo statických URL a `MERGE()` vracia URL s koreňom. Podrobnosti nájdeš v [Konfigurácia](../../guides/configuration/).\n\nPredvolene: `''`.\n\nExample: Konfiguračný súbor\n```text\n$root : /app/\n```\n\n### $httpcacheoffset\n\nType: `config` · Since: `0.0.16`\n\nPosunie dátum Last-Modified statických súborov.\n\nReturns: `String`\n\nČas, napríklad `1 minute`, pripočítaný k dátumu súboru v hlavičke `Last-Modified` statických súborov. Pozri [Konfigurácia](../../guides/configuration/).\n\nPredvolene: `''`.\n\nExample: Konfiguračný súbor\n```text\n$httpcacheoffset : 1 minute\n```\n","entries":[{"type":"type","name":"public folder","signature":"public/","since":"","deprecated":false},{"type":"type","name":"plugin public files","signature":"/_<plugin>/<path>","since":"","deprecated":false},{"type":"type","name":"minified file names","signature":"*.min.js, *-min.css, *@min.js","since":"","deprecated":false},{"type":"type","name":"static cache headers","signature":"Expires, Cache-Control, Last-Modified, ETag","since":"","deprecated":false},{"type":"type","name":"static compression","signature":"Content-Encoding: gzip","since":"","deprecated":false},{"type":"type","name":"Range requests","signature":"Range: bytes=<start>-<end>","since":"","deprecated":false},{"type":"type","name":".webmanifest","signature":"application/manifest+json","since":"","deprecated":false},{"type":"method","name":"controller.resume()","signature":"$.resume()","since":"","deprecated":false},{"type":"method","name":"controller.notmodified(date)","signature":"$.notmodified(date)","since":"","deprecated":false},{"type":"method","name":"controller.httpcache(date)","signature":"$.httpcache(date)","since":"","deprecated":false},{"type":"method","name":"TOUCH([url])","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"MERGE(url, files...)","signature":"MERGE(url, file1, [file2], [...])","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(fn)","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"PATH.public([path])","signature":"PATH.public([path])","since":"","deprecated":false},{"type":"config","name":"$dirpublic","signature":"$dirpublic","since":"","deprecated":false},{"type":"config","name":"$httpfiles","signature":"$httpfiles","since":"","deprecated":false},{"type":"config","name":"$httpcompress","signature":"$httpcompress","since":"","deprecated":false},{"type":"config","name":"$httpmaxage","signature":"$httpmaxage","since":"","deprecated":false},{"type":"config","name":"$httpexpire","signature":"CONF.$httpexpire","since":"","deprecated":false},{"type":"config","name":"$httpetag","signature":"$httpetag","since":"","deprecated":false},{"type":"config","name":"$httprangebuffer","signature":"$httprangebuffer","since":"","deprecated":false},{"type":"config","name":"$minifyjs","signature":"$minifyjs","since":"","deprecated":false},{"type":"config","name":"$minifycss","signature":"$minifycss","since":"","deprecated":false},{"type":"config","name":"$minifyhtml","signature":"$minifyhtml","since":"","deprecated":false},{"type":"config","name":"$root","signature":"$root","since":"","deprecated":false},{"type":"config","name":"$httpcacheoffset","signature":"$httpcacheoffset","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JaqmEM7Gc61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/websockets/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"WebSockets","summary":"The WebSocket object, its clients, WEBSOCKETCLIENT() and the WebSocket configuration.","markdown":"---\ntitle: WebSockets\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/websockets/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# WebSockets\n\n> The WebSocket object, its clients, WEBSOCKETCLIENT() and the WebSocket configuration.\n\nMethods, properties and events of WebSocket routes (`ROUTE('SOCKET ...')`), the WebSocket object, its clients, `WEBSOCKETCLIENT()` and the `$ws*` configuration keys. For an introduction with examples read the guide [WebSockets](../../guides/websockets/).\n\n## API\n\n### ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])\n\nType: `method`\n\nRegisters a WebSocket route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Method, path, flags and middleware |\n| `action` | `Function` | yes |  | Called with the WebSocket object |\n| `size` | `Number` | no | `CONF.$wsmaxsize * 1024` | Max. size of one message in bytes |\n\nReturns: `Route` The registered route\n\nThe action runs once per URL, when the first client connects, with the WebSocket object as `this` and as the first argument. Prefix the method with `+` (authorized users only) or `-` (anonymous only). Flags: `@json` (default), `@text`, `@binary` (messages are `Buffer` objects and go out as binary frames, also when they are compressed) and `@csrf`. A client that the authorization refuses (it does not match `+` or `-`) is accepted and then closed with the code `4001`. `#name` runs a middleware before the upgrade. The size limit is `CONF.$wsmaxsize` kB unless you pass `size` in bytes or `<NMB` in the URL. Returns the route.\n\nExample: Chat room\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\t\tself.send(message);\n\t});\n}\n```\n\nExample: Authorized users, text messages, 1 MB\n```js\nROUTE('+SOCKET /console/ @text <1MB', terminal);\n```\n\nExample: Binary messages\n```js\nROUTE('SOCKET /files/ @binary', function($) {\n\t$.on('message', function(client, buffer) {\n\t\tclient.send(buffer); // a binary frame back\n\t});\n});\n```\n\n### CONF.$wsmaxsize\n\nType: `config`\n\nDefault max. size of a WebSocket message in kB.\n\nReturns: `Number`\n\nDefault `256`. A larger message closes the client with code `1009`. A route can set its own size.\n\nExample: config file\n```js\n$wsmaxsize\t\t: 512\n```\n\n### CONF.$wscompress\n\nType: `config`\n\nAllows `permessage-deflate` compression.\n\nReturns: `Boolean`\n\nDefault `true`. When the browser offers `permessage-deflate`, messages are compressed in both directions.\n\nExample: Disable compression\n```js\n$wscompress\t   : false\n```\n\n### CONF.$wsencodedecode\n\nType: `config`\n\nEncodes and decodes all WebSocket messages with URI encoding.\n\nReturns: `Boolean`\n\nDefault `false`. With `true`, outgoing messages and close reasons go through `encodeURIComponent()` and incoming ones through `decodeURIComponent()`. The other side must do the same.\n\nExample: config file\n```js\n$wsencodedecode   : true\n```\n\n### CONF.$wsmaxlatency\n\nType: `config`\n\nMax. latency in ms before the ping check closes a client.\n\nReturns: `Number`\n\nDefault `2000`. Three times a minute (15, 30 and 60 seconds into each minute) the framework pings all clients of all WebSocket routes and measures `client.latency` from the pong. Before each ping it checks the clients: a client that has not answered the previous ping, or whose latency is higher than `CONF.$wsmaxlatency` (2000 ms), is closed. This removes dead connections without your code.\n\nExample: config file\n```js\n$wsmaxlatency\t : 5000\n```\n\n### function() { var websocket = this; }\n\nType: `class`\n\nThe object that groups all clients of one WebSocket URL.\n\nReturns: `WebSocket`\n\nIt is `this` in the action of a `SOCKET` route. One object exists per URL: a dynamic route has one per distinct URL. It is an event emitter (`on`, `once`, `emit`, `off`).\n\nExample: Events\n```js\nfunction live() {\n\tvar self = this;\n\tself.on('open', function(client) {});\n\tself.on('message', function(client, message) {});\n\tself.on('close', function(client) {});\n}\n```\n\n### websocket.online\n\nType: `property`\n\nThe number of connected clients.\n\nReturns: `Number`\n\nExample: Count\n```js\nself.on('open', function() {\n\tself.send({ type: 'online', count: self.online });\n});\n```\n\n### websocket.connections\n\nType: `property`\n\nThe connected clients as an object `{ id: client }`.\n\nReturns: `Object`\n\nExample: Iterate\n```js\nfor (var id in self.connections) {\n\tvar client = self.connections[id];\n}\n```\n\n### websocket.params\n\nType: `property`\n\nThe dynamic parameters of the URL.\n\nReturns: `Object`\n\nFilled from the first client of the URL; all clients of the object share the same values.\n\nExample: Room name\n```js\nROUTE('SOCKET /room/{name}/', function() {\n\tvar name = this.params.name;\n});\n```\n\n### websocket.url\n\nType: `property`\n\nThe URL of the group in lower case.\n\nReturns: `String`\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nSends a message to all clients, or to the clients chosen by a comparer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  | The message |\n| `comparer` | `Function` | no |  | `function(client, message, params)` returning a boolean |\n| `replacer` | `Function` | no |  | A JSON replacer |\n| `params` | `Object` | no |  | Passed to the comparer |\n\nReturns: `WebSocket` The same object\n\nThe message is serialized with `JSON.stringify()` once (for `@json` and `@text` routes); on `@binary` routes pass a `Buffer`. `comparer(client, message, params)` returns `true` for the clients that receive it. `replacer` is passed to `JSON.stringify()`; when the third argument is not a function, it is used as `params`.\n\nExample: Everyone\n```js\nself.send({ type: 'refresh' });\n```\n\nExample: Only admins\n```js\nself.send({ type: 'alert' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nFinds the first client for which `fn(client)` returns `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` returning a boolean |\n\nReturns: `Controller` The client, or `undefined`\n\nExample: By user\n```js\nvar client = self.find(function(client) {\n\treturn client.user && client.user.id === id;\n});\n```\n\n### websocket.close([code], [message])\n\nType: `method`\n\nCloses all clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | The close code |\n| `message` | `String` | no |  | The close reason |\n\nReturns: `WebSocket`\n\nThe WebSocket object stays, so new clients can connect.\n\nExample: Close everyone\n```js\nself.close(4000, 'Maintenance');\n```\n\n### websocket.destroy()\n\nType: `method`\n\nCloses all clients and removes the WebSocket object.\n\nEmits `destroy`. The next client that connects to the URL runs the route action again and gets a new object.\n\nExample: Destroy\n```js\nself.destroy();\n```\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nDestroys the object 5 seconds after the last client leaves.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called before the object is destroyed |\n\nReturns: `WebSocket`\n\nIf a client connects in those 5 seconds, the object stays. Before destroying, every `callback` is called with the WebSocket object as `this`. Call it more times to add more callbacks.\n\nExample: Stop a timer\n```js\nvar timer = setInterval(function() {\n\tself.send({ ts: Date.now() });\n}, 1000);\n\nself.autodestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nEncrypts and decrypts all messages of the group with `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` |  |\n\nWith no argument or `true` it enables encryption; `false` disables it. It does nothing while `CONF.secret_encryption` is empty.\n\nExample: Enable\n```js\nfunction secure() {\n\tthis.encrypt();\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nPings all clients.\n\nReturns: `WebSocket`\n\nEach pong sets `client.latency`. The framework calls it three times a minute (15, 30 and 60 seconds into each minute) for all WebSocket objects.\n\nExample: Ping now\n```js\nself.ping();\n```\n\n### websocket.error(err)\n\nType: `method`\n\nLogs an error with the URL of the WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  |  |\n\nA string is converted to an `Error`. The error goes to the framework error log.\n\nExample: Log\n```js\nself.on('message', function(client, message) {\n\tif (!message.type)\n\t\tself.error('Missing type');\n});\n```\n\n### websocket.on('open', function(client) {})\n\nType: `event`\n\nA client has connected.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  | The new client |\n\nExample: Welcome\n```js\nself.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message, size) {})\n\nType: `event`\n\nA client has sent a message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  |  |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nOn `@json` routes `message` is a parsed object; on `@text` routes a string; on `@binary` routes a `Buffer`. `size` is the size in bytes.\n\nExample: Echo\n```js\nself.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 has disconnected.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  |  |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n`code` and `message` are the close code and reason sent by the client, or the ones passed to `close()` when the server closes the connection.\n\nExample: Left\n```js\nself.on('close', function(client) {\n\tself.send({ type: 'left', id: client.id });\n});\n```\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nAn error on a client socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nConnection resets and broken pipes do not emit it; they close the client. An error while a message is compressed or decompressed (`permessage-deflate`) is emitted here with the client.\n\nExample: Log\n```js\nself.on('error', function(err, client) {\n\tself.error(err);\n});\n```\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nThe WebSocket object is being destroyed.\n\nEmitted by `destroy()` and `autodestroy()`.\n\nExample: Cleanup\n```js\nself.on('destroy', function() {\n\tclearInterval(timer);\n});\n```\n\n### ON('websocket_end', function(websocket, client) {})\n\nType: `event`\n\nAny client of any WebSocket route has disconnected.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `websocket` | `WebSocket` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nExample: Global log\n```js\nON('websocket_end', function(websocket, client) {\n\tconsole.log(websocket.url, client.ip);\n});\n```\n\n### client\n\nType: `class`\n\nOne connected client of a WebSocket route.\n\nClients arrive in the events of the WebSocket object. They have the data of the upgrade request: `id`, `ip`, `user`, `query`, `params`, `headers`, `url`, `uri`, `ua`, `mobile`, `robot`, `referrer`, `host`, `address`, `protocol`, `language`, and `req` and `socket`. You can add your own properties. `F.extend('controller', name, fn)` adds a method to HTTP and WebSocket controllers.\n\nExample: Own data\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n### client.id\n\nType: `property`\n\nA unique identifier of the client.\n\nReturns: `String`\n\nAlso `client.ID`. It is the key in `websocket.connections`.\n\nExample: Send id\n```js\nclient.send({ id: client.id });\n```\n\n### client.user\n\nType: `property`\n\nThe user returned by the authorization delegate.\n\nReturns: `Object`\n\n`undefined` for anonymous clients.\n\nExample: Greet\n```js\nself.on('open', function(client) {\n\tclient.send({ name: client.user ? client.user.name : 'guest' });\n});\n```\n\n### client.ip\n\nType: `property`\n\nThe IP address of the client.\n\nReturns: `String`\n\nThe first address of `X-Forwarded-For` behind a proxy.\n\n### client.query\n\nType: `property`\n\nThe query string of the WebSocket URL as an object.\n\nReturns: `Object`\n\nUse it to pass data that browsers cannot send in headers, such as a token.\n\nExample: Token\n```js\n// new WebSocket('ws://localhost:8000/live/?token=abc')\nvar token = client.query.token;\n```\n\n### client.params\n\nType: `property`\n\nThe dynamic parameters of the URL.\n\nReturns: `Object`\n\n### client.headers\n\nType: `property`\n\nThe headers of the upgrade request, with lower-case names.\n\nReturns: `Object`\n\n### client.latency\n\nType: `property`\n\nThe time in ms between the last ping and its pong.\n\nReturns: `Number`\n\nEach ping resets it to `null`; the pong sets the measured time.\n\nExample: Show latency\n```js\nself.on('message', function(client) {\n\tclient.send({ latency: client.latency });\n});\n```\n\n### client.address\n\nType: `property`\n\nThe full URL the client connected to.\n\nReturns: `String`\n\nThe protocol (`http` or `https`), the host and the path with the query string.\n\n### client.ua\n\nType: `property`\n\nA short name of the browser and system, parsed from `User-Agent`.\n\nReturns: `String`\n\n`client.mobile` and `client.robot` are `true` for mobile devices and crawlers.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nSends a message to one client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Send a string without JSON serialization (`@text` routes) |\n| `replacer` | `Function` | no |  | A JSON replacer |\n\nOn `@json` routes objects are serialized with `JSON.stringify()` and other values are sent as strings. On `@text` routes the message is serialized to JSON unless `raw` is `true`, which sends the string as it is. On `@binary` routes pass a `Buffer`. `replacer` is passed to `JSON.stringify()`.\n\nExample: JSON\n```js\nclient.send({ type: 'pong' });\n```\n\nExample: Plain text\n```js\nclient.send('OK', true);\n```\n\n### client.close([code], [message])\n\nType: `method`\n\nCloses the connection with the client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | The close code |\n| `message` | `String` | no |  | The close reason |\n\nThe close frame is sent after 1 second and then the socket is destroyed.\n\nExample: Reject\n```js\nself.on('open', function(client) {\n\tif (!client.query.token)\n\t\tclient.close(4003, 'Forbidden');\n});\n```\n\n### client.ping()\n\nType: `method`\n\nSends a ping to the client.\n\nReturns: `Controller` The same client\n\nThe pong sets `client.latency`.\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 |  |  |\n\nReturns: `String` The decoded value, or an empty string\n\nExample: Session\n```js\nvar sid = client.cookie('sid');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nReturns the protocol and host of the request, with an optional path.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Appended to the host |\n\nReturns: `String` For example `https://example.com/path/`\n\n### client.destroy()\n\nType: `method`\n\nDestroys the socket immediately, without a close frame.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nCreates a WebSocket client that connects to another server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(client)` |\n\nReturns: `WebSocketClient` The client\n\n`callback(client)` is called at once with the new client. Set the options, headers and events, 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('ws://127.0.0.1:8000/live/');\n});\n```\n\n### wsclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nOpens the connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  |  |\n| `protocol` | `String` | no |  |  |\n| `origin` | `String` | no |  |  |\n\n`url` is a `ws://` or `wss://` address, or an object `{ socket: '/path/to/unix.socket', path: '/live/' }` for a Unix socket. `protocol` is sent as `Sec-WebSocket-Protocol` and `origin` as `Sec-WebSocket-Origin`. HTTP redirects (301, 302) are followed. The client emits `open` when the server accepts the connection.\n\nExample: Secure\n```js\nclient.connect('wss://example.com/live/');\n```\n\n### wsclient.options\n\nType: `property`\n\nThe options of the client.\n\nReturns: `Object`\n\nSet them before `connect()`: `type` (`json`, `text` or `binary`, default `json`), `compress` (`true`), `reconnect` (delay in ms after the connection closes, `3000`, `0` disables it), `reconnectserver` (`true` also reconnects when the connection cannot be opened or the server answers with an HTTP error), `masking` (`false`), `encodedecode` (`false`), `encrypt` (a key for encrypting messages), `size` (max. size in bytes of a decompressed message, `0` no limit), `rejectunauthorized` (`false`), `timeout` (TCP keep-alive delay in ms, `30000`, `0` disables it), and `key`, `cert`, `dhparam` for TLS.\n\nExample: Text client\n```js\nvar client = WEBSOCKETCLIENT();\nclient.options.type = 'text';\nclient.options.reconnect = 0;\nclient.connect('ws://127.0.0.1:8000/terminal/');\n```\n\n### wsclient.headers\n\nType: `property`\n\nExtra headers of the upgrade request.\n\nReturns: `Object`\n\nSet them before `connect()`.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\n```\n\n### wsclient.send(message, [raw], [replacer])\n\nType: `method`\n\nSends a message to the server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Send a prepared JSON string |\n| `replacer` | `Function` | no |  | A JSON replacer |\n\nReturns: `Boolean` `true` when the message was written\n\nWith type `json`, the message is serialized with `JSON.stringify()` unless `raw` is `true`. With type `text`, objects are serialized and other values are sent as strings. With type `binary`, a non-Buffer value is converted to a `Buffer`. Returns `false` when the connection is closed.\n\nExample: Send\n```js\nclient.send({ type: 'subscribe', channel: 'news' });\n```\n\n### wsclient.sendcustom(type, message)\n\nType: `method`\n\nSends one message as text or binary, regardless of `options.type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `binary` or `text` |\n| `message` | `String|Buffer` | yes |  |  |\n\nReturns: `Boolean` `true` when the message was written\n\n`type` is `'binary'` or any other value for text.\n\nExample: Binary\n```js\nclient.sendcustom('binary', Buffer.from([1, 2, 3]));\n```\n\n### wsclient.close([code], [message])\n\nType: `method`\n\nCloses the connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` |  |\n| `message` | `String|Boolean` | no |  | The close reason, or `true` |\n\nReturns: `WebSocketClient`\n\nIt stops reconnecting. Pass `true` as `message` to close the connection and keep the automatic reconnection.\n\nExample: Close\n```js\nclient.close();\n```\n\n### wsclient.destroy()\n\nType: `method`\n\nDestroys the connection and stops reconnecting.\n\nEmits `destroy`.\n\nExample: Destroy\n```js\nclient.destroy();\n```\n\n### wsclient.ping([timeout])\n\nType: `method`\n\nSends a ping and waits for the pong.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | no | `3000` | Time in ms |\n\nReturns: `WebSocketClient`\n\nThe pong sets `client.latency`. Without a pong in `timeout` ms the client emits `error` with a `Timeout` error, closes the connection and reconnects when `options.reconnect` is set.\n\nExample: Keep checking\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### wsclient.api(schema, [data], [callback], [timeout])\n\nType: `method`\n\nSends an API request over the connection and waits for the answer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  |  |\n| `data` | `Object` | no |  |  |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `5000` | Time in ms |\n\nReturns: `Promise` When no callback is given\n\nSends `{ TYPE: 'api', callbackid, data: { schema, data } }` and resolves when the server answers with a message `{ TYPE: 'api', callbackid, data }` (with `error: true`, `data` is the error). Without an answer in `timeout` ms (5000) the callback gets `408`. Without a callback it returns a promise.\n\nExample: Promise\n```js\nvar response = await client.api('users_list', { page: 1 });\n```\n\n### wsclient.on('message', function(message, size) {})\n\nType: `event`\n\nA message from the server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nA parsed object with type `json`, a string with `text`, a `Buffer` with `binary`.\n\n### wsclient.on('open', function() {})\n\nType: `event`\n\nThe connection is open.\n\nAlso emitted after each reconnection.\n\n### wsclient.on('close', function(code, message) {})\n\nType: `event`\n\nThe connection was closed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n### wsclient.on('error', function(err) {})\n\nType: `event`\n\nA connection error, an unexpected HTTP response, an invalid server key or a ping timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n\nExample: Log\n```js\nclient.on('error', function(err) {\n\tconsole.log('WS error', err.message);\n});\n```\n\n### route.remove()\n\nType: `method` · Since: `0.0.17`\n\nRemoves a route registered with `ROUTE()`.\n\nFor a `SOCKET` route it removes the route and destroys all its WebSocket objects, so every connected client is disconnected.\n\nExample: Remove\n```js\nvar route = ROUTE('SOCKET /live/', live);\nroute.remove();\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET ...')","signature":"ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"CONF.$wsmaxsize","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"CONF.$wscompress","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"CONF.$wsencodedecode","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"CONF.$wsmaxlatency","since":"","deprecated":false},{"type":"class","name":"WebSocket","signature":"function() { var websocket = this; }","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.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","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.close()","signature":"websocket.close([code], [message])","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.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.error()","signature":"websocket.error(err)","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, size) {})","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":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(websocket, client) {})","since":"","deprecated":false},{"type":"class","name":"Controller (WebSocket client)","signature":"client","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.ip","signature":"client.ip","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.params","signature":"client.params","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":"property","name":"client.address","signature":"client.address","since":"","deprecated":false},{"type":"property","name":"client.ua","signature":"client.ua","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([code], [message])","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","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":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"method","name":"wsclient.connect()","signature":"wsclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"property","name":"wsclient.options","signature":"wsclient.options","since":"","deprecated":false},{"type":"property","name":"wsclient.headers","signature":"wsclient.headers","since":"","deprecated":false},{"type":"method","name":"wsclient.send()","signature":"wsclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"wsclient.sendcustom()","signature":"wsclient.sendcustom(type, message)","since":"","deprecated":false},{"type":"method","name":"wsclient.close()","signature":"wsclient.close([code], [message])","since":"","deprecated":false},{"type":"method","name":"wsclient.destroy()","signature":"wsclient.destroy()","since":"","deprecated":false},{"type":"method","name":"wsclient.ping()","signature":"wsclient.ping([timeout])","since":"","deprecated":false},{"type":"method","name":"wsclient.api()","signature":"wsclient.api(schema, [data], [callback], [timeout])","since":"","deprecated":false},{"type":"event","name":"wsclient.on('message')","signature":"wsclient.on('message', function(message, size) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('open')","signature":"wsclient.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('close')","signature":"wsclient.on('close', function(code, message) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('error')","signature":"wsclient.on('error', function(err) {})","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmEM7Gc61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/websockets/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"WebSockets","summary":"Das WebSocket-Objekt, seine Clients, WEBSOCKETCLIENT() und die WebSocket-Konfiguration.","markdown":"---\ntitle: WebSockets\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/websockets/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# WebSockets\n\n> Das WebSocket-Objekt, seine Clients, WEBSOCKETCLIENT() und die WebSocket-Konfiguration.\n\nMethoden, Eigenschaften und Ereignisse von WebSocket-Routen (`ROUTE('SOCKET ...')`), dem WebSocket-Objekt, seinen Clients, `WEBSOCKETCLIENT()` und den Konfigurationsschlüsseln `$ws*`. Eine Einführung mit Beispielen findest du in der Anleitung [WebSockets](../../guides/websockets/).\n\n## API\n\n### ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])\n\nType: `method`\n\nRegistriert eine WebSocket-Route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Methode, Pfad, Flags und Middleware |\n| `action` | `Function` | yes |  | Wird mit dem WebSocket-Objekt aufgerufen |\n| `size` | `Number` | no | `CONF.$wsmaxsize * 1024` | Max. Größe einer Nachricht in Bytes |\n\nReturns: `Route` Die registrierte Route\n\nDie Aktion läuft einmal pro URL, wenn sich der erste Client verbindet, mit dem WebSocket-Objekt als `this` und als erstem Argument. Stelle der Methode `+` (nur autorisierte Benutzer) oder `-` (nur anonyme) voran. Flags: `@json` (Standard), `@text`, `@binary` (Nachrichten sind `Buffer`-Objekte und werden als binäre Frames gesendet, auch wenn sie komprimiert sind) und `@csrf`. Ein Client, den die Autorisierung ablehnt (er passt nicht zu `+` oder `-`), wird angenommen und dann mit dem Code `4001` geschlossen. `#name` führt vor dem Upgrade eine Middleware aus. Die Größengrenze ist `CONF.$wsmaxsize` kB, außer du übergibst `size` in Bytes oder `<NMB` in der URL. Gibt die Route zurück.\n\nExample: Chatraum\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\t\tself.send(message);\n\t});\n}\n```\n\nExample: Autorisierte Benutzer, Textnachrichten, 1 MB\n```js\nROUTE('+SOCKET /console/ @text <1MB', terminal);\n```\n\nExample: Binäre Nachrichten\n```js\nROUTE('SOCKET /files/ @binary', function($) {\n\t$.on('message', function(client, buffer) {\n\t\tclient.send(buffer); // a binary frame back\n\t});\n});\n```\n\n### CONF.$wsmaxsize\n\nType: `config`\n\nStandardmäßige max. Größe einer WebSocket-Nachricht in kB.\n\nReturns: `Number`\n\nStandard `256`. Eine größere Nachricht schließt den Client mit dem Code `1009`. Eine Route kann ihre eigene Größe setzen.\n\nExample: Konfigurationsdatei\n```js\n$wsmaxsize\t\t: 512\n```\n\n### CONF.$wscompress\n\nType: `config`\n\nErlaubt die Komprimierung mit `permessage-deflate`.\n\nReturns: `Boolean`\n\nStandard `true`. Wenn der Browser `permessage-deflate` anbietet, werden Nachrichten in beide Richtungen komprimiert.\n\nExample: Komprimierung deaktivieren\n```js\n$wscompress\t   : false\n```\n\n### CONF.$wsencodedecode\n\nType: `config`\n\nKodiert und dekodiert alle WebSocket-Nachrichten mit URI-Kodierung.\n\nReturns: `Boolean`\n\nStandard `false`. Mit `true` gehen ausgehende Nachrichten und Schließgründe durch `encodeURIComponent()` und eingehende durch `decodeURIComponent()`. Die andere Seite muss dasselbe tun.\n\nExample: Konfigurationsdatei\n```js\n$wsencodedecode   : true\n```\n\n### CONF.$wsmaxlatency\n\nType: `config`\n\nMax. Latenz in ms, bevor die Ping-Prüfung einen Client schließt.\n\nReturns: `Number`\n\nStandard `2000`. Dreimal pro Minute (15, 30 und 60 Sekunden nach Beginn jeder Minute) pingt das Framework alle Clients aller WebSocket-Routen an und misst `client.latency` anhand des Pongs. Vor jedem Ping prüft es die Clients: Ein Client, der den vorherigen Ping nicht beantwortet hat oder dessen Latenz höher als `CONF.$wsmaxlatency` (2000 ms) ist, wird geschlossen. Das entfernt tote Verbindungen ohne deinen Code.\n\nExample: Konfigurationsdatei\n```js\n$wsmaxlatency\t : 5000\n```\n\n### function() { var websocket = this; }\n\nType: `class`\n\nDas Objekt, das alle Clients einer WebSocket-URL gruppiert.\n\nReturns: `WebSocket`\n\nEs ist `this` in der Aktion einer `SOCKET`-Route. Pro URL existiert ein Objekt: Eine dynamische Route hat eines pro unterschiedlicher URL. Es ist ein Event-Emitter (`on`, `once`, `emit`, `off`).\n\nExample: Ereignisse\n```js\nfunction live() {\n\tvar self = this;\n\tself.on('open', function(client) {});\n\tself.on('message', function(client, message) {});\n\tself.on('close', function(client) {});\n}\n```\n\n### websocket.online\n\nType: `property`\n\nDie Anzahl der verbundenen Clients.\n\nReturns: `Number`\n\nExample: Anzahl\n```js\nself.on('open', function() {\n\tself.send({ type: 'online', count: self.online });\n});\n```\n\n### websocket.connections\n\nType: `property`\n\nDie verbundenen Clients als Objekt `{ id: client }`.\n\nReturns: `Object`\n\nExample: Iterieren\n```js\nfor (var id in self.connections) {\n\tvar client = self.connections[id];\n}\n```\n\n### websocket.params\n\nType: `property`\n\nDie dynamischen Parameter der URL.\n\nReturns: `Object`\n\nWird vom ersten Client der URL gefüllt; alle Clients des Objekts teilen dieselben Werte.\n\nExample: Name des Raums\n```js\nROUTE('SOCKET /room/{name}/', function() {\n\tvar name = this.params.name;\n});\n```\n\n### websocket.url\n\nType: `property`\n\nDie URL der Gruppe in Kleinbuchstaben.\n\nReturns: `String`\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nSendet eine Nachricht an alle Clients oder an die von einem Comparer gewählten Clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  | Die Nachricht |\n| `comparer` | `Function` | no |  | `function(client, message, params)`, die einen Boolean zurückgibt |\n| `replacer` | `Function` | no |  | Ein JSON-Replacer |\n| `params` | `Object` | no |  | Wird an den Comparer übergeben |\n\nReturns: `WebSocket` Dasselbe Objekt\n\nDie Nachricht wird einmal mit `JSON.stringify()` serialisiert (bei `@json`- und `@text`-Routen); bei `@binary`-Routen übergibst du einen `Buffer`. `comparer(client, message, params)` gibt `true` für die Clients zurück, die sie erhalten. `replacer` wird an `JSON.stringify()` übergeben; wenn das dritte Argument keine Funktion ist, wird es als `params` verwendet.\n\nExample: Alle\n```js\nself.send({ type: 'refresh' });\n```\n\nExample: Nur Admins\n```js\nself.send({ type: 'alert' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nFindet den ersten Client, für den `fn(client)` `true` zurückgibt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)`, die einen Boolean zurückgibt |\n\nReturns: `Controller` Der Client oder `undefined`\n\nExample: Nach Benutzer\n```js\nvar client = self.find(function(client) {\n\treturn client.user && client.user.id === id;\n});\n```\n\n### websocket.close([code], [message])\n\nType: `method`\n\nSchließt alle Clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | Der Schließcode |\n| `message` | `String` | no |  | Der Schließgrund |\n\nReturns: `WebSocket`\n\nDas WebSocket-Objekt bleibt bestehen, sodass sich neue Clients verbinden können.\n\nExample: Alle schließen\n```js\nself.close(4000, 'Maintenance');\n```\n\n### websocket.destroy()\n\nType: `method`\n\nSchließt alle Clients und entfernt das WebSocket-Objekt.\n\nLöst `destroy` aus. Der nächste Client, der sich mit der URL verbindet, führt die Aktion der Route erneut aus und erhält ein neues Objekt.\n\nExample: Zerstören\n```js\nself.destroy();\n```\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nZerstört das Objekt 5 Sekunden nachdem der letzte Client gegangen ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird aufgerufen, bevor das Objekt zerstört wird |\n\nReturns: `WebSocket`\n\nVerbindet sich innerhalb dieser 5 Sekunden ein Client, bleibt das Objekt bestehen. Vor dem Zerstören wird jeder `callback` mit dem WebSocket-Objekt als `this` aufgerufen. Rufe sie mehrmals auf, um weitere Callbacks hinzuzufügen.\n\nExample: Einen Timer stoppen\n```js\nvar timer = setInterval(function() {\n\tself.send({ ts: Date.now() });\n}, 1000);\n\nself.autodestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nVerschlüsselt und entschlüsselt alle Nachrichten der Gruppe mit `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` |  |\n\nOhne Argument oder mit `true` aktiviert sie die Verschlüsselung; `false` deaktiviert sie. Solange `CONF.secret_encryption` leer ist, tut sie nichts.\n\nExample: Aktivieren\n```js\nfunction secure() {\n\tthis.encrypt();\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nPingt alle Clients an.\n\nReturns: `WebSocket`\n\nJeder Pong setzt `client.latency`. Das Framework ruft sie dreimal pro Minute (15, 30 und 60 Sekunden nach Beginn jeder Minute) für alle WebSocket-Objekte auf.\n\nExample: Jetzt pingen\n```js\nself.ping();\n```\n\n### websocket.error(err)\n\nType: `method`\n\nProtokolliert einen Fehler mit der URL des WebSockets.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  |  |\n\nEin String wird in einen `Error` umgewandelt. Der Fehler landet im Fehlerprotokoll des Frameworks.\n\nExample: Protokollieren\n```js\nself.on('message', function(client, message) {\n\tif (!message.type)\n\t\tself.error('Missing type');\n});\n```\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` | `Controller` | yes |  | Der neue Client |\n\nExample: Willkommen\n```js\nself.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message, size) {})\n\nType: `event`\n\nEin Client hat eine Nachricht gesendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  |  |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nBei `@json`-Routen ist `message` ein geparstes Objekt, bei `@text`-Routen ein String, bei `@binary`-Routen ein `Buffer`. `size` ist die Größe in Bytes.\n\nExample: Echo\n```js\nself.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` | `Controller` | yes |  |  |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n`code` und `message` sind der Schließcode und der Grund, die der Client gesendet hat, oder die an `close()` übergebenen, wenn der Server die Verbindung schließt.\n\nExample: Gegangen\n```js\nself.on('close', function(client) {\n\tself.send({ type: 'left', id: client.id });\n});\n```\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nEin Fehler an einem Client-Socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nVerbindungsabbrüche (Connection Resets) und unterbrochene Pipes lösen es nicht aus; sie schließen den Client. Ein Fehler beim Komprimieren oder Dekomprimieren einer Nachricht (`permessage-deflate`) wird hier mit dem Client ausgelöst.\n\nExample: Protokollieren\n```js\nself.on('error', function(err, client) {\n\tself.error(err);\n});\n```\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nDas WebSocket-Objekt wird zerstört.\n\nWird von `destroy()` und `autodestroy()` ausgelöst.\n\nExample: Aufräumen\n```js\nself.on('destroy', function() {\n\tclearInterval(timer);\n});\n```\n\n### ON('websocket_end', function(websocket, client) {})\n\nType: `event`\n\nEin beliebiger Client einer beliebigen WebSocket-Route hat sich getrennt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `websocket` | `WebSocket` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nExample: Globales Protokoll\n```js\nON('websocket_end', function(websocket, client) {\n\tconsole.log(websocket.url, client.ip);\n});\n```\n\n### client\n\nType: `class`\n\nEin verbundener Client einer WebSocket-Route.\n\nClients kommen in den Ereignissen des WebSocket-Objekts an. Sie haben die Daten der Upgrade-Anfrage: `id`, `ip`, `user`, `query`, `params`, `headers`, `url`, `uri`, `ua`, `mobile`, `robot`, `referrer`, `host`, `address`, `protocol`, `language` sowie `req` und `socket`. Du kannst eigene Eigenschaften hinzufügen. `F.extend('controller', name, fn)` fügt HTTP- und WebSocket-Controllern eine Methode hinzu.\n\nExample: Eigene Daten\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n### client.id\n\nType: `property`\n\nEine eindeutige Kennung des Clients.\n\nReturns: `String`\n\nAuch `client.ID`. Sie ist der Schlüssel in `websocket.connections`.\n\nExample: ID senden\n```js\nclient.send({ id: client.id });\n```\n\n### client.user\n\nType: `property`\n\nDer Benutzer, den der Autorisierungs-Delegate zurückgegeben hat.\n\nReturns: `Object`\n\n`undefined` bei anonymen Clients.\n\nExample: Begrüßen\n```js\nself.on('open', function(client) {\n\tclient.send({ name: client.user ? client.user.name : 'guest' });\n});\n```\n\n### client.ip\n\nType: `property`\n\nDie IP-Adresse des Clients.\n\nReturns: `String`\n\nHinter einem Proxy die erste Adresse aus `X-Forwarded-For`.\n\n### client.query\n\nType: `property`\n\nDer Query String der WebSocket-URL als Objekt.\n\nReturns: `Object`\n\nVerwende ihn, um Daten zu übergeben, die Browser nicht in Headern senden können, zum Beispiel ein Token.\n\nExample: Token\n```js\n// new WebSocket('ws://localhost:8000/live/?token=abc')\nvar token = client.query.token;\n```\n\n### client.params\n\nType: `property`\n\nDie dynamischen Parameter der URL.\n\nReturns: `Object`\n\n### client.headers\n\nType: `property`\n\nDie Header der Upgrade-Anfrage, mit kleingeschriebenen Namen.\n\nReturns: `Object`\n\n### client.latency\n\nType: `property`\n\nDie Zeit in ms zwischen dem letzten Ping und seinem Pong.\n\nReturns: `Number`\n\nJeder Ping setzt sie auf `null` zurück; der Pong setzt die gemessene Zeit.\n\nExample: Latenz anzeigen\n```js\nself.on('message', function(client) {\n\tclient.send({ latency: client.latency });\n});\n```\n\n### client.address\n\nType: `property`\n\nDie vollständige URL, mit der sich der Client verbunden hat.\n\nReturns: `String`\n\nDas Protokoll (`http` oder `https`), der Host und der Pfad mit dem Query String.\n\n### client.ua\n\nType: `property`\n\nEin kurzer Name des Browsers und des Systems, aus `User-Agent` geparst.\n\nReturns: `String`\n\n`client.mobile` und `client.robot` sind `true` für Mobilgeräte und Crawler.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nSendet eine Nachricht an einen Client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Einen String ohne JSON-Serialisierung senden (`@text`-Routen) |\n| `replacer` | `Function` | no |  | Ein JSON-Replacer |\n\nBei `@json`-Routen werden Objekte mit `JSON.stringify()` serialisiert und andere Werte als Strings gesendet. Bei `@text`-Routen wird die Nachricht zu JSON serialisiert, es sei denn, `raw` ist `true`, was den String unverändert sendet. Bei `@binary`-Routen übergibst du einen `Buffer`. `replacer` wird an `JSON.stringify()` übergeben.\n\nExample: JSON\n```js\nclient.send({ type: 'pong' });\n```\n\nExample: Reiner Text\n```js\nclient.send('OK', true);\n```\n\n### client.close([code], [message])\n\nType: `method`\n\nSchließt die Verbindung mit dem Client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | Der Schließcode |\n| `message` | `String` | no |  | Der Schließgrund |\n\nDer Close-Frame wird nach 1 Sekunde gesendet, danach wird der Socket zerstört.\n\nExample: Ablehnen\n```js\nself.on('open', function(client) {\n\tif (!client.query.token)\n\t\tclient.close(4003, 'Forbidden');\n});\n```\n\n### client.ping()\n\nType: `method`\n\nSendet einen Ping an den Client.\n\nReturns: `Controller` Derselbe Client\n\nDer Pong setzt `client.latency`.\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 |  |  |\n\nReturns: `String` Der dekodierte Wert oder ein leerer String\n\nExample: Sitzung\n```js\nvar sid = client.cookie('sid');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nGibt das Protokoll und den Host der Anfrage zurück, mit einem optionalen Pfad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Wird an den Host angehängt |\n\nReturns: `String` Zum Beispiel `https://example.com/path/`\n\n### client.destroy()\n\nType: `method`\n\nZerstört den Socket sofort, ohne Close-Frame.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nErstellt einen WebSocket-Client, der sich mit einem anderen Server verbindet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(client)` |\n\nReturns: `WebSocketClient` Der Client\n\n`callback(client)` wird sofort mit dem neuen Client aufgerufen. Setze die Optionen, Header und Ereignisse 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('ws://127.0.0.1:8000/live/');\n});\n```\n\n### wsclient.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 |  |  |\n| `protocol` | `String` | no |  |  |\n| `origin` | `String` | no |  |  |\n\n`url` ist eine `ws://`- oder `wss://`-Adresse oder ein Objekt `{ socket: '/path/to/unix.socket', path: '/live/' }` für einen Unix-Socket. `protocol` wird als `Sec-WebSocket-Protocol` gesendet und `origin` als `Sec-WebSocket-Origin`. HTTP-Weiterleitungen (301, 302) werden verfolgt. Der Client löst `open` aus, wenn der Server die Verbindung annimmt.\n\nExample: Sicher\n```js\nclient.connect('wss://example.com/live/');\n```\n\n### wsclient.options\n\nType: `property`\n\nDie Optionen des Clients.\n\nReturns: `Object`\n\nSetze sie vor `connect()`: `type` (`json`, `text` oder `binary`, Standard `json`), `compress` (`true`), `reconnect` (Verzögerung in ms, nachdem die Verbindung geschlossen wurde, `3000`, `0` deaktiviert es), `reconnectserver` (`true` verbindet auch erneut, wenn die Verbindung nicht geöffnet werden kann oder der Server mit einem HTTP-Fehler antwortet), `masking` (`false`), `encodedecode` (`false`), `encrypt` (ein Schlüssel zum Verschlüsseln von Nachrichten), `size` (max. Größe einer dekomprimierten Nachricht in Bytes, `0` ohne Begrenzung), `rejectunauthorized` (`false`), `timeout` (TCP-Keep-Alive-Verzögerung in ms, `30000`, `0` deaktiviert es) sowie `key`, `cert`, `dhparam` für TLS.\n\nExample: Text-Client\n```js\nvar client = WEBSOCKETCLIENT();\nclient.options.type = 'text';\nclient.options.reconnect = 0;\nclient.connect('ws://127.0.0.1:8000/terminal/');\n```\n\n### wsclient.headers\n\nType: `property`\n\nZusätzliche Header des Upgrade-Requests.\n\nReturns: `Object`\n\nSetze sie vor `connect()`.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\n```\n\n### wsclient.send(message, [raw], [replacer])\n\nType: `method`\n\nSendet eine Nachricht an den Server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Einen vorbereiteten JSON-String senden |\n| `replacer` | `Function` | no |  | Ein JSON-Replacer |\n\nReturns: `Boolean` `true`, wenn die Nachricht geschrieben wurde\n\nBeim Typ `json` wird die Nachricht mit `JSON.stringify()` serialisiert, es sei denn, `raw` ist `true`. Beim Typ `text` werden Objekte serialisiert und andere Werte als Strings gesendet. Beim Typ `binary` wird ein Wert, der kein Buffer ist, in einen `Buffer` umgewandelt. Gibt `false` zurück, wenn die Verbindung geschlossen ist.\n\nExample: Senden\n```js\nclient.send({ type: 'subscribe', channel: 'news' });\n```\n\n### wsclient.sendcustom(type, message)\n\nType: `method`\n\nSendet eine Nachricht als Text oder binär, unabhängig von `options.type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `binary` oder `text` |\n| `message` | `String|Buffer` | yes |  |  |\n\nReturns: `Boolean` `true`, wenn die Nachricht geschrieben wurde\n\n`type` ist `'binary'` oder ein beliebiger anderer Wert für Text.\n\nExample: Binär\n```js\nclient.sendcustom('binary', Buffer.from([1, 2, 3]));\n```\n\n### wsclient.close([code], [message])\n\nType: `method`\n\nSchließt die Verbindung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` |  |\n| `message` | `String|Boolean` | no |  | Der Schließgrund oder `true` |\n\nReturns: `WebSocketClient`\n\nSie beendet die erneuten Verbindungsversuche. Übergib `true` als `message`, um die Verbindung zu schließen und die automatische Neuverbindung beizubehalten.\n\nExample: Schließen\n```js\nclient.close();\n```\n\n### wsclient.destroy()\n\nType: `method`\n\nZerstört die Verbindung und beendet die erneuten Verbindungsversuche.\n\nLöst `destroy` aus.\n\nExample: Zerstören\n```js\nclient.destroy();\n```\n\n### wsclient.ping([timeout])\n\nType: `method`\n\nSendet einen Ping und wartet auf den Pong.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | no | `3000` | Zeit in ms |\n\nReturns: `WebSocketClient`\n\nDer Pong setzt `client.latency`. Ohne Pong innerhalb von `timeout` ms löst der Client `error` mit einem `Timeout`-Fehler aus, schließt die Verbindung und verbindet sich neu, wenn `options.reconnect` gesetzt ist.\n\nExample: Regelmäßig prüfen\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### wsclient.api(schema, [data], [callback], [timeout])\n\nType: `method`\n\nSendet eine API-Anfrage über die Verbindung und wartet auf die Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  |  |\n| `data` | `Object` | no |  |  |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `5000` | Zeit in ms |\n\nReturns: `Promise` Wenn kein Callback übergeben wird\n\nSendet `{ TYPE: 'api', callbackid, data: { schema, data } }` und wird aufgelöst, wenn der Server mit einer Nachricht `{ TYPE: 'api', callbackid, data }` antwortet (mit `error: true` ist `data` der Fehler). Ohne Antwort innerhalb von `timeout` ms (5000) erhält der Callback `408`. Ohne Callback gibt sie ein Promise zurück.\n\nExample: Promise\n```js\nvar response = await client.api('users_list', { page: 1 });\n```\n\n### wsclient.on('message', function(message, size) {})\n\nType: `event`\n\nEine Nachricht vom Server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nEin geparstes Objekt beim Typ `json`, ein String bei `text`, ein `Buffer` bei `binary`.\n\n### wsclient.on('open', function() {})\n\nType: `event`\n\nDie Verbindung ist offen.\n\nWird auch nach jeder erneuten Verbindung ausgelöst.\n\n### wsclient.on('close', function(code, message) {})\n\nType: `event`\n\nDie Verbindung wurde geschlossen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n### wsclient.on('error', function(err) {})\n\nType: `event`\n\nEin Verbindungsfehler, eine unerwartete HTTP-Antwort, ein ungültiger Serverschlüssel oder ein Ping-Timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n\nExample: Protokollieren\n```js\nclient.on('error', function(err) {\n\tconsole.log('WS error', err.message);\n});\n```\n\n### route.remove()\n\nType: `method` · Since: `0.0.17`\n\nEntfernt eine mit `ROUTE()` registrierte Route.\n\nBei einer `SOCKET`-Route entfernt es die Route und zerstört alle ihre WebSocket-Objekte, sodass jeder verbundene Client getrennt wird.\n\nExample: Entfernen\n```js\nvar route = ROUTE('SOCKET /live/', live);\nroute.remove();\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET ...')","signature":"ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"CONF.$wsmaxsize","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"CONF.$wscompress","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"CONF.$wsencodedecode","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"CONF.$wsmaxlatency","since":"","deprecated":false},{"type":"class","name":"WebSocket","signature":"function() { var websocket = this; }","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.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","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.close()","signature":"websocket.close([code], [message])","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.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.error()","signature":"websocket.error(err)","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, size) {})","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":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(websocket, client) {})","since":"","deprecated":false},{"type":"class","name":"Controller (WebSocket client)","signature":"client","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.ip","signature":"client.ip","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.params","signature":"client.params","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":"property","name":"client.address","signature":"client.address","since":"","deprecated":false},{"type":"property","name":"client.ua","signature":"client.ua","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([code], [message])","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","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":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"method","name":"wsclient.connect()","signature":"wsclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"property","name":"wsclient.options","signature":"wsclient.options","since":"","deprecated":false},{"type":"property","name":"wsclient.headers","signature":"wsclient.headers","since":"","deprecated":false},{"type":"method","name":"wsclient.send()","signature":"wsclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"wsclient.sendcustom()","signature":"wsclient.sendcustom(type, message)","since":"","deprecated":false},{"type":"method","name":"wsclient.close()","signature":"wsclient.close([code], [message])","since":"","deprecated":false},{"type":"method","name":"wsclient.destroy()","signature":"wsclient.destroy()","since":"","deprecated":false},{"type":"method","name":"wsclient.ping()","signature":"wsclient.ping([timeout])","since":"","deprecated":false},{"type":"method","name":"wsclient.api()","signature":"wsclient.api(schema, [data], [callback], [timeout])","since":"","deprecated":false},{"type":"event","name":"wsclient.on('message')","signature":"wsclient.on('message', function(message, size) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('open')","signature":"wsclient.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('close')","signature":"wsclient.on('close', function(code, message) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('error')","signature":"wsclient.on('error', function(err) {})","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmEM7Gc61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/websockets/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"WebSockets","summary":"El objeto WebSocket, sus clientes, WEBSOCKETCLIENT() y la configuración de WebSocket.","markdown":"---\ntitle: WebSockets\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/websockets/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# WebSockets\n\n> El objeto WebSocket, sus clientes, WEBSOCKETCLIENT() y la configuración de WebSocket.\n\nMétodos, propiedades y eventos de las rutas WebSocket (`ROUTE('SOCKET ...')`), el objeto WebSocket, sus clientes, `WEBSOCKETCLIENT()` y las claves de configuración `$ws*`. Para una introducción con ejemplos, lee la guía [WebSockets](../../guides/websockets/).\n\n## API\n\n### ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])\n\nType: `method`\n\nRegistra una ruta WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Método, ruta, flags y middleware |\n| `action` | `Function` | yes |  | Se llama con el objeto WebSocket |\n| `size` | `Number` | no | `CONF.$wsmaxsize * 1024` | Tamaño máx. de un mensaje en bytes |\n\nReturns: `Route` La ruta registrada\n\nLa acción se ejecuta una vez por URL, cuando se conecta el primer cliente, con el objeto WebSocket como `this` y como primer argumento. Pon delante del método `+` (solo usuarios autorizados) o `-` (solo anónimos). Flags: `@json` (por defecto), `@text`, `@binary` (los mensajes son objetos `Buffer` y salen como frames binarios, también cuando van comprimidos) y `@csrf`. Un cliente que la autorización rechaza (no cumple `+` o `-`) se acepta y después se cierra con el código `4001`. `#name` ejecuta un middleware antes del upgrade. El límite de tamaño es `CONF.$wsmaxsize` kB, salvo que pases `size` en bytes o `<NMB` en la URL. Devuelve la ruta.\n\nExample: Sala de chat\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\t\tself.send(message);\n\t});\n}\n```\n\nExample: Usuarios autorizados, mensajes de texto, 1 MB\n```js\nROUTE('+SOCKET /console/ @text <1MB', terminal);\n```\n\nExample: Mensajes binarios\n```js\nROUTE('SOCKET /files/ @binary', function($) {\n\t$.on('message', function(client, buffer) {\n\t\tclient.send(buffer); // a binary frame back\n\t});\n});\n```\n\n### CONF.$wsmaxsize\n\nType: `config`\n\nTamaño máx. por defecto de un mensaje WebSocket en kB.\n\nReturns: `Number`\n\nPor defecto `256`. Un mensaje mayor cierra el cliente con el código `1009`. Una ruta puede establecer su propio tamaño.\n\nExample: Archivo de configuración\n```js\n$wsmaxsize\t\t: 512\n```\n\n### CONF.$wscompress\n\nType: `config`\n\nPermite la compresión `permessage-deflate`.\n\nReturns: `Boolean`\n\nPor defecto `true`. Cuando el navegador ofrece `permessage-deflate`, los mensajes se comprimen en ambas direcciones.\n\nExample: Desactivar la compresión\n```js\n$wscompress\t   : false\n```\n\n### CONF.$wsencodedecode\n\nType: `config`\n\nCodifica y decodifica todos los mensajes WebSocket con codificación URI.\n\nReturns: `Boolean`\n\nPor defecto `false`. Con `true`, los mensajes salientes y los motivos de cierre pasan por `encodeURIComponent()` y los entrantes por `decodeURIComponent()`. El otro lado debe hacer lo mismo.\n\nExample: Archivo de configuración\n```js\n$wsencodedecode   : true\n```\n\n### CONF.$wsmaxlatency\n\nType: `config`\n\nLatencia máx. en ms antes de que la comprobación de ping cierre un cliente.\n\nReturns: `Number`\n\nPor defecto `2000`. Tres veces por minuto (a los 15, 30 y 60 segundos de cada minuto) el framework hace ping a todos los clientes de todas las rutas WebSocket y mide `client.latency` a partir del pong. Antes de cada ping comprueba los clientes: se cierra un cliente que no ha respondido al ping anterior, o cuya latencia es mayor que `CONF.$wsmaxlatency` (2000 ms). Esto elimina las conexiones muertas sin código por tu parte.\n\nExample: Archivo de configuración\n```js\n$wsmaxlatency\t : 5000\n```\n\n### function() { var websocket = this; }\n\nType: `class`\n\nEl objeto que agrupa todos los clientes de una URL WebSocket.\n\nReturns: `WebSocket`\n\nEs `this` en la acción de una ruta `SOCKET`. Existe un objeto por URL: una ruta dinámica tiene uno por cada URL distinta. Es un emisor de eventos (`on`, `once`, `emit`, `off`).\n\nExample: Eventos\n```js\nfunction live() {\n\tvar self = this;\n\tself.on('open', function(client) {});\n\tself.on('message', function(client, message) {});\n\tself.on('close', function(client) {});\n}\n```\n\n### websocket.online\n\nType: `property`\n\nEl número de clientes conectados.\n\nReturns: `Number`\n\nExample: Contar\n```js\nself.on('open', function() {\n\tself.send({ type: 'online', count: self.online });\n});\n```\n\n### websocket.connections\n\nType: `property`\n\nLos clientes conectados como un objeto `{ id: client }`.\n\nReturns: `Object`\n\nExample: Recorrer\n```js\nfor (var id in self.connections) {\n\tvar client = self.connections[id];\n}\n```\n\n### websocket.params\n\nType: `property`\n\nLos parámetros dinámicos de la URL.\n\nReturns: `Object`\n\nSe rellena a partir del primer cliente de la URL; todos los clientes del objeto comparten los mismos valores.\n\nExample: Nombre de la sala\n```js\nROUTE('SOCKET /room/{name}/', function() {\n\tvar name = this.params.name;\n});\n```\n\n### websocket.url\n\nType: `property`\n\nLa URL del grupo en minúsculas.\n\nReturns: `String`\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nEnvía un mensaje a todos los clientes, o a los clientes elegidos por un comparer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  | El mensaje |\n| `comparer` | `Function` | no |  | `function(client, message, params)` que devuelve un booleano |\n| `replacer` | `Function` | no |  | Un replacer de JSON |\n| `params` | `Object` | no |  | Se pasa al comparer |\n\nReturns: `WebSocket` El mismo objeto\n\nEl mensaje se serializa una sola vez con `JSON.stringify()` (en las rutas `@json` y `@text`); en las rutas `@binary` pasa un `Buffer`. `comparer(client, message, params)` devuelve `true` para los clientes que lo reciben. `replacer` se pasa a `JSON.stringify()`; cuando el tercer argumento no es una función, se usa como `params`.\n\nExample: Todos\n```js\nself.send({ type: 'refresh' });\n```\n\nExample: Solo administradores\n```js\nself.send({ type: 'alert' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nBusca el primer cliente para el que `fn(client)` devuelve `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` que devuelve un booleano |\n\nReturns: `Controller` El cliente, o `undefined`\n\nExample: Por usuario\n```js\nvar client = self.find(function(client) {\n\treturn client.user && client.user.id === id;\n});\n```\n\n### websocket.close([code], [message])\n\nType: `method`\n\nCierra todos los clientes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | El código de cierre |\n| `message` | `String` | no |  | El motivo del cierre |\n\nReturns: `WebSocket`\n\nEl objeto WebSocket se mantiene, así que pueden conectarse clientes nuevos.\n\nExample: Cerrar todos\n```js\nself.close(4000, 'Maintenance');\n```\n\n### websocket.destroy()\n\nType: `method`\n\nCierra todos los clientes y elimina el objeto WebSocket.\n\nEmite `destroy`. El siguiente cliente que se conecte a la URL vuelve a ejecutar la acción de la ruta y obtiene un objeto nuevo.\n\nExample: Destruir\n```js\nself.destroy();\n```\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nDestruye el objeto 5 segundos después de que se vaya el último cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama antes de destruir el objeto |\n\nReturns: `WebSocket`\n\nSi un cliente se conecta durante esos 5 segundos, el objeto se mantiene. Antes de destruirlo, se llama a cada `callback` con el objeto WebSocket como `this`. Llámalo más veces para añadir más callbacks.\n\nExample: Detener un temporizador\n```js\nvar timer = setInterval(function() {\n\tself.send({ ts: Date.now() });\n}, 1000);\n\nself.autodestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nCifra y descifra todos los mensajes del grupo con `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` |  |\n\nSin argumento o con `true` activa el cifrado; `false` lo desactiva. No hace nada mientras `CONF.secret_encryption` esté vacío.\n\nExample: Activar\n```js\nfunction secure() {\n\tthis.encrypt();\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nHace ping a todos los clientes.\n\nReturns: `WebSocket`\n\nCada pong establece `client.latency`. El framework lo llama tres veces por minuto (a los 15, 30 y 60 segundos de cada minuto) para todos los objetos WebSocket.\n\nExample: Hacer ping ahora\n```js\nself.ping();\n```\n\n### websocket.error(err)\n\nType: `method`\n\nRegistra un error con la URL del WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  |  |\n\nUna cadena se convierte en un `Error`. El error va al log de errores del framework.\n\nExample: Registrar\n```js\nself.on('message', function(client, message) {\n\tif (!message.type)\n\t\tself.error('Missing type');\n});\n```\n\n### websocket.on('open', function(client) {})\n\nType: `event`\n\nSe ha conectado un cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  | El cliente nuevo |\n\nExample: Bienvenida\n```js\nself.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message, size) {})\n\nType: `event`\n\nUn cliente ha enviado un mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  |  |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nEn las rutas `@json` `message` es un objeto parseado; en las rutas `@text`, una cadena; en las rutas `@binary`, un `Buffer`. `size` es el tamaño en bytes.\n\nExample: Eco\n```js\nself.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 ha desconectado un cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  |  |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n`code` y `message` son el código y el motivo de cierre enviados por el cliente, o los que se pasan a `close()` cuando el servidor cierra la conexión.\n\nExample: Salida\n```js\nself.on('close', function(client) {\n\tself.send({ type: 'left', id: client.id });\n});\n```\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nUn error en el socket de un cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nReturns: `undefined` Nada\n\nLos reinicios de conexión y las tuberías rotas no lo emiten; cierran el cliente. Un error al comprimir o descomprimir un mensaje (`permessage-deflate`) se emite aquí con el cliente.\n\nExample: Registrar\n```js\nself.on('error', function(err, client) {\n\tself.error(err);\n});\n```\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nEl objeto WebSocket se está destruyendo.\n\nLo emiten `destroy()` y `autodestroy()`.\n\nExample: Limpieza\n```js\nself.on('destroy', function() {\n\tclearInterval(timer);\n});\n```\n\n### ON('websocket_end', function(websocket, client) {})\n\nType: `event`\n\nSe ha desconectado cualquier cliente de cualquier ruta WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `websocket` | `WebSocket` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nExample: Log global\n```js\nON('websocket_end', function(websocket, client) {\n\tconsole.log(websocket.url, client.ip);\n});\n```\n\n### client\n\nType: `class`\n\nUn cliente conectado a una ruta WebSocket.\n\nLos clientes llegan en los eventos del objeto WebSocket. Tienen los datos de la petición de upgrade: `id`, `ip`, `user`, `query`, `params`, `headers`, `url`, `uri`, `ua`, `mobile`, `robot`, `referrer`, `host`, `address`, `protocol`, `language`, y `req` y `socket`. Puedes añadir tus propias propiedades. `F.extend('controller', name, fn)` añade un método a los controladores HTTP y WebSocket.\n\nExample: Datos propios\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n### client.id\n\nType: `property`\n\nUn identificador único del cliente.\n\nReturns: `String`\n\nTambién `client.ID`. Es la clave en `websocket.connections`.\n\nExample: Enviar el id\n```js\nclient.send({ id: client.id });\n```\n\n### client.user\n\nType: `property`\n\nEl usuario que devuelve el delegado de autorización.\n\nReturns: `Object`\n\n`undefined` para clientes anónimos.\n\nExample: Saludar\n```js\nself.on('open', function(client) {\n\tclient.send({ name: client.user ? client.user.name : 'guest' });\n});\n```\n\n### client.ip\n\nType: `property`\n\nLa dirección IP del cliente.\n\nReturns: `String`\n\nLa primera dirección de `X-Forwarded-For` detrás de un proxy.\n\n### client.query\n\nType: `property`\n\nEl query string de la URL WebSocket como objeto.\n\nReturns: `Object`\n\nÚsalo para pasar datos que los navegadores no pueden enviar en cabeceras, como un token.\n\nExample: Token\n```js\n// new WebSocket('ws://localhost:8000/live/?token=abc')\nvar token = client.query.token;\n```\n\n### client.params\n\nType: `property`\n\nLos parámetros dinámicos de la URL.\n\nReturns: `Object`\n\n### client.headers\n\nType: `property`\n\nLas cabeceras de la petición de upgrade, con nombres en minúsculas.\n\nReturns: `Object`\n\n### client.latency\n\nType: `property`\n\nEl tiempo en ms entre el último ping y su pong.\n\nReturns: `Number`\n\nCada ping lo restablece a `null`; el pong establece el tiempo medido.\n\nExample: Mostrar la latencia\n```js\nself.on('message', function(client) {\n\tclient.send({ latency: client.latency });\n});\n```\n\n### client.address\n\nType: `property`\n\nLa URL completa a la que se conectó el cliente.\n\nReturns: `String`\n\nEl protocolo (`http` o `https`), el host y la ruta con el query string.\n\n### client.ua\n\nType: `property`\n\nUn nombre corto del navegador y del sistema, obtenido de `User-Agent`.\n\nReturns: `String`\n\n`client.mobile` y `client.robot` son `true` para dispositivos móviles y crawlers.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nEnvía un mensaje a un cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Enviar una cadena sin serialización JSON (rutas `@text`) |\n| `replacer` | `Function` | no |  | Un replacer de JSON |\n\nEn las rutas `@json` los objetos se serializan con `JSON.stringify()` y los demás valores se envían como cadenas. En las rutas `@text` el mensaje se serializa a JSON salvo que `raw` sea `true`, que envía la cadena tal cual. En las rutas `@binary` pasa un `Buffer`. `replacer` se pasa a `JSON.stringify()`.\n\nExample: JSON\n```js\nclient.send({ type: 'pong' });\n```\n\nExample: Texto plano\n```js\nclient.send('OK', true);\n```\n\n### client.close([code], [message])\n\nType: `method`\n\nCierra la conexión con el cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | El código de cierre |\n| `message` | `String` | no |  | El motivo del cierre |\n\nEl frame de cierre se envía al cabo de 1 segundo y después se destruye el socket.\n\nExample: Rechazar\n```js\nself.on('open', function(client) {\n\tif (!client.query.token)\n\t\tclient.close(4003, 'Forbidden');\n});\n```\n\n### client.ping()\n\nType: `method`\n\nEnvía un ping al cliente.\n\nReturns: `Controller` El mismo cliente\n\nEl pong establece `client.latency`.\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 |  |  |\n\nReturns: `String` El valor decodificado, o una cadena vacía\n\nExample: Sesión\n```js\nvar sid = client.cookie('sid');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nDevuelve el protocolo y el host de la petición, con una ruta opcional.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Se añade al host |\n\nReturns: `String` Por ejemplo `https://example.com/path/`\n\n### client.destroy()\n\nType: `method`\n\nDestruye el socket de inmediato, sin frame de cierre.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nCrea un cliente WebSocket que se conecta a otro servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(client)` |\n\nReturns: `WebSocketClient` El cliente\n\n`callback(client)` se llama de inmediato con el cliente nuevo. Configura las opciones, las cabeceras y los eventos, y después 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('ws://127.0.0.1:8000/live/');\n});\n```\n\n### wsclient.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 |  |  |\n| `protocol` | `String` | no |  |  |\n| `origin` | `String` | no |  |  |\n\n`url` es una dirección `ws://` o `wss://`, o un objeto `{ socket: '/path/to/unix.socket', path: '/live/' }` para un socket Unix. `protocol` se envía como `Sec-WebSocket-Protocol` y `origin` como `Sec-WebSocket-Origin`. Se siguen las redirecciones HTTP (301, 302). El cliente emite `open` cuando el servidor acepta la conexión.\n\nExample: Seguro\n```js\nclient.connect('wss://example.com/live/');\n```\n\n### wsclient.options\n\nType: `property`\n\nLas opciones del cliente.\n\nReturns: `Object`\n\nEstablécelas antes de `connect()`: `type` (`json`, `text` o `binary`, por defecto `json`), `compress` (`true`), `reconnect` (retardo en ms después de que se cierre la conexión, `3000`, `0` lo desactiva), `reconnectserver` (`true` también reconecta cuando no se puede abrir la conexión o el servidor responde con un error HTTP), `masking` (`false`), `encodedecode` (`false`), `encrypt` (una clave para cifrar los mensajes), `size` (tamaño máx. en bytes de un mensaje descomprimido, `0` sin límite), `rejectunauthorized` (`false`), `timeout` (retardo de keep-alive TCP en ms, `30000`, `0` lo desactiva), y `key`, `cert`, `dhparam` para TLS.\n\nExample: Cliente de texto\n```js\nvar client = WEBSOCKETCLIENT();\nclient.options.type = 'text';\nclient.options.reconnect = 0;\nclient.connect('ws://127.0.0.1:8000/terminal/');\n```\n\n### wsclient.headers\n\nType: `property`\n\nCabeceras adicionales de la petición de upgrade.\n\nReturns: `Object`\n\nEstablécelas antes de `connect()`.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\n```\n\n### wsclient.send(message, [raw], [replacer])\n\nType: `method`\n\nEnvía un mensaje al servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Enviar una cadena JSON ya preparada |\n| `replacer` | `Function` | no |  | Un replacer de JSON |\n\nReturns: `Boolean` `true` cuando se escribió el mensaje\n\nCon el tipo `json`, el mensaje se serializa con `JSON.stringify()` salvo que `raw` sea `true`. Con el tipo `text`, los objetos se serializan y los demás valores se envían como cadenas. Con el tipo `binary`, un valor que no es Buffer se convierte en un `Buffer`. Devuelve `false` cuando la conexión está cerrada.\n\nExample: Enviar\n```js\nclient.send({ type: 'subscribe', channel: 'news' });\n```\n\n### wsclient.sendcustom(type, message)\n\nType: `method`\n\nEnvía un mensaje como texto o binario, independientemente de `options.type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `binary` o `text` |\n| `message` | `String|Buffer` | yes |  |  |\n\nReturns: `Boolean` `true` cuando se escribió el mensaje\n\n`type` es `'binary'` o cualquier otro valor para texto.\n\nExample: Binario\n```js\nclient.sendcustom('binary', Buffer.from([1, 2, 3]));\n```\n\n### wsclient.close([code], [message])\n\nType: `method`\n\nCierra la conexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` |  |\n| `message` | `String|Boolean` | no |  | El motivo del cierre, o `true` |\n\nReturns: `WebSocketClient`\n\nDeja de reconectar. Pasa `true` como `message` para cerrar la conexión y mantener la reconexión automática.\n\nExample: Cerrar\n```js\nclient.close();\n```\n\n### wsclient.destroy()\n\nType: `method`\n\nDestruye la conexión y deja de reconectar.\n\nEmite `destroy`.\n\nExample: Destruir\n```js\nclient.destroy();\n```\n\n### wsclient.ping([timeout])\n\nType: `method`\n\nEnvía un ping y espera el pong.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | no | `3000` | Tiempo en ms |\n\nReturns: `WebSocketClient`\n\nEl pong establece `client.latency`. Si no llega un pong en `timeout` ms, el cliente emite `error` con un error `Timeout`, cierra la conexión y reconecta cuando `options.reconnect` está establecido.\n\nExample: Comprobar de forma continua\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### wsclient.api(schema, [data], [callback], [timeout])\n\nType: `method`\n\nEnvía una petición de API por la conexión y espera la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  |  |\n| `data` | `Object` | no |  |  |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `5000` | Tiempo en ms |\n\nReturns: `Promise` Cuando no se pasa un callback\n\nEnvía `{ TYPE: 'api', callbackid, data: { schema, data } }` y se resuelve cuando el servidor responde con un mensaje `{ TYPE: 'api', callbackid, data }` (con `error: true`, `data` es el error). Si no hay respuesta en `timeout` ms (5000), el callback recibe `408`. Sin callback devuelve una promesa.\n\nExample: Promesa\n```js\nvar response = await client.api('users_list', { page: 1 });\n```\n\n### wsclient.on('message', function(message, size) {})\n\nType: `event`\n\nUn mensaje del servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nUn objeto parseado con el tipo `json`, una cadena con `text`, un `Buffer` con `binary`.\n\n### wsclient.on('open', function() {})\n\nType: `event`\n\nLa conexión está abierta.\n\nTambién se emite después de cada reconexión.\n\n### wsclient.on('close', function(code, message) {})\n\nType: `event`\n\nSe cerró la conexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n### wsclient.on('error', function(err) {})\n\nType: `event`\n\nUn error de conexión, una respuesta HTTP inesperada, una clave de servidor no válida o un timeout de ping.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n\nExample: Log\n```js\nclient.on('error', function(err) {\n\tconsole.log('WS error', err.message);\n});\n```\n\n### route.remove()\n\nType: `method` · Since: `0.0.17`\n\nElimina una ruta registrada con `ROUTE()`.\n\nPara una ruta `SOCKET` elimina la ruta y destruye todos sus objetos WebSocket, así que se desconecta a todos los clientes conectados.\n\nExample: Eliminar\n```js\nvar route = ROUTE('SOCKET /live/', live);\nroute.remove();\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET ...')","signature":"ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"CONF.$wsmaxsize","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"CONF.$wscompress","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"CONF.$wsencodedecode","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"CONF.$wsmaxlatency","since":"","deprecated":false},{"type":"class","name":"WebSocket","signature":"function() { var websocket = this; }","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.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","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.close()","signature":"websocket.close([code], [message])","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.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.error()","signature":"websocket.error(err)","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, size) {})","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":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(websocket, client) {})","since":"","deprecated":false},{"type":"class","name":"Controller (WebSocket client)","signature":"client","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.ip","signature":"client.ip","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.params","signature":"client.params","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":"property","name":"client.address","signature":"client.address","since":"","deprecated":false},{"type":"property","name":"client.ua","signature":"client.ua","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([code], [message])","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","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":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"method","name":"wsclient.connect()","signature":"wsclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"property","name":"wsclient.options","signature":"wsclient.options","since":"","deprecated":false},{"type":"property","name":"wsclient.headers","signature":"wsclient.headers","since":"","deprecated":false},{"type":"method","name":"wsclient.send()","signature":"wsclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"wsclient.sendcustom()","signature":"wsclient.sendcustom(type, message)","since":"","deprecated":false},{"type":"method","name":"wsclient.close()","signature":"wsclient.close([code], [message])","since":"","deprecated":false},{"type":"method","name":"wsclient.destroy()","signature":"wsclient.destroy()","since":"","deprecated":false},{"type":"method","name":"wsclient.ping()","signature":"wsclient.ping([timeout])","since":"","deprecated":false},{"type":"method","name":"wsclient.api()","signature":"wsclient.api(schema, [data], [callback], [timeout])","since":"","deprecated":false},{"type":"event","name":"wsclient.on('message')","signature":"wsclient.on('message', function(message, size) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('open')","signature":"wsclient.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('close')","signature":"wsclient.on('close', function(code, message) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('error')","signature":"wsclient.on('error', function(err) {})","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmEM7Gc61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/websockets/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"WebSockets","summary":"L'objet WebSocket, ses clients, WEBSOCKETCLIENT() et la configuration WebSocket.","markdown":"---\ntitle: WebSockets\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/websockets/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# WebSockets\n\n> L'objet WebSocket, ses clients, WEBSOCKETCLIENT() et la configuration WebSocket.\n\nMéthodes, propriétés et événements des routes WebSocket (`ROUTE('SOCKET ...')`), de l'objet WebSocket, de ses clients, de `WEBSOCKETCLIENT()` et des clés de configuration `$ws*`. Pour une introduction avec des exemples, lis le guide [WebSockets](../../guides/websockets/).\n\n## API\n\n### ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])\n\nType: `method`\n\nEnregistre une route WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Méthode, chemin, flags et middleware |\n| `action` | `Function` | yes |  | Appelée avec l'objet WebSocket |\n| `size` | `Number` | no | `CONF.$wsmaxsize * 1024` | Taille max. d'un message en octets |\n\nReturns: `Route` La route enregistrée\n\nL'action s'exécute une fois par URL, quand le premier client se connecte, avec l'objet WebSocket comme `this` et comme premier argument. Préfixe la méthode avec `+` (utilisateurs autorisés seulement) ou `-` (anonymes seulement). Flags : `@json` (par défaut), `@text`, `@binary` (les messages sont des objets `Buffer` et partent en frames binaires, même quand ils sont compressés) et `@csrf`. Un client que l'autorisation refuse (il ne correspond pas à `+` ou `-`) est accepté puis fermé avec le code `4001`. `#name` exécute un middleware avant l'upgrade. La limite de taille est `CONF.$wsmaxsize` ko, sauf si tu passes `size` en octets ou `<NMB` dans l'URL. Renvoie la route.\n\nExample: Salon de discussion\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\t\tself.send(message);\n\t});\n}\n```\n\nExample: Utilisateurs autorisés, messages texte, 1 Mo\n```js\nROUTE('+SOCKET /console/ @text <1MB', terminal);\n```\n\nExample: Messages binaires\n```js\nROUTE('SOCKET /files/ @binary', function($) {\n\t$.on('message', function(client, buffer) {\n\t\tclient.send(buffer); // a binary frame back\n\t});\n});\n```\n\n### CONF.$wsmaxsize\n\nType: `config`\n\nTaille max. par défaut d'un message WebSocket en kB.\n\nReturns: `Number`\n\nPar défaut `256`. Un message plus grand ferme le client avec le code `1009`. Une route peut définir sa propre taille.\n\nExample: Fichier de configuration\n```js\n$wsmaxsize\t\t: 512\n```\n\n### CONF.$wscompress\n\nType: `config`\n\nAutorise la compression `permessage-deflate`.\n\nReturns: `Boolean`\n\nPar défaut `true`. Quand le navigateur propose `permessage-deflate`, les messages sont compressés dans les deux sens.\n\nExample: Désactiver la compression\n```js\n$wscompress\t   : false\n```\n\n### CONF.$wsencodedecode\n\nType: `config`\n\nEncode et décode tous les messages WebSocket avec l'encodage URI.\n\nReturns: `Boolean`\n\nPar défaut `false`. Avec `true`, les messages sortants et les motifs de fermeture passent par `encodeURIComponent()` et les messages entrants par `decodeURIComponent()`. L'autre côté doit faire de même.\n\nExample: Fichier de configuration\n```js\n$wsencodedecode   : true\n```\n\n### CONF.$wsmaxlatency\n\nType: `config`\n\nLatence max. en ms avant que la vérification du ping ferme un client.\n\nReturns: `Number`\n\nPar défaut `2000`. Trois fois par minute (à 15, 30 et 60 secondes de chaque minute), le framework envoie un ping à tous les clients de toutes les routes WebSocket et mesure `client.latency` à partir du pong. Avant chaque ping, il vérifie les clients : un client qui n'a pas répondu au ping précédent, ou dont la latence dépasse `CONF.$wsmaxlatency` (2000 ms), est fermé. Cela supprime les connexions mortes sans code de ta part.\n\nExample: Fichier de configuration\n```js\n$wsmaxlatency\t : 5000\n```\n\n### function() { var websocket = this; }\n\nType: `class`\n\nL'objet qui regroupe tous les clients d'une URL WebSocket.\n\nReturns: `WebSocket`\n\nC'est `this` dans l'action d'une route `SOCKET`. Il existe un objet par URL : une route dynamique en a un par URL distincte. C'est un émetteur d'événements (`on`, `once`, `emit`, `off`).\n\nExample: Événements\n```js\nfunction live() {\n\tvar self = this;\n\tself.on('open', function(client) {});\n\tself.on('message', function(client, message) {});\n\tself.on('close', function(client) {});\n}\n```\n\n### websocket.online\n\nType: `property`\n\nLe nombre de clients connectés.\n\nReturns: `Number`\n\nExample: Compter\n```js\nself.on('open', function() {\n\tself.send({ type: 'online', count: self.online });\n});\n```\n\n### websocket.connections\n\nType: `property`\n\nLes clients connectés sous forme d'objet `{ id: client }`.\n\nReturns: `Object`\n\nExample: Parcourir\n```js\nfor (var id in self.connections) {\n\tvar client = self.connections[id];\n}\n```\n\n### websocket.params\n\nType: `property`\n\nLes paramètres dynamiques de l'URL.\n\nReturns: `Object`\n\nRempli à partir du premier client de l'URL ; tous les clients de l'objet partagent les mêmes valeurs.\n\nExample: Nom du salon\n```js\nROUTE('SOCKET /room/{name}/', function() {\n\tvar name = this.params.name;\n});\n```\n\n### websocket.url\n\nType: `property`\n\nL'URL du groupe en minuscules.\n\nReturns: `String`\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nEnvoie un message à tous les clients, ou aux clients choisis par un comparateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  | Le message |\n| `comparer` | `Function` | no |  | `function(client, message, params)` qui renvoie un booléen |\n| `replacer` | `Function` | no |  | Un replacer JSON |\n| `params` | `Object` | no |  | Passé au comparateur |\n\nReturns: `WebSocket` Le même objet\n\nLe message est sérialisé une seule fois avec `JSON.stringify()` (pour les routes `@json` et `@text`) ; sur les routes `@binary`, passe un `Buffer`. `comparer(client, message, params)` renvoie `true` pour les clients qui le reçoivent. `replacer` est passé à `JSON.stringify()` ; quand le troisième argument n'est pas une fonction, il est utilisé comme `params`.\n\nExample: Tout le monde\n```js\nself.send({ type: 'refresh' });\n```\n\nExample: Seulement les administrateurs\n```js\nself.send({ type: 'alert' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nTrouve le premier client pour lequel `fn(client)` renvoie `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` qui renvoie un booléen |\n\nReturns: `Controller` Le client, ou `undefined`\n\nExample: Par utilisateur\n```js\nvar client = self.find(function(client) {\n\treturn client.user && client.user.id === id;\n});\n```\n\n### websocket.close([code], [message])\n\nType: `method`\n\nFerme tous les clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | Le code de fermeture |\n| `message` | `String` | no |  | Le motif de fermeture |\n\nReturns: `WebSocket`\n\nL'objet WebSocket reste, donc de nouveaux clients peuvent se connecter.\n\nExample: Fermer tout le monde\n```js\nself.close(4000, 'Maintenance');\n```\n\n### websocket.destroy()\n\nType: `method`\n\nFerme tous les clients et supprime l'objet WebSocket.\n\nÉmet `destroy`. Le prochain client qui se connecte à l'URL exécute à nouveau l'action de la route et obtient un nouvel objet.\n\nExample: Détruire\n```js\nself.destroy();\n```\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nDétruit l'objet 5 secondes après le départ du dernier client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelé avant la destruction de l'objet |\n\nReturns: `WebSocket`\n\nSi un client se connecte pendant ces 5 secondes, l'objet reste. Avant la destruction, chaque `callback` est appelé avec l'objet WebSocket comme `this`. Appelle-la plusieurs fois pour ajouter d'autres callbacks.\n\nExample: Arrêter un timer\n```js\nvar timer = setInterval(function() {\n\tself.send({ ts: Date.now() });\n}, 1000);\n\nself.autodestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nChiffre et déchiffre tous les messages du groupe avec `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` |  |\n\nSans argument ou avec `true`, elle active le chiffrement ; `false` le désactive. Elle ne fait rien tant que `CONF.secret_encryption` est vide.\n\nExample: Activer\n```js\nfunction secure() {\n\tthis.encrypt();\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nEnvoie un ping à tous les clients.\n\nReturns: `WebSocket`\n\nChaque pong définit `client.latency`. Le framework l'appelle trois fois par minute (à 15, 30 et 60 secondes de chaque minute) pour tous les objets WebSocket.\n\nExample: Ping immédiat\n```js\nself.ping();\n```\n\n### websocket.error(err)\n\nType: `method`\n\nJournalise une erreur avec l'URL du WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  |  |\n\nUne chaîne est convertie en `Error`. L'erreur va dans le journal des erreurs du framework.\n\nExample: Journaliser\n```js\nself.on('message', function(client, message) {\n\tif (!message.type)\n\t\tself.error('Missing type');\n});\n```\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` | `Controller` | yes |  | Le nouveau client |\n\nExample: Bienvenue\n```js\nself.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message, size) {})\n\nType: `event`\n\nUn client a envoyé un message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  |  |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nSur les routes `@json`, `message` est un objet analysé ; sur les routes `@text`, une chaîne ; sur les routes `@binary`, un `Buffer`. `size` est la taille en octets.\n\nExample: Écho\n```js\nself.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` | `Controller` | yes |  |  |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n`code` et `message` sont le code et le motif de fermeture envoyés par le client, ou ceux passés à `close()` lorsque le serveur ferme la connexion.\n\nExample: Départ\n```js\nself.on('close', function(client) {\n\tself.send({ type: 'left', id: client.id });\n});\n```\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nUne erreur sur le socket d'un client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nLes réinitialisations de connexion et les pipes cassés ne l'émettent pas ; ils ferment le client. Une erreur pendant la compression ou la décompression d'un message (`permessage-deflate`) est émise ici avec le client.\n\nExample: Journaliser\n```js\nself.on('error', function(err, client) {\n\tself.error(err);\n});\n```\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nL'objet WebSocket est en cours de destruction.\n\nÉmis par `destroy()` et `autodestroy()`.\n\nExample: Nettoyage\n```js\nself.on('destroy', function() {\n\tclearInterval(timer);\n});\n```\n\n### ON('websocket_end', function(websocket, client) {})\n\nType: `event`\n\nUn client d'une route WebSocket quelconque s'est déconnecté.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `websocket` | `WebSocket` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nExample: Journal global\n```js\nON('websocket_end', function(websocket, client) {\n\tconsole.log(websocket.url, client.ip);\n});\n```\n\n### client\n\nType: `class`\n\nUn client connecté d'une route WebSocket.\n\nLes clients arrivent dans les événements de l'objet WebSocket. Ils possèdent les données de la requête d'upgrade : `id`, `ip`, `user`, `query`, `params`, `headers`, `url`, `uri`, `ua`, `mobile`, `robot`, `referrer`, `host`, `address`, `protocol`, `language`, ainsi que `req` et `socket`. Tu peux ajouter tes propres propriétés. `F.extend('controller', name, fn)` ajoute une méthode aux contrôleurs HTTP et WebSocket.\n\nExample: Données propres\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n### client.id\n\nType: `property`\n\nUn identifiant unique du client.\n\nReturns: `String`\n\nAussi `client.ID`. C'est la clé dans `websocket.connections`.\n\nExample: Envoyer l'id\n```js\nclient.send({ id: client.id });\n```\n\n### client.user\n\nType: `property`\n\nL'utilisateur renvoyé par le délégué d'autorisation.\n\nReturns: `Object`\n\n`undefined` pour les clients anonymes.\n\nExample: Saluer\n```js\nself.on('open', function(client) {\n\tclient.send({ name: client.user ? client.user.name : 'guest' });\n});\n```\n\n### client.ip\n\nType: `property`\n\nL'adresse IP du client.\n\nReturns: `String`\n\nLa première adresse de `X-Forwarded-For` derrière un proxy.\n\n### client.query\n\nType: `property`\n\nLa query string de l'URL WebSocket sous forme d'objet.\n\nReturns: `Object`\n\nUtilise-la pour passer des données que les navigateurs ne peuvent pas envoyer dans les en-têtes, comme un jeton.\n\nExample: Jeton\n```js\n// new WebSocket('ws://localhost:8000/live/?token=abc')\nvar token = client.query.token;\n```\n\n### client.params\n\nType: `property`\n\nLes paramètres dynamiques de l'URL.\n\nReturns: `Object`\n\n### client.headers\n\nType: `property`\n\nLes en-têtes de la requête d'upgrade, avec des noms en minuscules.\n\nReturns: `Object`\n\n### client.latency\n\nType: `property`\n\nLe temps en ms entre le dernier ping et son pong.\n\nReturns: `Number`\n\nChaque ping le remet à `null` ; le pong définit le temps mesuré.\n\nExample: Afficher la latence\n```js\nself.on('message', function(client) {\n\tclient.send({ latency: client.latency });\n});\n```\n\n### client.address\n\nType: `property`\n\nL'URL complète à laquelle le client s'est connecté.\n\nReturns: `String`\n\nLe protocole (`http` ou `https`), l'hôte et le chemin avec la query string.\n\n### client.ua\n\nType: `property`\n\nUn nom court du navigateur et du système, extrait de `User-Agent`.\n\nReturns: `String`\n\n`client.mobile` et `client.robot` valent `true` pour les appareils mobiles et les robots d'indexation.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nEnvoie un message à un client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Envoie une chaîne sans sérialisation JSON (routes `@text`) |\n| `replacer` | `Function` | no |  | Un replacer JSON |\n\nSur les routes `@json`, les objets sont sérialisés avec `JSON.stringify()` et les autres valeurs sont envoyées sous forme de chaînes. Sur les routes `@text`, le message est sérialisé en JSON sauf si `raw` vaut `true`, ce qui envoie la chaîne telle quelle. Sur les routes `@binary`, passe un `Buffer`. `replacer` est passé à `JSON.stringify()`.\n\nExample: JSON\n```js\nclient.send({ type: 'pong' });\n```\n\nExample: Texte brut\n```js\nclient.send('OK', true);\n```\n\n### client.close([code], [message])\n\nType: `method`\n\nFerme la connexion avec le client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | Le code de fermeture |\n| `message` | `String` | no |  | Le motif de fermeture |\n\nLa trame de fermeture est envoyée après 1 seconde, puis le socket est détruit.\n\nExample: Refuser\n```js\nself.on('open', function(client) {\n\tif (!client.query.token)\n\t\tclient.close(4003, 'Forbidden');\n});\n```\n\n### client.ping()\n\nType: `method`\n\nEnvoie un ping au client.\n\nReturns: `Controller` Le même client\n\nLe pong définit `client.latency`.\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 |  |  |\n\nReturns: `String` La valeur décodée, ou une chaîne vide\n\nExample: Session\n```js\nvar sid = client.cookie('sid');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nRenvoie le protocole et l'hôte de la requête, avec un chemin facultatif.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ajouté après l'hôte |\n\nReturns: `String` Par exemple `https://example.com/path/`\n\n### client.destroy()\n\nType: `method`\n\nDétruit le socket immédiatement, sans trame de fermeture.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nCrée un client WebSocket qui se connecte à un autre serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(client)` |\n\nReturns: `WebSocketClient` Le client\n\n`callback(client)` est appelé immédiatement avec le nouveau client. Définis 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('ws://127.0.0.1:8000/live/');\n});\n```\n\n### wsclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nOuvre la connexion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  |  |\n| `protocol` | `String` | no |  |  |\n| `origin` | `String` | no |  |  |\n\n`url` est une adresse `ws://` ou `wss://`, ou un objet `{ socket: '/path/to/unix.socket', path: '/live/' }` pour un socket Unix. `protocol` est envoyé comme `Sec-WebSocket-Protocol` et `origin` comme `Sec-WebSocket-Origin`. Les redirections HTTP (301, 302) sont suivies. Le client émet `open` quand le serveur accepte la connexion.\n\nExample: Sécurisé\n```js\nclient.connect('wss://example.com/live/');\n```\n\n### wsclient.options\n\nType: `property`\n\nLes options du client.\n\nReturns: `Object`\n\nDéfinis-les avant `connect()` : `type` (`json`, `text` ou `binary`, `json` par défaut), `compress` (`true`), `reconnect` (délai en ms après la fermeture de la connexion, `3000`, `0` le désactive), `reconnectserver` (`true` reconnecte aussi quand la connexion ne peut pas être ouverte ou que le serveur répond par une erreur HTTP), `masking` (`false`), `encodedecode` (`false`), `encrypt` (une clé pour chiffrer les messages), `size` (taille max. en octets d'un message décompressé, `0` sans limite), `rejectunauthorized` (`false`), `timeout` (délai de keep-alive TCP en ms, `30000`, `0` le désactive), ainsi que `key`, `cert`, `dhparam` pour TLS.\n\nExample: Client texte\n```js\nvar client = WEBSOCKETCLIENT();\nclient.options.type = 'text';\nclient.options.reconnect = 0;\nclient.connect('ws://127.0.0.1:8000/terminal/');\n```\n\n### wsclient.headers\n\nType: `property`\n\nEn-têtes supplémentaires de la requête d'upgrade.\n\nReturns: `Object`\n\nDéfinis-les avant `connect()`.\n\nExample: Jeton\n```js\nclient.headers['x-token'] = 'secret';\n```\n\n### wsclient.send(message, [raw], [replacer])\n\nType: `method`\n\nEnvoie un message au serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Envoie une chaîne JSON préparée |\n| `replacer` | `Function` | no |  | Un replacer JSON |\n\nReturns: `Boolean` `true` quand le message a été écrit\n\nAvec le type `json`, le message est sérialisé avec `JSON.stringify()` sauf si `raw` vaut `true`. Avec le type `text`, les objets sont sérialisés et les autres valeurs sont envoyées sous forme de chaînes. Avec le type `binary`, une valeur qui n'est pas un Buffer est convertie en `Buffer`. Renvoie `false` quand la connexion est fermée.\n\nExample: Envoyer\n```js\nclient.send({ type: 'subscribe', channel: 'news' });\n```\n\n### wsclient.sendcustom(type, message)\n\nType: `method`\n\nEnvoie un message en texte ou en binaire, quel que soit `options.type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `binary` ou `text` |\n| `message` | `String|Buffer` | yes |  |  |\n\nReturns: `Boolean` `true` quand le message a été écrit\n\n`type` vaut `'binary'`, ou toute autre valeur pour du texte.\n\nExample: Binaire\n```js\nclient.sendcustom('binary', Buffer.from([1, 2, 3]));\n```\n\n### wsclient.close([code], [message])\n\nType: `method`\n\nFerme la connexion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` |  |\n| `message` | `String|Boolean` | no |  | Le motif de fermeture, ou `true` |\n\nReturns: `WebSocketClient`\n\nElle arrête la reconnexion. Passe `true` comme `message` pour fermer la connexion et conserver la reconnexion automatique.\n\nExample: Fermer\n```js\nclient.close();\n```\n\n### wsclient.destroy()\n\nType: `method`\n\nDétruit la connexion et arrête la reconnexion.\n\nÉmet `destroy`.\n\nExample: Détruire\n```js\nclient.destroy();\n```\n\n### wsclient.ping([timeout])\n\nType: `method`\n\nEnvoie un ping et attend le pong.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | no | `3000` | Durée en ms |\n\nReturns: `WebSocketClient`\n\nLe pong définit `client.latency`. Sans pong dans les `timeout` ms, le client émet `error` avec une erreur `Timeout`, ferme la connexion et se reconnecte quand `options.reconnect` est défini.\n\nExample: Vérifier en continu\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### wsclient.api(schema, [data], [callback], [timeout])\n\nType: `method`\n\nEnvoie une requête d'API sur la connexion et attend la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  |  |\n| `data` | `Object` | no |  |  |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `5000` | Durée en ms |\n\nReturns: `Promise` Quand aucun callback n'est fourni\n\nEnvoie `{ TYPE: 'api', callbackid, data: { schema, data } }` et se résout quand le serveur répond avec un message `{ TYPE: 'api', callbackid, data }` (avec `error: true`, `data` est l'erreur). Sans réponse dans les `timeout` ms (5000), le callback reçoit `408`. Sans callback, elle renvoie une promesse.\n\nExample: Promesse\n```js\nvar response = await client.api('users_list', { page: 1 });\n```\n\n### wsclient.on('message', function(message, size) {})\n\nType: `event`\n\nUn message du serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nUn objet analysé avec le type `json`, une chaîne avec `text`, un `Buffer` avec `binary`.\n\n### wsclient.on('open', function() {})\n\nType: `event`\n\nLa connexion est ouverte.\n\nÉmis aussi après chaque reconnexion.\n\n### wsclient.on('close', function(code, message) {})\n\nType: `event`\n\nLa connexion a été fermée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n### wsclient.on('error', function(err) {})\n\nType: `event`\n\nUne erreur de connexion, une réponse HTTP inattendue, une clé de serveur invalide ou un timeout du ping.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n\nExample: Journaliser\n```js\nclient.on('error', function(err) {\n\tconsole.log('WS error', err.message);\n});\n```\n\n### route.remove()\n\nType: `method` · Since: `0.0.17`\n\nSupprime une route enregistrée avec `ROUTE()`.\n\nPour une route `SOCKET`, elle supprime la route et détruit tous ses objets WebSocket : chaque client connecté est donc déconnecté.\n\nExample: Supprimer\n```js\nvar route = ROUTE('SOCKET /live/', live);\nroute.remove();\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET ...')","signature":"ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"CONF.$wsmaxsize","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"CONF.$wscompress","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"CONF.$wsencodedecode","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"CONF.$wsmaxlatency","since":"","deprecated":false},{"type":"class","name":"WebSocket","signature":"function() { var websocket = this; }","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.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","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.close()","signature":"websocket.close([code], [message])","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.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.error()","signature":"websocket.error(err)","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, size) {})","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":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(websocket, client) {})","since":"","deprecated":false},{"type":"class","name":"Controller (WebSocket client)","signature":"client","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.ip","signature":"client.ip","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.params","signature":"client.params","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":"property","name":"client.address","signature":"client.address","since":"","deprecated":false},{"type":"property","name":"client.ua","signature":"client.ua","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([code], [message])","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","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":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"method","name":"wsclient.connect()","signature":"wsclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"property","name":"wsclient.options","signature":"wsclient.options","since":"","deprecated":false},{"type":"property","name":"wsclient.headers","signature":"wsclient.headers","since":"","deprecated":false},{"type":"method","name":"wsclient.send()","signature":"wsclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"wsclient.sendcustom()","signature":"wsclient.sendcustom(type, message)","since":"","deprecated":false},{"type":"method","name":"wsclient.close()","signature":"wsclient.close([code], [message])","since":"","deprecated":false},{"type":"method","name":"wsclient.destroy()","signature":"wsclient.destroy()","since":"","deprecated":false},{"type":"method","name":"wsclient.ping()","signature":"wsclient.ping([timeout])","since":"","deprecated":false},{"type":"method","name":"wsclient.api()","signature":"wsclient.api(schema, [data], [callback], [timeout])","since":"","deprecated":false},{"type":"event","name":"wsclient.on('message')","signature":"wsclient.on('message', function(message, size) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('open')","signature":"wsclient.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('close')","signature":"wsclient.on('close', function(code, message) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('error')","signature":"wsclient.on('error', function(err) {})","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmEM7Gc61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/websockets/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"WebSocket","summary":"L'oggetto WebSocket, i suoi client, WEBSOCKETCLIENT() e la configurazione WebSocket.","markdown":"---\ntitle: WebSocket\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/websockets/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# WebSocket\n\n> L'oggetto WebSocket, i suoi client, WEBSOCKETCLIENT() e la configurazione WebSocket.\n\nMetodi, proprietà ed eventi delle route WebSocket (`ROUTE('SOCKET ...')`), dell'oggetto WebSocket, dei suoi client, di `WEBSOCKETCLIENT()` e delle chiavi di configurazione `$ws*`. Per un'introduzione con esempi leggi la guida [WebSocket](../../guides/websockets/).\n\n## API\n\n### ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])\n\nType: `method`\n\nRegistra una route WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Metodo, percorso, flag e middleware |\n| `action` | `Function` | yes |  | Chiamata con l'oggetto WebSocket |\n| `size` | `Number` | no | `CONF.$wsmaxsize * 1024` | Dimensione massima di un messaggio in byte |\n\nReturns: `Route` La route registrata\n\nL'azione viene eseguita una volta per URL, quando si connette il primo client, con l'oggetto WebSocket come `this` e come primo argomento. Metti davanti al metodo `+` (solo utenti autorizzati) o `-` (solo anonimi). Flag: `@json` (predefinito), `@text`, `@binary` (i messaggi sono oggetti `Buffer` e vengono inviati come frame binari, anche quando sono compressi) e `@csrf`. Un client che l'autorizzazione rifiuta (non corrisponde a `+` o `-`) viene accettato e poi chiuso con il codice `4001`. `#name` esegue un middleware prima dell'upgrade. Il limite di dimensione è `CONF.$wsmaxsize` kB, a meno che tu non passi `size` in byte o `<NMB` nell'URL. Restituisce la route.\n\nExample: Chat room\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\t\tself.send(message);\n\t});\n}\n```\n\nExample: Utenti autorizzati, messaggi di testo, 1 MB\n```js\nROUTE('+SOCKET /console/ @text <1MB', terminal);\n```\n\nExample: Messaggi binari\n```js\nROUTE('SOCKET /files/ @binary', function($) {\n\t$.on('message', function(client, buffer) {\n\t\tclient.send(buffer); // a binary frame back\n\t});\n});\n```\n\n### CONF.$wsmaxsize\n\nType: `config`\n\nDimensione massima predefinita di un messaggio WebSocket in kB.\n\nReturns: `Number`\n\nPredefinito `256`. Un messaggio più grande chiude il client con il codice `1009`. Una route può impostare la propria dimensione.\n\nExample: file di configurazione\n```js\n$wsmaxsize\t\t: 512\n```\n\n### CONF.$wscompress\n\nType: `config`\n\nConsente la compressione `permessage-deflate`.\n\nReturns: `Boolean`\n\nPredefinito `true`. Quando il browser offre `permessage-deflate`, i messaggi vengono compressi in entrambe le direzioni.\n\nExample: Disattivare la compressione\n```js\n$wscompress\t   : false\n```\n\n### CONF.$wsencodedecode\n\nType: `config`\n\nCodifica e decodifica tutti i messaggi WebSocket con la codifica URI.\n\nReturns: `Boolean`\n\nPredefinito `false`. Con `true`, i messaggi in uscita e i motivi di chiusura passano attraverso `encodeURIComponent()` e quelli in arrivo attraverso `decodeURIComponent()`. L'altra parte deve fare lo stesso.\n\nExample: file di configurazione\n```js\n$wsencodedecode   : true\n```\n\n### CONF.$wsmaxlatency\n\nType: `config`\n\nLatenza massima in ms prima che il controllo del ping chiuda un client.\n\nReturns: `Number`\n\nPredefinito `2000`. Tre volte al minuto (a 15, 30 e 60 secondi di ogni minuto) il framework invia un ping a tutti i client di tutte le route WebSocket e misura `client.latency` dal pong. Prima di ogni ping controlla i client: un client che non ha risposto al ping precedente, o la cui latenza è superiore a `CONF.$wsmaxlatency` (2000 ms), viene chiuso. In questo modo le connessioni morte vengono rimosse senza codice da parte tua.\n\nExample: file di configurazione\n```js\n$wsmaxlatency\t : 5000\n```\n\n### function() { var websocket = this; }\n\nType: `class`\n\nL'oggetto che raggruppa tutti i client di un URL WebSocket.\n\nReturns: `WebSocket`\n\nÈ `this` nell'azione di una route `SOCKET`. Esiste un oggetto per URL: una route dinamica ne ha uno per ogni URL distinto. È un event emitter (`on`, `once`, `emit`, `off`).\n\nExample: Eventi\n```js\nfunction live() {\n\tvar self = this;\n\tself.on('open', function(client) {});\n\tself.on('message', function(client, message) {});\n\tself.on('close', function(client) {});\n}\n```\n\n### websocket.online\n\nType: `property`\n\nIl numero di client connessi.\n\nReturns: `Number`\n\nExample: Conteggio\n```js\nself.on('open', function() {\n\tself.send({ type: 'online', count: self.online });\n});\n```\n\n### websocket.connections\n\nType: `property`\n\nI client connessi come oggetto `{ id: client }`.\n\nReturns: `Object`\n\nExample: Iterare\n```js\nfor (var id in self.connections) {\n\tvar client = self.connections[id];\n}\n```\n\n### websocket.params\n\nType: `property`\n\nI parametri dinamici dell'URL.\n\nReturns: `Object`\n\nRicavato dal primo client dell'URL; tutti i client dell'oggetto condividono gli stessi valori.\n\nExample: Nome della stanza\n```js\nROUTE('SOCKET /room/{name}/', function() {\n\tvar name = this.params.name;\n});\n```\n\n### websocket.url\n\nType: `property`\n\nL'URL del gruppo in minuscolo.\n\nReturns: `String`\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nInvia un messaggio a tutti i client, o ai client scelti da un comparer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  | Il messaggio |\n| `comparer` | `Function` | no |  | `function(client, message, params)` che restituisce un booleano |\n| `replacer` | `Function` | no |  | Un replacer JSON |\n| `params` | `Object` | no |  | Passato al comparer |\n\nReturns: `WebSocket` Lo stesso oggetto\n\nIl messaggio viene serializzato con `JSON.stringify()` una sola volta (per le route `@json` e `@text`); sulle route `@binary` passa un `Buffer`. `comparer(client, message, params)` restituisce `true` per i client che lo ricevono. `replacer` viene passato a `JSON.stringify()`; quando il terzo argomento non è una funzione, viene usato come `params`.\n\nExample: Tutti\n```js\nself.send({ type: 'refresh' });\n```\n\nExample: Solo gli admin\n```js\nself.send({ type: 'alert' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nTrova il primo client per cui `fn(client)` restituisce `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` che restituisce un booleano |\n\nReturns: `Controller` Il client, oppure `undefined`\n\nExample: Per utente\n```js\nvar client = self.find(function(client) {\n\treturn client.user && client.user.id === id;\n});\n```\n\n### websocket.close([code], [message])\n\nType: `method`\n\nChiude tutti i client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | Il codice di chiusura |\n| `message` | `String` | no |  | Il motivo della chiusura |\n\nReturns: `WebSocket`\n\nL'oggetto WebSocket rimane, quindi nuovi client possono connettersi.\n\nExample: Chiudere tutti\n```js\nself.close(4000, 'Maintenance');\n```\n\n### websocket.destroy()\n\nType: `method`\n\nChiude tutti i client e rimuove l'oggetto WebSocket.\n\nEmette `destroy`. Il client successivo che si connette all'URL esegue di nuovo l'azione della route e ottiene un nuovo oggetto.\n\nExample: Distruggere\n```js\nself.destroy();\n```\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nDistrugge l'oggetto 5 secondi dopo che l'ultimo client se ne va.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata prima che l'oggetto venga distrutto |\n\nReturns: `WebSocket`\n\nSe un client si connette in quei 5 secondi, l'oggetto rimane. Prima della distruzione, ogni `callback` viene chiamata con l'oggetto WebSocket come `this`. Chiamalo più volte per aggiungere altre callback.\n\nExample: Fermare un timer\n```js\nvar timer = setInterval(function() {\n\tself.send({ ts: Date.now() });\n}, 1000);\n\nself.autodestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nCifra e decifra tutti i messaggi del gruppo con `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` |  |\n\nSenza argomenti o con `true` attiva la cifratura; `false` la disattiva. Non fa nulla finché `CONF.secret_encryption` è vuoto.\n\nExample: Attivare\n```js\nfunction secure() {\n\tthis.encrypt();\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nInvia un ping a tutti i client.\n\nReturns: `WebSocket`\n\nOgni pong imposta `client.latency`. Il framework lo chiama tre volte al minuto (a 15, 30 e 60 secondi di ogni minuto) per tutti gli oggetti WebSocket.\n\nExample: Ping immediato\n```js\nself.ping();\n```\n\n### websocket.error(err)\n\nType: `method`\n\nRegistra un errore con l'URL del WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  |  |\n\nUna stringa viene convertita in un `Error`. L'errore finisce nel log degli errori del framework.\n\nExample: Log\n```js\nself.on('message', function(client, message) {\n\tif (!message.type)\n\t\tself.error('Missing type');\n});\n```\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` | `Controller` | yes |  | Il nuovo client |\n\nExample: Benvenuto\n```js\nself.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message, size) {})\n\nType: `event`\n\nUn client ha inviato un messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  |  |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nSulle route `@json` `message` è un oggetto analizzato; sulle route `@text` una stringa; sulle route `@binary` un `Buffer`. `size` è la dimensione in byte.\n\nExample: Echo\n```js\nself.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` | `Controller` | yes |  |  |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n`code` e `message` sono il codice e il motivo di chiusura inviati dal client, oppure quelli passati a `close()` quando è il server a chiudere la connessione.\n\nExample: Uscita\n```js\nself.on('close', function(client) {\n\tself.send({ type: 'left', id: client.id });\n});\n```\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nUn errore sul socket di un client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nI reset della connessione e le pipe interrotte non lo emettono; chiudono il client. Un errore durante la compressione o la decompressione di un messaggio (`permessage-deflate`) viene emesso qui insieme al client.\n\nExample: Log\n```js\nself.on('error', function(err, client) {\n\tself.error(err);\n});\n```\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nL'oggetto WebSocket sta per essere distrutto.\n\nEmesso da `destroy()` e `autodestroy()`.\n\nExample: Pulizia\n```js\nself.on('destroy', function() {\n\tclearInterval(timer);\n});\n```\n\n### ON('websocket_end', function(websocket, client) {})\n\nType: `event`\n\nUn qualsiasi client di una qualsiasi route WebSocket si è disconnesso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `websocket` | `WebSocket` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nExample: Log globale\n```js\nON('websocket_end', function(websocket, client) {\n\tconsole.log(websocket.url, client.ip);\n});\n```\n\n### client\n\nType: `class`\n\nUn client connesso a una route WebSocket.\n\nI client arrivano negli eventi dell'oggetto WebSocket. Hanno i dati della richiesta di upgrade: `id`, `ip`, `user`, `query`, `params`, `headers`, `url`, `uri`, `ua`, `mobile`, `robot`, `referrer`, `host`, `address`, `protocol`, `language`, e `req` e `socket`. Puoi aggiungere le tue proprietà. `F.extend('controller', name, fn)` aggiunge un metodo ai controller HTTP e WebSocket.\n\nExample: Dati propri\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n### client.id\n\nType: `property`\n\nUn identificatore univoco del client.\n\nReturns: `String`\n\nAnche `client.ID`. È la chiave in `websocket.connections`.\n\nExample: Inviare l'id\n```js\nclient.send({ id: client.id });\n```\n\n### client.user\n\nType: `property`\n\nL'utente restituito dal delegate di autorizzazione.\n\nReturns: `Object`\n\n`undefined` per i client anonimi.\n\nExample: Saluto\n```js\nself.on('open', function(client) {\n\tclient.send({ name: client.user ? client.user.name : 'guest' });\n});\n```\n\n### client.ip\n\nType: `property`\n\nL'indirizzo IP del client.\n\nReturns: `String`\n\nIl primo indirizzo di `X-Forwarded-For` dietro un proxy.\n\n### client.query\n\nType: `property`\n\nLa query string dell'URL WebSocket come oggetto.\n\nReturns: `Object`\n\nUsala per passare dati che i browser non possono inviare negli header, come un token.\n\nExample: Token\n```js\n// new WebSocket('ws://localhost:8000/live/?token=abc')\nvar token = client.query.token;\n```\n\n### client.params\n\nType: `property`\n\nI parametri dinamici dell'URL.\n\nReturns: `Object`\n\n### client.headers\n\nType: `property`\n\nGli header della richiesta di upgrade, con i nomi in minuscolo.\n\nReturns: `Object`\n\n### client.latency\n\nType: `property`\n\nIl tempo in ms tra l'ultimo ping e il suo pong.\n\nReturns: `Number`\n\nOgni ping lo azzera a `null`; il pong imposta il tempo misurato.\n\nExample: Mostrare la latenza\n```js\nself.on('message', function(client) {\n\tclient.send({ latency: client.latency });\n});\n```\n\n### client.address\n\nType: `property`\n\nL'URL completo a cui il client si è connesso.\n\nReturns: `String`\n\nIl protocollo (`http` o `https`), l'host e il percorso con la query string.\n\n### client.ua\n\nType: `property`\n\nUn nome breve del browser e del sistema, ricavato da `User-Agent`.\n\nReturns: `String`\n\n`client.mobile` e `client.robot` sono `true` per i dispositivi mobili e i crawler.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nInvia un messaggio a un client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Invia una stringa senza serializzazione JSON (route `@text`) |\n| `replacer` | `Function` | no |  | Un replacer JSON |\n\nSulle route `@json` gli oggetti vengono serializzati con `JSON.stringify()` e gli altri valori vengono inviati come stringhe. Sulle route `@text` il messaggio viene serializzato in JSON a meno che `raw` sia `true`, che invia la stringa così com'è. Sulle route `@binary` passa un `Buffer`. `replacer` viene passato a `JSON.stringify()`.\n\nExample: JSON\n```js\nclient.send({ type: 'pong' });\n```\n\nExample: Testo semplice\n```js\nclient.send('OK', true);\n```\n\n### client.close([code], [message])\n\nType: `method`\n\nChiude la connessione con il client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | Il codice di chiusura |\n| `message` | `String` | no |  | Il motivo della chiusura |\n\nIl frame di chiusura viene inviato dopo 1 secondo e poi il socket viene distrutto.\n\nExample: Rifiutare\n```js\nself.on('open', function(client) {\n\tif (!client.query.token)\n\t\tclient.close(4003, 'Forbidden');\n});\n```\n\n### client.ping()\n\nType: `method`\n\nInvia un ping al client.\n\nReturns: `Controller` Lo stesso client\n\nIl pong imposta `client.latency`.\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 |  |  |\n\nReturns: `String` Il valore decodificato, oppure una stringa vuota\n\nExample: Sessione\n```js\nvar sid = client.cookie('sid');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nRestituisce il protocollo e l'host della richiesta, con un percorso opzionale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Aggiunto dopo l'host |\n\nReturns: `String` Per esempio `https://example.com/path/`\n\n### client.destroy()\n\nType: `method`\n\nDistrugge subito il socket, senza frame di chiusura.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nCrea un client WebSocket che si connette a un altro server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(client)` |\n\nReturns: `WebSocketClient` Il client\n\n`callback(client)` viene chiamata subito con il nuovo client. Imposta le opzioni, gli header e gli eventi, poi chiama `client.connect()`.\n\nExample: Connessione\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('ws://127.0.0.1:8000/live/');\n});\n```\n\n### wsclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nApre la connessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  |  |\n| `protocol` | `String` | no |  |  |\n| `origin` | `String` | no |  |  |\n\n`url` è un indirizzo `ws://` o `wss://`, oppure un oggetto `{ socket: '/path/to/unix.socket', path: '/live/' }` per un socket Unix. `protocol` viene inviato come `Sec-WebSocket-Protocol` e `origin` come `Sec-WebSocket-Origin`. I redirect HTTP (301, 302) vengono seguiti. Il client emette `open` quando il server accetta la connessione.\n\nExample: Sicuro\n```js\nclient.connect('wss://example.com/live/');\n```\n\n### wsclient.options\n\nType: `property`\n\nLe opzioni del client.\n\nReturns: `Object`\n\nImpostale prima di `connect()`: `type` (`json`, `text` o `binary`, predefinito `json`), `compress` (`true`), `reconnect` (ritardo in ms dopo la chiusura della connessione, `3000`, `0` la disattiva), `reconnectserver` (`true` si riconnette anche quando la connessione non può essere aperta o il server risponde con un errore HTTP), `masking` (`false`), `encodedecode` (`false`), `encrypt` (una chiave per cifrare i messaggi), `size` (dimensione massima in byte di un messaggio decompresso, `0` nessun limite), `rejectunauthorized` (`false`), `timeout` (ritardo del keep-alive TCP in ms, `30000`, `0` lo disattiva), e `key`, `cert`, `dhparam` per TLS.\n\nExample: Client di testo\n```js\nvar client = WEBSOCKETCLIENT();\nclient.options.type = 'text';\nclient.options.reconnect = 0;\nclient.connect('ws://127.0.0.1:8000/terminal/');\n```\n\n### wsclient.headers\n\nType: `property`\n\nIntestazioni aggiuntive della richiesta di upgrade.\n\nReturns: `Object`\n\nImpostali prima di `connect()`.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\n```\n\n### wsclient.send(message, [raw], [replacer])\n\nType: `method`\n\nInvia un messaggio al server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Invia una stringa JSON già pronta |\n| `replacer` | `Function` | no |  | Un replacer JSON |\n\nReturns: `Boolean` `true` quando il messaggio è stato scritto\n\nCon il tipo `json`, il messaggio viene serializzato con `JSON.stringify()` a meno che `raw` sia `true`. Con il tipo `text`, gli oggetti vengono serializzati e gli altri valori vengono inviati come stringhe. Con il tipo `binary`, un valore che non è un Buffer viene convertito in un `Buffer`. Restituisce `false` quando la connessione è chiusa.\n\nExample: Invio\n```js\nclient.send({ type: 'subscribe', channel: 'news' });\n```\n\n### wsclient.sendcustom(type, message)\n\nType: `method`\n\nInvia un messaggio come testo o binario, indipendentemente da `options.type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `binary` o `text` |\n| `message` | `String|Buffer` | yes |  |  |\n\nReturns: `Boolean` `true` quando il messaggio è stato scritto\n\n`type` è `'binary'` o qualsiasi altro valore per il testo.\n\nExample: Binario\n```js\nclient.sendcustom('binary', Buffer.from([1, 2, 3]));\n```\n\n### wsclient.close([code], [message])\n\nType: `method`\n\nChiude la connessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` |  |\n| `message` | `String|Boolean` | no |  | Il motivo della chiusura, oppure `true` |\n\nReturns: `WebSocketClient`\n\nInterrompe la riconnessione. Passa `true` come `message` per chiudere la connessione e mantenere la riconnessione automatica.\n\nExample: Chiusura\n```js\nclient.close();\n```\n\n### wsclient.destroy()\n\nType: `method`\n\nDistrugge la connessione e interrompe la riconnessione.\n\nEmette `destroy`.\n\nExample: Distruggere\n```js\nclient.destroy();\n```\n\n### wsclient.ping([timeout])\n\nType: `method`\n\nInvia un ping e attende il pong.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | no | `3000` | Tempo in ms |\n\nReturns: `WebSocketClient`\n\nIl pong imposta `client.latency`. Senza un pong entro `timeout` ms il client emette `error` con un errore `Timeout`, chiude la connessione e si riconnette quando `options.reconnect` è impostato.\n\nExample: Controllo continuo\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### wsclient.api(schema, [data], [callback], [timeout])\n\nType: `method`\n\nInvia una richiesta API sulla connessione e attende la risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  |  |\n| `data` | `Object` | no |  |  |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `5000` | Tempo in ms |\n\nReturns: `Promise` Quando non viene passata una callback\n\nInvia `{ TYPE: 'api', callbackid, data: { schema, data } }` e si risolve quando il server risponde con un messaggio `{ TYPE: 'api', callbackid, data }` (con `error: true`, `data` è l'errore). Senza una risposta entro `timeout` ms (5000) la callback riceve `408`. Senza callback restituisce una promise.\n\nExample: Promise\n```js\nvar response = await client.api('users_list', { page: 1 });\n```\n\n### wsclient.on('message', function(message, size) {})\n\nType: `event`\n\nUn messaggio dal server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nUn oggetto analizzato con il tipo `json`, una stringa con `text`, un `Buffer` con `binary`.\n\n### wsclient.on('open', function() {})\n\nType: `event`\n\nLa connessione è aperta.\n\nEmesso anche dopo ogni riconnessione.\n\n### wsclient.on('close', function(code, message) {})\n\nType: `event`\n\nLa connessione è stata chiusa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n### wsclient.on('error', function(err) {})\n\nType: `event`\n\nUn errore di connessione, una risposta HTTP inattesa, una chiave del server non valida o un timeout del ping.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n\nExample: Log\n```js\nclient.on('error', function(err) {\n\tconsole.log('WS error', err.message);\n});\n```\n\n### route.remove()\n\nType: `method` · Since: `0.0.17`\n\nRimuove una route registrata con `ROUTE()`.\n\nPer una route `SOCKET` rimuove la route e distrugge tutti i suoi oggetti WebSocket, quindi ogni client collegato viene disconnesso.\n\nExample: Rimuovere\n```js\nvar route = ROUTE('SOCKET /live/', live);\nroute.remove();\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET ...')","signature":"ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"CONF.$wsmaxsize","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"CONF.$wscompress","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"CONF.$wsencodedecode","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"CONF.$wsmaxlatency","since":"","deprecated":false},{"type":"class","name":"WebSocket","signature":"function() { var websocket = this; }","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.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","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.close()","signature":"websocket.close([code], [message])","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.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.error()","signature":"websocket.error(err)","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, size) {})","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":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(websocket, client) {})","since":"","deprecated":false},{"type":"class","name":"Controller (WebSocket client)","signature":"client","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.ip","signature":"client.ip","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.params","signature":"client.params","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":"property","name":"client.address","signature":"client.address","since":"","deprecated":false},{"type":"property","name":"client.ua","signature":"client.ua","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([code], [message])","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","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":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"method","name":"wsclient.connect()","signature":"wsclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"property","name":"wsclient.options","signature":"wsclient.options","since":"","deprecated":false},{"type":"property","name":"wsclient.headers","signature":"wsclient.headers","since":"","deprecated":false},{"type":"method","name":"wsclient.send()","signature":"wsclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"wsclient.sendcustom()","signature":"wsclient.sendcustom(type, message)","since":"","deprecated":false},{"type":"method","name":"wsclient.close()","signature":"wsclient.close([code], [message])","since":"","deprecated":false},{"type":"method","name":"wsclient.destroy()","signature":"wsclient.destroy()","since":"","deprecated":false},{"type":"method","name":"wsclient.ping()","signature":"wsclient.ping([timeout])","since":"","deprecated":false},{"type":"method","name":"wsclient.api()","signature":"wsclient.api(schema, [data], [callback], [timeout])","since":"","deprecated":false},{"type":"event","name":"wsclient.on('message')","signature":"wsclient.on('message', function(message, size) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('open')","signature":"wsclient.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('close')","signature":"wsclient.on('close', function(code, message) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('error')","signature":"wsclient.on('error', function(err) {})","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmEM7Gc61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/websockets/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"WebSockety","summary":"Objekt WebSocket, jeho klienti, WEBSOCKETCLIENT() a konfigurácia WebSocket.","markdown":"---\ntitle: WebSockety\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/websockets/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# WebSockety\n\n> Objekt WebSocket, jeho klienti, WEBSOCKETCLIENT() a konfigurácia WebSocket.\n\nMetódy, vlastnosti a udalosti WebSocket trás (`ROUTE('SOCKET ...')`), objektu WebSocket, jeho klientov, `WEBSOCKETCLIENT()` a konfiguračných kľúčov `$ws*`. Úvod s príkladmi nájdeš v návode [WebSockets](../../guides/websockets/).\n\n## API\n\n### ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])\n\nType: `method`\n\nZaregistruje WebSocket trasu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Metóda, cesta, príznaky a middleware |\n| `action` | `Function` | yes |  | Volá sa s objektom WebSocket |\n| `size` | `Number` | no | `CONF.$wsmaxsize * 1024` | Max. veľkosť jednej správy v bajtoch |\n\nReturns: `Route` Zaregistrovaná trasa\n\nAkcia sa spustí raz pre každú URL, keď sa pripojí prvý klient, s objektom WebSocket ako `this` aj ako prvým argumentom. Pred metódu daj `+` (iba autorizovaní používatelia) alebo `-` (iba anonymní). Príznaky: `@json` (predvolený), `@text`, `@binary` (správy sú objekty `Buffer` a odchádzajú ako binárne rámce, aj keď sú komprimované) a `@csrf`. Klient, ktorého autorizácia odmietne (nezodpovedá `+` ani `-`), sa prijme a potom sa zatvorí s kódom `4001`. `#name` spustí middleware pred upgradom. Limit veľkosti je `CONF.$wsmaxsize` kB, pokiaľ neodovzdáš `size` v bajtoch alebo `<NMB` v URL. Vráti trasu.\n\nExample: Chatovacia miestnosť\n```js\nexports.install = function() {\n\tROUTE('SOCKET /room/{name}/', room);\n};\n\nfunction room() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\t\tself.send(message);\n\t});\n}\n```\n\nExample: Autorizovaní používatelia, textové správy, 1 MB\n```js\nROUTE('+SOCKET /console/ @text <1MB', terminal);\n```\n\nExample: Binárne správy\n```js\nROUTE('SOCKET /files/ @binary', function($) {\n\t$.on('message', function(client, buffer) {\n\t\tclient.send(buffer); // a binary frame back\n\t});\n});\n```\n\n### CONF.$wsmaxsize\n\nType: `config`\n\nPredvolená max. veľkosť WebSocket správy v kB.\n\nReturns: `Number`\n\nPredvolene `256`. Väčšia správa zatvorí klienta s kódom `1009`. Trasa môže nastaviť vlastnú veľkosť.\n\nExample: konfiguračný súbor\n```js\n$wsmaxsize\t\t: 512\n```\n\n### CONF.$wscompress\n\nType: `config`\n\nPovolí kompresiu `permessage-deflate`.\n\nReturns: `Boolean`\n\nPredvolene `true`. Keď prehliadač ponúkne `permessage-deflate`, správy sa komprimujú v oboch smeroch.\n\nExample: Vypnutie kompresie\n```js\n$wscompress\t   : false\n```\n\n### CONF.$wsencodedecode\n\nType: `config`\n\nKóduje a dekóduje všetky WebSocket správy URI kódovaním.\n\nReturns: `Boolean`\n\nPredvolene `false`. S `true` prechádzajú odchádzajúce správy a dôvody zatvorenia cez `encodeURIComponent()` a prichádzajúce cez `decodeURIComponent()`. Druhá strana musí robiť to isté.\n\nExample: konfiguračný súbor\n```js\n$wsencodedecode   : true\n```\n\n### CONF.$wsmaxlatency\n\nType: `config`\n\nMax. latencia v ms, kým kontrola pingu zatvorí klienta.\n\nReturns: `Number`\n\nPredvolene `2000`. Trikrát za minútu (15, 30 a 60 sekúnd do každej minúty) framework pingne všetkých klientov všetkých WebSocket trás a z pongu zmeria `client.latency`. Pred každým pingom skontroluje klientov: klient, ktorý neodpovedal na predchádzajúci ping alebo ktorého latencia je vyššia ako `CONF.$wsmaxlatency` (2000 ms), sa zatvorí. Takto sa mŕtve spojenia odstránia bez tvojho kódu.\n\nExample: konfiguračný súbor\n```js\n$wsmaxlatency\t : 5000\n```\n\n### function() { var websocket = this; }\n\nType: `class`\n\nObjekt, ktorý zoskupuje všetkých klientov jednej WebSocket URL.\n\nReturns: `WebSocket`\n\nJe to `this` v akcii trasy `SOCKET`. Pre každú URL existuje jeden objekt: dynamická trasa má jeden pre každú odlišnú URL. Je to event emitter (`on`, `once`, `emit`, `off`).\n\nExample: Udalosti\n```js\nfunction live() {\n\tvar self = this;\n\tself.on('open', function(client) {});\n\tself.on('message', function(client, message) {});\n\tself.on('close', function(client) {});\n}\n```\n\n### websocket.online\n\nType: `property`\n\nPočet pripojených klientov.\n\nReturns: `Number`\n\nExample: Počet\n```js\nself.on('open', function() {\n\tself.send({ type: 'online', count: self.online });\n});\n```\n\n### websocket.connections\n\nType: `property`\n\nPripojení klienti ako objekt `{ id: client }`.\n\nReturns: `Object`\n\nExample: Iterácia\n```js\nfor (var id in self.connections) {\n\tvar client = self.connections[id];\n}\n```\n\n### websocket.params\n\nType: `property`\n\nDynamické parametre URL.\n\nReturns: `Object`\n\nNaplnené z prvého klienta URL; všetci klienti objektu zdieľajú rovnaké hodnoty.\n\nExample: Názov miestnosti\n```js\nROUTE('SOCKET /room/{name}/', function() {\n\tvar name = this.params.name;\n});\n```\n\n### websocket.url\n\nType: `property`\n\nURL skupiny malými písmenami.\n\nReturns: `String`\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nPošle správu všetkým klientom alebo klientom vybraným pomocou comparera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  | Správa |\n| `comparer` | `Function` | no |  | `function(client, message, params)`, ktorá vráti boolean |\n| `replacer` | `Function` | no |  | JSON replacer |\n| `params` | `Object` | no |  | Odovzdá sa compareru |\n\nReturns: `WebSocket` Ten istý objekt\n\nSpráva sa serializuje pomocou `JSON.stringify()` raz (pre trasy `@json` a `@text`); pri trasách `@binary` odovzdaj `Buffer`. `comparer(client, message, params)` vráti `true` pre klientov, ktorí ju dostanú. `replacer` sa odovzdá do `JSON.stringify()`; keď tretí argument nie je funkcia, použije sa ako `params`.\n\nExample: Všetkým\n```js\nself.send({ type: 'refresh' });\n```\n\nExample: Len adminom\n```js\nself.send({ type: 'alert' }, function(client) {\n\treturn client.user && client.user.isadmin;\n});\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nNájde prvého klienta, pre ktorého `fn(client)` vráti `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)`, ktorá vráti boolean |\n\nReturns: `Controller` Klient, alebo `undefined`\n\nExample: Podľa používateľa\n```js\nvar client = self.find(function(client) {\n\treturn client.user && client.user.id === id;\n});\n```\n\n### websocket.close([code], [message])\n\nType: `method`\n\nZatvorí všetkých klientov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | Kód zatvorenia |\n| `message` | `String` | no |  | Dôvod zatvorenia |\n\nReturns: `WebSocket`\n\nObjekt WebSocket zostane, takže sa môžu pripojiť noví klienti.\n\nExample: Zatvorenie všetkých\n```js\nself.close(4000, 'Maintenance');\n```\n\n### websocket.destroy()\n\nType: `method`\n\nZatvorí všetkých klientov a odstráni objekt WebSocket.\n\nVyvolá `destroy`. Ďalší klient, ktorý sa pripojí k URL, znova spustí akciu trasy a dostane nový objekt.\n\nExample: Zničenie\n```js\nself.destroy();\n```\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nZničí objekt 5 sekúnd po odchode posledného klienta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Zavolá sa pred zničením objektu |\n\nReturns: `WebSocket`\n\nAk sa počas týchto 5 sekúnd pripojí klient, objekt zostane. Pred zničením sa zavolá každý `callback` s objektom WebSocket ako `this`. Zavolaj ju viackrát, ak chceš pridať ďalšie callbacky.\n\nExample: Zastavenie časovača\n```js\nvar timer = setInterval(function() {\n\tself.send({ ts: Date.now() });\n}, 1000);\n\nself.autodestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nŠifruje a dešifruje všetky správy skupiny pomocou `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` |  |\n\nBez argumentu alebo s `true` zapne šifrovanie; `false` ho vypne. Kým je `CONF.secret_encryption` prázdne, nerobí nič.\n\nExample: Zapnutie\n```js\nfunction secure() {\n\tthis.encrypt();\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nPingne všetkých klientov.\n\nReturns: `WebSocket`\n\nKaždý pong nastaví `client.latency`. Framework ju volá trikrát za minútu (15, 30 a 60 sekúnd do každej minúty) pre všetky objekty WebSocket.\n\nExample: Ping hneď\n```js\nself.ping();\n```\n\n### websocket.error(err)\n\nType: `method`\n\nZaloguje chybu s URL WebSocketu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  |  |\n\nReťazec sa prevedie na `Error`. Chyba ide do chybového logu frameworku.\n\nExample: Logovanie\n```js\nself.on('message', function(client, message) {\n\tif (!message.type)\n\t\tself.error('Missing type');\n});\n```\n\n### websocket.on('open', function(client) {})\n\nType: `event`\n\nKlient sa pripojil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  | Nový klient |\n\nExample: Privítanie\n```js\nself.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message, size) {})\n\nType: `event`\n\nKlient poslal správu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Controller` | yes |  |  |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nPri trasách `@json` je `message` spracovaný objekt; pri trasách `@text` reťazec; pri trasách `@binary` `Buffer`. `size` je veľkosť v bajtoch.\n\nExample: Echo\n```js\nself.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` | `Controller` | yes |  |  |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n`code` a `message` sú kód a dôvod zatvorenia, ktoré poslal klient, alebo tie, ktoré boli odovzdané do `close()`, keď spojenie zatvára server.\n\nExample: Odchod\n```js\nself.on('close', function(client) {\n\tself.send({ type: 'left', id: client.id });\n});\n```\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nChyba na sockete klienta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nResetované spojenia a prerušené pipe ju nevyvolajú; tie klienta zatvoria. Chyba pri komprimovaní alebo dekomprimovaní správy (`permessage-deflate`) sa vyvolá tu, spolu s klientom.\n\nExample: Logovanie\n```js\nself.on('error', function(err, client) {\n\tself.error(err);\n});\n```\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nObjekt WebSocket sa ničí.\n\nVyvolávajú ju `destroy()` a `autodestroy()`.\n\nExample: Upratovanie\n```js\nself.on('destroy', function() {\n\tclearInterval(timer);\n});\n```\n\n### ON('websocket_end', function(websocket, client) {})\n\nType: `event`\n\nOdpojil sa ktorýkoľvek klient ktorejkoľvek WebSocket trasy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `websocket` | `WebSocket` | yes |  |  |\n| `client` | `Controller` | yes |  |  |\n\nExample: Globálny log\n```js\nON('websocket_end', function(websocket, client) {\n\tconsole.log(websocket.url, client.ip);\n});\n```\n\n### client\n\nType: `class`\n\nJeden pripojený klient WebSocket trasy.\n\nKlienti prichádzajú v udalostiach objektu WebSocket. Majú údaje upgrade požiadavky: `id`, `ip`, `user`, `query`, `params`, `headers`, `url`, `uri`, `ua`, `mobile`, `robot`, `referrer`, `host`, `address`, `protocol`, `language` a `req` a `socket`. Môžeš pridať vlastné vlastnosti. `F.extend('controller', name, fn)` pridá metódu HTTP a WebSocket kontrolérom.\n\nExample: Vlastné dáta\n```js\nself.on('open', function(client) {\n\tclient.nick = client.query.nick || 'guest';\n});\n```\n\n### client.id\n\nType: `property`\n\nJedinečný identifikátor klienta.\n\nReturns: `String`\n\nAj `client.ID`. Je to kľúč v `websocket.connections`.\n\nExample: Odoslanie id\n```js\nclient.send({ id: client.id });\n```\n\n### client.user\n\nType: `property`\n\nPoužívateľ, ktorého vrátil autorizačný delegát.\n\nReturns: `Object`\n\n`undefined` pre anonymných klientov.\n\nExample: Pozdrav\n```js\nself.on('open', function(client) {\n\tclient.send({ name: client.user ? client.user.name : 'guest' });\n});\n```\n\n### client.ip\n\nType: `property`\n\nIP adresa klienta.\n\nReturns: `String`\n\nZa proxy prvá adresa z `X-Forwarded-For`.\n\n### client.query\n\nType: `property`\n\nQuery string WebSocket URL ako objekt.\n\nReturns: `Object`\n\nPouži ho na odovzdanie dát, ktoré prehliadače nemôžu poslať v hlavičkách, napríklad tokenu.\n\nExample: Token\n```js\n// new WebSocket('ws://localhost:8000/live/?token=abc')\nvar token = client.query.token;\n```\n\n### client.params\n\nType: `property`\n\nDynamické parametre URL.\n\nReturns: `Object`\n\n### client.headers\n\nType: `property`\n\nHlavičky upgrade požiadavky s názvami malými písmenami.\n\nReturns: `Object`\n\n### client.latency\n\nType: `property`\n\nČas v ms medzi posledným pingom a jeho pongom.\n\nReturns: `Number`\n\nKaždý ping ho vynuluje na `null`; pong nastaví nameraný čas.\n\nExample: Zobrazenie latencie\n```js\nself.on('message', function(client) {\n\tclient.send({ latency: client.latency });\n});\n```\n\n### client.address\n\nType: `property`\n\nÚplná URL, ku ktorej sa klient pripojil.\n\nReturns: `String`\n\nProtokol (`http` alebo `https`), host a cesta s query stringom.\n\n### client.ua\n\nType: `property`\n\nKrátky názov prehliadača a systému, získaný z `User-Agent`.\n\nReturns: `String`\n\n`client.mobile` a `client.robot` sú `true` pre mobilné zariadenia a crawlery.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nPošle správu jednému klientovi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Poslať reťazec bez JSON serializácie (trasy `@text`) |\n| `replacer` | `Function` | no |  | JSON replacer |\n\nPri trasách `@json` sa objekty serializujú pomocou `JSON.stringify()` a ostatné hodnoty sa posielajú ako reťazce. Pri trasách `@text` sa správa serializuje do JSON, ak `raw` nie je `true`, čo pošle reťazec tak, ako je. Pri trasách `@binary` odovzdaj `Buffer`. `replacer` sa odovzdá do `JSON.stringify()`.\n\nExample: JSON\n```js\nclient.send({ type: 'pong' });\n```\n\nExample: Čistý text\n```js\nclient.send('OK', true);\n```\n\n### client.close([code], [message])\n\nType: `method`\n\nZatvorí spojenie s klientom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` | Kód zatvorenia |\n| `message` | `String` | no |  | Dôvod zatvorenia |\n\nRámec zatvorenia sa pošle po 1 sekunde a potom sa socket zničí.\n\nExample: Odmietnutie\n```js\nself.on('open', function(client) {\n\tif (!client.query.token)\n\t\tclient.close(4003, 'Forbidden');\n});\n```\n\n### client.ping()\n\nType: `method`\n\nPošle klientovi ping.\n\nReturns: `Controller` Ten istý klient\n\nPong nastaví `client.latency`.\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\nReturns: `String` Dekódovaná hodnota, alebo prázdny reťazec\n\nExample: Relácia\n```js\nvar sid = client.cookie('sid');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nVráti protokol a host požiadavky s voliteľnou cestou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Pripojí sa k hostu |\n\nReturns: `String` Napríklad `https://example.com/path/`\n\n### client.destroy()\n\nType: `method`\n\nOkamžite zničí socket bez rámca zatvorenia.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nVytvorí WebSocket klienta, ktorý sa pripojí k inému serveru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(client)` |\n\nReturns: `WebSocketClient` Klient\n\n`callback(client)` sa zavolá hneď s novým klientom. Nastav voľby, 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('ws://127.0.0.1:8000/live/');\n});\n```\n\n### wsclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nOtvorí spojenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  |  |\n| `protocol` | `String` | no |  |  |\n| `origin` | `String` | no |  |  |\n\n`url` je adresa `ws://` alebo `wss://`, alebo objekt `{ socket: '/path/to/unix.socket', path: '/live/' }` pre Unix socket. `protocol` sa pošle ako `Sec-WebSocket-Protocol` a `origin` ako `Sec-WebSocket-Origin`. HTTP presmerovania (301, 302) sa nasledujú. Klient vyvolá `open`, keď server prijme spojenie.\n\nExample: Zabezpečené\n```js\nclient.connect('wss://example.com/live/');\n```\n\n### wsclient.options\n\nType: `property`\n\nVoľby klienta.\n\nReturns: `Object`\n\nNastav ich pred `connect()`: `type` (`json`, `text` alebo `binary`, predvolene `json`), `compress` (`true`), `reconnect` (oneskorenie v ms po zatvorení spojenia, `3000`, `0` ho vypne), `reconnectserver` (`true` sa pripojí znova aj vtedy, keď sa spojenie nedá otvoriť alebo server odpovie HTTP chybou), `masking` (`false`), `encodedecode` (`false`), `encrypt` (kľúč na šifrovanie správ), `size` (max. veľkosť dekomprimovanej správy v bajtoch, `0` bez obmedzenia), `rejectunauthorized` (`false`), `timeout` (oneskorenie TCP keep-alive v ms, `30000`, `0` ho vypne) a `key`, `cert`, `dhparam` pre TLS.\n\nExample: Textový klient\n```js\nvar client = WEBSOCKETCLIENT();\nclient.options.type = 'text';\nclient.options.reconnect = 0;\nclient.connect('ws://127.0.0.1:8000/terminal/');\n```\n\n### wsclient.headers\n\nType: `property`\n\nĎalšie hlavičky upgrade požiadavky.\n\nReturns: `Object`\n\nNastav ich pred `connect()`.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\n```\n\n### wsclient.send(message, [raw], [replacer])\n\nType: `method`\n\nPošle správu serveru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `raw` | `Boolean` | no | `false` | Poslať pripravený JSON reťazec |\n| `replacer` | `Function` | no |  | JSON replacer |\n\nReturns: `Boolean` `true`, keď sa správa zapísala\n\nPri type `json` sa správa serializuje pomocou `JSON.stringify()`, ak `raw` nie je `true`. Pri type `text` sa objekty serializujú a ostatné hodnoty sa posielajú ako reťazce. Pri type `binary` sa hodnota, ktorá nie je Buffer, prevedie na `Buffer`. Vráti `false`, keď je spojenie zatvorené.\n\nExample: Odoslanie\n```js\nclient.send({ type: 'subscribe', channel: 'news' });\n```\n\n### wsclient.sendcustom(type, message)\n\nType: `method`\n\nPošle jednu správu ako text alebo binárne, bez ohľadu na `options.type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `binary` alebo `text` |\n| `message` | `String|Buffer` | yes |  |  |\n\nReturns: `Boolean` `true`, keď sa správa zapísala\n\n`type` je `'binary'` alebo akákoľvek iná hodnota pre text.\n\nExample: Binárne\n```js\nclient.sendcustom('binary', Buffer.from([1, 2, 3]));\n```\n\n### wsclient.close([code], [message])\n\nType: `method`\n\nZatvorí spojenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `1000` |  |\n| `message` | `String|Boolean` | no |  | Dôvod zatvorenia, alebo `true` |\n\nReturns: `WebSocketClient`\n\nZastaví opätovné pripájanie. Odovzdaj `true` ako `message`, ak chceš zatvoriť spojenie a ponechať automatické opätovné pripájanie.\n\nExample: Zatvorenie\n```js\nclient.close();\n```\n\n### wsclient.destroy()\n\nType: `method`\n\nZničí spojenie a zastaví opätovné pripájanie.\n\nVyvolá `destroy`.\n\nExample: Zničenie\n```js\nclient.destroy();\n```\n\n### wsclient.ping([timeout])\n\nType: `method`\n\nPošle ping a čaká na pong.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | no | `3000` | Čas v ms |\n\nReturns: `WebSocketClient`\n\nPong nastaví `client.latency`. Bez pongu do `timeout` ms klient vyvolá `error` s chybou `Timeout`, zatvorí spojenie a pripojí sa znova, keď je nastavené `options.reconnect`.\n\nExample: Priebežná kontrola\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### wsclient.api(schema, [data], [callback], [timeout])\n\nType: `method`\n\nPošle cez spojenie API požiadavku a čaká na odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  |  |\n| `data` | `Object` | no |  |  |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `5000` | Čas v ms |\n\nReturns: `Promise` Keď nie je zadaný callback\n\nPošle `{ TYPE: 'api', callbackid, data: { schema, data } }` a vyrieši sa, keď server odpovie správou `{ TYPE: 'api', callbackid, data }` (s `error: true` je `data` chyba). Bez odpovede do `timeout` ms (5000) dostane callback `408`. Bez callbacku vráti promise.\n\nExample: Promise\n```js\nvar response = await client.api('users_list', { page: 1 });\n```\n\n### wsclient.on('message', function(message, size) {})\n\nType: `event`\n\nSpráva zo servera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object|String|Buffer` | yes |  |  |\n| `size` | `Number` | yes |  |  |\n\nSpracovaný objekt pri type `json`, reťazec pri `text`, `Buffer` pri `binary`.\n\n### wsclient.on('open', function() {})\n\nType: `event`\n\nSpojenie je otvorené.\n\nVyvolá sa aj po každom opätovnom pripojení.\n\n### wsclient.on('close', function(code, message) {})\n\nType: `event`\n\nSpojenie bolo zatvorené.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  |  |\n| `message` | `String` | yes |  |  |\n\n### wsclient.on('error', function(err) {})\n\nType: `event`\n\nChyba spojenia, neočakávaná HTTP odpoveď, neplatný kľúč servera alebo timeout pingu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  |  |\n\nExample: Logovanie\n```js\nclient.on('error', function(err) {\n\tconsole.log('WS error', err.message);\n});\n```\n\n### route.remove()\n\nType: `method` · Since: `0.0.17`\n\nOdstráni trasu registrovanú cez `ROUTE()`.\n\nPri trase `SOCKET` odstráni trasu a zničí všetky jej WebSocket objekty, takže každý pripojený klient sa odpojí.\n\nExample: Odstránenie\n```js\nvar route = ROUTE('SOCKET /live/', live);\nroute.remove();\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET ...')","signature":"ROUTE('SOCKET /url/ [@flags] [#middleware] [<size]', action, [size])","since":"","deprecated":false},{"type":"config","name":"$wsmaxsize","signature":"CONF.$wsmaxsize","since":"","deprecated":false},{"type":"config","name":"$wscompress","signature":"CONF.$wscompress","since":"","deprecated":false},{"type":"config","name":"$wsencodedecode","signature":"CONF.$wsencodedecode","since":"","deprecated":false},{"type":"config","name":"$wsmaxlatency","signature":"CONF.$wsmaxlatency","since":"","deprecated":false},{"type":"class","name":"WebSocket","signature":"function() { var websocket = this; }","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.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","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.close()","signature":"websocket.close([code], [message])","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.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.error()","signature":"websocket.error(err)","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, size) {})","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":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(websocket, client) {})","since":"","deprecated":false},{"type":"class","name":"Controller (WebSocket client)","signature":"client","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.ip","signature":"client.ip","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.params","signature":"client.params","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":"property","name":"client.address","signature":"client.address","since":"","deprecated":false},{"type":"property","name":"client.ua","signature":"client.ua","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([code], [message])","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","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":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"method","name":"wsclient.connect()","signature":"wsclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"property","name":"wsclient.options","signature":"wsclient.options","since":"","deprecated":false},{"type":"property","name":"wsclient.headers","signature":"wsclient.headers","since":"","deprecated":false},{"type":"method","name":"wsclient.send()","signature":"wsclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"wsclient.sendcustom()","signature":"wsclient.sendcustom(type, message)","since":"","deprecated":false},{"type":"method","name":"wsclient.close()","signature":"wsclient.close([code], [message])","since":"","deprecated":false},{"type":"method","name":"wsclient.destroy()","signature":"wsclient.destroy()","since":"","deprecated":false},{"type":"method","name":"wsclient.ping()","signature":"wsclient.ping([timeout])","since":"","deprecated":false},{"type":"method","name":"wsclient.api()","signature":"wsclient.api(schema, [data], [callback], [timeout])","since":"","deprecated":false},{"type":"event","name":"wsclient.on('message')","signature":"wsclient.on('message', function(message, size) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('open')","signature":"wsclient.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('close')","signature":"wsclient.on('close', function(code, message) {})","since":"","deprecated":false},{"type":"event","name":"wsclient.on('error')","signature":"wsclient.on('error', function(err) {})","since":"","deprecated":false},{"type":"method","name":"route.remove()","signature":"route.remove()","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmDe5Xc60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/nosql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"NoSQL database","summary":"NOSQL(name), its query builder methods and the NoSQL engine of DATA.","markdown":"---\ntitle: NoSQL database\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/nosql/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# NoSQL database\n\n> NOSQL(name), its query builder methods and the NoSQL engine of DATA.\n\nMethods of `NOSQL(name)`, the query builder they return (filters, fields, sorting, paging and results), the NoSQL reads of `DATA` and the `$dirdatabases` configuration key. For an introduction with examples read the guide [NoSQL database](../../guides/nosql/).\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nReturns a NoSQL database stored in a text file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the database, or a file path with a slash. |\n\nReturns: `Object` An object with `insert()`, `find()`, `read()`, `update()`, `modify()`, `remove()`, `clear()` and `clean()`.\n\nA plain name uses the file `databases/<name>.nosql`; the directory and the file are created when needed. A name with a slash is used as the file path as it is. Every method of the returned object returns a query builder.\n\nExample: Use a database\n```js\nvar db = NOSQL('users');\ndb.find().where('active', true).callback(console.log);\n```\n\n### NOSQL(name).insert(doc)\n\nType: `method`\n\nAppends a new document.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | The document. |\n\nReturns: `QueryBuilder` Builder; the response is `1`.\n\nAdds the document as a new line at the end of the file. No `id` is generated, so add your own. Keys with the prefixes `+ - * / > <` store the value without the prefix, `!key` stores `true` and `=key` stores the value as it is. The response is `1`.\n\nExample: Insert\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n```\n\n### NOSQL(name).find()\n\nType: `method`\n\nFinds documents.\n\nReturns: `QueryBuilder` Builder; the response is an Array.\n\nReturns all matching documents as an array, or an empty array. Without `sort()` the most recently written documents come first.\n\nExample: Find\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### NOSQL(name).read()\n\nType: `method`\n\nReads one document.\n\nReturns: `QueryBuilder` Builder; the response is an Object or `undefined`.\n\nReturns the first matching document (the most recently written one when you do not sort), or `undefined` when nothing matches. Combine it with `error()` to answer with an error for a missing document.\n\nExample: Read by id\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n```\n\n### NOSQL(name).update(data)\n\nType: `method`\n\nUpdates matching documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Fields to write, optionally with a prefix. |\n\nReturns: `QueryBuilder` Builder; the response is the count of updated documents.\n\nWrites the keys of `data` into every matching document; other fields are kept. Without a filter all documents are updated. Key prefixes: `+key`, `-key`, `*key` and `/key` add, subtract, multiply or divide the field by the number (a missing field counts as `0`), `>key` writes the value only when it is greater than the field and `<key` only when it is smaller (a missing field takes the value), `!key` toggles a boolean, `=key` evaluates a JavaScript expression with `doc`. The response is the number of updated documents.\n\nExample: Update\n```js\nNOSQL('products').update({ '+stock': -1, dtupdated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log(count);\n});\n```\n\nExample: Counters and limits\n```js\nNOSQL('products').update({ '-stock': 1, '*price': 1.1, '>maxorder': 3 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).modify(data)\n\nType: `method`\n\nAlias of `update()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Fields to write, optionally with a prefix. |\n\nReturns: `QueryBuilder` Builder; the response is the count of updated documents.\n\nWrites the keys of `data` into every matching document; other fields are kept. Without a filter all documents are updated. Key prefixes: `+key`, `-key`, `*key` and `/key` add, subtract, multiply or divide the field by the number (a missing field counts as `0`), `>key` writes the value only when it is greater than the field and `<key` only when it is smaller (a missing field takes the value), `!key` toggles a boolean, `=key` evaluates a JavaScript expression with `doc`. The response is the number of updated documents.\n\nExample: Modify\n```js\nNOSQL('users').modify({ '!active': 1 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).remove()\n\nType: `method`\n\nRemoves matching documents.\n\nReturns: `QueryBuilder` Builder; the response is the count of removed documents.\n\nMarks every matching document as removed. Without a filter all documents are removed. The response is the count of removed documents. The lines stay in the file until `clean()`.\n\nExample: Remove old logs\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(console.log);\n```\n\n### NOSQL(name).clear()\n\nType: `method`\n\nDeletes all documents.\n\nReturns: `QueryBuilder` Builder.\n\nDeletes the database file. The next insert creates it again.\n\nExample: Clear\n```js\nNOSQL('cache').clear().callback(function(err) {\n\tconsole.log('empty');\n});\n```\n\n### NOSQL(name).clean()\n\nType: `method`\n\nCompacts the database file.\n\nReturns: `QueryBuilder` Builder.\n\nRewrites the file without the lines of removed documents and of old versions of updated documents. Writes wait until it finishes.\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### builder.where(name, [comparer], value)\n\nType: `method`\n\nCompares a field with a value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `comparer` | `String` | no | `'='` | Comparison operator. |\n| `value` | `Object` | yes |  | Value to compare. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nComparers: `=` (default), `==`, `<>`, `!=`, `>`, `>=`, `<`, `<=`. `=` compares loosely, so `'5'` matches `5`. The name can be nested (`address.city`). With only one argument it works as `query()`.\n\nExample: Where\n```js\nNOSQL('users').find().where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.query(code)\n\nType: `method`\n\nAdds a raw JavaScript condition.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | JavaScript expression. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nThe condition can use `doc`, the document. A condition that contains `require` or `global` matches nothing. Never build it from user input.\n\nExample: Raw condition\n```js\nNOSQL('orders').find().query('doc.items.length > 2').callback(console.log);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nAdds `where(key, value)` for every key of an object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Fields and values. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nEach key of the object must equal its value.\n\nExample: Equal\n```js\nNOSQL('users').find().equal({ role: 'admin', active: true }).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFilters by the `id` field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | Identifier or identifiers. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nA value adds `where('id', id)`, an array adds `in('id', id)`.\n\nExample: By id\n```js\nNOSQL('users').read().id($.params.id).callback($);\n```\n\n### builder.userid(id)\n\nType: `method`\n\nFilters by the `userid` field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array|Object` | yes |  | Identifier, identifiers, a user object or `$`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nAccepts a string, an array of identifiers, an object with `id`, or `$` (it then uses `$.user.id`).\n\nExample: Documents of the user\n```js\nNOSQL('notes').find().userid($).callback($);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nThe field is one of the values.\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\nA single value is wrapped in an array. When the field is an array, a document matches if any of its items is one of the values. With `key`, the values are taken from that property of the objects in `value`.\n\nExample: In\n```js\nNOSQL('products').find().in('tags', ['usb', 'wireless']).callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nThe field is none of the values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `value` | `Array` | yes |  | Forbidden 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 the same arguments.\n\nExample: Not in\n```js\nNOSQL('users').find().notin('role', ['guest', 'banned']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nThe field is between two values, inclusive.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `a` | `Number|Date` | yes |  | Lower bound. |\n| `b` | `Number|Date` | yes |  | Upper bound. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nWorks with numbers, strings and dates.\n\nExample: Between\n```js\nNOSQL('orders').find().between('price', 10, 100).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nSearches text in a field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `value` | `String` | yes |  | Text to find. |\n| `where` | `String` | no |  | `'beg'` or `'end'`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nCase-insensitive. By default the text can be anywhere; `'beg'` matches the beginning and `'end'` the end. An array field matches when any item matches. `%` characters in the text are removed.\n\nExample: Search\n```js\nNOSQL('users').find().search('email', '@example.com', 'end').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nThe field has a value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nMatches a truthy value, or an array with at least one item.\n\nExample: Contains\n```js\nNOSQL('users').find().contains('photo').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nThe field has no value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nMatches a missing or falsy value, or an empty array.\n\nExample: Empty\n```js\nNOSQL('products').find().empty('tags').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nJoins a group of filters with OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(builder) that adds the filters. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nThe function receives the builder (also as `this`); filters added inside it form one group where any of them can match.\n\nExample: Or\n```js\nNOSQL('users').find().or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('owner', true);\n}).callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nCompares the full year of a Date field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Date field. |\n| `comparer` | `String` | no | `'='` | Comparison operator. |\n| `value` | `Number` | yes |  | Value to compare. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nDocuments where the field is not a `Date` do not match. Comparers are the same as in `where()`.\n\nExample: Year\n```js\nNOSQL('orders').find().year('dtcreated', 2024).callback(console.log);\n```\n\n### builder.month(name, [comparer], value)\n\nType: `method`\n\nCompares the month (1-12) of a Date field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Date field. |\n| `comparer` | `String` | no | `'='` | Comparison operator. |\n| `value` | `Number` | yes |  | Value to compare. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nDocuments where the field is not a `Date` do not match. Comparers are the same as in `where()`.\n\nExample: Month\n```js\nNOSQL('orders').find().month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.day(name, [comparer], value)\n\nType: `method`\n\nCompares the day of the month (1-31) of a Date field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Date field. |\n| `comparer` | `String` | no | `'='` | Comparison operator. |\n| `value` | `Number` | yes |  | Value to compare. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nDocuments where the field is not a `Date` do not match. Comparers are the same as in `where()`.\n\nExample: Day\n```js\nNOSQL('orders').find().day('dtcreated', 1).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 |  | Comma-separated field names. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nA comma-separated list of fields to return, or of fields with `-` to leave out (`'-password,-token'`).\n\nExample: Fields\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nSorts the result.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `desc` | `Boolean|String` | no | `false` | `true` or `'desc'` for descending order. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nCall it more times to sort by more fields. Nested fields work (`address.city`). Without sorting the most recently written documents come first.\n\nExample: Sort\n```js\nNOSQL('articles').find().sort('dtcreated', true).sort('title').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nLimits the number of documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximum count. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nReading stops as soon as enough documents are found, unless the result is sorted.\n\nExample: Take\n```js\nNOSQL('logs').find().take(50).callback(console.log);\n```\n\n### builder.limit(count)\n\nType: `method`\n\nAlias of `take()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximum count. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nLimits the number of documents.\n\nExample: Limit\n```js\nNOSQL('logs').find().limit(50).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nSkips documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Count to skip. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nSkips the first `count` matching documents.\n\nExample: Skip\n```js\nNOSQL('logs').find().skip(100).take(50).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nReturns only one document.\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nSets `take(1)` and the response is an object (or `undefined`) instead of an array.\n\nExample: First\n```js\nNOSQL('users').find().where('email', email).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSets skip from a page number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Page number from 1. |\n| `limit` | `Number` | no |  | Documents per page. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nPage numbers start at 1. `limit` sets `take()`; without it the current `take()` value is used.\n\nExample: Page\n```js\nNOSQL('articles').find().sort('dtcreated', true).page(2, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSets skip and take from untrusted values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Page number from 1. |\n| `limit` | `Number|String` | yes |  | Documents per page. |\n| `maxlimit` | `Number` | no |  | Maximum and default limit. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nAccepts strings (for example from the query string). A page below 1 becomes 1; `limit` is capped at `maxlimit`, and a missing limit uses `maxlimit`.\n\nExample: Paginate in an action\n```js\nNOSQL('articles').find().sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nPrints the compiled operation.\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nLogs the file, the operation and the compiled filter to the console with the prefix `-- NoSQL -->`.\n\nExample: Debug\n```js\nNOSQL('users').find().where('age', '>', 18).debug().callback(console.log);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nReads the result with a callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), or `$`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\n`fn(err, response)` is called when the operation finishes. Pass `$` in an action to send the response or the error to the client. `pipe()` is an alias.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items) {\n\tif (err)\n\t\treturn console.error(err);\n\tconsole.log(items.length);\n});\n```\n\n### builder.pipe(fn)\n\nType: `method`\n\nAlias of `callback()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), or `$`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\n`fn(err, response)`, or `$`.\n\nExample: Pipe\n```js\nNOSQL('users').find().pipe($);\n```\n\n### builder.promise([$])\n\nType: `method`\n\nReturns the result as a Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Options of an action. |\n\nReturns: `Promise` Resolves with the response.\n\nThe Promise resolves with the response. On an error it rejects, or, when `$` is given, the error is sent to `$.invalid()`.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nCalls a function with the response, errors go to `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Options of an action. |\n| `fn` | `Function` | yes |  | function(response, param). |\n| `param` | `Object` | no |  | A value passed to `fn`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nOn success `fn(response, param)` is called; an error is sent to `$.invalid()`.\n\nExample: Done\n```js\nNOSQL('users').read().id(id).error('Not found').done($, function(user) {\n\t$.callback({ name: user.name });\n});\n```\n\n### builder.data(fn)\n\nType: `method`\n\nCalls a function only with a response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(response). |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\n`fn(response)` is called only when there is no error. It can be combined with `callback()`.\n\nExample: Data\n```js\nNOSQL('users').find().data(function(items) {\n\tconsole.log(items);\n});\n```\n\n### builder.fail(fn)\n\nType: `method`\n\nCalls a function only with an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(err). |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\n`fn(err)` is called only when the operation fails.\n\nExample: Fail\n```js\nNOSQL('users').read().id(id).error('Not found').fail(function(err) {\n\tconsole.log(err);\n});\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nTurns an empty result into an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | Error message. |\n| `reverse` | `Boolean` | no | `false` | Fail when the result is not empty. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nThe operation fails with `message` when the response is empty: `undefined`, an empty array, or `0` updated or removed documents. With `reverse` it fails when the response is not empty, for example to stop a duplicate. `err()` is an alias.\n\nExample: Not found and duplicate\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n\nNOSQL('users').read().where('email', email).error('E-mail is already used', true).callback(function(err) {\n\t// err when the e-mail exists\n});\n```\n\n### DATA.count('nosql/' + name)\n\nType: `method`\n\nCounts matching documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Database name with the `nosql/` prefix. |\n\nReturns: `QueryBuilder` Builder; the response is `{ count }`.\n\nUses the NoSQL engine through the global query builder. The response is an object `{ count: Number }`.\n\nExample: Count\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### DATA.check('nosql/' + name)\n\nType: `method`\n\nChecks if a document exists.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Database name with the `nosql/` prefix. |\n\nReturns: `QueryBuilder` Builder; the response is a Boolean.\n\nStops at the first matching document. The response is `true` or `false`.\n\nExample: Check\n```js\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\tconsole.log(exists);\n});\n```\n\n### DATA.scalar('nosql/' + name, type, key, [key2])\n\nType: `method`\n\nComputes a sum, minimum, maximum, count or groups.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Database name with the `nosql/` prefix. |\n| `type` | `String` | yes |  | `'sum'`, `'min'`, `'max'`, `'avg'`, `'count'` or `'group'`. |\n| `key` | `String` | no | `'*'` | Field to compute or to group by. `'*'` (the default) counts each document as `1`. |\n| `key2` | `String` | no |  | Field to sum per group (only with `'group'`). |\n\nReturns: `QueryBuilder` Builder; the response is `{ value }` or an Array of groups.\n\nWith `type` `'sum'`, `'min'`, `'max'`, `'avg'` or `'count'` the response is `{ value }` for the field `key` (documents without the field are skipped; `min` and `max` work with dates too). `avg` is the sum divided by the count, or `null` when no document matches. Without `key` (or with `'*'`) every matching document counts as `1`, so `DATA.scalar('nosql/orders', 'count')` counts the documents. With `'group'` the response is an array of `{ <key>: value, value: count }`; with `key2` the values of `key2` are summed per group instead of counted.\n\nExample: Sum\n```js\nDATA.scalar('nosql/orders', 'sum', 'price').where('paid', true).callback(function(err, response) {\n\tconsole.log(response.value);\n});\n```\n\nExample: Group\n```js\nDATA.scalar('nosql/orders', 'group', 'status').callback(function(err, groups) {\n\t// [{ status: 'paid', value: 12 }, { status: 'new', value: 3 }]\n});\n```\n\nExample: Average and count\n```js\nDATA.scalar('nosql/orders', 'avg', 'price').callback(function(err, response) {\n\tconsole.log(response.value); // the average price\n});\n\nDATA.scalar('nosql/orders', 'count').where('paid', true).callback(console.log);\n```\n\n### $dirdatabases : String\n\nType: `config`\n\nDirectory of the database files.\n\nReturns: `String`\n\nThe directory where `NOSQL()` keeps its `.nosql` files. The default is `databases` in the root of the application.\n\nExample: config\n```text\n$dirdatabases : /var/data/myapp/\n```\n","entries":[{"type":"method","name":"NOSQL(name)","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"nosql.insert(doc)","signature":"NOSQL(name).insert(doc)","since":"","deprecated":false},{"type":"method","name":"nosql.find()","signature":"NOSQL(name).find()","since":"","deprecated":false},{"type":"method","name":"nosql.read()","signature":"NOSQL(name).read()","since":"","deprecated":false},{"type":"method","name":"nosql.update(data)","signature":"NOSQL(name).update(data)","since":"","deprecated":false},{"type":"method","name":"nosql.modify(data)","signature":"NOSQL(name).modify(data)","since":"","deprecated":false},{"type":"method","name":"nosql.remove()","signature":"NOSQL(name).remove()","since":"","deprecated":false},{"type":"method","name":"nosql.clear()","signature":"NOSQL(name).clear()","since":"","deprecated":false},{"type":"method","name":"nosql.clean()","signature":"NOSQL(name).clean()","since":"","deprecated":false},{"type":"method","name":"builder.where(name, [comparer], value)","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query(code)","signature":"builder.query(code)","since":"","deprecated":false},{"type":"method","name":"builder.equal(obj)","signature":"builder.equal(obj)","since":"","deprecated":false},{"type":"method","name":"builder.id(id)","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.userid(id)","signature":"builder.userid(id)","since":"","deprecated":false},{"type":"method","name":"builder.in(name, value, [key])","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin(name, value, [key])","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between(name, a, b)","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search(name, value, [where])","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains(name)","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty(name)","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.or(fn)","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.year(name, [comparer], value)","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.month(name, [comparer], value)","signature":"builder.month(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.day(name, [comparer], value)","signature":"builder.day(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.fields(fields)","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort(name, [desc])","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take(count)","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.limit(count)","signature":"builder.limit(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip(count)","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page(page, [limit])","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate(page, limit, [maxlimit])","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback(fn)","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.pipe(fn)","signature":"builder.pipe(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise([$])","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.done($, fn, [param])","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.data(fn)","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.fail(fn)","signature":"builder.fail(fn)","since":"","deprecated":false},{"type":"method","name":"builder.error(message, [reverse])","signature":"builder.error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"DATA.count('nosql/name')","signature":"DATA.count('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.check('nosql/name')","signature":"DATA.check('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.scalar('nosql/name', type, key, [key2])","signature":"DATA.scalar('nosql/' + name, type, key, [key2])","since":"","deprecated":false},{"type":"config","name":"$dirdatabases","signature":"$dirdatabases : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmDe5Xc60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/nosql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"NoSQL-Datenbank","summary":"NOSQL(name), die Methoden seines Query Builders und die NoSQL-Engine von DATA.","markdown":"---\ntitle: NoSQL-Datenbank\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/nosql/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# NoSQL-Datenbank\n\n> NOSQL(name), die Methoden seines Query Builders und die NoSQL-Engine von DATA.\n\nMethoden von `NOSQL(name)`, der Query Builder, den sie zurückgeben (Filter, Felder, Sortierung, Paginierung und Ergebnisse), die NoSQL-Lesevorgänge von `DATA` und der Konfigurationsschlüssel `$dirdatabases`. Eine Einführung mit Beispielen findest du im Leitfaden [NoSQL-Datenbank](../../guides/nosql/).\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nGibt eine NoSQL-Datenbank zurück, die in einer Textdatei gespeichert ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Datenbank oder ein Dateipfad mit Schrägstrich. |\n\nReturns: `Object` Ein Objekt mit `insert()`, `find()`, `read()`, `update()`, `modify()`, `remove()`, `clear()` und `clean()`.\n\nEin einfacher Name verwendet die Datei `databases/<name>.nosql`; das Verzeichnis und die Datei werden bei Bedarf erstellt. Ein Name mit Schrägstrich wird unverändert als Dateipfad verwendet. Jede Methode des zurückgegebenen Objekts gibt einen Query Builder zurück.\n\nExample: Eine Datenbank verwenden\n```js\nvar db = NOSQL('users');\ndb.find().where('active', true).callback(console.log);\n```\n\n### NOSQL(name).insert(doc)\n\nType: `method`\n\nHängt ein neues Dokument an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Das Dokument. |\n\nReturns: `QueryBuilder` Builder; die Antwort ist `1`.\n\nFügt das Dokument als neue Zeile am Ende der Datei hinzu. Es wird keine `id` erzeugt, füge also deine eigene hinzu. Schlüssel mit den Präfixen `+ - * / > <` speichern den Wert ohne das Präfix, `!key` speichert `true` und `=key` speichert den Wert unverändert. Die Antwort ist `1`.\n\nExample: Einfügen\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n```\n\n### NOSQL(name).find()\n\nType: `method`\n\nFindet Dokumente.\n\nReturns: `QueryBuilder` Builder; die Antwort ist ein Array.\n\nGibt alle passenden Dokumente als Array zurück oder ein leeres Array. Ohne `sort()` kommen die zuletzt geschriebenen Dokumente zuerst.\n\nExample: Finden\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### NOSQL(name).read()\n\nType: `method`\n\nLiest ein Dokument.\n\nReturns: `QueryBuilder` Builder; die Antwort ist ein Objekt oder `undefined`.\n\nGibt das erste passende Dokument zurück (das zuletzt geschriebene, wenn du nicht sortierst) oder `undefined`, wenn nichts passt. Kombiniere es mit `error()`, um bei einem fehlenden Dokument mit einem Fehler zu antworten.\n\nExample: Nach ID lesen\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n```\n\n### NOSQL(name).update(data)\n\nType: `method`\n\nAktualisiert passende Dokumente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Zu schreibende Felder, optional mit einem Präfix. |\n\nReturns: `QueryBuilder` Builder; die Antwort ist die Anzahl der aktualisierten Dokumente.\n\nSchreibt die Schlüssel von `data` in jedes passende Dokument; andere Felder bleiben erhalten. Ohne Filter werden alle Dokumente aktualisiert. Präfixe für Schlüssel: `+key`, `-key`, `*key` und `/key` addieren, subtrahieren, multiplizieren oder dividieren das Feld mit der Zahl (ein fehlendes Feld zählt als `0`), `>key` schreibt den Wert nur, wenn er größer als das Feld ist, und `<key` nur, wenn er kleiner ist (ein fehlendes Feld übernimmt den Wert), `!key` schaltet einen Boolean um, `=key` wertet einen JavaScript-Ausdruck mit `doc` aus. Die Antwort ist die Anzahl der aktualisierten Dokumente.\n\nExample: Aktualisieren\n```js\nNOSQL('products').update({ '+stock': -1, dtupdated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log(count);\n});\n```\n\nExample: Zähler und Grenzwerte\n```js\nNOSQL('products').update({ '-stock': 1, '*price': 1.1, '>maxorder': 3 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).modify(data)\n\nType: `method`\n\nAlias von `update()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Zu schreibende Felder, optional mit einem Präfix. |\n\nReturns: `QueryBuilder` Builder; die Antwort ist die Anzahl der aktualisierten Dokumente.\n\nSchreibt die Schlüssel von `data` in jedes passende Dokument; andere Felder bleiben erhalten. Ohne Filter werden alle Dokumente aktualisiert. Präfixe für Schlüssel: `+key`, `-key`, `*key` und `/key` addieren, subtrahieren, multiplizieren oder dividieren das Feld mit der Zahl (ein fehlendes Feld zählt als `0`), `>key` schreibt den Wert nur, wenn er größer als das Feld ist, und `<key` nur, wenn er kleiner ist (ein fehlendes Feld übernimmt den Wert), `!key` schaltet einen Boolean um, `=key` wertet einen JavaScript-Ausdruck mit `doc` aus. Die Antwort ist die Anzahl der aktualisierten Dokumente.\n\nExample: Modify\n```js\nNOSQL('users').modify({ '!active': 1 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).remove()\n\nType: `method`\n\nEntfernt passende Dokumente.\n\nReturns: `QueryBuilder` Builder; die Antwort ist die Anzahl der entfernten Dokumente.\n\nMarkiert jedes passende Dokument als entfernt. Ohne Filter werden alle Dokumente entfernt. Die Antwort ist die Anzahl der entfernten Dokumente. Die Zeilen bleiben bis zu `clean()` in der Datei.\n\nExample: Alte Logs entfernen\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(console.log);\n```\n\n### NOSQL(name).clear()\n\nType: `method`\n\nLöscht alle Dokumente.\n\nReturns: `QueryBuilder` Builder.\n\nLöscht die Datenbankdatei. Das nächste Einfügen erstellt sie erneut.\n\nExample: Leeren\n```js\nNOSQL('cache').clear().callback(function(err) {\n\tconsole.log('empty');\n});\n```\n\n### NOSQL(name).clean()\n\nType: `method`\n\nKomprimiert die Datenbankdatei.\n\nReturns: `QueryBuilder` Builder.\n\nSchreibt die Datei ohne die Zeilen entfernter Dokumente und alter Versionen aktualisierter Dokumente neu. Schreibvorgänge warten, bis es fertig ist.\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### builder.where(name, [comparer], value)\n\nType: `method`\n\nVergleicht ein Feld mit einem Wert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Feldname. |\n| `comparer` | `String` | no | `'='` | Vergleichsoperator. |\n| `value` | `Object` | yes |  | Zu vergleichender Wert. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nVergleichsoperatoren: `=` (Standard), `==`, `<>`, `!=`, `>`, `>=`, `<`, `<=`. `=` vergleicht lose, sodass `'5'` zu `5` passt. Der Name kann verschachtelt sein (`address.city`). Mit nur einem Argument funktioniert es wie `query()`.\n\nExample: Where\n```js\nNOSQL('users').find().where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.query(code)\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. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nDie Bedingung kann `doc` verwenden, das Dokument. Eine Bedingung, die `require` oder `global` enthält, passt zu nichts. Erstelle sie niemals aus Benutzereingaben.\n\nExample: Rohe Bedingung\n```js\nNOSQL('orders').find().query('doc.items.length > 2').callback(console.log);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nFügt `where(key, value)` für jeden Schlüssel eines Objekts hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Felder und Werte. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nJeder Schlüssel des Objekts muss seinem Wert entsprechen.\n\nExample: Equal\n```js\nNOSQL('users').find().equal({ role: 'admin', active: true }).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltert nach dem Feld `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | Kennung oder Kennungen. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nEin Wert fügt `where('id', id)` hinzu, ein Array fügt `in('id', id)` hinzu.\n\nExample: Nach ID\n```js\nNOSQL('users').read().id($.params.id).callback($);\n```\n\n### builder.userid(id)\n\nType: `method`\n\nFiltert nach dem Feld `userid`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array|Object` | yes |  | Kennung, Kennungen, ein Benutzerobjekt oder `$`. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nAkzeptiert einen String, ein Array von Kennungen, ein Objekt mit `id` oder `$` (dann wird `$.user.id` verwendet).\n\nExample: Dokumente des Benutzers\n```js\nNOSQL('notes').find().userid($).callback($);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nDas Feld ist einer der Werte.\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\nEin einzelner Wert wird in ein Array verpackt. Ist das Feld ein Array, passt ein Dokument, wenn eines seiner Elemente einer der Werte ist. Mit `key` werden die Werte aus dieser Eigenschaft der Objekte in `value` gelesen.\n\nExample: In\n```js\nNOSQL('products').find().in('tags', ['usb', 'wireless']).callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nDas Feld ist keiner der Werte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Feldname. |\n| `value` | `Array` | yes |  | Verbotene 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 denselben Argumenten.\n\nExample: Not in\n```js\nNOSQL('users').find().notin('role', ['guest', 'banned']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nDas Feld liegt zwischen zwei Werten, einschließlich.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Feldname. |\n| `a` | `Number|Date` | yes |  | Untere Grenze. |\n| `b` | `Number|Date` | yes |  | Obere Grenze. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nFunktioniert mit Zahlen, Strings und Datumswerten.\n\nExample: Between\n```js\nNOSQL('orders').find().between('price', 10, 100).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nSucht Text in einem Feld.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Feldname. |\n| `value` | `String` | yes |  | Zu suchender Text. |\n| `where` | `String` | no |  | `'beg'` oder `'end'`. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nOhne Beachtung der Groß-/Kleinschreibung. Standardmäßig kann der Text überall stehen; `'beg'` passt auf den Anfang und `'end'` auf das Ende. Ein Array-Feld passt, wenn irgendein Element passt. `%`-Zeichen im Text werden entfernt.\n\nExample: Suchen\n```js\nNOSQL('users').find().search('email', '@example.com', 'end').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nDas Feld hat einen Wert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nPasst auf einen Truthy-Wert oder ein Array mit mindestens einem Element.\n\nExample: Contains\n```js\nNOSQL('users').find().contains('photo').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nDas Feld hat keinen Wert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nPasst auf einen fehlenden oder Falsy-Wert oder ein leeres Array.\n\nExample: Empty\n```js\nNOSQL('products').find().empty('tags').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nVerbindet eine Gruppe von Filtern mit OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(builder), die die Filter hinzufügt. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nDie Funktion erhält den Builder (auch als `this`); die darin hinzugefügten Filter bilden eine Gruppe, in der jeder von ihnen passen kann.\n\nExample: Or\n```js\nNOSQL('users').find().or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('owner', true);\n}).callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nVergleicht das vollständige Jahr eines Date-Felds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Datumsfeld. |\n| `comparer` | `String` | no | `'='` | Vergleichsoperator. |\n| `value` | `Number` | yes |  | Zu vergleichender Wert. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nDokumente, bei denen das Feld kein `Date` ist, passen nicht. Die Vergleichsoperatoren sind dieselben wie bei `where()`.\n\nExample: Jahr\n```js\nNOSQL('orders').find().year('dtcreated', 2024).callback(console.log);\n```\n\n### builder.month(name, [comparer], value)\n\nType: `method`\n\nVergleicht den Monat (1-12) eines Date-Felds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Datumsfeld. |\n| `comparer` | `String` | no | `'='` | Vergleichsoperator. |\n| `value` | `Number` | yes |  | Zu vergleichender Wert. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nDokumente, bei denen das Feld kein `Date` ist, passen nicht. Die Vergleichsoperatoren sind dieselben wie bei `where()`.\n\nExample: Monat\n```js\nNOSQL('orders').find().month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.day(name, [comparer], value)\n\nType: `method`\n\nVergleicht den Tag des Monats (1-31) eines Date-Felds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Datumsfeld. |\n| `comparer` | `String` | no | `'='` | Vergleichsoperator. |\n| `value` | `Number` | yes |  | Zu vergleichender Wert. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nDokumente, bei denen das Feld kein `Date` ist, passen nicht. Die Vergleichsoperatoren sind dieselben wie bei `where()`.\n\nExample: Tag\n```js\nNOSQL('orders').find().day('dtcreated', 1).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 |  | Kommagetrennte Feldnamen. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nEine kommagetrennte Liste der zurückzugebenden Felder oder der mit `-` auszulassenden Felder (`'-password,-token'`).\n\nExample: Fields\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nSortiert das Ergebnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Feldname. |\n| `desc` | `Boolean|String` | no | `false` | `true` oder `'desc'` für absteigende Reihenfolge. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nRufe es mehrmals auf, um nach weiteren Feldern zu sortieren. Verschachtelte Felder funktionieren (`address.city`). Ohne Sortierung kommen die zuletzt geschriebenen Dokumente zuerst.\n\nExample: Sortieren\n```js\nNOSQL('articles').find().sort('dtcreated', true).sort('title').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nBegrenzt die Anzahl der Dokumente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximale Anzahl. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nDas Lesen stoppt, sobald genug Dokumente gefunden sind, außer das Ergebnis wird sortiert.\n\nExample: Take\n```js\nNOSQL('logs').find().take(50).callback(console.log);\n```\n\n### builder.limit(count)\n\nType: `method`\n\nAlias von `take()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximale Anzahl. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nBegrenzt die Anzahl der Dokumente.\n\nExample: Limit\n```js\nNOSQL('logs').find().limit(50).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nÜberspringt 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\nÜberspringt die ersten `count` passenden Dokumente.\n\nExample: Skip\n```js\nNOSQL('logs').find().skip(100).take(50).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nGibt nur ein Dokument zurück.\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nSetzt `take(1)`, und die Antwort ist ein Objekt (oder `undefined`) statt eines Arrays.\n\nExample: First\n```js\nNOSQL('users').find().where('email', email).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSetzt skip aus einer Seitenzahl.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Seitenzahl ab 1. |\n| `limit` | `Number` | no |  | Dokumente pro Seite. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nSeitenzahlen beginnen bei 1. `limit` setzt `take()`; ohne es wird der aktuelle Wert von `take()` verwendet.\n\nExample: Seite\n```js\nNOSQL('articles').find().sort('dtcreated', true).page(2, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSetzt skip und take aus nicht vertrauenswürdigen Werten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Seitenzahl ab 1. |\n| `limit` | `Number|String` | yes |  | Dokumente pro Seite. |\n| `maxlimit` | `Number` | no |  | Maximales und Standardlimit. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nAkzeptiert Strings (zum Beispiel aus dem Query String). Eine Seite unter 1 wird zu 1; `limit` wird auf `maxlimit` begrenzt, und ein fehlendes Limit verwendet `maxlimit`.\n\nExample: Paginierung in einer Aktion\n```js\nNOSQL('articles').find().sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nGibt die kompilierte Operation aus.\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nProtokolliert die Datei, die Operation und den kompilierten Filter mit dem Präfix `-- NoSQL -->` in der Konsole.\n\nExample: Debug\n```js\nNOSQL('users').find().where('age', '>', 18).debug().callback(console.log);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nLiest das Ergebnis mit einem Callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response) oder `$`. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\n`fn(err, response)` wird aufgerufen, wenn die Operation beendet ist. Übergib in einer Aktion `$`, um die Antwort oder den Fehler an den Client zu senden. `pipe()` ist ein Alias.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items) {\n\tif (err)\n\t\treturn console.error(err);\n\tconsole.log(items.length);\n});\n```\n\n### builder.pipe(fn)\n\nType: `method`\n\nAlias von `callback()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response) oder `$`. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\n`fn(err, response)` oder `$`.\n\nExample: Pipe\n```js\nNOSQL('users').find().pipe($);\n```\n\n### builder.promise([$])\n\nType: `method`\n\nGibt das Ergebnis als Promise zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Optionen einer Aktion. |\n\nReturns: `Promise` Wird mit der Antwort aufgelöst.\n\nDas Promise wird mit der Antwort erfüllt. Bei einem Fehler wird es abgelehnt, oder, wenn `$` angegeben ist, wird der Fehler an `$.invalid()` gesendet.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nRuft eine Funktion mit der Antwort auf, Fehler gehen an `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Optionen einer Aktion. |\n| `fn` | `Function` | yes |  | function(response, param). |\n| `param` | `Object` | no |  | Ein Wert, der an `fn` übergeben wird. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nBei Erfolg wird `fn(response, param)` aufgerufen; ein Fehler wird an `$.invalid()` gesendet.\n\nExample: Done\n```js\nNOSQL('users').read().id(id).error('Not found').done($, function(user) {\n\t$.callback({ name: user.name });\n});\n```\n\n### builder.data(fn)\n\nType: `method`\n\nRuft eine Funktion nur mit einer Antwort auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(response). |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\n`fn(response)` wird nur aufgerufen, wenn kein Fehler auftritt. Es kann mit `callback()` kombiniert werden.\n\nExample: Data\n```js\nNOSQL('users').find().data(function(items) {\n\tconsole.log(items);\n});\n```\n\n### builder.fail(fn)\n\nType: `method`\n\nRuft eine Funktion nur bei einem Fehler auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(err). |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\n`fn(err)` wird nur aufgerufen, wenn die Operation fehlschlägt.\n\nExample: Fail\n```js\nNOSQL('users').read().id(id).error('Not found').fail(function(err) {\n\tconsole.log(err);\n});\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nMacht aus einem leeren Ergebnis einen Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | Fehlermeldung. |\n| `reverse` | `Boolean` | no | `false` | Fehlschlagen, wenn das Ergebnis nicht leer ist. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nDie Operation schlägt mit `message` fehl, wenn die Antwort leer ist: `undefined`, ein leeres Array oder `0` aktualisierte oder entfernte Dokumente. Mit `reverse` schlägt sie fehl, wenn die Antwort nicht leer ist, zum Beispiel um ein Duplikat zu verhindern. `err()` ist ein Alias.\n\nExample: Nicht gefunden und Duplikat\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n\nNOSQL('users').read().where('email', email).error('E-mail is already used', true).callback(function(err) {\n\t// err when the e-mail exists\n});\n```\n\n### DATA.count('nosql/' + name)\n\nType: `method`\n\nZählt passende Dokumente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Datenbankname mit dem Präfix `nosql/`. |\n\nReturns: `QueryBuilder` Builder; die Antwort ist `{ count }`.\n\nVerwendet die NoSQL-Engine über den globalen Query Builder. Die Antwort ist ein Objekt `{ count: Number }`.\n\nExample: Zählen\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### DATA.check('nosql/' + name)\n\nType: `method`\n\nPrüft, ob ein Dokument existiert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Datenbankname mit dem Präfix `nosql/`. |\n\nReturns: `QueryBuilder` Builder; die Antwort ist ein Boolean.\n\nStoppt beim ersten passenden Dokument. Die Antwort ist `true` oder `false`.\n\nExample: Prüfen\n```js\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\tconsole.log(exists);\n});\n```\n\n### DATA.scalar('nosql/' + name, type, key, [key2])\n\nType: `method`\n\nBerechnet eine Summe, ein Minimum, ein Maximum, eine Anzahl oder Gruppen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Datenbank mit dem Präfix `nosql/`. |\n| `type` | `String` | yes |  | `'sum'`, `'min'`, `'max'`, `'avg'`, `'count'` oder `'group'`. |\n| `key` | `String` | no | `'*'` | Feld, das berechnet oder nach dem gruppiert wird. `'*'` (der Standard) zählt jedes Dokument als `1`. |\n| `key2` | `String` | no |  | Feld, das pro Gruppe summiert wird (nur mit `'group'`). |\n\nReturns: `QueryBuilder` Builder; die Antwort ist `{ value }` oder ein Array von Gruppen.\n\nMit `type` `'sum'`, `'min'`, `'max'`, `'avg'` oder `'count'` ist die Antwort `{ value }` für das Feld `key` (Dokumente ohne das Feld werden übersprungen; `min` und `max` funktionieren auch mit Datumswerten). `avg` ist die Summe geteilt durch die Anzahl, oder `null`, wenn kein Dokument passt. Ohne `key` (oder mit `'*'`) zählt jedes passende Dokument als `1`, sodass `DATA.scalar('nosql/orders', 'count')` die Dokumente zählt. Mit `'group'` ist die Antwort ein Array von `{ <key>: value, value: count }`; mit `key2` werden die Werte von `key2` pro Gruppe summiert statt gezählt.\n\nExample: Summe\n```js\nDATA.scalar('nosql/orders', 'sum', 'price').where('paid', true).callback(function(err, response) {\n\tconsole.log(response.value);\n});\n```\n\nExample: Gruppe\n```js\nDATA.scalar('nosql/orders', 'group', 'status').callback(function(err, groups) {\n\t// [{ status: 'paid', value: 12 }, { status: 'new', value: 3 }]\n});\n```\n\nExample: Durchschnitt und Anzahl\n```js\nDATA.scalar('nosql/orders', 'avg', 'price').callback(function(err, response) {\n\tconsole.log(response.value); // the average price\n});\n\nDATA.scalar('nosql/orders', 'count').where('paid', true).callback(console.log);\n```\n\n### $dirdatabases : String\n\nType: `config`\n\nVerzeichnis der Datenbankdateien.\n\nReturns: `String`\n\nDas Verzeichnis, in dem `NOSQL()` seine `.nosql`-Dateien ablegt. Der Standard ist `databases` im Stammverzeichnis der Anwendung.\n\nExample: config\n```text\n$dirdatabases : /var/data/myapp/\n```\n","entries":[{"type":"method","name":"NOSQL(name)","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"nosql.insert(doc)","signature":"NOSQL(name).insert(doc)","since":"","deprecated":false},{"type":"method","name":"nosql.find()","signature":"NOSQL(name).find()","since":"","deprecated":false},{"type":"method","name":"nosql.read()","signature":"NOSQL(name).read()","since":"","deprecated":false},{"type":"method","name":"nosql.update(data)","signature":"NOSQL(name).update(data)","since":"","deprecated":false},{"type":"method","name":"nosql.modify(data)","signature":"NOSQL(name).modify(data)","since":"","deprecated":false},{"type":"method","name":"nosql.remove()","signature":"NOSQL(name).remove()","since":"","deprecated":false},{"type":"method","name":"nosql.clear()","signature":"NOSQL(name).clear()","since":"","deprecated":false},{"type":"method","name":"nosql.clean()","signature":"NOSQL(name).clean()","since":"","deprecated":false},{"type":"method","name":"builder.where(name, [comparer], value)","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query(code)","signature":"builder.query(code)","since":"","deprecated":false},{"type":"method","name":"builder.equal(obj)","signature":"builder.equal(obj)","since":"","deprecated":false},{"type":"method","name":"builder.id(id)","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.userid(id)","signature":"builder.userid(id)","since":"","deprecated":false},{"type":"method","name":"builder.in(name, value, [key])","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin(name, value, [key])","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between(name, a, b)","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search(name, value, [where])","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains(name)","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty(name)","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.or(fn)","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.year(name, [comparer], value)","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.month(name, [comparer], value)","signature":"builder.month(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.day(name, [comparer], value)","signature":"builder.day(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.fields(fields)","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort(name, [desc])","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take(count)","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.limit(count)","signature":"builder.limit(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip(count)","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page(page, [limit])","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate(page, limit, [maxlimit])","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback(fn)","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.pipe(fn)","signature":"builder.pipe(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise([$])","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.done($, fn, [param])","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.data(fn)","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.fail(fn)","signature":"builder.fail(fn)","since":"","deprecated":false},{"type":"method","name":"builder.error(message, [reverse])","signature":"builder.error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"DATA.count('nosql/name')","signature":"DATA.count('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.check('nosql/name')","signature":"DATA.check('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.scalar('nosql/name', type, key, [key2])","signature":"DATA.scalar('nosql/' + name, type, key, [key2])","since":"","deprecated":false},{"type":"config","name":"$dirdatabases","signature":"$dirdatabases : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmDe5Xc60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/nosql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Base de datos NoSQL","summary":"NOSQL(name), los métodos de su query builder y el motor NoSQL de DATA.","markdown":"---\ntitle: Base de datos NoSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/nosql/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# Base de datos NoSQL\n\n> NOSQL(name), los métodos de su query builder y el motor NoSQL de DATA.\n\nMétodos de `NOSQL(name)`, el query builder que devuelven (filtros, campos, ordenación, paginación y resultados), las lecturas NoSQL de `DATA` y la clave de configuración `$dirdatabases`. Para una introducción con ejemplos lee la guía [Base de datos NoSQL](../../guides/nosql/).\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nDevuelve una base de datos NoSQL guardada en un archivo de texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la base de datos, o una ruta de archivo con barra. |\n\nReturns: `Object` Un objeto con `insert()`, `find()`, `read()`, `update()`, `modify()`, `remove()`, `clear()` y `clean()`.\n\nUn nombre simple usa el archivo `databases/<name>.nosql`; el directorio y el archivo se crean cuando hacen falta. Un nombre con barra se usa tal cual como ruta del archivo. Cada método del objeto devuelto devuelve un query builder.\n\nExample: Usar una base de datos\n```js\nvar db = NOSQL('users');\ndb.find().where('active', true).callback(console.log);\n```\n\n### NOSQL(name).insert(doc)\n\nType: `method`\n\nAñade un documento nuevo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | El documento. |\n\nReturns: `QueryBuilder` Builder; la respuesta es `1`.\n\nAñade el documento como una línea nueva al final del archivo. No se genera ningún `id`, así que añade el tuyo. Las claves con los prefijos `+ - * / > <` guardan el valor sin el prefijo, `!key` guarda `true` y `=key` guarda el valor tal cual. La respuesta es `1`.\n\nExample: Insertar\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n```\n\n### NOSQL(name).find()\n\nType: `method`\n\nBusca documentos.\n\nReturns: `QueryBuilder` Builder; la respuesta es un Array.\n\nDevuelve todos los documentos que coinciden como un array, o un array vacío. Sin `sort()` los documentos escritos más recientemente van primero.\n\nExample: Buscar\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### NOSQL(name).read()\n\nType: `method`\n\nLee un documento.\n\nReturns: `QueryBuilder` Builder; la respuesta es un Object o `undefined`.\n\nDevuelve el primer documento que coincide (el escrito más recientemente cuando no ordenas), o `undefined` cuando no coincide nada. Combínalo con `error()` para responder con un error cuando falta un documento.\n\nExample: Leer por id\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n```\n\n### NOSQL(name).update(data)\n\nType: `method`\n\nActualiza los documentos que coinciden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Campos que se escriben, opcionalmente con un prefijo. |\n\nReturns: `QueryBuilder` Builder; la respuesta es el número de documentos actualizados.\n\nEscribe las claves de `data` en cada documento que coincide; los demás campos se conservan. Sin filtro se actualizan todos los documentos. Prefijos de clave: `+key`, `-key`, `*key` y `/key` suman, restan, multiplican o dividen el campo por el número (un campo que falta cuenta como `0`), `>key` escribe el valor solo cuando es mayor que el campo y `<key` solo cuando es menor (un campo que falta recibe el valor), `!key` invierte un booleano, `=key` evalúa una expresión JavaScript con `doc`. La respuesta es el número de documentos actualizados.\n\nExample: Actualizar\n```js\nNOSQL('products').update({ '+stock': -1, dtupdated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log(count);\n});\n```\n\nExample: Contadores y límites\n```js\nNOSQL('products').update({ '-stock': 1, '*price': 1.1, '>maxorder': 3 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).modify(data)\n\nType: `method`\n\nAlias de `update()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Campos que se escriben, opcionalmente con un prefijo. |\n\nReturns: `QueryBuilder` Builder; la respuesta es el número de documentos actualizados.\n\nEscribe las claves de `data` en cada documento que coincide; los demás campos se conservan. Sin filtro se actualizan todos los documentos. Prefijos de clave: `+key`, `-key`, `*key` y `/key` suman, restan, multiplican o dividen el campo por el número (un campo que falta cuenta como `0`), `>key` escribe el valor solo cuando es mayor que el campo y `<key` solo cuando es menor (un campo que falta recibe el valor), `!key` invierte un booleano, `=key` evalúa una expresión JavaScript con `doc`. La respuesta es el número de documentos actualizados.\n\nExample: Modify\n```js\nNOSQL('users').modify({ '!active': 1 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).remove()\n\nType: `method`\n\nElimina los documentos que coinciden.\n\nReturns: `QueryBuilder` Builder; la respuesta es el número de documentos eliminados.\n\nMarca como eliminado cada documento que coincide. Sin filtro se eliminan todos los documentos. La respuesta es el número de documentos eliminados. Las líneas se quedan en el archivo hasta `clean()`.\n\nExample: Eliminar logs antiguos\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(console.log);\n```\n\n### NOSQL(name).clear()\n\nType: `method`\n\nBorra todos los documentos.\n\nReturns: `QueryBuilder` Builder.\n\nBorra el archivo de la base de datos. La siguiente inserción lo vuelve a crear.\n\nExample: Clear\n```js\nNOSQL('cache').clear().callback(function(err) {\n\tconsole.log('empty');\n});\n```\n\n### NOSQL(name).clean()\n\nType: `method`\n\nCompacta el archivo de la base de datos.\n\nReturns: `QueryBuilder` Builder.\n\nReescribe el archivo sin las líneas de los documentos eliminados ni de las versiones antiguas de los documentos actualizados. Las escrituras esperan hasta que termina.\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### builder.where(name, [comparer], value)\n\nType: `method`\n\nCompara un campo con un valor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `comparer` | `String` | no | `'='` | Operador de comparación. |\n| `value` | `Object` | yes |  | Valor que se compara. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nComparadores: `=` (por defecto), `==`, `<>`, `!=`, `>`, `>=`, `<`, `<=`. `=` compara de forma flexible, así que `'5'` coincide con `5`. El nombre puede estar anidado (`address.city`). Con un solo argumento funciona como `query()`.\n\nExample: Where\n```js\nNOSQL('users').find().where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.query(code)\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. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLa condición puede usar `doc`, el documento. Una condición que contiene `require` o `global` no coincide con nada. Nunca la construyas a partir de datos del usuario.\n\nExample: Condición en bruto\n```js\nNOSQL('orders').find().query('doc.items.length > 2').callback(console.log);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nAñade `where(key, value)` para cada clave de un objeto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Campos y valores. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nCada clave del objeto debe ser igual a su valor.\n\nExample: Equal\n```js\nNOSQL('users').find().equal({ role: 'admin', active: true }).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltra por el campo `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | Identificador o identificadores. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nUn valor añade `where('id', id)`, un array añade `in('id', id)`.\n\nExample: Por id\n```js\nNOSQL('users').read().id($.params.id).callback($);\n```\n\n### builder.userid(id)\n\nType: `method`\n\nFiltra por el campo `userid`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array|Object` | yes |  | Identificador, identificadores, un objeto de usuario o `$`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nAcepta una cadena, un array de identificadores, un objeto con `id`, o `$` (entonces usa `$.user.id`).\n\nExample: Documentos del usuario\n```js\nNOSQL('notes').find().userid($).callback($);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nEl campo es uno de los valores.\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\nUn valor único se envuelve en un array. Cuando el campo es un array, un documento coincide si alguno de sus elementos es uno de los valores. Con `key`, los valores se toman de esa propiedad de los objetos de `value`.\n\nExample: In\n```js\nNOSQL('products').find().in('tags', ['usb', 'wireless']).callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nEl campo no es ninguno de los valores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `value` | `Array` | yes |  | Valores prohibidos. |\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 los mismos argumentos.\n\nExample: Not in\n```js\nNOSQL('users').find().notin('role', ['guest', 'banned']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nEl campo está entre dos valores, ambos incluidos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `a` | `Number|Date` | yes |  | Límite inferior. |\n| `b` | `Number|Date` | yes |  | Límite superior. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nFunciona con números, cadenas y fechas.\n\nExample: Between\n```js\nNOSQL('orders').find().between('price', 10, 100).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nBusca texto en un campo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `value` | `String` | yes |  | Texto que se busca. |\n| `where` | `String` | no |  | `'beg'` o `'end'`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nSin distinguir mayúsculas y minúsculas. Por defecto el texto puede estar en cualquier sitio; `'beg'` coincide con el principio y `'end'` con el final. Un campo array coincide cuando coincide cualquiera de sus elementos. Los caracteres `%` del texto se eliminan.\n\nExample: Búsqueda\n```js\nNOSQL('users').find().search('email', '@example.com', 'end').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nEl campo tiene un valor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nCoincide con un valor truthy, o con un array con al menos un elemento.\n\nExample: Contains\n```js\nNOSQL('users').find().contains('photo').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nEl campo no tiene valor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nCoincide con un valor que falta o es falsy, o con un array vacío.\n\nExample: Empty\n```js\nNOSQL('products').find().empty('tags').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nUne un grupo de filtros con OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(builder) que añade los filtros. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLa función recibe el builder (también como `this`); los filtros añadidos dentro forman un grupo en el que puede coincidir cualquiera de ellos.\n\nExample: Or\n```js\nNOSQL('users').find().or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('owner', true);\n}).callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nCompara el año completo de un campo Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Campo de fecha. |\n| `comparer` | `String` | no | `'='` | Operador de comparación. |\n| `value` | `Number` | yes |  | Valor que se compara. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLos documentos en los que el campo no es un `Date` no coinciden. Los comparadores son los mismos que en `where()`.\n\nExample: Año\n```js\nNOSQL('orders').find().year('dtcreated', 2024).callback(console.log);\n```\n\n### builder.month(name, [comparer], value)\n\nType: `method`\n\nCompara el mes (1-12) de un campo Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Campo de fecha. |\n| `comparer` | `String` | no | `'='` | Operador de comparación. |\n| `value` | `Number` | yes |  | Valor que se compara. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLos documentos en los que el campo no es un `Date` no coinciden. Los comparadores son los mismos que en `where()`.\n\nExample: Mes\n```js\nNOSQL('orders').find().month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.day(name, [comparer], value)\n\nType: `method`\n\nCompara el día del mes (1-31) de un campo Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Campo de fecha. |\n| `comparer` | `String` | no | `'='` | Operador de comparación. |\n| `value` | `Number` | yes |  | Valor que se compara. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLos documentos en los que el campo no es un `Date` no coinciden. Los comparadores son los mismos que en `where()`.\n\nExample: Día\n```js\nNOSQL('orders').find().day('dtcreated', 1).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 |  | Nombres de campos separados por comas. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nUna lista separada por comas de los campos que se devuelven, o de campos con `-` que se dejan fuera (`'-password,-token'`).\n\nExample: Fields\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nOrdena el resultado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `desc` | `Boolean|String` | no | `false` | `true` o `'desc'` para orden descendente. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLlámalo más veces para ordenar por más campos. Los campos anidados funcionan (`address.city`). Sin ordenación los documentos escritos más recientemente van primero.\n\nExample: Ordenar\n```js\nNOSQL('articles').find().sort('dtcreated', true).sort('title').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nLimita el número de documentos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Número máximo. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLa lectura se detiene en cuanto se encuentran suficientes documentos, salvo que el resultado esté ordenado.\n\nExample: Take\n```js\nNOSQL('logs').find().take(50).callback(console.log);\n```\n\n### builder.limit(count)\n\nType: `method`\n\nAlias de `take()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Número máximo. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLimita el número de documentos.\n\nExample: Limit\n```js\nNOSQL('logs').find().limit(50).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nOmite documentos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Número de documentos que se omiten. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nSalta los primeros `count` documentos coincidentes.\n\nExample: Skip\n```js\nNOSQL('logs').find().skip(100).take(50).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nDevuelve solo un documento.\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nDefine `take(1)` y la respuesta es un objeto (o `undefined`) en lugar de un array.\n\nExample: First\n```js\nNOSQL('users').find().where('email', email).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nDefine skip a partir de un número de página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Número de página desde 1. |\n| `limit` | `Number` | no |  | Documentos por página. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLos números de página empiezan en 1. `limit` define `take()`; sin él se usa el valor actual de `take()`.\n\nExample: Página\n```js\nNOSQL('articles').find().sort('dtcreated', true).page(2, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nDefine skip y take a partir de valores no fiables.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Número de página desde 1. |\n| `limit` | `Number|String` | yes |  | Documentos por página. |\n| `maxlimit` | `Number` | no |  | Límite máximo y por defecto. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nAcepta cadenas (por ejemplo de la query string). Una página menor que 1 se convierte en 1; `limit` se limita a `maxlimit`, y si falta el límite se usa `maxlimit`.\n\nExample: Paginar en una acción\n```js\nNOSQL('articles').find().sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nImprime la operación compilada.\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nRegistra en la consola el archivo, la operación y el filtro compilado con el prefijo `-- NoSQL -->`.\n\nExample: Debug\n```js\nNOSQL('users').find().where('age', '>', 18).debug().callback(console.log);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nLee el resultado con un callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), o `$`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nSe llama a `fn(err, response)` cuando termina la operación. Pasa `$` en una acción para enviar la respuesta o el error al cliente. `pipe()` es un alias.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items) {\n\tif (err)\n\t\treturn console.error(err);\n\tconsole.log(items.length);\n});\n```\n\n### builder.pipe(fn)\n\nType: `method`\n\nAlias de `callback()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), o `$`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\n`fn(err, response)`, o `$`.\n\nExample: Pipe\n```js\nNOSQL('users').find().pipe($);\n```\n\n### builder.promise([$])\n\nType: `method`\n\nDevuelve el resultado como una Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Opciones de una acción. |\n\nReturns: `Promise` Se resuelve con la respuesta.\n\nLa Promise se resuelve con la respuesta. Ante un error se rechaza, o, cuando se indica `$`, el error se envía a `$.invalid()`.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nLlama a una función con la respuesta; los errores van a `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Opciones de una acción. |\n| `fn` | `Function` | yes |  | function(response, param). |\n| `param` | `Object` | no |  | Un valor que se pasa a `fn`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nSi hay éxito se llama a `fn(response, param)`; un error se envía a `$.invalid()`.\n\nExample: Done\n```js\nNOSQL('users').read().id(id).error('Not found').done($, function(user) {\n\t$.callback({ name: user.name });\n});\n```\n\n### builder.data(fn)\n\nType: `method`\n\nLlama a una función solo con una respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(response). |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nSe llama a `fn(response)` solo cuando no hay error. Se puede combinar con `callback()`.\n\nExample: Data\n```js\nNOSQL('users').find().data(function(items) {\n\tconsole.log(items);\n});\n```\n\n### builder.fail(fn)\n\nType: `method`\n\nLlama a una función solo con un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(err). |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nSe llama a `fn(err)` solo cuando la operación falla.\n\nExample: Fail\n```js\nNOSQL('users').read().id(id).error('Not found').fail(function(err) {\n\tconsole.log(err);\n});\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nConvierte un resultado vacío en un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | Mensaje de error. |\n| `reverse` | `Boolean` | no | `false` | Falla cuando el resultado no está vacío. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLa operación falla con `message` cuando la respuesta está vacía: `undefined`, un array vacío, o `0` documentos actualizados o eliminados. Con `reverse` falla cuando la respuesta no está vacía, por ejemplo para impedir un duplicado. `err()` es un alias.\n\nExample: No encontrado y duplicado\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n\nNOSQL('users').read().where('email', email).error('E-mail is already used', true).callback(function(err) {\n\t// err when the e-mail exists\n});\n```\n\n### DATA.count('nosql/' + name)\n\nType: `method`\n\nCuenta los documentos que coinciden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la base de datos con el prefijo `nosql/`. |\n\nReturns: `QueryBuilder` Builder; la respuesta es `{ count }`.\n\nUsa el motor NoSQL a través del query builder global. La respuesta es un objeto `{ count: Number }`.\n\nExample: Contar\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### DATA.check('nosql/' + name)\n\nType: `method`\n\nComprueba si existe un documento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la base de datos con el prefijo `nosql/`. |\n\nReturns: `QueryBuilder` Builder; la respuesta es un Boolean.\n\nSe detiene en el primer documento que coincide. La respuesta es `true` o `false`.\n\nExample: Comprobar\n```js\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\tconsole.log(exists);\n});\n```\n\n### DATA.scalar('nosql/' + name, type, key, [key2])\n\nType: `method`\n\nCalcula una suma, un mínimo, un máximo, un recuento o grupos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la base de datos con el prefijo `nosql/`. |\n| `type` | `String` | yes |  | `'sum'`, `'min'`, `'max'`, `'avg'`, `'count'` o `'group'`. |\n| `key` | `String` | no | `'*'` | Campo que se calcula o por el que se agrupa. `'*'` (el valor por defecto) cuenta cada documento como `1`. |\n| `key2` | `String` | no |  | Campo que se suma por grupo (solo con `'group'`). |\n\nReturns: `QueryBuilder` Builder; la respuesta es `{ value }` o un Array de grupos.\n\nCon `type` `'sum'`, `'min'`, `'max'`, `'avg'` o `'count'` la respuesta es `{ value }` para el campo `key` (los documentos sin el campo se omiten; `min` y `max` también funcionan con fechas). `avg` es la suma dividida por el recuento, o `null` cuando no coincide ningún documento. Sin `key` (o con `'*'`) cada documento que coincide cuenta como `1`, así que `DATA.scalar('nosql/orders', 'count')` cuenta los documentos. Con `'group'` la respuesta es un array de `{ <key>: value, value: count }`; con `key2` los valores de `key2` se suman por grupo en lugar de contarse.\n\nExample: Suma\n```js\nDATA.scalar('nosql/orders', 'sum', 'price').where('paid', true).callback(function(err, response) {\n\tconsole.log(response.value);\n});\n```\n\nExample: Agrupar\n```js\nDATA.scalar('nosql/orders', 'group', 'status').callback(function(err, groups) {\n\t// [{ status: 'paid', value: 12 }, { status: 'new', value: 3 }]\n});\n```\n\nExample: Media y recuento\n```js\nDATA.scalar('nosql/orders', 'avg', 'price').callback(function(err, response) {\n\tconsole.log(response.value); // the average price\n});\n\nDATA.scalar('nosql/orders', 'count').where('paid', true).callback(console.log);\n```\n\n### $dirdatabases : String\n\nType: `config`\n\nDirectorio de los archivos de base de datos.\n\nReturns: `String`\n\nEl directorio donde `NOSQL()` guarda sus archivos `.nosql`. El valor por defecto es `databases` en la raíz de la aplicación.\n\nExample: config\n```text\n$dirdatabases : /var/data/myapp/\n```\n","entries":[{"type":"method","name":"NOSQL(name)","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"nosql.insert(doc)","signature":"NOSQL(name).insert(doc)","since":"","deprecated":false},{"type":"method","name":"nosql.find()","signature":"NOSQL(name).find()","since":"","deprecated":false},{"type":"method","name":"nosql.read()","signature":"NOSQL(name).read()","since":"","deprecated":false},{"type":"method","name":"nosql.update(data)","signature":"NOSQL(name).update(data)","since":"","deprecated":false},{"type":"method","name":"nosql.modify(data)","signature":"NOSQL(name).modify(data)","since":"","deprecated":false},{"type":"method","name":"nosql.remove()","signature":"NOSQL(name).remove()","since":"","deprecated":false},{"type":"method","name":"nosql.clear()","signature":"NOSQL(name).clear()","since":"","deprecated":false},{"type":"method","name":"nosql.clean()","signature":"NOSQL(name).clean()","since":"","deprecated":false},{"type":"method","name":"builder.where(name, [comparer], value)","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query(code)","signature":"builder.query(code)","since":"","deprecated":false},{"type":"method","name":"builder.equal(obj)","signature":"builder.equal(obj)","since":"","deprecated":false},{"type":"method","name":"builder.id(id)","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.userid(id)","signature":"builder.userid(id)","since":"","deprecated":false},{"type":"method","name":"builder.in(name, value, [key])","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin(name, value, [key])","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between(name, a, b)","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search(name, value, [where])","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains(name)","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty(name)","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.or(fn)","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.year(name, [comparer], value)","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.month(name, [comparer], value)","signature":"builder.month(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.day(name, [comparer], value)","signature":"builder.day(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.fields(fields)","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort(name, [desc])","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take(count)","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.limit(count)","signature":"builder.limit(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip(count)","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page(page, [limit])","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate(page, limit, [maxlimit])","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback(fn)","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.pipe(fn)","signature":"builder.pipe(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise([$])","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.done($, fn, [param])","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.data(fn)","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.fail(fn)","signature":"builder.fail(fn)","since":"","deprecated":false},{"type":"method","name":"builder.error(message, [reverse])","signature":"builder.error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"DATA.count('nosql/name')","signature":"DATA.count('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.check('nosql/name')","signature":"DATA.check('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.scalar('nosql/name', type, key, [key2])","signature":"DATA.scalar('nosql/' + name, type, key, [key2])","since":"","deprecated":false},{"type":"config","name":"$dirdatabases","signature":"$dirdatabases : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmDe5Xc60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/nosql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Base de données NoSQL","summary":"NOSQL(name), les méthodes de son query builder et le moteur NoSQL de DATA.","markdown":"---\ntitle: \"Base de données NoSQL\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/nosql/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# Base de données NoSQL\n\n> NOSQL(name), les méthodes de son query builder et le moteur NoSQL de DATA.\n\nLes méthodes de `NOSQL(name)`, le query builder qu'elles renvoient (filtres, champs, tri, pagination et résultats), les lectures NoSQL de `DATA` et la clé de configuration `$dirdatabases`. Pour une introduction avec des exemples, lis le guide [Base de données NoSQL](../../guides/nosql/).\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nRenvoie une base de données NoSQL stockée dans un fichier texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la base de données, ou un chemin de fichier avec une barre oblique. |\n\nReturns: `Object` Un objet avec `insert()`, `find()`, `read()`, `update()`, `modify()`, `remove()`, `clear()` et `clean()`.\n\nUn nom simple utilise le fichier `databases/<name>.nosql` ; le répertoire et le fichier sont créés lorsque c'est nécessaire. Un nom contenant une barre oblique est utilisé tel quel comme chemin de fichier. Chaque méthode de l'objet renvoyé renvoie un query builder.\n\nExample: Utiliser une base de données\n```js\nvar db = NOSQL('users');\ndb.find().where('active', true).callback(console.log);\n```\n\n### NOSQL(name).insert(doc)\n\nType: `method`\n\nAjoute un nouveau document.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Le document. |\n\nReturns: `QueryBuilder` Builder ; la réponse est `1`.\n\nAjoute le document comme nouvelle ligne à la fin du fichier. Aucun `id` n'est généré ; ajoute donc le tien. Les clés avec les préfixes `+ - * / > <` stockent la valeur sans le préfixe, `!key` stocke `true` et `=key` stocke la valeur telle quelle. La réponse est `1`.\n\nExample: Insérer\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n```\n\n### NOSQL(name).find()\n\nType: `method`\n\nRecherche des documents.\n\nReturns: `QueryBuilder` Builder ; la réponse est un Array.\n\nRenvoie tous les documents correspondants sous forme de tableau, ou un tableau vide. Sans `sort()`, les documents écrits le plus récemment viennent en premier.\n\nExample: Rechercher\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### NOSQL(name).read()\n\nType: `method`\n\nLit un document.\n\nReturns: `QueryBuilder` Builder ; la réponse est un Object ou `undefined`.\n\nRenvoie le premier document correspondant (le plus récemment écrit si tu ne tries pas), ou `undefined` lorsque rien ne correspond. Combine-la avec `error()` pour répondre par une erreur lorsqu'un document est absent.\n\nExample: Lire par id\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n```\n\n### NOSQL(name).update(data)\n\nType: `method`\n\nMet à jour les documents correspondants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Les champs à écrire, éventuellement avec un préfixe. |\n\nReturns: `QueryBuilder` Builder ; la réponse est le nombre de documents mis à jour.\n\nÉcrit les clés de `data` dans chaque document correspondant ; les autres champs sont conservés. Sans filtre, tous les documents sont mis à jour. Préfixes de clé : `+key`, `-key`, `*key` et `/key` ajoutent, soustraient, multiplient ou divisent le champ par le nombre (un champ absent compte comme `0`), `>key` n'écrit la valeur que si elle est plus grande que le champ et `<key` seulement si elle est plus petite (un champ absent prend la valeur), `!key` inverse un booléen, `=key` évalue une expression JavaScript avec `doc`. La réponse est le nombre de documents mis à jour.\n\nExample: Mettre à jour\n```js\nNOSQL('products').update({ '+stock': -1, dtupdated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log(count);\n});\n```\n\nExample: Compteurs et limites\n```js\nNOSQL('products').update({ '-stock': 1, '*price': 1.1, '>maxorder': 3 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).modify(data)\n\nType: `method`\n\nAlias de `update()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Les champs à écrire, éventuellement avec un préfixe. |\n\nReturns: `QueryBuilder` Builder ; la réponse est le nombre de documents mis à jour.\n\nÉcrit les clés de `data` dans chaque document correspondant ; les autres champs sont conservés. Sans filtre, tous les documents sont mis à jour. Préfixes de clé : `+key`, `-key`, `*key` et `/key` ajoutent, soustraient, multiplient ou divisent le champ par le nombre (un champ absent compte comme `0`), `>key` n'écrit la valeur que si elle est plus grande que le champ et `<key` seulement si elle est plus petite (un champ absent prend la valeur), `!key` inverse un booléen, `=key` évalue une expression JavaScript avec `doc`. La réponse est le nombre de documents mis à jour.\n\nExample: Modify\n```js\nNOSQL('users').modify({ '!active': 1 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).remove()\n\nType: `method`\n\nSupprime les documents correspondants.\n\nReturns: `QueryBuilder` Builder ; la réponse est le nombre de documents supprimés.\n\nMarque chaque document correspondant comme supprimé. Sans filtre, tous les documents sont supprimés. La réponse est le nombre de documents supprimés. Les lignes restent dans le fichier jusqu'à `clean()`.\n\nExample: Supprimer les anciens journaux\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(console.log);\n```\n\n### NOSQL(name).clear()\n\nType: `method`\n\nSupprime tous les documents.\n\nReturns: `QueryBuilder` Builder.\n\nSupprime le fichier de la base de données. L'insertion suivante le recrée.\n\nExample: Vider\n```js\nNOSQL('cache').clear().callback(function(err) {\n\tconsole.log('empty');\n});\n```\n\n### NOSQL(name).clean()\n\nType: `method`\n\nCompacte le fichier de la base de données.\n\nReturns: `QueryBuilder` Builder.\n\nRéécrit le fichier sans les lignes des documents supprimés ni celles des anciennes versions des documents mis à jour. Les écritures attendent la fin de l'opération.\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### builder.where(name, [comparer], value)\n\nType: `method`\n\nCompare un champ avec une valeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `comparer` | `String` | no | `'='` | L'opérateur de comparaison. |\n| `value` | `Object` | yes |  | La valeur à comparer. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nComparateurs : `=` (par défaut), `==`, `<>`, `!=`, `>`, `>=`, `<`, `<=`. `=` compare de façon souple ; ainsi `'5'` correspond à `5`. Le nom peut être imbriqué (`address.city`). Avec un seul argument, elle fonctionne comme `query()`.\n\nExample: Where\n```js\nNOSQL('users').find().where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.query(code)\n\nType: `method`\n\nAjoute une condition JavaScript brute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Une expression JavaScript. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLa condition peut utiliser `doc`, le document. Une condition qui contient `require` ou `global` ne correspond à rien. Ne la construis jamais à partir d'une saisie utilisateur.\n\nExample: Condition brute\n```js\nNOSQL('orders').find().query('doc.items.length > 2').callback(console.log);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nAjoute `where(key, value)` pour chaque clé d'un objet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Les champs et les valeurs. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nChaque clé de l'objet doit être égale à sa valeur.\n\nExample: Equal\n```js\nNOSQL('users').find().equal({ role: 'admin', active: true }).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltre par le champ `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | Un ou plusieurs identifiants. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nUne valeur ajoute `where('id', id)`, un tableau ajoute `in('id', id)`.\n\nExample: Par id\n```js\nNOSQL('users').read().id($.params.id).callback($);\n```\n\n### builder.userid(id)\n\nType: `method`\n\nFiltre par le champ `userid`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array|Object` | yes |  | Un identifiant, des identifiants, un objet utilisateur ou `$`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nAccepte une chaîne, un tableau d'identifiants, un objet avec `id`, ou `$` (elle utilise alors `$.user.id`).\n\nExample: Documents de l'utilisateur\n```js\nNOSQL('notes').find().userid($).callback($);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nLe champ vaut l'une des valeurs.\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\nUne valeur unique est enveloppée dans un tableau. Lorsque le champ est un tableau, un document correspond si l'un de ses éléments fait partie des valeurs. Avec `key`, les valeurs sont lues dans cette propriété des objets de `value`.\n\nExample: In\n```js\nNOSQL('products').find().in('tags', ['usb', 'wireless']).callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nLe champ ne vaut aucune des valeurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `value` | `Array` | yes |  | Les valeurs interdites. |\n| `key` | `String` | no |  | La 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 les mêmes arguments.\n\nExample: Not in\n```js\nNOSQL('users').find().notin('role', ['guest', 'banned']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nLe champ est compris entre deux valeurs, bornes incluses.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `a` | `Number|Date` | yes |  | La borne inférieure. |\n| `b` | `Number|Date` | yes |  | La borne supérieure. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nFonctionne avec les nombres, les chaînes et les dates.\n\nExample: Between\n```js\nNOSQL('orders').find().between('price', 10, 100).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nRecherche un texte dans un champ.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `value` | `String` | yes |  | Le texte à trouver. |\n| `where` | `String` | no |  | `'beg'` ou `'end'`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nSans tenir compte de la casse. Par défaut, le texte peut se trouver n'importe où ; `'beg'` correspond au début et `'end'` à la fin. Un champ tableau correspond lorsque l'un de ses éléments correspond. Les caractères `%` du texte sont retirés.\n\nExample: Recherche\n```js\nNOSQL('users').find().search('email', '@example.com', 'end').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nLe champ a une valeur.\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\nCorrespond à une valeur truthy, ou à un tableau contenant au moins un élément.\n\nExample: Contains\n```js\nNOSQL('users').find().contains('photo').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nLe champ n'a pas de valeur.\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\nCorrespond à une valeur absente ou falsy, ou à un tableau vide.\n\nExample: Empty\n```js\nNOSQL('products').find().empty('tags').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nRelie un groupe de filtres avec OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(builder) qui ajoute les filtres. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLa fonction reçoit le builder (aussi en tant que `this`) ; les filtres ajoutés à l'intérieur forment un groupe dont n'importe lequel peut correspondre.\n\nExample: Or\n```js\nNOSQL('users').find().or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('owner', true);\n}).callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nCompare l'année complète d'un champ Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le champ de date. |\n| `comparer` | `String` | no | `'='` | L'opérateur de comparaison. |\n| `value` | `Number` | yes |  | La valeur à comparer. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLes documents dont le champ n'est pas une `Date` ne correspondent pas. Les comparateurs sont les mêmes que dans `where()`.\n\nExample: Année\n```js\nNOSQL('orders').find().year('dtcreated', 2024).callback(console.log);\n```\n\n### builder.month(name, [comparer], value)\n\nType: `method`\n\nCompare le mois (1-12) d'un champ Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le champ de date. |\n| `comparer` | `String` | no | `'='` | L'opérateur de comparaison. |\n| `value` | `Number` | yes |  | La valeur à comparer. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLes documents dont le champ n'est pas une `Date` ne correspondent pas. Les comparateurs sont les mêmes que dans `where()`.\n\nExample: Mois\n```js\nNOSQL('orders').find().month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.day(name, [comparer], value)\n\nType: `method`\n\nCompare le jour du mois (1-31) d'un champ Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le champ de date. |\n| `comparer` | `String` | no | `'='` | L'opérateur de comparaison. |\n| `value` | `Number` | yes |  | La valeur à comparer. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLes documents dont le champ n'est pas une `Date` ne correspondent pas. Les comparateurs sont les mêmes que dans `where()`.\n\nExample: Jour\n```js\nNOSQL('orders').find().day('dtcreated', 1).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 |  | Les noms de champs séparés par des virgules. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nUne liste, séparée par des virgules, des champs à renvoyer, ou des champs précédés de `-` à exclure (`'-password,-token'`).\n\nExample: Fields\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nTrie le résultat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `desc` | `Boolean|String` | no | `false` | `true` ou `'desc'` pour l'ordre décroissant. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nAppelle-la plusieurs fois pour trier selon plusieurs champs. Les champs imbriqués fonctionnent (`address.city`). Sans tri, les documents écrits le plus récemment viennent en premier.\n\nExample: Tri\n```js\nNOSQL('articles').find().sort('dtcreated', true).sort('title').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nLimite le nombre de documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre maximal. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLa lecture s'arrête dès que suffisamment de documents sont trouvés, sauf si le résultat est trié.\n\nExample: Take\n```js\nNOSQL('logs').find().take(50).callback(console.log);\n```\n\n### builder.limit(count)\n\nType: `method`\n\nAlias de `take()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre maximal. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLimite le nombre de documents.\n\nExample: Limit\n```js\nNOSQL('logs').find().limit(50).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nSaute des documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre à sauter. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nSaute les `count` premiers documents correspondants.\n\nExample: Skip\n```js\nNOSQL('logs').find().skip(100).take(50).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nNe renvoie qu'un seul document.\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nDéfinit `take(1)` et la réponse est un objet (ou `undefined`) au lieu d'un tableau.\n\nExample: First\n```js\nNOSQL('users').find().where('email', email).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nDéfinit skip à partir d'un numéro de page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Le numéro de page, à partir de 1. |\n| `limit` | `Number` | no |  | Les documents par page. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLes numéros de page commencent à 1. `limit` définit `take()` ; sans lui, la valeur actuelle de `take()` est utilisée.\n\nExample: Page\n```js\nNOSQL('articles').find().sort('dtcreated', true).page(2, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nDéfinit skip et take à partir de valeurs non fiables.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Le numéro de page, à partir de 1. |\n| `limit` | `Number|String` | yes |  | Les documents par page. |\n| `maxlimit` | `Number` | no |  | La limite maximale et par défaut. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nAccepte des chaînes (par exemple issues de la query string). Une page inférieure à 1 devient 1 ; `limit` est plafonné à `maxlimit`, et une limite absente utilise `maxlimit`.\n\nExample: Paginer dans une action\n```js\nNOSQL('articles').find().sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nAffiche l'opération compilée.\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nJournalise le fichier, l'opération et le filtre compilé dans la console avec le préfixe `-- NoSQL -->`.\n\nExample: Debug\n```js\nNOSQL('users').find().where('age', '>', 18).debug().callback(console.log);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nLit le résultat avec un callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), ou `$`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\n`fn(err, response)` est appelée à la fin de l'opération. Passe `$` dans une action pour envoyer la réponse ou l'erreur au client. `pipe()` est un alias.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items) {\n\tif (err)\n\t\treturn console.error(err);\n\tconsole.log(items.length);\n});\n```\n\n### builder.pipe(fn)\n\nType: `method`\n\nAlias de `callback()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), ou `$`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\n`fn(err, response)`, ou `$`.\n\nExample: Pipe\n```js\nNOSQL('users').find().pipe($);\n```\n\n### builder.promise([$])\n\nType: `method`\n\nRenvoie le résultat sous forme de Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Les options d'une action. |\n\nReturns: `Promise` Résolue avec la réponse.\n\nLa Promise est résolue avec la réponse. En cas d'erreur, elle est rejetée, ou, lorsque `$` est fourni, l'erreur est envoyée à `$.invalid()`.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nAppelle une fonction avec la réponse ; les erreurs vont à `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Les options d'une action. |\n| `fn` | `Function` | yes |  | function(response, param). |\n| `param` | `Object` | no |  | Une valeur transmise à `fn`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nEn cas de succès, `fn(response, param)` est appelée ; une erreur est envoyée à `$.invalid()`.\n\nExample: Done\n```js\nNOSQL('users').read().id(id).error('Not found').done($, function(user) {\n\t$.callback({ name: user.name });\n});\n```\n\n### builder.data(fn)\n\nType: `method`\n\nAppelle une fonction uniquement avec une réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(response). |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\n`fn(response)` n'est appelée qu'en l'absence d'erreur. Elle peut être combinée avec `callback()`.\n\nExample: Data\n```js\nNOSQL('users').find().data(function(items) {\n\tconsole.log(items);\n});\n```\n\n### builder.fail(fn)\n\nType: `method`\n\nAppelle une fonction uniquement avec une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(err). |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\n`fn(err)` n'est appelée que lorsque l'opération échoue.\n\nExample: Fail\n```js\nNOSQL('users').read().id(id).error('Not found').fail(function(err) {\n\tconsole.log(err);\n});\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nTransforme un résultat vide en erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | Le message d'erreur. |\n| `reverse` | `Boolean` | no | `false` | Échoue lorsque le résultat n'est pas vide. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nL'opération échoue avec `message` lorsque la réponse est vide : `undefined`, un tableau vide, ou `0` document mis à jour ou supprimé. Avec `reverse`, elle échoue lorsque la réponse n'est pas vide, par exemple pour empêcher un doublon. `err()` est un alias.\n\nExample: Introuvable et doublon\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n\nNOSQL('users').read().where('email', email).error('E-mail is already used', true).callback(function(err) {\n\t// err when the e-mail exists\n});\n```\n\n### DATA.count('nosql/' + name)\n\nType: `method`\n\nCompte les documents correspondants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la base de données avec le préfixe `nosql/`. |\n\nReturns: `QueryBuilder` Builder ; la réponse est `{ count }`.\n\nUtilise le moteur NoSQL via le query builder global. La réponse est un objet `{ count: Number }`.\n\nExample: Compter\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### DATA.check('nosql/' + name)\n\nType: `method`\n\nVérifie si un document existe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la base de données avec le préfixe `nosql/`. |\n\nReturns: `QueryBuilder` Builder ; la réponse est un Boolean.\n\nS'arrête au premier document correspondant. La réponse est `true` ou `false`.\n\nExample: Vérifier\n```js\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\tconsole.log(exists);\n});\n```\n\n### DATA.scalar('nosql/' + name, type, key, [key2])\n\nType: `method`\n\nCalcule une somme, un minimum, un maximum, un comptage ou des groupes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la base de données avec le préfixe `nosql/`. |\n| `type` | `String` | yes |  | `'sum'`, `'min'`, `'max'`, `'avg'`, `'count'` ou `'group'`. |\n| `key` | `String` | no | `'*'` | Champ à calculer ou par lequel regrouper. `'*'` (la valeur par défaut) compte chaque document comme `1`. |\n| `key2` | `String` | no |  | Champ à additionner par groupe (seulement avec `'group'`). |\n\nReturns: `QueryBuilder` Builder ; la réponse est `{ value }` ou un Array de groupes.\n\nAvec `type` à `'sum'`, `'min'`, `'max'`, `'avg'` ou `'count'`, la réponse est `{ value }` pour le champ `key` (les documents sans ce champ sont ignorés ; `min` et `max` fonctionnent aussi avec les dates). `avg` est la somme divisée par le nombre, ou `null` quand aucun document ne correspond. Sans `key` (ou avec `'*'`), chaque document correspondant compte comme `1`, donc `DATA.scalar('nosql/orders', 'count')` compte les documents. Avec `'group'`, la réponse est un tableau de `{ <key>: value, value: count }` ; avec `key2`, les valeurs de `key2` sont additionnées par groupe au lieu d'être comptées.\n\nExample: Somme\n```js\nDATA.scalar('nosql/orders', 'sum', 'price').where('paid', true).callback(function(err, response) {\n\tconsole.log(response.value);\n});\n```\n\nExample: Groupe\n```js\nDATA.scalar('nosql/orders', 'group', 'status').callback(function(err, groups) {\n\t// [{ status: 'paid', value: 12 }, { status: 'new', value: 3 }]\n});\n```\n\nExample: Moyenne et comptage\n```js\nDATA.scalar('nosql/orders', 'avg', 'price').callback(function(err, response) {\n\tconsole.log(response.value); // the average price\n});\n\nDATA.scalar('nosql/orders', 'count').where('paid', true).callback(console.log);\n```\n\n### $dirdatabases : String\n\nType: `config`\n\nLe répertoire des fichiers de base de données.\n\nReturns: `String`\n\nLe répertoire où `NOSQL()` conserve ses fichiers `.nosql`. La valeur par défaut est `databases` à la racine de l'application.\n\nExample: config\n```text\n$dirdatabases : /var/data/myapp/\n```\n","entries":[{"type":"method","name":"NOSQL(name)","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"nosql.insert(doc)","signature":"NOSQL(name).insert(doc)","since":"","deprecated":false},{"type":"method","name":"nosql.find()","signature":"NOSQL(name).find()","since":"","deprecated":false},{"type":"method","name":"nosql.read()","signature":"NOSQL(name).read()","since":"","deprecated":false},{"type":"method","name":"nosql.update(data)","signature":"NOSQL(name).update(data)","since":"","deprecated":false},{"type":"method","name":"nosql.modify(data)","signature":"NOSQL(name).modify(data)","since":"","deprecated":false},{"type":"method","name":"nosql.remove()","signature":"NOSQL(name).remove()","since":"","deprecated":false},{"type":"method","name":"nosql.clear()","signature":"NOSQL(name).clear()","since":"","deprecated":false},{"type":"method","name":"nosql.clean()","signature":"NOSQL(name).clean()","since":"","deprecated":false},{"type":"method","name":"builder.where(name, [comparer], value)","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query(code)","signature":"builder.query(code)","since":"","deprecated":false},{"type":"method","name":"builder.equal(obj)","signature":"builder.equal(obj)","since":"","deprecated":false},{"type":"method","name":"builder.id(id)","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.userid(id)","signature":"builder.userid(id)","since":"","deprecated":false},{"type":"method","name":"builder.in(name, value, [key])","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin(name, value, [key])","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between(name, a, b)","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search(name, value, [where])","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains(name)","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty(name)","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.or(fn)","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.year(name, [comparer], value)","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.month(name, [comparer], value)","signature":"builder.month(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.day(name, [comparer], value)","signature":"builder.day(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.fields(fields)","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort(name, [desc])","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take(count)","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.limit(count)","signature":"builder.limit(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip(count)","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page(page, [limit])","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate(page, limit, [maxlimit])","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback(fn)","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.pipe(fn)","signature":"builder.pipe(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise([$])","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.done($, fn, [param])","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.data(fn)","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.fail(fn)","signature":"builder.fail(fn)","since":"","deprecated":false},{"type":"method","name":"builder.error(message, [reverse])","signature":"builder.error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"DATA.count('nosql/name')","signature":"DATA.count('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.check('nosql/name')","signature":"DATA.check('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.scalar('nosql/name', type, key, [key2])","signature":"DATA.scalar('nosql/' + name, type, key, [key2])","since":"","deprecated":false},{"type":"config","name":"$dirdatabases","signature":"$dirdatabases : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmDe5Xc60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/nosql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Database NoSQL","summary":"NOSQL(name), i metodi del suo query builder e il motore NoSQL di DATA.","markdown":"---\ntitle: Database NoSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/nosql/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# Database NoSQL\n\n> NOSQL(name), i metodi del suo query builder e il motore NoSQL di DATA.\n\nMetodi di `NOSQL(name)`, il query builder che restituiscono (filtri, campi, ordinamento, paginazione e risultati), le letture NoSQL di `DATA` e la chiave di configurazione `$dirdatabases`. Per un'introduzione con esempi leggi la guida [Database NoSQL](../../guides/nosql/).\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nRestituisce un database NoSQL salvato in un file di testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del database, oppure un percorso di file con una barra. |\n\nReturns: `Object` Un oggetto con `insert()`, `find()`, `read()`, `update()`, `modify()`, `remove()`, `clear()` e `clean()`.\n\nUn nome semplice usa il file `databases/<name>.nosql`; la directory e il file vengono creati quando servono. Un nome con una barra viene usato così com'è come percorso del file. Ogni metodo dell'oggetto restituito restituisce un query builder.\n\nExample: Usare un database\n```js\nvar db = NOSQL('users');\ndb.find().where('active', true).callback(console.log);\n```\n\n### NOSQL(name).insert(doc)\n\nType: `method`\n\nAggiunge un nuovo documento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Il documento. |\n\nReturns: `QueryBuilder` Builder; la risposta è `1`.\n\nAggiunge il documento come nuova riga alla fine del file. Non viene generato alcun `id`, quindi aggiungi il tuo. Le chiavi con i prefissi `+ - * / > <` salvano il valore senza il prefisso, `!key` salva `true` e `=key` salva il valore così com'è. La risposta è `1`.\n\nExample: Insert\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n```\n\n### NOSQL(name).find()\n\nType: `method`\n\nTrova documenti.\n\nReturns: `QueryBuilder` Builder; la risposta è un Array.\n\nRestituisce tutti i documenti corrispondenti come array, oppure un array vuoto. Senza `sort()` vengono prima i documenti scritti più di recente.\n\nExample: Find\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### NOSQL(name).read()\n\nType: `method`\n\nLegge un documento.\n\nReturns: `QueryBuilder` Builder; la risposta è un Object o `undefined`.\n\nRestituisce il primo documento corrispondente (quello scritto più di recente quando non ordini), oppure `undefined` quando nulla corrisponde. Combinalo con `error()` per rispondere con un errore quando un documento manca.\n\nExample: Leggere per id\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n```\n\n### NOSQL(name).update(data)\n\nType: `method`\n\nAggiorna i documenti corrispondenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Campi da scrivere, facoltativamente con un prefisso. |\n\nReturns: `QueryBuilder` Builder; la risposta è il numero di documenti aggiornati.\n\nScrive le chiavi di `data` in ogni documento corrispondente; gli altri campi vengono mantenuti. Senza filtro vengono aggiornati tutti i documenti. Prefissi delle chiavi: `+key`, `-key`, `*key` e `/key` aggiungono, sottraggono, moltiplicano o dividono il campo per il numero (un campo mancante vale `0`), `>key` scrive il valore solo quando è maggiore del campo e `<key` solo quando è minore (un campo mancante prende il valore), `!key` inverte un booleano, `=key` valuta un'espressione JavaScript con `doc`. La risposta è il numero di documenti aggiornati.\n\nExample: Aggiornare\n```js\nNOSQL('products').update({ '+stock': -1, dtupdated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log(count);\n});\n```\n\nExample: Contatori e limiti\n```js\nNOSQL('products').update({ '-stock': 1, '*price': 1.1, '>maxorder': 3 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).modify(data)\n\nType: `method`\n\nAlias di `update()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Campi da scrivere, facoltativamente con un prefisso. |\n\nReturns: `QueryBuilder` Builder; la risposta è il numero di documenti aggiornati.\n\nScrive le chiavi di `data` in ogni documento corrispondente; gli altri campi vengono mantenuti. Senza filtro vengono aggiornati tutti i documenti. Prefissi delle chiavi: `+key`, `-key`, `*key` e `/key` aggiungono, sottraggono, moltiplicano o dividono il campo per il numero (un campo mancante vale `0`), `>key` scrive il valore solo quando è maggiore del campo e `<key` solo quando è minore (un campo mancante prende il valore), `!key` inverte un booleano, `=key` valuta un'espressione JavaScript con `doc`. La risposta è il numero di documenti aggiornati.\n\nExample: Modify\n```js\nNOSQL('users').modify({ '!active': 1 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).remove()\n\nType: `method`\n\nRimuove i documenti corrispondenti.\n\nReturns: `QueryBuilder` Builder; la risposta è il numero di documenti rimossi.\n\nContrassegna come rimosso ogni documento corrispondente. Senza filtro vengono rimossi tutti i documenti. La risposta è il numero di documenti rimossi. Le righe restano nel file fino a `clean()`.\n\nExample: Rimuovere i vecchi log\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(console.log);\n```\n\n### NOSQL(name).clear()\n\nType: `method`\n\nElimina tutti i documenti.\n\nReturns: `QueryBuilder` Builder.\n\nElimina il file del database. Il prossimo inserimento lo crea di nuovo.\n\nExample: Clear\n```js\nNOSQL('cache').clear().callback(function(err) {\n\tconsole.log('empty');\n});\n```\n\n### NOSQL(name).clean()\n\nType: `method`\n\nCompatta il file del database.\n\nReturns: `QueryBuilder` Builder.\n\nRiscrive il file senza le righe dei documenti rimossi e delle vecchie versioni dei documenti aggiornati. Le scritture attendono che termini.\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### builder.where(name, [comparer], value)\n\nType: `method`\n\nConfronta un campo con un valore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `comparer` | `String` | no | `'='` | Operatore di confronto. |\n| `value` | `Object` | yes |  | Valore da confrontare. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nComparatori: `=` (predefinito), `==`, `<>`, `!=`, `>`, `>=`, `<`, `<=`. `=` confronta in modo non stretto, quindi `'5'` corrisponde a `5`. Il nome può essere annidato (`address.city`). Con un solo argomento funziona come `query()`.\n\nExample: Where\n```js\nNOSQL('users').find().where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.query(code)\n\nType: `method`\n\nAggiunge una condizione JavaScript grezza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Espressione JavaScript. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nLa condizione può usare `doc`, il documento. Una condizione che contiene `require` o `global` non corrisponde a nulla. Non costruirla mai a partire dall'input dell'utente.\n\nExample: Condizione grezza\n```js\nNOSQL('orders').find().query('doc.items.length > 2').callback(console.log);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nAggiunge `where(key, value)` per ogni chiave di un oggetto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Campi e valori. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nOgni chiave dell'oggetto deve essere uguale al suo valore.\n\nExample: Uguaglianza\n```js\nNOSQL('users').find().equal({ role: 'admin', active: true }).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltra per il campo `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | Identificatore o identificatori. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nUn valore aggiunge `where('id', id)`, un array aggiunge `in('id', id)`.\n\nExample: Per id\n```js\nNOSQL('users').read().id($.params.id).callback($);\n```\n\n### builder.userid(id)\n\nType: `method`\n\nFiltra per il campo `userid`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array|Object` | yes |  | Identificatore, identificatori, un oggetto utente o `$`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nAccetta una stringa, un array di identificatori, un oggetto con `id` oppure `$` (in tal caso usa `$.user.id`).\n\nExample: Documenti dell'utente\n```js\nNOSQL('notes').find().userid($).callback($);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nIl campo è uno dei valori.\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\nUn valore singolo viene racchiuso in un array. Quando il campo è un array, un documento corrisponde se uno qualsiasi dei suoi elementi è uno dei valori. Con `key`, i valori vengono presi da quella proprietà degli oggetti in `value`.\n\nExample: In\n```js\nNOSQL('products').find().in('tags', ['usb', 'wireless']).callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nIl campo non è nessuno dei valori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `value` | `Array` | yes |  | Valori vietati. |\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 gli stessi argomenti.\n\nExample: Not in\n```js\nNOSQL('users').find().notin('role', ['guest', 'banned']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nIl campo è compreso tra due valori, estremi inclusi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `a` | `Number|Date` | yes |  | Limite inferiore. |\n| `b` | `Number|Date` | yes |  | Limite superiore. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nFunziona con numeri, stringhe e date.\n\nExample: Between\n```js\nNOSQL('orders').find().between('price', 10, 100).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nCerca un testo in un campo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `value` | `String` | yes |  | Testo da trovare. |\n| `where` | `String` | no |  | `'beg'` o `'end'`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nSenza distinzione tra maiuscole e minuscole. Per impostazione predefinita il testo può trovarsi ovunque; `'beg'` corrisponde all'inizio e `'end'` alla fine. Un campo array corrisponde quando uno qualsiasi degli elementi corrisponde. I caratteri `%` nel testo vengono rimossi.\n\nExample: Ricerca\n```js\nNOSQL('users').find().search('email', '@example.com', 'end').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nIl campo ha un valore.\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\nCorrisponde a un valore truthy, oppure a un array con almeno un elemento.\n\nExample: Contains\n```js\nNOSQL('users').find().contains('photo').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nIl campo non ha alcun valore.\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\nCorrisponde a un valore mancante o falsy, oppure a un array vuoto.\n\nExample: Empty\n```js\nNOSQL('products').find().empty('tags').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nUnisce un gruppo di filtri con OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(builder) che aggiunge i filtri. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nLa funzione riceve il builder (anche come `this`); i filtri aggiunti al suo interno formano un gruppo in cui è sufficiente che uno qualsiasi corrisponda.\n\nExample: Or\n```js\nNOSQL('users').find().or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('owner', true);\n}).callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nConfronta l'anno completo di un campo Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Campo data. |\n| `comparer` | `String` | no | `'='` | Operatore di confronto. |\n| `value` | `Number` | yes |  | Valore da confrontare. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nI documenti in cui il campo non è un `Date` non corrispondono. I comparatori sono gli stessi di `where()`.\n\nExample: Anno\n```js\nNOSQL('orders').find().year('dtcreated', 2024).callback(console.log);\n```\n\n### builder.month(name, [comparer], value)\n\nType: `method`\n\nConfronta il mese (1-12) di un campo Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Campo data. |\n| `comparer` | `String` | no | `'='` | Operatore di confronto. |\n| `value` | `Number` | yes |  | Valore da confrontare. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nI documenti in cui il campo non è un `Date` non corrispondono. I comparatori sono gli stessi di `where()`.\n\nExample: Mese\n```js\nNOSQL('orders').find().month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.day(name, [comparer], value)\n\nType: `method`\n\nConfronta il giorno del mese (1-31) di un campo Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Campo data. |\n| `comparer` | `String` | no | `'='` | Operatore di confronto. |\n| `value` | `Number` | yes |  | Valore da confrontare. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nI documenti in cui il campo non è un `Date` non corrispondono. I comparatori sono gli stessi di `where()`.\n\nExample: Giorno\n```js\nNOSQL('orders').find().day('dtcreated', 1).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 |  | Nomi di campi separati da virgole. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nUn elenco separato da virgole di campi da restituire, oppure di campi con `-` da escludere (`'-password,-token'`).\n\nExample: Campi\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nOrdina il risultato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `desc` | `Boolean|String` | no | `false` | `true` o `'desc'` per l'ordine decrescente. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nChiamalo più volte per ordinare per più campi. I campi annidati funzionano (`address.city`). Senza ordinamento vengono prima i documenti scritti più di recente.\n\nExample: Ordinamento\n```js\nNOSQL('articles').find().sort('dtcreated', true).sort('title').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nLimita il numero di documenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Numero massimo. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nLa lettura si ferma non appena vengono trovati abbastanza documenti, a meno che il risultato non sia ordinato.\n\nExample: Take\n```js\nNOSQL('logs').find().take(50).callback(console.log);\n```\n\n### builder.limit(count)\n\nType: `method`\n\nAlias di `take()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Numero massimo. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nLimita il numero di documenti.\n\nExample: Limit\n```js\nNOSQL('logs').find().limit(50).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nSalta documenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Numero da saltare. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nSalta i primi `count` documenti corrispondenti.\n\nExample: Skip\n```js\nNOSQL('logs').find().skip(100).take(50).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nRestituisce un solo documento.\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nImposta `take(1)` e la risposta è un oggetto (o `undefined`) invece di un array.\n\nExample: First\n```js\nNOSQL('users').find().where('email', email).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nImposta skip a partire da un numero di pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Numero di pagina a partire da 1. |\n| `limit` | `Number` | no |  | Documenti per pagina. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nI numeri di pagina iniziano da 1. `limit` imposta `take()`; senza di esso viene usato il valore attuale di `take()`.\n\nExample: Pagina\n```js\nNOSQL('articles').find().sort('dtcreated', true).page(2, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nImposta skip e take da valori non attendibili.\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 e predefinito. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nAccetta stringhe (per esempio dalla query string). Una pagina inferiore a 1 diventa 1; `limit` è limitato a `maxlimit` e un limite mancante usa `maxlimit`.\n\nExample: Paginare in un'azione\n```js\nNOSQL('articles').find().sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nStampa l'operazione compilata.\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nRegistra nella console il file, l'operazione e il filtro compilato con il prefisso `-- NoSQL -->`.\n\nExample: Debug\n```js\nNOSQL('users').find().where('age', '>', 18).debug().callback(console.log);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nLegge il risultato con una callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), oppure `$`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\n`fn(err, response)` viene chiamata quando l'operazione termina. Passa `$` in un'azione per inviare la risposta o l'errore al client. `pipe()` è un alias.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items) {\n\tif (err)\n\t\treturn console.error(err);\n\tconsole.log(items.length);\n});\n```\n\n### builder.pipe(fn)\n\nType: `method`\n\nAlias di `callback()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), oppure `$`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\n`fn(err, response)`, oppure `$`.\n\nExample: Pipe\n```js\nNOSQL('users').find().pipe($);\n```\n\n### builder.promise([$])\n\nType: `method`\n\nRestituisce il risultato come Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Opzioni di un'azione. |\n\nReturns: `Promise` Si risolve con la risposta.\n\nLa Promise si risolve con la risposta. In caso di errore viene rifiutata oppure, quando viene passato `$`, l'errore viene inviato a `$.invalid()`.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nChiama una funzione con la risposta, gli errori vanno a `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Opzioni di un'azione. |\n| `fn` | `Function` | yes |  | function(response, param). |\n| `param` | `Object` | no |  | Un valore passato a `fn`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nIn caso di successo viene chiamata `fn(response, param)`; un errore viene inviato a `$.invalid()`.\n\nExample: Done\n```js\nNOSQL('users').read().id(id).error('Not found').done($, function(user) {\n\t$.callback({ name: user.name });\n});\n```\n\n### builder.data(fn)\n\nType: `method`\n\nChiama una funzione solo con una risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(response). |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\n`fn(response)` viene chiamata solo quando non c'è alcun errore. Si può combinare con `callback()`.\n\nExample: Data\n```js\nNOSQL('users').find().data(function(items) {\n\tconsole.log(items);\n});\n```\n\n### builder.fail(fn)\n\nType: `method`\n\nChiama una funzione solo con un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(err). |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\n`fn(err)` viene chiamata solo quando l'operazione fallisce.\n\nExample: Fail\n```js\nNOSQL('users').read().id(id).error('Not found').fail(function(err) {\n\tconsole.log(err);\n});\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nTrasforma un risultato vuoto in un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | Messaggio di errore. |\n| `reverse` | `Boolean` | no | `false` | Fallisce quando il risultato non è vuoto. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nL'operazione fallisce con `message` quando la risposta è vuota: `undefined`, un array vuoto, oppure `0` documenti aggiornati o rimossi. Con `reverse` fallisce quando la risposta non è vuota, per esempio per bloccare un duplicato. `err()` è un alias.\n\nExample: Non trovato e duplicato\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n\nNOSQL('users').read().where('email', email).error('E-mail is already used', true).callback(function(err) {\n\t// err when the e-mail exists\n});\n```\n\n### DATA.count('nosql/' + name)\n\nType: `method`\n\nConta i documenti corrispondenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del database con il prefisso `nosql/`. |\n\nReturns: `QueryBuilder` Builder; la risposta è `{ count }`.\n\nUsa il motore NoSQL tramite il query builder globale. La risposta è un oggetto `{ count: Number }`.\n\nExample: Count\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### DATA.check('nosql/' + name)\n\nType: `method`\n\nVerifica se un documento esiste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del database con il prefisso `nosql/`. |\n\nReturns: `QueryBuilder` Builder; la risposta è un Boolean.\n\nSi ferma al primo documento corrispondente. La risposta è `true` o `false`.\n\nExample: Check\n```js\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\tconsole.log(exists);\n});\n```\n\n### DATA.scalar('nosql/' + name, type, key, [key2])\n\nType: `method`\n\nCalcola una somma, un minimo, un massimo, un conteggio o dei gruppi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del database con il prefisso `nosql/`. |\n| `type` | `String` | yes |  | `'sum'`, `'min'`, `'max'`, `'avg'`, `'count'` o `'group'`. |\n| `key` | `String` | no | `'*'` | Campo da calcolare o per cui raggruppare. `'*'` (il predefinito) conta ogni documento come `1`. |\n| `key2` | `String` | no |  | Campo da sommare per gruppo (solo con `'group'`). |\n\nReturns: `QueryBuilder` Builder; la risposta è `{ value }` o un Array di gruppi.\n\nCon `type` `'sum'`, `'min'`, `'max'`, `'avg'` o `'count'` la risposta è `{ value }` per il campo `key` (i documenti senza il campo vengono saltati; `min` e `max` funzionano anche con le date). `avg` è la somma divisa per il conteggio, o `null` quando nessun documento corrisponde. Senza `key` (o con `'*'`) ogni documento corrispondente vale `1`, quindi `DATA.scalar('nosql/orders', 'count')` conta i documenti. Con `'group'` la risposta è un array di `{ <key>: value, value: count }`; con `key2` i valori di `key2` vengono sommati per gruppo invece di essere contati.\n\nExample: Somma\n```js\nDATA.scalar('nosql/orders', 'sum', 'price').where('paid', true).callback(function(err, response) {\n\tconsole.log(response.value);\n});\n```\n\nExample: Gruppo\n```js\nDATA.scalar('nosql/orders', 'group', 'status').callback(function(err, groups) {\n\t// [{ status: 'paid', value: 12 }, { status: 'new', value: 3 }]\n});\n```\n\nExample: Media e conteggio\n```js\nDATA.scalar('nosql/orders', 'avg', 'price').callback(function(err, response) {\n\tconsole.log(response.value); // the average price\n});\n\nDATA.scalar('nosql/orders', 'count').where('paid', true).callback(console.log);\n```\n\n### $dirdatabases : String\n\nType: `config`\n\nDirectory dei file del database.\n\nReturns: `String`\n\nLa directory in cui `NOSQL()` conserva i suoi file `.nosql`. Il valore predefinito è `databases` nella radice dell'applicazione.\n\nExample: config\n```text\n$dirdatabases : /var/data/myapp/\n```\n","entries":[{"type":"method","name":"NOSQL(name)","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"nosql.insert(doc)","signature":"NOSQL(name).insert(doc)","since":"","deprecated":false},{"type":"method","name":"nosql.find()","signature":"NOSQL(name).find()","since":"","deprecated":false},{"type":"method","name":"nosql.read()","signature":"NOSQL(name).read()","since":"","deprecated":false},{"type":"method","name":"nosql.update(data)","signature":"NOSQL(name).update(data)","since":"","deprecated":false},{"type":"method","name":"nosql.modify(data)","signature":"NOSQL(name).modify(data)","since":"","deprecated":false},{"type":"method","name":"nosql.remove()","signature":"NOSQL(name).remove()","since":"","deprecated":false},{"type":"method","name":"nosql.clear()","signature":"NOSQL(name).clear()","since":"","deprecated":false},{"type":"method","name":"nosql.clean()","signature":"NOSQL(name).clean()","since":"","deprecated":false},{"type":"method","name":"builder.where(name, [comparer], value)","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query(code)","signature":"builder.query(code)","since":"","deprecated":false},{"type":"method","name":"builder.equal(obj)","signature":"builder.equal(obj)","since":"","deprecated":false},{"type":"method","name":"builder.id(id)","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.userid(id)","signature":"builder.userid(id)","since":"","deprecated":false},{"type":"method","name":"builder.in(name, value, [key])","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin(name, value, [key])","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between(name, a, b)","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search(name, value, [where])","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains(name)","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty(name)","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.or(fn)","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.year(name, [comparer], value)","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.month(name, [comparer], value)","signature":"builder.month(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.day(name, [comparer], value)","signature":"builder.day(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.fields(fields)","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort(name, [desc])","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take(count)","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.limit(count)","signature":"builder.limit(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip(count)","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page(page, [limit])","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate(page, limit, [maxlimit])","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback(fn)","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.pipe(fn)","signature":"builder.pipe(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise([$])","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.done($, fn, [param])","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.data(fn)","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.fail(fn)","signature":"builder.fail(fn)","since":"","deprecated":false},{"type":"method","name":"builder.error(message, [reverse])","signature":"builder.error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"DATA.count('nosql/name')","signature":"DATA.count('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.check('nosql/name')","signature":"DATA.check('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.scalar('nosql/name', type, key, [key2])","signature":"DATA.scalar('nosql/' + name, type, key, [key2])","since":"","deprecated":false},{"type":"config","name":"$dirdatabases","signature":"$dirdatabases : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JaqmDe5Xc60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/nosql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"NoSQL databáza","summary":"NOSQL(name), metódy jeho query buildera a NoSQL engine pre DATA.","markdown":"---\ntitle: \"NoSQL databáza\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/nosql/\nupdated: 2026-11-19T16:17:12.159Z\n---\n\n# NoSQL databáza\n\n> NOSQL(name), metódy jeho query buildera a NoSQL engine pre DATA.\n\nMetódy `NOSQL(name)`, query builder, ktorý vracajú (filtre, polia, zoradenie, stránkovanie a výsledky), NoSQL čítania cez `DATA` a konfiguračný kľúč `$dirdatabases`. Úvod s príkladmi nájdeš v návode [NoSQL databáza](../../guides/nosql/).\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nVráti NoSQL databázu uloženú v textovom súbore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov databázy, alebo cesta k súboru s lomkou. |\n\nReturns: `Object` Objekt s `insert()`, `find()`, `read()`, `update()`, `modify()`, `remove()`, `clear()` a `clean()`.\n\nObyčajný názov používa súbor `databases/<name>.nosql`; priečinok aj súbor sa vytvoria, keď sú potrebné. Názov s lomkou sa použije ako cesta k súboru tak, ako je. Každá metóda vráteného objektu vracia query builder.\n\nExample: Použitie databázy\n```js\nvar db = NOSQL('users');\ndb.find().where('active', true).callback(console.log);\n```\n\n### NOSQL(name).insert(doc)\n\nType: `method`\n\nPripojí nový dokument.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Dokument. |\n\nReturns: `QueryBuilder` Builder; odpoveď je `1`.\n\nPridá dokument ako nový riadok na koniec súboru. Negeneruje sa žiadne `id`, preto pridaj vlastné. Kľúče s prefixmi `+ - * / > <` uložia hodnotu bez prefixu, `!key` uloží `true` a `=key` uloží hodnotu tak, ako je. Odpoveď je `1`.\n\nExample: Vloženie\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', dtcreated: NOW }).callback(function(err, response) {\n\t// response === 1\n});\n```\n\n### NOSQL(name).find()\n\nType: `method`\n\nVyhľadá dokumenty.\n\nReturns: `QueryBuilder` Builder; odpoveď je Array.\n\nVráti všetky vyhovujúce dokumenty ako pole, alebo prázdne pole. Bez `sort()` idú ako prvé naposledy zapísané dokumenty.\n\nExample: Vyhľadanie\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').take(10).callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### NOSQL(name).read()\n\nType: `method`\n\nPrečíta jeden dokument.\n\nReturns: `QueryBuilder` Builder; odpoveď je Object alebo `undefined`.\n\nVráti prvý vyhovujúci dokument (bez zoradenia ten naposledy zapísaný), alebo `undefined`, keď nič nevyhovuje. Skombinuj ho s `error()`, ak chceš na chýbajúci dokument odpovedať chybou.\n\nExample: Čítanie podľa id\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n```\n\n### NOSQL(name).update(data)\n\nType: `method`\n\nAktualizuje vyhovujúce dokumenty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Polia na zápis, voliteľne s prefixom. |\n\nReturns: `QueryBuilder` Builder; odpoveď je počet aktualizovaných dokumentov.\n\nZapíše kľúče z `data` do každého vyhovujúceho dokumentu; ostatné polia zostanú. Bez filtra sa aktualizujú všetky dokumenty. Prefixy kľúčov: `+key`, `-key`, `*key` a `/key` pripočítajú, odpočítajú, vynásobia alebo vydelia pole číslom (chýbajúce pole sa počíta ako `0`), `>key` zapíše hodnotu iba vtedy, keď je väčšia ako pole, a `<key` iba vtedy, keď je menšia (chýbajúce pole hodnotu prevezme), `!key` prepne boolean, `=key` vyhodnotí JavaScriptový výraz s `doc`. Odpoveď je počet aktualizovaných dokumentov.\n\nExample: Aktualizácia\n```js\nNOSQL('products').update({ '+stock': -1, dtupdated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log(count);\n});\n```\n\nExample: Počítadlá a limity\n```js\nNOSQL('products').update({ '-stock': 1, '*price': 1.1, '>maxorder': 3 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).modify(data)\n\nType: `method`\n\nAlias `update()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Polia na zápis, voliteľne s prefixom. |\n\nReturns: `QueryBuilder` Builder; odpoveď je počet aktualizovaných dokumentov.\n\nZapíše kľúče z `data` do každého vyhovujúceho dokumentu; ostatné polia zostanú. Bez filtra sa aktualizujú všetky dokumenty. Prefixy kľúčov: `+key`, `-key`, `*key` a `/key` pripočítajú, odpočítajú, vynásobia alebo vydelia pole číslom (chýbajúce pole sa počíta ako `0`), `>key` zapíše hodnotu iba vtedy, keď je väčšia ako pole, a `<key` iba vtedy, keď je menšia (chýbajúce pole hodnotu prevezme), `!key` prepne boolean, `=key` vyhodnotí JavaScriptový výraz s `doc`. Odpoveď je počet aktualizovaných dokumentov.\n\nExample: Modify\n```js\nNOSQL('users').modify({ '!active': 1 }).id(id).callback(console.log);\n```\n\n### NOSQL(name).remove()\n\nType: `method`\n\nOdstráni vyhovujúce dokumenty.\n\nReturns: `QueryBuilder` Builder; odpoveď je počet odstránených dokumentov.\n\nOznačí každý vyhovujúci dokument ako odstránený. Bez filtra sa odstránia všetky dokumenty. Odpoveď je počet odstránených dokumentov. Riadky zostávajú v súbore až do `clean()`.\n\nExample: Odstránenie starých logov\n```js\nNOSQL('logs').remove().where('dtcreated', '<', NOW.add('-30 days')).callback(console.log);\n```\n\n### NOSQL(name).clear()\n\nType: `method`\n\nVymaže všetky dokumenty.\n\nReturns: `QueryBuilder` Builder.\n\nVymaže súbor databázy. Nasledujúce vloženie ho vytvorí znova.\n\nExample: Vymazanie\n```js\nNOSQL('cache').clear().callback(function(err) {\n\tconsole.log('empty');\n});\n```\n\n### NOSQL(name).clean()\n\nType: `method`\n\nZhutní súbor databázy.\n\nReturns: `QueryBuilder` Builder.\n\nPrepíše súbor bez riadkov odstránených dokumentov a starých verzií aktualizovaných dokumentov. Zápisy počkajú, kým neskončí.\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### builder.where(name, [comparer], value)\n\nType: `method`\n\nPorovná pole s hodnotou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `comparer` | `String` | no | `'='` | Operátor porovnania. |\n| `value` | `Object` | yes |  | Hodnota na porovnanie. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nOperátory porovnania: `=` (predvolený), `==`, `<>`, `!=`, `>`, `>=`, `<`, `<=`. `=` porovnáva voľne, takže `'5'` vyhovuje `5`. Názov môže byť vnorený (`address.city`). Iba s jedným argumentom funguje ako `query()`.\n\nExample: Where\n```js\nNOSQL('users').find().where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.query(code)\n\nType: `method`\n\nPridá surovú JavaScript podmienku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | JavaScriptový výraz. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPodmienka môže používať `doc`, teda dokument. Podmienka, ktorá obsahuje `require` alebo `global`, nevyhovuje ničomu. Nikdy ju nezostavuj zo vstupu od používateľa.\n\nExample: Surová podmienka\n```js\nNOSQL('orders').find().query('doc.items.length > 2').callback(console.log);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nPridá `where(key, value)` pre každý kľúč objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Polia a hodnoty. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nKaždý kľúč objektu sa musí rovnať svojej hodnote.\n\nExample: Equal\n```js\nNOSQL('users').find().equal({ role: 'admin', active: true }).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltruje podľa poľa `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | Identifikátor alebo identifikátory. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nHodnota pridá `where('id', id)`, pole pridá `in('id', id)`.\n\nExample: Podľa id\n```js\nNOSQL('users').read().id($.params.id).callback($);\n```\n\n### builder.userid(id)\n\nType: `method`\n\nFiltruje podľa poľa `userid`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array|Object` | yes |  | Identifikátor, identifikátory, objekt používateľa alebo `$`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPrijíma reťazec, pole identifikátorov, objekt s `id` alebo `$` (vtedy použije `$.user.id`).\n\nExample: Dokumenty používateľa\n```js\nNOSQL('notes').find().userid($).callback($);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nPole je jednou z 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\nJedna hodnota sa zabalí do poľa. Keď je pole dokumentu typu array, dokument vyhovuje, ak je ktorákoľvek jeho položka jednou z hodnôt. S `key` sa hodnoty berú z tejto vlastnosti objektov vo `value`.\n\nExample: In\n```js\nNOSQL('products').find().in('tags', ['usb', 'wireless']).callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nPole nie je žiadnou z hodnôt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `value` | `Array` | yes |  | Zakázané hodnoty. |\n| `key` | `String` | no |  | Vlastnosť, ktorá sa prečíta z objektov vo `value`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nOpak `in()` s rovnakými argumentmi.\n\nExample: Not in\n```js\nNOSQL('users').find().notin('role', ['guest', 'banned']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nPole je medzi dvoma hodnotami, vrátane nich.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `a` | `Number|Date` | yes |  | Dolná hranica. |\n| `b` | `Number|Date` | yes |  | Horná hranica. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nFunguje s číslami, reťazcami a dátumami.\n\nExample: Between\n```js\nNOSQL('orders').find().between('price', 10, 100).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nVyhľadá text v poli.\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 ohľadu na veľkosť písmen. Predvolene môže byť text kdekoľvek; `'beg'` hľadá na začiatku a `'end'` na konci. Pole typu array vyhovuje, keď vyhovuje ktorákoľvek položka. Znaky `%` sa z textu odstránia.\n\nExample: Vyhľadávanie\n```js\nNOSQL('users').find().search('email', '@example.com', 'end').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nPole má hodnotu.\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\nVyhovuje pravdivá hodnota alebo pole s aspoň jednou položkou.\n\nExample: Contains\n```js\nNOSQL('users').find().contains('photo').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nPole nemá žiadnu hodnotu.\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\nVyhovuje chýbajúca alebo nepravdivá hodnota, alebo prázdne pole.\n\nExample: Empty\n```js\nNOSQL('products').find().empty('tags').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nSpojí skupinu filtrov cez OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(builder), ktorá pridá filtre. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nFunkcia dostane builder (aj ako `this`); filtre pridané vnútri nej tvoria jednu skupinu, v ktorej môže vyhovieť ktorýkoľvek z nich.\n\nExample: Or\n```js\nNOSQL('users').find().or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('owner', true);\n}).callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nPorovná celý rok poľa typu Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Dátumové pole. |\n| `comparer` | `String` | no | `'='` | Operátor porovnania. |\n| `value` | `Number` | yes |  | Hodnota na porovnanie. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nDokumenty, v ktorých pole nie je `Date`, nevyhovujú. Operátory porovnania sú rovnaké ako vo `where()`.\n\nExample: Rok\n```js\nNOSQL('orders').find().year('dtcreated', 2024).callback(console.log);\n```\n\n### builder.month(name, [comparer], value)\n\nType: `method`\n\nPorovná mesiac (1-12) poľa typu Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Dátumové pole. |\n| `comparer` | `String` | no | `'='` | Operátor porovnania. |\n| `value` | `Number` | yes |  | Hodnota na porovnanie. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nDokumenty, v ktorých pole nie je `Date`, nevyhovujú. Operátory porovnania sú rovnaké ako vo `where()`.\n\nExample: Mesiac\n```js\nNOSQL('orders').find().month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.day(name, [comparer], value)\n\nType: `method`\n\nPorovná deň v mesiaci (1-31) poľa typu Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Dátumové pole. |\n| `comparer` | `String` | no | `'='` | Operátor porovnania. |\n| `value` | `Number` | yes |  | Hodnota na porovnanie. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nDokumenty, v ktorých pole nie je `Date`, nevyhovujú. Operátory porovnania sú rovnaké ako vo `where()`.\n\nExample: Deň\n```js\nNOSQL('orders').find().day('dtcreated', 1).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 |  | Názvy polí oddelené čiarkou. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nZoznam polí oddelených čiarkou, ktoré sa majú vrátiť, alebo polí s `-`, ktoré sa majú vynechať (`'-password,-token'`).\n\nExample: Polia\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nZoradí výsledok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `desc` | `Boolean|String` | no | `false` | `true` alebo `'desc'` pre zostupné poradie. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nZavolaj ju viackrát, ak chceš zoraďovať podľa viacerých polí. Vnorené polia fungujú (`address.city`). Bez zoradenia idú ako prvé naposledy zapísané dokumenty.\n\nExample: Zoradenie\n```js\nNOSQL('articles').find().sort('dtcreated', true).sort('title').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nObmedzí počet dokumentov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximálny počet. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nČítanie sa zastaví hneď, ako sa nájde dosť dokumentov, pokiaľ výsledok nie je zoradený.\n\nExample: Take\n```js\nNOSQL('logs').find().take(50).callback(console.log);\n```\n\n### builder.limit(count)\n\nType: `method`\n\nAlias `take()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximálny počet. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nObmedzí počet dokumentov.\n\nExample: Limit\n```js\nNOSQL('logs').find().limit(50).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nPreskočí dokumenty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Počet na preskočenie. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPreskočí prvých `count` vyhovujúcich dokumentov.\n\nExample: Skip\n```js\nNOSQL('logs').find().skip(100).take(50).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nVráti iba jeden dokument.\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nNastaví `take(1)` a odpoveď je objekt (alebo `undefined`) namiesto poľa.\n\nExample: First\n```js\nNOSQL('users').find().where('email', email).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nNastaví skip z čísla stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Číslo stránky od 1. |\n| `limit` | `Number` | no |  | Počet dokumentov na stránku. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nČísla stránok začínajú od 1. `limit` nastaví `take()`; bez neho sa použije aktuálna hodnota `take()`.\n\nExample: Stránka\n```js\nNOSQL('articles').find().sort('dtcreated', true).page(2, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nNastaví skip a take z nedôveryhodných hodnôt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Číslo stránky od 1. |\n| `limit` | `Number|String` | yes |  | Počet dokumentov na stránku. |\n| `maxlimit` | `Number` | no |  | Maximálny a predvolený limit. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPrijíma reťazce (napríklad z query stringu). Stránka pod 1 sa zmení na 1; `limit` je obmedzený na `maxlimit` a pri chýbajúcom limite sa použije `maxlimit`.\n\nExample: Stránkovanie v akcii\n```js\nNOSQL('articles').find().sort('dtcreated', true).paginate($.query.page, $.query.limit, 50).callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nVypíše skompilovanú operáciu.\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nZaloguje súbor, operáciu a skompilovaný filter do konzoly s prefixom `-- NoSQL -->`.\n\nExample: Debug\n```js\nNOSQL('users').find().where('age', '>', 18).debug().callback(console.log);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nPrečíta výsledok cez callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), alebo `$`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\n`fn(err, response)` sa zavolá, keď operácia skončí. V akcii odovzdaj `$`, ak chceš poslať odpoveď alebo chybu klientovi. `pipe()` je alias.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items) {\n\tif (err)\n\t\treturn console.error(err);\n\tconsole.log(items.length);\n});\n```\n\n### builder.pipe(fn)\n\nType: `method`\n\nAlias `callback()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | function(err, response), alebo `$`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\n`fn(err, response)`, alebo `$`.\n\nExample: Pipe\n```js\nNOSQL('users').find().pipe($);\n```\n\n### builder.promise([$])\n\nType: `method`\n\nVráti výsledok ako Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Voľby akcie. |\n\nReturns: `Promise` Vyrieši sa s odpoveďou.\n\nPromise sa vyrieši s odpoveďou. Pri chybe sa zamietne, alebo keď je zadané `$`, chyba sa pošle do `$.invalid()`.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nZavolá funkciu s odpoveďou, chyby idú do `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Voľby akcie. |\n| `fn` | `Function` | yes |  | function(response, param). |\n| `param` | `Object` | no |  | Hodnota odovzdaná do `fn`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPri úspechu sa zavolá `fn(response, param)`; chyba sa pošle do `$.invalid()`.\n\nExample: Done\n```js\nNOSQL('users').read().id(id).error('Not found').done($, function(user) {\n\t$.callback({ name: user.name });\n});\n```\n\n### builder.data(fn)\n\nType: `method`\n\nZavolá funkciu iba s odpoveďou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(response). |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\n`fn(response)` sa zavolá iba vtedy, keď nenastane chyba. Dá sa kombinovať s `callback()`.\n\nExample: Data\n```js\nNOSQL('users').find().data(function(items) {\n\tconsole.log(items);\n});\n```\n\n### builder.fail(fn)\n\nType: `method`\n\nZavolá funkciu iba s chybou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | function(err). |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\n`fn(err)` sa zavolá iba vtedy, keď operácia zlyhá.\n\nExample: Fail\n```js\nNOSQL('users').read().id(id).error('Not found').fail(function(err) {\n\tconsole.log(err);\n});\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nZmení prázdny výsledok na chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String|Number` | yes |  | Chybové hlásenie. |\n| `reverse` | `Boolean` | no | `false` | Zlyhať, keď výsledok nie je prázdny. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nOperácia zlyhá s `message`, keď je odpoveď prázdna: `undefined`, prázdne pole alebo `0` aktualizovaných či odstránených dokumentov. S `reverse` zlyhá, keď odpoveď nie je prázdna, napríklad na zastavenie duplikátu. `err()` je alias.\n\nExample: Nenájdené a duplikát\n```js\nNOSQL('users').read().id(id).error('Not found').callback($);\n\nNOSQL('users').read().where('email', email).error('E-mail is already used', true).callback(function(err) {\n\t// err when the e-mail exists\n});\n```\n\n### DATA.count('nosql/' + name)\n\nType: `method`\n\nSpočíta vyhovujúce dokumenty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov databázy s prefixom `nosql/`. |\n\nReturns: `QueryBuilder` Builder; odpoveď je `{ count }`.\n\nPoužíva NoSQL engine cez globálny query builder. Odpoveď je objekt `{ count: Number }`.\n\nExample: Počet\n```js\nDATA.count('nosql/users').where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### DATA.check('nosql/' + name)\n\nType: `method`\n\nOverí, či dokument existuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov databázy s prefixom `nosql/`. |\n\nReturns: `QueryBuilder` Builder; odpoveď je Boolean.\n\nZastaví sa pri prvom vyhovujúcom dokumente. Odpoveď je `true` alebo `false`.\n\nExample: Kontrola\n```js\nDATA.check('nosql/users').where('email', email).callback(function(err, exists) {\n\tconsole.log(exists);\n});\n```\n\n### DATA.scalar('nosql/' + name, type, key, [key2])\n\nType: `method`\n\nVypočíta súčet, minimum, maximum, počet alebo skupiny.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov databázy s prefixom `nosql/`. |\n| `type` | `String` | yes |  | `'sum'`, `'min'`, `'max'`, `'avg'`, `'count'` alebo `'group'`. |\n| `key` | `String` | no | `'*'` | Pole, ktoré sa počíta alebo podľa ktorého sa zoskupuje. `'*'` (predvolené) počíta každý dokument ako `1`. |\n| `key2` | `String` | no |  | Pole, ktoré sa sčíta v každej skupine (iba s `'group'`). |\n\nReturns: `QueryBuilder` Builder; odpoveď je `{ value }` alebo Array skupín.\n\nS `type` `'sum'`, `'min'`, `'max'`, `'avg'` alebo `'count'` je odpoveď `{ value }` pre pole `key` (dokumenty bez tohto poľa sa preskočia; `min` a `max` fungujú aj s dátumami). `avg` je súčet vydelený počtom, alebo `null`, keď nevyhovuje žiadny dokument. Bez `key` (alebo s `'*'`) sa každý vyhovujúci dokument počíta ako `1`, takže `DATA.scalar('nosql/orders', 'count')` spočíta dokumenty. S `'group'` je odpoveď pole `{ <key>: value, value: count }`; s `key2` sa hodnoty `key2` v každej skupine namiesto počítania sčítajú.\n\nExample: Súčet\n```js\nDATA.scalar('nosql/orders', 'sum', 'price').where('paid', true).callback(function(err, response) {\n\tconsole.log(response.value);\n});\n```\n\nExample: Skupina\n```js\nDATA.scalar('nosql/orders', 'group', 'status').callback(function(err, groups) {\n\t// [{ status: 'paid', value: 12 }, { status: 'new', value: 3 }]\n});\n```\n\nExample: Priemer a počet\n```js\nDATA.scalar('nosql/orders', 'avg', 'price').callback(function(err, response) {\n\tconsole.log(response.value); // the average price\n});\n\nDATA.scalar('nosql/orders', 'count').where('paid', true).callback(console.log);\n```\n\n### $dirdatabases : String\n\nType: `config`\n\nPriečinok databázových súborov.\n\nReturns: `String`\n\nPriečinok, v ktorom `NOSQL()` uchováva svoje súbory `.nosql`. Predvolene je to `databases` v koreňovom priečinku aplikácie.\n\nExample: config\n```text\n$dirdatabases : /var/data/myapp/\n```\n","entries":[{"type":"method","name":"NOSQL(name)","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"nosql.insert(doc)","signature":"NOSQL(name).insert(doc)","since":"","deprecated":false},{"type":"method","name":"nosql.find()","signature":"NOSQL(name).find()","since":"","deprecated":false},{"type":"method","name":"nosql.read()","signature":"NOSQL(name).read()","since":"","deprecated":false},{"type":"method","name":"nosql.update(data)","signature":"NOSQL(name).update(data)","since":"","deprecated":false},{"type":"method","name":"nosql.modify(data)","signature":"NOSQL(name).modify(data)","since":"","deprecated":false},{"type":"method","name":"nosql.remove()","signature":"NOSQL(name).remove()","since":"","deprecated":false},{"type":"method","name":"nosql.clear()","signature":"NOSQL(name).clear()","since":"","deprecated":false},{"type":"method","name":"nosql.clean()","signature":"NOSQL(name).clean()","since":"","deprecated":false},{"type":"method","name":"builder.where(name, [comparer], value)","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query(code)","signature":"builder.query(code)","since":"","deprecated":false},{"type":"method","name":"builder.equal(obj)","signature":"builder.equal(obj)","since":"","deprecated":false},{"type":"method","name":"builder.id(id)","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.userid(id)","signature":"builder.userid(id)","since":"","deprecated":false},{"type":"method","name":"builder.in(name, value, [key])","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin(name, value, [key])","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between(name, a, b)","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search(name, value, [where])","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains(name)","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty(name)","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.or(fn)","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.year(name, [comparer], value)","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.month(name, [comparer], value)","signature":"builder.month(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.day(name, [comparer], value)","signature":"builder.day(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.fields(fields)","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort(name, [desc])","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take(count)","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.limit(count)","signature":"builder.limit(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip(count)","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page(page, [limit])","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate(page, limit, [maxlimit])","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback(fn)","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.pipe(fn)","signature":"builder.pipe(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise([$])","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.done($, fn, [param])","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.data(fn)","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.fail(fn)","signature":"builder.fail(fn)","since":"","deprecated":false},{"type":"method","name":"builder.error(message, [reverse])","signature":"builder.error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"DATA.count('nosql/name')","signature":"DATA.count('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.check('nosql/name')","signature":"DATA.check('nosql/' + name)","since":"","deprecated":false},{"type":"method","name":"DATA.scalar('nosql/name', type, key, [key2])","signature":"DATA.scalar('nosql/' + name, type, key, [key2])","since":"","deprecated":false},{"type":"config","name":"$dirdatabases","signature":"$dirdatabases : String","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:12.159Z"}
{"id":"JafwRq1fx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() and the methods of the QueryBuilder.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() and the methods of the QueryBuilder.\n\nThe global `DATA`, the `DB()` chain and the adapters registered with `NEWDB()`, together with every method of the QueryBuilder that they return. An introduction with examples is in the guide [QueryBuilder](../../guides/querybuilder/).\n\n## API\n\n### DATA\n\nType: `property`\n\nThe global database object that starts each query immediately.\n\nReturns: `Database`\n\nA shared instance of the database controller. Every operation on it (`find()`, `insert()`…) creates a QueryBuilder and executes it on the next tick, independently of other queries. Use `DB()` when you need several queries in a sequence with one result.\n\nExample: Find rows\n```js\nDATA.find('users').where('isremoved', false).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### DB()\n\nType: `method`\n\nCreates a database object that runs queries in sequence.\n\nReturns: `Database` A new database controller.\n\nEach operation you call on the returned object is queued and executed in order after the current tick. The final response is the result of the last query, or an object filled by `set(name)` of each query. The first error stops the chain and is passed to `callback()`. If you add a query after the chain finished, the chain starts again.\n\nExample: Two queries\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nRegisters or removes a database adapter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | The connection name. |\n| `fn` | `Function` | no |  | `function(filter, callback)` that executes the query. Omit it to remove the adapter. |\n\nThe adapter executes the queries of the connection `name`. It is called with `this` as the internal query object, `filter` as the options of the query (`exec`, `table`, `filter`, `fields`, `sort`, `take`, `skip`, `payload`, `upsert`, `returning`, `first`, `language`, `query`, `params`, `scalar`, `command`, `primarykey`, `schema`, `checksum`, `debug`) and a callback `(err, response)`. The `checksum` is a short hash of the structure of the filter, useful as a cache key for prepared queries. The adapter `*` is used for connections without their own adapter. Without `fn` the adapter `name` is removed; `name` is required then. The framework registers the adapter `nosql` for the embedded NoSQL files, and `DATA.init()` registers adapters for PostgreSQL (see [PostgreSQL](../../reference/postgresql/)).\n\nExample: A logging adapter\n```js\nNEWDB('default', function(filter, callback) {\n\tconsole.log(filter.exec, filter.table, filter.filter);\n\tcallback(null, filter.exec === 'list' ? { items: [], count: 0 } : []);\n});\n```\n\n### db.find(table)\n\nType: `method`\n\nFinds all rows that match the filter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `find`. The response is the array that the adapter returns. Alias: `db.all()`.\n\nExample: Find\n```js\nDATA.find('products').where('price', '>', 10).sort('name').callback(console.log);\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. `connection/table` selects a connection; without a slash the connection is `default`. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `read`, `take` 1 and the `first` option. When the adapter returns an array, the response is its first item or `null`. Alias: `db.one()`.\n\nExample: Read by id\n```js\nDATA.read('users').id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nReads one page of rows with paging metadata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `list`, `skip` 0 and `take` 100. The adapter returns an object with the rows and the total `count`; the `nosql` adapter returns `{ items, count }`, where `count` is the number of all matching documents. The QueryBuilder adds `page`, `limit` and `pages` to that object.\n\nExample: A page\n```js\nDATA.list('products').page(2, 20).callback(function(err, response) {\n\tconsole.log(response.items, response.count, response.pages);\n});\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. `connection/table` selects a connection; without a slash the connection is `default`. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `check`, `take` 1 and the `first` option. The adapter answers whether a row matches (the `nosql` adapter returns `true` or `false`).\n\nExample: Unique e-mail\n```js\nDATA.check('users').where('email', model.email).error('@(E-mail already exists)', true).callback($);\n```\n\n### db.count(table)\n\nType: `method`\n\nCounts the rows that match the filter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `count`. The adapter decides the form of the response.\n\nExample: Count\n```js\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nComputes an aggregate value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |\n| `type` | `String` | yes |  | The aggregate, for example `sum`, `avg`, `min`, `max`, `count`. |\n| `key` | `String` | no | `'*'` | The column. |\n| `key2` | `String` | no |  | A second column to group by `key`. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `scalar` and the option `scalar = { type, key, key2 }`. `key` defaults to `*`. With `key2` the adapter groups the values of `key2` by `key`. The types are interpreted by the adapter; the `nosql` adapter supports `min`, `max`, `sum`, `avg` and `count` (without `key2`; with the default `*` each document counts as `1`), and `group` (`key2` sums the values of `key2` per `key`).\n\nExample: Sum\n```js\nDATA.scalar('orders', 'sum', 'price').where('status', 'paid').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. `connection/table` selects a connection; without a slash the connection is `default`. |\n| `data` | `Object` | yes |  | The row to insert. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `insert` and `data` as the payload. Alias: `db.ins()`.\n\nExample: Insert\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nUpdates the rows that match the filter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |\n| `data` | `Object` | yes |  | The columns to change. |\n| `upsert` | `Boolean` | no | `false` | Insert the payload when nothing was updated. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `update` and `data` as the payload. With `upsert` set to `true`, an update that returns no result (or an empty `returning` result) is executed again as an `insert` of the same payload with no conditions; `builder.insert(fn)` can change the payload before that. Aliases: `db.modify()`, `db.mod()`, `db.upd()`.\n\nExample: Update\n```js\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.remove(table)\n\nType: `method`\n\nRemoves the rows that match the filter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. `connection/table` selects a connection; without a slash the connection is `default`. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `remove`. Alias: `db.rem()`.\n\nExample: Remove\n```js\nDATA.remove('users').id('u1').callback(console.log);\n```\n\n### db.query([connection], query, [params])\n\nType: `method`\n\nRuns a raw query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | The connection name. |\n| `query` | `String` | yes |  | The raw query. |\n| `params` | `Object|Array` | no |  | Parameters for the adapter. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `query` and the options `query` and `params`. With one argument (or when the second argument is an object) the query runs on the connection `default`; otherwise the first argument is the connection name. The adapter decides the syntax of the query and of the parameters.\n\nExample: Raw SQL\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE isremoved=FALSE').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. `connection/table` selects a connection; without a slash the connection is `default`. |\n\nReturns: `QueryBuilder`\n\nReturns a QueryBuilder with the operation `truncate`. Alias: `db.clear()`. `db.drop(table)` works the same with the operation `drop`, and `db.command(table, name)` with the operation `command` and the option `command = name`, for custom commands of the adapter.\n\nExample: Truncate\n```js\nDATA.truncate('logs/requests').callback(console.log);\n```\n\n### db.exec(filter, callback)\n\nType: `method`\n\nRuns a query described by a plain object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | The options, for example `{ exec: 'find', table: 'users', take: 10 }`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\n`filter.exec` selects the operation (`find`, `list`, `read`, `count`, `truncate`, `drop`, `remove`, `insert`, `update`, `scalar`, `command` or `query`) and `filter.table` the table; every other key is copied into the options of the query. For `query` the raw query is in `filter.query`.\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'users', take: 5 }, console.log);\n```\n\n### db.load([connection], options)\n\nType: `method`\n\nCreates a query from prepared options.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | The connection name. |\n| `options` | `Object` | yes |  | The prepared options. |\n\nReturns: `QueryBuilder`\n\nCreates a QueryBuilder from an object with `table`, `exec`, `fields`, `skip`, `take`, `query`, `sort`, `payload`, `upsert`, `returning` and `filter` (an array of filter items). The connection defaults to `default`.\n\nExample: Load\n```js\nDATA.load({ table: 'users', exec: 'find', take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nSets the defaults for localized columns.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | The prefix put before the language code. |\n| `skip` | `String` | yes |  | A language that means \"no language\". |\n\nReturns: `Database`\n\nSets the global prefix and the language to skip that `builder.language()` uses when it gets no own values. The default skipped language is `_`.\n\nExample: Defaults\n```js\nDATA.language('_', 'en');\n```\n\n### db.debug()\n\nType: `method`\n\nSets the debug option on every query of a DB() chain.\n\nReturns: `Database`\n\nEach query created after this call gets the option `debug = true`, so an adapter that supports it can log the generated query.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('users');\ndb.callback(console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nSets the callback of a DB() chain.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` or the `$` of an action. |\n\nReturns: `Database`\n\nThe callback gets the first error or the final response. Pass `$` of an action instead of a function to answer the action. Alias: `db.pipe()`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.callback($);\n```\n\n### db.promise([$])\n\nType: `method`\n\nReturns a promise of a DB() chain.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | The `$` of an action. |\n\nReturns: `Promise`\n\nThe promise resolves with the final response. On error it is rejected, or, with `$`, the error goes to `$.invalid()`.\n\nExample: Await\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\nvar response = await db.promise($);\n```\n\n### db.done($, fn)\n\nType: `method`\n\nCalls fn on success and $.invalid() on error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `Database`\n\nEnds a DB() chain inside an action: an error is passed to `$.invalid()`, a response to `fn(response)`.\n\nExample: Done\n```js\nvar db = DB();\ndb.read('users').id($.params.id).set('user');\ndb.done($, function(response) {\n\t$.callback(response.user);\n});\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nAdds a comparison.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=`, `<=`. |\n| `value` | `Object` | yes |  | The value. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nWithout `comparer` the comparison is `=`. `==` becomes `=` and `!=` becomes `<>`. With only `name`, the argument is a raw condition, the same as `query()`.\n\nExample: Where\n```js\nDATA.find('products').where('price', '>=', 10).where('ispublished', true).callback(console.log);\n```\n\n### builder.id(value)\n\nType: `method`\n\nFilters by the column id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | An id or a list of ids. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\n`where('id', value)`, or `in('id', value)` when the value is an array.\n\nExample: Id\n```js\nDATA.read('users').id('u1').callback(console.log);\n```\n\n### builder.userid(value)\n\nType: `method`\n\nFilters by the column userid.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Object` | yes |  | An id, a list, a user or `$`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nAccepts an id, an array of ids (`in`), a user object (its `id`) or an object with `user` such as `$` of an action (its `user.id`).\n\nExample: Rows of the current user\n```js\nDATA.find('orders').userid($).callback($);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nAdds one equality per key.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Column names and values. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nCalls `where(key, value)` for every key of the object.\n\nExample: Equal\n```js\nDATA.find('users').equal({ role: 'admin', isremoved: false }).callback(console.log);\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` | yes |  | The values. |\n| `key` | `String` | no |  | A property to read from each object of `value`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nA single value is wrapped in an array. With `key`, `value` is an array of objects and the values are taken from their property `key`.\n\nExample: In\n```js\nDATA.find('users').in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nThe column is none of the values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `value` | `Array` | yes |  | The values. |\n| `key` | `String` | no |  | A property to read from each object of `value`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nThe opposite of `in()`, with the same arguments.\n\nExample: Not in\n```js\nDATA.find('users').notin('role', ['guest']).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 same QueryBuilder, for chaining.\n\nAdds a `between` item with `a` and `b`.\n\nExample: Last week\n```js\nDATA.find('orders').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nSearches text in a column.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `value` | `String` | yes |  | The text. |\n| `where` | `String` | no |  | `beg` or `end`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nThe column contains `value`. With `where` set to `beg` the text must be at the beginning, with `end` at the end.\n\nExample: Search\n```js\nDATA.find('products').search('name', 'phone').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nJoins a group of conditions with OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nThe filters added inside `fn` form one group. `fn` is called with the builder as `this` and as the argument. An empty group is ignored.\n\nExample: Or\n```js\nDATA.find('users').or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('role', 'editor');\n}).callback(console.log);\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 same QueryBuilder, for chaining.\n\nAdds a `contains` item: the column is not empty (for arrays: it has items). `empty(name)` is the opposite: the column has no value.\n\nExample: Contains\n```js\nDATA.find('users').contains('phone').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 comparer. |\n| `value` | `Array|String` | yes |  | The values. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nAdds an `array` item. The default comparer is `&&` (the arrays overlap); the adapter interprets it.\n\nExample: Tags\n```js\nDATA.find('products').array('tags', ['sale', 'new']).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 comparer. |\n| `value` | `Number` | yes |  | The value of the part. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nCompares the year of a date column. `month()`, `day()`, `hour()` and `minute()` have the same arguments and compare that part. The default comparer is `=`.\n\nExample: Date parts\n```js\nDATA.find('orders').year('dtcreated', 2024).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(value)\n\nType: `method`\n\nAdds a raw condition.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The raw condition. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nThe text is passed to the adapter as it is, so it must be in the syntax of the engine.\n\nExample: Raw\n```js\nDATA.find('users').query('age > 18').callback(console.log);\n```\n\n### builder.join(name, table, type, a, b)\n\nType: `method`\n\nAdds a join item for the adapter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the join. |\n| `table` | `String` | yes |  | The joined table. |\n| `type` | `String` | yes |  | The join type. |\n| `a` | `String` | yes |  | The column of the main table. |\n| `b` | `String` | yes |  | The column of the joined table. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nAdds `{ type: 'join', name, table, join: type, on: [a, b] }` to the filter. Whether joins are supported is up to the adapter.\n\nExample: Join\n```js\nDATA.find('orders').join('user', 'users', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nAdds a permission condition for the adapter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column with permissions. |\n| `type` | `String` | yes |  | The letters `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Roles or groups. |\n| `userid` | `String` | no |  | The id of the user. |\n| `required` | `Boolean` | no | `true` | The permission is required. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nEach letter of `type` (`R` read, `W` write, `D` delete) is combined with each item of `value`, so `permit('permissions', 'RW', ['admin'])` gives `['Radmin', 'Wadmin']`. The item also carries `userid` and `required` (default `true`).\n\nExample: Permit\n```js\nDATA.find('documents').permit('permissions', 'R', $.user.roles, $.user.id).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 same QueryBuilder, for chaining.\n\nA comma-separated list of columns.\n\nExample: Fields\n```js\nDATA.find('users').fields('id,name,email').callback(console.log);\n```\n\n### builder.gridfields(fields, [allowed])\n\nType: `method`\n\nSelects the columns from an untrusted list.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | no |  | The requested fields, for example `id,name`. Can be empty or `undefined`. |\n| `allowed` | `String` | no |  | The fields that may be selected, for example `id,name,price`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nTakes a comma-separated list, usually `$.query.fields`, and selects the fields that are also in `allowed`. Quotes, backticks, `|` and spaces are removed first. Empty names are skipped. When the list is empty or missing, or none of the fields is allowed, the selection does not change (all columns). Without `allowed` every field of the list is selected.\n\nExample: Fields from the query string\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nAdds a sort column.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `desc` | `Boolean|String` | no | `false` | `true` or `desc` for descending. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\n`desc` can be `true` or `'desc'`; anything else sorts ascending. Several calls add more columns.\n\nExample: Sort\n```js\nDATA.find('products').sort('price', true).sort('name').callback(console.log);\n```\n\n### builder.gridsort(sort, [map])\n\nType: `method`\n\nAdds sort columns from a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | The sort string. |\n| `map` | `Object` | no |  | Field names mapped to columns. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nThe string has the form `name_asc,dtcreated_desc`; a name without a suffix is ascending. `map` can rename the fields to columns.\n\nExample: Gridsort\n```js\nDATA.find('products').gridsort('price_desc,name').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nSets the maximum number of rows.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | The number of rows. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nAlias: `limit()`. `first()` sets `take` to 1 and returns only the first row. `skip(count)` sets the number of rows to skip.\n\nExample: Take\n```js\nDATA.find('products').take(10).callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSelects a 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 same QueryBuilder, for chaining.\n\nSets `skip` to `(page - 1) * take`. With `limit` it also sets `take` first.\n\nExample: Page\n```js\nDATA.list('products').page(3, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSelects a page from untrusted values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | The page. |\n| `limit` | `Number|String` | yes |  | Rows per page. |\n| `maxlimit` | `Number` | no |  | The highest allowed limit. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nConverts `page` and `limit` to numbers (strings from a query string work), uses page 1 when the page is missing, zero or negative, keeps the limit under `maxlimit` and uses `maxlimit` when no limit is given.\n\nExample: From a query string\n```js\nDATA.list('products').paginate($.query.page, $.query.limit, 100).callback($);\n```\n\n### builder.autoquery(query, schema, [defsort], [maxlimit])\n\nType: `method`\n\nBuilds fields, filters, sort and paging from a query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | The query string, usually `$.query`. |\n| `schema` | `String` | yes |  | The allowed fields and types. |\n| `defsort` | `String` | no |  | The default sort, for example `dtcreated_desc`. |\n| `maxlimit` | `Number` | no |  | Enables paging with this highest limit. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\n`schema` lists the allowed fields as `name:type` separated by commas (types: `string`, `number`, `date`, `boolean`, `[string]`, `json`; the default is `string`), or `@SchemaName` to take them from a JSON schema. `query.fields` selects among the allowed fields (all of them when it is missing), each allowed field is filtered with `gridfilter()`, `query.sort` (`name_asc`, `name_desc`) sorts by allowed fields or `defsort` is used, and with `maxlimit` `query.page` and `query.limit` go to `paginate()`. Fields that are not in the schema are ignored. Columns selected with `fields()` before `autoquery()` stay selected, and the fields of the query string are added to them for this query only.\n\nExample: A grid\n```js\nDATA.list('products').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($);\n```\n\n### builder.autoqueryjson($, column, schema, [defsort], [maxlimit])\n\nType: `method`\n\nBuilds fields, filters, sort and paging for properties of a JSON column.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action, or the query string. |\n| `column` | `String` | yes |  | The JSON column. |\n| `schema` | `String` | yes |  | The allowed properties and types. |\n| `defsort` | `String` | no |  | The default sort, for example `weight_desc`. |\n| `maxlimit` | `Number` | no |  | Enables paging with this highest limit. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nWorks like `autoquery()`, but the fields are properties stored in the JSON column `column`. `$` is the `$` of an action (its `query` is used) or the query string itself. `schema` lists the properties as `name:type` separated by commas (types: `string`, `number`, `boolean`, `date`, `[string]`; the default is `string`). The QueryBuilder gives the adapter each property as the name `json:column:property:type` in the fields, the filter and the sort, and the adapter translates it into its own syntax; the PostgreSQL adapter reads the property with `->>` and converts it to its type. `column` may contain only letters, digits and `_`, otherwise the method throws an error; properties with other characters are ignored. It can follow `autoquery()` on the same query.\n\nExample: Columns and JSON properties\n```js\nDATA.list('tbl_product').autoquery($.query, 'id,name,price:number', 'name_asc', 100).autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date').callback($);\n```\n\n### builder.gridfilter(name, query, [type], [column])\n\nType: `method`\n\nAdds a filter from a query string value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The key in `query`. |\n| `query` | `Object` | yes |  | The query string. |\n| `type` | `String` | no | `'string'` | The type of the value. |\n| `column` | `String` | no |  | The column, when it differs from `name`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nReads `query[name]` and adds a condition by its form: `a - b` is `between`, `a,b` is an OR of searches for text and `in` for other types, `=a,b` is `in` with exact texts, `=a` an exact match, a plain text a `search`, `>v` and `<v` comparisons. For dates `today`, `yesterday` and a date select the whole day, a 4-digit number the year and a small number the month. `type` is `string`, `number`, `date`, `boolean`, `[string]` (array filter) or `json` (search). Empty values add nothing.\n\nExample: Gridfilter\n```js\nDATA.find('orders').gridfilter('price', $.query, 'number').gridfilter('dtcreated', $.query, 'date').callback($);\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nSets the language for localized columns.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | The language or an object with `language`. |\n| `prefix` | `String` | no |  | The prefix. |\n| `skip` | `String` | no |  | A language that means \"no language\". |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nSets the option `language` to `prefix + value`. `value` can be an object with `language` (such as `$`). When `value` equals `skip` the language is empty. Without `prefix` and `skip` the defaults of `db.language()` apply. The `nosql` adapter replaces a trailing `§` in column names with the language.\n\nExample: Language\n```js\nDATA.find('products').fields('id,name§').language($).callback($);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nAsks the adapter to return columns of the changed rows.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | For example `id,name`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nA comma-separated list stored in the option `returning`. With an upsert, an empty returned result means \"nothing was updated\".\n\nExample: Returning\n```js\nDATA.update('users', { name: 'Lucia' }).id('u1').returning('id,name').callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPrepares the payload of an upsert insert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(payload, param)`. |\n| `param` | `Object` | no |  | A value passed to `fn`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nWith `update(table, data, true)`, `fn(payload, param)` is called before the payload is inserted, so you can add values that only a new row needs.\n\nExample: Upsert\n```js\nDATA.update('stats', { dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nTurns an empty result into an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | The error, for example `@(User not found)`. |\n| `reverse` | `Boolean` | no | `false` | Fail when there is a result. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nWhen the response is empty (no value, or an empty array for queries that do not take one row), the query fails with `message`. With `reverse` set to `true`, a non-empty response fails. Alias: `err()`.\n\nExample: Not found\n```js\nDATA.read('users').id($.params.id).error('@(User not found)').callback($);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nSets the callback of the query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` or `$`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\n`fn(err, response)` is called when the query finishes. Pass `$` of an action to answer the action with the result. Alias: `pipe()`. `data(fn)` sets a callback only for success (`fn(response)`) and `fail(fn)` one only for errors (`fn(err)`).\n\nExample: Callback\n```js\nDATA.find('users').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nReturns a promise of the query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | The `$` of an action. |\n\nReturns: `Promise`\n\nResolves with the response. On error the promise is rejected with the error (an error object of the adapter gets the name `QueryBuilder(table --> operation)`), or, with `$`, the error goes to `$.invalid()`.\n\nExample: Await\n```js\nvar user = await DATA.read('users').id('u1').promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nCalls fn on success and $.invalid() on error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | A value passed to `fn`. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nOn success `fn(response, param)` is called; an error goes to `$.invalid()`.\n\nExample: Done\n```js\nDATA.read('users').id($.params.id).done($, function(user) {\n\t$.callback({ id: user.id, name: user.name });\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 `$` of an action. |\n| `message` | `String` | no |  | The message. |\n| `type` | `String` | no |  | The type of the record. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nAfter a successful query, calls `$.audit(message, type)`. Placeholders such as `{data.name}` in the message are filled from the payload, `{user.name}` from the user.\n\nExample: Audit\n```js\nDATA.insert('products', model).audit($, 'Created product {data.name}').callback($);\n```\n\n### builder.set(name)\n\nType: `method`\n\nStores the result under a key of the DB() response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The key. |\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nIn a `DB()` chain the response becomes an object and this result is saved as `response[name]`. `nobind()` keeps the result out of the response completely.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.count('orders').where('userid', 'u1').set('orders');\ndb.callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nSets the debug option of the query.\n\nReturns: `QueryBuilder` The same QueryBuilder, for chaining.\n\nSets `debug = true` in the options, so an adapter that supports it can log the query. `primarykey(name)` and `schema(name)` set the options `primarykey` and `schema` in the same way, for adapters that use them.\n\nExample: Debug\n```js\nDATA.find('users').debug().callback(console.log);\n```\n","entries":[{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count(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([connection], query, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.exec()","signature":"db.exec(filter, callback)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([connection], options)","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.promise()","signature":"db.promise([$])","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, fn)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.userid()","signature":"builder.userid(value)","since":"","deprecated":false},{"type":"method","name":"builder.equal()","signature":"builder.equal(obj)","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.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, type, 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.gridfields()","signature":"builder.gridfields(fields, [allowed])","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.gridsort()","signature":"builder.gridsort(sort, [map])","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.autoquery()","signature":"builder.autoquery(query, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autoqueryjson()","signature":"builder.autoqueryjson($, column, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, query, [type], [column])","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(message, [reverse])","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.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRq1fx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() und die Methoden des QueryBuilders.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() und die Methoden des QueryBuilders.\n\nDas globale `DATA`, die `DB()`-Kette und die mit `NEWDB()` registrierten Adapter, zusammen mit allen Methoden des QueryBuilders, den sie zurückgeben. Eine Einführung mit Beispielen findest du im Leitfaden [QueryBuilder](../../guides/querybuilder/).\n\n## API\n\n### DATA\n\nType: `property`\n\nDas globale Datenbankobjekt, das jede Abfrage sofort startet.\n\nReturns: `Database`\n\nEine gemeinsame Instanz des Datenbank-Controllers. Jede Operation darauf (`find()`, `insert()`…) erstellt einen QueryBuilder und führt ihn im nächsten Tick aus, unabhängig von anderen Abfragen. Verwende `DB()`, wenn du mehrere Abfragen nacheinander mit einem Ergebnis brauchst.\n\nExample: Zeilen finden\n```js\nDATA.find('users').where('isremoved', false).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### DB()\n\nType: `method`\n\nErstellt ein Datenbankobjekt, das Abfragen nacheinander ausführt.\n\nReturns: `Database` Ein neuer Datenbank-Controller.\n\nJede Operation, die du auf dem zurückgegebenen Objekt aufrufst, wird in eine Warteschlange gestellt und nach dem aktuellen Tick der Reihe nach ausgeführt. Die endgültige Antwort ist das Ergebnis der letzten Abfrage oder ein Objekt, das von `set(name)` jeder Abfrage gefüllt wird. Der erste Fehler stoppt die Kette und wird an `callback()` übergeben. Fügst du eine Abfrage hinzu, nachdem die Kette beendet ist, startet die Kette erneut.\n\nExample: Zwei Abfragen\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nRegistriert oder entfernt einen Datenbankadapter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Der Verbindungsname. |\n| `fn` | `Function` | no |  | `function(filter, callback)`, die die Abfrage ausführt. Lass sie weg, um den Adapter zu entfernen. |\n\nDer Adapter führt die Abfragen der Verbindung `name` aus. Er wird mit `this` als internem Abfrageobjekt, `filter` als Optionen der Abfrage (`exec`, `table`, `filter`, `fields`, `sort`, `take`, `skip`, `payload`, `upsert`, `returning`, `first`, `language`, `query`, `params`, `scalar`, `command`, `primarykey`, `schema`, `checksum`, `debug`) und einem Callback `(err, response)` aufgerufen. `checksum` ist ein kurzer Hash der Struktur des Filters, nützlich als Cache-Schlüssel für vorbereitete Abfragen. Der Adapter `*` wird für Verbindungen ohne eigenen Adapter verwendet. Ohne `fn` wird der Adapter `name` entfernt; `name` ist dann erforderlich. Das Framework registriert den Adapter `nosql` für die eingebetteten NoSQL-Dateien, und `DATA.init()` registriert Adapter für PostgreSQL (siehe [PostgreSQL](../../reference/postgresql/)).\n\nExample: Ein protokollierender Adapter\n```js\nNEWDB('default', function(filter, callback) {\n\tconsole.log(filter.exec, filter.table, filter.filter);\n\tcallback(null, filter.exec === 'list' ? { items: [], count: 0 } : []);\n});\n```\n\n### db.find(table)\n\nType: `method`\n\nFindet alle Zeilen, die dem Filter entsprechen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `find` zurück. Die Antwort ist das Array, das der Adapter zurückgibt. Alias: `db.all()`.\n\nExample: Finden\n```js\nDATA.find('products').where('price', '>', 10).sort('name').callback(console.log);\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. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `read`, `take` 1 und der Option `first` zurück. Gibt der Adapter ein Array zurück, ist die Antwort dessen erstes Element oder `null`. Alias: `db.one()`.\n\nExample: Nach ID lesen\n```js\nDATA.read('users').id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nLiest eine Seite von Zeilen mit Metadaten zur Paginierung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `list`, `skip` 0 und `take` 100 zurück. Der Adapter gibt ein Objekt mit den Zeilen und der Gesamtzahl `count` zurück; der Adapter `nosql` gibt `{ items, count }` zurück, wobei `count` die Anzahl aller passenden Dokumente ist. Der QueryBuilder fügt diesem Objekt `page`, `limit` und `pages` hinzu.\n\nExample: Eine Seite\n```js\nDATA.list('products').page(2, 20).callback(function(err, response) {\n\tconsole.log(response.items, response.count, response.pages);\n});\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. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `check`, `take` 1 und der Option `first` zurück. Der Adapter antwortet, ob eine Zeile passt (der Adapter `nosql` gibt `true` oder `false` zurück).\n\nExample: Eindeutige E-Mail\n```js\nDATA.check('users').where('email', model.email).error('@(E-mail already exists)', true).callback($);\n```\n\n### db.count(table)\n\nType: `method`\n\nZählt die Zeilen, die dem Filter entsprechen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `count` zurück. Der Adapter bestimmt die Form der Antwort.\n\nExample: Zählen\n```js\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nBerechnet einen Aggregatwert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n| `type` | `String` | yes |  | Das Aggregat, zum Beispiel `sum`, `avg`, `min`, `max`, `count`. |\n| `key` | `String` | no | `'*'` | Die Spalte. |\n| `key2` | `String` | no |  | Eine zweite Spalte, die nach `key` gruppiert wird. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `scalar` und der Option `scalar = { type, key, key2 }` zurück. `key` ist standardmäßig `*`. Mit `key2` gruppiert der Adapter die Werte von `key2` nach `key`. Die Typen werden vom Adapter interpretiert; der Adapter `nosql` unterstützt `min`, `max`, `sum`, `avg` und `count` (ohne `key2`; mit dem Standard `*` zählt jedes Dokument als `1`) sowie `group` (`key2` summiert die Werte von `key2` pro `key`).\n\nExample: Summe\n```js\nDATA.scalar('orders', 'sum', 'price').where('status', 'paid').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. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n| `data` | `Object` | yes |  | Die einzufügende Zeile. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `insert` und `data` als Payload zurück. Alias: `db.ins()`.\n\nExample: Einfügen\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nAktualisiert die Zeilen, die dem Filter entsprechen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n| `data` | `Object` | yes |  | Die zu ändernden Spalten. |\n| `upsert` | `Boolean` | no | `false` | Den Payload einfügen, wenn nichts aktualisiert wurde. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `update` und `data` als Payload zurück. Ist `upsert` auf `true` gesetzt, wird ein Update ohne Ergebnis (oder mit leerem `returning`-Ergebnis) erneut als `insert` desselben Payloads ohne Bedingungen ausgeführt; `builder.insert(fn)` kann den Payload vorher ändern. Aliase: `db.modify()`, `db.mod()`, `db.upd()`.\n\nExample: Aktualisieren\n```js\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.remove(table)\n\nType: `method`\n\nEntfernt die Zeilen, die dem Filter entsprechen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `remove` zurück. Alias: `db.rem()`.\n\nExample: Entfernen\n```js\nDATA.remove('users').id('u1').callback(console.log);\n```\n\n### db.query([connection], query, [params])\n\nType: `method`\n\nFührt eine Rohabfrage aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | Der Verbindungsname. |\n| `query` | `String` | yes |  | Die Rohabfrage. |\n| `params` | `Object|Array` | no |  | Parameter für den Adapter. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `query` und den Optionen `query` und `params` zurück. Mit einem Argument (oder wenn das zweite Argument ein Objekt ist) läuft die Abfrage auf der Verbindung `default`; andernfalls ist das erste Argument der Verbindungsname. Der Adapter bestimmt die Syntax der Abfrage und der Parameter.\n\nExample: Rohes SQL\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE isremoved=FALSE').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. `connection/table` wählt eine Verbindung; ohne Schrägstrich ist die Verbindung `default`. |\n\nReturns: `QueryBuilder`\n\nGibt einen QueryBuilder mit der Operation `truncate` zurück. Alias: `db.clear()`. `db.drop(table)` funktioniert genauso mit der Operation `drop`, und `db.command(table, name)` mit der Operation `command` und der Option `command = name`, für eigene Befehle des Adapters.\n\nExample: Leeren\n```js\nDATA.truncate('logs/requests').callback(console.log);\n```\n\n### db.exec(filter, callback)\n\nType: `method`\n\nFührt eine Abfrage aus, die durch ein einfaches Objekt beschrieben wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | Die Optionen, zum Beispiel `{ exec: 'find', table: 'users', take: 10 }`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\n`filter.exec` wählt die Operation (`find`, `list`, `read`, `count`, `truncate`, `drop`, `remove`, `insert`, `update`, `scalar`, `command` oder `query`) und `filter.table` die Tabelle; jeder andere Schlüssel wird in die Optionen der Abfrage kopiert. Bei `query` steht die Rohabfrage in `filter.query`.\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'users', take: 5 }, console.log);\n```\n\n### db.load([connection], options)\n\nType: `method`\n\nErstellt eine Abfrage aus vorbereiteten Optionen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | Der Verbindungsname. |\n| `options` | `Object` | yes |  | Die vorbereiteten Optionen. |\n\nReturns: `QueryBuilder`\n\nErstellt einen QueryBuilder aus einem Objekt mit `table`, `exec`, `fields`, `skip`, `take`, `query`, `sort`, `payload`, `upsert`, `returning` und `filter` (ein Array von Filterelementen). Die Verbindung ist standardmäßig `default`.\n\nExample: Laden\n```js\nDATA.load({ table: 'users', exec: 'find', take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nLegt die Standardwerte für lokalisierte Spalten fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Das Präfix vor dem Sprachcode. |\n| `skip` | `String` | yes |  | Eine Sprache, die „keine Sprache“ bedeutet. |\n\nReturns: `Database`\n\nLegt das globale Präfix und die zu überspringende Sprache fest, die `builder.language()` verwendet, wenn es keine eigenen Werte erhält. Die standardmäßig übersprungene Sprache ist `_`.\n\nExample: Standardwerte\n```js\nDATA.language('_', 'en');\n```\n\n### db.debug()\n\nType: `method`\n\nSetzt die Debug-Option für jede Abfrage einer DB()-Kette.\n\nReturns: `Database`\n\nJede Abfrage, die nach diesem Aufruf erstellt wird, erhält die Option `debug = true`, sodass ein Adapter, der dies unterstützt, die erzeugte Abfrage protokollieren kann.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('users');\ndb.callback(console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nSetzt den Callback einer DB()-Kette.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` oder das `$` einer Aktion. |\n\nReturns: `Database`\n\nDer Callback erhält den ersten Fehler oder die endgültige Antwort. Übergib statt einer Funktion `$` einer Aktion, um die Aktion zu beantworten. Alias: `db.pipe()`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.callback($);\n```\n\n### db.promise([$])\n\nType: `method`\n\nGibt ein Promise einer DB()-Kette zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Das `$` einer Aktion. |\n\nReturns: `Promise`\n\nDas Promise wird mit der endgültigen Antwort erfüllt. Bei einem Fehler wird es abgelehnt, oder, mit `$`, geht der Fehler an `$.invalid()`.\n\nExample: Await\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\nvar response = await db.promise($);\n```\n\n### db.done($, fn)\n\nType: `method`\n\nRuft bei Erfolg fn und bei einem Fehler $.invalid() auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$` einer Aktion. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `Database`\n\nBeendet eine DB()-Kette innerhalb einer Aktion: Ein Fehler wird an `$.invalid()` übergeben, eine Antwort an `fn(response)`.\n\nExample: Done\n```js\nvar db = DB();\ndb.read('users').id($.params.id).set('user');\ndb.done($, function(response) {\n\t$.callback(response.user);\n});\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nFügt einen Vergleich hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=`, `<=`. |\n| `value` | `Object` | yes |  | Der Wert. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nOhne `comparer` ist der Vergleich `=`. `==` wird zu `=` und `!=` wird zu `<>`. Nur mit `name` ist das Argument eine rohe Bedingung, genau wie bei `query()`.\n\nExample: Where\n```js\nDATA.find('products').where('price', '>=', 10).where('ispublished', true).callback(console.log);\n```\n\n### builder.id(value)\n\nType: `method`\n\nFiltert nach der Spalte id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Eine ID oder eine Liste von IDs. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\n`where('id', value)`, oder `in('id', value)`, wenn der Wert ein Array ist.\n\nExample: Id\n```js\nDATA.read('users').id('u1').callback(console.log);\n```\n\n### builder.userid(value)\n\nType: `method`\n\nFiltert nach der Spalte userid.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Object` | yes |  | Eine ID, eine Liste, ein Benutzer oder `$`. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nAkzeptiert eine ID, ein Array von IDs (`in`), ein Benutzerobjekt (dessen `id`) oder ein Objekt mit `user` wie `$` einer Aktion (dessen `user.id`).\n\nExample: Zeilen des aktuellen Benutzers\n```js\nDATA.find('orders').userid($).callback($);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nFügt pro Schlüssel eine Gleichheitsbedingung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Spaltennamen und Werte. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nRuft `where(key, value)` für jeden Schlüssel des Objekts auf.\n\nExample: Equal\n```js\nDATA.find('users').equal({ role: 'admin', isremoved: false }).callback(console.log);\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` | yes |  | Die Werte. |\n| `key` | `String` | no |  | Eine Eigenschaft, die aus jedem Objekt von `value` gelesen wird. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nEin einzelner Wert wird in ein Array verpackt. Mit `key` ist `value` ein Array von Objekten, und die Werte werden aus deren Eigenschaft `key` gelesen.\n\nExample: In\n```js\nDATA.find('users').in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nDie Spalte entspricht keinem der Werte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `value` | `Array` | yes |  | Die Werte. |\n| `key` | `String` | no |  | Eine Eigenschaft, die aus jedem Objekt von `value` gelesen wird. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nDas Gegenteil von `in()`, mit denselben Argumenten.\n\nExample: Not in\n```js\nDATA.find('users').notin('role', ['guest']).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` Derselbe QueryBuilder, zum Verketten.\n\nFügt ein `between`-Element mit `a` und `b` hinzu.\n\nExample: Letzte Woche\n```js\nDATA.find('orders').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nSucht Text in einer Spalte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `value` | `String` | yes |  | Der Text. |\n| `where` | `String` | no |  | `beg` oder `end`. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nDie Spalte enthält `value`. Ist `where` auf `beg` gesetzt, muss der Text am Anfang stehen, mit `end` am Ende.\n\nExample: Suchen\n```js\nDATA.find('products').search('name', 'phone').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nVerbindet eine Gruppe von Bedingungen mit OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nDie innerhalb von `fn` hinzugefügten Filter bilden eine Gruppe. `fn` wird mit dem Builder als `this` und als Argument aufgerufen. Eine leere Gruppe wird ignoriert.\n\nExample: Or\n```js\nDATA.find('users').or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('role', 'editor');\n}).callback(console.log);\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` Derselbe QueryBuilder, zum Verketten.\n\nFügt ein `contains`-Element hinzu: Die Spalte ist nicht leer (bei Arrays: Sie hat Elemente). `empty(name)` ist das Gegenteil: Die Spalte hat keinen Wert.\n\nExample: Contains\n```js\nDATA.find('users').contains('phone').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 Vergleichsoperator. |\n| `value` | `Array|String` | yes |  | Die Werte. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nFügt ein `array`-Element hinzu. Der Standardvergleich ist `&&` (die Arrays überschneiden sich); der Adapter interpretiert ihn.\n\nExample: Tags\n```js\nDATA.find('products').array('tags', ['sale', 'new']).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 Vergleichsoperator. |\n| `value` | `Number` | yes |  | Der Wert des Teils. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nVergleicht das Jahr einer Datumsspalte. `month()`, `day()`, `hour()` und `minute()` haben dieselben Argumente und vergleichen den jeweiligen Teil. Der Standardvergleich ist `=`.\n\nExample: Datumsteile\n```js\nDATA.find('orders').year('dtcreated', 2024).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(value)\n\nType: `method`\n\nFügt eine rohe Bedingung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Die rohe Bedingung. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nDer Text wird unverändert an den Adapter übergeben, er muss also in der Syntax der Engine sein.\n\nExample: Roh\n```js\nDATA.find('users').query('age > 18').callback(console.log);\n```\n\n### builder.join(name, table, type, a, b)\n\nType: `method`\n\nFügt ein Join-Element für den Adapter hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Joins. |\n| `table` | `String` | yes |  | Die verknüpfte Tabelle. |\n| `type` | `String` | yes |  | Der Join-Typ. |\n| `a` | `String` | yes |  | Die Spalte der Haupttabelle. |\n| `b` | `String` | yes |  | Die Spalte der verknüpften Tabelle. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nFügt `{ type: 'join', name, table, join: type, on: [a, b] }` zum Filter hinzu. Ob Joins unterstützt werden, entscheidet der Adapter.\n\nExample: Join\n```js\nDATA.find('orders').join('user', 'users', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nFügt eine Berechtigungsbedingung für den Adapter hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte mit den Berechtigungen. |\n| `type` | `String` | yes |  | Die Buchstaben `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Rollen oder Gruppen. |\n| `userid` | `String` | no |  | Die ID des Benutzers. |\n| `required` | `Boolean` | no | `true` | Die Berechtigung ist erforderlich. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nJeder Buchstabe von `type` (`R` lesen, `W` schreiben, `D` löschen) wird mit jedem Element von `value` kombiniert, sodass `permit('permissions', 'RW', ['admin'])` `['Radmin', 'Wadmin']` ergibt. Das Element enthält außerdem `userid` und `required` (Standard `true`).\n\nExample: Permit\n```js\nDATA.find('documents').permit('permissions', 'R', $.user.roles, $.user.id).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` Derselbe QueryBuilder, zum Verketten.\n\nEine kommagetrennte Liste von Spalten.\n\nExample: Fields\n```js\nDATA.find('users').fields('id,name,email').callback(console.log);\n```\n\n### builder.gridfields(fields, [allowed])\n\nType: `method`\n\nWählt die Spalten aus einer nicht vertrauenswürdigen Liste aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | no |  | Die angeforderten Felder, zum Beispiel `id,name`. Kann leer oder `undefined` sein. |\n| `allowed` | `String` | no |  | Die Felder, die ausgewählt werden dürfen, zum Beispiel `id,name,price`. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nNimmt eine kommagetrennte Liste, meist `$.query.fields`, und wählt die Felder aus, die auch in `allowed` stehen. Anführungszeichen, Backticks, `|` und Leerzeichen werden zuerst entfernt. Leere Namen werden übersprungen. Wenn die Liste leer ist oder fehlt oder keines der Felder erlaubt ist, ändert sich die Auswahl nicht (alle Spalten). Ohne `allowed` wird jedes Feld der Liste ausgewählt.\n\nExample: Felder aus dem Query String\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nFügt eine Sortierspalte hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `desc` | `Boolean|String` | no | `false` | `true` oder `desc` für absteigend. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\n`desc` kann `true` oder `'desc'` sein; alles andere sortiert aufsteigend. Mehrere Aufrufe fügen weitere Spalten hinzu.\n\nExample: Sortieren\n```js\nDATA.find('products').sort('price', true).sort('name').callback(console.log);\n```\n\n### builder.gridsort(sort, [map])\n\nType: `method`\n\nFügt Sortierspalten aus einem String hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Der Sortier-String. |\n| `map` | `Object` | no |  | Feldnamen, die auf Spalten abgebildet werden. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nDer String hat die Form `name_asc,dtcreated_desc`; ein Name ohne Suffix ist aufsteigend. `map` kann die Felder in Spalten umbenennen.\n\nExample: Gridsort\n```js\nDATA.find('products').gridsort('price_desc,name').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nLegt die maximale Anzahl von Zeilen fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Die Anzahl der Zeilen. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nAlias: `limit()`. `first()` setzt `take` auf 1 und gibt nur die erste Zeile zurück. `skip(count)` legt die Anzahl der zu überspringenden Zeilen fest.\n\nExample: Take\n```js\nDATA.find('products').take(10).callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nWählt eine Seite aus.\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` Derselbe QueryBuilder, zum Verketten.\n\nSetzt `skip` auf `(page - 1) * take`. Mit `limit` setzt es vorher auch `take`.\n\nExample: Seite\n```js\nDATA.list('products').page(3, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nWählt eine Seite aus nicht vertrauenswürdigen Werten aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Die Seite. |\n| `limit` | `Number|String` | yes |  | Zeilen pro Seite. |\n| `maxlimit` | `Number` | no |  | Das höchste erlaubte Limit. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nWandelt `page` und `limit` in Zahlen um (Strings aus einem Query String funktionieren), verwendet Seite 1, wenn die Seite fehlt, null oder negativ ist, hält das Limit unter `maxlimit` und verwendet `maxlimit`, wenn kein Limit angegeben ist.\n\nExample: Aus einem Query String\n```js\nDATA.list('products').paginate($.query.page, $.query.limit, 100).callback($);\n```\n\n### builder.autoquery(query, schema, [defsort], [maxlimit])\n\nType: `method`\n\nErstellt Felder, Filter, Sortierung und Paginierung aus einem Query String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | Der Query String, normalerweise `$.query`. |\n| `schema` | `String` | yes |  | Die erlaubten Felder und Typen. |\n| `defsort` | `String` | no |  | Die Standardsortierung, zum Beispiel `dtcreated_desc`. |\n| `maxlimit` | `Number` | no |  | Aktiviert die Paginierung mit diesem höchsten Limit. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\n`schema` listet die erlaubten Felder als `name:type`, durch Kommas getrennt (Typen: `string`, `number`, `date`, `boolean`, `[string]`, `json`; Standard ist `string`), oder `@SchemaName`, um sie aus einem JSON-Schema zu übernehmen. `query.fields` wählt unter den erlaubten Feldern aus (alle, wenn es fehlt), jedes erlaubte Feld wird mit `gridfilter()` gefiltert, `query.sort` (`name_asc`, `name_desc`) sortiert nach erlaubten Feldern, sonst wird `defsort` verwendet, und mit `maxlimit` gehen `query.page` und `query.limit` an `paginate()`. Felder, die nicht im Schema stehen, werden ignoriert. Spalten, die vor `autoquery()` mit `fields()` ausgewählt wurden, bleiben ausgewählt, und die Felder des Query Strings werden nur für diese Abfrage hinzugefügt.\n\nExample: Ein Grid\n```js\nDATA.list('products').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($);\n```\n\n### builder.autoqueryjson($, column, schema, [defsort], [maxlimit])\n\nType: `method`\n\nBaut Felder, Filter, Sortierung und Paging für Eigenschaften einer JSON-Spalte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$` einer Aktion oder der Query String. |\n| `column` | `String` | yes |  | Die JSON-Spalte. |\n| `schema` | `String` | yes |  | Die erlaubten Eigenschaften und Typen. |\n| `defsort` | `String` | no |  | Die Standardsortierung, zum Beispiel `weight_desc`. |\n| `maxlimit` | `Number` | no |  | Aktiviert Paging mit diesem höchsten Limit. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nFunktioniert wie `autoquery()`, aber die Felder sind Eigenschaften, die in der JSON-Spalte `column` gespeichert sind. `$` ist das `$` einer Aktion (ihr `query` wird verwendet) oder der Query String selbst. `schema` listet die Eigenschaften als `name:type`, getrennt durch Kommas (Typen: `string`, `number`, `boolean`, `date`, `[string]`; der Standard ist `string`). Der QueryBuilder übergibt dem Adapter jede Eigenschaft als Namen `json:column:property:type` in den Feldern, im Filter und in der Sortierung, und der Adapter übersetzt ihn in seine eigene Syntax; der PostgreSQL-Adapter liest die Eigenschaft mit `->>` und wandelt sie in ihren Typ um. `column` darf nur Buchstaben, Ziffern und `_` enthalten, sonst wirft die Methode einen Fehler; Eigenschaften mit anderen Zeichen werden ignoriert. Es kann in derselben Abfrage auf `autoquery()` folgen.\n\nExample: Spalten und JSON-Eigenschaften\n```js\nDATA.list('tbl_product').autoquery($.query, 'id,name,price:number', 'name_asc', 100).autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date').callback($);\n```\n\n### builder.gridfilter(name, query, [type], [column])\n\nType: `method`\n\nFügt einen Filter aus einem Wert des Query Strings hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Schlüssel in `query`. |\n| `query` | `Object` | yes |  | Der Query String. |\n| `type` | `String` | no | `'string'` | Der Typ des Werts. |\n| `column` | `String` | no |  | Die Spalte, wenn sie sich von `name` unterscheidet. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nLiest `query[name]` und fügt je nach Form eine Bedingung hinzu: `a - b` ist `between`, `a,b` ist ein OR von Suchen bei Text und `in` bei anderen Typen, `=a,b` ist `in` mit exakten Texten, `=a` eine exakte Übereinstimmung, ein einfacher Text eine `search`, `>v` und `<v` Vergleiche. Bei Datumswerten wählen `today`, `yesterday` und ein Datum den ganzen Tag aus, eine 4-stellige Zahl das Jahr und eine kleine Zahl den Monat. `type` ist `string`, `number`, `date`, `boolean`, `[string]` (Array-Filter) oder `json` (Suche). Leere Werte fügen nichts hinzu.\n\nExample: Gridfilter\n```js\nDATA.find('orders').gridfilter('price', $.query, 'number').gridfilter('dtcreated', $.query, 'date').callback($);\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nLegt die Sprache für lokalisierte Spalten fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | Die Sprache oder ein Objekt mit `language`. |\n| `prefix` | `String` | no |  | Das Präfix. |\n| `skip` | `String` | no |  | Eine Sprache, die „keine Sprache“ bedeutet. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nSetzt die Option `language` auf `prefix + value`. `value` kann ein Objekt mit `language` sein (wie `$`). Ist `value` gleich `skip`, ist die Sprache leer. Ohne `prefix` und `skip` gelten die Standardwerte von `db.language()`. Der Adapter `nosql` ersetzt ein abschließendes `§` in Spaltennamen durch die Sprache.\n\nExample: Sprache\n```js\nDATA.find('products').fields('id,name§').language($).callback($);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nBittet den Adapter, Spalten der geänderten Zeilen zurückzugeben.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Zum Beispiel `id,name`. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nEine kommagetrennte Liste, gespeichert in der Option `returning`. Bei einem Upsert bedeutet ein leeres zurückgegebenes Ergebnis „nichts wurde aktualisiert“.\n\nExample: Returning\n```js\nDATA.update('users', { name: 'Lucia' }).id('u1').returning('id,name').callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nBereitet den Payload eines Upsert-Inserts vor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(payload, param)`. |\n| `param` | `Object` | no |  | Ein Wert, der an `fn` übergeben wird. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nMit `update(table, data, true)` wird `fn(payload, param)` aufgerufen, bevor der Payload eingefügt wird, sodass du Werte hinzufügen kannst, die nur eine neue Zeile braucht.\n\nExample: Upsert\n```js\nDATA.update('stats', { dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nMacht aus einem leeren Ergebnis einen Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Der Fehler, zum Beispiel `@(User not found)`. |\n| `reverse` | `Boolean` | no | `false` | Fehlschlagen, wenn es ein Ergebnis gibt. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nIst die Antwort leer (kein Wert oder ein leeres Array bei Abfragen, die nicht eine einzelne Zeile lesen), schlägt die Abfrage mit `message` fehl. Ist `reverse` auf `true` gesetzt, schlägt eine nicht leere Antwort fehl. Alias: `err()`.\n\nExample: Nicht gefunden\n```js\nDATA.read('users').id($.params.id).error('@(User not found)').callback($);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nSetzt den Callback der Abfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` oder `$`. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\n`fn(err, response)` wird aufgerufen, wenn die Abfrage beendet ist. Übergib `$` einer Aktion, um die Aktion mit dem Ergebnis zu beantworten. Alias: `pipe()`. `data(fn)` setzt einen Callback nur für den Erfolg (`fn(response)`) und `fail(fn)` einen nur für Fehler (`fn(err)`).\n\nExample: Callback\n```js\nDATA.find('users').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nGibt ein Promise der Abfrage zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Das `$` einer Aktion. |\n\nReturns: `Promise`\n\nWird mit der Antwort erfüllt. Bei einem Fehler wird das Promise mit dem Fehler abgelehnt (ein Fehlerobjekt des Adapters erhält den Namen `QueryBuilder(table --> operation)`), oder, mit `$`, geht der Fehler an `$.invalid()`.\n\nExample: Await\n```js\nvar user = await DATA.read('users').id('u1').promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nRuft bei Erfolg fn und bei einem Fehler $.invalid() auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$` einer Aktion. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Ein Wert, der an `fn` übergeben wird. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nBei Erfolg wird `fn(response, param)` aufgerufen; ein Fehler geht an `$.invalid()`.\n\nExample: Done\n```js\nDATA.read('users').id($.params.id).done($, function(user) {\n\t$.callback({ id: user.id, name: user.name });\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 |  | Das `$` einer Aktion. |\n| `message` | `String` | no |  | Die Nachricht. |\n| `type` | `String` | no |  | Der Typ des Eintrags. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nRuft nach einer erfolgreichen Abfrage `$.audit(message, type)` auf. Platzhalter wie `{data.name}` in der Nachricht werden aus dem Payload gefüllt, `{user.name}` aus dem Benutzer.\n\nExample: Audit\n```js\nDATA.insert('products', model).audit($, 'Created product {data.name}').callback($);\n```\n\n### builder.set(name)\n\nType: `method`\n\nSpeichert das Ergebnis unter einem Schlüssel der DB()-Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Schlüssel. |\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nIn einer `DB()`-Kette wird die Antwort zu einem Objekt, und dieses Ergebnis wird als `response[name]` gespeichert. `nobind()` hält das Ergebnis vollständig aus der Antwort heraus.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.count('orders').where('userid', 'u1').set('orders');\ndb.callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nSetzt die Debug-Option der Abfrage.\n\nReturns: `QueryBuilder` Derselbe QueryBuilder, zum Verketten.\n\nSetzt `debug = true` in den Optionen, sodass ein Adapter, der dies unterstützt, die Abfrage protokollieren kann. `primarykey(name)` und `schema(name)` setzen auf die gleiche Weise die Optionen `primarykey` und `schema`, für Adapter, die sie verwenden.\n\nExample: Debug\n```js\nDATA.find('users').debug().callback(console.log);\n```\n","entries":[{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count(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([connection], query, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.exec()","signature":"db.exec(filter, callback)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([connection], options)","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.promise()","signature":"db.promise([$])","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, fn)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.userid()","signature":"builder.userid(value)","since":"","deprecated":false},{"type":"method","name":"builder.equal()","signature":"builder.equal(obj)","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.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, type, 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.gridfields()","signature":"builder.gridfields(fields, [allowed])","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.gridsort()","signature":"builder.gridsort(sort, [map])","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.autoquery()","signature":"builder.autoquery(query, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autoqueryjson()","signature":"builder.autoqueryjson($, column, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, query, [type], [column])","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(message, [reverse])","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.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRq1fx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() y los métodos del QueryBuilder.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() y los métodos del QueryBuilder.\n\nEl objeto global `DATA`, la cadena `DB()` y los adaptadores registrados con `NEWDB()`, junto con todos los métodos del QueryBuilder que devuelven. En la guía [QueryBuilder](../../guides/querybuilder/) tienes una introducción con ejemplos.\n\n## API\n\n### DATA\n\nType: `property`\n\nEl objeto global de base de datos que inicia cada consulta de inmediato.\n\nReturns: `Database`\n\nUna instancia compartida del controlador de base de datos. Cada operación sobre él (`find()`, `insert()`…) crea un QueryBuilder y lo ejecuta en el siguiente tick, de forma independiente de las demás consultas. Usa `DB()` cuando necesites varias consultas en secuencia con un solo resultado.\n\nExample: Buscar filas\n```js\nDATA.find('users').where('isremoved', false).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### DB()\n\nType: `method`\n\nCrea un objeto de base de datos que ejecuta las consultas en secuencia.\n\nReturns: `Database` Un nuevo controlador de base de datos.\n\nCada operación que llamas sobre el objeto devuelto se pone en cola y se ejecuta en orden después del tick actual. La respuesta final es el resultado de la última consulta, o un objeto rellenado por `set(name)` de cada consulta. El primer error detiene la cadena y se pasa a `callback()`. Si añades una consulta después de que la cadena haya terminado, la cadena empieza de nuevo.\n\nExample: Dos consultas\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nRegistra o elimina un adaptador de base de datos.\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)` que ejecuta la consulta. Omítelo para eliminar el adaptador. |\n\nEl adaptador ejecuta las consultas de la conexión `name`. Se llama con `this` como el objeto interno de la consulta, `filter` como las opciones de la consulta (`exec`, `table`, `filter`, `fields`, `sort`, `take`, `skip`, `payload`, `upsert`, `returning`, `first`, `language`, `query`, `params`, `scalar`, `command`, `primarykey`, `schema`, `checksum`, `debug`) y un callback `(err, response)`. El `checksum` es un hash corto de la estructura del filtro, útil como clave de caché para consultas preparadas. El adaptador `*` se usa para las conexiones sin adaptador propio. Sin `fn` se elimina el adaptador `name`; en ese caso `name` es obligatorio. El framework registra el adaptador `nosql` para los archivos NoSQL integrados, y `DATA.init()` registra adaptadores para PostgreSQL (consulta [PostgreSQL](../../reference/postgresql/)).\n\nExample: Un adaptador que registra en el log\n```js\nNEWDB('default', function(filter, callback) {\n\tconsole.log(filter.exec, filter.table, filter.filter);\n\tcallback(null, filter.exec === 'list' ? { items: [], count: 0 } : []);\n});\n```\n\n### db.find(table)\n\nType: `method`\n\nBusca todas las filas que cumplen el filtro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `find`. La respuesta es el array que devuelve el adaptador. Alias: `db.all()`.\n\nExample: Buscar\n```js\nDATA.find('products').where('price', '>', 10).sort('name').callback(console.log);\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. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `read`, `take` 1 y la opción `first`. Cuando el adaptador devuelve un array, la respuesta es su primer elemento o `null`. Alias: `db.one()`.\n\nExample: Leer por id\n```js\nDATA.read('users').id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nLee una página de filas con metadatos de paginación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `list`, `skip` 0 y `take` 100. El adaptador devuelve un objeto con las filas y el total `count`; el adaptador `nosql` devuelve `{ items, count }`, donde `count` es el número de todos los documentos que coinciden. El QueryBuilder añade `page`, `limit` y `pages` a ese objeto.\n\nExample: Una página\n```js\nDATA.list('products').page(2, 20).callback(function(err, response) {\n\tconsole.log(response.items, response.count, response.pages);\n});\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. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `check`, `take` 1 y la opción `first`. El adaptador responde si alguna fila coincide (el adaptador `nosql` devuelve `true` o `false`).\n\nExample: E-mail único\n```js\nDATA.check('users').where('email', model.email).error('@(E-mail already exists)', true).callback($);\n```\n\n### db.count(table)\n\nType: `method`\n\nCuenta las filas que cumplen el filtro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `count`. El adaptador decide la forma de la respuesta.\n\nExample: Contar\n```js\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nCalcula un valor agregado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n| `type` | `String` | yes |  | El agregado, por ejemplo `sum`, `avg`, `min`, `max`, `count`. |\n| `key` | `String` | no | `'*'` | La columna. |\n| `key2` | `String` | no |  | Una segunda columna para agrupar por `key`. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `scalar` y la opción `scalar = { type, key, key2 }`. `key` es `*` por defecto. Con `key2` el adaptador agrupa los valores de `key2` por `key`. Los tipos los interpreta el adaptador; el adaptador `nosql` admite `min`, `max`, `sum`, `avg` y `count` (sin `key2`; con el `*` por defecto cada documento cuenta como `1`), y `group` (`key2` suma los valores de `key2` por `key`).\n\nExample: Suma\n```js\nDATA.scalar('orders', 'sum', 'price').where('status', 'paid').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. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n| `data` | `Object` | yes |  | La fila que se inserta. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `insert` y `data` como payload. Alias: `db.ins()`.\n\nExample: Insertar\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nActualiza las filas que cumplen el filtro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n| `data` | `Object` | yes |  | Las columnas que se cambian. |\n| `upsert` | `Boolean` | no | `false` | Inserta el payload cuando no se actualizó nada. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `update` y `data` como payload. Con `upsert` en `true`, una actualización que no devuelve ningún resultado (o un resultado `returning` vacío) se ejecuta de nuevo como un `insert` del mismo payload sin condiciones; `builder.insert(fn)` puede cambiar el payload antes. Alias: `db.modify()`, `db.mod()`, `db.upd()`.\n\nExample: Actualizar\n```js\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.remove(table)\n\nType: `method`\n\nElimina las filas que cumplen el filtro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `remove`. Alias: `db.rem()`.\n\nExample: Eliminar\n```js\nDATA.remove('users').id('u1').callback(console.log);\n```\n\n### db.query([connection], query, [params])\n\nType: `method`\n\nEjecuta una consulta en bruto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | El nombre de la conexión. |\n| `query` | `String` | yes |  | La consulta en bruto. |\n| `params` | `Object|Array` | no |  | Parámetros para el adaptador. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `query` y las opciones `query` y `params`. Con un argumento (o cuando el segundo argumento es un objeto) la consulta se ejecuta en la conexión `default`; si no, el primer argumento es el nombre de la conexión. El adaptador decide la sintaxis de la consulta y de los parámetros.\n\nExample: SQL en bruto\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE isremoved=FALSE').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. `connection/table` selecciona una conexión; sin barra la conexión es `default`. |\n\nReturns: `QueryBuilder`\n\nDevuelve un QueryBuilder con la operación `truncate`. Alias: `db.clear()`. `db.drop(table)` funciona igual con la operación `drop`, y `db.command(table, name)` con la operación `command` y la opción `command = name`, para comandos personalizados del adaptador.\n\nExample: Truncate\n```js\nDATA.truncate('logs/requests').callback(console.log);\n```\n\n### db.exec(filter, callback)\n\nType: `method`\n\nEjecuta una consulta descrita por un objeto plano.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | Las opciones, por ejemplo `{ exec: 'find', table: 'users', take: 10 }`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\n`filter.exec` selecciona la operación (`find`, `list`, `read`, `count`, `truncate`, `drop`, `remove`, `insert`, `update`, `scalar`, `command` o `query`) y `filter.table` la tabla; cualquier otra clave se copia a las opciones de la consulta. Para `query` la consulta en bruto está en `filter.query`.\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'users', take: 5 }, console.log);\n```\n\n### db.load([connection], options)\n\nType: `method`\n\nCrea una consulta a partir de opciones preparadas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | El nombre de la conexión. |\n| `options` | `Object` | yes |  | Las opciones preparadas. |\n\nReturns: `QueryBuilder`\n\nCrea un QueryBuilder a partir de un objeto con `table`, `exec`, `fields`, `skip`, `take`, `query`, `sort`, `payload`, `upsert`, `returning` y `filter` (un array de elementos de filtro). La conexión por defecto es `default`.\n\nExample: Load\n```js\nDATA.load({ table: 'users', exec: 'find', take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nDefine los valores por defecto para las columnas localizadas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | El prefijo que se pone antes del código de idioma. |\n| `skip` | `String` | yes |  | Un idioma que significa \"sin idioma\". |\n\nReturns: `Database`\n\nDefine el prefijo global y el idioma que se omite, que `builder.language()` usa cuando no recibe valores propios. El idioma omitido por defecto es `_`.\n\nExample: Valores por defecto\n```js\nDATA.language('_', 'en');\n```\n\n### db.debug()\n\nType: `method`\n\nActiva la opción debug en cada consulta de una cadena DB().\n\nReturns: `Database`\n\nCada consulta creada después de esta llamada recibe la opción `debug = true`, así un adaptador que lo admita puede registrar en el log la consulta generada.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('users');\ndb.callback(console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nDefine el callback de una cadena DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` o el `$` de una acción. |\n\nReturns: `Database`\n\nEl callback recibe el primer error o la respuesta final. Pasa el `$` de una acción en lugar de una función para responder a la acción. Alias: `db.pipe()`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.callback($);\n```\n\n### db.promise([$])\n\nType: `method`\n\nDevuelve una promesa de una cadena DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | El `$` de una acción. |\n\nReturns: `Promise`\n\nLa promesa se resuelve con la respuesta final. En caso de error se rechaza, o, con `$`, el error va a `$.invalid()`.\n\nExample: Await\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\nvar response = await db.promise($);\n```\n\n### db.done($, fn)\n\nType: `method`\n\nLlama a fn si hay éxito y a $.invalid() si hay error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `Database`\n\nTermina una cadena DB() dentro de una acción: un error se pasa a `$.invalid()`, una respuesta a `fn(response)`.\n\nExample: Done\n```js\nvar db = DB();\ndb.read('users').id($.params.id).set('user');\ndb.done($, function(response) {\n\t$.callback(response.user);\n});\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nAñade una comparación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=`, `<=`. |\n| `value` | `Object` | yes |  | El valor. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nSin `comparer` la comparación es `=`. `==` se convierte en `=` y `!=` en `<>`. Solo con `name`, el argumento es una condición en bruto, igual que `query()`.\n\nExample: Where\n```js\nDATA.find('products').where('price', '>=', 10).where('ispublished', true).callback(console.log);\n```\n\n### builder.id(value)\n\nType: `method`\n\nFiltra por la columna id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Un id o una lista de ids. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\n`where('id', value)`, o `in('id', value)` cuando el valor es un array.\n\nExample: Id\n```js\nDATA.read('users').id('u1').callback(console.log);\n```\n\n### builder.userid(value)\n\nType: `method`\n\nFiltra por la columna userid.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Object` | yes |  | Un id, una lista, un usuario o `$`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nAcepta un id, un array de ids (`in`), un objeto de usuario (su `id`) o un objeto con `user` como el `$` de una acción (su `user.id`).\n\nExample: Filas del usuario actual\n```js\nDATA.find('orders').userid($).callback($);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nAñade una igualdad por cada clave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Nombres de columnas y valores. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nLlama a `where(key, value)` para cada clave del objeto.\n\nExample: Equal\n```js\nDATA.find('users').equal({ role: 'admin', isremoved: false }).callback(console.log);\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` | yes |  | Los valores. |\n| `key` | `String` | no |  | Una propiedad que se lee de cada objeto de `value`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nUn valor único se envuelve en un array. Con `key`, `value` es un array de objetos y los valores se toman de su propiedad `key`.\n\nExample: In\n```js\nDATA.find('users').in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nLa columna no es ninguno de los valores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `value` | `Array` | yes |  | Los valores. |\n| `key` | `String` | no |  | Una propiedad que se lee de cada objeto de `value`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nLo contrario de `in()`, con los mismos argumentos.\n\nExample: Not in\n```js\nDATA.find('users').notin('role', ['guest']).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 mismo QueryBuilder, para encadenar.\n\nAñade un elemento `between` con `a` y `b`.\n\nExample: La última semana\n```js\nDATA.find('orders').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nBusca texto en una columna.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `value` | `String` | yes |  | El texto. |\n| `where` | `String` | no |  | `beg` o `end`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nLa columna contiene `value`. Con `where` en `beg` el texto debe estar al principio, con `end` al final.\n\nExample: Búsqueda\n```js\nDATA.find('products').search('name', 'phone').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nUne un grupo de condiciones con OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nLos filtros añadidos dentro de `fn` forman un grupo. `fn` se llama con el builder como `this` y como argumento. Un grupo vacío se ignora.\n\nExample: Or\n```js\nDATA.find('users').or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('role', 'editor');\n}).callback(console.log);\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 mismo QueryBuilder, para encadenar.\n\nAñade un elemento `contains`: la columna no está vacía (para arrays: tiene elementos). `empty(name)` es lo contrario: la columna no tiene valor.\n\nExample: Contains\n```js\nDATA.find('users').contains('phone').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 comparador. |\n| `value` | `Array|String` | yes |  | Los valores. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nAñade un elemento `array`. El comparador por defecto es `&&` (los arrays se solapan); el adaptador lo interpreta.\n\nExample: Etiquetas\n```js\nDATA.find('products').array('tags', ['sale', 'new']).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 comparador. |\n| `value` | `Number` | yes |  | El valor de la parte. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nCompara el año de una columna de fecha. `month()`, `day()`, `hour()` y `minute()` tienen los mismos argumentos y comparan esa parte. El comparador por defecto es `=`.\n\nExample: Partes de la fecha\n```js\nDATA.find('orders').year('dtcreated', 2024).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(value)\n\nType: `method`\n\nAñade una condición en bruto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La condición en bruto. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nEl texto se pasa al adaptador tal cual, así que debe estar en la sintaxis del motor.\n\nExample: En bruto\n```js\nDATA.find('users').query('age > 18').callback(console.log);\n```\n\n### builder.join(name, table, type, a, b)\n\nType: `method`\n\nAñade un elemento join para el adaptador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del join. |\n| `table` | `String` | yes |  | La tabla unida. |\n| `type` | `String` | yes |  | El tipo de join. |\n| `a` | `String` | yes |  | La columna de la tabla principal. |\n| `b` | `String` | yes |  | La columna de la tabla unida. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nAñade `{ type: 'join', name, table, join: type, on: [a, b] }` al filtro. Si los joins se admiten o no depende del adaptador.\n\nExample: Join\n```js\nDATA.find('orders').join('user', 'users', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nAñade una condición de permisos para el adaptador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna con los permisos. |\n| `type` | `String` | yes |  | Las letras `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Roles o grupos. |\n| `userid` | `String` | no |  | El id del usuario. |\n| `required` | `Boolean` | no | `true` | El permiso es obligatorio. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nCada letra de `type` (`R` lectura, `W` escritura, `D` borrado) se combina con cada elemento de `value`, así que `permit('permissions', 'RW', ['admin'])` da `['Radmin', 'Wadmin']`. El elemento lleva también `userid` y `required` (por defecto `true`).\n\nExample: Permit\n```js\nDATA.find('documents').permit('permissions', 'R', $.user.roles, $.user.id).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 mismo QueryBuilder, para encadenar.\n\nUna lista de columnas separadas por comas.\n\nExample: Fields\n```js\nDATA.find('users').fields('id,name,email').callback(console.log);\n```\n\n### builder.gridfields(fields, [allowed])\n\nType: `method`\n\nSelecciona las columnas de una lista no fiable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | no |  | Los campos pedidos, por ejemplo `id,name`. Puede estar vacío o ser `undefined`. |\n| `allowed` | `String` | no |  | Los campos que se pueden seleccionar, por ejemplo `id,name,price`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nToma una lista separada por comas, normalmente `$.query.fields`, y selecciona los campos que también están en `allowed`. Primero se quitan las comillas, los backticks, `|` y los espacios. Los nombres vacíos se omiten. Cuando la lista está vacía o falta, o ninguno de los campos está permitido, la selección no cambia (todas las columnas). Sin `allowed` se seleccionan todos los campos de la lista.\n\nExample: Campos del query string\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nAñade una columna de ordenación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `desc` | `Boolean|String` | no | `false` | `true` o `desc` para orden descendente. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\n`desc` puede ser `true` o `'desc'`; cualquier otro valor ordena de forma ascendente. Varias llamadas añaden más columnas.\n\nExample: Ordenar\n```js\nDATA.find('products').sort('price', true).sort('name').callback(console.log);\n```\n\n### builder.gridsort(sort, [map])\n\nType: `method`\n\nAñade columnas de ordenación a partir de una cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | La cadena de ordenación. |\n| `map` | `Object` | no |  | Nombres de campos asignados a columnas. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nLa cadena tiene la forma `name_asc,dtcreated_desc`; un nombre sin sufijo es ascendente. `map` puede renombrar los campos a columnas.\n\nExample: Gridsort\n```js\nDATA.find('products').gridsort('price_desc,name').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nDefine el número máximo de filas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | El número de filas. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nAlias: `limit()`. `first()` pone `take` a 1 y devuelve solo la primera fila. `skip(count)` define el número de filas que se omiten.\n\nExample: Take\n```js\nDATA.find('products').take(10).callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSelecciona una 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 mismo QueryBuilder, para encadenar.\n\nPone `skip` a `(page - 1) * take`. Con `limit` también define `take` primero.\n\nExample: Página\n```js\nDATA.list('products').page(3, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSelecciona una página a partir de valores no fiables.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | La página. |\n| `limit` | `Number|String` | yes |  | Filas por página. |\n| `maxlimit` | `Number` | no |  | El límite más alto permitido. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nConvierte `page` y `limit` a números (funcionan las cadenas de una query string), usa la página 1 cuando la página falta, es cero o es negativa, mantiene el límite por debajo de `maxlimit` y usa `maxlimit` cuando no se indica ningún límite.\n\nExample: Desde una query string\n```js\nDATA.list('products').paginate($.query.page, $.query.limit, 100).callback($);\n```\n\n### builder.autoquery(query, schema, [defsort], [maxlimit])\n\nType: `method`\n\nConstruye campos, filtros, ordenación y paginación a partir de una query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | La query string, normalmente `$.query`. |\n| `schema` | `String` | yes |  | Los campos y tipos permitidos. |\n| `defsort` | `String` | no |  | La ordenación por defecto, por ejemplo `dtcreated_desc`. |\n| `maxlimit` | `Number` | no |  | Activa la paginación con este límite máximo. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\n`schema` lista los campos permitidos como `name:type` separados por comas (tipos: `string`, `number`, `date`, `boolean`, `[string]`, `json`; el valor por defecto es `string`), o `@SchemaName` para tomarlos de un esquema JSON. `query.fields` elige entre los campos permitidos (todos cuando falta), cada campo permitido se filtra con `gridfilter()`, `query.sort` (`name_asc`, `name_desc`) ordena por los campos permitidos o se usa `defsort`, y con `maxlimit`, `query.page` y `query.limit` van a `paginate()`. Los campos que no están en el esquema se ignoran. Las columnas seleccionadas con `fields()` antes de `autoquery()` siguen seleccionadas, y los campos de la query string se les añaden solo para esta consulta.\n\nExample: Una tabla de datos\n```js\nDATA.list('products').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($);\n```\n\n### builder.autoqueryjson($, column, schema, [defsort], [maxlimit])\n\nType: `method`\n\nConstruye campos, filtros, orden y paginación para propiedades de una columna JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción, o el query string. |\n| `column` | `String` | yes |  | La columna JSON. |\n| `schema` | `String` | yes |  | Las propiedades y los tipos permitidos. |\n| `defsort` | `String` | no |  | El orden por defecto, por ejemplo `weight_desc`. |\n| `maxlimit` | `Number` | no |  | Activa la paginación con este límite máximo. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nFunciona como `autoquery()`, pero los campos son propiedades guardadas en la columna JSON `column`. `$` es el `$` de una acción (se usa su `query`) o el propio query string. `schema` enumera las propiedades como `name:type` separadas por comas (tipos: `string`, `number`, `boolean`, `date`, `[string]`; por defecto `string`). El QueryBuilder pasa al adaptador cada propiedad con el nombre `json:column:property:type` en los campos, el filtro y el orden, y el adaptador lo traduce a su propia sintaxis; el adaptador de PostgreSQL lee la propiedad con `->>` y la convierte a su tipo. `column` solo puede contener letras, dígitos y `_`; si no, el método lanza un error; las propiedades con otros caracteres se ignoran. Puede ir después de `autoquery()` en la misma consulta.\n\nExample: Columnas y propiedades JSON\n```js\nDATA.list('tbl_product').autoquery($.query, 'id,name,price:number', 'name_asc', 100).autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date').callback($);\n```\n\n### builder.gridfilter(name, query, [type], [column])\n\nType: `method`\n\nAñade un filtro a partir de un valor de la query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La clave en `query`. |\n| `query` | `Object` | yes |  | La query string. |\n| `type` | `String` | no | `'string'` | El tipo del valor. |\n| `column` | `String` | no |  | La columna, cuando es distinta de `name`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nLee `query[name]` y añade una condición según su forma: `a - b` es `between`, `a,b` es un OR de búsquedas para texto e `in` para otros tipos, `=a,b` es `in` con textos exactos, `=a` una coincidencia exacta, un texto simple un `search`, `>v` y `<v` comparaciones. Para fechas, `today`, `yesterday` y una fecha seleccionan el día entero, un número de 4 dígitos el año y un número pequeño el mes. `type` es `string`, `number`, `date`, `boolean`, `[string]` (filtro de array) o `json` (búsqueda). Los valores vacíos no añaden nada.\n\nExample: Gridfilter\n```js\nDATA.find('orders').gridfilter('price', $.query, 'number').gridfilter('dtcreated', $.query, 'date').callback($);\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nDefine el idioma para las columnas localizadas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | El idioma o un objeto con `language`. |\n| `prefix` | `String` | no |  | El prefijo. |\n| `skip` | `String` | no |  | Un idioma que significa \"sin idioma\". |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nPone la opción `language` a `prefix + value`. `value` puede ser un objeto con `language` (como `$`). Cuando `value` es igual a `skip` el idioma queda vacío. Sin `prefix` ni `skip` se aplican los valores por defecto de `db.language()`. El adaptador `nosql` sustituye un `§` final en los nombres de columna por el idioma.\n\nExample: Idioma\n```js\nDATA.find('products').fields('id,name§').language($).callback($);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nPide al adaptador que devuelva columnas de las filas cambiadas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Por ejemplo `id,name`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nUna lista separada por comas que se guarda en la opción `returning`. Con un upsert, un resultado devuelto vacío significa \"no se actualizó nada\".\n\nExample: Returning\n```js\nDATA.update('users', { name: 'Lucia' }).id('u1').returning('id,name').callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPrepara el payload de la inserción de un upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(payload, param)`. |\n| `param` | `Object` | no |  | Un valor que se pasa a `fn`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nCon `update(table, data, true)`, se llama a `fn(payload, param)` antes de insertar el payload, así puedes añadir valores que solo necesita una fila nueva.\n\nExample: Upsert\n```js\nDATA.update('stats', { dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nConvierte un resultado vacío en un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | El error, por ejemplo `@(User not found)`. |\n| `reverse` | `Boolean` | no | `false` | Falla cuando hay un resultado. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nCuando la respuesta está vacía (sin valor, o un array vacío para las consultas que no toman una sola fila), la consulta falla con `message`. Con `reverse` en `true`, falla una respuesta no vacía. Alias: `err()`.\n\nExample: No encontrado\n```js\nDATA.read('users').id($.params.id).error('@(User not found)').callback($);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nDefine el callback de la consulta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` o `$`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nSe llama a `fn(err, response)` cuando la consulta termina. Pasa el `$` de una acción para responder a la acción con el resultado. Alias: `pipe()`. `data(fn)` define un callback solo para el éxito (`fn(response)`) y `fail(fn)` uno solo para los errores (`fn(err)`).\n\nExample: Callback\n```js\nDATA.find('users').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nDevuelve una promesa de la consulta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | El `$` de una acción. |\n\nReturns: `Promise`\n\nSe resuelve con la respuesta. En caso de error la promesa se rechaza con el error (un objeto de error del adaptador recibe el nombre `QueryBuilder(table --> operation)`), o, con `$`, el error va a `$.invalid()`.\n\nExample: Await\n```js\nvar user = await DATA.read('users').id('u1').promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nLlama a fn si hay éxito y a $.invalid() si hay error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Un valor que se pasa a `fn`. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nSi hay éxito se llama a `fn(response, param)`; un error va a `$.invalid()`.\n\nExample: Done\n```js\nDATA.read('users').id($.params.id).done($, function(user) {\n\t$.callback({ id: user.id, name: user.name });\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 |  | El `$` de una acción. |\n| `message` | `String` | no |  | El mensaje. |\n| `type` | `String` | no |  | El tipo del registro. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nDespués de una consulta correcta, llama a `$.audit(message, type)`. Los marcadores como `{data.name}` del mensaje se rellenan desde el payload, `{user.name}` desde el usuario.\n\nExample: Auditoría\n```js\nDATA.insert('products', model).audit($, 'Created product {data.name}').callback($);\n```\n\n### builder.set(name)\n\nType: `method`\n\nGuarda el resultado bajo una clave de la respuesta de DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La clave. |\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nEn una cadena `DB()` la respuesta se convierte en un objeto y este resultado se guarda como `response[name]`. `nobind()` deja el resultado totalmente fuera de la respuesta.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.count('orders').where('userid', 'u1').set('orders');\ndb.callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nActiva la opción debug de la consulta.\n\nReturns: `QueryBuilder` El mismo QueryBuilder, para encadenar.\n\nPone `debug = true` en las opciones, así un adaptador que lo admita puede registrar la consulta en el log. `primarykey(name)` y `schema(name)` definen las opciones `primarykey` y `schema` de la misma forma, para los adaptadores que las usan.\n\nExample: Debug\n```js\nDATA.find('users').debug().callback(console.log);\n```\n","entries":[{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count(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([connection], query, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.exec()","signature":"db.exec(filter, callback)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([connection], options)","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.promise()","signature":"db.promise([$])","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, fn)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.userid()","signature":"builder.userid(value)","since":"","deprecated":false},{"type":"method","name":"builder.equal()","signature":"builder.equal(obj)","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.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, type, 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.gridfields()","signature":"builder.gridfields(fields, [allowed])","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.gridsort()","signature":"builder.gridsort(sort, [map])","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.autoquery()","signature":"builder.autoquery(query, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autoqueryjson()","signature":"builder.autoqueryjson($, column, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, query, [type], [column])","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(message, [reverse])","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.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRq1fx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() et les méthodes du QueryBuilder.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() et les méthodes du QueryBuilder.\n\nL'objet global `DATA`, la chaîne `DB()` et les adaptateurs enregistrés avec `NEWDB()`, ainsi que toutes les méthodes du QueryBuilder qu'ils renvoient. Une introduction avec des exemples se trouve dans le guide [QueryBuilder](../../guides/querybuilder/).\n\n## API\n\n### DATA\n\nType: `property`\n\nL'objet de base de données global qui lance chaque requête immédiatement.\n\nReturns: `Database`\n\nUne instance partagée du contrôleur de base de données. Chaque opération sur cet objet (`find()`, `insert()`…) crée un QueryBuilder et l'exécute au tick suivant, indépendamment des autres requêtes. Utilise `DB()` lorsque tu as besoin de plusieurs requêtes en séquence avec un seul résultat.\n\nExample: Rechercher des lignes\n```js\nDATA.find('users').where('isremoved', false).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### DB()\n\nType: `method`\n\nCrée un objet de base de données qui exécute les requêtes en séquence.\n\nReturns: `Database` Un nouveau contrôleur de base de données.\n\nChaque opération appelée sur l'objet renvoyé est mise en file d'attente et exécutée dans l'ordre après le tick courant. La réponse finale est le résultat de la dernière requête, ou un objet rempli par le `set(name)` de chaque requête. La première erreur arrête la chaîne et est transmise à `callback()`. Si tu ajoutes une requête après la fin de la chaîne, la chaîne redémarre.\n\nExample: Deux requêtes\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nEnregistre ou supprime un adaptateur de base de données.\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)` qui exécute la requête. Omets-la pour supprimer l'adaptateur. |\n\nL'adaptateur exécute les requêtes de la connexion `name`. Il est appelé avec `this` comme objet de requête interne, `filter` comme options de la requête (`exec`, `table`, `filter`, `fields`, `sort`, `take`, `skip`, `payload`, `upsert`, `returning`, `first`, `language`, `query`, `params`, `scalar`, `command`, `primarykey`, `schema`, `checksum`, `debug`) et un callback `(err, response)`. Le `checksum` est un hash court de la structure du filtre, utile comme clé de cache pour les requêtes préparées. L'adaptateur `*` est utilisé pour les connexions sans adaptateur propre. Sans `fn`, l'adaptateur `name` est supprimé ; `name` est alors obligatoire. Le framework enregistre l'adaptateur `nosql` pour les fichiers NoSQL intégrés, et `DATA.init()` enregistre des adaptateurs pour PostgreSQL (voir [PostgreSQL](../../reference/postgresql/)).\n\nExample: Un adaptateur de journalisation\n```js\nNEWDB('default', function(filter, callback) {\n\tconsole.log(filter.exec, filter.table, filter.filter);\n\tcallback(null, filter.exec === 'list' ? { items: [], count: 0 } : []);\n});\n```\n\n### db.find(table)\n\nType: `method`\n\nRecherche toutes les lignes qui correspondent au filtre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `find`. La réponse est le tableau renvoyé par l'adaptateur. Alias : `db.all()`.\n\nExample: Rechercher\n```js\nDATA.find('products').where('price', '>', 10).sort('name').callback(console.log);\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. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `read`, `take` 1 et l'option `first`. Lorsque l'adaptateur renvoie un tableau, la réponse est son premier élément ou `null`. Alias : `db.one()`.\n\nExample: Lire par id\n```js\nDATA.read('users').id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nLit une page de lignes avec les métadonnées de pagination.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `list`, `skip` 0 et `take` 100. L'adaptateur renvoie un objet avec les lignes et le total `count` ; l'adaptateur `nosql` renvoie `{ items, count }`, où `count` est le nombre de tous les documents correspondants. Le QueryBuilder ajoute `page`, `limit` et `pages` à cet objet.\n\nExample: Une page\n```js\nDATA.list('products').page(2, 20).callback(function(err, response) {\n\tconsole.log(response.items, response.count, response.pages);\n});\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. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `check`, `take` 1 et l'option `first`. L'adaptateur indique si une ligne correspond (l'adaptateur `nosql` renvoie `true` ou `false`).\n\nExample: E-mail unique\n```js\nDATA.check('users').where('email', model.email).error('@(E-mail already exists)', true).callback($);\n```\n\n### db.count(table)\n\nType: `method`\n\nCompte les lignes qui correspondent au filtre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `count`. L'adaptateur décide de la forme de la réponse.\n\nExample: Compter\n```js\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nCalcule une valeur agrégée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n| `type` | `String` | yes |  | L'agrégat, par exemple `sum`, `avg`, `min`, `max`, `count`. |\n| `key` | `String` | no | `'*'` | La colonne. |\n| `key2` | `String` | no |  | Une seconde colonne à regrouper par `key`. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `scalar` et l'option `scalar = { type, key, key2 }`. `key` vaut `*` par défaut. Avec `key2`, l'adaptateur regroupe les valeurs de `key2` par `key`. Les types sont interprétés par l'adaptateur ; l'adaptateur `nosql` prend en charge `min`, `max`, `sum`, `avg` et `count` (sans `key2` ; avec le `*` par défaut, chaque document compte comme `1`), ainsi que `group` (`key2` additionne les valeurs de `key2` par `key`).\n\nExample: Somme\n```js\nDATA.scalar('orders', 'sum', 'price').where('status', 'paid').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. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n| `data` | `Object` | yes |  | La ligne à insérer. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `insert` et `data` comme payload. Alias : `db.ins()`.\n\nExample: Insérer\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nMet à jour les lignes qui correspondent au filtre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n| `data` | `Object` | yes |  | Les colonnes à modifier. |\n| `upsert` | `Boolean` | no | `false` | Insère le payload lorsque rien n'a été mis à jour. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `update` et `data` comme payload. Avec `upsert` à `true`, une mise à jour qui ne renvoie aucun résultat (ou un résultat `returning` vide) est exécutée à nouveau comme un `insert` du même payload, sans conditions ; `builder.insert(fn)` peut modifier le payload avant cela. Alias : `db.modify()`, `db.mod()`, `db.upd()`.\n\nExample: Mettre à jour\n```js\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.remove(table)\n\nType: `method`\n\nSupprime les lignes qui correspondent au filtre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `remove`. Alias : `db.rem()`.\n\nExample: Supprimer\n```js\nDATA.remove('users').id('u1').callback(console.log);\n```\n\n### db.query([connection], query, [params])\n\nType: `method`\n\nExécute une requête brute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | Le nom de la connexion. |\n| `query` | `String` | yes |  | La requête brute. |\n| `params` | `Object|Array` | no |  | Les paramètres pour l'adaptateur. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `query` et les options `query` et `params`. Avec un seul argument (ou lorsque le deuxième argument est un objet), la requête s'exécute sur la connexion `default` ; sinon, le premier argument est le nom de la connexion. L'adaptateur décide de la syntaxe de la requête et des paramètres.\n\nExample: SQL brut\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE isremoved=FALSE').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. `connection/table` sélectionne une connexion ; sans barre oblique, la connexion est `default`. |\n\nReturns: `QueryBuilder`\n\nRenvoie un QueryBuilder avec l'opération `truncate`. Alias : `db.clear()`. `db.drop(table)` fonctionne de la même façon avec l'opération `drop`, et `db.command(table, name)` avec l'opération `command` et l'option `command = name`, pour les commandes personnalisées de l'adaptateur.\n\nExample: Vider la table\n```js\nDATA.truncate('logs/requests').callback(console.log);\n```\n\n### db.exec(filter, callback)\n\nType: `method`\n\nExécute une requête décrite par un objet simple.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | Les options, par exemple `{ exec: 'find', table: 'users', take: 10 }`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\n`filter.exec` sélectionne l'opération (`find`, `list`, `read`, `count`, `truncate`, `drop`, `remove`, `insert`, `update`, `scalar`, `command` ou `query`) et `filter.table` la table ; toutes les autres clés sont copiées dans les options de la requête. Pour `query`, la requête brute se trouve dans `filter.query`.\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'users', take: 5 }, console.log);\n```\n\n### db.load([connection], options)\n\nType: `method`\n\nCrée une requête à partir d'options préparées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | Le nom de la connexion. |\n| `options` | `Object` | yes |  | Les options préparées. |\n\nReturns: `QueryBuilder`\n\nCrée un QueryBuilder à partir d'un objet avec `table`, `exec`, `fields`, `skip`, `take`, `query`, `sort`, `payload`, `upsert`, `returning` et `filter` (un tableau d'éléments de filtre). La connexion vaut `default` par défaut.\n\nExample: Charger\n```js\nDATA.load({ table: 'users', exec: 'find', take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nDéfinit les valeurs par défaut des colonnes localisées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Le préfixe placé devant le code de langue. |\n| `skip` | `String` | yes |  | Une langue qui signifie « aucune langue ». |\n\nReturns: `Database`\n\nDéfinit le préfixe global et la langue à ignorer qu'utilise `builder.language()` lorsqu'il ne reçoit pas ses propres valeurs. La langue ignorée par défaut est `_`.\n\nExample: Valeurs par défaut\n```js\nDATA.language('_', 'en');\n```\n\n### db.debug()\n\nType: `method`\n\nActive l'option debug sur chaque requête d'une chaîne DB().\n\nReturns: `Database`\n\nChaque requête créée après cet appel reçoit l'option `debug = true`, de sorte qu'un adaptateur qui la prend en charge peut journaliser la requête générée.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('users');\ndb.callback(console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nDéfinit le callback d'une chaîne DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` ou le `$` d'une action. |\n\nReturns: `Database`\n\nLe callback reçoit la première erreur ou la réponse finale. Passe le `$` d'une action au lieu d'une fonction pour répondre à l'action. Alias : `db.pipe()`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.callback($);\n```\n\n### db.promise([$])\n\nType: `method`\n\nRenvoie une promesse d'une chaîne DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Le `$` d'une action. |\n\nReturns: `Promise`\n\nLa promesse est résolue avec la réponse finale. En cas d'erreur, elle est rejetée, ou, avec `$`, l'erreur est transmise à `$.invalid()`.\n\nExample: Await\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\nvar response = await db.promise($);\n```\n\n### db.done($, fn)\n\nType: `method`\n\nAppelle fn en cas de succès et $.invalid() en cas d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `Database`\n\nTermine une chaîne DB() dans une action : une erreur est transmise à `$.invalid()`, une réponse à `fn(response)`.\n\nExample: Done\n```js\nvar db = DB();\ndb.read('users').id($.params.id).set('user');\ndb.done($, function(response) {\n\t$.callback(response.user);\n});\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nAjoute une comparaison.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=`, `<=`. |\n| `value` | `Object` | yes |  | La valeur. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nSans `comparer`, la comparaison est `=`. `==` devient `=` et `!=` devient `<>`. Avec seulement `name`, l'argument est une condition brute, comme pour `query()`.\n\nExample: Where\n```js\nDATA.find('products').where('price', '>=', 10).where('ispublished', true).callback(console.log);\n```\n\n### builder.id(value)\n\nType: `method`\n\nFiltre par la colonne id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Un id ou une liste d'ids. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\n`where('id', value)`, ou `in('id', value)` lorsque la valeur est un tableau.\n\nExample: Id\n```js\nDATA.read('users').id('u1').callback(console.log);\n```\n\n### builder.userid(value)\n\nType: `method`\n\nFiltre par la colonne userid.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Object` | yes |  | Un id, une liste, un utilisateur ou `$`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nAccepte un id, un tableau d'ids (`in`), un objet utilisateur (son `id`) ou un objet avec `user`, comme le `$` d'une action (son `user.id`).\n\nExample: Lignes de l'utilisateur courant\n```js\nDATA.find('orders').userid($).callback($);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nAjoute une égalité par clé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Les noms de colonnes et les valeurs. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nAppelle `where(key, value)` pour chaque clé de l'objet.\n\nExample: Equal\n```js\nDATA.find('users').equal({ role: 'admin', isremoved: false }).callback(console.log);\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` | yes |  | Les valeurs. |\n| `key` | `String` | no |  | Une propriété à lire dans chaque objet de `value`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nUne valeur unique est enveloppée dans un tableau. Avec `key`, `value` est un tableau d'objets et les valeurs sont lues dans leur propriété `key`.\n\nExample: In\n```js\nDATA.find('users').in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nLa colonne ne vaut aucune des valeurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `value` | `Array` | yes |  | Les valeurs. |\n| `key` | `String` | no |  | Une propriété à lire dans chaque objet de `value`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nL'inverse de `in()`, avec les mêmes arguments.\n\nExample: Not in\n```js\nDATA.find('users').notin('role', ['guest']).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 même QueryBuilder, pour le chaînage.\n\nAjoute un élément `between` avec `a` et `b`.\n\nExample: La semaine dernière\n```js\nDATA.find('orders').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nRecherche un texte dans une colonne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `value` | `String` | yes |  | Le texte. |\n| `where` | `String` | no |  | `beg` ou `end`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nLa colonne contient `value`. Avec `where` à `beg`, le texte doit être au début ; avec `end`, à la fin.\n\nExample: Recherche\n```js\nDATA.find('products').search('name', 'phone').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nRelie un groupe de conditions avec OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nLes filtres ajoutés dans `fn` forment un groupe. `fn` est appelée avec le builder comme `this` et comme argument. Un groupe vide est ignoré.\n\nExample: Or\n```js\nDATA.find('users').or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('role', 'editor');\n}).callback(console.log);\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 même QueryBuilder, pour le chaînage.\n\nAjoute un élément `contains` : la colonne n'est pas vide (pour les tableaux : elle contient des éléments). `empty(name)` est l'inverse : la colonne n'a pas de valeur.\n\nExample: Contains\n```js\nDATA.find('users').contains('phone').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 | `'&&'` | Le comparateur. |\n| `value` | `Array|String` | yes |  | Les valeurs. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nAjoute un élément `array`. Le comparateur par défaut est `&&` (les tableaux se chevauchent) ; c'est l'adaptateur qui l'interprète.\n\nExample: Tags\n```js\nDATA.find('products').array('tags', ['sale', 'new']).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 | `'='` | Le comparateur. |\n| `value` | `Number` | yes |  | La valeur de la partie. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nCompare l'année d'une colonne de date. `month()`, `day()`, `hour()` et `minute()` ont les mêmes arguments et comparent la partie correspondante. Le comparateur par défaut est `=`.\n\nExample: Parties d'une date\n```js\nDATA.find('orders').year('dtcreated', 2024).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(value)\n\nType: `method`\n\nAjoute une condition brute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La condition brute. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nLe texte est transmis tel quel à l'adaptateur ; il doit donc respecter la syntaxe du moteur.\n\nExample: Brut\n```js\nDATA.find('users').query('age > 18').callback(console.log);\n```\n\n### builder.join(name, table, type, a, b)\n\nType: `method`\n\nAjoute un élément de jointure pour l'adaptateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la jointure. |\n| `table` | `String` | yes |  | La table jointe. |\n| `type` | `String` | yes |  | Le type de jointure. |\n| `a` | `String` | yes |  | La colonne de la table principale. |\n| `b` | `String` | yes |  | La colonne de la table jointe. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nAjoute `{ type: 'join', name, table, join: type, on: [a, b] }` au filtre. La prise en charge des jointures dépend de l'adaptateur.\n\nExample: Join\n```js\nDATA.find('orders').join('user', 'users', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nAjoute une condition de permission pour l'adaptateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne contenant les permissions. |\n| `type` | `String` | yes |  | Les lettres `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Des rôles ou des groupes. |\n| `userid` | `String` | no |  | L'id de l'utilisateur. |\n| `required` | `Boolean` | no | `true` | La permission est obligatoire. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nChaque lettre de `type` (`R` lecture, `W` écriture, `D` suppression) est combinée avec chaque élément de `value` ; ainsi `permit('permissions', 'RW', ['admin'])` donne `['Radmin', 'Wadmin']`. L'élément contient aussi `userid` et `required` (par défaut `true`).\n\nExample: Permit\n```js\nDATA.find('documents').permit('permissions', 'R', $.user.roles, $.user.id).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 même QueryBuilder, pour le chaînage.\n\nUne liste de colonnes séparées par des virgules.\n\nExample: Fields\n```js\nDATA.find('users').fields('id,name,email').callback(console.log);\n```\n\n### builder.gridfields(fields, [allowed])\n\nType: `method`\n\nSélectionne les colonnes à partir d'une liste non fiable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | no |  | Les champs demandés, par exemple `id,name`. Peut être vide ou `undefined`. |\n| `allowed` | `String` | no |  | Les champs qui peuvent être sélectionnés, par exemple `id,name,price`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nPrend une liste séparée par des virgules, généralement `$.query.fields`, et sélectionne les champs qui se trouvent aussi dans `allowed`. Les guillemets, les backticks, `|` et les espaces sont d'abord supprimés. Les noms vides sont ignorés. Quand la liste est vide ou absente, ou qu'aucun des champs n'est autorisé, la sélection ne change pas (toutes les colonnes). Sans `allowed`, chaque champ de la liste est sélectionné.\n\nExample: Champs à partir de la query string\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nAjoute une colonne de tri.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `desc` | `Boolean|String` | no | `false` | `true` ou `desc` pour l'ordre décroissant. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\n`desc` peut valoir `true` ou `'desc'` ; toute autre valeur trie par ordre croissant. Plusieurs appels ajoutent d'autres colonnes.\n\nExample: Tri\n```js\nDATA.find('products').sort('price', true).sort('name').callback(console.log);\n```\n\n### builder.gridsort(sort, [map])\n\nType: `method`\n\nAjoute des colonnes de tri à partir d'une chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | La chaîne de tri. |\n| `map` | `Object` | no |  | Les noms de champs associés aux colonnes. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nLa chaîne a la forme `name_asc,dtcreated_desc` ; un nom sans suffixe est trié par ordre croissant. `map` permet de renommer les champs en colonnes.\n\nExample: Gridsort\n```js\nDATA.find('products').gridsort('price_desc,name').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nDéfinit le nombre maximal de lignes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre de lignes. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nAlias : `limit()`. `first()` définit `take` à 1 et ne renvoie que la première ligne. `skip(count)` définit le nombre de lignes à sauter.\n\nExample: Take\n```js\nDATA.find('products').take(10).callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSélectionne une 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 même QueryBuilder, pour le chaînage.\n\nDéfinit `skip` à `(page - 1) * take`. Avec `limit`, définit aussi `take` au préalable.\n\nExample: Page\n```js\nDATA.list('products').page(3, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSélectionne une page à partir de valeurs non fiables.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | La page. |\n| `limit` | `Number|String` | yes |  | Les lignes par page. |\n| `maxlimit` | `Number` | no |  | La limite maximale autorisée. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nConvertit `page` et `limit` en nombres (les chaînes d'une query string fonctionnent), utilise la page 1 lorsque la page est absente, nulle ou négative, maintient la limite sous `maxlimit` et utilise `maxlimit` lorsqu'aucune limite n'est fournie.\n\nExample: Depuis une query string\n```js\nDATA.list('products').paginate($.query.page, $.query.limit, 100).callback($);\n```\n\n### builder.autoquery(query, schema, [defsort], [maxlimit])\n\nType: `method`\n\nConstruit les champs, les filtres, le tri et la pagination à partir d'une query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | La query string, généralement `$.query`. |\n| `schema` | `String` | yes |  | Les champs et types autorisés. |\n| `defsort` | `String` | no |  | Le tri par défaut, par exemple `dtcreated_desc`. |\n| `maxlimit` | `Number` | no |  | Active la pagination avec cette limite maximale. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\n`schema` liste les champs autorisés sous la forme `name:type` séparés par des virgules (types : `string`, `number`, `date`, `boolean`, `[string]`, `json` ; la valeur par défaut est `string`), ou `@SchemaName` pour les prendre d'un schéma JSON. `query.fields` sélectionne parmi les champs autorisés (tous quand il est absent), chaque champ autorisé est filtré avec `gridfilter()`, `query.sort` (`name_asc`, `name_desc`) trie par les champs autorisés, sinon `defsort` est utilisé, et avec `maxlimit`, `query.page` et `query.limit` vont à `paginate()`. Les champs qui ne sont pas dans le schéma sont ignorés. Les colonnes sélectionnées avec `fields()` avant `autoquery()` restent sélectionnées, et les champs de la query string s'y ajoutent pour cette requête seulement.\n\nExample: Une grille\n```js\nDATA.list('products').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($);\n```\n\n### builder.autoqueryjson($, column, schema, [defsort], [maxlimit])\n\nType: `method`\n\nConstruit les champs, les filtres, le tri et la pagination pour les propriétés d'une colonne JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action, ou la query string. |\n| `column` | `String` | yes |  | La colonne JSON. |\n| `schema` | `String` | yes |  | Les propriétés et les types autorisés. |\n| `defsort` | `String` | no |  | Le tri par défaut, par exemple `weight_desc`. |\n| `maxlimit` | `Number` | no |  | Active la pagination avec cette limite maximale. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nFonctionne comme `autoquery()`, mais les champs sont des propriétés stockées dans la colonne JSON `column`. `$` est le `$` d'une action (sa `query` est utilisée) ou la query string elle-même. `schema` liste les propriétés sous la forme `name:type` séparées par des virgules (types : `string`, `number`, `boolean`, `date`, `[string]` ; par défaut `string`). Le QueryBuilder donne chaque propriété à l'adaptateur sous le nom `json:column:property:type` dans les champs, le filtre et le tri, et l'adaptateur la traduit dans sa propre syntaxe ; l'adaptateur PostgreSQL lit la propriété avec `->>` et la convertit dans son type. `column` ne peut contenir que des lettres, des chiffres et `_`, sinon la méthode lève une erreur ; les propriétés avec d'autres caractères sont ignorées. Elle peut suivre `autoquery()` sur la même requête.\n\nExample: Colonnes et propriétés JSON\n```js\nDATA.list('tbl_product').autoquery($.query, 'id,name,price:number', 'name_asc', 100).autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date').callback($);\n```\n\n### builder.gridfilter(name, query, [type], [column])\n\nType: `method`\n\nAjoute un filtre à partir d'une valeur de query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La clé dans `query`. |\n| `query` | `Object` | yes |  | La query string. |\n| `type` | `String` | no | `'string'` | Le type de la valeur. |\n| `column` | `String` | no |  | La colonne, lorsqu'elle diffère de `name`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nLit `query[name]` et ajoute une condition selon sa forme : `a - b` est un `between`, `a,b` est un OR de recherches pour du texte et un `in` pour les autres types, `=a,b` est un `in` avec des textes exacts, `=a` une correspondance exacte, un texte simple une `search`, `>v` et `<v` des comparaisons. Pour les dates, `today`, `yesterday` et une date sélectionnent la journée entière, un nombre à 4 chiffres l'année et un petit nombre le mois. `type` vaut `string`, `number`, `date`, `boolean`, `[string]` (filtre de tableau) ou `json` (recherche). Les valeurs vides n'ajoutent rien.\n\nExample: Gridfilter\n```js\nDATA.find('orders').gridfilter('price', $.query, 'number').gridfilter('dtcreated', $.query, 'date').callback($);\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nDéfinit la langue des colonnes localisées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | La langue ou un objet avec `language`. |\n| `prefix` | `String` | no |  | Le préfixe. |\n| `skip` | `String` | no |  | Une langue qui signifie « aucune langue ». |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nDéfinit l'option `language` à `prefix + value`. `value` peut être un objet avec `language` (comme `$`). Lorsque `value` est égal à `skip`, la langue est vide. Sans `prefix` ni `skip`, les valeurs par défaut de `db.language()` s'appliquent. L'adaptateur `nosql` remplace un `§` final dans les noms de colonnes par la langue.\n\nExample: Langue\n```js\nDATA.find('products').fields('id,name§').language($).callback($);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nDemande à l'adaptateur de renvoyer des colonnes des lignes modifiées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Par exemple `id,name`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nUne liste séparée par des virgules, stockée dans l'option `returning`. Avec un upsert, un résultat renvoyé vide signifie « rien n'a été mis à jour ».\n\nExample: Returning\n```js\nDATA.update('users', { name: 'Lucia' }).id('u1').returning('id,name').callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPrépare le payload de l'insertion d'un upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(payload, param)`. |\n| `param` | `Object` | no |  | Une valeur transmise à `fn`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nAvec `update(table, data, true)`, `fn(payload, param)` est appelée avant l'insertion du payload ; tu peux ainsi ajouter des valeurs dont seule une nouvelle ligne a besoin.\n\nExample: Upsert\n```js\nDATA.update('stats', { dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nTransforme un résultat vide en erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | L'erreur, par exemple `@(User not found)`. |\n| `reverse` | `Boolean` | no | `false` | Échoue lorsqu'il y a un résultat. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nLorsque la réponse est vide (aucune valeur, ou un tableau vide pour les requêtes qui ne prennent pas une seule ligne), la requête échoue avec `message`. Avec `reverse` à `true`, c'est une réponse non vide qui échoue. Alias : `err()`.\n\nExample: Introuvable\n```js\nDATA.read('users').id($.params.id).error('@(User not found)').callback($);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nDéfinit le callback de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` ou `$`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\n`fn(err, response)` est appelée à la fin de la requête. Passe le `$` d'une action pour répondre à l'action avec le résultat. Alias : `pipe()`. `data(fn)` définit un callback uniquement pour le succès (`fn(response)`) et `fail(fn)` un callback uniquement pour les erreurs (`fn(err)`).\n\nExample: Callback\n```js\nDATA.find('users').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nRenvoie une promesse de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Le `$` d'une action. |\n\nReturns: `Promise`\n\nEst résolue avec la réponse. En cas d'erreur, la promesse est rejetée avec l'erreur (un objet d'erreur de l'adaptateur reçoit le nom `QueryBuilder(table --> operation)`), ou, avec `$`, l'erreur est transmise à `$.invalid()`.\n\nExample: Await\n```js\nvar user = await DATA.read('users').id('u1').promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nAppelle fn en cas de succès et $.invalid() en cas d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Une valeur transmise à `fn`. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nEn cas de succès, `fn(response, param)` est appelée ; une erreur est transmise à `$.invalid()`.\n\nExample: Done\n```js\nDATA.read('users').id($.params.id).done($, function(user) {\n\t$.callback({ id: user.id, name: user.name });\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 |  | Le `$` d'une action. |\n| `message` | `String` | no |  | Le message. |\n| `type` | `String` | no |  | Le type de l'enregistrement. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nAprès une requête réussie, appelle `$.audit(message, type)`. Les placeholders comme `{data.name}` dans le message sont remplis à partir du payload, `{user.name}` à partir de l'utilisateur.\n\nExample: Audit\n```js\nDATA.insert('products', model).audit($, 'Created product {data.name}').callback($);\n```\n\n### builder.set(name)\n\nType: `method`\n\nStocke le résultat sous une clé de la réponse de DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La clé. |\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nDans une chaîne `DB()`, la réponse devient un objet et ce résultat est enregistré comme `response[name]`. `nobind()` exclut complètement le résultat de la réponse.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.count('orders').where('userid', 'u1').set('orders');\ndb.callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nActive l'option debug de la requête.\n\nReturns: `QueryBuilder` Le même QueryBuilder, pour le chaînage.\n\nDéfinit `debug = true` dans les options, de sorte qu'un adaptateur qui la prend en charge peut journaliser la requête. `primarykey(name)` et `schema(name)` définissent de la même façon les options `primarykey` et `schema`, pour les adaptateurs qui les utilisent.\n\nExample: Debug\n```js\nDATA.find('users').debug().callback(console.log);\n```\n","entries":[{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count(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([connection], query, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.exec()","signature":"db.exec(filter, callback)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([connection], options)","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.promise()","signature":"db.promise([$])","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, fn)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.userid()","signature":"builder.userid(value)","since":"","deprecated":false},{"type":"method","name":"builder.equal()","signature":"builder.equal(obj)","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.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, type, 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.gridfields()","signature":"builder.gridfields(fields, [allowed])","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.gridsort()","signature":"builder.gridsort(sort, [map])","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.autoquery()","signature":"builder.autoquery(query, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autoqueryjson()","signature":"builder.autoqueryjson($, column, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, query, [type], [column])","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(message, [reverse])","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.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRq1fx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() e i metodi del QueryBuilder.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() e i metodi del QueryBuilder.\n\nIl `DATA` globale, la catena `DB()` e gli adapter registrati con `NEWDB()`, insieme a tutti i metodi del QueryBuilder che restituiscono. Un'introduzione con esempi si trova nella guida [QueryBuilder](../../guides/querybuilder/).\n\n## API\n\n### DATA\n\nType: `property`\n\nL'oggetto database globale che avvia subito ogni query.\n\nReturns: `Database`\n\nUn'istanza condivisa del controller del database. Ogni operazione su di esso (`find()`, `insert()`…) crea un QueryBuilder e lo esegue al tick successivo, indipendentemente dalle altre query. Usa `DB()` quando ti servono più query in sequenza con un unico risultato.\n\nExample: Trovare righe\n```js\nDATA.find('users').where('isremoved', false).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### DB()\n\nType: `method`\n\nCrea un oggetto database che esegue le query in sequenza.\n\nReturns: `Database` Un nuovo controller del database.\n\nOgni operazione che chiami sull'oggetto restituito viene messa in coda ed eseguita in ordine dopo il tick corrente. La risposta finale è il risultato dell'ultima query, oppure un oggetto riempito da `set(name)` di ciascuna query. Il primo errore interrompe la catena e viene passato a `callback()`. Se aggiungi una query dopo che la catena è terminata, la catena riparte.\n\nExample: Due query\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nRegistra o rimuove un adapter del database.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Il nome della connessione. |\n| `fn` | `Function` | no |  | `function(filter, callback)` che esegue la query. Omettilo per rimuovere l'adapter. |\n\nL'adapter esegue le query della connessione `name`. Viene chiamato con `this` come oggetto interno della query, `filter` come opzioni della query (`exec`, `table`, `filter`, `fields`, `sort`, `take`, `skip`, `payload`, `upsert`, `returning`, `first`, `language`, `query`, `params`, `scalar`, `command`, `primarykey`, `schema`, `checksum`, `debug`) e una callback `(err, response)`. Il `checksum` è un breve hash della struttura del filtro, utile come chiave di cache per le query preparate. L'adapter `*` viene usato per le connessioni senza un adapter proprio. Senza `fn` l'adapter `name` viene rimosso; in quel caso `name` è obbligatorio. Il framework registra l'adapter `nosql` per i file NoSQL integrati, e `DATA.init()` registra gli adapter per PostgreSQL (vedi [PostgreSQL](../../reference/postgresql/)).\n\nExample: Un adapter che registra i log\n```js\nNEWDB('default', function(filter, callback) {\n\tconsole.log(filter.exec, filter.table, filter.filter);\n\tcallback(null, filter.exec === 'list' ? { items: [], count: 0 } : []);\n});\n```\n\n### db.find(table)\n\nType: `method`\n\nTrova tutte le righe che corrispondono al filtro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `find`. La risposta è l'array restituito dall'adapter. Alias: `db.all()`.\n\nExample: Find\n```js\nDATA.find('products').where('price', '>', 10).sort('name').callback(console.log);\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. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `read`, `take` 1 e l'opzione `first`. Quando l'adapter restituisce un array, la risposta è il suo primo elemento oppure `null`. Alias: `db.one()`.\n\nExample: Leggere per id\n```js\nDATA.read('users').id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nLegge una pagina di righe con i metadati di paginazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `list`, `skip` 0 e `take` 100. L'adapter restituisce un oggetto con le righe e il totale `count`; l'adapter `nosql` restituisce `{ items, count }`, dove `count` è il numero di tutti i documenti corrispondenti. Il QueryBuilder aggiunge `page`, `limit` e `pages` a quell'oggetto.\n\nExample: Una pagina\n```js\nDATA.list('products').page(2, 20).callback(function(err, response) {\n\tconsole.log(response.items, response.count, response.pages);\n});\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. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `check`, `take` 1 e l'opzione `first`. L'adapter risponde se una riga corrisponde (l'adapter `nosql` restituisce `true` o `false`).\n\nExample: E-mail univoca\n```js\nDATA.check('users').where('email', model.email).error('@(E-mail already exists)', true).callback($);\n```\n\n### db.count(table)\n\nType: `method`\n\nConta le righe che corrispondono al filtro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `count`. L'adapter decide la forma della risposta.\n\nExample: Count\n```js\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nCalcola un valore aggregato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n| `type` | `String` | yes |  | L'aggregato, per esempio `sum`, `avg`, `min`, `max`, `count`. |\n| `key` | `String` | no | `'*'` | La colonna. |\n| `key2` | `String` | no |  | Una seconda colonna da raggruppare per `key`. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `scalar` e l'opzione `scalar = { type, key, key2 }`. `key` è `*` per impostazione predefinita. Con `key2` l'adapter raggruppa i valori di `key2` per `key`. I tipi vengono interpretati dall'adapter; l'adapter `nosql` supporta `min`, `max`, `sum`, `avg` e `count` (senza `key2`; con il predefinito `*` ogni documento vale `1`), e `group` (`key2` somma i valori di `key2` per ogni `key`).\n\nExample: Somma\n```js\nDATA.scalar('orders', 'sum', 'price').where('status', 'paid').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. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n| `data` | `Object` | yes |  | La riga da inserire. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `insert` e `data` come payload. Alias: `db.ins()`.\n\nExample: Insert\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nAggiorna le righe che corrispondono al filtro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n| `data` | `Object` | yes |  | Le colonne da modificare. |\n| `upsert` | `Boolean` | no | `false` | Inserisce il payload quando non è stato aggiornato nulla. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `update` e `data` come payload. Con `upsert` impostato a `true`, un aggiornamento che non restituisce alcun risultato (o un risultato `returning` vuoto) viene eseguito di nuovo come `insert` dello stesso payload senza condizioni; `builder.insert(fn)` può modificare il payload prima di farlo. Alias: `db.modify()`, `db.mod()`, `db.upd()`.\n\nExample: Update\n```js\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.remove(table)\n\nType: `method`\n\nRimuove le righe che corrispondono al filtro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `remove`. Alias: `db.rem()`.\n\nExample: Remove\n```js\nDATA.remove('users').id('u1').callback(console.log);\n```\n\n### db.query([connection], query, [params])\n\nType: `method`\n\nEsegue una query grezza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | Il nome della connessione. |\n| `query` | `String` | yes |  | La query grezza. |\n| `params` | `Object|Array` | no |  | Parametri per l'adapter. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `query` e le opzioni `query` e `params`. Con un solo argomento (o quando il secondo argomento è un oggetto) la query viene eseguita sulla connessione `default`; altrimenti il primo argomento è il nome della connessione. L'adapter decide la sintassi della query e dei parametri.\n\nExample: SQL grezzo\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE isremoved=FALSE').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. `connection/table` seleziona una connessione; senza barra la connessione è `default`. |\n\nReturns: `QueryBuilder`\n\nRestituisce un QueryBuilder con l'operazione `truncate`. Alias: `db.clear()`. `db.drop(table)` funziona allo stesso modo con l'operazione `drop`, e `db.command(table, name)` con l'operazione `command` e l'opzione `command = name`, per i comandi personalizzati dell'adapter.\n\nExample: Truncate\n```js\nDATA.truncate('logs/requests').callback(console.log);\n```\n\n### db.exec(filter, callback)\n\nType: `method`\n\nEsegue una query descritta da un oggetto semplice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | Le opzioni, per esempio `{ exec: 'find', table: 'users', take: 10 }`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\n`filter.exec` seleziona l'operazione (`find`, `list`, `read`, `count`, `truncate`, `drop`, `remove`, `insert`, `update`, `scalar`, `command` o `query`) e `filter.table` la tabella; ogni altra chiave viene copiata nelle opzioni della query. Per `query` la query grezza si trova in `filter.query`.\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'users', take: 5 }, console.log);\n```\n\n### db.load([connection], options)\n\nType: `method`\n\nCrea una query da opzioni preparate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | Il nome della connessione. |\n| `options` | `Object` | yes |  | Le opzioni preparate. |\n\nReturns: `QueryBuilder`\n\nCrea un QueryBuilder da un oggetto con `table`, `exec`, `fields`, `skip`, `take`, `query`, `sort`, `payload`, `upsert`, `returning` e `filter` (un array di elementi del filtro). La connessione predefinita è `default`.\n\nExample: Load\n```js\nDATA.load({ table: 'users', exec: 'find', take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nImposta i valori predefiniti per le colonne localizzate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Il prefisso messo prima del codice della lingua. |\n| `skip` | `String` | yes |  | Una lingua che significa \"nessuna lingua\". |\n\nReturns: `Database`\n\nImposta il prefisso globale e la lingua da ignorare che `builder.language()` usa quando non riceve valori propri. La lingua ignorata predefinita è `_`.\n\nExample: Valori predefiniti\n```js\nDATA.language('_', 'en');\n```\n\n### db.debug()\n\nType: `method`\n\nImposta l'opzione debug su ogni query di una catena DB().\n\nReturns: `Database`\n\nOgni query creata dopo questa chiamata riceve l'opzione `debug = true`, così un adapter che la supporta può registrare nei log la query generata.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('users');\ndb.callback(console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nImposta la callback di una catena DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` oppure il `$` di un'azione. |\n\nReturns: `Database`\n\nLa callback riceve il primo errore o la risposta finale. Passa il `$` di un'azione al posto di una funzione per rispondere all'azione. Alias: `db.pipe()`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.callback($);\n```\n\n### db.promise([$])\n\nType: `method`\n\nRestituisce una promise di una catena DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Il `$` di un'azione. |\n\nReturns: `Promise`\n\nLa promise si risolve con la risposta finale. In caso di errore viene rifiutata oppure, con `$`, l'errore va a `$.invalid()`.\n\nExample: Await\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\nvar response = await db.promise($);\n```\n\n### db.done($, fn)\n\nType: `method`\n\nChiama fn in caso di successo e $.invalid() in caso di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `Database`\n\nTermina una catena DB() all'interno di un'azione: un errore viene passato a `$.invalid()`, una risposta a `fn(response)`.\n\nExample: Done\n```js\nvar db = DB();\ndb.read('users').id($.params.id).set('user');\ndb.done($, function(response) {\n\t$.callback(response.user);\n});\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nAggiunge un confronto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=`, `<=`. |\n| `value` | `Object` | yes |  | Il valore. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nSenza `comparer` il confronto è `=`. `==` diventa `=` e `!=` diventa `<>`. Con il solo `name`, l'argomento è una condizione grezza, come per `query()`.\n\nExample: Where\n```js\nDATA.find('products').where('price', '>=', 10).where('ispublished', true).callback(console.log);\n```\n\n### builder.id(value)\n\nType: `method`\n\nFiltra per la colonna id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Un id o un elenco di id. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\n`where('id', value)`, oppure `in('id', value)` quando il valore è un array.\n\nExample: Id\n```js\nDATA.read('users').id('u1').callback(console.log);\n```\n\n### builder.userid(value)\n\nType: `method`\n\nFiltra per la colonna userid.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Object` | yes |  | Un id, un elenco, un utente o `$`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nAccetta un id, un array di id (`in`), un oggetto utente (il suo `id`) o un oggetto con `user` come il `$` di un'azione (il suo `user.id`).\n\nExample: Righe dell'utente corrente\n```js\nDATA.find('orders').userid($).callback($);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nAggiunge un'uguaglianza per ogni chiave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Nomi delle colonne e valori. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nChiama `where(key, value)` per ogni chiave dell'oggetto.\n\nExample: Uguaglianza\n```js\nDATA.find('users').equal({ role: 'admin', isremoved: false }).callback(console.log);\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` | yes |  | I valori. |\n| `key` | `String` | no |  | Una proprietà da leggere da ciascun oggetto di `value`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nUn valore singolo viene racchiuso in un array. Con `key`, `value` è un array di oggetti e i valori vengono presi dalla loro proprietà `key`.\n\nExample: In\n```js\nDATA.find('users').in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nLa colonna non è nessuno dei valori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `value` | `Array` | yes |  | I valori. |\n| `key` | `String` | no |  | Una proprietà da leggere da ciascun oggetto di `value`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nL'opposto di `in()`, con gli stessi argomenti.\n\nExample: Not in\n```js\nDATA.find('users').notin('role', ['guest']).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` Lo stesso QueryBuilder, per il concatenamento.\n\nAggiunge un elemento `between` con `a` e `b`.\n\nExample: Ultima settimana\n```js\nDATA.find('orders').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nCerca un testo in una colonna.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `value` | `String` | yes |  | Il testo. |\n| `where` | `String` | no |  | `beg` o `end`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nLa colonna contiene `value`. Con `where` impostato a `beg` il testo deve trovarsi all'inizio, con `end` alla fine.\n\nExample: Ricerca\n```js\nDATA.find('products').search('name', 'phone').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nUnisce un gruppo di condizioni con OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nI filtri aggiunti dentro `fn` formano un unico gruppo. `fn` viene chiamata con il builder come `this` e come argomento. Un gruppo vuoto viene ignorato.\n\nExample: Or\n```js\nDATA.find('users').or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('role', 'editor');\n}).callback(console.log);\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` Lo stesso QueryBuilder, per il concatenamento.\n\nAggiunge un elemento `contains`: la colonna non è vuota (per gli array: contiene elementi). `empty(name)` è l'opposto: la colonna non ha alcun valore.\n\nExample: Contains\n```js\nDATA.find('users').contains('phone').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 | `'&&'` | Il comparatore. |\n| `value` | `Array|String` | yes |  | I valori. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nAggiunge un elemento `array`. Il comparatore predefinito è `&&` (gli array si sovrappongono); lo interpreta l'adapter.\n\nExample: Tag\n```js\nDATA.find('products').array('tags', ['sale', 'new']).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 | `'='` | Il comparatore. |\n| `value` | `Number` | yes |  | Il valore della parte. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nConfronta l'anno di una colonna data. `month()`, `day()`, `hour()` e `minute()` hanno gli stessi argomenti e confrontano quella parte. Il comparatore predefinito è `=`.\n\nExample: Parti della data\n```js\nDATA.find('orders').year('dtcreated', 2024).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(value)\n\nType: `method`\n\nAggiunge una condizione grezza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La condizione grezza. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nIl testo viene passato all'adapter così com'è, quindi deve essere nella sintassi del motore.\n\nExample: Grezzo\n```js\nDATA.find('users').query('age > 18').callback(console.log);\n```\n\n### builder.join(name, table, type, a, b)\n\nType: `method`\n\nAggiunge un elemento join per l'adapter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del join. |\n| `table` | `String` | yes |  | La tabella unita. |\n| `type` | `String` | yes |  | Il tipo di join. |\n| `a` | `String` | yes |  | La colonna della tabella principale. |\n| `b` | `String` | yes |  | La colonna della tabella unita. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nAggiunge `{ type: 'join', name, table, join: type, on: [a, b] }` al filtro. Il supporto dei join dipende dall'adapter.\n\nExample: Join\n```js\nDATA.find('orders').join('user', 'users', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nAggiunge una condizione di permesso per l'adapter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna con i permessi. |\n| `type` | `String` | yes |  | Le lettere `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Ruoli o gruppi. |\n| `userid` | `String` | no |  | L'id dell'utente. |\n| `required` | `Boolean` | no | `true` | Il permesso è obbligatorio. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nOgni lettera di `type` (`R` lettura, `W` scrittura, `D` eliminazione) viene combinata con ogni elemento di `value`, quindi `permit('permissions', 'RW', ['admin'])` dà `['Radmin', 'Wadmin']`. L'elemento contiene anche `userid` e `required` (predefinito `true`).\n\nExample: Permit\n```js\nDATA.find('documents').permit('permissions', 'R', $.user.roles, $.user.id).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 |  | Per esempio `id,name,email`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nUn elenco di colonne separate da virgole.\n\nExample: Campi\n```js\nDATA.find('users').fields('id,name,email').callback(console.log);\n```\n\n### builder.gridfields(fields, [allowed])\n\nType: `method`\n\nSeleziona le colonne da un elenco non affidabile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | no |  | I campi richiesti, per esempio `id,name`. Può essere vuoto o `undefined`. |\n| `allowed` | `String` | no |  | I campi che possono essere selezionati, per esempio `id,name,price`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nPrende un elenco separato da virgole, di solito `$.query.fields`, e seleziona i campi che sono anche in `allowed`. Prima vengono rimossi virgolette, backtick, `|` e spazi. I nomi vuoti vengono saltati. Quando l'elenco è vuoto o manca, o nessuno dei campi è consentito, la selezione non cambia (tutte le colonne). Senza `allowed` viene selezionato ogni campo dell'elenco.\n\nExample: Campi dalla query string\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nAggiunge una colonna di ordinamento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `desc` | `Boolean|String` | no | `false` | `true` o `desc` per l'ordine decrescente. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\n`desc` può essere `true` o `'desc'`; qualsiasi altro valore ordina in modo crescente. Più chiamate aggiungono altre colonne.\n\nExample: Ordinamento\n```js\nDATA.find('products').sort('price', true).sort('name').callback(console.log);\n```\n\n### builder.gridsort(sort, [map])\n\nType: `method`\n\nAggiunge colonne di ordinamento da una stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | La stringa di ordinamento. |\n| `map` | `Object` | no |  | Nomi dei campi mappati sulle colonne. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nLa stringa ha la forma `name_asc,dtcreated_desc`; un nome senza suffisso è in ordine crescente. `map` può rinominare i campi in colonne.\n\nExample: Gridsort\n```js\nDATA.find('products').gridsort('price_desc,name').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nImposta il numero massimo di righe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Il numero di righe. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nAlias: `limit()`. `first()` imposta `take` a 1 e restituisce solo la prima riga. `skip(count)` imposta il numero di righe da saltare.\n\nExample: Take\n```js\nDATA.find('products').take(10).callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSeleziona una 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` Lo stesso QueryBuilder, per il concatenamento.\n\nImposta `skip` a `(page - 1) * take`. Con `limit` imposta prima anche `take`.\n\nExample: Pagina\n```js\nDATA.list('products').page(3, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSeleziona una pagina da valori non attendibili.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | La pagina. |\n| `limit` | `Number|String` | yes |  | Righe per pagina. |\n| `maxlimit` | `Number` | no |  | Il limite massimo consentito. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nConverte `page` e `limit` in numeri (le stringhe di una query string funzionano), usa la pagina 1 quando la pagina manca, è zero o negativa, mantiene il limite sotto `maxlimit` e usa `maxlimit` quando non viene indicato alcun limite.\n\nExample: Da una query string\n```js\nDATA.list('products').paginate($.query.page, $.query.limit, 100).callback($);\n```\n\n### builder.autoquery(query, schema, [defsort], [maxlimit])\n\nType: `method`\n\nCostruisce campi, filtri, ordinamento e paginazione da una query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | La query string, di solito `$.query`. |\n| `schema` | `String` | yes |  | I campi e i tipi consentiti. |\n| `defsort` | `String` | no |  | L'ordinamento predefinito, per esempio `dtcreated_desc`. |\n| `maxlimit` | `Number` | no |  | Attiva la paginazione con questo limite massimo. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\n`schema` elenca i campi consentiti come `name:type` separati da virgole (tipi: `string`, `number`, `date`, `boolean`, `[string]`, `json`; il predefinito è `string`), o `@SchemaName` per prenderli da uno schema JSON. `query.fields` seleziona tra i campi consentiti (tutti quando manca), ogni campo consentito viene filtrato con `gridfilter()`, `query.sort` (`name_asc`, `name_desc`) ordina per i campi consentiti oppure viene usato `defsort`, e con `maxlimit` `query.page` e `query.limit` vanno a `paginate()`. I campi che non sono nello schema vengono ignorati. Le colonne selezionate con `fields()` prima di `autoquery()` restano selezionate, e i campi della query string vengono aggiunti a esse solo per questa query.\n\nExample: Una griglia\n```js\nDATA.list('products').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($);\n```\n\n### builder.autoqueryjson($, column, schema, [defsort], [maxlimit])\n\nType: `method`\n\nCostruisce campi, filtri, ordinamento e paginazione per le proprietà di una colonna JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione, oppure la query string. |\n| `column` | `String` | yes |  | La colonna JSON. |\n| `schema` | `String` | yes |  | Le proprietà e i tipi consentiti. |\n| `defsort` | `String` | no |  | L'ordinamento predefinito, per esempio `weight_desc`. |\n| `maxlimit` | `Number` | no |  | Attiva la paginazione con questo limite massimo. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nFunziona come `autoquery()`, ma i campi sono proprietà salvate nella colonna JSON `column`. `$` è il `$` di un'azione (viene usata la sua `query`) oppure la query string stessa. `schema` elenca le proprietà come `name:type` separate da virgole (tipi: `string`, `number`, `boolean`, `date`, `[string]`; il predefinito è `string`). Il QueryBuilder passa all'adapter ogni proprietà con il nome `json:column:property:type` nei campi, nel filtro e nell'ordinamento, e l'adapter lo traduce nella propria sintassi; l'adapter PostgreSQL legge la proprietà con `->>` e la converte nel suo tipo. `column` può contenere solo lettere, cifre e `_`, altrimenti il metodo lancia un errore; le proprietà con altri caratteri vengono ignorate. Può seguire `autoquery()` sulla stessa query.\n\nExample: Colonne e proprietà JSON\n```js\nDATA.list('tbl_product').autoquery($.query, 'id,name,price:number', 'name_asc', 100).autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date').callback($);\n```\n\n### builder.gridfilter(name, query, [type], [column])\n\nType: `method`\n\nAggiunge un filtro da un valore della query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La chiave in `query`. |\n| `query` | `Object` | yes |  | La query string. |\n| `type` | `String` | no | `'string'` | Il tipo del valore. |\n| `column` | `String` | no |  | La colonna, quando è diversa da `name`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nLegge `query[name]` e aggiunge una condizione in base alla sua forma: `a - b` è `between`, `a,b` è un OR di ricerche per il testo e `in` per gli altri tipi, `=a,b` è `in` con testi esatti, `=a` una corrispondenza esatta, un testo semplice una `search`, `>v` e `<v` confronti. Per le date `today`, `yesterday` e una data selezionano l'intera giornata, un numero di 4 cifre l'anno e un numero piccolo il mese. `type` è `string`, `number`, `date`, `boolean`, `[string]` (filtro array) o `json` (ricerca). I valori vuoti non aggiungono nulla.\n\nExample: Gridfilter\n```js\nDATA.find('orders').gridfilter('price', $.query, 'number').gridfilter('dtcreated', $.query, 'date').callback($);\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nImposta la lingua per le colonne localizzate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | La lingua o un oggetto con `language`. |\n| `prefix` | `String` | no |  | Il prefisso. |\n| `skip` | `String` | no |  | Una lingua che significa \"nessuna lingua\". |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nImposta l'opzione `language` a `prefix + value`. `value` può essere un oggetto con `language` (come `$`). Quando `value` è uguale a `skip` la lingua è vuota. Senza `prefix` e `skip` si applicano i valori predefiniti di `db.language()`. L'adapter `nosql` sostituisce un `§` finale nei nomi delle colonne con la lingua.\n\nExample: Lingua\n```js\nDATA.find('products').fields('id,name§').language($).callback($);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nChiede all'adapter di restituire colonne delle righe modificate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Per esempio `id,name`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nUn elenco separato da virgole salvato nell'opzione `returning`. Con un upsert, un risultato restituito vuoto significa \"non è stato aggiornato nulla\".\n\nExample: Returning\n```js\nDATA.update('users', { name: 'Lucia' }).id('u1').returning('id,name').callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPrepara il payload dell'inserimento di un upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(payload, param)`. |\n| `param` | `Object` | no |  | Un valore passato a `fn`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nCon `update(table, data, true)`, `fn(payload, param)` viene chiamata prima che il payload venga inserito, così puoi aggiungere valori che servono solo a una riga nuova.\n\nExample: Upsert\n```js\nDATA.update('stats', { dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nTrasforma un risultato vuoto in un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | L'errore, per esempio `@(User not found)`. |\n| `reverse` | `Boolean` | no | `false` | Fallisce quando c'è un risultato. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nQuando la risposta è vuota (nessun valore, o un array vuoto per le query che non prendono una sola riga), la query fallisce con `message`. Con `reverse` impostato a `true`, fallisce una risposta non vuota. Alias: `err()`.\n\nExample: Non trovato\n```js\nDATA.read('users').id($.params.id).error('@(User not found)').callback($);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nImposta la callback della query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` o `$`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\n`fn(err, response)` viene chiamata quando la query termina. Passa il `$` di un'azione per rispondere all'azione con il risultato. Alias: `pipe()`. `data(fn)` imposta una callback solo per il successo (`fn(response)`) e `fail(fn)` una solo per gli errori (`fn(err)`).\n\nExample: Callback\n```js\nDATA.find('users').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nRestituisce una promise della query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Il `$` di un'azione. |\n\nReturns: `Promise`\n\nSi risolve con la risposta. In caso di errore la promise viene rifiutata con l'errore (un oggetto errore dell'adapter riceve il nome `QueryBuilder(table --> operation)`) oppure, con `$`, l'errore va a `$.invalid()`.\n\nExample: Await\n```js\nvar user = await DATA.read('users').id('u1').promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nChiama fn in caso di successo e $.invalid() in caso di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Un valore passato a `fn`. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nIn caso di successo viene chiamata `fn(response, param)`; un errore va a `$.invalid()`.\n\nExample: Done\n```js\nDATA.read('users').id($.params.id).done($, function(user) {\n\t$.callback({ id: user.id, name: user.name });\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 |  | Il `$` di un'azione. |\n| `message` | `String` | no |  | Il messaggio. |\n| `type` | `String` | no |  | Il tipo del record. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nDopo una query riuscita, chiama `$.audit(message, type)`. I segnaposto come `{data.name}` nel messaggio vengono riempiti dal payload, `{user.name}` dall'utente.\n\nExample: Audit\n```js\nDATA.insert('products', model).audit($, 'Created product {data.name}').callback($);\n```\n\n### builder.set(name)\n\nType: `method`\n\nSalva il risultato sotto una chiave della risposta di DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La chiave. |\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nIn una catena `DB()` la risposta diventa un oggetto e questo risultato viene salvato come `response[name]`. `nobind()` tiene il risultato completamente fuori dalla risposta.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.count('orders').where('userid', 'u1').set('orders');\ndb.callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nImposta l'opzione debug della query.\n\nReturns: `QueryBuilder` Lo stesso QueryBuilder, per il concatenamento.\n\nImposta `debug = true` nelle opzioni, così un adapter che la supporta può registrare la query nei log. `primarykey(name)` e `schema(name)` impostano allo stesso modo le opzioni `primarykey` e `schema`, per gli adapter che le usano.\n\nExample: Debug\n```js\nDATA.find('users').debug().callback(console.log);\n```\n","entries":[{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count(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([connection], query, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.exec()","signature":"db.exec(filter, callback)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([connection], options)","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.promise()","signature":"db.promise([$])","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, fn)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.userid()","signature":"builder.userid(value)","since":"","deprecated":false},{"type":"method","name":"builder.equal()","signature":"builder.equal(obj)","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.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, type, 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.gridfields()","signature":"builder.gridfields(fields, [allowed])","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.gridsort()","signature":"builder.gridsort(sort, [map])","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.autoquery()","signature":"builder.autoquery(query, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autoqueryjson()","signature":"builder.autoqueryjson($, column, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, query, [type], [column])","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(message, [reverse])","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.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwRq1fx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/querybuilder/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() a metódy QueryBuilderu.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/querybuilder/\nupdated: 2026-11-19T20:13:51.296Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() a metódy QueryBuilderu.\n\nGlobálny `DATA`, reťazec `DB()` a adaptéry registrované cez `NEWDB()` spolu so všetkými metódami QueryBuilderu, ktorý vracajú. Úvod s príkladmi nájdeš v návode [QueryBuilder](../../guides/querybuilder/).\n\n## API\n\n### DATA\n\nType: `property`\n\nGlobálny databázový objekt, ktorý spúšťa každý dotaz okamžite.\n\nReturns: `Database`\n\nZdieľaná inštancia databázového kontroléra. Každá operácia na ňom (`find()`, `insert()`…) vytvorí QueryBuilder a vykoná ho v nasledujúcom ticku, nezávisle od ostatných dotazov. Keď potrebuješ niekoľko dotazov za sebou s jedným výsledkom, použi `DB()`.\n\nExample: Vyhľadanie riadkov\n```js\nDATA.find('users').where('isremoved', false).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### DB()\n\nType: `method`\n\nVytvorí databázový objekt, ktorý spúšťa dotazy postupne.\n\nReturns: `Database` Nový databázový kontrolér.\n\nKaždá operácia, ktorú na vrátenom objekte zavoláš, sa zaradí do frontu a vykoná sa v poradí po aktuálnom ticku. Výsledná odpoveď je výsledok posledného dotazu alebo objekt naplnený cez `set(name)` jednotlivých dotazov. Prvá chyba reťazec zastaví a odovzdá sa do `callback()`. Ak pridáš dotaz po skončení reťazca, reťazec sa spustí znova.\n\nExample: Dva dotazy\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nZaregistruje alebo odstráni databázový adaptér.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Názov spojenia. |\n| `fn` | `Function` | no |  | `function(filter, callback)`, ktorá vykoná dotaz. Vynechaj ju, ak chceš adaptér odstrániť. |\n\nAdaptér vykonáva dotazy spojenia `name`. Volá sa s `this` ako interným objektom dotazu, s `filter` ako voľbami dotazu (`exec`, `table`, `filter`, `fields`, `sort`, `take`, `skip`, `payload`, `upsert`, `returning`, `first`, `language`, `query`, `params`, `scalar`, `command`, `primarykey`, `schema`, `checksum`, `debug`) a s callbackom `(err, response)`. `checksum` je krátky hash štruktúry filtra, užitočný ako kľúč cache pre pripravené dotazy. Adaptér `*` sa používa pre spojenia bez vlastného adaptéra. Bez `fn` sa adaptér `name` odstráni; `name` je potom povinné. Framework registruje adaptér `nosql` pre vstavané NoSQL súbory a `DATA.init()` registruje adaptéry pre PostgreSQL (pozri [PostgreSQL](../../reference/postgresql/)).\n\nExample: Logovací adaptér\n```js\nNEWDB('default', function(filter, callback) {\n\tconsole.log(filter.exec, filter.table, filter.filter);\n\tcallback(null, filter.exec === 'list' ? { items: [], count: 0 } : []);\n});\n```\n\n### db.find(table)\n\nType: `method`\n\nNájde všetky riadky, ktoré vyhovujú filtru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `find`. Odpoveď je pole, ktoré vráti adaptér. Alias: `db.all()`.\n\nExample: Vyhľadanie\n```js\nDATA.find('products').where('price', '>', 10).sort('name').callback(console.log);\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. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `read`, `take` 1 a voľbou `first`. Keď adaptér vráti pole, odpoveď je jeho prvá položka alebo `null`. Alias: `db.one()`.\n\nExample: Čítanie podľa id\n```js\nDATA.read('users').id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nNačíta jednu stránku riadkov s metadátami stránkovania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `list`, `skip` 0 a `take` 100. Adaptér vráti objekt s riadkami a celkovým `count`; adaptér `nosql` vráti `{ items, count }`, kde `count` je počet všetkých vyhovujúcich dokumentov. QueryBuilder k tomuto objektu pridá `page`, `limit` a `pages`.\n\nExample: Stránka\n```js\nDATA.list('products').page(2, 20).callback(function(err, response) {\n\tconsole.log(response.items, response.count, response.pages);\n});\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. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `check`, `take` 1 a voľbou `first`. Adaptér odpovie, či nejaký riadok vyhovuje (adaptér `nosql` vracia `true` alebo `false`).\n\nExample: Jedinečný e-mail\n```js\nDATA.check('users').where('email', model.email).error('@(E-mail already exists)', true).callback($);\n```\n\n### db.count(table)\n\nType: `method`\n\nSpočíta riadky, ktoré vyhovujú filtru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `count`. Tvar odpovede určuje adaptér.\n\nExample: Počet\n```js\nDATA.count('orders').where('status', 'paid').callback(console.log);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nVypočíta agregovanú hodnotu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n| `type` | `String` | yes |  | Agregácia, napríklad `sum`, `avg`, `min`, `max`, `count`. |\n| `key` | `String` | no | `'*'` | Stĺpec. |\n| `key2` | `String` | no |  | Druhý stĺpec, ktorý sa zoskupí podľa `key`. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `scalar` a voľbou `scalar = { type, key, key2 }`. `key` je predvolene `*`. S `key2` adaptér zoskupí hodnoty `key2` podľa `key`. Typy interpretuje adaptér; adaptér `nosql` podporuje `min`, `max`, `sum`, `avg` a `count` (bez `key2`; s predvoleným `*` sa každý dokument počíta ako `1`) a `group` (`key2` sčíta hodnoty `key2` pre každý `key`).\n\nExample: Súčet\n```js\nDATA.scalar('orders', 'sum', 'price').where('status', 'paid').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. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n| `data` | `Object` | yes |  | Riadok na vloženie. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `insert` a `data` ako payloadom. Alias: `db.ins()`.\n\nExample: Vloženie\n```js\nDATA.insert('users', { id: UID(), name: 'Peter', dtcreated: NOW }).callback(console.log);\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nAktualizuje riadky, ktoré vyhovujú filtru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n| `data` | `Object` | yes |  | Stĺpce, ktoré sa majú zmeniť. |\n| `upsert` | `Boolean` | no | `false` | Vloží payload, keď sa nič neaktualizovalo. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `update` a `data` ako payloadom. Keď je `upsert` nastavené na `true`, aktualizácia, ktorá nevráti žiadny výsledok (alebo prázdny výsledok `returning`), sa vykoná znova ako `insert` toho istého payloadu bez podmienok; `builder.insert(fn)` môže payload predtým zmeniť. Aliasy: `db.modify()`, `db.mod()`, `db.upd()`.\n\nExample: Aktualizácia\n```js\nDATA.update('users', { name: 'Lucia', dtupdated: NOW }).id('u1').error('@(User not found)').callback(console.log);\n```\n\n### db.remove(table)\n\nType: `method`\n\nOdstráni riadky, ktoré vyhovujú filtru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `remove`. Alias: `db.rem()`.\n\nExample: Odstránenie\n```js\nDATA.remove('users').id('u1').callback(console.log);\n```\n\n### db.query([connection], query, [params])\n\nType: `method`\n\nSpustí surový dotaz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | Názov spojenia. |\n| `query` | `String` | yes |  | Surový dotaz. |\n| `params` | `Object|Array` | no |  | Parametre pre adaptér. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `query` a voľbami `query` a `params`. S jedným argumentom (alebo keď je druhý argument objekt) sa dotaz spustí na spojení `default`; inak je prvý argument názov spojenia. Syntax dotazu a parametrov určuje adaptér.\n\nExample: Surové SQL\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE isremoved=FALSE').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. `connection/table` vyberie spojenie; bez lomky je spojenie `default`. |\n\nReturns: `QueryBuilder`\n\nVráti QueryBuilder s operáciou `truncate`. Alias: `db.clear()`. `db.drop(table)` funguje rovnako s operáciou `drop` a `db.command(table, name)` s operáciou `command` a voľbou `command = name`, pre vlastné príkazy adaptéra.\n\nExample: Vyprázdnenie\n```js\nDATA.truncate('logs/requests').callback(console.log);\n```\n\n### db.exec(filter, callback)\n\nType: `method`\n\nSpustí dotaz opísaný obyčajným objektom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | Voľby, napríklad `{ exec: 'find', table: 'users', take: 10 }`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\n`filter.exec` vyberie operáciu (`find`, `list`, `read`, `count`, `truncate`, `drop`, `remove`, `insert`, `update`, `scalar`, `command` alebo `query`) a `filter.table` tabuľku; každý ďalší kľúč sa skopíruje do volieb dotazu. Pre `query` je surový dotaz v `filter.query`.\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'users', take: 5 }, console.log);\n```\n\n### db.load([connection], options)\n\nType: `method`\n\nVytvorí dotaz z pripravených volieb.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `String` | no | `'default'` | Názov spojenia. |\n| `options` | `Object` | yes |  | Pripravené voľby. |\n\nReturns: `QueryBuilder`\n\nVytvorí QueryBuilder z objektu s `table`, `exec`, `fields`, `skip`, `take`, `query`, `sort`, `payload`, `upsert`, `returning` a `filter` (pole položiek filtra). Predvolené spojenie je `default`.\n\nExample: Načítanie\n```js\nDATA.load({ table: 'users', exec: 'find', take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nNastaví predvolené hodnoty pre lokalizované stĺpce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Prefix vložený pred kód jazyka. |\n| `skip` | `String` | yes |  | Jazyk, ktorý znamená „žiadny jazyk“. |\n\nReturns: `Database`\n\nNastaví globálny prefix a jazyk, ktorý sa má preskočiť, a ktoré `builder.language()` použije, keď nedostane vlastné hodnoty. Predvolený preskočený jazyk je `_`.\n\nExample: Predvolené hodnoty\n```js\nDATA.language('_', 'en');\n```\n\n### db.debug()\n\nType: `method`\n\nNastaví voľbu debug pre každý dotaz reťazca DB().\n\nReturns: `Database`\n\nKaždý dotaz vytvorený po tomto volaní dostane voľbu `debug = true`, takže adaptér, ktorý to podporuje, môže vygenerovaný dotaz zalogovať.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('users');\ndb.callback(console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nNastaví callback reťazca DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` alebo `$` akcie. |\n\nReturns: `Database`\n\nCallback dostane prvú chybu alebo výslednú odpoveď. Namiesto funkcie môžeš odovzdať `$` akcie, aby sa odpovedalo akcii. Alias: `db.pipe()`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.callback($);\n```\n\n### db.promise([$])\n\nType: `method`\n\nVráti promise reťazca DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | `$` akcie. |\n\nReturns: `Promise`\n\nPromise sa vyrieši s výslednou odpoveďou. Pri chybe sa zamietne, alebo s `$` ide chyba do `$.invalid()`.\n\nExample: Await\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.find('orders').where('userid', 'u1').set('orders');\nvar response = await db.promise($);\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 |  | `$` akcie. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `Database`\n\nUkončí reťazec DB() vnútri akcie: chyba sa odovzdá do `$.invalid()`, odpoveď do `fn(response)`.\n\nExample: Done\n```js\nvar db = DB();\ndb.read('users').id($.params.id).set('user');\ndb.done($, function(response) {\n\t$.callback(response.user);\n});\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nPridá porovnanie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=`, `<=`. |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nBez `comparer` je porovnanie `=`. `==` sa zmení na `=` a `!=` na `<>`. Iba s `name` je argument surová podmienka, rovnako ako pri `query()`.\n\nExample: Where\n```js\nDATA.find('products').where('price', '>=', 10).where('ispublished', true).callback(console.log);\n```\n\n### builder.id(value)\n\nType: `method`\n\nFiltruje podľa stĺpca id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Id alebo zoznam id. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\n`where('id', value)`, alebo `in('id', value)`, keď je hodnota pole.\n\nExample: Id\n```js\nDATA.read('users').id('u1').callback(console.log);\n```\n\n### builder.userid(value)\n\nType: `method`\n\nFiltruje podľa stĺpca userid.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Object` | yes |  | Id, zoznam, používateľ alebo `$`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nPrijíma id, pole id (`in`), objekt používateľa (jeho `id`) alebo objekt s `user`, napríklad `$` akcie (jeho `user.id`).\n\nExample: Riadky aktuálneho používateľa\n```js\nDATA.find('orders').userid($).callback($);\n```\n\n### builder.equal(obj)\n\nType: `method`\n\nPridá jednu rovnosť pre každý kľúč.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Názvy stĺpcov a hodnoty. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nZavolá `where(key, value)` pre každý kľúč objektu.\n\nExample: Equal\n```js\nDATA.find('users').equal({ role: 'admin', isremoved: false }).callback(console.log);\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` | yes |  | Hodnoty. |\n| `key` | `String` | no |  | Vlastnosť, ktorá sa prečíta z každého objektu vo `value`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nJedna hodnota sa zabalí do poľa. S `key` je `value` pole objektov a hodnoty sa berú z ich vlastnosti `key`.\n\nExample: In\n```js\nDATA.find('users').in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nStĺpec nie je žiadna z hodnôt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `value` | `Array` | yes |  | Hodnoty. |\n| `key` | `String` | no |  | Vlastnosť, ktorá sa prečíta z každého objektu vo `value`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nOpak `in()` s rovnakými argumentmi.\n\nExample: Not in\n```js\nDATA.find('users').notin('role', ['guest']).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` Ten istý QueryBuilder na reťazenie.\n\nPridá položku `between` s `a` a `b`.\n\nExample: Minulý týždeň\n```js\nDATA.find('orders').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nVyhľadá text v stĺpci.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `value` | `String` | yes |  | Text. |\n| `where` | `String` | no |  | `beg` alebo `end`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nStĺpec obsahuje `value`. Keď je `where` nastavené na `beg`, text musí byť na začiatku, pri `end` na konci.\n\nExample: Vyhľadávanie\n```js\nDATA.find('products').search('name', 'phone').callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nSpojí skupinu podmienok cez OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nFiltre pridané vnútri `fn` tvoria jednu skupinu. `fn` sa volá s builderom ako `this` aj ako argumentom. Prázdna skupina sa ignoruje.\n\nExample: Or\n```js\nDATA.find('users').or(function(builder) {\n\tbuilder.where('role', 'admin');\n\tbuilder.where('role', 'editor');\n}).callback(console.log);\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` Ten istý QueryBuilder na reťazenie.\n\nPridá položku `contains`: stĺpec nie je prázdny (pri poliach: má položky). `empty(name)` je opak: stĺpec nemá žiadnu hodnotu.\n\nExample: Contains\n```js\nDATA.find('users').contains('phone').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 porovnania. |\n| `value` | `Array|String` | yes |  | Hodnoty. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nPridá položku `array`. Predvolený operátor porovnania je `&&` (polia sa prekrývajú); interpretuje ho adaptér.\n\nExample: Tagy\n```js\nDATA.find('products').array('tags', ['sale', 'new']).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 porovnania. |\n| `value` | `Number` | yes |  | Hodnota danej časti. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nPorovná rok dátumového stĺpca. `month()`, `day()`, `hour()` a `minute()` majú rovnaké argumenty a porovnávajú danú časť. Predvolený operátor porovnania je `=`.\n\nExample: Časti dátumu\n```js\nDATA.find('orders').year('dtcreated', 2024).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(value)\n\nType: `method`\n\nPridá surovú podmienku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Surová podmienka. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nText sa odovzdá adaptéru tak, ako je, preto musí byť v syntaxi daného enginu.\n\nExample: Surová podmienka\n```js\nDATA.find('users').query('age > 18').callback(console.log);\n```\n\n### builder.join(name, table, type, a, b)\n\nType: `method`\n\nPridá položku join pre adaptér.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov joinu. |\n| `table` | `String` | yes |  | Pripojená tabuľka. |\n| `type` | `String` | yes |  | Typ joinu. |\n| `a` | `String` | yes |  | Stĺpec hlavnej tabuľky. |\n| `b` | `String` | yes |  | Stĺpec pripojenej tabuľky. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nPridá do filtra `{ type: 'join', name, table, join: type, on: [a, b] }`. Či sú joiny podporované, závisí od adaptéra.\n\nExample: Join\n```js\nDATA.find('orders').join('user', 'users', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nPridá podmienku oprávnení pre adaptér.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec s oprávneniami. |\n| `type` | `String` | yes |  | Písmená `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Roly alebo skupiny. |\n| `userid` | `String` | no |  | Id používateľa. |\n| `required` | `Boolean` | no | `true` | Oprávnenie je povinné. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nKaždé písmeno `type` (`R` čítanie, `W` zápis, `D` mazanie) sa skombinuje s každou položkou `value`, takže `permit('permissions', 'RW', ['admin'])` dá `['Radmin', 'Wadmin']`. Položka nesie aj `userid` a `required` (predvolene `true`).\n\nExample: Permit\n```js\nDATA.find('documents').permit('permissions', 'R', $.user.roles, $.user.id).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` Ten istý QueryBuilder na reťazenie.\n\nZoznam stĺpcov oddelených čiarkou.\n\nExample: Polia\n```js\nDATA.find('users').fields('id,name,email').callback(console.log);\n```\n\n### builder.gridfields(fields, [allowed])\n\nType: `method`\n\nVyberie stĺpce z nedôveryhodného zoznamu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | no |  | Požadované polia, napríklad `id,name`. Môže byť prázdne alebo `undefined`. |\n| `allowed` | `String` | no |  | Polia, ktoré sa smú vybrať, napríklad `id,name,price`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nVezme zoznam oddelený čiarkami, zvyčajne `$.query.fields`, a vyberie polia, ktoré sú aj v `allowed`. Úvodzovky, backticky, `|` a medzery sa najprv odstránia. Prázdne názvy sa preskočia. Keď je zoznam prázdny alebo chýba, alebo keď nie je povolené žiadne z polí, výber sa nezmení (všetky stĺpce). Bez `allowed` sa vyberie každé pole zoznamu.\n\nExample: Polia z query stringu\n```js\nDATA.find('products').gridfields($.query.fields, 'id,name,price').callback($);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nPridá stĺpec na zoradenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `desc` | `Boolean|String` | no | `false` | `true` alebo `desc` pre zostupné poradie. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\n`desc` môže byť `true` alebo `'desc'`; čokoľvek iné zoraďuje vzostupne. Ďalšie volania pridávajú ďalšie stĺpce.\n\nExample: Zoradenie\n```js\nDATA.find('products').sort('price', true).sort('name').callback(console.log);\n```\n\n### builder.gridsort(sort, [map])\n\nType: `method`\n\nPridá stĺpce na zoradenie z reťazca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Reťazec zoradenia. |\n| `map` | `Object` | no |  | Názvy polí namapované na stĺpce. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nReťazec má tvar `name_asc,dtcreated_desc`; názov bez prípony je vzostupný. `map` môže premenovať polia na stĺpce.\n\nExample: Gridsort\n```js\nDATA.find('products').gridsort('price_desc,name').callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nNastaví maximálny počet riadkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Počet riadkov. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nAlias: `limit()`. `first()` nastaví `take` na 1 a vráti iba prvý riadok. `skip(count)` nastaví počet riadkov, ktoré sa preskočia.\n\nExample: Take\n```js\nDATA.find('products').take(10).callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nVyberie stránku.\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` Ten istý QueryBuilder na reťazenie.\n\nNastaví `skip` na `(page - 1) * take`. S `limit` najprv nastaví aj `take`.\n\nExample: Stránka\n```js\nDATA.list('products').page(3, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nVyberie stránku z nedôveryhodných hodnôt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Stránka. |\n| `limit` | `Number|String` | yes |  | Počet riadkov na stránku. |\n| `maxlimit` | `Number` | no |  | Najvyšší povolený limit. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nPrevedie `page` a `limit` na čísla (fungujú aj reťazce z query stringu), použije stránku 1, keď stránka chýba, je nula alebo záporná, udrží limit pod `maxlimit` a použije `maxlimit`, keď limit nie je zadaný.\n\nExample: Z query stringu\n```js\nDATA.list('products').paginate($.query.page, $.query.limit, 100).callback($);\n```\n\n### builder.autoquery(query, schema, [defsort], [maxlimit])\n\nType: `method`\n\nZostaví polia, filtre, zoradenie a stránkovanie z query stringu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | Query string, zvyčajne `$.query`. |\n| `schema` | `String` | yes |  | Povolené polia a typy. |\n| `defsort` | `String` | no |  | Predvolené zoradenie, napríklad `dtcreated_desc`. |\n| `maxlimit` | `Number` | no |  | Zapne stránkovanie s týmto najvyšším limitom. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\n`schema` vymenúva povolené polia ako `name:type` oddelené čiarkami (typy: `string`, `number`, `date`, `boolean`, `[string]`, `json`; predvolený je `string`), alebo `@SchemaName`, aby sa prevzali z JSON schémy. `query.fields` vyberá z povolených polí (všetky, keď chýba), každé povolené pole sa filtruje cez `gridfilter()`, `query.sort` (`name_asc`, `name_desc`) zoraďuje podľa povolených polí, inak sa použije `defsort`, a s `maxlimit` idú `query.page` a `query.limit` do `paginate()`. Polia, ktoré nie sú v schéme, sa ignorujú. Stĺpce vybrané cez `fields()` pred `autoquery()` zostanú vybrané a polia z query stringu sa k nim pridajú iba pre tento dopyt.\n\nExample: Grid\n```js\nDATA.list('products').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($);\n```\n\n### builder.autoqueryjson($, column, schema, [defsort], [maxlimit])\n\nType: `method`\n\nZostaví polia, filtre, triedenie a stránkovanie pre vlastnosti JSON stĺpca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie alebo query string. |\n| `column` | `String` | yes |  | JSON stĺpec. |\n| `schema` | `String` | yes |  | Povolené vlastnosti a typy. |\n| `defsort` | `String` | no |  | Predvolené triedenie, napríklad `weight_desc`. |\n| `maxlimit` | `Number` | no |  | Zapne stránkovanie s týmto najvyšším limitom. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nFunguje ako `autoquery()`, ale polia sú vlastnosti uložené v JSON stĺpci `column`. `$` je `$` akcie (použije sa jeho `query`) alebo samotný query string. `schema` vymenúva vlastnosti ako `name:type` oddelené čiarkami (typy: `string`, `number`, `boolean`, `date`, `[string]`; predvolený je `string`). QueryBuilder odovzdá adaptéru každú vlastnosť ako názov `json:column:property:type` v poliach, vo filtri a v triedení a adaptér ho preloží do vlastnej syntaxe; adaptér PostgreSQL načíta vlastnosť cez `->>` a skonvertuje ju na jej typ. `column` smie obsahovať iba písmená, číslice a `_`, inak metóda vyhodí chybu; vlastnosti s inými znakmi sa ignorujú. Môže nasledovať po `autoquery()` na tom istom dopyte.\n\nExample: Stĺpce a JSON vlastnosti\n```js\nDATA.list('tbl_product').autoquery($.query, 'id,name,price:number', 'name_asc', 100).autoqueryjson($, 'data', 'color,weight:number,waterproof:boolean,released:date').callback($);\n```\n\n### builder.gridfilter(name, query, [type], [column])\n\nType: `method`\n\nPridá filter z hodnoty query stringu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Kľúč v `query`. |\n| `query` | `Object` | yes |  | Query string. |\n| `type` | `String` | no | `'string'` | Typ hodnoty. |\n| `column` | `String` | no |  | Stĺpec, keď sa líši od `name`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nPrečíta `query[name]` a pridá podmienku podľa jej tvaru: `a - b` je `between`, `a,b` je OR vyhľadávaní pre text a `in` pre ostatné typy, `=a,b` je `in` s presnými textami, `=a` presná zhoda, obyčajný text `search`, `>v` a `<v` porovnania. Pri dátumoch `today`, `yesterday` a dátum vyberú celý deň, 4-ciferné číslo rok a malé číslo mesiac. `type` je `string`, `number`, `date`, `boolean`, `[string]` (filter poľa) alebo `json` (vyhľadávanie). Prázdne hodnoty nepridajú nič.\n\nExample: Gridfilter\n```js\nDATA.find('orders').gridfilter('price', $.query, 'number').gridfilter('dtcreated', $.query, 'date').callback($);\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nNastaví jazyk pre lokalizované stĺpce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | Jazyk alebo objekt s `language`. |\n| `prefix` | `String` | no |  | Prefix. |\n| `skip` | `String` | no |  | Jazyk, ktorý znamená „žiadny jazyk“. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nNastaví voľbu `language` na `prefix + value`. `value` môže byť objekt s `language` (napríklad `$`). Keď sa `value` rovná `skip`, jazyk je prázdny. Bez `prefix` a `skip` platia predvolené hodnoty z `db.language()`. Adaptér `nosql` nahradí koncové `§` v názvoch stĺpcov jazykom.\n\nExample: Jazyk\n```js\nDATA.find('products').fields('id,name§').language($).callback($);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nPožiada adaptér, aby vrátil stĺpce zmenených riadkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Napríklad `id,name`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nZoznam oddelený čiarkami uložený vo voľbe `returning`. Pri upserte prázdny vrátený výsledok znamená „nič sa neaktualizovalo“.\n\nExample: Returning\n```js\nDATA.update('users', { name: 'Lucia' }).id('u1').returning('id,name').callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPripraví payload pre vloženie pri upserte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(payload, param)`. |\n| `param` | `Object` | no |  | Hodnota odovzdaná do `fn`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nPri `update(table, data, true)` sa pred vložením payloadu zavolá `fn(payload, param)`, takže môžeš pridať hodnoty, ktoré potrebuje iba nový riadok.\n\nExample: Upsert\n```js\nDATA.update('stats', { dtupdated: NOW }, true).id('home').insert(function(doc) {\n\tdoc.id = 'home';\n\tdoc.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(message, [reverse])\n\nType: `method`\n\nZmení prázdny výsledok na chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Chyba, napríklad `@(User not found)`. |\n| `reverse` | `Boolean` | no | `false` | Zlyhať, keď existuje výsledok. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nKeď je odpoveď prázdna (žiadna hodnota alebo prázdne pole pri dotazoch, ktoré neberú jeden riadok), dotaz zlyhá s `message`. Keď je `reverse` nastavené na `true`, zlyhá neprázdna odpoveď. Alias: `err()`.\n\nExample: Nenájdené\n```js\nDATA.read('users').id($.params.id).error('@(User not found)').callback($);\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nNastaví callback dotazu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|$` | yes |  | `function(err, response)` alebo `$`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\n`fn(err, response)` sa zavolá, keď dotaz skončí. Odovzdaj `$` akcie, ak chceš akcii odpovedať výsledkom. Alias: `pipe()`. `data(fn)` nastaví callback iba pre úspech (`fn(response)`) a `fail(fn)` iba pre chyby (`fn(err)`).\n\nExample: Callback\n```js\nDATA.find('users').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nVráti promise dotazu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | `$` akcie. |\n\nReturns: `Promise`\n\nVyrieši sa s odpoveďou. Pri chybe sa promise zamietne s chybou (objekt chyby adaptéra dostane názov `QueryBuilder(table --> operation)`), alebo s `$` ide chyba do `$.invalid()`.\n\nExample: Await\n```js\nvar user = await DATA.read('users').id('u1').promise($);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nPri úspechu zavolá fn, pri chybe $.invalid().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Hodnota odovzdaná do `fn`. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nPri úspechu sa zavolá `fn(response, param)`; chyba ide do `$.invalid()`.\n\nExample: Done\n```js\nDATA.read('users').id($.params.id).done($, function(user) {\n\t$.callback({ id: user.id, name: user.name });\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 |  | `$` akcie. |\n| `message` | `String` | no |  | Správa. |\n| `type` | `String` | no |  | Typ záznamu. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nPo úspešnom dotaze zavolá `$.audit(message, type)`. Zástupné symboly ako `{data.name}` v správe sa vyplnia z payloadu, `{user.name}` z používateľa.\n\nExample: Audit\n```js\nDATA.insert('products', model).audit($, 'Created product {data.name}').callback($);\n```\n\n### builder.set(name)\n\nType: `method`\n\nUloží výsledok pod kľúčom odpovede DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Kľúč. |\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nV reťazci `DB()` sa odpoveď stane objektom a tento výsledok sa uloží ako `response[name]`. `nobind()` výsledok z odpovede úplne vynechá.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('users').id('u1').set('user');\ndb.count('orders').where('userid', 'u1').set('orders');\ndb.callback($);\n```\n\n### builder.debug()\n\nType: `method`\n\nNastaví voľbu debug dotazu.\n\nReturns: `QueryBuilder` Ten istý QueryBuilder na reťazenie.\n\nNastaví vo voľbách `debug = true`, takže adaptér, ktorý to podporuje, môže dotaz zalogovať. `primarykey(name)` a `schema(name)` rovnakým spôsobom nastavia voľby `primarykey` a `schema` pre adaptéry, ktoré ich používajú.\n\nExample: Debug\n```js\nDATA.find('users').debug().callback(console.log);\n```\n","entries":[{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count(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([connection], query, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.exec()","signature":"db.exec(filter, callback)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([connection], options)","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.promise()","signature":"db.promise([$])","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, fn)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.userid()","signature":"builder.userid(value)","since":"","deprecated":false},{"type":"method","name":"builder.equal()","signature":"builder.equal(obj)","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.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","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(value)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, type, 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.gridfields()","signature":"builder.gridfields(fields, [allowed])","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.gridsort()","signature":"builder.gridsort(sort, [map])","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.autoquery()","signature":"builder.autoquery(query, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autoqueryjson()","signature":"builder.autoqueryjson($, column, schema, [defsort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, query, [type], [column])","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(message, [reverse])","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.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:51.296Z"}
{"id":"JafwSC3Yx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/postgresql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"PostgreSQL","summary":"DATA.init(), the connection string, the SQL results and errors, and the PostgreSQL client.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/postgresql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# PostgreSQL\n\n> DATA.init(), the connection string, the SQL results and errors, and the PostgreSQL client.\n\n`DATA.init()` and its connection string, what the PostgreSQL adapter returns, the operators of the payload, the errors, `PG_ESCAPE()` and the client `total5/client-postgresql`. The methods of the QueryBuilder are in the reference of [QueryBuilder](../../reference/querybuilder/). An introduction with examples is in the guide [PostgreSQL](../../guides/postgresql/).\n\n## API\n\n### DATA.init([name], [connection], [onerror])\n\nType: `method`\n\nRegisters a PostgreSQL connection for the QueryBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | The connection name. |\n| `connection` | `String` | no |  | The connection string: `postgresql://user:password@host:port/database?options`. See the connection string. |\n| `onerror` | `Function` | no |  | `function(message)` called for every failed query. |\n\nRegisters an adapter (`NEWDB()`) with the name `name` that runs the queries of `DATA` and `DB()` on PostgreSQL. The connection `default` serves the tables without a prefix, any other connection the tables with its prefix (`DATA.find('logs/tbl_request')`). Calling it again with the same name closes the old pool and replaces the connection. Without `connection` the connection is removed. Every failed query is passed to `onerror` as a text with the error and the first 100 characters of the SQL; without `onerror` it is logged with `ERROR(name)`. The callback of the query gets the error in both cases.\n\nExample: In definitions/db.js\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nExample: A second connection\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nExample: Own error handling\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n});\n```\n\n### postgresql://user:password@host:port/database?options\n\nType: `type`\n\nThe URL of the database and its options.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `pooling` | `Number` | no |  | The maximum number of connections in a pool. Without it every query opens a new connection and closes it at the end. An idle connection of the pool closes after 10 seconds. |\n| `schema` | `String` | no |  | The schema of the tables: `DATA.find('tbl_product')` reads `schema.tbl_product`. `builder.schema(name)` changes it for one query. Raw queries do not use it. |\n| `sslmode` | `String` | no | `'disable'` | `disable`, `prefer`, `allow`, `require`, `no-verify`, `verify-ca` or `verify-full`. |\n| `ssl` | `Boolean` | no |  | `true` or `1` is the same as `sslmode=require`. |\n| `connect_timeout` | `Number` | no |  | Seconds to wait for the connection. Then the query fails with `Connection timeout`. |\n| `application_name` | `String` | no |  | The name of the connections in `pg_stat_activity`. |\n| `host` | `String` | no |  | Replaces the host of the URL. A value that starts with `/` is the directory of a Unix socket. |\n| `port, user, password, dbname` | `String` | no |  | Replace the parts of the URL. |\n\nThe port defaults to `5432`. Without a database name the client uses the database named like the user. Special characters of the user name and the password must be encoded with `encodeURIComponent()`. The options go in the query string. Other options are ignored.\n\nThe values of `sslmode`: `disable` (default) is not encrypted; `prefer` and `allow` encrypt when the server supports SSL; `require` and `no-verify` encrypt without checking the certificate and fail with `The server does not support SSL connections` when the server has no SSL; `verify-ca` and `verify-full` encrypt and the certificate must be valid.\n\nThe client signs in with a password in plain text, MD5 or SCRAM-SHA-256, as the server asks.\n\nExample: In the config file\n```text\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nExample: Options\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\n### { '+stock': 5, '=dtupdated': 'NOW()' }\n\nType: `type`\n\nKeys of the update() payload that change the value in the database.\n\nThe first character of a key in the payload of `update()`:\n\n| Key | SQL |\n| --- | --- |\n| `+name`, `-name`, `*name`, `/name` | `\"name\"=COALESCE(\"name\",0)+$1` (and `-`, `*`, `/`) |\n| `>name` | `\"name\"=GREATEST(\"name\",$1)` |\n| `<name` | `\"name\"=LEAST(\"name\",$1)` |\n| `!name` | `\"name\"=NOT \"name\"` |\n| `=name` | `\"name\"=value`, the value is raw SQL |\n| `#name` | The same as `=`, but `insert()` leaves the key out |\n\nIn `insert()` (also the insert of an upsert) the character is removed: the column gets the value (`0` when it is empty), `!` inserts `FALSE` and `=` inserts the raw SQL. Keys without an operator are sent as parameters.\n\nExample: Stock\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n```\n\nExample: A daily counter (upsert)\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n```\n\n### callback(err, response)\n\nType: `type`\n\nWhat each operation of the QueryBuilder returns on PostgreSQL.\n\n| Operation | Response |\n| --- | --- |\n| `find()` | An array of rows. |\n| `read()` | One row or `null`. |\n| `list()` | `{ items, count, page, limit, pages }`; the adapter runs the page and `SELECT COUNT(1)`. |\n| `check()` | `true` or `false`. |\n| `count()` | A number. |\n| `scalar()` | A number for `sum`, `avg`, `min`, `max` and `count`; rows `{ key, value }` for `group`. |\n| `insert()` | The number of inserted rows, the value of the `primarykey()` column, or the inserted row with `returning()`. |\n| `update()` | The number of changed rows, an array of rows with `returning()`, one row with `returning()` and `first()`. |\n| `remove()` | The number of removed rows, or an array of rows with `returning()`. |\n| `query()` | An array of rows; `undefined` for SQL with several statements. |\n| `truncate()`, `drop()` | Run `TRUNCATE TABLE … RESTART IDENTITY` and `DROP TABLE …`. |\n\nValues: `boolean` is a `Boolean`; `smallint`, `integer`, `real`, `double precision` and `numeric` are numbers; `bigint` is a `String`; `json` and `jsonb` are parsed (texts in the ISO date format become `Date` objects); `date`, `timestamp` and `timestamptz` are `Date` objects; `bytea` is a `Buffer`; arrays are arrays; other types are strings.\n\nExample: Returning\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n```\n\n### err\n\nType: `type`\n\nThe error of a failed query.\n\nAn error of the server is an `Error` with the message of PostgreSQL and the fields the server sends: `code` (the SQLSTATE code), `severity`, `detail`, `hint`, `position`, `where`, `schema`, `table`, `column`, `datatype`, `constraint` and `routine`. Errors of the connection are `Error` objects of Node.js (`ECONNREFUSED`…) or `Connection timeout`, `The server does not support SSL connections` and `Pool is closed`.\n\nExample: A duplicate key\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\n### PG_ESCAPE(value)\n\nType: `method`\n\nEscapes a value for a PostgreSQL query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value. |\n\nReturns: `String` The SQL literal.\n\nReturns the value as an SQL literal, the same way the adapter writes the values of conditions: a string in single quotes (`'O''Brien'`, with the prefix `E` when it contains a backslash), a number and a boolean as they are, `null` and `undefined` as `null`, an array as `ARRAY[…]`, a `Date` as `'yyyy-MM-dd HH:mm:ss'` and an object as its JSON in quotes. A function is called and its result is escaped. The global exists after the first `DATA.init()`.\n\nExample: Escaping\n```js\nDATA.query('SELECT id FROM eshop.tbl_product WHERE name=' + PG_ESCAPE(\"Kid's watch\")).callback(console.log);\n```\n\n### require('total5/client-postgresql')\n\nType: `method`\n\nThe PostgreSQL client without the QueryBuilder.\n\nReturns: `Object` The module.\n\nThe module exports `connect()`, `pool()`, `types` and the classes `Client` and `Pool`. The adapter of `DATA.init()` uses the same module, so a change in `types` applies to both.\n\nExample: Require\n```js\nconst PG = require('total5/client-postgresql');\n```\n\n### PG.connect(options, callback)\n\nType: `method`\n\nOpens one connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | The connection string or the options. |\n| `callback` | `Function` | yes |  | `function(err, client)`. |\n\nReturns: `Client`\n\n`options` is a connection string or an object with `connectionString`, `host`, `port`, `user`, `password`, `database`, `ssl` (`true`, an `sslmode` value or an object of options for `tls.connect()`), `timeout` (milliseconds) and `name` (the application name). Close the connection with `client.end()` or `client.close()`.\n\nExample: One connection\n```js\nconst PG = require('total5/client-postgresql');\n\nPG.connect(CONF.database, async function(err, client) {\n\tvar response = await client.query('SELECT $1::int + 1 AS value', [41]);\n\tconsole.log(response.rows); // [ { value: 42 } ]\n\tclient.close();\n});\n```\n\n### PG.pool(options, [max])\n\nType: `method`\n\nCreates a pool of connections.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | The connection string or the options of `PG.connect()`. |\n| `max` | `Number` | no | `10` | The maximum number of connections. |\n\nReturns: `Pool`\n\nThe pool opens up to `max` connections (default 10) and reuses them. When `options` is an object, `max` and `idle` (milliseconds an idle connection stays open, default 10000) can be in it too. A connection that comes back in an open transaction is closed.\n\nExample: A pool\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.query('SELECT id FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.rows);\n});\n```\n\n### pool.connect(callback)\n\nType: `method`\n\nBorrows a connection from the pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, client, release)`. |\n\nThe callback gets the connection and a `release` function that returns it to the pool (`client.release()` does the same). Use it for several queries on one connection, for example a transaction.\n\nExample: A transaction\n```js\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n### client.query(sql, [params], [callback])\n\nType: `method`\n\nRuns a query on the connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | The SQL. |\n| `params` | `Array` | no |  | The values of the parameters. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Without `callback`. The response is `{ command, rowCount, rows, fields }`.\n\nThe parameters are `$1`, `$2`… in the SQL. Without parameters the SQL can have several statements; the response is then an array with one result for each statement. A `Date` is sent with its time zone, an object as JSON, a `Buffer` as binary data and an array as a PostgreSQL array, or as JSON for a `json` or `jsonb` parameter. Without `callback` it returns a promise. `pool.query()` takes the same arguments and runs the query on a free connection of the pool.\n\nExample: Query\n```js\nclient.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.command, response.rowCount, response.rows);\n});\n```\n\n### client.close([callback])\n\nType: `method`\n\nReturns the connection to its pool or closes it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called when it is done. |\n\nA connection of a pool goes back to the pool (alias `client.release()`). Other connections are closed after their pending queries, like `client.end([callback])`.\n\nExample: Close\n```js\nclient.close();\n```\n\n### pool.end([callback])\n\nType: `method`\n\nCloses all connections of the pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called when all connections are closed. |\n\nIdle connections close at once, busy ones when they are released. Waiting and later requests fail with `Pool is closed`.\n\nExample: End\n```js\npool.end(() => console.log('closed'));\n```\n\n### PG.types\n\nType: `property`\n\nThe parsers of values by the OID of the type.\n\nReturns: `Object`\n\nAn object `{ oid: function(text) }`. A type without a parser is returned as a string. `bigint` (OID 20) has no parser because its values do not always fit into a JavaScript number.\n\nExample: bigint as a number\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value;\n```\n","entries":[{"type":"method","name":"DATA.init()","signature":"DATA.init([name], [connection], [onerror])","since":"","deprecated":false},{"type":"type","name":"Connection string","signature":"postgresql://user:password@host:port/database?options","since":"","deprecated":false},{"type":"type","name":"Payload operators","signature":"{ '+stock': 5, '=dtupdated': 'NOW()' }","since":"","deprecated":false},{"type":"type","name":"Results","signature":"callback(err, response)","since":"","deprecated":false},{"type":"type","name":"Errors","signature":"err","since":"","deprecated":false},{"type":"method","name":"PG_ESCAPE()","signature":"PG_ESCAPE(value)","since":"","deprecated":false},{"type":"method","name":"require('total5/client-postgresql')","signature":"require('total5/client-postgresql')","since":"","deprecated":false},{"type":"method","name":"PG.connect()","signature":"PG.connect(options, callback)","since":"","deprecated":false},{"type":"method","name":"PG.pool()","signature":"PG.pool(options, [max])","since":"","deprecated":false},{"type":"method","name":"pool.connect()","signature":"pool.connect(callback)","since":"","deprecated":false},{"type":"method","name":"client.query()","signature":"client.query(sql, [params], [callback])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([callback])","since":"","deprecated":false},{"type":"method","name":"pool.end()","signature":"pool.end([callback])","since":"","deprecated":false},{"type":"property","name":"PG.types","signature":"PG.types","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JafwSC3Yx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/postgresql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"PostgreSQL","summary":"DATA.init(), der Connection String, die SQL-Ergebnisse und Fehler sowie der PostgreSQL-Client.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/postgresql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# PostgreSQL\n\n> DATA.init(), der Connection String, die SQL-Ergebnisse und Fehler sowie der PostgreSQL-Client.\n\n`DATA.init()` und sein Connection String, was der PostgreSQL-Adapter zurückgibt, die Operatoren des Payloads, die Fehler, `PG_ESCAPE()` und der Client `total5/client-postgresql`. Die Methoden des QueryBuilders stehen in der Referenz [QueryBuilder](../../reference/querybuilder/). Eine Einführung mit Beispielen findest du in der Anleitung [PostgreSQL](../../guides/postgresql/).\n\n## API\n\n### DATA.init([name], [connection], [onerror])\n\nType: `method`\n\nRegistriert eine PostgreSQL-Verbindung für den QueryBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Der Verbindungsname. |\n| `connection` | `String` | no |  | Der Connection String: `postgresql://user:password@host:port/database?options`. Siehe den Connection String. |\n| `onerror` | `Function` | no |  | `function(message)`, aufgerufen für jede fehlgeschlagene Abfrage. |\n\nRegistriert einen Adapter (`NEWDB()`) mit dem Namen `name`, der die Abfragen von `DATA` und `DB()` auf PostgreSQL ausführt. Die Verbindung `default` bedient die Tabellen ohne Präfix, jede andere Verbindung die Tabellen mit ihrem Präfix (`DATA.find('logs/tbl_request')`). Ein erneuter Aufruf mit demselben Namen schließt den alten Pool und ersetzt die Verbindung. Ohne `connection` wird die Verbindung entfernt. Jede fehlgeschlagene Abfrage wird an `onerror` als Text mit dem Fehler und den ersten 100 Zeichen des SQL übergeben; ohne `onerror` wird sie mit `ERROR(name)` geloggt. Der Callback der Abfrage erhält den Fehler in beiden Fällen.\n\nExample: In definitions/db.js\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nExample: Eine zweite Verbindung\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nExample: Eigene Fehlerbehandlung\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n});\n```\n\n### postgresql://user:password@host:port/database?options\n\nType: `type`\n\nDie URL der Datenbank und ihre Optionen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `pooling` | `Number` | no |  | Die maximale Anzahl an Verbindungen in einem Pool. Ohne diese Option öffnet jede Abfrage eine neue Verbindung und schließt sie am Ende. Eine unbenutzte Verbindung des Pools wird nach 10 Sekunden geschlossen. |\n| `schema` | `String` | no |  | Das Schema der Tabellen: `DATA.find('tbl_product')` liest `schema.tbl_product`. `builder.schema(name)` ändert es für eine einzelne Abfrage. Rohe Abfragen verwenden es nicht. |\n| `sslmode` | `String` | no | `'disable'` | `disable`, `prefer`, `allow`, `require`, `no-verify`, `verify-ca` oder `verify-full`. |\n| `ssl` | `Boolean` | no |  | `true` oder `1` ist dasselbe wie `sslmode=require`. |\n| `connect_timeout` | `Number` | no |  | Sekunden, die auf die Verbindung gewartet wird. Danach schlägt die Abfrage mit `Connection timeout` fehl. |\n| `application_name` | `String` | no |  | Der Name der Verbindungen in `pg_stat_activity`. |\n| `host` | `String` | no |  | Ersetzt den Host der URL. Ein Wert, der mit `/` beginnt, ist das Verzeichnis eines Unix-Sockets. |\n| `port, user, password, dbname` | `String` | no |  | Ersetzen die Teile der URL. |\n\nDer Port ist standardmäßig `5432`. Ohne Datenbanknamen verwendet der Client die Datenbank, die wie der Benutzer heißt. Sonderzeichen im Benutzernamen und im Passwort müssen mit `encodeURIComponent()` kodiert werden. Die Optionen stehen im Query String. Andere Optionen werden ignoriert.\n\nDie Werte von `sslmode`: `disable` (Standard) ist nicht verschlüsselt; `prefer` und `allow` verschlüsseln, wenn der Server SSL unterstützt; `require` und `no-verify` verschlüsseln, ohne das Zertifikat zu prüfen, und schlagen mit `The server does not support SSL connections` fehl, wenn der Server kein SSL hat; `verify-ca` und `verify-full` verschlüsseln, und das Zertifikat muss gültig sein.\n\nDer Client meldet sich mit einem Passwort im Klartext, mit MD5 oder mit SCRAM-SHA-256 an, je nachdem, was der Server verlangt.\n\nExample: In der Konfigurationsdatei\n```text\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nExample: Optionen\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\n### { '+stock': 5, '=dtupdated': 'NOW()' }\n\nType: `type`\n\nSchlüssel des update()-Payloads, die den Wert in der Datenbank verändern.\n\nDas erste Zeichen eines Schlüssels im Payload von `update()`:\n\n| Schlüssel | SQL |\n| --- | --- |\n| `+name`, `-name`, `*name`, `/name` | `\"name\"=COALESCE(\"name\",0)+$1` (und `-`, `*`, `/`) |\n| `>name` | `\"name\"=GREATEST(\"name\",$1)` |\n| `<name` | `\"name\"=LEAST(\"name\",$1)` |\n| `!name` | `\"name\"=NOT \"name\"` |\n| `=name` | `\"name\"=value`, der Wert ist rohes SQL |\n| `#name` | Dasselbe wie `=`, aber `insert()` lässt den Schlüssel weg |\n\nIn `insert()` (auch im Insert eines Upserts) wird das Zeichen entfernt: Die Spalte erhält den Wert (`0`, wenn er leer ist), `!` fügt `FALSE` ein und `=` das rohe SQL. Schlüssel ohne Operator werden als Parameter gesendet.\n\nExample: Lagerbestand\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n```\n\nExample: Ein Tageszähler (Upsert)\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n```\n\n### callback(err, response)\n\nType: `type`\n\nWas jede Operation des QueryBuilders auf PostgreSQL zurückgibt.\n\n| Operation | Antwort |\n| --- | --- |\n| `find()` | Ein Array von Zeilen. |\n| `read()` | Eine Zeile oder `null`. |\n| `list()` | `{ items, count, page, limit, pages }`; der Adapter führt die Seite und `SELECT COUNT(1)` aus. |\n| `check()` | `true` oder `false`. |\n| `count()` | Eine Zahl. |\n| `scalar()` | Eine Zahl für `sum`, `avg`, `min`, `max` und `count`; Zeilen `{ key, value }` für `group`. |\n| `insert()` | Die Anzahl der eingefügten Zeilen, der Wert der Spalte aus `primarykey()` oder mit `returning()` die eingefügte Zeile. |\n| `update()` | Die Anzahl der geänderten Zeilen, mit `returning()` ein Array von Zeilen, mit `returning()` und `first()` eine Zeile. |\n| `remove()` | Die Anzahl der entfernten Zeilen oder mit `returning()` ein Array von Zeilen. |\n| `query()` | Ein Array von Zeilen; `undefined` bei SQL mit mehreren Anweisungen. |\n| `truncate()`, `drop()` | Führen `TRUNCATE TABLE … RESTART IDENTITY` und `DROP TABLE …` aus. |\n\nWerte: `boolean` ist ein `Boolean`; `smallint`, `integer`, `real`, `double precision` und `numeric` sind Zahlen; `bigint` ist ein `String`; `json` und `jsonb` werden geparst (Texte im ISO-Datumsformat werden zu `Date`-Objekten); `date`, `timestamp` und `timestamptz` sind `Date`-Objekte; `bytea` ist ein `Buffer`; Arrays sind Arrays; andere Typen sind Strings.\n\nExample: Returning\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n```\n\n### err\n\nType: `type`\n\nDer Fehler einer fehlgeschlagenen Abfrage.\n\nEin Fehler des Servers ist ein `Error` mit der Meldung von PostgreSQL und den Feldern, die der Server sendet: `code` (der SQLSTATE-Code), `severity`, `detail`, `hint`, `position`, `where`, `schema`, `table`, `column`, `datatype`, `constraint` und `routine`. Fehler der Verbindung sind `Error`-Objekte von Node.js (`ECONNREFUSED`…) oder `Connection timeout`, `The server does not support SSL connections` und `Pool is closed`.\n\nExample: Ein doppelter Schlüssel\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\n### PG_ESCAPE(value)\n\nType: `method`\n\nEscaped einen Wert für eine PostgreSQL-Abfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der Wert. |\n\nReturns: `String` Das SQL-Literal.\n\nGibt den Wert als SQL-Literal zurück, genauso wie der Adapter die Werte von Bedingungen schreibt: einen String in einfachen Anführungszeichen (`'O''Brien'`, mit dem Präfix `E`, wenn er einen Backslash enthält), eine Zahl und einen Boolean so, wie sie sind, `null` und `undefined` als `null`, ein Array als `ARRAY[…]`, ein `Date` als `'yyyy-MM-dd HH:mm:ss'` und ein Objekt als sein JSON in Anführungszeichen. Eine Funktion wird aufgerufen und ihr Ergebnis escaped. Die globale Funktion existiert nach dem ersten `DATA.init()`.\n\nExample: Escaping\n```js\nDATA.query('SELECT id FROM eshop.tbl_product WHERE name=' + PG_ESCAPE(\"Kid's watch\")).callback(console.log);\n```\n\n### require('total5/client-postgresql')\n\nType: `method`\n\nDer PostgreSQL-Client ohne QueryBuilder.\n\nReturns: `Object` Das Modul.\n\nDas Modul exportiert `connect()`, `pool()`, `types` und die Klassen `Client` und `Pool`. Der Adapter von `DATA.init()` verwendet dasselbe Modul, daher gilt eine Änderung in `types` für beide.\n\nExample: Require\n```js\nconst PG = require('total5/client-postgresql');\n```\n\n### PG.connect(options, callback)\n\nType: `method`\n\nÖffnet eine Verbindung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | Der Connection String oder die Optionen. |\n| `callback` | `Function` | yes |  | `function(err, client)`. |\n\nReturns: `Client`\n\n`options` ist ein Connection String oder ein Objekt mit `connectionString`, `host`, `port`, `user`, `password`, `database`, `ssl` (`true`, ein Wert von `sslmode` oder ein Objekt mit Optionen für `tls.connect()`), `timeout` (Millisekunden) und `name` (der Anwendungsname). Schließe die Verbindung mit `client.end()` oder `client.close()`.\n\nExample: Eine Verbindung\n```js\nconst PG = require('total5/client-postgresql');\n\nPG.connect(CONF.database, async function(err, client) {\n\tvar response = await client.query('SELECT $1::int + 1 AS value', [41]);\n\tconsole.log(response.rows); // [ { value: 42 } ]\n\tclient.close();\n});\n```\n\n### PG.pool(options, [max])\n\nType: `method`\n\nErstellt einen Pool von Verbindungen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | Der Connection String oder die Optionen von `PG.connect()`. |\n| `max` | `Number` | no | `10` | Die maximale Anzahl an Verbindungen. |\n\nReturns: `Pool`\n\nDer Pool öffnet bis zu `max` Verbindungen (Standard 10) und verwendet sie wieder. Wenn `options` ein Objekt ist, können auch `max` und `idle` (Millisekunden, die eine unbenutzte Verbindung offen bleibt, Standard 10000) darin stehen. Eine Verbindung, die in einer offenen Transaktion zurückkommt, wird geschlossen.\n\nExample: Ein Pool\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.query('SELECT id FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.rows);\n});\n```\n\n### pool.connect(callback)\n\nType: `method`\n\nLeiht eine Verbindung aus dem Pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, client, release)`. |\n\nDer Callback erhält die Verbindung und eine Funktion `release`, die sie an den Pool zurückgibt (`client.release()` macht dasselbe). Verwende es für mehrere Abfragen auf einer Verbindung, zum Beispiel für eine Transaktion.\n\nExample: Eine Transaktion\n```js\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n### client.query(sql, [params], [callback])\n\nType: `method`\n\nFührt eine Abfrage auf der Verbindung aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | Das SQL. |\n| `params` | `Array` | no |  | Die Werte der Parameter. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Ohne `callback`. Die Antwort ist `{ command, rowCount, rows, fields }`.\n\nDie Parameter sind `$1`, `$2`… im SQL. Ohne Parameter kann das SQL mehrere Anweisungen enthalten; die Antwort ist dann ein Array mit einem Ergebnis für jede Anweisung. Ein `Date` wird mit seiner Zeitzone gesendet, ein Objekt als JSON, ein `Buffer` als Binärdaten und ein Array als PostgreSQL-Array oder als JSON bei einem `json`- oder `jsonb`-Parameter. Ohne `callback` gibt es eine Promise zurück. `pool.query()` nimmt dieselben Argumente und führt die Abfrage auf einer freien Verbindung des Pools aus.\n\nExample: Abfrage\n```js\nclient.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.command, response.rowCount, response.rows);\n});\n```\n\n### client.close([callback])\n\nType: `method`\n\nGibt die Verbindung an ihren Pool zurück oder schließt sie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn es fertig ist. |\n\nEine Verbindung eines Pools geht zurück in den Pool (Alias `client.release()`). Andere Verbindungen werden nach ihren ausstehenden Abfragen geschlossen, wie `client.end([callback])`.\n\nExample: Schließen\n```js\nclient.close();\n```\n\n### pool.end([callback])\n\nType: `method`\n\nSchließt alle Verbindungen des Pools.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn alle Verbindungen geschlossen sind. |\n\nUnbenutzte Verbindungen werden sofort geschlossen, belegte, sobald sie freigegeben werden. Wartende und spätere Anfragen schlagen mit `Pool is closed` fehl.\n\nExample: Beenden\n```js\npool.end(() => console.log('closed'));\n```\n\n### PG.types\n\nType: `property`\n\nDie Parser der Werte nach der OID des Typs.\n\nReturns: `Object`\n\nEin Objekt `{ oid: function(text) }`. Ein Typ ohne Parser wird als String zurückgegeben. `bigint` (OID 20) hat keinen Parser, weil seine Werte nicht immer in eine JavaScript-Zahl passen.\n\nExample: bigint als Zahl\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value;\n```\n","entries":[{"type":"method","name":"DATA.init()","signature":"DATA.init([name], [connection], [onerror])","since":"","deprecated":false},{"type":"type","name":"Connection string","signature":"postgresql://user:password@host:port/database?options","since":"","deprecated":false},{"type":"type","name":"Payload operators","signature":"{ '+stock': 5, '=dtupdated': 'NOW()' }","since":"","deprecated":false},{"type":"type","name":"Results","signature":"callback(err, response)","since":"","deprecated":false},{"type":"type","name":"Errors","signature":"err","since":"","deprecated":false},{"type":"method","name":"PG_ESCAPE()","signature":"PG_ESCAPE(value)","since":"","deprecated":false},{"type":"method","name":"require('total5/client-postgresql')","signature":"require('total5/client-postgresql')","since":"","deprecated":false},{"type":"method","name":"PG.connect()","signature":"PG.connect(options, callback)","since":"","deprecated":false},{"type":"method","name":"PG.pool()","signature":"PG.pool(options, [max])","since":"","deprecated":false},{"type":"method","name":"pool.connect()","signature":"pool.connect(callback)","since":"","deprecated":false},{"type":"method","name":"client.query()","signature":"client.query(sql, [params], [callback])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([callback])","since":"","deprecated":false},{"type":"method","name":"pool.end()","signature":"pool.end([callback])","since":"","deprecated":false},{"type":"property","name":"PG.types","signature":"PG.types","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JafwSC3Yx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/postgresql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"PostgreSQL","summary":"DATA.init(), la cadena de conexión, los resultados y errores del SQL, y el cliente de PostgreSQL.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/postgresql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# PostgreSQL\n\n> DATA.init(), la cadena de conexión, los resultados y errores del SQL, y el cliente de PostgreSQL.\n\n`DATA.init()` y su cadena de conexión, lo que devuelve el adaptador de PostgreSQL, los operadores de la carga útil, los errores, `PG_ESCAPE()` y el cliente `total5/client-postgresql`. Los métodos del QueryBuilder están en la referencia de [QueryBuilder](../../reference/querybuilder/). Una introducción con ejemplos está en la guía [PostgreSQL](../../guides/postgresql/).\n\n## API\n\n### DATA.init([name], [connection], [onerror])\n\nType: `method`\n\nRegistra una conexión de PostgreSQL para el QueryBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | El nombre de la conexión. |\n| `connection` | `String` | no |  | La cadena de conexión: `postgresql://user:password@host:port/database?options`. Consulta la cadena de conexión. |\n| `onerror` | `Function` | no |  | `function(message)` que se llama para cada consulta fallida. |\n\nRegistra un adaptador (`NEWDB()`) con el nombre `name` que ejecuta las consultas de `DATA` y `DB()` sobre PostgreSQL. La conexión `default` atiende las tablas sin prefijo, cualquier otra conexión las tablas con su prefijo (`DATA.find('logs/tbl_request')`). Llamarlo de nuevo con el mismo nombre cierra el pool antiguo y sustituye la conexión. Sin `connection` se elimina la conexión. Cada consulta fallida se pasa a `onerror` como un texto con el error y los primeros 100 caracteres del SQL; sin `onerror` se registra con `ERROR(name)`. El callback de la consulta recibe el error en ambos casos.\n\nExample: En definitions/db.js\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nExample: Una segunda conexión\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nExample: Gestión de errores propia\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n});\n```\n\n### postgresql://user:password@host:port/database?options\n\nType: `type`\n\nLa URL de la base de datos y sus opciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `pooling` | `Number` | no |  | El número máximo de conexiones en un pool. Sin ella, cada consulta abre una conexión nueva y la cierra al terminar. Una conexión inactiva del pool se cierra a los 10 segundos. |\n| `schema` | `String` | no |  | El esquema de las tablas: `DATA.find('tbl_product')` lee `schema.tbl_product`. `builder.schema(name)` lo cambia para una consulta. Las consultas en bruto no lo usan. |\n| `sslmode` | `String` | no | `'disable'` | `disable`, `prefer`, `allow`, `require`, `no-verify`, `verify-ca` o `verify-full`. |\n| `ssl` | `Boolean` | no |  | `true` o `1` es lo mismo que `sslmode=require`. |\n| `connect_timeout` | `Number` | no |  | Segundos de espera para la conexión. Después la consulta falla con `Connection timeout`. |\n| `application_name` | `String` | no |  | El nombre de las conexiones en `pg_stat_activity`. |\n| `host` | `String` | no |  | Sustituye el host de la URL. Un valor que empieza por `/` es el directorio de un socket Unix. |\n| `port, user, password, dbname` | `String` | no |  | Sustituyen las partes de la URL. |\n\nEl puerto por defecto es `5432`. Sin nombre de base de datos, el cliente usa la base de datos que se llama como el usuario. Los caracteres especiales del nombre de usuario y de la contraseña se deben codificar con `encodeURIComponent()`. Las opciones van en el query string. Las demás opciones se ignoran.\n\nLos valores de `sslmode`: `disable` (por defecto) no cifra; `prefer` y `allow` cifran cuando el servidor admite SSL; `require` y `no-verify` cifran sin comprobar el certificado y fallan con `The server does not support SSL connections` cuando el servidor no tiene SSL; `verify-ca` y `verify-full` cifran y el certificado debe ser válido.\n\nEl cliente inicia sesión con una contraseña en texto plano, MD5 o SCRAM-SHA-256, según lo pida el servidor.\n\nExample: En el archivo config\n```text\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nExample: Opciones\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\n### { '+stock': 5, '=dtupdated': 'NOW()' }\n\nType: `type`\n\nClaves de la carga útil de update() que cambian el valor en la base de datos.\n\nReturns: `undefined` Nada\n\nEl primer carácter de una clave en la carga útil de `update()`:\n\n| Clave | SQL |\n| --- | --- |\n| `+name`, `-name`, `*name`, `/name` | `\"name\"=COALESCE(\"name\",0)+$1` (y `-`, `*`, `/`) |\n| `>name` | `\"name\"=GREATEST(\"name\",$1)` |\n| `<name` | `\"name\"=LEAST(\"name\",$1)` |\n| `!name` | `\"name\"=NOT \"name\"` |\n| `=name` | `\"name\"=value`, el valor es SQL en bruto |\n| `#name` | Igual que `=`, pero `insert()` omite la clave |\n\nEn `insert()` (también el insert de un upsert) el carácter se quita: la columna recibe el valor (`0` cuando está vacío), `!` inserta `FALSE` y `=` inserta el SQL en bruto. Las claves sin operador se envían como parámetros.\n\nExample: Stock\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n```\n\nExample: Un contador diario (upsert)\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n```\n\n### callback(err, response)\n\nType: `type`\n\nLo que devuelve cada operación del QueryBuilder en PostgreSQL.\n\n| Operación | Respuesta |\n| --- | --- |\n| `find()` | Un array de filas. |\n| `read()` | Una fila o `null`. |\n| `list()` | `{ items, count, page, limit, pages }`; el adaptador ejecuta la página y `SELECT COUNT(1)`. |\n| `check()` | `true` o `false`. |\n| `count()` | Un número. |\n| `scalar()` | Un número para `sum`, `avg`, `min`, `max` y `count`; filas `{ key, value }` para `group`. |\n| `insert()` | El número de filas insertadas, el valor de la columna `primarykey()`, o la fila insertada con `returning()`. |\n| `update()` | El número de filas modificadas, un array de filas con `returning()`, una fila con `returning()` y `first()`. |\n| `remove()` | El número de filas eliminadas, o un array de filas con `returning()`. |\n| `query()` | Un array de filas; `undefined` para SQL con varias sentencias. |\n| `truncate()`, `drop()` | Ejecutan `TRUNCATE TABLE … RESTART IDENTITY` y `DROP TABLE …`. |\n\nValores: `boolean` es un `Boolean`; `smallint`, `integer`, `real`, `double precision` y `numeric` son números; `bigint` es un `String`; `json` y `jsonb` se parsean (los textos en formato de fecha ISO se convierten en objetos `Date`); `date`, `timestamp` y `timestamptz` son objetos `Date`; `bytea` es un `Buffer`; los arrays son arrays; los demás tipos son strings.\n\nExample: Returning\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n```\n\n### err\n\nType: `type`\n\nEl error de una consulta fallida.\n\nUn error del servidor es un `Error` con el mensaje de PostgreSQL y los campos que envía el servidor: `code` (el código SQLSTATE), `severity`, `detail`, `hint`, `position`, `where`, `schema`, `table`, `column`, `datatype`, `constraint` y `routine`. Los errores de la conexión son objetos `Error` de Node.js (`ECONNREFUSED`…) o `Connection timeout`, `The server does not support SSL connections` y `Pool is closed`.\n\nExample: Una clave duplicada\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\n### PG_ESCAPE(value)\n\nType: `method`\n\nEscapa un valor para una consulta de PostgreSQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor. |\n\nReturns: `String` El literal SQL.\n\nDevuelve el valor como literal SQL, igual que el adaptador escribe los valores de las condiciones: un string entre comillas simples (`'O''Brien'`, con el prefijo `E` cuando contiene una barra invertida), un número y un booleano tal cual, `null` y `undefined` como `null`, un array como `ARRAY[…]`, un `Date` como `'yyyy-MM-dd HH:mm:ss'` y un objeto como su JSON entre comillas. Una función se llama y se escapa su resultado. La global existe después del primer `DATA.init()`.\n\nExample: Escapar\n```js\nDATA.query('SELECT id FROM eshop.tbl_product WHERE name=' + PG_ESCAPE(\"Kid's watch\")).callback(console.log);\n```\n\n### require('total5/client-postgresql')\n\nType: `method`\n\nEl cliente de PostgreSQL sin el QueryBuilder.\n\nReturns: `Object` El módulo.\n\nEl módulo exporta `connect()`, `pool()`, `types` y las clases `Client` y `Pool`. El adaptador de `DATA.init()` usa el mismo módulo, así que un cambio en `types` se aplica a ambos.\n\nExample: Require\n```js\nconst PG = require('total5/client-postgresql');\n```\n\n### PG.connect(options, callback)\n\nType: `method`\n\nAbre una conexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | La cadena de conexión o las opciones. |\n| `callback` | `Function` | yes |  | `function(err, client)`. |\n\nReturns: `Client`\n\n`options` es una cadena de conexión o un objeto con `connectionString`, `host`, `port`, `user`, `password`, `database`, `ssl` (`true`, un valor de `sslmode` o un objeto de opciones para `tls.connect()`), `timeout` (milisegundos) y `name` (el nombre de la aplicación). Cierra la conexión con `client.end()` o `client.close()`.\n\nExample: Una conexión\n```js\nconst PG = require('total5/client-postgresql');\n\nPG.connect(CONF.database, async function(err, client) {\n\tvar response = await client.query('SELECT $1::int + 1 AS value', [41]);\n\tconsole.log(response.rows); // [ { value: 42 } ]\n\tclient.close();\n});\n```\n\n### PG.pool(options, [max])\n\nType: `method`\n\nCrea un pool de conexiones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | La cadena de conexión o las opciones de `PG.connect()`. |\n| `max` | `Number` | no | `10` | El número máximo de conexiones. |\n\nReturns: `Pool`\n\nEl pool abre hasta `max` conexiones (10 por defecto) y las reutiliza. Cuando `options` es un objeto, también puede contener `max` e `idle` (milisegundos que una conexión inactiva sigue abierta, 10000 por defecto). Una conexión que vuelve dentro de una transacción abierta se cierra.\n\nExample: Un pool\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.query('SELECT id FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.rows);\n});\n```\n\n### pool.connect(callback)\n\nType: `method`\n\nToma prestada una conexión del pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, client, release)`. |\n\nEl callback recibe la conexión y una función `release` que la devuelve al pool (`client.release()` hace lo mismo). Úsalo para varias consultas en una conexión, por ejemplo una transacción.\n\nExample: Una transacción\n```js\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n### client.query(sql, [params], [callback])\n\nType: `method`\n\nEjecuta una consulta en la conexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | El SQL. |\n| `params` | `Array` | no |  | Los valores de los parámetros. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Sin `callback`. La respuesta es `{ command, rowCount, rows, fields }`.\n\nLos parámetros son `$1`, `$2`… en el SQL. Sin parámetros, el SQL puede tener varias sentencias; la respuesta es entonces un array con un resultado por sentencia. Un `Date` se envía con su zona horaria, un objeto como JSON, un `Buffer` como datos binarios y un array como array de PostgreSQL, o como JSON para un parámetro `json` o `jsonb`. Sin `callback` devuelve una promesa. `pool.query()` acepta los mismos argumentos y ejecuta la consulta en una conexión libre del pool.\n\nExample: Consulta\n```js\nclient.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.command, response.rowCount, response.rows);\n});\n```\n\n### client.close([callback])\n\nType: `method`\n\nDevuelve la conexión a su pool o la cierra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama cuando termina. |\n\nUna conexión de un pool vuelve al pool (alias `client.release()`). Las demás conexiones se cierran después de sus consultas pendientes, como `client.end([callback])`.\n\nExample: Cerrar\n```js\nclient.close();\n```\n\n### pool.end([callback])\n\nType: `method`\n\nCierra todas las conexiones del pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama cuando todas las conexiones están cerradas. |\n\nLas conexiones inactivas se cierran de inmediato, las ocupadas cuando se liberan. Las peticiones en espera y las posteriores fallan con `Pool is closed`.\n\nExample: Terminar\n```js\npool.end(() => console.log('closed'));\n```\n\n### PG.types\n\nType: `property`\n\nLos parsers de valores según el OID del tipo.\n\nReturns: `Object`\n\nUn objeto `{ oid: function(text) }`. Un tipo sin parser se devuelve como string. `bigint` (OID 20) no tiene parser porque sus valores no siempre caben en un número de JavaScript.\n\nExample: bigint como número\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value;\n```\n","entries":[{"type":"method","name":"DATA.init()","signature":"DATA.init([name], [connection], [onerror])","since":"","deprecated":false},{"type":"type","name":"Connection string","signature":"postgresql://user:password@host:port/database?options","since":"","deprecated":false},{"type":"type","name":"Payload operators","signature":"{ '+stock': 5, '=dtupdated': 'NOW()' }","since":"","deprecated":false},{"type":"type","name":"Results","signature":"callback(err, response)","since":"","deprecated":false},{"type":"type","name":"Errors","signature":"err","since":"","deprecated":false},{"type":"method","name":"PG_ESCAPE()","signature":"PG_ESCAPE(value)","since":"","deprecated":false},{"type":"method","name":"require('total5/client-postgresql')","signature":"require('total5/client-postgresql')","since":"","deprecated":false},{"type":"method","name":"PG.connect()","signature":"PG.connect(options, callback)","since":"","deprecated":false},{"type":"method","name":"PG.pool()","signature":"PG.pool(options, [max])","since":"","deprecated":false},{"type":"method","name":"pool.connect()","signature":"pool.connect(callback)","since":"","deprecated":false},{"type":"method","name":"client.query()","signature":"client.query(sql, [params], [callback])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([callback])","since":"","deprecated":false},{"type":"method","name":"pool.end()","signature":"pool.end([callback])","since":"","deprecated":false},{"type":"property","name":"PG.types","signature":"PG.types","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JafwSC3Yx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/postgresql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"PostgreSQL","summary":"DATA.init(), la chaîne de connexion, les résultats et les erreurs SQL, et le client PostgreSQL.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/postgresql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# PostgreSQL\n\n> DATA.init(), la chaîne de connexion, les résultats et les erreurs SQL, et le client PostgreSQL.\n\n`DATA.init()` et sa chaîne de connexion, ce que renvoie l'adaptateur PostgreSQL, les opérateurs des données envoyées, les erreurs, `PG_ESCAPE()` et le client `total5/client-postgresql`. Les méthodes du QueryBuilder se trouvent dans la référence de [QueryBuilder](../../reference/querybuilder/). Une introduction avec des exemples se trouve dans le guide [PostgreSQL](../../guides/postgresql/).\n\n## API\n\n### DATA.init([name], [connection], [onerror])\n\nType: `method`\n\nEnregistre une connexion PostgreSQL pour le QueryBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Le nom de la connexion. |\n| `connection` | `String` | no |  | La chaîne de connexion : `postgresql://user:password@host:port/database?options`. Voir la chaîne de connexion. |\n| `onerror` | `Function` | no |  | `function(message)` appelée pour chaque requête qui échoue. |\n\nEnregistre un adaptateur (`NEWDB()`) avec le nom `name` qui exécute les requêtes de `DATA` et de `DB()` sur PostgreSQL. La connexion `default` sert les tables sans préfixe, toute autre connexion les tables avec son préfixe (`DATA.find('logs/tbl_request')`). L'appeler à nouveau avec le même nom ferme l'ancien pool et remplace la connexion. Sans `connection`, la connexion est supprimée. Chaque requête qui échoue est passée à `onerror` sous forme de texte avec l'erreur et les 100 premiers caractères du SQL ; sans `onerror`, elle est enregistrée avec `ERROR(name)`. Le callback de la requête reçoit l'erreur dans les deux cas.\n\nExample: Dans definitions/db.js\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nExample: Une deuxième connexion\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nExample: Gestion des erreurs personnalisée\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n});\n```\n\n### postgresql://user:password@host:port/database?options\n\nType: `type`\n\nL'URL de la base de données et ses options.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `pooling` | `Number` | no |  | Le nombre maximal de connexions dans un pool. Sans elle, chaque requête ouvre une nouvelle connexion et la ferme à la fin. Une connexion inactive du pool se ferme après 10 secondes. |\n| `schema` | `String` | no |  | Le schéma des tables : `DATA.find('tbl_product')` lit `schema.tbl_product`. `builder.schema(name)` le change pour une seule requête. Les requêtes brutes ne l'utilisent pas. |\n| `sslmode` | `String` | no | `'disable'` | `disable`, `prefer`, `allow`, `require`, `no-verify`, `verify-ca` ou `verify-full`. |\n| `ssl` | `Boolean` | no |  | `true` ou `1` est identique à `sslmode=require`. |\n| `connect_timeout` | `Number` | no |  | Secondes d'attente pour la connexion. Ensuite la requête échoue avec `Connection timeout`. |\n| `application_name` | `String` | no |  | Le nom des connexions dans `pg_stat_activity`. |\n| `host` | `String` | no |  | Remplace l'hôte de l'URL. Une valeur qui commence par `/` est le dossier d'un socket Unix. |\n| `port, user, password, dbname` | `String` | no |  | Remplacent les parties de l'URL. |\n\nLe port vaut par défaut `5432`. Sans nom de base de données, le client utilise la base de données qui porte le nom de l'utilisateur. Les caractères spéciaux du nom d'utilisateur et du mot de passe doivent être encodés avec `encodeURIComponent()`. Les options vont dans la query string. Les autres options sont ignorées.\n\nLes valeurs de `sslmode` : `disable` (par défaut) n'est pas chiffré ; `prefer` et `allow` chiffrent quand le serveur prend en charge SSL ; `require` et `no-verify` chiffrent sans vérifier le certificat et échouent avec `The server does not support SSL connections` quand le serveur n'a pas SSL ; `verify-ca` et `verify-full` chiffrent et le certificat doit être valide.\n\nLe client se connecte avec un mot de passe en texte clair, MD5 ou SCRAM-SHA-256, selon ce que demande le serveur.\n\nExample: Dans le fichier config\n```text\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nExample: Options\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\n### { '+stock': 5, '=dtupdated': 'NOW()' }\n\nType: `type`\n\nClés des données envoyées à update() qui modifient la valeur dans la base de données.\n\nLe premier caractère d'une clé dans les données envoyées à `update()` :\n\n| Clé | SQL |\n| --- | --- |\n| `+name`, `-name`, `*name`, `/name` | `\"name\"=COALESCE(\"name\",0)+$1` (et `-`, `*`, `/`) |\n| `>name` | `\"name\"=GREATEST(\"name\",$1)` |\n| `<name` | `\"name\"=LEAST(\"name\",$1)` |\n| `!name` | `\"name\"=NOT \"name\"` |\n| `=name` | `\"name\"=value`, la valeur est du SQL brut |\n| `#name` | Identique à `=`, mais `insert()` omet la clé |\n\nDans `insert()` (y compris l'insertion d'un upsert), le caractère est supprimé : la colonne reçoit la valeur (`0` quand elle est vide), `!` insère `FALSE` et `=` insère le SQL brut. Les clés sans opérateur sont envoyées sous forme de paramètres.\n\nExample: Stock\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n```\n\nExample: Un compteur journalier (upsert)\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n```\n\n### callback(err, response)\n\nType: `type`\n\nCe que renvoie chaque opération du QueryBuilder sur PostgreSQL.\n\n| Opération | Réponse |\n| --- | --- |\n| `find()` | Un tableau de lignes. |\n| `read()` | Une ligne ou `null`. |\n| `list()` | `{ items, count, page, limit, pages }` ; l'adaptateur exécute la page et `SELECT COUNT(1)`. |\n| `check()` | `true` ou `false`. |\n| `count()` | Un nombre. |\n| `scalar()` | Un nombre pour `sum`, `avg`, `min`, `max` et `count` ; des lignes `{ key, value }` pour `group`. |\n| `insert()` | Le nombre de lignes insérées, la valeur de la colonne `primarykey()`, ou la ligne insérée avec `returning()`. |\n| `update()` | Le nombre de lignes modifiées, un tableau de lignes avec `returning()`, une seule ligne avec `returning()` et `first()`. |\n| `remove()` | Le nombre de lignes supprimées, ou un tableau de lignes avec `returning()`. |\n| `query()` | Un tableau de lignes ; `undefined` pour du SQL avec plusieurs instructions. |\n| `truncate()`, `drop()` | Exécutent `TRUNCATE TABLE … RESTART IDENTITY` et `DROP TABLE …`. |\n\nValeurs : `boolean` est un `Boolean` ; `smallint`, `integer`, `real`, `double precision` et `numeric` sont des nombres ; `bigint` est une `String` ; `json` et `jsonb` sont analysés (les textes au format de date ISO deviennent des objets `Date`) ; `date`, `timestamp` et `timestamptz` sont des objets `Date` ; `bytea` est un `Buffer` ; les tableaux sont des tableaux ; les autres types sont des chaînes.\n\nExample: Returning\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n```\n\n### err\n\nType: `type`\n\nL'erreur d'une requête qui a échoué.\n\nUne erreur du serveur est une `Error` avec le message de PostgreSQL et les champs que le serveur envoie : `code` (le code SQLSTATE), `severity`, `detail`, `hint`, `position`, `where`, `schema`, `table`, `column`, `datatype`, `constraint` et `routine`. Les erreurs de connexion sont des objets `Error` de Node.js (`ECONNREFUSED`…) ou `Connection timeout`, `The server does not support SSL connections` et `Pool is closed`.\n\nExample: Une clé en double\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\n### PG_ESCAPE(value)\n\nType: `method`\n\nÉchappe une valeur pour une requête PostgreSQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur. |\n\nReturns: `String` Le littéral SQL.\n\nRenvoie la valeur sous forme de littéral SQL, de la même façon que l'adaptateur écrit les valeurs des conditions : une chaîne entre apostrophes (`'O''Brien'`, avec le préfixe `E` quand elle contient une barre oblique inverse), un nombre et un booléen tels quels, `null` et `undefined` comme `null`, un tableau comme `ARRAY[…]`, une `Date` comme `'yyyy-MM-dd HH:mm:ss'` et un objet comme son JSON entre apostrophes. Une fonction est appelée et son résultat est échappé. La variable globale existe après le premier `DATA.init()`.\n\nExample: Échappement\n```js\nDATA.query('SELECT id FROM eshop.tbl_product WHERE name=' + PG_ESCAPE(\"Kid's watch\")).callback(console.log);\n```\n\n### require('total5/client-postgresql')\n\nType: `method`\n\nLe client PostgreSQL sans le QueryBuilder.\n\nReturns: `Object` Le module.\n\nLe module exporte `connect()`, `pool()`, `types` et les classes `Client` et `Pool`. L'adaptateur de `DATA.init()` utilise le même module, donc une modification de `types` s'applique aux deux.\n\nExample: Require\n```js\nconst PG = require('total5/client-postgresql');\n```\n\n### PG.connect(options, callback)\n\nType: `method`\n\nOuvre une connexion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | La chaîne de connexion ou les options. |\n| `callback` | `Function` | yes |  | `function(err, client)`. |\n\nReturns: `Client`\n\n`options` est une chaîne de connexion ou un objet avec `connectionString`, `host`, `port`, `user`, `password`, `database`, `ssl` (`true`, une valeur de `sslmode` ou un objet d'options pour `tls.connect()`), `timeout` (millisecondes) et `name` (le nom de l'application). Ferme la connexion avec `client.end()` ou `client.close()`.\n\nExample: Une connexion\n```js\nconst PG = require('total5/client-postgresql');\n\nPG.connect(CONF.database, async function(err, client) {\n\tvar response = await client.query('SELECT $1::int + 1 AS value', [41]);\n\tconsole.log(response.rows); // [ { value: 42 } ]\n\tclient.close();\n});\n```\n\n### PG.pool(options, [max])\n\nType: `method`\n\nCrée un pool de connexions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | La chaîne de connexion ou les options de `PG.connect()`. |\n| `max` | `Number` | no | `10` | Le nombre maximal de connexions. |\n\nReturns: `Pool`\n\nLe pool ouvre jusqu'à `max` connexions (10 par défaut) et les réutilise. Quand `options` est un objet, `max` et `idle` (les millisecondes pendant lesquelles une connexion inactive reste ouverte, 10000 par défaut) peuvent aussi s'y trouver. Une connexion qui revient au milieu d'une transaction ouverte est fermée.\n\nExample: Un pool\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.query('SELECT id FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.rows);\n});\n```\n\n### pool.connect(callback)\n\nType: `method`\n\nEmprunte une connexion au pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, client, release)`. |\n\nLe callback reçoit la connexion et une fonction `release` qui la rend au pool (`client.release()` fait la même chose). Utilise-le pour plusieurs requêtes sur une seule connexion, par exemple une transaction.\n\nExample: Une transaction\n```js\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n### client.query(sql, [params], [callback])\n\nType: `method`\n\nExécute une requête sur la connexion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | Le SQL. |\n| `params` | `Array` | no |  | Les valeurs des paramètres. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Sans `callback`. La réponse est `{ command, rowCount, rows, fields }`.\n\nLes paramètres sont `$1`, `$2`… dans le SQL. Sans paramètres, le SQL peut contenir plusieurs instructions ; la réponse est alors un tableau avec un résultat pour chaque instruction. Une `Date` est envoyée avec son fuseau horaire, un objet en JSON, un `Buffer` en données binaires et un tableau en tableau PostgreSQL, ou en JSON pour un paramètre `json` ou `jsonb`. Sans `callback`, elle renvoie une promesse. `pool.query()` prend les mêmes arguments et exécute la requête sur une connexion libre du pool.\n\nExample: Requête\n```js\nclient.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.command, response.rowCount, response.rows);\n});\n```\n\n### client.close([callback])\n\nType: `method`\n\nRend la connexion à son pool ou la ferme.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelée quand c'est terminé. |\n\nUne connexion d'un pool retourne dans le pool (alias `client.release()`). Les autres connexions sont fermées après leurs requêtes en attente, comme `client.end([callback])`.\n\nExample: Fermer\n```js\nclient.close();\n```\n\n### pool.end([callback])\n\nType: `method`\n\nFerme toutes les connexions du pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelée quand toutes les connexions sont fermées. |\n\nLes connexions inactives se ferment immédiatement, les connexions occupées quand elles sont libérées. Les requêtes en attente et les suivantes échouent avec `Pool is closed`.\n\nExample: Terminer\n```js\npool.end(() => console.log('closed'));\n```\n\n### PG.types\n\nType: `property`\n\nLes parseurs des valeurs selon l'OID du type.\n\nReturns: `Object`\n\nUn objet `{ oid: function(text) }`. Un type sans parseur est renvoyé sous forme de chaîne. `bigint` (OID 20) n'a pas de parseur car ses valeurs ne tiennent pas toujours dans un nombre JavaScript.\n\nExample: bigint en nombre\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value;\n```\n","entries":[{"type":"method","name":"DATA.init()","signature":"DATA.init([name], [connection], [onerror])","since":"","deprecated":false},{"type":"type","name":"Connection string","signature":"postgresql://user:password@host:port/database?options","since":"","deprecated":false},{"type":"type","name":"Payload operators","signature":"{ '+stock': 5, '=dtupdated': 'NOW()' }","since":"","deprecated":false},{"type":"type","name":"Results","signature":"callback(err, response)","since":"","deprecated":false},{"type":"type","name":"Errors","signature":"err","since":"","deprecated":false},{"type":"method","name":"PG_ESCAPE()","signature":"PG_ESCAPE(value)","since":"","deprecated":false},{"type":"method","name":"require('total5/client-postgresql')","signature":"require('total5/client-postgresql')","since":"","deprecated":false},{"type":"method","name":"PG.connect()","signature":"PG.connect(options, callback)","since":"","deprecated":false},{"type":"method","name":"PG.pool()","signature":"PG.pool(options, [max])","since":"","deprecated":false},{"type":"method","name":"pool.connect()","signature":"pool.connect(callback)","since":"","deprecated":false},{"type":"method","name":"client.query()","signature":"client.query(sql, [params], [callback])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([callback])","since":"","deprecated":false},{"type":"method","name":"pool.end()","signature":"pool.end([callback])","since":"","deprecated":false},{"type":"property","name":"PG.types","signature":"PG.types","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JafwSC3Yx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/postgresql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"PostgreSQL","summary":"DATA.init(), la stringa di connessione, i risultati e gli errori SQL, e il client PostgreSQL.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/postgresql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# PostgreSQL\n\n> DATA.init(), la stringa di connessione, i risultati e gli errori SQL, e il client PostgreSQL.\n\n`DATA.init()` e la sua stringa di connessione, cosa restituisce l'adapter PostgreSQL, gli operatori del payload, gli errori, `PG_ESCAPE()` e il client `total5/client-postgresql`. I metodi del QueryBuilder sono nel riferimento di [QueryBuilder](../../reference/querybuilder/). Un'introduzione con esempi è nella guida [PostgreSQL](../../guides/postgresql/).\n\n## API\n\n### DATA.init([name], [connection], [onerror])\n\nType: `method`\n\nRegistra una connessione PostgreSQL per il QueryBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Il nome della connessione. |\n| `connection` | `String` | no |  | La stringa di connessione: `postgresql://user:password@host:port/database?options`. Vedi la stringa di connessione. |\n| `onerror` | `Function` | no |  | `function(message)` chiamata per ogni query fallita. |\n\nRegistra un adapter (`NEWDB()`) con il nome `name` che esegue le query di `DATA` e `DB()` su PostgreSQL. La connessione `default` serve le tabelle senza prefisso, ogni altra connessione le tabelle con il suo prefisso (`DATA.find('logs/tbl_request')`). Chiamarla di nuovo con lo stesso nome chiude il vecchio pool e sostituisce la connessione. Senza `connection` la connessione viene rimossa. Ogni query fallita viene passata a `onerror` come testo con l'errore e i primi 100 caratteri dell'SQL; senza `onerror` viene registrata con `ERROR(name)`. La callback della query riceve l'errore in entrambi i casi.\n\nExample: In definitions/db.js\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nExample: Una seconda connessione\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nExample: Gestione degli errori propria\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n});\n```\n\n### postgresql://user:password@host:port/database?options\n\nType: `type`\n\nL'URL del database e le sue opzioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `pooling` | `Number` | no |  | Il numero massimo di connessioni in un pool. Senza di essa ogni query apre una nuova connessione e la chiude alla fine. Una connessione inattiva del pool si chiude dopo 10 secondi. |\n| `schema` | `String` | no |  | Lo schema delle tabelle: `DATA.find('tbl_product')` legge `schema.tbl_product`. `builder.schema(name)` lo cambia per una sola query. Le query grezze non lo usano. |\n| `sslmode` | `String` | no | `'disable'` | `disable`, `prefer`, `allow`, `require`, `no-verify`, `verify-ca` o `verify-full`. |\n| `ssl` | `Boolean` | no |  | `true` o `1` equivale a `sslmode=require`. |\n| `connect_timeout` | `Number` | no |  | Secondi di attesa per la connessione. Poi la query fallisce con `Connection timeout`. |\n| `application_name` | `String` | no |  | Il nome delle connessioni in `pg_stat_activity`. |\n| `host` | `String` | no |  | Sostituisce l'host dell'URL. Un valore che inizia con `/` è la cartella di un socket Unix. |\n| `port, user, password, dbname` | `String` | no |  | Sostituiscono le parti dell'URL. |\n\nLa porta predefinita è `5432`. Senza il nome del database il client usa il database che ha il nome dell'utente. I caratteri speciali del nome utente e della password devono essere codificati con `encodeURIComponent()`. Le opzioni vanno nella query string. Le altre opzioni vengono ignorate.\n\nI valori di `sslmode`: `disable` (predefinito) non è cifrato; `prefer` e `allow` cifrano quando il server supporta SSL; `require` e `no-verify` cifrano senza controllare il certificato e falliscono con `The server does not support SSL connections` quando il server non ha SSL; `verify-ca` e `verify-full` cifrano e il certificato deve essere valido.\n\nIl client si autentica con una password in chiaro, MD5 o SCRAM-SHA-256, come chiede il server.\n\nExample: Nel file config\n```text\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nExample: Opzioni\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\n### { '+stock': 5, '=dtupdated': 'NOW()' }\n\nType: `type`\n\nChiavi del payload di update() che modificano il valore nel database.\n\nIl primo carattere di una chiave nel payload di `update()`:\n\n| Chiave | SQL |\n| --- | --- |\n| `+name`, `-name`, `*name`, `/name` | `\"name\"=COALESCE(\"name\",0)+$1` (e `-`, `*`, `/`) |\n| `>name` | `\"name\"=GREATEST(\"name\",$1)` |\n| `<name` | `\"name\"=LEAST(\"name\",$1)` |\n| `!name` | `\"name\"=NOT \"name\"` |\n| `=name` | `\"name\"=value`, il valore è SQL grezzo |\n| `#name` | Come `=`, ma `insert()` omette la chiave |\n\nIn `insert()` (anche nell'insert di un upsert) il carattere viene rimosso: la colonna riceve il valore (`0` quando è vuoto), `!` inserisce `FALSE` e `=` inserisce l'SQL grezzo. Le chiavi senza operatore vengono inviate come parametri.\n\nExample: Magazzino\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n```\n\nExample: Un contatore giornaliero (upsert)\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n```\n\n### callback(err, response)\n\nType: `type`\n\nCosa restituisce ogni operazione del QueryBuilder su PostgreSQL.\n\n| Operazione | Risposta |\n| --- | --- |\n| `find()` | Un array di righe. |\n| `read()` | Una riga oppure `null`. |\n| `list()` | `{ items, count, page, limit, pages }`; l'adapter esegue la pagina e `SELECT COUNT(1)`. |\n| `check()` | `true` o `false`. |\n| `count()` | Un numero. |\n| `scalar()` | Un numero per `sum`, `avg`, `min`, `max` e `count`; righe `{ key, value }` per `group`. |\n| `insert()` | Il numero di righe inserite, il valore della colonna `primarykey()`, oppure la riga inserita con `returning()`. |\n| `update()` | Il numero di righe modificate, un array di righe con `returning()`, una riga con `returning()` e `first()`. |\n| `remove()` | Il numero di righe rimosse, oppure un array di righe con `returning()`. |\n| `query()` | Un array di righe; `undefined` per SQL con più istruzioni. |\n| `truncate()`, `drop()` | Eseguono `TRUNCATE TABLE … RESTART IDENTITY` e `DROP TABLE …`. |\n\nValori: `boolean` è un `Boolean`; `smallint`, `integer`, `real`, `double precision` e `numeric` sono numeri; `bigint` è una `String`; `json` e `jsonb` vengono interpretati (i testi nel formato di data ISO diventano oggetti `Date`); `date`, `timestamp` e `timestamptz` sono oggetti `Date`; `bytea` è un `Buffer`; gli array sono array; gli altri tipi sono stringhe.\n\nExample: Returning\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n```\n\n### err\n\nType: `type`\n\nL'errore di una query fallita.\n\nUn errore del server è un `Error` con il messaggio di PostgreSQL e i campi che il server invia: `code` (il codice SQLSTATE), `severity`, `detail`, `hint`, `position`, `where`, `schema`, `table`, `column`, `datatype`, `constraint` e `routine`. Gli errori della connessione sono oggetti `Error` di Node.js (`ECONNREFUSED`…) oppure `Connection timeout`, `The server does not support SSL connections` e `Pool is closed`.\n\nExample: Una chiave duplicata\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\n### PG_ESCAPE(value)\n\nType: `method`\n\nEsegue l'escape di un valore per una query PostgreSQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore. |\n\nReturns: `String` Il letterale SQL.\n\nRestituisce il valore come letterale SQL, nello stesso modo in cui l'adapter scrive i valori delle condizioni: una stringa tra apici singoli (`'O''Brien'`, con il prefisso `E` quando contiene un backslash), un numero e un booleano così come sono, `null` e `undefined` come `null`, un array come `ARRAY[…]`, una `Date` come `'yyyy-MM-dd HH:mm:ss'` e un oggetto come il suo JSON tra apici. Una funzione viene chiamata e il suo risultato viene sottoposto a escape. La variabile globale esiste dopo la prima `DATA.init()`.\n\nExample: Escape\n```js\nDATA.query('SELECT id FROM eshop.tbl_product WHERE name=' + PG_ESCAPE(\"Kid's watch\")).callback(console.log);\n```\n\n### require('total5/client-postgresql')\n\nType: `method`\n\nIl client PostgreSQL senza il QueryBuilder.\n\nReturns: `Object` Il modulo.\n\nIl modulo esporta `connect()`, `pool()`, `types` e le classi `Client` e `Pool`. L'adapter di `DATA.init()` usa lo stesso modulo, quindi una modifica in `types` vale per entrambi.\n\nExample: Require\n```js\nconst PG = require('total5/client-postgresql');\n```\n\n### PG.connect(options, callback)\n\nType: `method`\n\nApre una connessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | La stringa di connessione o le opzioni. |\n| `callback` | `Function` | yes |  | `function(err, client)`. |\n\nReturns: `Client`\n\n`options` è una stringa di connessione o un oggetto con `connectionString`, `host`, `port`, `user`, `password`, `database`, `ssl` (`true`, un valore di `sslmode` o un oggetto di opzioni per `tls.connect()`), `timeout` (millisecondi) e `name` (il nome dell'applicazione). Chiudi la connessione con `client.end()` o `client.close()`.\n\nExample: Una connessione\n```js\nconst PG = require('total5/client-postgresql');\n\nPG.connect(CONF.database, async function(err, client) {\n\tvar response = await client.query('SELECT $1::int + 1 AS value', [41]);\n\tconsole.log(response.rows); // [ { value: 42 } ]\n\tclient.close();\n});\n```\n\n### PG.pool(options, [max])\n\nType: `method`\n\nCrea un pool di connessioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | La stringa di connessione o le opzioni di `PG.connect()`. |\n| `max` | `Number` | no | `10` | Il numero massimo di connessioni. |\n\nReturns: `Pool`\n\nIl pool apre fino a `max` connessioni (predefinito 10) e le riutilizza. Quando `options` è un oggetto, può contenere anche `max` e `idle` (i millisecondi per cui una connessione inattiva resta aperta, predefinito 10000). Una connessione che torna dentro una transazione aperta viene chiusa.\n\nExample: Un pool\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.query('SELECT id FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.rows);\n});\n```\n\n### pool.connect(callback)\n\nType: `method`\n\nPrende in prestito una connessione dal pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, client, release)`. |\n\nLa callback riceve la connessione e una funzione `release` che la restituisce al pool (`client.release()` fa lo stesso). Usala per più query su una sola connessione, per esempio una transazione.\n\nExample: Una transazione\n```js\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n### client.query(sql, [params], [callback])\n\nType: `method`\n\nEsegue una query sulla connessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | L'SQL. |\n| `params` | `Array` | no |  | I valori dei parametri. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Senza `callback`. La risposta è `{ command, rowCount, rows, fields }`.\n\nI parametri sono `$1`, `$2`… nell'SQL. Senza parametri l'SQL può avere più istruzioni; la risposta è allora un array con un risultato per ogni istruzione. Una `Date` viene inviata con il suo fuso orario, un oggetto come JSON, un `Buffer` come dati binari e un array come array PostgreSQL, oppure come JSON per un parametro `json` o `jsonb`. Senza `callback` restituisce una promise. `pool.query()` accetta gli stessi argomenti ed esegue la query su una connessione libera del pool.\n\nExample: Query\n```js\nclient.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.command, response.rowCount, response.rows);\n});\n```\n\n### client.close([callback])\n\nType: `method`\n\nRestituisce la connessione al suo pool oppure la chiude.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata quando ha finito. |\n\nUna connessione di un pool torna nel pool (alias `client.release()`). Le altre connessioni vengono chiuse dopo le loro query in sospeso, come `client.end([callback])`.\n\nExample: Chiudere\n```js\nclient.close();\n```\n\n### pool.end([callback])\n\nType: `method`\n\nChiude tutte le connessioni del pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata quando tutte le connessioni sono chiuse. |\n\nLe connessioni inattive si chiudono subito, quelle occupate quando vengono rilasciate. Le richieste in attesa e successive falliscono con `Pool is closed`.\n\nExample: Terminare\n```js\npool.end(() => console.log('closed'));\n```\n\n### PG.types\n\nType: `property`\n\nI parser dei valori in base all'OID del tipo.\n\nReturns: `Object`\n\nUn oggetto `{ oid: function(text) }`. Un tipo senza parser viene restituito come stringa. `bigint` (OID 20) non ha un parser perché i suoi valori non sempre entrano in un numero JavaScript.\n\nExample: bigint come numero\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value;\n```\n","entries":[{"type":"method","name":"DATA.init()","signature":"DATA.init([name], [connection], [onerror])","since":"","deprecated":false},{"type":"type","name":"Connection string","signature":"postgresql://user:password@host:port/database?options","since":"","deprecated":false},{"type":"type","name":"Payload operators","signature":"{ '+stock': 5, '=dtupdated': 'NOW()' }","since":"","deprecated":false},{"type":"type","name":"Results","signature":"callback(err, response)","since":"","deprecated":false},{"type":"type","name":"Errors","signature":"err","since":"","deprecated":false},{"type":"method","name":"PG_ESCAPE()","signature":"PG_ESCAPE(value)","since":"","deprecated":false},{"type":"method","name":"require('total5/client-postgresql')","signature":"require('total5/client-postgresql')","since":"","deprecated":false},{"type":"method","name":"PG.connect()","signature":"PG.connect(options, callback)","since":"","deprecated":false},{"type":"method","name":"PG.pool()","signature":"PG.pool(options, [max])","since":"","deprecated":false},{"type":"method","name":"pool.connect()","signature":"pool.connect(callback)","since":"","deprecated":false},{"type":"method","name":"client.query()","signature":"client.query(sql, [params], [callback])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([callback])","since":"","deprecated":false},{"type":"method","name":"pool.end()","signature":"pool.end([callback])","since":"","deprecated":false},{"type":"property","name":"PG.types","signature":"PG.types","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JafwSC3Yx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/postgresql/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"PostgreSQL","summary":"DATA.init(), connection string, výsledky a chyby SQL a klient PostgreSQL.","markdown":"---\ntitle: PostgreSQL\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/postgresql/\nupdated: 2026-11-19T20:13:56.297Z\n---\n\n# PostgreSQL\n\n> DATA.init(), connection string, výsledky a chyby SQL a klient PostgreSQL.\n\n`DATA.init()` a jeho connection string, čo vracia adaptér PostgreSQL, operátory payloadu, chyby, `PG_ESCAPE()` a klient `total5/client-postgresql`. Metódy QueryBuildera sú v referencii [QueryBuilder](../../reference/querybuilder/). Úvod s príkladmi je v návode [PostgreSQL](../../guides/postgresql/).\n\n## API\n\n### DATA.init([name], [connection], [onerror])\n\nType: `method`\n\nZaregistruje PostgreSQL pripojenie pre QueryBuilder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Názov pripojenia. |\n| `connection` | `String` | no |  | Connection string: `postgresql://user:password@host:port/database?options`. Pozri connection string. |\n| `onerror` | `Function` | no |  | `function(message)` volaná pre každý neúspešný dopyt. |\n\nZaregistruje adaptér (`NEWDB()`) s názvom `name`, ktorý spúšťa dopyty `DATA` a `DB()` na PostgreSQL. Pripojenie `default` obsluhuje tabuľky bez prefixu, každé iné pripojenie tabuľky so svojím prefixom (`DATA.find('logs/tbl_request')`). Ďalšie volanie s rovnakým názvom zatvorí starý pool a nahradí pripojenie. Bez `connection` sa pripojenie odstráni. Každý neúspešný dopyt sa odovzdá do `onerror` ako text s chybou a prvými 100 znakmi SQL; bez `onerror` sa zaloguje cez `ERROR(name)`. Callback dopytu dostane chybu v oboch prípadoch.\n\nExample: V definitions/db.js\n```js\nDATA.init('default', CONF.database + '?pooling=10');\n```\n\nExample: Druhé pripojenie\n```js\nDATA.init('logs', CONF.database_logs);\nDATA.insert('logs/tbl_request', { url: '/', dtcreated: NOW }).callback(console.log);\n```\n\nExample: Vlastné spracovanie chýb\n```js\nDATA.init('default', CONF.database + '?pooling=10', function(message) {\n\tconsole.log('SQL error:', message);\n});\n```\n\n### postgresql://user:password@host:port/database?options\n\nType: `type`\n\nURL databázy a jej možnosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `pooling` | `Number` | no |  | Maximálny počet pripojení v poole. Bez nej každý dopyt otvorí nové pripojenie a na konci ho zatvorí. Nečinné pripojenie poolu sa zatvorí po 10 sekundách. |\n| `schema` | `String` | no |  | Schéma tabuliek: `DATA.find('tbl_product')` číta `schema.tbl_product`. `builder.schema(name)` ju zmení pre jeden dopyt. Čisté dopyty ju nepoužívajú. |\n| `sslmode` | `String` | no | `'disable'` | `disable`, `prefer`, `allow`, `require`, `no-verify`, `verify-ca` alebo `verify-full`. |\n| `ssl` | `Boolean` | no |  | `true` alebo `1` je to isté ako `sslmode=require`. |\n| `connect_timeout` | `Number` | no |  | Počet sekúnd čakania na pripojenie. Potom dopyt zlyhá s `Connection timeout`. |\n| `application_name` | `String` | no |  | Názov pripojení v `pg_stat_activity`. |\n| `host` | `String` | no |  | Nahradí hosta v URL. Hodnota, ktorá začína na `/`, je adresár Unix socketu. |\n| `port, user, password, dbname` | `String` | no |  | Nahradia časti URL. |\n\nPort je predvolene `5432`. Bez názvu databázy klient použije databázu pomenovanú ako používateľ. Špeciálne znaky mena používateľa a hesla musia byť zakódované cez `encodeURIComponent()`. Možnosti idú do query stringu. Ostatné možnosti sa ignorujú.\n\nHodnoty `sslmode`: `disable` (predvolené) nie je šifrované; `prefer` a `allow` šifrujú, keď server podporuje SSL; `require` a `no-verify` šifrujú bez kontroly certifikátu a zlyhajú s `The server does not support SSL connections`, keď server nemá SSL; `verify-ca` a `verify-full` šifrujú a certifikát musí byť platný.\n\nKlient sa prihlási heslom v čistom texte, MD5 alebo SCRAM-SHA-256, podľa toho, čo server žiada.\n\nExample: V konfiguračnom súbore\n```text\ndatabase : postgresql://user:password@localhost:5432/eshop\n```\n\nExample: Možnosti\n```js\nDATA.init('default', CONF.database + '?schema=eshop&pooling=10&sslmode=require&connect_timeout=5');\n```\n\n### { '+stock': 5, '=dtupdated': 'NOW()' }\n\nType: `type`\n\nKľúče payloadu update(), ktoré zmenia hodnotu v databáze.\n\nPrvý znak kľúča v payloade `update()`:\n\n| Kľúč | SQL |\n| --- | --- |\n| `+name`, `-name`, `*name`, `/name` | `\"name\"=COALESCE(\"name\",0)+$1` (a `-`, `*`, `/`) |\n| `>name` | `\"name\"=GREATEST(\"name\",$1)` |\n| `<name` | `\"name\"=LEAST(\"name\",$1)` |\n| `!name` | `\"name\"=NOT \"name\"` |\n| `=name` | `\"name\"=value`, hodnota je čisté SQL |\n| `#name` | To isté ako `=`, ale `insert()` kľúč vynechá |\n\nV `insert()` (aj v inserte upsertu) sa znak odstráni: stĺpec dostane hodnotu (`0`, keď je prázdna), `!` vloží `FALSE` a `=` vloží čisté SQL. Kľúče bez operátora sa posielajú ako parametre.\n\nExample: Sklad\n```js\nDATA.update('tbl_product', { '+stock': 5, '-reserved': 5, '=dtupdated': 'NOW()' }).id('p1').callback(console.log);\n```\n\nExample: Denné počítadlo (upsert)\n```js\nvar id = NOW.format('yyyy-MM-dd');\nDATA.update('tbl_visitor', { '+count': 1, '=dtupdated': 'NOW()' }, true).id(id).insert(doc => doc.id = id).callback(console.log);\n```\n\n### callback(err, response)\n\nType: `type`\n\nČo vracia každá operácia QueryBuildera na PostgreSQL.\n\n| Operácia | Odpoveď |\n| --- | --- |\n| `find()` | Pole riadkov. |\n| `read()` | Jeden riadok alebo `null`. |\n| `list()` | `{ items, count, page, limit, pages }`; adaptér spustí stránku a `SELECT COUNT(1)`. |\n| `check()` | `true` alebo `false`. |\n| `count()` | Číslo. |\n| `scalar()` | Číslo pre `sum`, `avg`, `min`, `max` a `count`; riadky `{ key, value }` pre `group`. |\n| `insert()` | Počet vložených riadkov, hodnota stĺpca `primarykey()` alebo vložený riadok s `returning()`. |\n| `update()` | Počet zmenených riadkov, pole riadkov s `returning()`, jeden riadok s `returning()` a `first()`. |\n| `remove()` | Počet odstránených riadkov alebo pole riadkov s `returning()`. |\n| `query()` | Pole riadkov; `undefined` pre SQL s viacerými príkazmi. |\n| `truncate()`, `drop()` | Spustia `TRUNCATE TABLE … RESTART IDENTITY` a `DROP TABLE …`. |\n\nHodnoty: `boolean` je `Boolean`; `smallint`, `integer`, `real`, `double precision` a `numeric` sú čísla; `bigint` je `String`; `json` a `jsonb` sa sparsujú (texty vo formáte dátumu ISO sa zmenia na objekty `Date`); `date`, `timestamp` a `timestamptz` sú objekty `Date`; `bytea` je `Buffer`; polia sú polia; ostatné typy sú reťazce.\n\nExample: Returning\n```js\nDATA.insert('tbl_product', { id: 'p3', name: 'Watch', price: 80 }).returning('id,dtcreated').callback(console.log);\n// null { id: 'p3', dtcreated: 2026-11-16T16:22:26.950Z }\n```\n\n### err\n\nType: `type`\n\nChyba neúspešného dopytu.\n\nChyba servera je `Error` so správou PostgreSQL a s poľami, ktoré server pošle: `code` (kód SQLSTATE), `severity`, `detail`, `hint`, `position`, `where`, `schema`, `table`, `column`, `datatype`, `constraint` a `routine`. Chyby pripojenia sú objekty `Error` z Node.js (`ECONNREFUSED`…) alebo `Connection timeout`, `The server does not support SSL connections` a `Pool is closed`.\n\nExample: Duplicitný kľúč\n```js\nDATA.insert('tbl_order', { id: 'o1', productid: 'p2', count: 1 }).callback(function(err, response) {\n\tif (err)\n\t\tconsole.log(err.code, err.constraint, err.detail);\n\t// 23505 tbl_order_pkey Key (id)=(o1) already exists.\n});\n```\n\n### PG_ESCAPE(value)\n\nType: `method`\n\nEscapuje hodnotu pre PostgreSQL dopyt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `String` SQL literál.\n\nVráti hodnotu ako SQL literál, rovnako ako adaptér zapisuje hodnoty podmienok: reťazec v jednoduchých úvodzovkách (`'O''Brien'`, s prefixom `E`, keď obsahuje spätnú lomku), číslo a boolean tak, ako sú, `null` a `undefined` ako `null`, pole ako `ARRAY[…]`, `Date` ako `'yyyy-MM-dd HH:mm:ss'` a objekt ako jeho JSON v úvodzovkách. Funkcia sa zavolá a jej výsledok sa escapuje. Globálna funkcia existuje po prvom `DATA.init()`.\n\nExample: Escapovanie\n```js\nDATA.query('SELECT id FROM eshop.tbl_product WHERE name=' + PG_ESCAPE(\"Kid's watch\")).callback(console.log);\n```\n\n### require('total5/client-postgresql')\n\nType: `method`\n\nKlient PostgreSQL bez QueryBuildera.\n\nReturns: `Object` Modul.\n\nModul exportuje `connect()`, `pool()`, `types` a triedy `Client` a `Pool`. Adaptér `DATA.init()` používa ten istý modul, takže zmena v `types` platí pre oba.\n\nExample: Require\n```js\nconst PG = require('total5/client-postgresql');\n```\n\n### PG.connect(options, callback)\n\nType: `method`\n\nOtvorí jedno pripojenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | Connection string alebo možnosti. |\n| `callback` | `Function` | yes |  | `function(err, client)`. |\n\nReturns: `Client`\n\n`options` je connection string alebo objekt s `connectionString`, `host`, `port`, `user`, `password`, `database`, `ssl` (`true`, hodnota `sslmode` alebo objekt možností pre `tls.connect()`), `timeout` (milisekundy) a `name` (názov aplikácie). Pripojenie zatvor cez `client.end()` alebo `client.close()`.\n\nExample: Jedno pripojenie\n```js\nconst PG = require('total5/client-postgresql');\n\nPG.connect(CONF.database, async function(err, client) {\n\tvar response = await client.query('SELECT $1::int + 1 AS value', [41]);\n\tconsole.log(response.rows); // [ { value: 42 } ]\n\tclient.close();\n});\n```\n\n### PG.pool(options, [max])\n\nType: `method`\n\nVytvorí pool pripojení.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `String|Object` | yes |  | Connection string alebo možnosti `PG.connect()`. |\n| `max` | `Number` | no | `10` | Maximálny počet pripojení. |\n\nReturns: `Pool`\n\nPool otvorí až `max` pripojení (predvolene 10) a opakovane ich používa. Keď je `options` objekt, môžu v ňom byť aj `max` a `idle` (počet milisekúnd, počas ktorých zostane nečinné pripojenie otvorené, predvolene 10000). Pripojenie, ktoré sa vráti uprostred otvorenej transakcie, sa zatvorí.\n\nExample: Pool\n```js\nconst PG = require('total5/client-postgresql');\nconst pool = PG.pool(CONF.database, 5);\n\npool.query('SELECT id FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.rows);\n});\n```\n\n### pool.connect(callback)\n\nType: `method`\n\nPožičia si pripojenie z poolu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, client, release)`. |\n\nCallback dostane pripojenie a funkciu `release`, ktorá ho vráti do poolu (`client.release()` robí to isté). Použi ho pre viac dopytov na jednom pripojení, napríklad pre transakciu.\n\nExample: Transakcia\n```js\npool.connect(async function(err, client, release) {\n\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait client.query('BEGIN');\n\t\tawait client.query('UPDATE eshop.tbl_product SET stock=stock-$1 WHERE id=$2', [2, 'p1']);\n\t\tawait client.query('INSERT INTO eshop.tbl_order (id, productid, count) VALUES($1, $2, $3)', ['o2', 'p1', 2]);\n\t\tawait client.query('COMMIT');\n\t} catch (e) {\n\t\tawait client.query('ROLLBACK');\n\t} finally {\n\t\trelease();\n\t}\n});\n```\n\n### client.query(sql, [params], [callback])\n\nType: `method`\n\nSpustí dopyt na pripojení.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | SQL. |\n| `params` | `Array` | no |  | Hodnoty parametrov. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Bez `callback`. Odpoveď je `{ command, rowCount, rows, fields }`.\n\nParametre sú v SQL `$1`, `$2`…. Bez parametrov môže SQL obsahovať viac príkazov; odpoveď je potom pole s jedným výsledkom pre každý príkaz. `Date` sa posiela s časovou zónou, objekt ako JSON, `Buffer` ako binárne dáta a pole ako pole PostgreSQL, alebo ako JSON pre parameter `json` alebo `jsonb`. Bez `callback` vráti promise. `pool.query()` prijíma rovnaké argumenty a spustí dopyt na voľnom pripojení poolu.\n\nExample: Dopyt\n```js\nclient.query('SELECT id, name FROM eshop.tbl_product WHERE price>$1', [100], function(err, response) {\n\tconsole.log(response.command, response.rowCount, response.rows);\n});\n```\n\n### client.close([callback])\n\nType: `method`\n\nVráti pripojenie do jeho poolu alebo ho zatvorí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Volá sa, keď je hotovo. |\n\nPripojenie poolu sa vráti do poolu (alias `client.release()`). Ostatné pripojenia sa zatvoria po ich čakajúcich dopytoch, ako pri `client.end([callback])`.\n\nExample: Zatvorenie\n```js\nclient.close();\n```\n\n### pool.end([callback])\n\nType: `method`\n\nZatvorí všetky pripojenia poolu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Volá sa, keď sú všetky pripojenia zatvorené. |\n\nNečinné pripojenia sa zatvoria hneď, zaneprázdnené, keď sa uvoľnia. Čakajúce a neskoršie požiadavky zlyhajú s `Pool is closed`.\n\nExample: Ukončenie\n```js\npool.end(() => console.log('closed'));\n```\n\n### PG.types\n\nType: `property`\n\nParsery hodnôt podľa OID typu.\n\nReturns: `Object`\n\nObjekt `{ oid: function(text) }`. Typ bez parsera sa vráti ako reťazec. `bigint` (OID 20) nemá parser, pretože jeho hodnoty sa nie vždy zmestia do čísla JavaScriptu.\n\nExample: bigint ako číslo\n```js\nconst PG = require('total5/client-postgresql');\nPG.types[20] = value => +value;\n```\n","entries":[{"type":"method","name":"DATA.init()","signature":"DATA.init([name], [connection], [onerror])","since":"","deprecated":false},{"type":"type","name":"Connection string","signature":"postgresql://user:password@host:port/database?options","since":"","deprecated":false},{"type":"type","name":"Payload operators","signature":"{ '+stock': 5, '=dtupdated': 'NOW()' }","since":"","deprecated":false},{"type":"type","name":"Results","signature":"callback(err, response)","since":"","deprecated":false},{"type":"type","name":"Errors","signature":"err","since":"","deprecated":false},{"type":"method","name":"PG_ESCAPE()","signature":"PG_ESCAPE(value)","since":"","deprecated":false},{"type":"method","name":"require('total5/client-postgresql')","signature":"require('total5/client-postgresql')","since":"","deprecated":false},{"type":"method","name":"PG.connect()","signature":"PG.connect(options, callback)","since":"","deprecated":false},{"type":"method","name":"PG.pool()","signature":"PG.pool(options, [max])","since":"","deprecated":false},{"type":"method","name":"pool.connect()","signature":"pool.connect(callback)","since":"","deprecated":false},{"type":"method","name":"client.query()","signature":"client.query(sql, [params], [callback])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([callback])","since":"","deprecated":false},{"type":"method","name":"pool.end()","signature":"pool.end([callback])","since":"","deprecated":false},{"type":"property","name":"PG.types","signature":"PG.types","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:56.297Z"}
{"id":"JaedDnAlT60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/localization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Localization","summary":"Resource files, @(...) texts, TRANSLATE(), LOCALIZE(), LOADRESOURCE() and the language of a request.","markdown":"---\ntitle: Localization\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/localization/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Localization\n\n> Resource files, @(...) texts, TRANSLATE(), LOCALIZE(), LOADRESOURCE() and the language of a request.\n\nFunctions, delegates and files of the localization: resource files, `@(...)` texts, `TRANSLATE()`, `LOCALIZE()`, the language of a request and the `total5 translate` command. 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 a dictionary of translations.\n\nEvery `.resource` file in `/resources/` and its subfolders is loaded when the application starts. The file name without the extension is the name of the dictionary (`sk.resource` is `sk`). Paths that contain `-bk` or `_bk` are skipped.\n\nEach line is `key : value`. The separator is the first `:`, or the first `=` when the line has no `:`; the value starts at the second character after the separator, so keep one space there. Keys and values are trimmed. Empty lines and lines that start with `#` or `//` are ignored. Keys of `@(...)` texts are `T` and a hash of the text; other keys are any names you read with `F.resource()`.\n\nExample: sk.resource\n```text\n# Slovak\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\nname          : Meno\nJanuary       : január\n```\n\n### /resources/default.resource\n\nType: `type`\n\nThe fallback dictionary.\n\nWhen a key is missing in the dictionary of the language, or the language has no dictionary, the key is read from the dictionary `default`. An empty language (the default of a request) reads `default` directly.\n\nExample: Fallback\n```js\n// /resources/default.resource contains: name : Name\nF.resource('de', 'name'); // 'Name' when de.resource has no \"name\"\n```\n\n### 'T' + text.hash(true).toString(36)\n\nType: `type`\n\nHow the key of an `@(...)` text is created.\n\nThe key is `T` followed by the unsigned hash of the text inside `@(...)` in base 36. The same text always has the same key, so the same text in many places needs one translation. Changing the original text changes the key. The `total5 translate` command creates the keys for you.\n\nExample: Compute a key\n```js\nvar key = 'T' + 'Welcome'.hash(true).toString(36); // 'T1bx8wg2'\n```\n\n### @(text)\n\nType: `command`\n\nMarks a text for translation.\n\nThe text is replaced by its translation from the dictionary of the current language, with a fallback to `default`. Without a translation the text is printed as it is (without `@(` and `)`). Parentheses inside the text must be balanced. It works in views, static `.html` files, `TRANSLATE()`, error messages, e-mail subjects and bodies and templates. In views it is replaced before the view is compiled, so it holds plain text only.\n\nExample: In a view\n```html\n<h1>@(Welcome)</h1>\n<p>@(Free delivery (over 50 EUR))</p>\n```\n\nExample: In code\n```js\n$.invalid('@(The name is required)');\n```\n\n### LOADRESOURCE(name, [text])\n\nType: `method`\n\nParses the text of a resource file and stores it as a dictionary.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the dictionary, usually a language code. |\n| `text` | `String` | no |  | The content in the resource format. |\n\nThe text has the format of a `.resource` file. The dictionary replaces a dictionary of the same name as a whole. It is the same function as `F.loadresource()`.\n\nExample: Load a dictionary\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte\\nname : Meno');\n```\n\nExample: From a file of your own\n```js\nLOADRESOURCE('de', F.Fs.readFileSync(PATH.root('lang/de.txt'), 'utf8'));\n```\n\n### LOADRESOURCE(url)\n\nType: `method`\n\nDownloads dictionaries from a URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL of a JSON response with dictionaries. |\n\nWithout the second argument the first argument is a URL. The response must be JSON. An object is read as `{ name: text }`, where every text is in the resource format. An array is read as items with the name in `id`, `key`, `code` or `language` and the text in `value`, `name`, `text` or `body`. Every dictionary is loaded with `LOADRESOURCE(name, text)`. A failed request throws an error.\n\nExample: Remote dictionaries\n```js\n// response: { \"sk\": \"T1bx8wg2 : Vitajte\", \"de\": \"T1bx8wg2 : Willkommen\" }\nLOADRESOURCE('https://example.com/translations.json');\n```\n\n### TRANSLATE(language, text)\n\nType: `method`\n\nTranslates all `@(...)` texts in a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | The name of the dictionary. An empty string uses `default`. |\n| `text` | `String` | yes |  | A string with `@(...)` texts. |\n\nReturns: `String` The translated string.\n\nEvery `@(...)` is replaced by its translation from the dictionary of the language, with a fallback to `default`; a text without a translation stays without the brackets. The rest of the string is not changed. It is the same function as `F.translate()`.\n\nExample: Translate a string\n```js\nTRANSLATE('sk', '<b>@(Welcome)</b>, Peter'); // '<b>Vitajte</b>, Peter'\n```\n\nExample: In a route\n```js\nfunction detail($) {\n\t$.plain(TRANSLATE($.language, '@(Order) #' + $.params.id));\n}\n```\n\n### F.resource(language, key)\n\nType: `method`\n\nReads one key of a dictionary.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | The name of the dictionary. |\n| `key` | `String` | yes |  | The key. |\n\nReturns: `String` The value, or an empty string when the key does not exist.\n\nReads the key from the dictionary of the language, then from `default`. Use it for keys with your own names, not for `@(...)` texts.\n\nExample: Read a key\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n### F.resources\n\nType: `property`\n\nAll loaded dictionaries.\n\nReturns: `Object`\n\nAn object with the dictionaries by their names. Each dictionary is a plain object of keys and values.\n\nExample: List the languages\n```js\nvar languages = Object.keys(F.resources); // ['default', 'sk', 'de']\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nRegisters the delegate that chooses the language of a request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)` that returns the language as a string. |\n\nThe function gets the controller and returns the language (a dictionary name). It is called for routes after the authorization and before the middleware, for static `.html` files and for WebSocket routes. For HTTP routes and static files it is not called when the language is already set. The result is stored in `$.language`. It sets `DEF.onLocalize`.\n\nExample: From the query string or the browser\n```js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nExample: From the user\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\n### DEF.onLocalize = function($) {}\n\nType: `delegate`\n\nThe delegate that `LOCALIZE()` sets.\n\n`LOCALIZE(fn)` stores the function here. You can also assign it directly; set it to `null` to stop choosing the language.\n\nExample: Assign directly\n```js\nDEF.onLocalize = function($) {\n\treturn $.cookie('language') || 'en';\n};\n```\n\n### $.language\n\nType: `property`\n\nThe language of the request.\n\nReturns: `String`\n\nAn empty string by default, or the value that the `LOCALIZE()` delegate returned. In a route `$` is the controller and you can assign a new language; a view takes the language when you call `$.view()`, so assign it before.\n\nExample: Set the language in a route\n```js\nexports.install = function() {\n\tROUTE('GET /sk/', index_sk);\n};\n\nfunction index_sk($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\n### $.language\n\nType: `property`\n\nThe language of the request that called the action.\n\nReturns: `String`\n\nIn actions and schemas `$` is an options object. `$.language` returns the language of its controller, or an empty string when the action was called without a request. It is read-only.\n\nExample: Translate in an action\n```js\nNEWACTION('Orders/read', {\n\tname: 'Read an order',\n\taction: function($) {\n\t\t$.callback({ title: TRANSLATE($.language, '@(Your order)') });\n\t}\n});\n```\n\n### view.language\n\nType: `property`\n\nThe language of a view.\n\nReturns: `String`\n\nA view created for a request takes the language of the request. For `F.view()` set it in the `prepare` function. Views are compiled and cached per name and language.\n\nExample: Render a view in German\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{language}\n\nType: `command`\n\nPrints the language of the view.\n\nPrints the language of the request (`$.language`) as it is (an empty string by default, and always empty in `F.view()`). The variable `language` is available in all view expressions.\n\nExample: HTML lang attribute\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\n### /public/*.html\n\nType: `type`\n\nStatic HTML files are translated too.\n\nAn `.html` file from `/public/` is translated into the language of the request (`LOCALIZE()` is called for it) and cached per language. Files whose name contains `.min`, `-min` or `@min` are sent as they are.\n\nExample: A static page\n```html\n<!-- /public/about.html -->\n<h1>@(About us)</h1>\n```\n\n### total5 translate [filename]\n\nType: `command`\n\nCreates a resource file with all `@(...)` texts of a project.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `translate.resource` | The output file. |\n\nReads all `.js` and `.html` files in the current directory and its subfolders, collects every `@(...)` text and writes `key : text` lines into the file. The default file is `translate.resource` in the current directory. Copy the result into `/resources/` under the name of a language and translate the values.\n\nExample: Create a dictionary\n```bash\ncd my-app\ntotal5 translate resources/sk.resource\n```\n\nExample: The result\n```text\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\n### errorbuilder.output([language])\n\nType: `method`\n\nReturns the errors translated into a language.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | The name of the dictionary. |\n\nReturns: `Array` Objects with `name`, `error`, `path` and `index`.\n\nA message in `@(...)` is translated. A field error from a schema validation is read from the resources by the name of the field; without that key the message is `The field \"name\" is invalid`. The framework calls it with the language of the request when it sends errors.\n\nExample: Translate errors\n```js\nvar err = new ErrorBuilder();\nerr.push('@(The name is required)');\nerr.output('sk'); // [{ error: 'Meno je povinné', ... }]\n```\n\n### errorbuilder.toString([language], [divider])\n\nType: `method`\n\nReturns the translated messages as one string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | The name of the dictionary. |\n| `divider` | `String` | no | `'\\n'` | The text between messages. |\n\nReturns: `String`\n\nJoins the messages of `output(language)` with the divider.\n\nExample: One line\n```js\nvar text = err.toString('sk', ', ');\n```\n\n### {field} : message\n\nType: `type`\n\nTranslated messages for invalid fields.\n\nWhen a field fails the validation of a schema, the message is read from the resources with the name of the field as the key, in the language of the request and then in `default`. Without that key the message is `The field \"{name}\" is invalid`.\n\nExample: Messages for fields\n```text\n# /resources/default.resource\nemail : Enter a valid e-mail address\nname  : Enter your name\n```\n\n### MAIL(email, subject, view, model, [language], [callback])\n\nType: `method`\n\nSends an e-mail rendered from a view in a language.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | The recipient. |\n| `subject` | `String` | yes |  | The subject; it can contain `@(...)`. |\n| `view` | `String` | yes |  | The name of the view. |\n| `model` | `Object` | yes |  | The model of the view. |\n| `language` | `String` | no |  | The language. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nWith a language, `@(...)` texts in the subject are translated and the view is rendered with that language. The callback can also come before the language. The [Mail](../../guides/mail/) guide explains sending.\n\nExample: A localized e-mail\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language);\n```\n\n### HTMLMAIL(email, subject, body, [language], [callback])\n\nType: `method`\n\nSends HTML as an e-mail, translated into a language.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | The recipient. |\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\nWith a language, `@(...)` texts in the subject and the body are translated.\n\nExample: Translated body\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for your registration)</p>', 'sk');\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nRenders a template translated into the language of `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | The template, its file name or a URL. |\n| `model` | `Object` | no |  | The model. |\n| `$` | `Object` | no |  | The controller or action options with the language. |\n\nReturns: `Promise` The rendered HTML.\n\nWhen you pass `$`, `@(...)` texts in the template are translated into `$.language` before the template is compiled, and the compiled template is cached per language.\n\nExample: In an action\n```js\nNEWACTION('Orders/print', {\n\tname: 'Print an order',\n\taction: async function($) {\n\t\tvar html = await TEMPLATE('invoice', { number: 'F001' }, $);\n\t\t$.callback(html);\n\t}\n});\n```\n\n### date.format(format, [dictionary])\n\nType: `method`\n\nFormats a date with month and day names from a dictionary.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | yes |  | The format, for example `dddd d. MMMM yyyy`. |\n| `dictionary` | `String` | no |  | The name of the dictionary. |\n\nReturns: `String`\n\n`MMMM` and `MMM` print the month name, `dddd` and `ddd` the day name. With a dictionary, the English name (`January`, `Monday`) is the key; without a translation the English name is used. `MMM` prints the first three characters and `ddd` the first two in upper case.\n\nExample: Slovak names\n```js\n// sk.resource: January : január, Monday : pondelok\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // 'pondelok 1. január'\n```\n\n### AUTH({ localize: function(data, $) {} })\n\nType: `config`\n\nSets the language in the built-in session authorization.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | The session data, or `null`. |\n| `$` | `Controller` | yes |  | The controller of the request. |\n\nThe built-in session authorization calls `localize` (or `locale`) with the session data and the controller and stores the result in `$.language`. Without a session it is called with `null`. The `LOCALIZE()` delegate is then not called. The [Authorization](../../guides/authorization/) guide explains the other options.\n\nExample: Language of the user\n```js\nAUTH({\n\tcookie: 'session',\n\tlocalize: function(data, $) {\n\t\treturn data ? data.language : 'en';\n\t}\n\t// other options\n});\n```\n","entries":[{"type":"type","name":"Resource file","signature":"/resources/{name}.resource","since":"","deprecated":false},{"type":"type","name":"default.resource","signature":"/resources/default.resource","since":"","deprecated":false},{"type":"type","name":"Translation keys","signature":"'T' + text.hash(true).toString(36)","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, [text])","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE(url)","signature":"LOADRESOURCE(url)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE(language, text)","since":"","deprecated":false},{"type":"method","name":"F.resource()","signature":"F.resource(language, key)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocalize","signature":"DEF.onLocalize = function($) {}","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.language (action)","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"type","name":"Static HTML files","signature":"/public/*.html","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate [filename]","since":"","deprecated":false},{"type":"method","name":"errorbuilder.output()","signature":"errorbuilder.output([language])","since":"","deprecated":false},{"type":"method","name":"errorbuilder.toString()","signature":"errorbuilder.toString([language], [divider])","since":"","deprecated":false},{"type":"type","name":"Field error resources","signature":"{field} : message","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(email, subject, view, model, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(email, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"method","name":"date.format()","signature":"date.format(format, [dictionary])","since":"","deprecated":false},{"type":"config","name":"AUTH() localize option","signature":"AUTH({ localize: function(data, $) {} })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JaedDnAlT60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/localization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Lokalisierung","summary":"Ressourcendateien, @(...)-Texte, TRANSLATE(), LOCALIZE(), LOADRESOURCE() und die Sprache einer Anfrage.","markdown":"---\ntitle: Lokalisierung\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/localization/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Lokalisierung\n\n> Ressourcendateien, @(...)-Texte, TRANSLATE(), LOCALIZE(), LOADRESOURCE() und die Sprache einer Anfrage.\n\nFunktionen, Delegates und Dateien der Lokalisierung: Ressourcendateien, `@(...)`-Texte, `TRANSLATE()`, `LOCALIZE()`, die Sprache einer Anfrage und der Befehl `total5 translate`. Der Leitfaden [Lokalisierung](../../guides/localization/) erklärt mit Beispielen, wie sie zusammenarbeiten; diese Seite ist die genaue Referenz.\n\n## API\n\n### /resources/{name}.resource\n\nType: `type`\n\nEine Textdatei mit einem Wörterbuch von Übersetzungen.\n\nJede `.resource`-Datei in `/resources/` und seinen Unterordnern wird beim Start der Anwendung geladen. Der Dateiname ohne Endung ist der Name des Wörterbuchs (`sk.resource` ist `sk`). Pfade, die `-bk` oder `_bk` enthalten, werden übersprungen.\n\nJede Zeile ist `key : value`. Das Trennzeichen ist der erste `:` oder das erste `=`, wenn die Zeile keinen `:` hat; der Wert beginnt beim zweiten Zeichen nach dem Trennzeichen, lass dort also ein Leerzeichen. Schlüssel und Werte werden getrimmt. Leere Zeilen und Zeilen, die mit `#` oder `//` beginnen, werden ignoriert. Die Schlüssel von `@(...)`-Texten sind `T` und ein Hash des Texts; andere Schlüssel sind beliebige Namen, die du mit `F.resource()` liest.\n\nExample: sk.resource\n```text\n# Slovak\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\nname          : Meno\nJanuary       : január\n```\n\n### /resources/default.resource\n\nType: `type`\n\nDas Fallback-Wörterbuch.\n\nFehlt ein Schlüssel im Wörterbuch der Sprache oder hat die Sprache kein Wörterbuch, wird der Schlüssel aus dem Wörterbuch `default` gelesen. Eine leere Sprache (der Standard einer Anfrage) liest direkt `default`.\n\nExample: Fallback\n```js\n// /resources/default.resource contains: name : Name\nF.resource('de', 'name'); // 'Name' when de.resource has no \"name\"\n```\n\n### 'T' + text.hash(true).toString(36)\n\nType: `type`\n\nWie der Schlüssel eines `@(...)`-Texts erzeugt wird.\n\nDer Schlüssel ist `T`, gefolgt vom vorzeichenlosen Hash des Texts innerhalb von `@(...)` in Basis 36. Derselbe Text hat immer denselben Schlüssel, sodass derselbe Text an vielen Stellen nur eine Übersetzung braucht. Eine Änderung des Originaltexts ändert den Schlüssel. Der Befehl `total5 translate` erzeugt die Schlüssel für dich.\n\nExample: Einen Schlüssel berechnen\n```js\nvar key = 'T' + 'Welcome'.hash(true).toString(36); // 'T1bx8wg2'\n```\n\n### @(text)\n\nType: `command`\n\nMarkiert einen Text zur Übersetzung.\n\nDer Text wird durch seine Übersetzung aus dem Wörterbuch der aktuellen Sprache ersetzt, mit einem Fallback auf `default`. Ohne Übersetzung wird der Text unverändert ausgegeben (ohne `@(` und `)`). Klammern innerhalb des Texts müssen ausgeglichen sein. Es funktioniert in Views, statischen `.html`-Dateien, `TRANSLATE()`, Fehlermeldungen, Betreffzeilen und Inhalten von E-Mails sowie in Templates. In Views wird es ersetzt, bevor die View kompiliert wird, daher enthält es nur einfachen Text.\n\nExample: In einer View\n```html\n<h1>@(Welcome)</h1>\n<p>@(Free delivery (over 50 EUR))</p>\n```\n\nExample: Im Code\n```js\n$.invalid('@(The name is required)');\n```\n\n### LOADRESOURCE(name, [text])\n\nType: `method`\n\nParst den Text einer Ressourcendatei und speichert ihn als Wörterbuch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Wörterbuchs, meist ein Sprachcode. |\n| `text` | `String` | no |  | Der Inhalt im Ressourcenformat. |\n\nDer Text hat das Format einer `.resource`-Datei. Das Wörterbuch ersetzt ein Wörterbuch mit demselben Namen vollständig. Es ist dieselbe Funktion wie `F.loadresource()`.\n\nExample: Ein Wörterbuch laden\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte\\nname : Meno');\n```\n\nExample: Aus einer eigenen Datei\n```js\nLOADRESOURCE('de', F.Fs.readFileSync(PATH.root('lang/de.txt'), 'utf8'));\n```\n\n### LOADRESOURCE(url)\n\nType: `method`\n\nLädt Wörterbücher von einer URL herunter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL einer JSON-Antwort mit Wörterbüchern. |\n\nOhne das zweite Argument ist das erste Argument eine URL. Die Antwort muss JSON sein. Ein Objekt wird als `{ name: text }` gelesen, wobei jeder Text im Ressourcenformat vorliegt. Ein Array wird als Elemente gelesen, mit dem Namen in `id`, `key`, `code` oder `language` und dem Text in `value`, `name`, `text` oder `body`. Jedes Wörterbuch wird mit `LOADRESOURCE(name, text)` geladen. Eine fehlgeschlagene Anfrage wirft einen Fehler.\n\nExample: Entfernte Wörterbücher\n```js\n// response: { \"sk\": \"T1bx8wg2 : Vitajte\", \"de\": \"T1bx8wg2 : Willkommen\" }\nLOADRESOURCE('https://example.com/translations.json');\n```\n\n### TRANSLATE(language, text)\n\nType: `method`\n\nÜbersetzt alle `@(...)`-Texte in einem String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Der Name des Wörterbuchs. Ein leerer String verwendet `default`. |\n| `text` | `String` | yes |  | Ein String mit `@(...)`-Texten. |\n\nReturns: `String` Der übersetzte String.\n\nJedes `@(...)` wird durch seine Übersetzung aus dem Wörterbuch der Sprache ersetzt, mit einem Fallback auf `default`; ein Text ohne Übersetzung bleibt ohne die Klammern stehen. Der Rest des Strings wird nicht verändert. Es ist dieselbe Funktion wie `F.translate()`.\n\nExample: Einen String übersetzen\n```js\nTRANSLATE('sk', '<b>@(Welcome)</b>, Peter'); // '<b>Vitajte</b>, Peter'\n```\n\nExample: In einer Route\n```js\nfunction detail($) {\n\t$.plain(TRANSLATE($.language, '@(Order) #' + $.params.id));\n}\n```\n\n### F.resource(language, key)\n\nType: `method`\n\nLiest einen Schlüssel eines Wörterbuchs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Der Name des Wörterbuchs. |\n| `key` | `String` | yes |  | Der Schlüssel. |\n\nReturns: `String` Der Wert oder ein leerer String, wenn der Schlüssel nicht existiert.\n\nLiest den Schlüssel aus dem Wörterbuch der Sprache, dann aus `default`. Verwende es für Schlüssel mit eigenen Namen, nicht für `@(...)`-Texte.\n\nExample: Einen Schlüssel lesen\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n### F.resources\n\nType: `property`\n\nAlle geladenen Wörterbücher.\n\nReturns: `Object`\n\nEin Objekt mit den Wörterbüchern nach ihren Namen. Jedes Wörterbuch ist ein einfaches Objekt aus Schlüsseln und Werten.\n\nExample: Die Sprachen auflisten\n```js\nvar languages = Object.keys(F.resources); // ['default', 'sk', 'de']\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nRegistriert den Delegate, der die Sprache einer Anfrage wählt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)`, die die Sprache als String zurückgibt. |\n\nDie Funktion erhält den Controller und gibt die Sprache (einen Wörterbuchnamen) zurück. Sie wird für Routen nach der Autorisierung und vor der Middleware, für statische `.html`-Dateien und für WebSocket-Routen aufgerufen. Für HTTP-Routen und statische Dateien wird sie nicht aufgerufen, wenn die Sprache bereits gesetzt ist. Das Ergebnis wird in `$.language` gespeichert. Sie setzt `DEF.onLocalize`.\n\nExample: Aus dem Query String oder dem Browser\n```js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nExample: Vom Benutzer\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\n### DEF.onLocalize = function($) {}\n\nType: `delegate`\n\nDer Delegate, den `LOCALIZE()` setzt.\n\n`LOCALIZE(fn)` speichert die Funktion hier. Du kannst sie auch direkt zuweisen; setze sie auf `null`, um die Sprachauswahl zu beenden.\n\nExample: Direkt zuweisen\n```js\nDEF.onLocalize = function($) {\n\treturn $.cookie('language') || 'en';\n};\n```\n\n### $.language\n\nType: `property`\n\nDie Sprache der Anfrage.\n\nReturns: `String`\n\nStandardmäßig ein leerer String oder der Wert, den der `LOCALIZE()`-Delegate zurückgegeben hat. In einer Route ist `$` der Controller, und du kannst eine neue Sprache zuweisen; eine View übernimmt die Sprache, wenn du `$.view()` aufrufst, weise sie also vorher zu.\n\nExample: Die Sprache in einer Route setzen\n```js\nexports.install = function() {\n\tROUTE('GET /sk/', index_sk);\n};\n\nfunction index_sk($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\n### $.language\n\nType: `property`\n\nDie Sprache der Anfrage, die die Aktion aufgerufen hat.\n\nReturns: `String`\n\nIn Aktionen und Schemas ist `$` ein Optionsobjekt. `$.language` gibt die Sprache seines Controllers zurück oder einen leeren String, wenn die Aktion ohne Anfrage aufgerufen wurde. Sie ist schreibgeschützt.\n\nExample: In einer Aktion übersetzen\n```js\nNEWACTION('Orders/read', {\n\tname: 'Read an order',\n\taction: function($) {\n\t\t$.callback({ title: TRANSLATE($.language, '@(Your order)') });\n\t}\n});\n```\n\n### view.language\n\nType: `property`\n\nDie Sprache einer View.\n\nReturns: `String`\n\nEine für eine Anfrage erstellte View übernimmt die Sprache der Anfrage. Für `F.view()` setze sie in der Funktion `prepare`. Views werden pro Name und Sprache kompiliert und gecacht.\n\nExample: Eine View auf Deutsch rendern\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{language}\n\nType: `command`\n\nGibt die Sprache der View aus.\n\nGibt die Sprache der Anfrage (`$.language`) unverändert aus (standardmäßig einen leeren String und in `F.view()` immer leer). Die Variable `language` ist in allen Ausdrücken der View verfügbar.\n\nExample: HTML-Attribut lang\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\n### /public/*.html\n\nType: `type`\n\nAuch statische HTML-Dateien werden übersetzt.\n\nEine `.html`-Datei aus `/public/` wird in die Sprache der Anfrage übersetzt (`LOCALIZE()` wird dafür aufgerufen) und pro Sprache gecacht. Dateien, deren Name `.min`, `-min` oder `@min` enthält, werden unverändert gesendet.\n\nExample: Eine statische Seite\n```html\n<!-- /public/about.html -->\n<h1>@(About us)</h1>\n```\n\n### total5 translate [filename]\n\nType: `command`\n\nErstellt eine Ressourcendatei mit allen `@(...)`-Texten eines Projekts.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `translate.resource` | Die Ausgabedatei. |\n\nLiest alle `.js`- und `.html`-Dateien im aktuellen Verzeichnis und seinen Unterordnern, sammelt jeden `@(...)`-Text und schreibt `key : text`-Zeilen in die Datei. Die Standarddatei ist `translate.resource` im aktuellen Verzeichnis. Kopiere das Ergebnis unter dem Namen einer Sprache nach `/resources/` und übersetze die Werte.\n\nExample: Ein Wörterbuch erstellen\n```bash\ncd my-app\ntotal5 translate resources/sk.resource\n```\n\nExample: Das Ergebnis\n```text\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\n### errorbuilder.output([language])\n\nType: `method`\n\nGibt die in eine Sprache übersetzten Fehler zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Der Name des Wörterbuchs. |\n\nReturns: `Array` Objekte mit `name`, `error`, `path` und `index`.\n\nEine Meldung in `@(...)` wird übersetzt. Ein Feldfehler aus einer Schemavalidierung wird über den Namen des Felds aus den Ressourcen gelesen; ohne diesen Schlüssel lautet die Meldung `The field \"name\" is invalid`. Das Framework ruft es beim Senden von Fehlern mit der Sprache der Anfrage auf.\n\nExample: Fehler übersetzen\n```js\nvar err = new ErrorBuilder();\nerr.push('@(The name is required)');\nerr.output('sk'); // [{ error: 'Meno je povinné', ... }]\n```\n\n### errorbuilder.toString([language], [divider])\n\nType: `method`\n\nGibt die übersetzten Meldungen als einen String zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Der Name des Wörterbuchs. |\n| `divider` | `String` | no | `'\\n'` | Der Text zwischen den Meldungen. |\n\nReturns: `String`\n\nVerbindet die Meldungen von `output(language)` mit dem Trennzeichen.\n\nExample: Eine Zeile\n```js\nvar text = err.toString('sk', ', ');\n```\n\n### {field} : message\n\nType: `type`\n\nÜbersetzte Meldungen für ungültige Felder.\n\nBesteht ein Feld die Validierung eines Schemas nicht, wird die Meldung mit dem Namen des Felds als Schlüssel aus den Ressourcen gelesen, in der Sprache der Anfrage und dann in `default`. Ohne diesen Schlüssel lautet die Meldung `The field \"{name}\" is invalid`.\n\nExample: Meldungen für Felder\n```text\n# /resources/default.resource\nemail : Enter a valid e-mail address\nname  : Enter your name\n```\n\n### MAIL(email, subject, view, model, [language], [callback])\n\nType: `method`\n\nSendet eine aus einer View gerenderte E-Mail in einer Sprache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Der Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff; er kann `@(...)` enthalten. |\n| `view` | `String` | yes |  | Der Name der View. |\n| `model` | `Object` | yes |  | Das Modell der View. |\n| `language` | `String` | no |  | Die Sprache. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nMit einer Sprache werden `@(...)`-Texte im Betreff übersetzt, und die View wird in dieser Sprache gerendert. Der Callback kann auch vor der Sprache stehen. Der Leitfaden [Mail](../../guides/mail/) erklärt das Senden.\n\nExample: Eine lokalisierte E-Mail\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language);\n```\n\n### HTMLMAIL(email, subject, body, [language], [callback])\n\nType: `method`\n\nSendet HTML als E-Mail, übersetzt in eine Sprache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Der Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff. |\n| `body` | `String` | yes |  | Der HTML-Inhalt. |\n| `language` | `String` | no |  | Die Sprache. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nMit einer Sprache werden `@(...)`-Texte im Betreff und im Inhalt übersetzt.\n\nExample: Übersetzter Inhalt\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for your registration)</p>', 'sk');\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nRendert ein Template, übersetzt in die Sprache von `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Das Template, sein Dateiname oder eine URL. |\n| `model` | `Object` | no |  | Das Modell. |\n| `$` | `Object` | no |  | Der Controller oder die Optionen der Aktion mit der Sprache. |\n\nReturns: `Promise` Das gerenderte HTML.\n\nWenn du `$` übergibst, werden `@(...)`-Texte im Template vor dem Kompilieren in `$.language` übersetzt, und das kompilierte Template wird pro Sprache gecacht.\n\nExample: In einer Aktion\n```js\nNEWACTION('Orders/print', {\n\tname: 'Print an order',\n\taction: async function($) {\n\t\tvar html = await TEMPLATE('invoice', { number: 'F001' }, $);\n\t\t$.callback(html);\n\t}\n});\n```\n\n### date.format(format, [dictionary])\n\nType: `method`\n\nFormatiert ein Datum mit Monats- und Tagesnamen aus einem Wörterbuch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | yes |  | Das Format, zum Beispiel `dddd d. MMMM yyyy`. |\n| `dictionary` | `String` | no |  | Der Name des Wörterbuchs. |\n\nReturns: `String`\n\n`MMMM` und `MMM` geben den Monatsnamen aus, `dddd` und `ddd` den Tagesnamen. Mit einem Wörterbuch ist der englische Name (`January`, `Monday`) der Schlüssel; ohne Übersetzung wird der englische Name verwendet. `MMM` gibt die ersten drei Zeichen aus und `ddd` die ersten zwei in Großbuchstaben.\n\nExample: Slowakische Namen\n```js\n// sk.resource: January : január, Monday : pondelok\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // 'pondelok 1. január'\n```\n\n### AUTH({ localize: function(data, $) {} })\n\nType: `config`\n\nSetzt die Sprache in der eingebauten Session-Autorisierung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Die Session-Daten oder `null`. |\n| `$` | `Controller` | yes |  | Der Controller der Anfrage. |\n\nDie eingebaute Session-Autorisierung ruft `localize` (oder `locale`) mit den Session-Daten und dem Controller auf und speichert das Ergebnis in `$.language`. Ohne Session wird sie mit `null` aufgerufen. Der `LOCALIZE()`-Delegate wird dann nicht aufgerufen. Der Leitfaden [Autorisierung](../../guides/authorization/) erklärt die anderen Optionen.\n\nExample: Sprache des Benutzers\n```js\nAUTH({\n\tcookie: 'session',\n\tlocalize: function(data, $) {\n\t\treturn data ? data.language : 'en';\n\t}\n\t// other options\n});\n```\n","entries":[{"type":"type","name":"Resource file","signature":"/resources/{name}.resource","since":"","deprecated":false},{"type":"type","name":"default.resource","signature":"/resources/default.resource","since":"","deprecated":false},{"type":"type","name":"Translation keys","signature":"'T' + text.hash(true).toString(36)","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, [text])","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE(url)","signature":"LOADRESOURCE(url)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE(language, text)","since":"","deprecated":false},{"type":"method","name":"F.resource()","signature":"F.resource(language, key)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocalize","signature":"DEF.onLocalize = function($) {}","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.language (action)","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"type","name":"Static HTML files","signature":"/public/*.html","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate [filename]","since":"","deprecated":false},{"type":"method","name":"errorbuilder.output()","signature":"errorbuilder.output([language])","since":"","deprecated":false},{"type":"method","name":"errorbuilder.toString()","signature":"errorbuilder.toString([language], [divider])","since":"","deprecated":false},{"type":"type","name":"Field error resources","signature":"{field} : message","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(email, subject, view, model, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(email, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"method","name":"date.format()","signature":"date.format(format, [dictionary])","since":"","deprecated":false},{"type":"config","name":"AUTH() localize option","signature":"AUTH({ localize: function(data, $) {} })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JaedDnAlT60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/localization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Localización","summary":"Archivos de recursos, textos @(...), TRANSLATE(), LOCALIZE(), LOADRESOURCE() y el idioma de una petición.","markdown":"---\ntitle: \"Localización\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/localization/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Localización\n\n> Archivos de recursos, textos @(...), TRANSLATE(), LOCALIZE(), LOADRESOURCE() y el idioma de una petición.\n\nFunciones, delegados y archivos de la localización: archivos de recursos, textos `@(...)`, `TRANSLATE()`, `LOCALIZE()`, el idioma de una petición y el comando `total5 translate`. La guía [Localización](../../guides/localization/) explica con ejemplos cómo funcionan juntos; esta página es la referencia exacta.\n\n## API\n\n### /resources/{name}.resource\n\nType: `type`\n\nUn archivo de texto con un diccionario de traducciones.\n\nCada archivo `.resource` de `/resources/` y de sus subcarpetas se carga cuando arranca la aplicación. El nombre del archivo sin la extensión es el nombre del diccionario (`sk.resource` es `sk`). Las rutas que contienen `-bk` o `_bk` se omiten.\n\nCada línea es `key : value`. El separador es el primer `:`, o el primer `=` cuando la línea no tiene `:`; el valor empieza en el segundo carácter después del separador, así que deja un espacio ahí. Las claves y los valores se recortan. Las líneas vacías y las que empiezan por `#` o `//` se ignoran. Las claves de los textos `@(...)` son `T` y un hash del texto; las demás claves son cualquier nombre que leas con `F.resource()`.\n\nExample: sk.resource\n```text\n# Slovak\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\nname          : Meno\nJanuary       : január\n```\n\n### /resources/default.resource\n\nType: `type`\n\nEl diccionario de respaldo.\n\nCuando falta una clave en el diccionario del idioma, o el idioma no tiene diccionario, la clave se lee del diccionario `default`. Un idioma vacío (el valor por defecto de una petición) lee `default` directamente.\n\nExample: Respaldo\n```js\n// /resources/default.resource contains: name : Name\nF.resource('de', 'name'); // 'Name' when de.resource has no \"name\"\n```\n\n### 'T' + text.hash(true).toString(36)\n\nType: `type`\n\nCómo se crea la clave de un texto `@(...)`.\n\nLa clave es `T` seguida del hash sin signo del texto de dentro de `@(...)` en base 36. El mismo texto siempre tiene la misma clave, así que el mismo texto en muchos sitios necesita una sola traducción. Cambiar el texto original cambia la clave. El comando `total5 translate` crea las claves por ti.\n\nExample: Calcular una clave\n```js\nvar key = 'T' + 'Welcome'.hash(true).toString(36); // 'T1bx8wg2'\n```\n\n### @(text)\n\nType: `command`\n\nMarca un texto para traducirlo.\n\nEl texto se sustituye por su traducción del diccionario del idioma actual, con respaldo en `default`. Sin traducción, el texto se imprime tal cual (sin `@(` y `)`). Los paréntesis dentro del texto deben estar equilibrados. Funciona en vistas, archivos estáticos `.html`, `TRANSLATE()`, mensajes de error, asuntos y cuerpos de correos electrónicos y plantillas. En las vistas se sustituye antes de compilar la vista, así que contiene solo texto plano.\n\nExample: En una vista\n```html\n<h1>@(Welcome)</h1>\n<p>@(Free delivery (over 50 EUR))</p>\n```\n\nExample: En el código\n```js\n$.invalid('@(The name is required)');\n```\n\n### LOADRESOURCE(name, [text])\n\nType: `method`\n\nAnaliza el texto de un archivo de recursos y lo guarda como diccionario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del diccionario, normalmente un código de idioma. |\n| `text` | `String` | no |  | El contenido en el formato de recursos. |\n\nEl texto tiene el formato de un archivo `.resource`. El diccionario sustituye por completo a un diccionario con el mismo nombre. Es la misma función que `F.loadresource()`.\n\nExample: Cargar un diccionario\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte\\nname : Meno');\n```\n\nExample: Desde un archivo propio\n```js\nLOADRESOURCE('de', F.Fs.readFileSync(PATH.root('lang/de.txt'), 'utf8'));\n```\n\n### LOADRESOURCE(url)\n\nType: `method`\n\nDescarga diccionarios desde una URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL de una respuesta JSON con diccionarios. |\n\nSin el segundo argumento, el primer argumento es una URL. La respuesta debe ser JSON. Un objeto se lee como `{ name: text }`, donde cada texto está en el formato de recursos. Un array se lee como elementos con el nombre en `id`, `key`, `code` o `language` y el texto en `value`, `name`, `text` o `body`. Cada diccionario se carga con `LOADRESOURCE(name, text)`. Una petición fallida lanza un error.\n\nExample: Diccionarios remotos\n```js\n// response: { \"sk\": \"T1bx8wg2 : Vitajte\", \"de\": \"T1bx8wg2 : Willkommen\" }\nLOADRESOURCE('https://example.com/translations.json');\n```\n\n### TRANSLATE(language, text)\n\nType: `method`\n\nTraduce todos los textos `@(...)` de una cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | El nombre del diccionario. Una cadena vacía usa `default`. |\n| `text` | `String` | yes |  | Una cadena con textos `@(...)`. |\n\nReturns: `String` La cadena traducida.\n\nCada `@(...)` se sustituye por su traducción del diccionario del idioma, con respaldo en `default`; un texto sin traducción queda sin los paréntesis. El resto de la cadena no cambia. Es la misma función que `F.translate()`.\n\nExample: Traducir una cadena\n```js\nTRANSLATE('sk', '<b>@(Welcome)</b>, Peter'); // '<b>Vitajte</b>, Peter'\n```\n\nExample: En una ruta\n```js\nfunction detail($) {\n\t$.plain(TRANSLATE($.language, '@(Order) #' + $.params.id));\n}\n```\n\n### F.resource(language, key)\n\nType: `method`\n\nLee una clave de un diccionario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | El nombre del diccionario. |\n| `key` | `String` | yes |  | La clave. |\n\nReturns: `String` El valor, o una cadena vacía cuando la clave no existe.\n\nLee la clave del diccionario del idioma y después de `default`. Úsalo para claves con nombres propios, no para textos `@(...)`.\n\nExample: Leer una clave\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n### F.resources\n\nType: `property`\n\nTodos los diccionarios cargados.\n\nReturns: `Object`\n\nUn objeto con los diccionarios por sus nombres. Cada diccionario es un objeto plano de claves y valores.\n\nExample: Listar los idiomas\n```js\nvar languages = Object.keys(F.resources); // ['default', 'sk', 'de']\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nRegistra el delegado que elige el idioma de una petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)` que devuelve el idioma como cadena. |\n\nLa función recibe el controlador y devuelve el idioma (un nombre de diccionario). Se llama para las rutas después de la autorización y antes del middleware, para los archivos estáticos `.html` y para las rutas WebSocket. Para las rutas HTTP y los archivos estáticos no se llama cuando el idioma ya está definido. El resultado se guarda en `$.language`. Define `DEF.onLocalize`.\n\nExample: Desde la query string o el navegador\n```js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nExample: Desde el usuario\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\n### DEF.onLocalize = function($) {}\n\nType: `delegate`\n\nEl delegado que define `LOCALIZE()`.\n\n`LOCALIZE(fn)` guarda la función aquí. También puedes asignarla directamente; ponla a `null` para dejar de elegir el idioma.\n\nExample: Asignar directamente\n```js\nDEF.onLocalize = function($) {\n\treturn $.cookie('language') || 'en';\n};\n```\n\n### $.language\n\nType: `property`\n\nEl idioma de la petición.\n\nReturns: `String`\n\nUna cadena vacía por defecto, o el valor que devolvió el delegado de `LOCALIZE()`. En una ruta `$` es el controlador y puedes asignar un idioma nuevo; una vista toma el idioma cuando llamas a `$.view()`, así que asígnalo antes.\n\nExample: Definir el idioma en una ruta\n```js\nexports.install = function() {\n\tROUTE('GET /sk/', index_sk);\n};\n\nfunction index_sk($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\n### $.language\n\nType: `property`\n\nEl idioma de la petición que llamó a la acción.\n\nReturns: `String`\n\nEn las acciones y los esquemas `$` es un objeto de opciones. `$.language` devuelve el idioma de su controlador, o una cadena vacía cuando la acción se llamó sin petición. Es de solo lectura.\n\nExample: Traducir en una acción\n```js\nNEWACTION('Orders/read', {\n\tname: 'Read an order',\n\taction: function($) {\n\t\t$.callback({ title: TRANSLATE($.language, '@(Your order)') });\n\t}\n});\n```\n\n### view.language\n\nType: `property`\n\nEl idioma de una vista.\n\nReturns: `String`\n\nUna vista creada para una petición toma el idioma de la petición. Para `F.view()` defínelo en la función `prepare`. Las vistas se compilan y se guardan en caché por nombre e idioma.\n\nExample: Renderizar una vista en alemán\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{language}\n\nType: `command`\n\nImprime el idioma de la vista.\n\nImprime el idioma de la petición (`$.language`) tal cual (una cadena vacía por defecto, y siempre vacía en `F.view()`). La variable `language` está disponible en todas las expresiones de las vistas.\n\nExample: Atributo lang de HTML\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\n### /public/*.html\n\nType: `type`\n\nLos archivos HTML estáticos también se traducen.\n\nUn archivo `.html` de `/public/` se traduce al idioma de la petición (se llama a `LOCALIZE()` para él) y se guarda en caché por idioma. Los archivos cuyo nombre contiene `.min`, `-min` o `@min` se envían tal cual.\n\nExample: Una página estática\n```html\n<!-- /public/about.html -->\n<h1>@(About us)</h1>\n```\n\n### total5 translate [filename]\n\nType: `command`\n\nCrea un archivo de recursos con todos los textos `@(...)` de un proyecto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `translate.resource` | El archivo de salida. |\n\nLee todos los archivos `.js` y `.html` del directorio actual y de sus subcarpetas, reúne cada texto `@(...)` y escribe líneas `key : text` en el archivo. El archivo por defecto es `translate.resource` en el directorio actual. Copia el resultado en `/resources/` con el nombre de un idioma y traduce los valores.\n\nExample: Crear un diccionario\n```bash\ncd my-app\ntotal5 translate resources/sk.resource\n```\n\nExample: El resultado\n```text\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\n### errorbuilder.output([language])\n\nType: `method`\n\nDevuelve los errores traducidos a un idioma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | El nombre del diccionario. |\n\nReturns: `Array` Objetos con `name`, `error`, `path` e `index`.\n\nUn mensaje en `@(...)` se traduce. Un error de campo de la validación de un esquema se lee de los recursos por el nombre del campo; sin esa clave el mensaje es `The field \"name\" is invalid`. El framework lo llama con el idioma de la petición cuando envía errores.\n\nExample: Traducir errores\n```js\nvar err = new ErrorBuilder();\nerr.push('@(The name is required)');\nerr.output('sk'); // [{ error: 'Meno je povinné', ... }]\n```\n\n### errorbuilder.toString([language], [divider])\n\nType: `method`\n\nDevuelve los mensajes traducidos como una sola cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | El nombre del diccionario. |\n| `divider` | `String` | no | `'\\n'` | El texto entre mensajes. |\n\nReturns: `String`\n\nUne los mensajes de `output(language)` con el separador.\n\nExample: Una línea\n```js\nvar text = err.toString('sk', ', ');\n```\n\n### {field} : message\n\nType: `type`\n\nMensajes traducidos para campos no válidos.\n\nCuando un campo no supera la validación de un esquema, el mensaje se lee de los recursos con el nombre del campo como clave, en el idioma de la petición y después en `default`. Sin esa clave el mensaje es `The field \"{name}\" is invalid`.\n\nExample: Mensajes para campos\n```text\n# /resources/default.resource\nemail : Enter a valid e-mail address\nname  : Enter your name\n```\n\n### MAIL(email, subject, view, model, [language], [callback])\n\nType: `method`\n\nEnvía un correo electrónico renderizado desde una vista en un idioma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | El destinatario. |\n| `subject` | `String` | yes |  | El asunto; puede contener `@(...)`. |\n| `view` | `String` | yes |  | El nombre de la vista. |\n| `model` | `Object` | yes |  | El modelo de la vista. |\n| `language` | `String` | no |  | El idioma. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nCon un idioma, se traducen los textos `@(...)` del asunto y la vista se renderiza con ese idioma. El callback también puede ir antes del idioma. La guía [Correo](../../guides/mail/) explica el envío.\n\nExample: Un correo localizado\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language);\n```\n\n### HTMLMAIL(email, subject, body, [language], [callback])\n\nType: `method`\n\nEnvía HTML como correo electrónico, traducido a un idioma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | El destinatario. |\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\nCon un idioma, se traducen los textos `@(...)` del asunto y del cuerpo.\n\nExample: Cuerpo traducido\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for your registration)</p>', 'sk');\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nRenderiza una plantilla traducida al idioma de `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | La plantilla, su nombre de archivo o una URL. |\n| `model` | `Object` | no |  | El modelo. |\n| `$` | `Object` | no |  | El controlador o las opciones de la acción con el idioma. |\n\nReturns: `Promise` El HTML renderizado.\n\nCuando pasas `$`, los textos `@(...)` de la plantilla se traducen a `$.language` antes de compilar la plantilla, y la plantilla compilada se guarda en caché por idioma.\n\nExample: En una acción\n```js\nNEWACTION('Orders/print', {\n\tname: 'Print an order',\n\taction: async function($) {\n\t\tvar html = await TEMPLATE('invoice', { number: 'F001' }, $);\n\t\t$.callback(html);\n\t}\n});\n```\n\n### date.format(format, [dictionary])\n\nType: `method`\n\nFormatea una fecha con nombres de meses y días de un diccionario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | yes |  | El formato, por ejemplo `dddd d. MMMM yyyy`. |\n| `dictionary` | `String` | no |  | El nombre del diccionario. |\n\nReturns: `String`\n\n`MMMM` y `MMM` imprimen el nombre del mes, `dddd` y `ddd` el nombre del día. Con un diccionario, el nombre en inglés (`January`, `Monday`) es la clave; sin traducción se usa el nombre en inglés. `MMM` imprime los tres primeros caracteres y `ddd` los dos primeros en mayúsculas.\n\nExample: Nombres en eslovaco\n```js\n// sk.resource: January : január, Monday : pondelok\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // 'pondelok 1. január'\n```\n\n### AUTH({ localize: function(data, $) {} })\n\nType: `config`\n\nDefine el idioma en la autorización por sesión integrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Los datos de la sesión, o `null`. |\n| `$` | `Controller` | yes |  | El controlador de la petición. |\n\nLa autorización por sesión integrada llama a `localize` (o `locale`) con los datos de la sesión y el controlador y guarda el resultado en `$.language`. Sin sesión se llama con `null`. Entonces no se llama al delegado de `LOCALIZE()`. La guía [Autorización](../../guides/authorization/) explica las demás opciones.\n\nExample: Idioma del usuario\n```js\nAUTH({\n\tcookie: 'session',\n\tlocalize: function(data, $) {\n\t\treturn data ? data.language : 'en';\n\t}\n\t// other options\n});\n```\n","entries":[{"type":"type","name":"Resource file","signature":"/resources/{name}.resource","since":"","deprecated":false},{"type":"type","name":"default.resource","signature":"/resources/default.resource","since":"","deprecated":false},{"type":"type","name":"Translation keys","signature":"'T' + text.hash(true).toString(36)","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, [text])","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE(url)","signature":"LOADRESOURCE(url)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE(language, text)","since":"","deprecated":false},{"type":"method","name":"F.resource()","signature":"F.resource(language, key)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocalize","signature":"DEF.onLocalize = function($) {}","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.language (action)","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"type","name":"Static HTML files","signature":"/public/*.html","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate [filename]","since":"","deprecated":false},{"type":"method","name":"errorbuilder.output()","signature":"errorbuilder.output([language])","since":"","deprecated":false},{"type":"method","name":"errorbuilder.toString()","signature":"errorbuilder.toString([language], [divider])","since":"","deprecated":false},{"type":"type","name":"Field error resources","signature":"{field} : message","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(email, subject, view, model, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(email, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"method","name":"date.format()","signature":"date.format(format, [dictionary])","since":"","deprecated":false},{"type":"config","name":"AUTH() localize option","signature":"AUTH({ localize: function(data, $) {} })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JaedDnAlT60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/localization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Localisation","summary":"Fichiers de ressources, textes @(...), TRANSLATE(), LOCALIZE(), LOADRESOURCE() et la langue d'une requête.","markdown":"---\ntitle: Localisation\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/localization/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Localisation\n\n> Fichiers de ressources, textes @(...), TRANSLATE(), LOCALIZE(), LOADRESOURCE() et la langue d'une requête.\n\nLes fonctions, délégués et fichiers de la localisation : fichiers de ressources, textes `@(...)`, `TRANSLATE()`, `LOCALIZE()`, la langue d'une requête et la commande `total5 translate`. Le guide [Localisation](../../guides/localization/) explique avec des exemples comment ils fonctionnent ensemble ; cette page en est la référence exacte.\n\n## API\n\n### /resources/{name}.resource\n\nType: `type`\n\nUn fichier texte contenant un dictionnaire de traductions.\n\nChaque fichier `.resource` de `/resources/` et de ses sous-dossiers est chargé au démarrage de l'application. Le nom du fichier sans l'extension est le nom du dictionnaire (`sk.resource` est `sk`). Les chemins qui contiennent `-bk` ou `_bk` sont ignorés.\n\nChaque ligne est de la forme `key : value`. Le séparateur est le premier `:`, ou le premier `=` lorsque la ligne ne contient pas de `:` ; la valeur commence au deuxième caractère après le séparateur, laisse donc un espace à cet endroit. Les clés et les valeurs sont débarrassées de leurs espaces. Les lignes vides et les lignes qui commencent par `#` ou `//` sont ignorées. Les clés des textes `@(...)` sont `T` suivi d'un hash du texte ; les autres clés sont des noms quelconques que tu lis avec `F.resource()`.\n\nExample: sk.resource\n```text\n# Slovak\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\nname          : Meno\nJanuary       : január\n```\n\n### /resources/default.resource\n\nType: `type`\n\nLe dictionnaire de repli.\n\nLorsqu'une clé manque dans le dictionnaire de la langue, ou que la langue n'a pas de dictionnaire, la clé est lue dans le dictionnaire `default`. Une langue vide (la valeur par défaut d'une requête) lit directement `default`.\n\nExample: Repli\n```js\n// /resources/default.resource contains: name : Name\nF.resource('de', 'name'); // 'Name' when de.resource has no \"name\"\n```\n\n### 'T' + text.hash(true).toString(36)\n\nType: `type`\n\nComment la clé d'un texte `@(...)` est créée.\n\nLa clé est `T` suivi du hash non signé, en base 36, du texte placé dans `@(...)`. Un même texte a toujours la même clé ; le même texte à plusieurs endroits n'a donc besoin que d'une traduction. Modifier le texte original change la clé. La commande `total5 translate` crée les clés pour toi.\n\nExample: Calculer une clé\n```js\nvar key = 'T' + 'Welcome'.hash(true).toString(36); // 'T1bx8wg2'\n```\n\n### @(text)\n\nType: `command`\n\nMarque un texte à traduire.\n\nLe texte est remplacé par sa traduction issue du dictionnaire de la langue courante, avec un repli sur `default`. Sans traduction, le texte est affiché tel quel (sans `@(` ni `)`). Les parenthèses dans le texte doivent être équilibrées. Cela fonctionne dans les vues, les fichiers `.html` statiques, `TRANSLATE()`, les messages d'erreur, les sujets et corps d'e-mails et les templates. Dans les vues, il est remplacé avant la compilation de la vue ; il ne contient donc que du texte simple.\n\nExample: Dans une vue\n```html\n<h1>@(Welcome)</h1>\n<p>@(Free delivery (over 50 EUR))</p>\n```\n\nExample: Dans le code\n```js\n$.invalid('@(The name is required)');\n```\n\n### LOADRESOURCE(name, [text])\n\nType: `method`\n\nAnalyse le texte d'un fichier de ressources et le stocke comme dictionnaire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du dictionnaire, généralement un code de langue. |\n| `text` | `String` | no |  | Le contenu au format ressource. |\n\nLe texte a le format d'un fichier `.resource`. Le dictionnaire remplace entièrement un dictionnaire du même nom. C'est la même fonction que `F.loadresource()`.\n\nExample: Charger un dictionnaire\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte\\nname : Meno');\n```\n\nExample: Depuis ton propre fichier\n```js\nLOADRESOURCE('de', F.Fs.readFileSync(PATH.root('lang/de.txt'), 'utf8'));\n```\n\n### LOADRESOURCE(url)\n\nType: `method`\n\nTélécharge des dictionnaires depuis une URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL d'une réponse JSON contenant des dictionnaires. |\n\nSans le second argument, le premier argument est une URL. La réponse doit être du JSON. Un objet est lu comme `{ name: text }`, où chaque texte est au format ressource. Un tableau est lu comme des éléments avec le nom dans `id`, `key`, `code` ou `language` et le texte dans `value`, `name`, `text` ou `body`. Chaque dictionnaire est chargé avec `LOADRESOURCE(name, text)`. Une requête qui échoue lève une erreur.\n\nExample: Dictionnaires distants\n```js\n// response: { \"sk\": \"T1bx8wg2 : Vitajte\", \"de\": \"T1bx8wg2 : Willkommen\" }\nLOADRESOURCE('https://example.com/translations.json');\n```\n\n### TRANSLATE(language, text)\n\nType: `method`\n\nTraduit tous les textes `@(...)` d'une chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Le nom du dictionnaire. Une chaîne vide utilise `default`. |\n| `text` | `String` | yes |  | Une chaîne contenant des textes `@(...)`. |\n\nReturns: `String` La chaîne traduite.\n\nChaque `@(...)` est remplacé par sa traduction issue du dictionnaire de la langue, avec un repli sur `default` ; un texte sans traduction reste sans les délimiteurs. Le reste de la chaîne n'est pas modifié. C'est la même fonction que `F.translate()`.\n\nExample: Traduire une chaîne\n```js\nTRANSLATE('sk', '<b>@(Welcome)</b>, Peter'); // '<b>Vitajte</b>, Peter'\n```\n\nExample: Dans une route\n```js\nfunction detail($) {\n\t$.plain(TRANSLATE($.language, '@(Order) #' + $.params.id));\n}\n```\n\n### F.resource(language, key)\n\nType: `method`\n\nLit une clé d'un dictionnaire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Le nom du dictionnaire. |\n| `key` | `String` | yes |  | La clé. |\n\nReturns: `String` La valeur, ou une chaîne vide lorsque la clé n'existe pas.\n\nLit la clé dans le dictionnaire de la langue, puis dans `default`. Utilise-la pour des clés avec tes propres noms, pas pour les textes `@(...)`.\n\nExample: Lire une clé\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n### F.resources\n\nType: `property`\n\nTous les dictionnaires chargés.\n\nReturns: `Object`\n\nUn objet contenant les dictionnaires par leur nom. Chaque dictionnaire est un objet simple de clés et de valeurs.\n\nExample: Lister les langues\n```js\nvar languages = Object.keys(F.resources); // ['default', 'sk', 'de']\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nEnregistre le délégué qui choisit la langue d'une requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)` qui renvoie la langue sous forme de chaîne. |\n\nLa fonction reçoit le contrôleur et renvoie la langue (un nom de dictionnaire). Elle est appelée pour les routes après l'autorisation et avant le middleware, pour les fichiers `.html` statiques et pour les routes WebSocket. Pour les routes HTTP et les fichiers statiques, elle n'est pas appelée lorsque la langue est déjà définie. Le résultat est stocké dans `$.language`. Elle définit `DEF.onLocalize`.\n\nExample: Depuis la query string ou le navigateur\n```js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nExample: Depuis l'utilisateur\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\n### DEF.onLocalize = function($) {}\n\nType: `delegate`\n\nLe délégué que définit `LOCALIZE()`.\n\n`LOCALIZE(fn)` stocke la fonction ici. Tu peux aussi l'assigner directement ; définis-la à `null` pour ne plus choisir la langue.\n\nExample: Assigner directement\n```js\nDEF.onLocalize = function($) {\n\treturn $.cookie('language') || 'en';\n};\n```\n\n### $.language\n\nType: `property`\n\nLa langue de la requête.\n\nReturns: `String`\n\nUne chaîne vide par défaut, ou la valeur renvoyée par le délégué `LOCALIZE()`. Dans une route, `$` est le contrôleur et tu peux assigner une nouvelle langue ; une vue prend la langue au moment où tu appelles `$.view()`, assigne-la donc avant.\n\nExample: Définir la langue dans une route\n```js\nexports.install = function() {\n\tROUTE('GET /sk/', index_sk);\n};\n\nfunction index_sk($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\n### $.language\n\nType: `property`\n\nLa langue de la requête qui a appelé l'action.\n\nReturns: `String`\n\nDans les actions et les schémas, `$` est un objet d'options. `$.language` renvoie la langue de son contrôleur, ou une chaîne vide lorsque l'action a été appelée sans requête. Elle est en lecture seule.\n\nExample: Traduire dans une action\n```js\nNEWACTION('Orders/read', {\n\tname: 'Read an order',\n\taction: function($) {\n\t\t$.callback({ title: TRANSLATE($.language, '@(Your order)') });\n\t}\n});\n```\n\n### view.language\n\nType: `property`\n\nLa langue d'une vue.\n\nReturns: `String`\n\nUne vue créée pour une requête prend la langue de la requête. Pour `F.view()`, définis-la dans la fonction `prepare`. Les vues sont compilées et mises en cache par nom et par langue.\n\nExample: Rendre une vue en allemand\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{language}\n\nType: `command`\n\nAffiche la langue de la vue.\n\nAffiche la langue de la requête (`$.language`) telle quelle (une chaîne vide par défaut, et toujours vide dans `F.view()`). La variable `language` est disponible dans toutes les expressions de vue.\n\nExample: Attribut HTML lang\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\n### /public/*.html\n\nType: `type`\n\nLes fichiers HTML statiques sont aussi traduits.\n\nUn fichier `.html` de `/public/` est traduit dans la langue de la requête (`LOCALIZE()` est appelé pour lui) et mis en cache par langue. Les fichiers dont le nom contient `.min`, `-min` ou `@min` sont envoyés tels quels.\n\nExample: Une page statique\n```html\n<!-- /public/about.html -->\n<h1>@(About us)</h1>\n```\n\n### total5 translate [filename]\n\nType: `command`\n\nCrée un fichier de ressources avec tous les textes `@(...)` d'un projet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `translate.resource` | Le fichier de sortie. |\n\nLit tous les fichiers `.js` et `.html` du répertoire courant et de ses sous-dossiers, rassemble chaque texte `@(...)` et écrit des lignes `key : text` dans le fichier. Le fichier par défaut est `translate.resource` dans le répertoire courant. Copie le résultat dans `/resources/` sous le nom d'une langue et traduis les valeurs.\n\nExample: Créer un dictionnaire\n```bash\ncd my-app\ntotal5 translate resources/sk.resource\n```\n\nExample: Le résultat\n```text\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\n### errorbuilder.output([language])\n\nType: `method`\n\nRenvoie les erreurs traduites dans une langue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Le nom du dictionnaire. |\n\nReturns: `Array` Des objets avec `name`, `error`, `path` et `index`.\n\nUn message dans `@(...)` est traduit. Une erreur de champ issue de la validation d'un schéma est lue dans les ressources par le nom du champ ; sans cette clé, le message est `The field \"name\" is invalid`. Le framework l'appelle avec la langue de la requête lorsqu'il envoie les erreurs.\n\nExample: Traduire les erreurs\n```js\nvar err = new ErrorBuilder();\nerr.push('@(The name is required)');\nerr.output('sk'); // [{ error: 'Meno je povinné', ... }]\n```\n\n### errorbuilder.toString([language], [divider])\n\nType: `method`\n\nRenvoie les messages traduits en une seule chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Le nom du dictionnaire. |\n| `divider` | `String` | no | `'\\n'` | Le texte entre les messages. |\n\nReturns: `String`\n\nJoint les messages de `output(language)` avec le séparateur.\n\nExample: Une ligne\n```js\nvar text = err.toString('sk', ', ');\n```\n\n### {field} : message\n\nType: `type`\n\nMessages traduits pour les champs invalides.\n\nLorsqu'un champ échoue à la validation d'un schéma, le message est lu dans les ressources avec le nom du champ comme clé, dans la langue de la requête puis dans `default`. Sans cette clé, le message est `The field \"{name}\" is invalid`.\n\nExample: Messages pour les champs\n```text\n# /resources/default.resource\nemail : Enter a valid e-mail address\nname  : Enter your name\n```\n\n### MAIL(email, subject, view, model, [language], [callback])\n\nType: `method`\n\nEnvoie un e-mail rendu à partir d'une vue dans une langue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Le destinataire. |\n| `subject` | `String` | yes |  | Le sujet ; il peut contenir `@(...)`. |\n| `view` | `String` | yes |  | Le nom de la vue. |\n| `model` | `Object` | yes |  | Le modèle de la vue. |\n| `language` | `String` | no |  | La langue. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nAvec une langue, les textes `@(...)` du sujet sont traduits et la vue est rendue dans cette langue. Le callback peut aussi venir avant la langue. Le guide [Mail](../../guides/mail/) explique l'envoi.\n\nExample: Un e-mail localisé\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language);\n```\n\n### HTMLMAIL(email, subject, body, [language], [callback])\n\nType: `method`\n\nEnvoie du HTML comme e-mail, traduit dans une langue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Le destinataire. |\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\nAvec une langue, les textes `@(...)` du sujet et du corps sont traduits.\n\nExample: Corps traduit\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for your registration)</p>', 'sk');\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nRend un template traduit dans la langue de `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Le template, son nom de fichier ou une URL. |\n| `model` | `Object` | no |  | Le modèle. |\n| `$` | `Object` | no |  | Le contrôleur ou les options d'action avec la langue. |\n\nReturns: `Promise` Le HTML rendu.\n\nLorsque tu passes `$`, les textes `@(...)` du template sont traduits dans `$.language` avant la compilation du template, et le template compilé est mis en cache par langue.\n\nExample: Dans une action\n```js\nNEWACTION('Orders/print', {\n\tname: 'Print an order',\n\taction: async function($) {\n\t\tvar html = await TEMPLATE('invoice', { number: 'F001' }, $);\n\t\t$.callback(html);\n\t}\n});\n```\n\n### date.format(format, [dictionary])\n\nType: `method`\n\nFormate une date avec les noms des mois et des jours issus d'un dictionnaire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | yes |  | Le format, par exemple `dddd d. MMMM yyyy`. |\n| `dictionary` | `String` | no |  | Le nom du dictionnaire. |\n\nReturns: `String`\n\n`MMMM` et `MMM` affichent le nom du mois, `dddd` et `ddd` le nom du jour. Avec un dictionnaire, le nom anglais (`January`, `Monday`) est la clé ; sans traduction, le nom anglais est utilisé. `MMM` affiche les trois premiers caractères et `ddd` les deux premiers en majuscules.\n\nExample: Noms slovaques\n```js\n// sk.resource: January : január, Monday : pondelok\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // 'pondelok 1. január'\n```\n\n### AUTH({ localize: function(data, $) {} })\n\nType: `config`\n\nDéfinit la langue dans l'autorisation par session intégrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Les données de session, ou `null`. |\n| `$` | `Controller` | yes |  | Le contrôleur de la requête. |\n\nL'autorisation par session intégrée appelle `localize` (ou `locale`) avec les données de session et le contrôleur, et stocke le résultat dans `$.language`. Sans session, elle est appelée avec `null`. Le délégué `LOCALIZE()` n'est alors pas appelé. Le guide [Autorisation](../../guides/authorization/) explique les autres options.\n\nExample: Langue de l'utilisateur\n```js\nAUTH({\n\tcookie: 'session',\n\tlocalize: function(data, $) {\n\t\treturn data ? data.language : 'en';\n\t}\n\t// other options\n});\n```\n","entries":[{"type":"type","name":"Resource file","signature":"/resources/{name}.resource","since":"","deprecated":false},{"type":"type","name":"default.resource","signature":"/resources/default.resource","since":"","deprecated":false},{"type":"type","name":"Translation keys","signature":"'T' + text.hash(true).toString(36)","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, [text])","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE(url)","signature":"LOADRESOURCE(url)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE(language, text)","since":"","deprecated":false},{"type":"method","name":"F.resource()","signature":"F.resource(language, key)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocalize","signature":"DEF.onLocalize = function($) {}","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.language (action)","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"type","name":"Static HTML files","signature":"/public/*.html","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate [filename]","since":"","deprecated":false},{"type":"method","name":"errorbuilder.output()","signature":"errorbuilder.output([language])","since":"","deprecated":false},{"type":"method","name":"errorbuilder.toString()","signature":"errorbuilder.toString([language], [divider])","since":"","deprecated":false},{"type":"type","name":"Field error resources","signature":"{field} : message","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(email, subject, view, model, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(email, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"method","name":"date.format()","signature":"date.format(format, [dictionary])","since":"","deprecated":false},{"type":"config","name":"AUTH() localize option","signature":"AUTH({ localize: function(data, $) {} })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JaedDnAlT60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/localization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Localizzazione","summary":"File di risorse, testi @(...), TRANSLATE(), LOCALIZE(), LOADRESOURCE() e la lingua di una richiesta.","markdown":"---\ntitle: Localizzazione\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/localization/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Localizzazione\n\n> File di risorse, testi @(...), TRANSLATE(), LOCALIZE(), LOADRESOURCE() e la lingua di una richiesta.\n\nFunzioni, delegate e file della localizzazione: file di risorse, testi `@(...)`, `TRANSLATE()`, `LOCALIZE()`, la lingua di una richiesta e il comando `total5 translate`. 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 un dizionario di traduzioni.\n\nOgni file `.resource` in `/resources/` e nelle sue sottocartelle viene caricato all'avvio dell'applicazione. Il nome del file senza estensione è il nome del dizionario (`sk.resource` è `sk`). I percorsi che contengono `-bk` o `_bk` vengono saltati.\n\nOgni riga è `key : value`. Il separatore è il primo `:`, oppure il primo `=` quando la riga non contiene `:`; il valore inizia dal secondo carattere dopo il separatore, quindi lascia lì uno spazio. Chiavi e valori vengono privati degli spazi iniziali e finali. Le righe vuote e quelle che iniziano con `#` o `//` vengono ignorate. Le chiavi dei testi `@(...)` sono `T` e un hash del testo; le altre chiavi sono nomi qualsiasi che leggi con `F.resource()`.\n\nExample: sk.resource\n```text\n# Slovak\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\nname          : Meno\nJanuary       : január\n```\n\n### /resources/default.resource\n\nType: `type`\n\nIl dizionario di fallback.\n\nQuando una chiave manca nel dizionario della lingua, o la lingua non ha un dizionario, la chiave viene letta dal dizionario `default`. Una lingua vuota (il valore predefinito di una richiesta) legge direttamente `default`.\n\nExample: Fallback\n```js\n// /resources/default.resource contains: name : Name\nF.resource('de', 'name'); // 'Name' when de.resource has no \"name\"\n```\n\n### 'T' + text.hash(true).toString(36)\n\nType: `type`\n\nCome viene creata la chiave di un testo `@(...)`.\n\nLa chiave è `T` seguita dall'hash senza segno del testo dentro `@(...)` in base 36. Lo stesso testo ha sempre la stessa chiave, quindi lo stesso testo in molti punti richiede una sola traduzione. Cambiare il testo originale cambia la chiave. Il comando `total5 translate` crea le chiavi per te.\n\nExample: Calcolare una chiave\n```js\nvar key = 'T' + 'Welcome'.hash(true).toString(36); // 'T1bx8wg2'\n```\n\n### @(text)\n\nType: `command`\n\nContrassegna un testo da tradurre.\n\nIl testo viene sostituito dalla sua traduzione presa dal dizionario della lingua corrente, con fallback su `default`. Senza traduzione il testo viene stampato così com'è (senza `@(` e `)`). Le parentesi all'interno del testo devono essere bilanciate. Funziona nelle view, nei file `.html` statici, in `TRANSLATE()`, nei messaggi di errore, negli oggetti e nei corpi delle e-mail e nei template. Nelle view viene sostituito prima che la view venga compilata, quindi contiene solo testo semplice.\n\nExample: In una view\n```html\n<h1>@(Welcome)</h1>\n<p>@(Free delivery (over 50 EUR))</p>\n```\n\nExample: Nel codice\n```js\n$.invalid('@(The name is required)');\n```\n\n### LOADRESOURCE(name, [text])\n\nType: `method`\n\nAnalizza il testo di un file di risorse e lo salva come dizionario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del dizionario, di solito un codice di lingua. |\n| `text` | `String` | no |  | Il contenuto nel formato delle risorse. |\n\nIl testo ha il formato di un file `.resource`. Il dizionario sostituisce per intero un dizionario con lo stesso nome. È la stessa funzione di `F.loadresource()`.\n\nExample: Caricare un dizionario\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte\\nname : Meno');\n```\n\nExample: Da un tuo file\n```js\nLOADRESOURCE('de', F.Fs.readFileSync(PATH.root('lang/de.txt'), 'utf8'));\n```\n\n### LOADRESOURCE(url)\n\nType: `method`\n\nScarica dizionari da un URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL di una risposta JSON con dizionari. |\n\nSenza il secondo argomento il primo argomento è un URL. La risposta deve essere JSON. Un oggetto viene letto come `{ name: text }`, dove ogni testo è nel formato delle risorse. Un array viene letto come elementi con il nome in `id`, `key`, `code` o `language` e il testo in `value`, `name`, `text` o `body`. Ogni dizionario viene caricato con `LOADRESOURCE(name, text)`. Una richiesta fallita lancia un errore.\n\nExample: Dizionari remoti\n```js\n// response: { \"sk\": \"T1bx8wg2 : Vitajte\", \"de\": \"T1bx8wg2 : Willkommen\" }\nLOADRESOURCE('https://example.com/translations.json');\n```\n\n### TRANSLATE(language, text)\n\nType: `method`\n\nTraduce tutti i testi `@(...)` in una stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Il nome del dizionario. Una stringa vuota usa `default`. |\n| `text` | `String` | yes |  | Una stringa con testi `@(...)`. |\n\nReturns: `String` La stringa tradotta.\n\nOgni `@(...)` viene sostituito dalla sua traduzione presa dal dizionario della lingua, con fallback su `default`; un testo senza traduzione resta senza le parentesi. Il resto della stringa non cambia. È la stessa funzione di `F.translate()`.\n\nExample: Tradurre una stringa\n```js\nTRANSLATE('sk', '<b>@(Welcome)</b>, Peter'); // '<b>Vitajte</b>, Peter'\n```\n\nExample: In una route\n```js\nfunction detail($) {\n\t$.plain(TRANSLATE($.language, '@(Order) #' + $.params.id));\n}\n```\n\n### F.resource(language, key)\n\nType: `method`\n\nLegge una chiave di un dizionario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Il nome del dizionario. |\n| `key` | `String` | yes |  | La chiave. |\n\nReturns: `String` Il valore, oppure una stringa vuota quando la chiave non esiste.\n\nLegge la chiave dal dizionario della lingua, poi da `default`. Usala per chiavi con nomi tuoi, non per i testi `@(...)`.\n\nExample: Leggere una chiave\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n### F.resources\n\nType: `property`\n\nTutti i dizionari caricati.\n\nReturns: `Object`\n\nUn oggetto con i dizionari indicizzati per nome. Ogni dizionario è un oggetto semplice di chiavi e valori.\n\nExample: Elencare le lingue\n```js\nvar languages = Object.keys(F.resources); // ['default', 'sk', 'de']\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nRegistra il delegate che sceglie la lingua di una richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)` che restituisce la lingua come stringa. |\n\nLa funzione riceve il controller e restituisce la lingua (un nome di dizionario). Viene chiamata per le route dopo l'autorizzazione e prima del middleware, per i file `.html` statici e per le route WebSocket. Per le route HTTP e i file statici non viene chiamata quando la lingua è già impostata. Il risultato viene salvato in `$.language`. Imposta `DEF.onLocalize`.\n\nExample: Dalla query string o dal browser\n```js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nExample: Dall'utente\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\n### DEF.onLocalize = function($) {}\n\nType: `delegate`\n\nIl delegate che imposta `LOCALIZE()`.\n\n`LOCALIZE(fn)` salva qui la funzione. Puoi anche assegnarla direttamente; impostala a `null` per smettere di scegliere la lingua.\n\nExample: Assegnare direttamente\n```js\nDEF.onLocalize = function($) {\n\treturn $.cookie('language') || 'en';\n};\n```\n\n### $.language\n\nType: `property`\n\nLa lingua della richiesta.\n\nReturns: `String`\n\nUna stringa vuota per impostazione predefinita, oppure il valore restituito dal delegate di `LOCALIZE()`. In una route `$` è il controller e puoi assegnare una nuova lingua; una view prende la lingua quando chiami `$.view()`, quindi assegnala prima.\n\nExample: Impostare la lingua in una route\n```js\nexports.install = function() {\n\tROUTE('GET /sk/', index_sk);\n};\n\nfunction index_sk($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\n### $.language\n\nType: `property`\n\nLa lingua della richiesta che ha chiamato l'azione.\n\nReturns: `String`\n\nNelle azioni e negli schemi `$` è un oggetto di opzioni. `$.language` restituisce la lingua del suo controller, oppure una stringa vuota quando l'azione è stata chiamata senza una richiesta. È in sola lettura.\n\nExample: Tradurre in un'azione\n```js\nNEWACTION('Orders/read', {\n\tname: 'Read an order',\n\taction: function($) {\n\t\t$.callback({ title: TRANSLATE($.language, '@(Your order)') });\n\t}\n});\n```\n\n### view.language\n\nType: `property`\n\nLa lingua di una view.\n\nReturns: `String`\n\nUna view creata per una richiesta prende la lingua della richiesta. Per `F.view()` impostala nella funzione `prepare`. Le view vengono compilate e messe in cache per nome e lingua.\n\nExample: Renderizzare una view in tedesco\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{language}\n\nType: `command`\n\nStampa la lingua della view.\n\nStampa la lingua della richiesta (`$.language`) così com'è (una stringa vuota per impostazione predefinita, e sempre vuota in `F.view()`). La variabile `language` è disponibile in tutte le espressioni delle view.\n\nExample: Attributo HTML lang\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\n### /public/*.html\n\nType: `type`\n\nAnche i file HTML statici vengono tradotti.\n\nUn file `.html` di `/public/` viene tradotto nella lingua della richiesta (per esso viene chiamato `LOCALIZE()`) e messo in cache per lingua. I file il cui nome contiene `.min`, `-min` o `@min` vengono inviati così come sono.\n\nExample: Una pagina statica\n```html\n<!-- /public/about.html -->\n<h1>@(About us)</h1>\n```\n\n### total5 translate [filename]\n\nType: `command`\n\nCrea un file di risorse con tutti i testi `@(...)` di un progetto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `translate.resource` | Il file di output. |\n\nLegge tutti i file `.js` e `.html` nella directory corrente e nelle sue sottocartelle, raccoglie ogni testo `@(...)` e scrive righe `key : text` nel file. Il file predefinito è `translate.resource` nella directory corrente. Copia il risultato in `/resources/` con il nome di una lingua e traduci i valori.\n\nExample: Creare un dizionario\n```bash\ncd my-app\ntotal5 translate resources/sk.resource\n```\n\nExample: Il risultato\n```text\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\n### errorbuilder.output([language])\n\nType: `method`\n\nRestituisce gli errori tradotti in una lingua.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Il nome del dizionario. |\n\nReturns: `Array` Oggetti con `name`, `error`, `path` e `index`.\n\nUn messaggio in `@(...)` viene tradotto. Un errore di campo della validazione di uno schema viene letto dalle risorse in base al nome del campo; senza quella chiave il messaggio è `The field \"name\" is invalid`. Il framework la chiama con la lingua della richiesta quando invia gli errori.\n\nExample: Tradurre gli errori\n```js\nvar err = new ErrorBuilder();\nerr.push('@(The name is required)');\nerr.output('sk'); // [{ error: 'Meno je povinné', ... }]\n```\n\n### errorbuilder.toString([language], [divider])\n\nType: `method`\n\nRestituisce i messaggi tradotti come un'unica stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Il nome del dizionario. |\n| `divider` | `String` | no | `'\\n'` | Il testo tra i messaggi. |\n\nReturns: `String`\n\nUnisce i messaggi di `output(language)` con il separatore.\n\nExample: Una riga\n```js\nvar text = err.toString('sk', ', ');\n```\n\n### {field} : message\n\nType: `type`\n\nMessaggi tradotti per i campi non validi.\n\nQuando un campo non supera la validazione di uno schema, il messaggio viene letto dalle risorse con il nome del campo come chiave, nella lingua della richiesta e poi in `default`. Senza quella chiave il messaggio è `The field \"{name}\" is invalid`.\n\nExample: Messaggi per i campi\n```text\n# /resources/default.resource\nemail : Enter a valid e-mail address\nname  : Enter your name\n```\n\n### MAIL(email, subject, view, model, [language], [callback])\n\nType: `method`\n\nInvia un'e-mail renderizzata da una view in una lingua.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Il destinatario. |\n| `subject` | `String` | yes |  | L'oggetto; può contenere `@(...)`. |\n| `view` | `String` | yes |  | Il nome della view. |\n| `model` | `Object` | yes |  | Il modello della view. |\n| `language` | `String` | no |  | La lingua. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nCon una lingua, i testi `@(...)` nell'oggetto vengono tradotti e la view viene renderizzata in quella lingua. La callback può anche precedere la lingua. La guida [Mail](../../guides/mail/) spiega l'invio.\n\nExample: Un'e-mail localizzata\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language);\n```\n\n### HTMLMAIL(email, subject, body, [language], [callback])\n\nType: `method`\n\nInvia HTML come e-mail, tradotto in una lingua.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Il destinatario. |\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\nCon una lingua, i testi `@(...)` nell'oggetto e nel corpo vengono tradotti.\n\nExample: Corpo tradotto\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for your registration)</p>', 'sk');\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nRenderizza un template tradotto nella lingua di `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Il template, il nome del suo file o un URL. |\n| `model` | `Object` | no |  | Il modello. |\n| `$` | `Object` | no |  | Il controller o le opzioni dell'azione con la lingua. |\n\nReturns: `Promise` L'HTML renderizzato.\n\nQuando passi `$`, i testi `@(...)` nel template vengono tradotti in `$.language` prima che il template venga compilato, e il template compilato viene messo in cache per lingua.\n\nExample: In un'azione\n```js\nNEWACTION('Orders/print', {\n\tname: 'Print an order',\n\taction: async function($) {\n\t\tvar html = await TEMPLATE('invoice', { number: 'F001' }, $);\n\t\t$.callback(html);\n\t}\n});\n```\n\n### date.format(format, [dictionary])\n\nType: `method`\n\nFormatta una data con i nomi dei mesi e dei giorni presi da un dizionario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | yes |  | Il formato, per esempio `dddd d. MMMM yyyy`. |\n| `dictionary` | `String` | no |  | Il nome del dizionario. |\n\nReturns: `String`\n\n`MMMM` e `MMM` stampano il nome del mese, `dddd` e `ddd` il nome del giorno. Con un dizionario, il nome inglese (`January`, `Monday`) è la chiave; senza traduzione viene usato il nome inglese. `MMM` stampa i primi tre caratteri e `ddd` i primi due in maiuscolo.\n\nExample: Nomi in slovacco\n```js\n// sk.resource: January : január, Monday : pondelok\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // 'pondelok 1. január'\n```\n\n### AUTH({ localize: function(data, $) {} })\n\nType: `config`\n\nImposta la lingua nell'autorizzazione di sessione integrata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | I dati della sessione, oppure `null`. |\n| `$` | `Controller` | yes |  | Il controller della richiesta. |\n\nL'autorizzazione di sessione integrata chiama `localize` (o `locale`) con i dati della sessione e il controller e salva il risultato in `$.language`. Senza sessione viene chiamata con `null`. Il delegate di `LOCALIZE()` in questo caso non viene chiamato. La guida [Autorizzazione](../../guides/authorization/) spiega le altre opzioni.\n\nExample: Lingua dell'utente\n```js\nAUTH({\n\tcookie: 'session',\n\tlocalize: function(data, $) {\n\t\treturn data ? data.language : 'en';\n\t}\n\t// other options\n});\n```\n","entries":[{"type":"type","name":"Resource file","signature":"/resources/{name}.resource","since":"","deprecated":false},{"type":"type","name":"default.resource","signature":"/resources/default.resource","since":"","deprecated":false},{"type":"type","name":"Translation keys","signature":"'T' + text.hash(true).toString(36)","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, [text])","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE(url)","signature":"LOADRESOURCE(url)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE(language, text)","since":"","deprecated":false},{"type":"method","name":"F.resource()","signature":"F.resource(language, key)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocalize","signature":"DEF.onLocalize = function($) {}","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.language (action)","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"type","name":"Static HTML files","signature":"/public/*.html","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate [filename]","since":"","deprecated":false},{"type":"method","name":"errorbuilder.output()","signature":"errorbuilder.output([language])","since":"","deprecated":false},{"type":"method","name":"errorbuilder.toString()","signature":"errorbuilder.toString([language], [divider])","since":"","deprecated":false},{"type":"type","name":"Field error resources","signature":"{field} : message","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(email, subject, view, model, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(email, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"method","name":"date.format()","signature":"date.format(format, [dictionary])","since":"","deprecated":false},{"type":"config","name":"AUTH() localize option","signature":"AUTH({ localize: function(data, $) {} })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JaedDnAlT60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/localization/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Lokalizácia","summary":"Resource súbory, texty @(...), TRANSLATE(), LOCALIZE(), LOADRESOURCE() a jazyk požiadavky.","markdown":"---\ntitle: \"Lokalizácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/localization/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# Lokalizácia\n\n> Resource súbory, texty @(...), TRANSLATE(), LOCALIZE(), LOADRESOURCE() a jazyk požiadavky.\n\nFunkcie, delegáti a súbory lokalizácie: resource súbory, texty `@(...)`, `TRANSLATE()`, `LOCALIZE()`, jazyk požiadavky a príkaz `total5 translate`. Návod [Lokalizácia](../../guides/localization/) s príkladmi vysvetľuje, ako spolu fungujú; táto stránka je presná referencia.\n\n## API\n\n### /resources/{name}.resource\n\nType: `type`\n\nTextový súbor so slovníkom prekladov.\n\nKaždý súbor `.resource` v `/resources/` a jeho podpriečinkoch sa načíta pri štarte aplikácie. Názov súboru bez prípony je názov slovníka (`sk.resource` je `sk`). Cesty, ktoré obsahujú `-bk` alebo `_bk`, sa preskočia.\n\nKaždý riadok má tvar `key : value`. Oddeľovač je prvá `:`, alebo prvé `=`, keď riadok nemá `:`; hodnota začína druhým znakom za oddeľovačom, preto tam nechaj jednu medzeru. Kľúče aj hodnoty sa orežú. Prázdne riadky a riadky, ktoré začínajú na `#` alebo `//`, sa ignorujú. Kľúče textov `@(...)` sú `T` a hash textu; ostatné kľúče sú ľubovoľné názvy, ktoré čítaš cez `F.resource()`.\n\nExample: sk.resource\n```text\n# Slovak\nT1bx8wg2      : Vitajte\nT1oapati      : Pridať do košíka\nname          : Meno\nJanuary       : január\n```\n\n### /resources/default.resource\n\nType: `type`\n\nZáložný slovník.\n\nKeď kľúč v slovníku jazyka chýba alebo jazyk nemá žiadny slovník, kľúč sa prečíta zo slovníka `default`. Prázdny jazyk (predvolený pre požiadavku) číta priamo `default`.\n\nExample: Záloha\n```js\n// /resources/default.resource contains: name : Name\nF.resource('de', 'name'); // 'Name' when de.resource has no \"name\"\n```\n\n### 'T' + text.hash(true).toString(36)\n\nType: `type`\n\nAko vzniká kľúč textu `@(...)`.\n\nKľúč je `T` nasledované bezznamienkovým hashom textu vnútri `@(...)` v sústave so základom 36. Rovnaký text má vždy rovnaký kľúč, takže rovnaký text na mnohých miestach potrebuje jeden preklad. Zmena pôvodného textu zmení kľúč. Kľúče za teba vytvorí príkaz `total5 translate`.\n\nExample: Výpočet kľúča\n```js\nvar key = 'T' + 'Welcome'.hash(true).toString(36); // 'T1bx8wg2'\n```\n\n### @(text)\n\nType: `command`\n\nOznačí text na preklad.\n\nText sa nahradí prekladom zo slovníka aktuálneho jazyka, so zálohou na `default`. Bez prekladu sa text vypíše tak, ako je (bez `@(` a `)`). Zátvorky vnútri textu musia byť vyvážené. Funguje vo views, statických súboroch `.html`, `TRANSLATE()`, chybových hláseniach, predmetoch a telách e-mailov a v šablónach. Vo views sa nahrádza pred kompiláciou view, takže obsahuje iba obyčajný text.\n\nExample: Vo view\n```html\n<h1>@(Welcome)</h1>\n<p>@(Free delivery (over 50 EUR))</p>\n```\n\nExample: V kóde\n```js\n$.invalid('@(The name is required)');\n```\n\n### LOADRESOURCE(name, [text])\n\nType: `method`\n\nSpracuje text resource súboru a uloží ho ako slovník.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov slovníka, zvyčajne kód jazyka. |\n| `text` | `String` | no |  | Obsah vo formáte resource. |\n\nText má formát súboru `.resource`. Slovník nahradí celý slovník s rovnakým názvom. Je to tá istá funkcia ako `F.loadresource()`.\n\nExample: Načítanie slovníka\n```js\nLOADRESOURCE('sk', 'T1bx8wg2 : Vitajte\\nname : Meno');\n```\n\nExample: Z vlastného súboru\n```js\nLOADRESOURCE('de', F.Fs.readFileSync(PATH.root('lang/de.txt'), 'utf8'));\n```\n\n### LOADRESOURCE(url)\n\nType: `method`\n\nStiahne slovníky z URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL JSON odpovede so slovníkmi. |\n\nBez druhého argumentu je prvý argument URL. Odpoveď musí byť JSON. Objekt sa číta ako `{ name: text }`, kde každý text je vo formáte resource. Pole sa číta ako položky s názvom v `id`, `key`, `code` alebo `language` a textom vo `value`, `name`, `text` alebo `body`. Každý slovník sa načíta cez `LOADRESOURCE(name, text)`. Neúspešná požiadavka vyhodí chybu.\n\nExample: Vzdialené slovníky\n```js\n// response: { \"sk\": \"T1bx8wg2 : Vitajte\", \"de\": \"T1bx8wg2 : Willkommen\" }\nLOADRESOURCE('https://example.com/translations.json');\n```\n\n### TRANSLATE(language, text)\n\nType: `method`\n\nPreloží všetky texty `@(...)` v reťazci.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Názov slovníka. Prázdny reťazec použije `default`. |\n| `text` | `String` | yes |  | Reťazec s textami `@(...)`. |\n\nReturns: `String` Preložený reťazec.\n\nKaždé `@(...)` sa nahradí prekladom zo slovníka jazyka, so zálohou na `default`; text bez prekladu zostane bez zátvoriek. Zvyšok reťazca sa nemení. Je to tá istá funkcia ako `F.translate()`.\n\nExample: Preklad reťazca\n```js\nTRANSLATE('sk', '<b>@(Welcome)</b>, Peter'); // '<b>Vitajte</b>, Peter'\n```\n\nExample: V route\n```js\nfunction detail($) {\n\t$.plain(TRANSLATE($.language, '@(Order) #' + $.params.id));\n}\n```\n\n### F.resource(language, key)\n\nType: `method`\n\nPrečíta jeden kľúč slovníka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Názov slovníka. |\n| `key` | `String` | yes |  | Kľúč. |\n\nReturns: `String` Hodnota, alebo prázdny reťazec, keď kľúč neexistuje.\n\nPrečíta kľúč zo slovníka jazyka, potom z `default`. Používaj ho pre kľúče s vlastnými názvami, nie pre texty `@(...)`.\n\nExample: Čítanie kľúča\n```js\n// /resources/de.resource contains: currency : EUR\nvar currency = F.resource('de', 'currency') || 'USD';\n```\n\n### F.resources\n\nType: `property`\n\nVšetky načítané slovníky.\n\nReturns: `Object`\n\nObjekt so slovníkmi podľa ich názvov. Každý slovník je obyčajný objekt kľúčov a hodnôt.\n\nExample: Zoznam jazykov\n```js\nvar languages = Object.keys(F.resources); // ['default', 'sk', 'de']\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nZaregistruje delegáta, ktorý vyberá jazyk požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($)`, ktorá vráti jazyk ako reťazec. |\n\nFunkcia dostane kontrolér a vráti jazyk (názov slovníka). Volá sa pre routy po autorizácii a pred middleware, pre statické súbory `.html` a pre WebSocket routy. Pri HTTP routách a statických súboroch sa nevolá, keď je jazyk už nastavený. Výsledok sa uloží do `$.language`. Nastavuje `DEF.onLocalize`.\n\nExample: Z query stringu alebo z prehliadača\n```js\nLOCALIZE(function($) {\n\tvar language = $.query.language || ($.headers['accept-language'] || '').substring(0, 2).toLowerCase();\n\treturn language === 'sk' || language === 'de' ? language : 'en';\n});\n```\n\nExample: Od používateľa\n```js\nLOCALIZE(function($) {\n\treturn $.user ? $.user.language : 'en';\n});\n```\n\n### DEF.onLocalize = function($) {}\n\nType: `delegate`\n\nDelegát, ktorého nastavuje `LOCALIZE()`.\n\n`LOCALIZE(fn)` sem uloží funkciu. Môžeš ju priradiť aj priamo; nastav ju na `null`, ak chceš výber jazyka zastaviť.\n\nExample: Priame priradenie\n```js\nDEF.onLocalize = function($) {\n\treturn $.cookie('language') || 'en';\n};\n```\n\n### $.language\n\nType: `property`\n\nJazyk požiadavky.\n\nReturns: `String`\n\nPredvolene prázdny reťazec, alebo hodnota, ktorú vrátil delegát `LOCALIZE()`. V route je `$` kontrolér a môžeš priradiť nový jazyk; view preberá jazyk, keď zavoláš `$.view()`, preto ho priraď predtým.\n\nExample: Nastavenie jazyka v route\n```js\nexports.install = function() {\n\tROUTE('GET /sk/', index_sk);\n};\n\nfunction index_sk($) {\n\t$.language = 'sk';\n\t$.view('index');\n}\n```\n\n### $.language\n\nType: `property`\n\nJazyk požiadavky, ktorá zavolala akciu.\n\nReturns: `String`\n\nV akciách a schémach je `$` objekt volieb. `$.language` vracia jazyk jeho kontroléra, alebo prázdny reťazec, keď bola akcia zavolaná bez požiadavky. Je iba na čítanie.\n\nExample: Preklad v akcii\n```js\nNEWACTION('Orders/read', {\n\tname: 'Read an order',\n\taction: function($) {\n\t\t$.callback({ title: TRANSLATE($.language, '@(Your order)') });\n\t}\n});\n```\n\n### view.language\n\nType: `property`\n\nJazyk view.\n\nReturns: `String`\n\nView vytvorené pre požiadavku preberá jazyk požiadavky. Pri `F.view()` ho nastav vo funkcii `prepare`. Views sa kompilujú a cachujú podľa názvu a jazyka.\n\nExample: Vyrenderovanie view v nemčine\n```js\nvar html = F.view('mail/order', { id: 'A100' }, function(view) {\n\tview.language = 'de';\n});\n```\n\n### @{language}\n\nType: `command`\n\nVypíše jazyk view.\n\nVypíše jazyk požiadavky (`$.language`) tak, ako je (predvolene prázdny reťazec a v `F.view()` vždy prázdny). Premenná `language` je dostupná vo všetkých výrazoch view.\n\nExample: HTML atribút lang\n```html\n<html lang=\"@{language || 'en'}\">\n```\n\n### /public/*.html\n\nType: `type`\n\nPrekladajú sa aj statické HTML súbory.\n\nSúbor `.html` z `/public/` sa preloží do jazyka požiadavky (volá sa preň `LOCALIZE()`) a cachuje sa pre každý jazyk. Súbory, ktorých názov obsahuje `.min`, `-min` alebo `@min`, sa posielajú tak, ako sú.\n\nExample: Statická stránka\n```html\n<!-- /public/about.html -->\n<h1>@(About us)</h1>\n```\n\n### total5 translate [filename]\n\nType: `command`\n\nVytvorí resource súbor so všetkými textami `@(...)` projektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `translate.resource` | Výstupný súbor. |\n\nPrečíta všetky súbory `.js` a `.html` v aktuálnom priečinku a jeho podpriečinkoch, zozbiera každý text `@(...)` a zapíše do súboru riadky `key : text`. Predvolený súbor je `translate.resource` v aktuálnom priečinku. Výsledok skopíruj do `/resources/` pod názvom jazyka a prelož hodnoty.\n\nExample: Vytvorenie slovníka\n```bash\ncd my-app\ntotal5 translate resources/sk.resource\n```\n\nExample: Výsledok\n```text\nT1bx8wg2     : Welcome\nT1oapati     : Add to cart\n```\n\n### errorbuilder.output([language])\n\nType: `method`\n\nVráti chyby preložené do jazyka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Názov slovníka. |\n\nReturns: `Array` Objekty s `name`, `error`, `path` a `index`.\n\nHlásenie v `@(...)` sa preloží. Chyba poľa z validácie schémy sa prečíta z resources podľa názvu poľa; bez tohto kľúča je hlásenie `The field \"name\" is invalid`. Framework ju volá s jazykom požiadavky, keď posiela chyby.\n\nExample: Preklad chýb\n```js\nvar err = new ErrorBuilder();\nerr.push('@(The name is required)');\nerr.output('sk'); // [{ error: 'Meno je povinné', ... }]\n```\n\n### errorbuilder.toString([language], [divider])\n\nType: `method`\n\nVráti preložené hlásenia ako jeden reťazec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `'default'` | Názov slovníka. |\n| `divider` | `String` | no | `'\\n'` | Text medzi hláseniami. |\n\nReturns: `String`\n\nSpojí hlásenia z `output(language)` oddeľovačom.\n\nExample: Jeden riadok\n```js\nvar text = err.toString('sk', ', ');\n```\n\n### {field} : message\n\nType: `type`\n\nPreložené hlásenia pre neplatné polia.\n\nKeď pole neprejde validáciou schémy, hlásenie sa prečíta z resources s názvom poľa ako kľúčom, v jazyku požiadavky a potom v `default`. Bez tohto kľúča je hlásenie `The field \"{name}\" is invalid`.\n\nExample: Hlásenia pre polia\n```text\n# /resources/default.resource\nemail : Enter a valid e-mail address\nname  : Enter your name\n```\n\n### MAIL(email, subject, view, model, [language], [callback])\n\nType: `method`\n\nPošle e-mail vyrenderovaný z view v danom jazyku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Príjemca. |\n| `subject` | `String` | yes |  | Predmet; môže obsahovať `@(...)`. |\n| `view` | `String` | yes |  | Názov view. |\n| `model` | `Object` | yes |  | Model view. |\n| `language` | `String` | no |  | Jazyk. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nS jazykom sa preložia texty `@(...)` v predmete a view sa vyrenderuje s týmto jazykom. Callback môže byť aj pred jazykom. Posielanie vysvetľuje návod [Mail](../../guides/mail/).\n\nExample: Lokalizovaný e-mail\n```js\nMAIL(user.email, '@(Your order)', 'mail/order', order, user.language);\n```\n\n### HTMLMAIL(email, subject, body, [language], [callback])\n\nType: `method`\n\nPošle HTML ako e-mail preložený do daného jazyka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Príjemca. |\n| `subject` | `String` | yes |  | Predmet. |\n| `body` | `String` | yes |  | HTML telo. |\n| `language` | `String` | no |  | Jazyk. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nS jazykom sa preložia texty `@(...)` v predmete aj v tele.\n\nExample: Preložené telo\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for your registration)</p>', 'sk');\n```\n\n### TEMPLATE(body, [model], [$])\n\nType: `method`\n\nVyrenderuje šablónu preloženú do jazyka `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Šablóna, názov jej súboru alebo URL. |\n| `model` | `Object` | no |  | Model. |\n| `$` | `Object` | no |  | Kontrolér alebo voľby akcie s jazykom. |\n\nReturns: `Promise` Vyrenderované HTML.\n\nKeď odovzdáš `$`, texty `@(...)` v šablóne sa pred kompiláciou šablóny preložia do `$.language` a skompilovaná šablóna sa cachuje pre každý jazyk.\n\nExample: V akcii\n```js\nNEWACTION('Orders/print', {\n\tname: 'Print an order',\n\taction: async function($) {\n\t\tvar html = await TEMPLATE('invoice', { number: 'F001' }, $);\n\t\t$.callback(html);\n\t}\n});\n```\n\n### date.format(format, [dictionary])\n\nType: `method`\n\nNaformátuje dátum s názvami mesiacov a dní zo slovníka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | yes |  | Formát, napríklad `dddd d. MMMM yyyy`. |\n| `dictionary` | `String` | no |  | Názov slovníka. |\n\nReturns: `String`\n\n`MMMM` a `MMM` vypíšu názov mesiaca, `dddd` a `ddd` názov dňa. So slovníkom je kľúčom anglický názov (`January`, `Monday`); bez prekladu sa použije anglický názov. `MMM` vypíše prvé tri znaky a `ddd` prvé dva veľkými písmenami.\n\nExample: Slovenské názvy\n```js\n// sk.resource: January : január, Monday : pondelok\nnew Date(2024, 0, 1).format('dddd d. MMMM', 'sk'); // 'pondelok 1. január'\n```\n\n### AUTH({ localize: function(data, $) {} })\n\nType: `config`\n\nNastaví jazyk vo vstavanej session autorizácii.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Dáta session, alebo `null`. |\n| `$` | `Controller` | yes |  | Kontrolér požiadavky. |\n\nVstavaná session autorizácia zavolá `localize` (alebo `locale`) s dátami session a kontrolérom a výsledok uloží do `$.language`. Bez session sa volá s `null`. Delegát `LOCALIZE()` sa potom nevolá. Ostatné voľby vysvetľuje návod [Autorizácia](../../guides/authorization/).\n\nExample: Jazyk používateľa\n```js\nAUTH({\n\tcookie: 'session',\n\tlocalize: function(data, $) {\n\t\treturn data ? data.language : 'en';\n\t}\n\t// other options\n});\n```\n","entries":[{"type":"type","name":"Resource file","signature":"/resources/{name}.resource","since":"","deprecated":false},{"type":"type","name":"default.resource","signature":"/resources/default.resource","since":"","deprecated":false},{"type":"type","name":"Translation keys","signature":"'T' + text.hash(true).toString(36)","since":"","deprecated":false},{"type":"command","name":"@(text)","signature":"@(text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, [text])","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE(url)","signature":"LOADRESOURCE(url)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE(language, text)","since":"","deprecated":false},{"type":"method","name":"F.resource()","signature":"F.resource(language, key)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocalize","signature":"DEF.onLocalize = function($) {}","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"$.language (action)","signature":"$.language","since":"","deprecated":false},{"type":"property","name":"view.language","signature":"view.language","since":"","deprecated":false},{"type":"command","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"type","name":"Static HTML files","signature":"/public/*.html","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate [filename]","since":"","deprecated":false},{"type":"method","name":"errorbuilder.output()","signature":"errorbuilder.output([language])","since":"","deprecated":false},{"type":"method","name":"errorbuilder.toString()","signature":"errorbuilder.toString([language], [divider])","since":"","deprecated":false},{"type":"type","name":"Field error resources","signature":"{field} : message","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(email, subject, view, model, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(email, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"TEMPLATE()","signature":"TEMPLATE(body, [model], [$])","since":"","deprecated":false},{"type":"method","name":"date.format()","signature":"date.format(format, [dictionary])","since":"","deprecated":false},{"type":"config","name":"AUTH() localize option","signature":"AUTH({ localize: function(data, $) {} })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafwtJ1cx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/http-requests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"HTTP requests","summary":"RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() and Total.download().","markdown":"---\ntitle: HTTP requests\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/http-requests/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# HTTP requests\n\n> RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() and Total.download().\n\nThe global functions and the `RESTBuilder` class for HTTP requests to other services. For an introduction with examples read the guide [HTTP requests](../../guides/http-requests/). The WebSocket client `OPENCLIENT()` has its own page: [OpenClient](../openclient/).\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nSends an HTTP request with full control of the options.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.url` | `String` | yes |  | The URL of the request. Credentials in the URL (`https://user:password@host/`) are sent as `Authorization: Basic`; percent-encoded characters in them are decoded first. |\n| `options.method` | `String` | no | `'GET'` | The HTTP method in upper case. |\n| `options.headers` | `Object` | no |  | Request headers. The object is copied, so your object is not changed. |\n| `options.type` | `String` | no |  | Sets `Content-Type`: `'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'` or `'text'`, `'raw'` (`application/octet-stream`). |\n| `options.body` | `String|Buffer` | no |  | The request body. A string is sent as UTF-8; `Content-Length` is set for you. |\n| `options.query` | `Object|String` | no |  | Appended to the URL as a query string. |\n| `options.cookies` | `Object` | no |  | Cookies to send, as `{ name: value }`. |\n| `options.cook` | `Boolean` | no |  | Stores the cookies of the response into `options.cookies`, so the same options object sends them with the next request. |\n| `options.timeout` | `Number` | no | `8000` | Timeout in milliseconds; `0` disables it. |\n| `options.encoding` | `String` | no | `'utf8'` | Encoding of a text body. `'binary'` returns a `Buffer`. |\n| `options.xhr` | `Boolean` | no |  | Adds `X-Requested-With: XMLHttpRequest`. |\n| `options.files` | `Array` | no |  | Files for a `multipart/form-data` request: `[{ name, filename, buffer \\| path \\| url }]`. `options.body` is then an object of extra form fields. |\n| `options.compress` | `String` | no |  | Compresses the body: `'gzip'` or `'deflate'`, and sets `Content-Encoding`. |\n| `options.encrypt` | `String` | no |  | A key: the body is encrypted with it and the text response is decrypted with it. |\n| `options.writer` | `Function` | no |  | `function(req)` writes the body itself: it gets the Node.js request, writes the data and calls `req.end()`. `body` and `files` are then not used. |\n| `options.custom` | `Boolean` | no |  | Returns `response.stream` instead of reading the body. |\n| `options.noredirect` | `Boolean` | no |  | Does not follow redirects; the callback gets the `301`/`302` response. |\n| `options.keepalive` | `Boolean` | no |  | Uses a shared keep-alive agent (one for HTTP, one for HTTPS). |\n| `options.resolve` | `Boolean` | no |  | Resolves the hostname with a DNS cache. `options.dnscache` does the same. Skipped for `localhost` and IP addresses. |\n| `options.proxy` | `String` | no |  | A proxy for this request, as `'host:port'` or `'http://host:port'`. With `http://user:password@host:port` the credentials are sent as `Proxy-Authorization: Basic`. |\n| `options.insecure` | `Boolean` | no |  | Accepts invalid or self-signed TLS certificates. |\n| `options.key` | `Buffer` | no |  | Client TLS key. |\n| `options.cert` | `Buffer` | no |  | Client TLS certificate. |\n| `options.dhparam` | `Buffer` | no |  | TLS Diffie-Hellman parameters. |\n| `options.unixsocket` | `Object` | no |  | `{ socket, path }` to send the request through a Unix socket instead of `url`. |\n| `options.ondata` | `Function` | no |  | `function(chunk, percentage)` for every received chunk. |\n| `options.onprogress` | `Function` | no |  | `function(percentage)`; the percentage is known only with `Content-Length`. |\n| `options.callback` | `Function` | no |  | `function(err, response)`, instead of the second argument. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` A promise when no callback is given; otherwise nothing.\n\nSends one HTTP request described by `options`. The callback receives `(err, response)`; without a callback (in the argument or in `options.callback`) it returns a promise that resolves with `response`.\n\nThe response object has `status`, `headers`, `body`, `host`, `origin` (the resolved IP addresses when DNS caching is on) and `cookies` (the cookies collected on redirects). `body` is a string for `text/*` and `application/*` types (decoded with `encoding`) and a `Buffer` for the other types, or always a `Buffer` with `encoding: 'binary'`. The body is not parsed: use `RESTBuilder` or `AJAX()` for that.\n\nWith `custom: true` the callback runs as soon as the headers arrive and the response has `stream` (the Node.js response) instead of `body`.\n\nErrors: a network error passes the error object with `response.status === 0`; an expired timeout passes `'408: Request Timeout'` with `response.status === 408`; more than four redirects pass `'Too many redirects'`; a URL without a hostname passes `'Invalid hostname'`, and a string that is not a URL throws `TypeError: Invalid URL`. A status code of `400` or more is not an error: check `response.status`.\n\nRedirects `301` and `302` are followed (cookies of the redirect are sent to the next location). Requests use the proxy of the configuration key `$proxyrequest` when it is set, except for `localhost`, `127.0.0.1` and `0.0.0.0`.\n\nExample: POST JSON\n```js\nREQUEST({\n\turl: 'https://api.example.com/orders/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ id: 'p100', count: 2 })\n}, function(err, response) {\n\tif (err || response.status !== 200)\n\t\treturn;\n\tvar order = response.body.parseJSON();\n});\n```\n\nExample: With a promise\n```js\nvar response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });\nconsole.log(response.status, response.body);\n```\n\nExample: Upload a file\n```js\nREQUEST({\n\turl: 'https://files.example.com/upload/',\n\tmethod: 'POST',\n\tfiles: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],\n\tbody: { folder: 'reports' }\n}, console.log);\n```\n\nExample: Read a stream\n```js\nREQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));\n});\n```\n\nExample: Write the body yourself\n```js\nREQUEST({\n\turl: 'https://api.example.com/import/',\n\tmethod: 'POST',\n\ttype: 'plain',\n\twriter: function(req) {\n\t\tfor (var line of lines)\n\t\t\treq.write(line + '\\n');\n\t\treq.end();\n\t}\n}, console.log);\n```\n\n### AJAX('METHOD url', [data], [callback])\n\nType: `method`\n\nSends a JSON request and returns the parsed response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `'METHOD url'`, for example `'POST https://example.com/api/'`. |\n| `data` | `Object` | no |  | Data sent as JSON. |\n| `callback` | `Function` | no |  | `function(err, response, meta)`. |\n\nReturns: `Promise` A promise when no callback is given.\n\nSends a request and parses the response. The first argument is the method and the URL separated by a space; without a method it is `GET`. `data` is sent as a JSON body. The header `X-Requested-With: XMLHttpRequest` is always added.\n\nThe response is parsed by its `Content-Type`: JSON (`application/json`, `text/json`), URL-encoded data and XML (`application/xml`, `text/xml`) become objects; other types are returned as the raw body. An XML document becomes a flat object: the names of nested elements are joined with `_` (`order_name`), repeated elements give an array, and the attributes of an element are in an object under its name with `__` (`order__`). An empty XML body gives `{}`. The callback receives `(err, response, meta)` where `meta` has `status`, `headers` and `host`.\n\nFor a status of `400` or more `err` is the parsed body (for a Total.js service the error array) and `response` is `null`. Without a callback the function returns a promise that resolves with the parsed body and rejects with `err`; a Total.js error array becomes an `Error` whose message holds the error messages.\n\nExample: Callback\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {\n\tconsole.log(meta.status, response);\n});\n```\n\nExample: Promise\n```js\nvar products = await AJAX('GET https://api.example.com/products/?page=1');\n```\n\nExample: XML answer\n```js\n// the service answers <order id=\"100\"><name>Book</name><items><item>A</item><item>B</item></items></order>\nvar order = await AJAX('GET https://api.example.com/orders/100/');\n// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nDownloads a remote file to the disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | The URL, or `{ socket, path }` for a Unix socket. |\n| `filename` | `String` | yes |  | The target file path. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout in milliseconds. |\n\nReturns: `Promise` A promise when no callback is given.\n\nDownloads `url` and writes the body to `filename`. The callback runs when the file is written, with `(err, response)`. `response` has `status`, `headers`, `origin`, `filename` and `size` (the number of bytes written). The body is saved for every status code, so check `response.status`.\n\n`url` can also be an object `{ socket, path }` for a Unix socket. DNS lookups are cached. `timeout` is in milliseconds (8 seconds when not set). Without a callback the function returns a promise that resolves with `response`.\n\nExample: Download an image\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.filename);\n});\n```\n\nExample: Promise\n```js\nvar response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));\n```\n\n### Total.download(url, filename, [callback], [timeout])\n\nType: `method`\n\nThe framework method behind DOWNLOAD().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | The URL, or `{ socket, path }` for a Unix socket. |\n| `filename` | `String` | yes |  | The target file path. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout in milliseconds. |\n\nReturns: `Promise` A promise when no callback is given.\n\nThe same function as `DOWNLOAD()`. Downloads `url` and writes the body to `filename`. The callback runs when the file is written, with `(err, response)`. `response` has `status`, `headers`, `origin`, `filename` and `size` (the number of bytes written). The body is saved for every status code, so check `response.status`.\n\n`url` can also be an object `{ socket, path }` for a Unix socket. DNS lookups are cached. `timeout` is in milliseconds (8 seconds when not set). Without a callback the function returns a promise that resolves with `response`.\n\nExample: Download\n```js\nTotal.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n### new RESTBuilder([url])\n\nType: `class`\n\nA builder for requests to REST services.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | The URL of the request. |\n\nReturns: `RESTBuilder` A new builder.\n\nA global class. A new builder has the method `GET`, a timeout of 10 seconds, DNS caching on, the header `user-agent: Total.js/v...` and `accept: application/json, text/plain, text/plain, text/xml`. Nothing is sent until you call `callback()`, `promise()`, `stream()` or `exec()`.\n\nYou usually start with a static helper: `RESTBuilder.GET()`, `POST()`, `PUT()`, `PATCH()`, `DELETE()`, `HEAD()`, `API()`, `url()` or `make()`. `RESTBuilder.url(url)` is the same as `new RESTBuilder(url)`.\n\nExample: Create a builder\n```js\nvar builder = RESTBuilder.url('https://api.example.com/users/');\nbuilder.header('X-Token', CONF.apitoken);\nbuilder.callback(console.log);\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nCreates a 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\nCreates a builder without a URL and calls `fn(builder)`. Set the URL with `builder.url()`. The instance method `builder.make(fn)` calls `fn` with the builder as `this` and as the argument, for reusable settings.\n\nExample: Build a request\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.post({ name: 'Peter' });\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nCreates a GET request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL. |\n| `data` | `Object` | no |  | Sent as the query string. |\n\nReturns: `RESTBuilder` A new builder.\n\nCreates a builder with the method `GET`; `data` becomes the query string. For a `HEAD` request use `RESTBuilder.HEAD(url)`: it has no data, the parsed value is an empty object and you read `output.status` and `output.headers`.\n\nExample: Query string\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nExample: HEAD\n```js\nRESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers['last-modified']);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nCreates a POST request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL. |\n| `data` | `Object` | no |  | Sent as a JSON body. |\n\nReturns: `RESTBuilder` A new builder.\n\nCreates a builder with the method `POST`; `data` is sent as JSON. `RESTBuilder.PUT()`, `RESTBuilder.PATCH()` and `RESTBuilder.DELETE()` work the same way with their methods.\n\nExample: POST JSON\n```js\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {\n\tconsole.log(order.id);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nCreates a PUT request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL. |\n| `data` | `Object` | no |  | Sent as a JSON body. |\n\nReturns: `RESTBuilder` A new builder.\n\nCreates a builder with the method `PUT`; `data` is sent as JSON.\n\nExample: PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nCreates a PATCH request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL. |\n| `data` | `Object` | no |  | Sent as a JSON body. |\n\nReturns: `RESTBuilder` A new builder.\n\nCreates a builder with the method `PATCH`; `data` is sent as JSON.\n\nExample: PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nCreates a DELETE request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL. |\n| `data` | `Object` | no |  | Sent as a JSON body. |\n\nReturns: `RESTBuilder` A new builder.\n\nCreates a builder with the method `DELETE`; `data` is sent as JSON.\n\nExample: DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nCalls an API endpoint of a Total.js application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL of the API endpoint. |\n| `name` | `String` | yes |  | The name of the API operation. |\n| `data` | `Object` | no |  | The data of the operation. |\n\nReturns: `RESTBuilder` A new builder.\n\nCreates a `POST` request for a Total.js API route (`ROUTE('API /api/ ...')`). The body is JSON: `{ schema: name, data: data }`. `name` is the API name with optional parameters, for example `'products_detail/p100'`. `builder.get(query)` keeps the `POST` and sends the query in the body as `query`, next to `data`. `builder.compress()` leaves out the keys of the body whose value is `null` or `undefined`.\n\nExample: Call an API\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: With a query\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n### builder.compress([value])\n\nType: `method`\n\nLeaves out empty values from the body of a RESTBuilder.API() request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` turns it off. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nWithout an argument or with `true`, the JSON body of a `RESTBuilder.API()` request is written without the keys whose value is `null` or `undefined`, so the request is smaller. `compress(false)` turns it off. Other builders are not affected.\n\nExample: Smaller body\n```js\nRESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);\n// data: { id: 'A1', total: 120 }\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nRegisters a function that changes every builder before it is sent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nThe function runs for every builder in the application just before the request is made, with the builder as the argument. Use it for shared headers or tokens. Upgrades cannot be removed.\n\nExample: Add a token to one service\n```js\nRESTBuilder.upgrade(function(builder) {\n\tif (builder.url().startsWith(CONF.shopapi))\n\t\tbuilder.header('X-Token', CONF.shoptoken);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nSets or reads the URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | The new URL. |\n\nReturns: `RESTBuilder|String` The builder, or the URL when called without an argument.\n\nWith an argument sets the URL and returns the builder; without one returns the current URL.\n\nExample: Read the URL\n```js\nvar url = builder.url();\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 |  | The HTTP method. |\n| `data` | `Object` | no |  | Data sent as JSON. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nSets the method (lower case is converted to upper case). `data` is sent as JSON.\n\nShortcuts: `builder.get([query])` sets `GET` and the query string; `builder.post([data])`, `builder.put([data])`, `builder.patch([data])` and `builder.delete([data])` set the method and the body (in the type set before, JSON by default); `builder.head()` sets `HEAD`. Upper-case names (`builder.POST()`) are aliases.\n\nExample: Shortcuts\n```js\nRESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);\n```\n\n### builder.json([data])\n\nType: `method`\n\nSends data as JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | The data. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nSets the type to JSON and the body to `data` (an object is serialized when the request is sent). A `GET` request becomes `POST`.\n\nExample: JSON body\n```js\nRESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nSends data as a URL-encoded form.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | The form fields. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nSets `Content-Type: application/x-www-form-urlencoded` and the body; an object is encoded when the request is sent. A `GET` request becomes `POST`.\n\nExample: Form\n```js\nRESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);\n```\n\n### builder.xml([data])\n\nType: `method`\n\nSends an XML body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | The XML. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nSets `Content-Type: text/xml` and the body. Pass the XML as a string. A `GET` request becomes `POST`.\n\nExample: XML body\n```js\nRESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);\n```\n\n### builder.raw(value, [type])\n\nType: `method`\n\nSets the body as it is.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | The body. |\n| `type` | `String` | no |  | The short content type. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nSets the body without any serialization. `type` is one of the short types of `REQUEST()` (`'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'`, `'raw'`); without it set the header with `builder.type()`. A string is sent unchanged. A `Buffer` needs the type `'raw'` (`application/octet-stream`); without a type it is serialized as JSON like an object.\n\nExample: Binary body\n```js\nRESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.text(value)\n\nType: `method`\n\nSends plain text and keeps the response unparsed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The text. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\n`builder.plain(value)` is an alias. Sets `Content-Type: text/plain` and the body, and the callback receives the raw response body instead of a parsed value.\n\nExample: Plain text\n```js\nRESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {\n\t// response is the raw body\n});\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nAdds a file and sends a multipart request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The form field name. |\n| `filename` | `String` | yes |  | The file name sent to the service. |\n| `source` | `Buffer|String` | no |  | A buffer, a path or a URL. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nThe request becomes `multipart/form-data` (a `GET` becomes `POST`). `source` is a `Buffer`, a path on the disk, or a URL that is downloaded and streamed. Without `source` the file is read from `filename`. The body set with `json()` or `urlencoded()` is sent as extra form fields when it is an object.\n\nExample: Upload two files\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))\n\t.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')\n\t.callback(console.log);\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 header name. |\n| `value` | `String` | yes |  | The value. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nSets one header. Helpers for common headers: `builder.referrer(url)` (alias `referer()`) sets `Referer`, `builder.origin(url)` sets `Origin`, `builder.csrf(token)` sets `X-Csrf-Token` and `builder.xhr()` adds `X-Requested-With: XMLHttpRequest`.\n\nExample: Headers\n```js\nbuilder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();\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 MIME type. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nSets `Content-Type` to a full MIME type. A type set by `json()`, `urlencoded()`, `xml()` or `text()` replaces it, so use it with `raw(value)`.\n\nExample: Custom type\n```js\nbuilder.raw('{\"id\":1}').type('application/vnd.api+json');\n```\n\n### builder.accept(ext)\n\nType: `method`\n\nSets the Accept header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | An extension or a MIME type. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nTakes a file extension (`'json'`, `'xml'`, `'html'`...) and converts it to its MIME type; a longer value is used as it is.\n\nExample: Accept XML\n```js\nbuilder.accept('xml');\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 same builder, for chaining.\n\nWith `user` and `password` sets basic authentication (`Basic base64(user:password)`). With one argument the value is used as it is, for example `'Bearer TOKEN'`.\n\nExample: Basic and Bearer\n```js\nbuilder.auth('admin', 'secret');\nbuilder.auth('Bearer ' + CONF.apitoken);\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 cookie name. |\n| `value` | `String` | yes |  | The value. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nAdds one cookie. `builder.cookies(obj)` replaces all cookies with an object `{ name: value }`.\n\nExample: Cookies\n```js\nbuilder.cookie('session', token);\nbuilder.cookies({ lang: 'en', theme: 'dark' });\n```\n\n### builder.cook([value])\n\nType: `method`\n\nKeeps the response cookies in the builder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` turns it off. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nWith `cook()` the cookies set by the response are stored in the builder and sent with the next request made by the same builder. `output.cookies` then holds them. `cook(false)` turns it off.\n\nExample: Login, then read\n```js\nRESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {\n\tRESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);\n});\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 |  | Milliseconds. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nThe timeout in milliseconds (10000 by default). `0` disables it. When it expires the error is `408: Request Timeout`.\n\nExample: Five seconds\n```js\nbuilder.timeout(5000);\n```\n\n### builder.keepalive([val])\n\nType: `method`\n\nReuses connections with a keep-alive agent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `val` | `Boolean` | no | `true` | Turns keep-alive on or off. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nWithout an argument (or with a truthy value) the request uses the shared keep-alive agent of the framework, so connections to the same host are reused. `keepalive(false)` turns it off. Not used together with a proxy.\n\nExample: Keep-alive\n```js\nRESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nSends the request through a proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The proxy. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\n`url` is `'host:port'` or `'http://host:port'`. With `http://user:password@host:port` the credentials are sent as `Proxy-Authorization: Basic`. HTTPS targets are tunneled with `CONNECT`. Without it the proxy of the configuration key `$proxyrequest` is used when set.\n\nExample: Proxy\n```js\nbuilder.proxy('http://10.0.0.5:3128');\n```\n\nExample: Proxy with a login\n```js\nbuilder.proxy('http://user:secret@10.0.0.5:3128');\n```\n\n### builder.insecure()\n\nType: `method`\n\nAccepts invalid TLS certificates.\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nAccepts self-signed or expired certificates of the service. Use it only for internal services.\n\nExample: Self-signed\n```js\nRESTBuilder.GET('https://10.0.0.20/api/').insecure().callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nSets a client TLS 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 same builder, for chaining.\n\nFor services that require client certificates.\n\nExample: Client certificate\n```js\nbuilder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nSends the request through a Unix socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | The socket file. |\n| `path` | `String` | yes |  | The request path, for example `/api/`. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nConnects to the socket file instead of a host; `path` is the URL path of the request.\n\nExample: Docker API\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/docker.sock', '/containers/json');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nTurns off the DNS cache for this request.\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nBy default the builder resolves the hostname once and caches its addresses. With `nodnscache()` Node.js resolves it for every request.\n\nExample: No DNS cache\n```js\nbuilder.nodnscache();\n```\n\n### builder.redirect(value)\n\nType: `method`\n\nTurns following redirects on or off.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | yes |  | `false` stops following redirects. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\n`redirect(false)` returns the `301` or `302` response itself; read the target in `output.headers.location`. By default up to four redirects are followed.\n\nExample: Read the location\n```js\nRESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers.location);\n});\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` | yes |  | The encryption key. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nThe body is encrypted with `key` and sent with the header `X-Encryption: a`; a text response is decrypted with the same key. Both sides must use the same key.\n\nExample: Encrypted call\n```js\nbuilder.encrypt(CONF.sharedkey);\n```\n\n### builder.progress(fn)\n\nType: `method`\n\nReports the download progress.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(percentage)`. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nCalls `fn(percentage)` for every received chunk. The percentage is known only when the response has `Content-Length`, otherwise it is `0`.\n\nExample: Progress\n```js\nbuilder.progress(function(percentage) {\n\tconsole.log(percentage.toFixed(1) + '%');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nReturns the raw response body.\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nThe callback receives the body as a string (or a `Buffer` for binary types) instead of a parsed value.\n\nExample: Raw HTML\n```js\nRESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {\n\tconsole.log(html.length);\n});\n```\n\n### builder.base64()\n\nType: `method`\n\nReturns the response body as base64.\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nThe callback receives the body encoded in base64, for example to embed an image as a data URI.\n\nExample: Data URI\n```js\nRESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {\n\tvar uri = 'data:image/png;base64,' + data;\n});\n```\n\n### builder.debug()\n\nType: `method`\n\nPrints the request and the response to the console.\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nAfter the response arrives prints the status, the method, the URL with the query, the error and the raw body.\n\nExample: Debug\n```js\nRESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nSends the request and receives the parsed response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)` or the `$` of an action. |\n\nReturns: `RESTBuilder|Promise` The builder, or a promise when called without an argument.\n\nSends the request on the next tick and passes the result to `fn(err, response, output)`:\n\n- `response`: the body parsed by its `Content-Type` (JSON, also for `text/plain`; URL-encoded; XML through the HTML parser; other bodies are parsed as JSON when they look like JSON). An empty body gives an empty object; a `204` response gives `true`.\n- `output`: `status`, `headers`, `response` (the raw body), `hostname`, `origin`, `cookies` (with `cook()`) and `output.cookie(name)`, which reads a cookie of the response.\n- `err`: the network error or `'408: Request Timeout'`; an `ErrorBuilder` when the body is a Total.js error array (`[{ error: '...' }]`, `response` is then `null`); otherwise, for a status of `400` or more, an `ErrorBuilder` with one error whose name is the status code and whose message is the raw body. A value set with `builder.error()` replaces any error.\n\n`fn` can also be the `$` of an action: the parsed response is passed to `$.callback()` and an error is added to the errors of `$`. Without an argument it returns a promise that resolves with `response` and rejects with `err`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) {\n\tif (err)\n\t\treturn console.log(err);\n\tconsole.log(output.status, response.length);\n});\n```\n\nExample: In an action\n```js\nNEWACTION('Products/sync', {\n\tname: 'Sync products',\n\taction: function($) {\n\t\tRESTBuilder.GET(CONF.shopapi + '/products/').callback($);\n\t}\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 `$` of an action. |\n\nReturns: `Promise` Resolves with the parsed response.\n\nThe promise resolves with the parsed response. On an error it rejects with an `Error` made from the error (an `ErrorBuilder` becomes an `Error` with its messages). With `$` the error goes to `$.invalid()` instead and the promise is not rejected.\n\nExample: await\n```js\nvar user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();\n```\n\nExample: With $\n```js\nvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\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 same builder, for chaining.\n\nSends the request immediately and calls `callback(err, response, output)` with the same values as `callback()`. Prefer `callback()`, which waits for the next tick. When `callback` is omitted the result is ignored.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nReturns the response as a stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nSends the request on the next tick and calls `callback(err, response)` as soon as the headers arrive. `response` has `status`, `headers`, `origin` and `stream` (the Node.js response, not read yet). Use it for large files.\n\nExample: Save a large file\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (!err && response.status === 200)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### builder.error(value)\n\nType: `method` · Since: `0.0.16`\n\nReplaces any error with your own value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String` | yes |  | The error to return, for example a message or an `ErrorBuilder`. |\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nWhen the request ends with any error (network, timeout or a status of `400` or more), the callback or the promise receives `value` instead. Use it to hide the details of a remote service from your users.\n\nExample: Own error\n```js\nRESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);\n```\n\n### builder.logerror()\n\nType: `method` · Since: `0.0.16`\n\nPrints errors to the console.\n\nReturns: `RESTBuilder` The same builder, for chaining.\n\nWhen the request ends with an error, the error (or the raw response body) is passed to the framework error handler, which prints it with the name `RESTBuilder` and the method and URL of the request. The callback still receives the error.\n\nExample: Log errors\n```js\nRESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"AJAX()","signature":"AJAX('METHOD url', [data], [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"Total.download()","signature":"Total.download(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"class","name":"RESTBuilder","signature":"new RESTBuilder([url])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","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.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"builder.compress()","signature":"builder.compress([value])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","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.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])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, [type])","since":"","deprecated":false},{"type":"method","name":"builder.text()","signature":"builder.text(value)","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","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(ext)","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([value])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive([val])","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.insecure()","signature":"builder.insecure()","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt(key)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.base64()","signature":"builder.base64()","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.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(value)","since":"0.0.16","deprecated":false},{"type":"method","name":"builder.logerror()","signature":"builder.logerror()","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwtJ1cx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/http-requests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"HTTP-Anfragen","summary":"RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() und Total.download().","markdown":"---\ntitle: HTTP-Anfragen\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/http-requests/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# HTTP-Anfragen\n\n> RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() und Total.download().\n\nDie globalen Funktionen und die Klasse `RESTBuilder` für HTTP-Anfragen an andere Dienste. Eine Einführung mit Beispielen findest du in der Anleitung [HTTP-Anfragen](../../guides/http-requests/). Der WebSocket-Client `OPENCLIENT()` hat eine eigene Seite: [OpenClient](../openclient/).\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nSendet eine HTTP-Anfrage mit voller Kontrolle über die Optionen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.url` | `String` | yes |  | Die URL der Anfrage. Zugangsdaten in der URL (`https://user:password@host/`) werden als `Authorization: Basic` gesendet; prozentkodierte Zeichen darin werden vorher decodiert. |\n| `options.method` | `String` | no | `'GET'` | Die HTTP-Methode in Großbuchstaben. |\n| `options.headers` | `Object` | no |  | Anfrage-Header. Das Objekt wird kopiert, dein Objekt wird also nicht verändert. |\n| `options.type` | `String` | no |  | Setzt `Content-Type`: `'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'` oder `'text'`, `'raw'` (`application/octet-stream`). |\n| `options.body` | `String|Buffer` | no |  | Der Body der Anfrage. Ein String wird als UTF-8 gesendet; `Content-Length` wird für dich gesetzt. |\n| `options.query` | `Object|String` | no |  | Wird als Query-String an die URL angehängt. |\n| `options.cookies` | `Object` | no |  | Zu sendende Cookies, als `{ name: value }`. |\n| `options.cook` | `Boolean` | no |  | Speichert die Cookies der Antwort in `options.cookies`, sodass dasselbe Options-Objekt sie mit der nächsten Anfrage sendet. |\n| `options.timeout` | `Number` | no | `8000` | Timeout in Millisekunden; `0` deaktiviert ihn. |\n| `options.encoding` | `String` | no | `'utf8'` | Kodierung eines Text-Bodys. `'binary'` gibt einen `Buffer` zurück. |\n| `options.xhr` | `Boolean` | no |  | Fügt `X-Requested-With: XMLHttpRequest` hinzu. |\n| `options.files` | `Array` | no |  | Dateien für eine `multipart/form-data`-Anfrage: `[{ name, filename, buffer \\| path \\| url }]`. `options.body` ist dann ein Objekt mit zusätzlichen Formularfeldern. |\n| `options.compress` | `String` | no |  | Komprimiert den Body: `'gzip'` oder `'deflate'`, und setzt `Content-Encoding`. |\n| `options.encrypt` | `String` | no |  | Ein Schlüssel: Der Body wird damit verschlüsselt und die Textantwort damit entschlüsselt. |\n| `options.writer` | `Function` | no |  | `function(req)` schreibt den Body selbst: Sie erhält die Node.js-Anfrage, schreibt die Daten und ruft `req.end()` auf. `body` und `files` werden dann nicht verwendet. |\n| `options.custom` | `Boolean` | no |  | Gibt `response.stream` zurück, statt den Body zu lesen. |\n| `options.noredirect` | `Boolean` | no |  | Folgt keinen Weiterleitungen; der Callback erhält die `301`/`302`-Antwort. |\n| `options.keepalive` | `Boolean` | no |  | Verwendet einen gemeinsamen Keep-Alive-Agent (einen für HTTP, einen für HTTPS). |\n| `options.resolve` | `Boolean` | no |  | Löst den Hostnamen mit einem DNS-Cache auf. `options.dnscache` macht dasselbe. Wird für `localhost` und IP-Adressen übersprungen. |\n| `options.proxy` | `String` | no |  | Ein Proxy für diese Anfrage, als `'host:port'` oder `'http://host:port'`. Mit `http://user:password@host:port` werden die Zugangsdaten als `Proxy-Authorization: Basic` gesendet. |\n| `options.insecure` | `Boolean` | no |  | Akzeptiert ungültige oder selbstsignierte TLS-Zertifikate. |\n| `options.key` | `Buffer` | no |  | TLS-Schlüssel des Clients. |\n| `options.cert` | `Buffer` | no |  | TLS-Zertifikat des Clients. |\n| `options.dhparam` | `Buffer` | no |  | TLS-Diffie-Hellman-Parameter. |\n| `options.unixsocket` | `Object` | no |  | `{ socket, path }`, um die Anfrage statt über `url` über einen Unix-Socket zu senden. |\n| `options.ondata` | `Function` | no |  | `function(chunk, percentage)` für jeden empfangenen Chunk. |\n| `options.onprogress` | `Function` | no |  | `function(percentage)`; der Prozentsatz ist nur mit `Content-Length` bekannt. |\n| `options.callback` | `Function` | no |  | `function(err, response)`, statt des zweiten Arguments. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Ein Promise, wenn kein Callback übergeben wird; sonst nichts.\n\nSendet eine HTTP-Anfrage, die durch `options` beschrieben wird. Der Callback erhält `(err, response)`; ohne Callback (im Argument oder in `options.callback`) gibt die Funktion ein Promise zurück, das mit `response` erfüllt wird.\n\nDas Antwortobjekt hat `status`, `headers`, `body`, `host`, `origin` (die aufgelösten IP-Adressen, wenn DNS-Caching aktiv ist) und `cookies` (die bei Weiterleitungen gesammelten Cookies). `body` ist ein String für `text/*`- und `application/*`-Typen (mit `encoding` decodiert) und ein `Buffer` für die anderen Typen, oder mit `encoding: 'binary'` immer ein `Buffer`. Der Body wird nicht geparst: Verwende dafür `RESTBuilder` oder `AJAX()`.\n\nMit `custom: true` läuft der Callback, sobald die Header eintreffen, und die Antwort hat `stream` (die Node.js-Antwort) statt `body`.\n\nFehler: Ein Netzwerkfehler übergibt das Fehlerobjekt mit `response.status === 0`; ein abgelaufenes Timeout übergibt `'408: Request Timeout'` mit `response.status === 408`; mehr als vier Weiterleitungen übergeben `'Too many redirects'`; eine URL ohne Hostnamen übergibt `'Invalid hostname'`, und ein String, der keine URL ist, wirft `TypeError: Invalid URL`. Ein Statuscode ab `400` ist kein Fehler: Prüfe `response.status`.\n\nWeiterleitungen `301` und `302` werden verfolgt (die Cookies der Weiterleitung werden an das nächste Ziel gesendet). Anfragen verwenden den Proxy des Konfigurationsschlüssels `$proxyrequest`, wenn er gesetzt ist, außer für `localhost`, `127.0.0.1` und `0.0.0.0`.\n\nExample: POST JSON\n```js\nREQUEST({\n\turl: 'https://api.example.com/orders/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ id: 'p100', count: 2 })\n}, function(err, response) {\n\tif (err || response.status !== 200)\n\t\treturn;\n\tvar order = response.body.parseJSON();\n});\n```\n\nExample: Mit einem Promise\n```js\nvar response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });\nconsole.log(response.status, response.body);\n```\n\nExample: Eine Datei hochladen\n```js\nREQUEST({\n\turl: 'https://files.example.com/upload/',\n\tmethod: 'POST',\n\tfiles: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],\n\tbody: { folder: 'reports' }\n}, console.log);\n```\n\nExample: Einen Stream lesen\n```js\nREQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));\n});\n```\n\nExample: Den Body selbst schreiben\n```js\nREQUEST({\n\turl: 'https://api.example.com/import/',\n\tmethod: 'POST',\n\ttype: 'plain',\n\twriter: function(req) {\n\t\tfor (var line of lines)\n\t\t\treq.write(line + '\\n');\n\t\treq.end();\n\t}\n}, console.log);\n```\n\n### AJAX('METHOD url', [data], [callback])\n\nType: `method`\n\nSendet eine JSON-Anfrage und gibt die geparste Antwort zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `'METHOD url'`, zum Beispiel `'POST https://example.com/api/'`. |\n| `data` | `Object` | no |  | Als JSON gesendete Daten. |\n| `callback` | `Function` | no |  | `function(err, response, meta)`. |\n\nReturns: `Promise` Eine Promise, wenn kein Callback übergeben wird.\n\nSendet eine Anfrage und parst die Antwort. Das erste Argument ist die Methode und die URL, durch ein Leerzeichen getrennt; ohne Methode ist es `GET`. `data` wird als JSON-Body gesendet. Der Header `X-Requested-With: XMLHttpRequest` wird immer hinzugefügt.\n\nDie Antwort wird anhand ihres `Content-Type` geparst: JSON (`application/json`, `text/json`), URL-codierte Daten und XML (`application/xml`, `text/xml`) werden zu Objekten; andere Typen werden als roher Body zurückgegeben. Ein XML-Dokument wird zu einem flachen Objekt: Die Namen verschachtelter Elemente werden mit `_` verbunden (`order_name`), wiederholte Elemente ergeben ein Array, und die Attribute eines Elements stehen in einem Objekt unter seinem Namen mit `__` (`order__`). Ein leerer XML-Body ergibt `{}`. Der Callback erhält `(err, response, meta)`, wobei `meta` die Werte `status`, `headers` und `host` enthält.\n\nBei einem Status von `400` oder mehr ist `err` der geparste Body (bei einem Total.js-Dienst das Fehler-Array) und `response` ist `null`. Ohne Callback gibt die Funktion eine Promise zurück, die mit dem geparsten Body erfüllt und mit `err` abgelehnt wird; ein Total.js-Fehler-Array wird zu einem `Error`, dessen Meldung die Fehlermeldungen enthält.\n\nExample: Callback\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {\n\tconsole.log(meta.status, response);\n});\n```\n\nExample: Promise\n```js\nvar products = await AJAX('GET https://api.example.com/products/?page=1');\n```\n\nExample: XML-Antwort\n```js\n// the service answers <order id=\"100\"><name>Book</name><items><item>A</item><item>B</item></items></order>\nvar order = await AJAX('GET https://api.example.com/orders/100/');\n// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nLädt eine entfernte Datei auf die Festplatte herunter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | Die URL oder `{ socket, path }` für einen Unix-Socket. |\n| `filename` | `String` | yes |  | Der Pfad der Zieldatei. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout in Millisekunden. |\n\nReturns: `Promise` Eine Promise, wenn kein Callback übergeben wird.\n\nLädt `url` herunter und schreibt den Body in `filename`. Der Callback läuft, wenn die Datei geschrieben ist, mit `(err, response)`. `response` enthält `status`, `headers`, `origin`, `filename` und `size` (die Anzahl der geschriebenen Bytes). Der Body wird bei jedem Statuscode gespeichert, prüfe also `response.status`.\n\n`url` kann auch ein Objekt `{ socket, path }` für einen Unix-Socket sein. DNS-Abfragen werden zwischengespeichert. `timeout` ist in Millisekunden (8 Sekunden, wenn nicht gesetzt). Ohne Callback gibt die Funktion eine Promise zurück, die mit `response` erfüllt wird.\n\nExample: Ein Bild herunterladen\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.filename);\n});\n```\n\nExample: Promise\n```js\nvar response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));\n```\n\n### Total.download(url, filename, [callback], [timeout])\n\nType: `method`\n\nDie Framework-Methode hinter DOWNLOAD().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | Die URL oder `{ socket, path }` für einen Unix-Socket. |\n| `filename` | `String` | yes |  | Der Pfad der Zieldatei. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout in Millisekunden. |\n\nReturns: `Promise` Eine Promise, wenn kein Callback übergeben wird.\n\nDieselbe Funktion wie `DOWNLOAD()`. Lädt `url` herunter und schreibt den Body in `filename`. Der Callback läuft, wenn die Datei geschrieben ist, mit `(err, response)`. `response` enthält `status`, `headers`, `origin`, `filename` und `size` (die Anzahl der geschriebenen Bytes). Der Body wird bei jedem Statuscode gespeichert, prüfe also `response.status`.\n\n`url` kann auch ein Objekt `{ socket, path }` für einen Unix-Socket sein. DNS-Abfragen werden zwischengespeichert. `timeout` ist in Millisekunden (8 Sekunden, wenn nicht gesetzt). Ohne Callback gibt die Funktion eine Promise zurück, die mit `response` erfüllt wird.\n\nExample: Herunterladen\n```js\nTotal.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n### new RESTBuilder([url])\n\nType: `class`\n\nEin Builder für Anfragen an REST-Dienste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Die URL der Anfrage. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nEine globale Klasse. Ein neuer Builder hat die Methode `GET`, ein Timeout von 10 Sekunden, aktives DNS-Caching, den Header `user-agent: Total.js/v...` und `accept: application/json, text/plain, text/plain, text/xml`. Es wird nichts gesendet, bis du `callback()`, `promise()`, `stream()` oder `exec()` aufrufst.\n\nMeist beginnst du mit einem statischen Helper: `RESTBuilder.GET()`, `POST()`, `PUT()`, `PATCH()`, `DELETE()`, `HEAD()`, `API()`, `url()` oder `make()`. `RESTBuilder.url(url)` ist dasselbe wie `new RESTBuilder(url)`.\n\nExample: Einen Builder erstellen\n```js\nvar builder = RESTBuilder.url('https://api.example.com/users/');\nbuilder.header('X-Token', CONF.apitoken);\nbuilder.callback(console.log);\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nErstellt einen 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\nErstellt einen Builder ohne URL und ruft `fn(builder)` auf. Setze die URL mit `builder.url()`. Die Instanzmethode `builder.make(fn)` ruft `fn` mit dem Builder als `this` und als Argument auf, für wiederverwendbare Einstellungen.\n\nExample: Eine Anfrage aufbauen\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.post({ name: 'Peter' });\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nErstellt eine GET-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL. |\n| `data` | `Object` | no |  | Wird als Query String gesendet. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nErstellt einen Builder mit der Methode `GET`; `data` wird zum Query String. Für eine `HEAD`-Anfrage verwende `RESTBuilder.HEAD(url)`: Sie hat keine Daten, der geparste Wert ist ein leeres Objekt, und du liest `output.status` und `output.headers`.\n\nExample: Query String\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nExample: HEAD\n```js\nRESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers['last-modified']);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nErstellt eine POST-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL. |\n| `data` | `Object` | no |  | Wird als JSON-Body gesendet. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nErstellt einen Builder mit der Methode `POST`; `data` wird als JSON gesendet. `RESTBuilder.PUT()`, `RESTBuilder.PATCH()` und `RESTBuilder.DELETE()` funktionieren genauso mit ihren Methoden.\n\nExample: POST JSON\n```js\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {\n\tconsole.log(order.id);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nErstellt eine PUT-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL. |\n| `data` | `Object` | no |  | Wird als JSON-Body gesendet. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nErstellt einen Builder mit der Methode `PUT`; `data` wird als JSON gesendet.\n\nExample: PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nErstellt eine PATCH-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL. |\n| `data` | `Object` | no |  | Wird als JSON-Body gesendet. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nErstellt einen Builder mit der Methode `PATCH`; `data` wird als JSON gesendet.\n\nExample: PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nErstellt eine DELETE-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL. |\n| `data` | `Object` | no |  | Wird als JSON-Body gesendet. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nErstellt einen Builder mit der Methode `DELETE`; `data` wird als JSON gesendet.\n\nExample: DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nRuft einen API-Endpunkt einer Total.js-Anwendung auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL des API-Endpunkts. |\n| `name` | `String` | yes |  | Der Name der API-Operation. |\n| `data` | `Object` | no |  | Die Daten der Operation. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nErstellt eine `POST`-Anfrage für eine Total.js-API-Route (`ROUTE('API /api/ ...')`). Der Body ist JSON: `{ schema: name, data: data }`. `name` ist der API-Name mit optionalen Parametern, zum Beispiel `'products_detail/p100'`. `builder.get(query)` behält das `POST` bei und sendet die Query im Body als `query`, neben `data`. `builder.compress()` lässt die Schlüssel des Bodys weg, deren Wert `null` oder `undefined` ist.\n\nExample: Eine API aufrufen\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Mit einer Query\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n### builder.compress([value])\n\nType: `method`\n\nLässt leere Werte aus dem Body einer Anfrage mit RESTBuilder.API() weg.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` schaltet es ab. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nOhne Argument oder mit `true` wird der JSON-Body einer Anfrage mit `RESTBuilder.API()` ohne die Schlüssel geschrieben, deren Wert `null` oder `undefined` ist, sodass die Anfrage kleiner wird. `compress(false)` schaltet es ab. Andere Builder sind nicht betroffen.\n\nExample: Kleinerer Body\n```js\nRESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);\n// data: { id: 'A1', total: 120 }\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nRegistriert eine Funktion, die jeden Builder vor dem Senden ändert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nDie Funktion läuft für jeden Builder in der Anwendung direkt bevor die Anfrage ausgeführt wird, mit dem Builder als Argument. Verwende sie für gemeinsame Header oder Tokens. Upgrades können nicht entfernt werden.\n\nExample: Einem Dienst ein Token hinzufügen\n```js\nRESTBuilder.upgrade(function(builder) {\n\tif (builder.url().startsWith(CONF.shopapi))\n\t\tbuilder.header('X-Token', CONF.shoptoken);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nSetzt oder liest die URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Die neue URL. |\n\nReturns: `RESTBuilder|String` Der Builder oder, ohne Argument aufgerufen, die URL.\n\nMit einem Argument wird die URL gesetzt und der Builder zurückgegeben; ohne Argument wird die aktuelle URL zurückgegeben.\n\nExample: Die URL lesen\n```js\nvar url = builder.url();\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 |  | Die HTTP-Methode. |\n| `data` | `Object` | no |  | Als JSON gesendete Daten. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nSetzt die Methode (Kleinbuchstaben werden in Großbuchstaben umgewandelt). `data` wird als JSON gesendet.\n\nKurzformen: `builder.get([query])` setzt `GET` und den Query String; `builder.post([data])`, `builder.put([data])`, `builder.patch([data])` und `builder.delete([data])` setzen die Methode und den Body (im zuvor gesetzten Typ, standardmäßig JSON); `builder.head()` setzt `HEAD`. Namen in Großbuchstaben (`builder.POST()`) sind Aliase.\n\nExample: Kurzformen\n```js\nRESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);\n```\n\n### builder.json([data])\n\nType: `method`\n\nSendet Daten als JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Die Daten. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nSetzt den Typ auf JSON und den Body auf `data` (ein Objekt wird beim Senden der Anfrage serialisiert). Eine `GET`-Anfrage wird zu `POST`.\n\nExample: JSON-Body\n```js\nRESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nSendet Daten als URL-kodiertes Formular.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Die Formularfelder. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nSetzt `Content-Type: application/x-www-form-urlencoded` und den Body; ein Objekt wird beim Senden der Anfrage kodiert. Eine `GET`-Anfrage wird zu `POST`.\n\nExample: Formular\n```js\nRESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);\n```\n\n### builder.xml([data])\n\nType: `method`\n\nSendet einen XML-Body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | Das XML. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nSetzt `Content-Type: text/xml` und den Body. Übergib das XML als String. Eine `GET`-Anfrage wird zu `POST`.\n\nExample: XML-Body\n```js\nRESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);\n```\n\n### builder.raw(value, [type])\n\nType: `method`\n\nSetzt den Body unverändert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Der Body. |\n| `type` | `String` | no |  | Der kurze Content-Type. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nSetzt den Body ohne jede Serialisierung. `type` ist einer der Kurztypen von `REQUEST()` (`'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'`, `'raw'`); ohne ihn setzt du den Header mit `builder.type()`. Ein String wird unverändert gesendet. Ein `Buffer` braucht den Typ `'raw'` (`application/octet-stream`); ohne Typ wird er wie ein Objekt als JSON serialisiert.\n\nExample: Binärer Body\n```js\nRESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.text(value)\n\nType: `method`\n\nSendet einfachen Text und lässt die Antwort ungeparst.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der Text. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\n`builder.plain(value)` ist ein Alias. Setzt `Content-Type: text/plain` und den Body, und der Callback erhält den rohen Antwort-Body statt eines geparsten Werts.\n\nExample: Einfacher Text\n```js\nRESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {\n\t// response is the raw body\n});\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nFügt eine Datei hinzu und sendet eine Multipart-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Formularfelds. |\n| `filename` | `String` | yes |  | Der an den Dienst gesendete Dateiname. |\n| `source` | `Buffer|String` | no |  | Ein Buffer, ein Pfad oder eine URL. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nDie Anfrage wird zu `multipart/form-data` (ein `GET` wird zu `POST`). `source` ist ein `Buffer`, ein Pfad auf der Festplatte oder eine URL, die heruntergeladen und gestreamt wird. Ohne `source` wird die Datei aus `filename` gelesen. Der mit `json()` oder `urlencoded()` gesetzte Body wird als zusätzliche Formularfelder gesendet, wenn er ein Objekt ist.\n\nExample: Zwei Dateien hochladen\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))\n\t.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')\n\t.callback(console.log);\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` Derselbe Builder, für Verkettung.\n\nSetzt einen Header. Helfer für gängige Header: `builder.referrer(url)` (Alias `referer()`) setzt `Referer`, `builder.origin(url)` setzt `Origin`, `builder.csrf(token)` setzt `X-Csrf-Token` und `builder.xhr()` fügt `X-Requested-With: XMLHttpRequest` hinzu.\n\nExample: Header\n```js\nbuilder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();\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 MIME-Typ. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nSetzt `Content-Type` auf einen vollständigen MIME-Typ. Ein von `json()`, `urlencoded()`, `xml()` oder `text()` gesetzter Typ ersetzt ihn; verwende es also mit `raw(value)`.\n\nExample: Eigener Typ\n```js\nbuilder.raw('{\"id\":1}').type('application/vnd.api+json');\n```\n\n### builder.accept(ext)\n\nType: `method`\n\nSetzt den Header Accept.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Eine Endung oder ein MIME-Typ. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nNimmt eine Dateiendung (`'json'`, `'xml'`, `'html'`...) und wandelt sie in ihren MIME-Typ um; ein längerer Wert wird unverändert verwendet.\n\nExample: XML akzeptieren\n```js\nbuilder.accept('xml');\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 gesamte Header-Wert. |\n| `password` | `String` | no |  | Das Passwort. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nMit `user` und `password` wird Basic-Authentifizierung gesetzt (`Basic base64(user:password)`). Mit einem Argument wird der Wert unverändert verwendet, zum Beispiel `'Bearer TOKEN'`.\n\nExample: Basic und Bearer\n```js\nbuilder.auth('admin', 'secret');\nbuilder.auth('Bearer ' + CONF.apitoken);\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 des Cookies. |\n| `value` | `String` | yes |  | Der Wert. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nFügt ein Cookie hinzu. `builder.cookies(obj)` ersetzt alle Cookies durch ein Objekt `{ name: value }`.\n\nExample: Cookies\n```js\nbuilder.cookie('session', token);\nbuilder.cookies({ lang: 'en', theme: 'dark' });\n```\n\n### builder.cook([value])\n\nType: `method`\n\nBehält die Cookies der Antwort im Builder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` schaltet es ab. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nMit `cook()` werden die von der Antwort gesetzten Cookies im Builder gespeichert und mit der nächsten Anfrage desselben Builders gesendet. `output.cookies` enthält sie dann. `cook(false)` schaltet es ab.\n\nExample: Anmelden, dann lesen\n```js\nRESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {\n\tRESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);\n});\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 |  | Millisekunden. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nDas Timeout in Millisekunden (standardmäßig 10000). `0` deaktiviert es. Läuft es ab, lautet der Fehler `408: Request Timeout`.\n\nExample: Fünf Sekunden\n```js\nbuilder.timeout(5000);\n```\n\n### builder.keepalive([val])\n\nType: `method`\n\nVerwendet Verbindungen mit einem Keep-Alive-Agent wieder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `val` | `Boolean` | no | `true` | Schaltet Keep-Alive ein oder aus. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nOhne Argument (oder mit einem truthy Wert) verwendet die Anfrage den gemeinsamen Keep-Alive-Agent des Frameworks, sodass Verbindungen zum selben Host wiederverwendet werden. `keepalive(false)` schaltet es ab. Wird nicht zusammen mit einem Proxy verwendet.\n\nExample: Keep-Alive\n```js\nRESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nSendet die Anfrage über einen Proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Der Proxy. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\n`url` ist `'host:port'` oder `'http://host:port'`. Mit `http://user:password@host:port` werden die Zugangsdaten als `Proxy-Authorization: Basic` gesendet. HTTPS-Ziele werden mit `CONNECT` getunnelt. Ohne diese Methode wird der Proxy aus dem Konfigurationsschlüssel `$proxyrequest` verwendet, wenn er gesetzt ist.\n\nExample: Proxy\n```js\nbuilder.proxy('http://10.0.0.5:3128');\n```\n\nExample: Proxy mit Anmeldedaten\n```js\nbuilder.proxy('http://user:secret@10.0.0.5:3128');\n```\n\n### builder.insecure()\n\nType: `method`\n\nAkzeptiert ungültige TLS-Zertifikate.\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nAkzeptiert selbstsignierte oder abgelaufene Zertifikate des Dienstes. Verwende es nur für interne Dienste.\n\nExample: Selbstsigniert\n```js\nRESTBuilder.GET('https://10.0.0.20/api/').insecure().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` Derselbe Builder, für Verkettung.\n\nFür Dienste, die Client-Zertifikate verlangen.\n\nExample: Client-Zertifikat\n```js\nbuilder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nSendet die Anfrage über einen Unix-Socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | Die Socket-Datei. |\n| `path` | `String` | yes |  | Der Pfad der Anfrage, zum Beispiel `/api/`. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nVerbindet sich mit der Socket-Datei statt mit einem Host; `path` ist der URL-Pfad der Anfrage.\n\nExample: Docker-API\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/docker.sock', '/containers/json');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nSchaltet den DNS-Cache für diese Anfrage ab.\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nStandardmäßig löst der Builder den Hostnamen einmal auf und cacht seine Adressen. Mit `nodnscache()` löst Node.js ihn bei jeder Anfrage auf.\n\nExample: Kein DNS-Cache\n```js\nbuilder.nodnscache();\n```\n\n### builder.redirect(value)\n\nType: `method`\n\nSchaltet das Verfolgen von Weiterleitungen ein oder aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | yes |  | `false` beendet das Verfolgen von Weiterleitungen. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\n`redirect(false)` gibt die `301`- oder `302`-Antwort selbst zurück; lies das Ziel in `output.headers.location`. Standardmäßig werden bis zu vier Weiterleitungen verfolgt.\n\nExample: Die Location lesen\n```js\nRESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers.location);\n});\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` | yes |  | Der Verschlüsselungsschlüssel. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nDer Body wird mit `key` verschlüsselt und mit dem Header `X-Encryption: a` gesendet; eine Textantwort wird mit demselben Schlüssel entschlüsselt. Beide Seiten müssen denselben Schlüssel verwenden.\n\nExample: Verschlüsselter Aufruf\n```js\nbuilder.encrypt(CONF.sharedkey);\n```\n\n### builder.progress(fn)\n\nType: `method`\n\nMeldet den Download-Fortschritt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(percentage)`. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nRuft `fn(percentage)` für jeden empfangenen Chunk auf. Der Prozentsatz ist nur bekannt, wenn die Antwort `Content-Length` hat, sonst ist er `0`.\n\nExample: Fortschritt\n```js\nbuilder.progress(function(percentage) {\n\tconsole.log(percentage.toFixed(1) + '%');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nGibt den rohen Antwort-Body zurück.\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nDer Callback erhält den Body als String (oder als `Buffer` für binäre Typen) statt eines geparsten Werts.\n\nExample: Rohes HTML\n```js\nRESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {\n\tconsole.log(html.length);\n});\n```\n\n### builder.base64()\n\nType: `method`\n\nGibt den Antwort-Body als Base64 zurück.\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nDer Callback erhält den Body Base64-kodiert, zum Beispiel um ein Bild als Data-URI einzubetten.\n\nExample: Data-URI\n```js\nRESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {\n\tvar uri = 'data:image/png;base64,' + data;\n});\n```\n\n### builder.debug()\n\nType: `method`\n\nGibt die Anfrage und die Antwort in der Konsole aus.\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nGibt nach dem Eintreffen der Antwort den Status, die Methode, die URL mit der Query, den Fehler und den rohen Body aus.\n\nExample: Debug\n```js\nRESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nSendet die Anfrage und empfängt die geparste Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)` oder das `$` einer Action. |\n\nReturns: `RESTBuilder|Promise` Der Builder oder eine Promise, wenn ohne Argument aufgerufen.\n\nSendet die Anfrage im nächsten Tick und übergibt das Ergebnis an `fn(err, response, output)`:\n\n- `response`: der anhand seines `Content-Type` geparste Body (JSON, auch für `text/plain`; URL-codiert; XML über den HTML-Parser; andere Bodies werden als JSON geparst, wenn sie wie JSON aussehen). Ein leerer Body ergibt ein leeres Objekt; eine `204`-Antwort ergibt `true`.\n- `output`: `status`, `headers`, `response` (der rohe Body), `hostname`, `origin`, `cookies` (mit `cook()`) und `output.cookie(name)`, das ein Cookie der Antwort liest.\n- `err`: der Netzwerkfehler oder `'408: Request Timeout'`; ein `ErrorBuilder`, wenn der Body ein Total.js-Fehler-Array ist (`[{ error: '...' }]`, `response` ist dann `null`); sonst, bei einem Status von `400` oder mehr, ein `ErrorBuilder` mit einem Fehler, dessen Name der Statuscode und dessen Meldung der rohe Body ist. Ein mit `builder.error()` gesetzter Wert ersetzt jeden Fehler.\n\n`fn` kann auch das `$` einer Aktion sein: Die geparste Antwort wird an `$.callback()` übergeben, und ein Fehler wird zu den Fehlern von `$` hinzugefügt. Ohne Argument gibt es eine Promise zurück, die mit `response` erfüllt und mit `err` abgelehnt wird.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) {\n\tif (err)\n\t\treturn console.log(err);\n\tconsole.log(output.status, response.length);\n});\n```\n\nExample: In einer Action\n```js\nNEWACTION('Products/sync', {\n\tname: 'Sync products',\n\taction: function($) {\n\t\tRESTBuilder.GET(CONF.shopapi + '/products/').callback($);\n\t}\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 |  | Das `$` einer Aktion. |\n\nReturns: `Promise` Wird mit der geparsten Antwort aufgelöst.\n\nDie Promise wird mit der geparsten Antwort aufgelöst. Bei einem Fehler wird sie mit einem aus dem Fehler erzeugten `Error` abgelehnt (ein `ErrorBuilder` wird zu einem `Error` mit seinen Meldungen). Mit `$` geht der Fehler stattdessen an `$.invalid()`, und die Promise wird nicht abgelehnt.\n\nExample: await\n```js\nvar user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();\n```\n\nExample: Mit $\n```js\nvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\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` Derselbe Builder, für Verkettung.\n\nSendet die Anfrage sofort und ruft `callback(err, response, output)` mit denselben Werten wie `callback()` auf. Bevorzuge `callback()`, das auf den nächsten Tick wartet. Wird `callback` weggelassen, wird das Ergebnis ignoriert.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nGibt die Antwort als Stream zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nSendet die Anfrage im nächsten Tick und ruft `callback(err, response)` auf, sobald die Header eintreffen. `response` hat `status`, `headers`, `origin` und `stream` (die Node.js-Antwort, noch nicht gelesen). Verwende es für große Dateien.\n\nExample: Eine große Datei speichern\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (!err && response.status === 200)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### builder.error(value)\n\nType: `method` · Since: `0.0.16`\n\nErsetzt jeden Fehler durch deinen eigenen Wert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String` | yes |  | Der zurückzugebende Fehler, zum Beispiel eine Meldung oder ein `ErrorBuilder`. |\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nWenn die Anfrage mit irgendeinem Fehler endet (Netzwerk, Timeout oder ein Status von `400` oder mehr), erhält der Callback oder die Promise stattdessen `value`. Verwende es, um die Details eines entfernten Dienstes vor deinen Benutzern zu verbergen.\n\nExample: Eigener Fehler\n```js\nRESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);\n```\n\n### builder.logerror()\n\nType: `method` · Since: `0.0.16`\n\nGibt Fehler in der Konsole aus.\n\nReturns: `RESTBuilder` Derselbe Builder, für Verkettung.\n\nWenn die Anfrage mit einem Fehler endet, wird der Fehler (oder der rohe Body der Antwort) an den Fehler-Handler des Frameworks übergeben, der ihn mit dem Namen `RESTBuilder` und der Methode und URL der Anfrage ausgibt. Der Callback erhält den Fehler trotzdem.\n\nExample: Fehler protokollieren\n```js\nRESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"AJAX()","signature":"AJAX('METHOD url', [data], [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"Total.download()","signature":"Total.download(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"class","name":"RESTBuilder","signature":"new RESTBuilder([url])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","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.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"builder.compress()","signature":"builder.compress([value])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","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.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])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, [type])","since":"","deprecated":false},{"type":"method","name":"builder.text()","signature":"builder.text(value)","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","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(ext)","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([value])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive([val])","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.insecure()","signature":"builder.insecure()","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt(key)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.base64()","signature":"builder.base64()","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.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(value)","since":"0.0.16","deprecated":false},{"type":"method","name":"builder.logerror()","signature":"builder.logerror()","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwtJ1cx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/http-requests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Peticiones HTTP","summary":"RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() y Total.download().","markdown":"---\ntitle: Peticiones HTTP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/http-requests/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Peticiones HTTP\n\n> RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() y Total.download().\n\nLas funciones globales y la clase `RESTBuilder` para peticiones HTTP a otros servicios. Para una introducción con ejemplos, lee la guía [Peticiones HTTP](../../guides/http-requests/). El cliente WebSocket `OPENCLIENT()` tiene su propia página: [OpenClient](../openclient/).\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nEnvía una petición HTTP con control total de las opciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.url` | `String` | yes |  | La URL de la petición. Las credenciales de la URL (`https://user:password@host/`) se envían como `Authorization: Basic`; antes se decodifican los caracteres codificados con porcentaje que contengan. |\n| `options.method` | `String` | no | `'GET'` | El método HTTP en mayúsculas. |\n| `options.headers` | `Object` | no |  | Cabeceras de la petición. El objeto se copia, así que tu objeto no cambia. |\n| `options.type` | `String` | no |  | Establece `Content-Type`: `'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'` o `'text'`, `'raw'` (`application/octet-stream`). |\n| `options.body` | `String|Buffer` | no |  | El cuerpo de la petición. Un string se envía como UTF-8; `Content-Length` se establece por ti. |\n| `options.query` | `Object|String` | no |  | Se añade a la URL como query string. |\n| `options.cookies` | `Object` | no |  | Cookies que se envían, como `{ name: value }`. |\n| `options.cook` | `Boolean` | no |  | Guarda las cookies de la respuesta en `options.cookies`, de modo que el mismo objeto de opciones las envía con la siguiente petición. |\n| `options.timeout` | `Number` | no | `8000` | Tiempo de espera en milisegundos; `0` lo desactiva. |\n| `options.encoding` | `String` | no | `'utf8'` | Codificación de un cuerpo de texto. `'binary'` devuelve un `Buffer`. |\n| `options.xhr` | `Boolean` | no |  | Añade `X-Requested-With: XMLHttpRequest`. |\n| `options.files` | `Array` | no |  | Archivos para una petición `multipart/form-data`: `[{ name, filename, buffer \\| path \\| url }]`. En ese caso `options.body` es un objeto con campos de formulario adicionales. |\n| `options.compress` | `String` | no |  | Comprime el cuerpo: `'gzip'` o `'deflate'`, y establece `Content-Encoding`. |\n| `options.encrypt` | `String` | no |  | Una clave: el cuerpo se cifra con ella y la respuesta de texto se descifra con ella. |\n| `options.writer` | `Function` | no |  | `function(req)` escribe el cuerpo por sí misma: recibe la petición de Node.js, escribe los datos y llama a `req.end()`. En ese caso no se usan `body` ni `files`. |\n| `options.custom` | `Boolean` | no |  | Devuelve `response.stream` en lugar de leer el cuerpo. |\n| `options.noredirect` | `Boolean` | no |  | No sigue las redirecciones; el callback recibe la respuesta `301`/`302`. |\n| `options.keepalive` | `Boolean` | no |  | Usa un agente keep-alive compartido (uno para HTTP y otro para HTTPS). |\n| `options.resolve` | `Boolean` | no |  | Resuelve el hostname con una caché de DNS. `options.dnscache` hace lo mismo. Se omite para `localhost` y las direcciones IP. |\n| `options.proxy` | `String` | no |  | Un proxy para esta petición, como `'host:port'` o `'http://host:port'`. Con `http://user:password@host:port` las credenciales se envían como `Proxy-Authorization: Basic`. |\n| `options.insecure` | `Boolean` | no |  | Acepta certificados TLS no válidos o autofirmados. |\n| `options.key` | `Buffer` | no |  | Clave TLS del cliente. |\n| `options.cert` | `Buffer` | no |  | Certificado TLS del cliente. |\n| `options.dhparam` | `Buffer` | no |  | Parámetros Diffie-Hellman de TLS. |\n| `options.unixsocket` | `Object` | no |  | `{ socket, path }` para enviar la petición a través de un socket Unix en lugar de `url`. |\n| `options.ondata` | `Function` | no |  | `function(chunk, percentage)` para cada fragmento recibido. |\n| `options.onprogress` | `Function` | no |  | `function(percentage)`; el porcentaje solo se conoce con `Content-Length`. |\n| `options.callback` | `Function` | no |  | `function(err, response)`, en lugar del segundo argumento. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Una promesa cuando no se indica callback; si no, nada.\n\nEnvía una petición HTTP descrita por `options`. El callback recibe `(err, response)`; sin callback (en el argumento o en `options.callback`) devuelve una promesa que se resuelve con `response`.\n\nEl objeto de respuesta tiene `status`, `headers`, `body`, `host`, `origin` (las direcciones IP resueltas cuando la caché de DNS está activada) y `cookies` (las cookies recogidas en las redirecciones). `body` es un string para los tipos `text/*` y `application/*` (decodificado con `encoding`) y un `Buffer` para los demás tipos, o siempre un `Buffer` con `encoding: 'binary'`. El cuerpo no se parsea: usa `RESTBuilder` o `AJAX()` para eso.\n\nCon `custom: true` el callback se ejecuta en cuanto llegan las cabeceras y la respuesta tiene `stream` (la respuesta de Node.js) en lugar de `body`.\n\nErrores: un error de red pasa el objeto de error con `response.status === 0`; un tiempo de espera agotado pasa `'408: Request Timeout'` con `response.status === 408`; más de cuatro redirecciones pasan `'Too many redirects'`; una URL sin hostname pasa `'Invalid hostname'`, y un string que no es una URL lanza `TypeError: Invalid URL`. Un código de estado de `400` o superior no es un error: comprueba `response.status`.\n\nSe siguen las redirecciones `301` y `302` (las cookies de la redirección se envían a la siguiente ubicación). Las peticiones usan el proxy de la clave de configuración `$proxyrequest` cuando está establecida, excepto para `localhost`, `127.0.0.1` y `0.0.0.0`.\n\nExample: POST JSON\n```js\nREQUEST({\n\turl: 'https://api.example.com/orders/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ id: 'p100', count: 2 })\n}, function(err, response) {\n\tif (err || response.status !== 200)\n\t\treturn;\n\tvar order = response.body.parseJSON();\n});\n```\n\nExample: Con una promesa\n```js\nvar response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });\nconsole.log(response.status, response.body);\n```\n\nExample: Subir un archivo\n```js\nREQUEST({\n\turl: 'https://files.example.com/upload/',\n\tmethod: 'POST',\n\tfiles: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],\n\tbody: { folder: 'reports' }\n}, console.log);\n```\n\nExample: Leer un stream\n```js\nREQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));\n});\n```\n\nExample: Escribir el cuerpo tú mismo\n```js\nREQUEST({\n\turl: 'https://api.example.com/import/',\n\tmethod: 'POST',\n\ttype: 'plain',\n\twriter: function(req) {\n\t\tfor (var line of lines)\n\t\t\treq.write(line + '\\n');\n\t\treq.end();\n\t}\n}, console.log);\n```\n\n### AJAX('METHOD url', [data], [callback])\n\nType: `method`\n\nEnvía una petición JSON y devuelve la respuesta analizada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `'METHOD url'`, por ejemplo `'POST https://example.com/api/'`. |\n| `data` | `Object` | no |  | Datos enviados como JSON. |\n| `callback` | `Function` | no |  | `function(err, response, meta)`. |\n\nReturns: `Promise` Una promesa cuando no se indica callback.\n\nEnvía una petición y parsea la respuesta. El primer argumento es el método y la URL separados por un espacio; sin método es `GET`. `data` se envía como cuerpo JSON. Siempre se añade la cabecera `X-Requested-With: XMLHttpRequest`.\n\nLa respuesta se parsea según su `Content-Type`: JSON (`application/json`, `text/json`), los datos URL-encoded y XML (`application/xml`, `text/xml`) se convierten en objetos; los demás tipos se devuelven como el cuerpo en bruto. Un documento XML se convierte en un objeto plano: los nombres de los elementos anidados se unen con `_` (`order_name`), los elementos repetidos dan un array, y los atributos de un elemento están en un objeto bajo su nombre con `__` (`order__`). Un cuerpo XML vacío da `{}`. El callback recibe `(err, response, meta)`, donde `meta` tiene `status`, `headers` y `host`.\n\nPara un estado de `400` o más, `err` es el cuerpo parseado (en un servicio Total.js, el array de errores) y `response` es `null`. Sin callback la función devuelve una promesa que se resuelve con el cuerpo parseado y se rechaza con `err`; un array de errores de Total.js se convierte en un `Error` cuyo mensaje contiene los mensajes de error.\n\nExample: Callback\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {\n\tconsole.log(meta.status, response);\n});\n```\n\nExample: Promesa\n```js\nvar products = await AJAX('GET https://api.example.com/products/?page=1');\n```\n\nExample: Respuesta XML\n```js\n// the service answers <order id=\"100\"><name>Book</name><items><item>A</item><item>B</item></items></order>\nvar order = await AJAX('GET https://api.example.com/orders/100/');\n// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nDescarga un archivo remoto en el disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | La URL, o `{ socket, path }` para un socket Unix. |\n| `filename` | `String` | yes |  | La ruta del archivo de destino. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout en milisegundos. |\n\nReturns: `Promise` Una promesa cuando no se indica callback.\n\nDescarga `url` y escribe el cuerpo en `filename`. El callback se ejecuta cuando el archivo está escrito, con `(err, response)`. `response` tiene `status`, `headers`, `origin`, `filename` y `size` (el número de bytes escritos). El cuerpo se guarda para cualquier código de estado, así que comprueba `response.status`.\n\n`url` también puede ser un objeto `{ socket, path }` para un socket Unix. Las consultas DNS se guardan en caché. `timeout` está en milisegundos (8 segundos si no se establece). Sin callback la función devuelve una promesa que se resuelve con `response`.\n\nExample: Descargar una imagen\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.filename);\n});\n```\n\nExample: Promesa\n```js\nvar response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));\n```\n\n### Total.download(url, filename, [callback], [timeout])\n\nType: `method`\n\nEl método del framework que hay detrás de DOWNLOAD().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | La URL, o `{ socket, path }` para un socket Unix. |\n| `filename` | `String` | yes |  | La ruta del archivo de destino. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout en milisegundos. |\n\nReturns: `Promise` Una promesa cuando no se indica callback.\n\nLa misma función que `DOWNLOAD()`. Descarga `url` y escribe el cuerpo en `filename`. El callback se ejecuta cuando el archivo está escrito, con `(err, response)`. `response` tiene `status`, `headers`, `origin`, `filename` y `size` (el número de bytes escritos). El cuerpo se guarda para cualquier código de estado, así que comprueba `response.status`.\n\n`url` también puede ser un objeto `{ socket, path }` para un socket Unix. Las consultas DNS se guardan en caché. `timeout` está en milisegundos (8 segundos si no se establece). Sin callback la función devuelve una promesa que se resuelve con `response`.\n\nExample: Descargar\n```js\nTotal.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n### new RESTBuilder([url])\n\nType: `class`\n\nUn builder para peticiones a servicios REST.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | La URL de la petición. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nUna clase global. Un builder nuevo tiene el método `GET`, un tiempo de espera de 10 segundos, la caché de DNS activada, la cabecera `user-agent: Total.js/v...` y `accept: application/json, text/plain, text/plain, text/xml`. No se envía nada hasta que llamas a `callback()`, `promise()`, `stream()` o `exec()`.\n\nNormalmente empiezas con un helper estático: `RESTBuilder.GET()`, `POST()`, `PUT()`, `PATCH()`, `DELETE()`, `HEAD()`, `API()`, `url()` o `make()`. `RESTBuilder.url(url)` es lo mismo que `new RESTBuilder(url)`.\n\nExample: Crear un builder\n```js\nvar builder = RESTBuilder.url('https://api.example.com/users/');\nbuilder.header('X-Token', CONF.apitoken);\nbuilder.callback(console.log);\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nCrea un builder 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\nCrea un builder sin URL y llama a `fn(builder)`. Asigna la URL con `builder.url()`. El método de instancia `builder.make(fn)` llama a `fn` con el builder como `this` y como argumento, para configuraciones reutilizables.\n\nExample: Construir una petición\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.post({ name: 'Peter' });\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nCrea una petición GET.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL. |\n| `data` | `Object` | no |  | Se envía como query string. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nCrea un builder con el método `GET`; `data` se convierte en el query string. Para una petición `HEAD` usa `RESTBuilder.HEAD(url)`: no tiene datos, el valor analizado es un objeto vacío y lees `output.status` y `output.headers`.\n\nExample: Query string\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nExample: HEAD\n```js\nRESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers['last-modified']);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nCrea una petición POST.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL. |\n| `data` | `Object` | no |  | Se envía como cuerpo JSON. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nCrea un builder con el método `POST`; `data` se envía como JSON. `RESTBuilder.PUT()`, `RESTBuilder.PATCH()` y `RESTBuilder.DELETE()` funcionan igual con sus métodos.\n\nExample: POST JSON\n```js\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {\n\tconsole.log(order.id);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nCrea una petición PUT.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL. |\n| `data` | `Object` | no |  | Se envía como cuerpo JSON. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nCrea un builder con el método `PUT`; `data` se envía como JSON.\n\nExample: PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nCrea una petición PATCH.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL. |\n| `data` | `Object` | no |  | Se envía como cuerpo JSON. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nCrea un builder con el método `PATCH`; `data` se envía como JSON.\n\nExample: PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nCrea una petición DELETE.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL. |\n| `data` | `Object` | no |  | Se envía como cuerpo JSON. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nCrea un builder con el método `DELETE`; `data` se envía como JSON.\n\nExample: DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nLlama a un endpoint API de una aplicación Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL del endpoint API. |\n| `name` | `String` | yes |  | El nombre de la operación API. |\n| `data` | `Object` | no |  | Los datos de la operación. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nCrea una petición `POST` para una ruta API de Total.js (`ROUTE('API /api/ ...')`). El cuerpo es JSON: `{ schema: name, data: data }`. `name` es el nombre de la API con parámetros opcionales, por ejemplo `'products_detail/p100'`. `builder.get(query)` mantiene el `POST` y envía la query en el cuerpo como `query`, junto a `data`. `builder.compress()` omite las claves del cuerpo cuyo valor es `null` o `undefined`.\n\nExample: Llamar a una API\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Con una query\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n### builder.compress([value])\n\nType: `method`\n\nOmite los valores vacíos del cuerpo de una petición RESTBuilder.API().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` lo desactiva. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nSin argumento o con `true`, el cuerpo JSON de una petición `RESTBuilder.API()` se escribe sin las claves cuyo valor es `null` o `undefined`, así la petición es más pequeña. `compress(false)` lo desactiva. No afecta a los demás builders.\n\nExample: Cuerpo más pequeño\n```js\nRESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);\n// data: { id: 'A1', total: 120 }\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nRegistra una función que modifica cada builder antes de enviarlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nLa función se ejecuta para cada builder de la aplicación justo antes de hacer la petición, con el builder como argumento. Úsala para cabeceras o tokens compartidos. Las mejoras registradas no se pueden eliminar.\n\nExample: Añadir un token a un servicio\n```js\nRESTBuilder.upgrade(function(builder) {\n\tif (builder.url().startsWith(CONF.shopapi))\n\t\tbuilder.header('X-Token', CONF.shoptoken);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nAsigna o lee la URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | La nueva URL. |\n\nReturns: `RESTBuilder|String` El builder, o la URL cuando se llama sin argumento.\n\nCon un argumento, asigna la URL y devuelve el builder; sin él, devuelve la URL actual.\n\nExample: Leer la URL\n```js\nvar url = builder.url();\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 |  | El método HTTP. |\n| `data` | `Object` | no |  | Datos que se envían como JSON. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nAsigna el método (las minúsculas se convierten a mayúsculas). `data` se envía como JSON.\n\nAtajos: `builder.get([query])` asigna `GET` y el query string; `builder.post([data])`, `builder.put([data])`, `builder.patch([data])` y `builder.delete([data])` asignan el método y el cuerpo (en el tipo asignado antes, JSON por defecto); `builder.head()` asigna `HEAD`. Los nombres en mayúsculas (`builder.POST()`) son alias.\n\nExample: Atajos\n```js\nRESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);\n```\n\n### builder.json([data])\n\nType: `method`\n\nEnvía datos como JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Los datos. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nAsigna el tipo JSON y el cuerpo `data` (un objeto se serializa al enviar la petición). Una petición `GET` pasa a ser `POST`.\n\nExample: Cuerpo JSON\n```js\nRESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nEnvía datos como formulario codificado como URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Los campos del formulario. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nAsigna `Content-Type: application/x-www-form-urlencoded` y el cuerpo; un objeto se codifica al enviar la petición. Una petición `GET` pasa a ser `POST`.\n\nExample: Formulario\n```js\nRESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);\n```\n\n### builder.xml([data])\n\nType: `method`\n\nEnvía un cuerpo XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | El XML. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nAsigna `Content-Type: text/xml` y el cuerpo. Pasa el XML como string. Una petición `GET` pasa a ser `POST`.\n\nExample: Cuerpo XML\n```js\nRESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);\n```\n\n### builder.raw(value, [type])\n\nType: `method`\n\nAsigna el cuerpo tal cual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | El cuerpo. |\n| `type` | `String` | no |  | El tipo de contenido corto. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nAsigna el cuerpo sin ninguna serialización. `type` es uno de los tipos cortos de `REQUEST()` (`'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'`, `'raw'`); sin él, asigna la cabecera con `builder.type()`. Un string se envía sin cambios. Un `Buffer` necesita el tipo `'raw'` (`application/octet-stream`); sin tipo, se serializa como JSON igual que un objeto.\n\nExample: Cuerpo binario\n```js\nRESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.text(value)\n\nType: `method`\n\nEnvía texto plano y deja la respuesta sin analizar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El texto. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\n`builder.plain(value)` es un alias. Asigna `Content-Type: text/plain` y el cuerpo, y el callback recibe el cuerpo de la respuesta sin procesar en lugar de un valor analizado.\n\nExample: Texto plano\n```js\nRESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {\n\t// response is the raw body\n});\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nAñade un archivo y envía una petición multipart.\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 que se envía al servicio. |\n| `source` | `Buffer|String` | no |  | Un buffer, una ruta o una URL. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nLa petición pasa a ser `multipart/form-data` (un `GET` pasa a ser `POST`). `source` es un `Buffer`, una ruta en el disco o una URL que se descarga y se envía como stream. Sin `source`, el archivo se lee de `filename`. El cuerpo asignado con `json()` o `urlencoded()` se envía como campos adicionales del formulario cuando es un objeto.\n\nExample: Subir dos archivos\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))\n\t.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')\n\t.callback(console.log);\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 mismo builder, para encadenar.\n\nAsigna una cabecera. Funciones auxiliares para cabeceras comunes: `builder.referrer(url)` (alias `referer()`) asigna `Referer`, `builder.origin(url)` asigna `Origin`, `builder.csrf(token)` asigna `X-Csrf-Token` y `builder.xhr()` añade `X-Requested-With: XMLHttpRequest`.\n\nExample: Cabeceras\n```js\nbuilder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();\n```\n\n### builder.type(value)\n\nType: `method`\n\nAsigna la cabecera Content-Type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El tipo MIME. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nAsigna a `Content-Type` un tipo MIME completo. Un tipo asignado por `json()`, `urlencoded()`, `xml()` o `text()` lo sustituye, así que úsalo con `raw(value)`.\n\nExample: Tipo personalizado\n```js\nbuilder.raw('{\"id\":1}').type('application/vnd.api+json');\n```\n\n### builder.accept(ext)\n\nType: `method`\n\nAsigna la cabecera Accept.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Una extensión o un tipo MIME. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nRecibe una extensión de archivo (`'json'`, `'xml'`, `'html'`...) y la convierte en su tipo MIME; un valor más largo se usa tal cual.\n\nExample: Aceptar XML\n```js\nbuilder.accept('xml');\n```\n\n### builder.auth(user, [password])\n\nType: `method`\n\nAsigna 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 mismo builder, para encadenar.\n\nCon `user` y `password`, asigna autenticación básica (`Basic base64(user:password)`). Con un solo argumento, el valor se usa tal cual, por ejemplo `'Bearer TOKEN'`.\n\nExample: Basic y Bearer\n```js\nbuilder.auth('admin', 'secret');\nbuilder.auth('Bearer ' + CONF.apitoken);\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 de la cookie. |\n| `value` | `String` | yes |  | El valor. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nAñade una cookie. `builder.cookies(obj)` sustituye todas las cookies por un objeto `{ name: value }`.\n\nExample: Cookies\n```js\nbuilder.cookie('session', token);\nbuilder.cookies({ lang: 'en', theme: 'dark' });\n```\n\n### builder.cook([value])\n\nType: `method`\n\nGuarda en el builder las cookies de la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` lo desactiva. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nCon `cook()`, las cookies que asigna la respuesta se guardan en el builder y se envían en la siguiente petición que haga el mismo builder. En ese caso, `output.cookies` las contiene. `cook(false)` lo desactiva.\n\nExample: Iniciar sesión y luego leer\n```js\nRESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {\n\tRESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);\n});\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 |  | Milisegundos. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nEl timeout en milisegundos (10000 por defecto). `0` lo desactiva. Cuando vence, el error es `408: Request Timeout`.\n\nExample: Cinco segundos\n```js\nbuilder.timeout(5000);\n```\n\n### builder.keepalive([val])\n\nType: `method`\n\nReutiliza las conexiones con un agente keep-alive.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `val` | `Boolean` | no | `true` | Activa o desactiva keep-alive. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nSin argumento (o con un valor verdadero), la petición usa el agente keep-alive compartido del framework, de modo que se reutilizan las conexiones al mismo host. `keepalive(false)` lo desactiva. No se usa junto con un proxy.\n\nExample: Keep-alive\n```js\nRESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nEnvía la petición a través de un proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | El proxy. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\n`url` es `'host:port'` o `'http://host:port'`. Con `http://user:password@host:port` las credenciales se envían como `Proxy-Authorization: Basic`. Los destinos HTTPS se tunelizan con `CONNECT`. Sin él, se usa el proxy de la clave de configuración `$proxyrequest` cuando está definida.\n\nExample: Proxy\n```js\nbuilder.proxy('http://10.0.0.5:3128');\n```\n\nExample: Proxy con usuario y contraseña\n```js\nbuilder.proxy('http://user:secret@10.0.0.5:3128');\n```\n\n### builder.insecure()\n\nType: `method`\n\nAcepta certificados TLS no válidos.\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nAcepta certificados autofirmados o caducados del servicio. Úsalo solo para servicios internos.\n\nExample: Autofirmado\n```js\nRESTBuilder.GET('https://10.0.0.20/api/').insecure().callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nAsigna 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 mismo builder, para encadenar.\n\nPara servicios que exigen certificados de cliente.\n\nExample: Certificado de cliente\n```js\nbuilder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nEnvía la petición a través de un socket Unix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | El archivo de socket. |\n| `path` | `String` | yes |  | La ruta de la petición, por ejemplo `/api/`. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nSe conecta al archivo de socket en lugar de a un host; `path` es la ruta URL de la petición.\n\nExample: API de Docker\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/docker.sock', '/containers/json');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nDesactiva la caché DNS para esta petición.\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nPor defecto, el builder resuelve el nombre de host una vez y guarda sus direcciones en caché. Con `nodnscache()`, Node.js lo resuelve en cada petición.\n\nExample: Sin caché DNS\n```js\nbuilder.nodnscache();\n```\n\n### builder.redirect(value)\n\nType: `method`\n\nActiva o desactiva el seguimiento de redirecciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | yes |  | `false` deja de seguir las redirecciones. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\n`redirect(false)` devuelve la propia respuesta `301` o `302`; lee el destino en `output.headers.location`. Por defecto se siguen hasta cuatro redirecciones.\n\nExample: Leer la ubicación\n```js\nRESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers.location);\n});\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` | yes |  | La clave de cifrado. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nEl cuerpo se cifra con `key` y se envía con la cabecera `X-Encryption: a`; una respuesta de texto se descifra con la misma clave. Ambas partes deben usar la misma clave.\n\nExample: Llamada cifrada\n```js\nbuilder.encrypt(CONF.sharedkey);\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 mismo builder, para encadenar.\n\nLlama a `fn(percentage)` para cada fragmento recibido. El porcentaje solo se conoce cuando la respuesta tiene `Content-Length`; si no, es `0`.\n\nExample: Progreso\n```js\nbuilder.progress(function(percentage) {\n\tconsole.log(percentage.toFixed(1) + '%');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nDevuelve el cuerpo de la respuesta sin procesar.\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nEl callback recibe el cuerpo como string (o un `Buffer` para los tipos binarios) en lugar de un valor analizado.\n\nExample: HTML sin procesar\n```js\nRESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {\n\tconsole.log(html.length);\n});\n```\n\n### builder.base64()\n\nType: `method`\n\nDevuelve el cuerpo de la respuesta en base64.\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nEl callback recibe el cuerpo codificado en base64, por ejemplo para incrustar una imagen como data URI.\n\nExample: Data URI\n```js\nRESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {\n\tvar uri = 'data:image/png;base64,' + data;\n});\n```\n\n### builder.debug()\n\nType: `method`\n\nImprime la petición y la respuesta en la consola.\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nCuando llega la respuesta, imprime el estado, el método, la URL con el query, el error y el cuerpo sin procesar.\n\nExample: Depuración\n```js\nRESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nEnvía la petición y recibe la respuesta analizada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)` o el `$` de una acción. |\n\nReturns: `RESTBuilder|Promise` El builder, o una promesa cuando se llama sin argumento.\n\nEnvía la petición en el siguiente tick y pasa el resultado a `fn(err, response, output)`:\n\n- `response`: el cuerpo parseado según su `Content-Type` (JSON, también para `text/plain`; URL-encoded; XML mediante el parser de HTML; los demás cuerpos se parsean como JSON cuando parecen JSON). Un cuerpo vacío da un objeto vacío; una respuesta `204` da `true`.\n- `output`: `status`, `headers`, `response` (el cuerpo en bruto), `hostname`, `origin`, `cookies` (con `cook()`) y `output.cookie(name)`, que lee una cookie de la respuesta.\n- `err`: el error de red o `'408: Request Timeout'`; un `ErrorBuilder` cuando el cuerpo es un array de errores de Total.js (`[{ error: '...' }]`, y entonces `response` es `null`); en otro caso, para un estado de `400` o más, un `ErrorBuilder` con un error cuyo nombre es el código de estado y cuyo mensaje es el cuerpo en bruto. Un valor establecido con `builder.error()` sustituye cualquier error.\n\n`fn` también puede ser el `$` de una acción: la respuesta parseada se pasa a `$.callback()` y un error se añade a los errores de `$`. Sin argumento devuelve una promesa que se resuelve con `response` y se rechaza con `err`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) {\n\tif (err)\n\t\treturn console.log(err);\n\tconsole.log(output.status, response.length);\n});\n```\n\nExample: En una acción\n```js\nNEWACTION('Products/sync', {\n\tname: 'Sync products',\n\taction: function($) {\n\t\tRESTBuilder.GET(CONF.shopapi + '/products/').callback($);\n\t}\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 |  | El `$` de una acción. |\n\nReturns: `Promise` Se resuelve con la respuesta analizada.\n\nLa promesa se resuelve con la respuesta analizada. Ante un error, se rechaza con un `Error` creado a partir del error (un `ErrorBuilder` se convierte en un `Error` con sus mensajes). Con `$`, el error va a `$.invalid()` y la promesa no se rechaza.\n\nExample: await\n```js\nvar user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();\n```\n\nExample: Con $\n```js\nvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\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 mismo builder, para encadenar.\n\nEnvía la petición de inmediato y llama a `callback(err, response, output)` con los mismos valores que `callback()`. Es preferible `callback()`, que espera al siguiente tick. Si se omite `callback`, el resultado se ignora.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nDevuelve la respuesta como stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nEnvía la petición en el siguiente tick y llama a `callback(err, response)` en cuanto llegan las cabeceras. `response` tiene `status`, `headers`, `origin` y `stream` (la respuesta de Node.js, todavía sin leer). Úsalo para archivos grandes.\n\nExample: Guardar un archivo grande\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (!err && response.status === 200)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### builder.error(value)\n\nType: `method` · Since: `0.0.16`\n\nSustituye cualquier error por tu propio valor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String` | yes |  | El error que se devuelve, por ejemplo un mensaje o un `ErrorBuilder`. |\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nCuando la petición termina con cualquier error (de red, de tiempo de espera o un estado de `400` o más), el callback o la promesa recibe `value` en su lugar. Úsalo para ocultar a tus usuarios los detalles de un servicio remoto.\n\nExample: Error propio\n```js\nRESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);\n```\n\n### builder.logerror()\n\nType: `method` · Since: `0.0.16`\n\nImprime los errores en la consola.\n\nReturns: `RESTBuilder` El mismo builder, para encadenar.\n\nCuando la petición termina con un error, el error (o el cuerpo en bruto de la respuesta) se pasa al manejador de errores del framework, que lo imprime con el nombre `RESTBuilder` y el método y la URL de la petición. El callback sigue recibiendo el error.\n\nExample: Registrar errores\n```js\nRESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"AJAX()","signature":"AJAX('METHOD url', [data], [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"Total.download()","signature":"Total.download(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"class","name":"RESTBuilder","signature":"new RESTBuilder([url])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","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.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"builder.compress()","signature":"builder.compress([value])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","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.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])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, [type])","since":"","deprecated":false},{"type":"method","name":"builder.text()","signature":"builder.text(value)","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","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(ext)","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([value])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive([val])","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.insecure()","signature":"builder.insecure()","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt(key)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.base64()","signature":"builder.base64()","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.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(value)","since":"0.0.16","deprecated":false},{"type":"method","name":"builder.logerror()","signature":"builder.logerror()","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwtJ1cx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/http-requests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Requêtes HTTP","summary":"RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() et Total.download().","markdown":"---\ntitle: \"Requêtes HTTP\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/http-requests/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Requêtes HTTP\n\n> RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() et Total.download().\n\nLes fonctions globales et la classe `RESTBuilder` pour les requêtes HTTP vers d'autres services. Pour une introduction avec des exemples, lis le guide [Requêtes HTTP](../../guides/http-requests/). Le client WebSocket `OPENCLIENT()` a sa propre page : [OpenClient](../openclient/).\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nEnvoie une requête HTTP avec un contrôle total des options.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.url` | `String` | yes |  | L'URL de la requête. Les identifiants dans l'URL (`https://user:password@host/`) sont envoyés comme `Authorization: Basic` ; les caractères encodés en pourcentage qu'ils contiennent sont d'abord décodés. |\n| `options.method` | `String` | no | `'GET'` | La méthode HTTP en majuscules. |\n| `options.headers` | `Object` | no |  | En-têtes de la requête. L'objet est copié, ton objet n'est donc pas modifié. |\n| `options.type` | `String` | no |  | Définit `Content-Type` : `'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'` ou `'text'`, `'raw'` (`application/octet-stream`). |\n| `options.body` | `String|Buffer` | no |  | Le corps de la requête. Une chaîne est envoyée en UTF-8 ; `Content-Length` est défini pour toi. |\n| `options.query` | `Object|String` | no |  | Ajouté à l'URL comme query string. |\n| `options.cookies` | `Object` | no |  | Cookies à envoyer, sous la forme `{ name: value }`. |\n| `options.cook` | `Boolean` | no |  | Stocke les cookies de la réponse dans `options.cookies`, de sorte que le même objet d'options les envoie avec la requête suivante. |\n| `options.timeout` | `Number` | no | `8000` | Délai en millisecondes ; `0` le désactive. |\n| `options.encoding` | `String` | no | `'utf8'` | Encodage d'un corps texte. `'binary'` renvoie un `Buffer`. |\n| `options.xhr` | `Boolean` | no |  | Ajoute `X-Requested-With: XMLHttpRequest`. |\n| `options.files` | `Array` | no |  | Fichiers pour une requête `multipart/form-data` : `[{ name, filename, buffer \\| path \\| url }]`. `options.body` est alors un objet de champs de formulaire supplémentaires. |\n| `options.compress` | `String` | no |  | Compresse le corps : `'gzip'` ou `'deflate'`, et définit `Content-Encoding`. |\n| `options.encrypt` | `String` | no |  | Une clé : le corps est chiffré avec elle et la réponse texte est déchiffrée avec elle. |\n| `options.writer` | `Function` | no |  | `function(req)` écrit le corps lui-même : elle reçoit la requête Node.js, écrit les données et appelle `req.end()`. `body` et `files` ne sont alors pas utilisés. |\n| `options.custom` | `Boolean` | no |  | Renvoie `response.stream` au lieu de lire le corps. |\n| `options.noredirect` | `Boolean` | no |  | Ne suit pas les redirections ; le callback reçoit la réponse `301`/`302`. |\n| `options.keepalive` | `Boolean` | no |  | Utilise un agent keep-alive partagé (un pour HTTP, un pour HTTPS). |\n| `options.resolve` | `Boolean` | no |  | Résout le nom d'hôte avec un cache DNS. `options.dnscache` fait la même chose. Ignoré pour `localhost` et les adresses IP. |\n| `options.proxy` | `String` | no |  | Un proxy pour cette requête, sous la forme `'host:port'` ou `'http://host:port'`. Avec `http://user:password@host:port`, les identifiants sont envoyés comme `Proxy-Authorization: Basic`. |\n| `options.insecure` | `Boolean` | no |  | Accepte les certificats TLS invalides ou auto-signés. |\n| `options.key` | `Buffer` | no |  | Clé TLS du client. |\n| `options.cert` | `Buffer` | no |  | Certificat TLS du client. |\n| `options.dhparam` | `Buffer` | no |  | Paramètres Diffie-Hellman TLS. |\n| `options.unixsocket` | `Object` | no |  | `{ socket, path }` pour envoyer la requête via un socket Unix au lieu de `url`. |\n| `options.ondata` | `Function` | no |  | `function(chunk, percentage)` pour chaque fragment reçu. |\n| `options.onprogress` | `Function` | no |  | `function(percentage)` ; le pourcentage n'est connu qu'avec `Content-Length`. |\n| `options.callback` | `Function` | no |  | `function(err, response)`, au lieu du deuxième argument. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Une promesse lorsqu'aucun callback n'est fourni ; sinon rien.\n\nEnvoie une requête HTTP décrite par `options`. Le callback reçoit `(err, response)` ; sans callback (en argument ou dans `options.callback`), elle renvoie une promesse résolue avec `response`.\n\nL'objet de réponse contient `status`, `headers`, `body`, `host`, `origin` (les adresses IP résolues lorsque le cache DNS est activé) et `cookies` (les cookies collectés lors des redirections). `body` est une chaîne pour les types `text/*` et `application/*` (décodée avec `encoding`) et un `Buffer` pour les autres types, ou toujours un `Buffer` avec `encoding: 'binary'`. Le corps n'est pas analysé : utilise `RESTBuilder` ou `AJAX()` pour cela.\n\nAvec `custom: true`, le callback s'exécute dès l'arrivée des en-têtes et la réponse contient `stream` (la réponse Node.js) au lieu de `body`.\n\nErreurs : une erreur réseau transmet l'objet d'erreur avec `response.status === 0` ; un délai expiré transmet `'408: Request Timeout'` avec `response.status === 408` ; plus de quatre redirections transmettent `'Too many redirects'` ; une URL sans nom d'hôte transmet `'Invalid hostname'`, et une chaîne qui n'est pas une URL lève `TypeError: Invalid URL`. Un code de statut de `400` ou plus n'est pas une erreur : vérifie `response.status`.\n\nLes redirections `301` et `302` sont suivies (les cookies de la redirection sont envoyés à l'emplacement suivant). Les requêtes utilisent le proxy de la clé de configuration `$proxyrequest` lorsqu'elle est définie, sauf pour `localhost`, `127.0.0.1` et `0.0.0.0`.\n\nExample: POST JSON\n```js\nREQUEST({\n\turl: 'https://api.example.com/orders/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ id: 'p100', count: 2 })\n}, function(err, response) {\n\tif (err || response.status !== 200)\n\t\treturn;\n\tvar order = response.body.parseJSON();\n});\n```\n\nExample: Avec une promesse\n```js\nvar response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });\nconsole.log(response.status, response.body);\n```\n\nExample: Envoyer un fichier\n```js\nREQUEST({\n\turl: 'https://files.example.com/upload/',\n\tmethod: 'POST',\n\tfiles: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],\n\tbody: { folder: 'reports' }\n}, console.log);\n```\n\nExample: Lire un flux\n```js\nREQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));\n});\n```\n\nExample: Écrire le corps toi-même\n```js\nREQUEST({\n\turl: 'https://api.example.com/import/',\n\tmethod: 'POST',\n\ttype: 'plain',\n\twriter: function(req) {\n\t\tfor (var line of lines)\n\t\t\treq.write(line + '\\n');\n\t\treq.end();\n\t}\n}, console.log);\n```\n\n### AJAX('METHOD url', [data], [callback])\n\nType: `method`\n\nEnvoie une requête JSON et renvoie la réponse analysée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `'METHOD url'`, par exemple `'POST https://example.com/api/'`. |\n| `data` | `Object` | no |  | Données envoyées en JSON. |\n| `callback` | `Function` | no |  | `function(err, response, meta)`. |\n\nReturns: `Promise` Une promesse lorsqu'aucun callback n'est fourni.\n\nEnvoie une requête et analyse la réponse. Le premier argument est la méthode et l'URL séparées par une espace ; sans méthode, c'est `GET`. `data` est envoyé comme corps JSON. L'en-tête `X-Requested-With: XMLHttpRequest` est toujours ajouté.\n\nLa réponse est analysée selon son `Content-Type` : le JSON (`application/json`, `text/json`), les données URL-encoded et le XML (`application/xml`, `text/xml`) deviennent des objets ; les autres types sont renvoyés sous forme de corps brut. Un document XML devient un objet plat : les noms des éléments imbriqués sont reliés par `_` (`order_name`), les éléments répétés donnent un tableau, et les attributs d'un élément se trouvent dans un objet sous son nom avec `__` (`order__`). Un corps XML vide donne `{}`. Le callback reçoit `(err, response, meta)` où `meta` contient `status`, `headers` et `host`.\n\nPour un statut de `400` ou plus, `err` est le corps analysé (pour un service Total.js, le tableau d'erreurs) et `response` vaut `null`. Sans callback, la fonction renvoie une promesse résolue avec le corps analysé et rejetée avec `err` ; un tableau d'erreurs Total.js devient une `Error` dont le message contient les messages d'erreur.\n\nExample: Callback\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {\n\tconsole.log(meta.status, response);\n});\n```\n\nExample: Promesse\n```js\nvar products = await AJAX('GET https://api.example.com/products/?page=1');\n```\n\nExample: Réponse XML\n```js\n// the service answers <order id=\"100\"><name>Book</name><items><item>A</item><item>B</item></items></order>\nvar order = await AJAX('GET https://api.example.com/orders/100/');\n// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nTélécharge un fichier distant sur le disque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | L'URL, ou `{ socket, path }` pour un socket Unix. |\n| `filename` | `String` | yes |  | Le chemin du fichier cible. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Délai en millisecondes. |\n\nReturns: `Promise` Une promesse lorsqu'aucun callback n'est fourni.\n\nTélécharge `url` et écrit le corps dans `filename`. Le callback s'exécute une fois le fichier écrit, avec `(err, response)`. `response` contient `status`, `headers`, `origin`, `filename` et `size` (le nombre d'octets écrits). Le corps est enregistré quel que soit le code de statut : vérifie donc `response.status`.\n\n`url` peut aussi être un objet `{ socket, path }` pour un socket Unix. Les résolutions DNS sont mises en cache. `timeout` est en millisecondes (8 secondes s'il n'est pas défini). Sans callback, la fonction renvoie une promesse résolue avec `response`.\n\nExample: Télécharger une image\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.filename);\n});\n```\n\nExample: Promesse\n```js\nvar response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));\n```\n\n### Total.download(url, filename, [callback], [timeout])\n\nType: `method`\n\nLa méthode du framework derrière DOWNLOAD().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | L'URL, ou `{ socket, path }` pour un socket Unix. |\n| `filename` | `String` | yes |  | Le chemin du fichier cible. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Délai en millisecondes. |\n\nReturns: `Promise` Une promesse lorsqu'aucun callback n'est fourni.\n\nLa même fonction que `DOWNLOAD()`. Télécharge `url` et écrit le corps dans `filename`. Le callback s'exécute une fois le fichier écrit, avec `(err, response)`. `response` contient `status`, `headers`, `origin`, `filename` et `size` (le nombre d'octets écrits). Le corps est enregistré quel que soit le code de statut : vérifie donc `response.status`.\n\n`url` peut aussi être un objet `{ socket, path }` pour un socket Unix. Les résolutions DNS sont mises en cache. `timeout` est en millisecondes (8 secondes s'il n'est pas défini). Sans callback, la fonction renvoie une promesse résolue avec `response`.\n\nExample: Télécharger\n```js\nTotal.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n### new RESTBuilder([url])\n\nType: `class`\n\nUn builder pour les requêtes vers des services REST.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | L'URL de la requête. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nUne classe globale. Un nouveau builder a la méthode `GET`, un délai de 10 secondes, le cache DNS activé, l'en-tête `user-agent: Total.js/v...` et `accept: application/json, text/plain, text/plain, text/xml`. Rien n'est envoyé tant que tu n'appelles pas `callback()`, `promise()`, `stream()` ou `exec()`.\n\nEn général, tu commences par un helper statique : `RESTBuilder.GET()`, `POST()`, `PUT()`, `PATCH()`, `DELETE()`, `HEAD()`, `API()`, `url()` ou `make()`. `RESTBuilder.url(url)` équivaut à `new RESTBuilder(url)`.\n\nExample: Créer un builder\n```js\nvar builder = RESTBuilder.url('https://api.example.com/users/');\nbuilder.header('X-Token', CONF.apitoken);\nbuilder.callback(console.log);\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nCrée un builder 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\nCrée un builder sans URL et appelle `fn(builder)`. Définis l'URL avec `builder.url()`. La méthode d'instance `builder.make(fn)` appelle `fn` avec le builder comme `this` et comme argument, pour des réglages réutilisables.\n\nExample: Construire une requête\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.post({ name: 'Peter' });\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nCrée une requête GET.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Envoyé comme query string. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nCrée un builder avec la méthode `GET` ; `data` devient la query string. Pour une requête `HEAD`, utilise `RESTBuilder.HEAD(url)` : elle n'a pas de données, la valeur analysée est un objet vide et tu lis `output.status` et `output.headers`.\n\nExample: Query string\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nExample: HEAD\n```js\nRESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers['last-modified']);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nCrée une requête POST.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Envoyé sous forme de corps JSON. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nCrée un builder avec la méthode `POST` ; `data` est envoyé en JSON. `RESTBuilder.PUT()`, `RESTBuilder.PATCH()` et `RESTBuilder.DELETE()` fonctionnent de la même manière avec leurs méthodes.\n\nExample: POST JSON\n```js\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {\n\tconsole.log(order.id);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nCrée une requête PUT.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Envoyé sous forme de corps JSON. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nCrée un builder avec la méthode `PUT` ; `data` est envoyé en JSON.\n\nExample: PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nCrée une requête PATCH.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Envoyé sous forme de corps JSON. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nCrée un builder avec la méthode `PATCH` ; `data` est envoyé en JSON.\n\nExample: PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nCrée une requête DELETE.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Envoyé sous forme de corps JSON. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nCrée un builder avec la méthode `DELETE` ; `data` est envoyé en JSON.\n\nExample: DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nAppelle un endpoint API d'une application Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL de l'endpoint API. |\n| `name` | `String` | yes |  | Le nom de l'opération API. |\n| `data` | `Object` | no |  | Les données de l'opération. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nCrée une requête `POST` pour une route API Total.js (`ROUTE('API /api/ ...')`). Le corps est du JSON : `{ schema: name, data: data }`. `name` est le nom de l'API avec des paramètres facultatifs, par exemple `'products_detail/p100'`. `builder.get(query)` garde le `POST` et envoie la query dans le corps comme `query`, à côté de `data`. `builder.compress()` omet les clés du corps dont la valeur est `null` ou `undefined`.\n\nExample: Appeler une API\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Avec une query\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n### builder.compress([value])\n\nType: `method`\n\nOmet les valeurs vides du corps d'une requête RESTBuilder.API().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` le désactive. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nSans argument ou avec `true`, le corps JSON d'une requête `RESTBuilder.API()` est écrit sans les clés dont la valeur est `null` ou `undefined`, donc la requête est plus petite. `compress(false)` le désactive. Les autres builders ne sont pas concernés.\n\nExample: Corps plus petit\n```js\nRESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);\n// data: { id: 'A1', total: 120 }\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nEnregistre une fonction qui modifie chaque builder avant son envoi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nLa fonction s'exécute pour chaque builder de l'application juste avant que la requête ne soit effectuée, avec le builder comme argument. Utilise-la pour des en-têtes ou des jetons partagés. Les upgrades ne peuvent pas être retirés.\n\nExample: Ajouter un jeton pour un service\n```js\nRESTBuilder.upgrade(function(builder) {\n\tif (builder.url().startsWith(CONF.shopapi))\n\t\tbuilder.header('X-Token', CONF.shoptoken);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nDéfinit ou lit l'URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | La nouvelle URL. |\n\nReturns: `RESTBuilder|String` Le builder, ou l'URL quand elle est appelée sans argument.\n\nAvec un argument, définit l'URL et renvoie le builder ; sans argument, renvoie l'URL courante.\n\nExample: Lire l'URL\n```js\nvar url = builder.url();\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 |  | La méthode HTTP. |\n| `data` | `Object` | no |  | Données envoyées en JSON. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nDéfinit la méthode (les minuscules sont converties en majuscules). `data` est envoyé en JSON.\n\nRaccourcis : `builder.get([query])` définit `GET` et la query string ; `builder.post([data])`, `builder.put([data])`, `builder.patch([data])` et `builder.delete([data])` définissent la méthode et le corps (dans le type défini auparavant, JSON par défaut) ; `builder.head()` définit `HEAD`. Les noms en majuscules (`builder.POST()`) sont des alias.\n\nExample: Raccourcis\n```js\nRESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);\n```\n\n### builder.json([data])\n\nType: `method`\n\nEnvoie des données en JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Les données. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nDéfinit le type à JSON et le corps à `data` (un objet est sérialisé lors de l'envoi de la requête). Une requête `GET` devient `POST`.\n\nExample: Corps JSON\n```js\nRESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nEnvoie des données sous forme de formulaire encodé pour l'URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Les champs du formulaire. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nDéfinit `Content-Type: application/x-www-form-urlencoded` et le corps ; un objet est encodé lors de l'envoi de la requête. Une requête `GET` devient `POST`.\n\nExample: Formulaire\n```js\nRESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);\n```\n\n### builder.xml([data])\n\nType: `method`\n\nEnvoie un corps XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | Le XML. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nDéfinit `Content-Type: text/xml` et le corps. Passe le XML sous forme de chaîne. Une requête `GET` devient `POST`.\n\nExample: Corps XML\n```js\nRESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);\n```\n\n### builder.raw(value, [type])\n\nType: `method`\n\nDéfinit le corps tel quel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Le corps. |\n| `type` | `String` | no |  | Le type de contenu court. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nDéfinit le corps sans aucune sérialisation. `type` est l'un des types courts de `REQUEST()` (`'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'`, `'raw'`) ; sans lui, définis l'en-tête avec `builder.type()`. Une chaîne est envoyée sans modification. Un `Buffer` nécessite le type `'raw'` (`application/octet-stream`) ; sans type, il est sérialisé en JSON comme un objet.\n\nExample: Corps binaire\n```js\nRESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.text(value)\n\nType: `method`\n\nEnvoie du texte brut et laisse la réponse non analysée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le texte. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\n`builder.plain(value)` est un alias. Définit `Content-Type: text/plain` et le corps, et le callback reçoit le corps brut de la réponse au lieu d'une valeur analysée.\n\nExample: Texte brut\n```js\nRESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {\n\t// response is the raw body\n});\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nAjoute un fichier et envoie une requête multipart.\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 envoyé au service. |\n| `source` | `Buffer|String` | no |  | Un buffer, un chemin ou une URL. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nLa requête devient `multipart/form-data` (un `GET` devient `POST`). `source` est un `Buffer`, un chemin sur le disque ou une URL qui est téléchargée et transmise en flux. Sans `source`, le fichier est lu depuis `filename`. Le corps défini avec `json()` ou `urlencoded()` est envoyé sous forme de champs de formulaire supplémentaires lorsqu'il s'agit d'un objet.\n\nExample: Envoyer deux fichiers\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))\n\t.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')\n\t.callback(console.log);\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 même builder, pour le chaînage.\n\nDéfinit un en-tête. Fonctions pour les en-têtes courants : `builder.referrer(url)` (alias `referer()`) définit `Referer`, `builder.origin(url)` définit `Origin`, `builder.csrf(token)` définit `X-Csrf-Token` et `builder.xhr()` ajoute `X-Requested-With: XMLHttpRequest`.\n\nExample: En-têtes\n```js\nbuilder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();\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 MIME. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nDéfinit `Content-Type` avec un type MIME complet. Un type défini par `json()`, `urlencoded()`, `xml()` ou `text()` le remplace : utilise-la donc avec `raw(value)`.\n\nExample: Type personnalisé\n```js\nbuilder.raw('{\"id\":1}').type('application/vnd.api+json');\n```\n\n### builder.accept(ext)\n\nType: `method`\n\nDéfinit l'en-tête Accept.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Une extension ou un type MIME. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nPrend une extension de fichier (`'json'`, `'xml'`, `'html'`...) et la convertit en son type MIME ; une valeur plus longue est utilisée telle quelle.\n\nExample: Accepter XML\n```js\nbuilder.accept('xml');\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 même builder, pour le chaînage.\n\nAvec `user` et `password`, définit l'authentification basique (`Basic base64(user:password)`). Avec un seul argument, la valeur est utilisée telle quelle, par exemple `'Bearer TOKEN'`.\n\nExample: Basic et Bearer\n```js\nbuilder.auth('admin', 'secret');\nbuilder.auth('Bearer ' + CONF.apitoken);\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 du cookie. |\n| `value` | `String` | yes |  | La valeur. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nAjoute un cookie. `builder.cookies(obj)` remplace tous les cookies par un objet `{ name: value }`.\n\nExample: Cookies\n```js\nbuilder.cookie('session', token);\nbuilder.cookies({ lang: 'en', theme: 'dark' });\n```\n\n### builder.cook([value])\n\nType: `method`\n\nConserve les cookies de la réponse dans le builder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` le désactive. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nAvec `cook()`, les cookies définis par la réponse sont stockés dans le builder et envoyés avec la requête suivante effectuée par le même builder. `output.cookies` les contient alors. `cook(false)` désactive ce comportement.\n\nExample: Se connecter, puis lire\n```js\nRESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {\n\tRESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);\n});\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 |  | Millisecondes. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nLe délai en millisecondes (10000 par défaut). `0` le désactive. Lorsqu'il expire, l'erreur est `408: Request Timeout`.\n\nExample: Cinq secondes\n```js\nbuilder.timeout(5000);\n```\n\n### builder.keepalive([val])\n\nType: `method`\n\nRéutilise les connexions avec un agent keep-alive.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `val` | `Boolean` | no | `true` | Active ou désactive le keep-alive. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nSans argument (ou avec une valeur vraie), la requête utilise l'agent keep-alive partagé du framework, si bien que les connexions vers le même hôte sont réutilisées. `keepalive(false)` le désactive. Non utilisé avec un proxy.\n\nExample: Keep-alive\n```js\nRESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nEnvoie la requête par un proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Le proxy. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\n`url` vaut `'host:port'` ou `'http://host:port'`. Avec `http://user:password@host:port`, les identifiants sont envoyés comme `Proxy-Authorization: Basic`. Les cibles HTTPS passent par un tunnel avec `CONNECT`. Sans elle, le proxy de la clé de configuration `$proxyrequest` est utilisé lorsqu'il est défini.\n\nExample: Proxy\n```js\nbuilder.proxy('http://10.0.0.5:3128');\n```\n\nExample: Proxy avec identifiants\n```js\nbuilder.proxy('http://user:secret@10.0.0.5:3128');\n```\n\n### builder.insecure()\n\nType: `method`\n\nAccepte les certificats TLS invalides.\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nAccepte les certificats auto-signés ou expirés du service. Ne l'utilise que pour des services internes.\n\nExample: Auto-signé\n```js\nRESTBuilder.GET('https://10.0.0.20/api/').insecure().callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nDéfinit un certificat TLS client.\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 même builder, pour le chaînage.\n\nPour les services qui exigent des certificats client.\n\nExample: Certificat client\n```js\nbuilder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nEnvoie la requête par un socket Unix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | Le fichier socket. |\n| `path` | `String` | yes |  | Le chemin de la requête, par exemple `/api/`. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nSe connecte au fichier socket au lieu d'un hôte ; `path` est le chemin d'URL de la requête.\n\nExample: API Docker\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/docker.sock', '/containers/json');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nDésactive le cache DNS pour cette requête.\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nPar défaut, le builder résout le nom d'hôte une fois et met ses adresses en cache. Avec `nodnscache()`, Node.js le résout à chaque requête.\n\nExample: Sans cache DNS\n```js\nbuilder.nodnscache();\n```\n\n### builder.redirect(value)\n\nType: `method`\n\nActive ou désactive le suivi des redirections.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | yes |  | `false` arrête de suivre les redirections. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\n`redirect(false)` renvoie la réponse `301` ou `302` elle-même ; lis la cible dans `output.headers.location`. Par défaut, jusqu'à quatre redirections sont suivies.\n\nExample: Lire l'emplacement\n```js\nRESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers.location);\n});\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` | yes |  | La clé de chiffrement. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nLe corps est chiffré avec `key` et envoyé avec l'en-tête `X-Encryption: a` ; une réponse texte est déchiffrée avec la même clé. Les deux côtés doivent utiliser la même clé.\n\nExample: Appel chiffré\n```js\nbuilder.encrypt(CONF.sharedkey);\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 même builder, pour le chaînage.\n\nAppelle `fn(percentage)` pour chaque fragment reçu. Le pourcentage n'est connu que lorsque la réponse possède `Content-Length`, sinon il vaut `0`.\n\nExample: Progression\n```js\nbuilder.progress(function(percentage) {\n\tconsole.log(percentage.toFixed(1) + '%');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nRenvoie le corps brut de la réponse.\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nLe callback reçoit le corps sous forme de chaîne (ou de `Buffer` pour les types binaires) au lieu d'une valeur analysée.\n\nExample: HTML brut\n```js\nRESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {\n\tconsole.log(html.length);\n});\n```\n\n### builder.base64()\n\nType: `method`\n\nRenvoie le corps de la réponse en base64.\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nLe callback reçoit le corps encodé en base64, par exemple pour intégrer une image sous forme de data URI.\n\nExample: Data URI\n```js\nRESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {\n\tvar uri = 'data:image/png;base64,' + data;\n});\n```\n\n### builder.debug()\n\nType: `method`\n\nAffiche la requête et la réponse dans la console.\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nAprès l'arrivée de la réponse, affiche le statut, la méthode, l'URL avec la query, l'erreur et le corps brut.\n\nExample: Debug\n```js\nRESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nEnvoie la requête et reçoit la réponse analysée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)` ou le `$` d'une action. |\n\nReturns: `RESTBuilder|Promise` Le builder, ou une promesse en cas d'appel sans argument.\n\nEnvoie la requête au tick suivant et passe le résultat à `fn(err, response, output)` :\n\n- `response` : le corps analysé selon son `Content-Type` (JSON, aussi pour `text/plain` ; URL-encoded ; XML via le parseur HTML ; les autres corps sont analysés comme JSON lorsqu'ils ressemblent à du JSON). Un corps vide donne un objet vide ; une réponse `204` donne `true`.\n- `output` : `status`, `headers`, `response` (le corps brut), `hostname`, `origin`, `cookies` (avec `cook()`) et `output.cookie(name)`, qui lit un cookie de la réponse.\n- `err` : l'erreur réseau ou `'408: Request Timeout'` ; un `ErrorBuilder` lorsque le corps est un tableau d'erreurs Total.js (`[{ error: '...' }]`, `response` vaut alors `null`) ; sinon, pour un statut de `400` ou plus, un `ErrorBuilder` avec une erreur dont le nom est le code de statut et dont le message est le corps brut. Une valeur définie avec `builder.error()` remplace toute erreur.\n\n`fn` peut aussi être le `$` d'une action : la réponse analysée est passée à `$.callback()` et une erreur est ajoutée aux erreurs de `$`. Sans argument, la méthode renvoie une promesse résolue avec `response` et rejetée avec `err`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) {\n\tif (err)\n\t\treturn console.log(err);\n\tconsole.log(output.status, response.length);\n});\n```\n\nExample: Dans une action\n```js\nNEWACTION('Products/sync', {\n\tname: 'Sync products',\n\taction: function($) {\n\t\tRESTBuilder.GET(CONF.shopapi + '/products/').callback($);\n\t}\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 |  | Le `$` d'une action. |\n\nReturns: `Promise` Résolue avec la réponse analysée.\n\nLa promesse est résolue avec la réponse analysée. En cas d'erreur, elle est rejetée avec une `Error` construite à partir de l'erreur (un `ErrorBuilder` devient une `Error` avec ses messages). Avec `$`, l'erreur part plutôt dans `$.invalid()` et la promesse n'est pas rejetée.\n\nExample: await\n```js\nvar user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();\n```\n\nExample: Avec $\n```js\nvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\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 même builder, pour le chaînage.\n\nEnvoie la requête immédiatement et appelle `callback(err, response, output)` avec les mêmes valeurs que `callback()`. Préfère `callback()`, qui attend le tick suivant. Lorsque `callback` est omis, le résultat est ignoré.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nRenvoie 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 même builder, pour le chaînage.\n\nEnvoie la requête au tick suivant et appelle `callback(err, response)` dès l'arrivée des en-têtes. `response` possède `status`, `headers`, `origin` et `stream` (la réponse Node.js, pas encore lue). Utilise-la pour les fichiers volumineux.\n\nExample: Enregistrer un fichier volumineux\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (!err && response.status === 200)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### builder.error(value)\n\nType: `method` · Since: `0.0.16`\n\nRemplace toute erreur par ta propre valeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String` | yes |  | L'erreur à renvoyer, par exemple un message ou un `ErrorBuilder`. |\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nLorsque la requête se termine par une erreur quelconque (réseau, délai d'expiration ou statut de `400` ou plus), le callback ou la promesse reçoit `value` à la place. Utilise-la pour masquer à tes utilisateurs les détails d'un service distant.\n\nExample: Erreur personnalisée\n```js\nRESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);\n```\n\n### builder.logerror()\n\nType: `method` · Since: `0.0.16`\n\nAffiche les erreurs dans la console.\n\nReturns: `RESTBuilder` Le même builder, pour le chaînage.\n\nLorsque la requête se termine par une erreur, l'erreur (ou le corps brut de la réponse) est passée au gestionnaire d'erreurs du framework, qui l'affiche avec le nom `RESTBuilder` ainsi que la méthode et l'URL de la requête. Le callback reçoit toujours l'erreur.\n\nExample: Journaliser les erreurs\n```js\nRESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"AJAX()","signature":"AJAX('METHOD url', [data], [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"Total.download()","signature":"Total.download(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"class","name":"RESTBuilder","signature":"new RESTBuilder([url])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","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.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"builder.compress()","signature":"builder.compress([value])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","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.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])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, [type])","since":"","deprecated":false},{"type":"method","name":"builder.text()","signature":"builder.text(value)","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","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(ext)","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([value])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive([val])","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.insecure()","signature":"builder.insecure()","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt(key)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.base64()","signature":"builder.base64()","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.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(value)","since":"0.0.16","deprecated":false},{"type":"method","name":"builder.logerror()","signature":"builder.logerror()","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwtJ1cx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/http-requests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Richieste HTTP","summary":"RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() e Total.download().","markdown":"---\ntitle: Richieste HTTP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/http-requests/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Richieste HTTP\n\n> RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() e Total.download().\n\nLe funzioni globali e la classe `RESTBuilder` per le richieste HTTP verso altri servizi. Per un'introduzione con esempi leggi la guida [Richieste HTTP](../../guides/http-requests/). Il client WebSocket `OPENCLIENT()` ha una pagina propria: [OpenClient](../openclient/).\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nInvia una richiesta HTTP con il pieno controllo delle opzioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.url` | `String` | yes |  | L'URL della richiesta. Le credenziali nell'URL (`https://user:password@host/`) vengono inviate come `Authorization: Basic`; i caratteri codificati con percentuale al loro interno vengono prima decodificati. |\n| `options.method` | `String` | no | `'GET'` | Il metodo HTTP in maiuscolo. |\n| `options.headers` | `Object` | no |  | Header della richiesta. L'oggetto viene copiato, quindi il tuo oggetto non viene modificato. |\n| `options.type` | `String` | no |  | Imposta `Content-Type`: `'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'` o `'text'`, `'raw'` (`application/octet-stream`). |\n| `options.body` | `String|Buffer` | no |  | Il body della richiesta. Una stringa viene inviata come UTF-8; `Content-Length` viene impostato per te. |\n| `options.query` | `Object|String` | no |  | Aggiunto all'URL come query string. |\n| `options.cookies` | `Object` | no |  | Cookie da inviare, come `{ name: value }`. |\n| `options.cook` | `Boolean` | no |  | Salva i cookie della response in `options.cookies`, così lo stesso oggetto options li invia con la richiesta successiva. |\n| `options.timeout` | `Number` | no | `8000` | Timeout in millisecondi; `0` lo disattiva. |\n| `options.encoding` | `String` | no | `'utf8'` | Codifica di un body testuale. `'binary'` restituisce un `Buffer`. |\n| `options.xhr` | `Boolean` | no |  | Aggiunge `X-Requested-With: XMLHttpRequest`. |\n| `options.files` | `Array` | no |  | File per una richiesta `multipart/form-data`: `[{ name, filename, buffer \\| path \\| url }]`. `options.body` è quindi un oggetto di campi aggiuntivi del form. |\n| `options.compress` | `String` | no |  | Comprime il body: `'gzip'` o `'deflate'`, e imposta `Content-Encoding`. |\n| `options.encrypt` | `String` | no |  | Una chiave: il body viene cifrato con essa e la risposta testuale viene decifrata con essa. |\n| `options.writer` | `Function` | no |  | `function(req)` scrive il body da sé: riceve la richiesta di Node.js, scrive i dati e chiama `req.end()`. `body` e `files` non vengono quindi usati. |\n| `options.custom` | `Boolean` | no |  | Restituisce `response.stream` invece di leggere il body. |\n| `options.noredirect` | `Boolean` | no |  | Non segue i redirect; la callback riceve la risposta `301`/`302`. |\n| `options.keepalive` | `Boolean` | no |  | Usa un agent keep-alive condiviso (uno per HTTP, uno per HTTPS). |\n| `options.resolve` | `Boolean` | no |  | Risolve l'hostname con una cache DNS. `options.dnscache` fa lo stesso. Viene saltato per `localhost` e gli indirizzi IP. |\n| `options.proxy` | `String` | no |  | Un proxy per questa richiesta, come `'host:port'` o `'http://host:port'`. Con `http://user:password@host:port` le credenziali vengono inviate come `Proxy-Authorization: Basic`. |\n| `options.insecure` | `Boolean` | no |  | Accetta certificati TLS non validi o autofirmati. |\n| `options.key` | `Buffer` | no |  | Chiave TLS del client. |\n| `options.cert` | `Buffer` | no |  | Certificato TLS del client. |\n| `options.dhparam` | `Buffer` | no |  | Parametri Diffie-Hellman TLS. |\n| `options.unixsocket` | `Object` | no |  | `{ socket, path }` per inviare la richiesta attraverso un socket Unix invece di `url`. |\n| `options.ondata` | `Function` | no |  | `function(chunk, percentage)` per ogni chunk ricevuto. |\n| `options.onprogress` | `Function` | no |  | `function(percentage)`; la percentuale è nota solo con `Content-Length`. |\n| `options.callback` | `Function` | no |  | `function(err, response)`, al posto del secondo argomento. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Una promise quando non viene fornita alcuna callback; altrimenti nulla.\n\nInvia una richiesta HTTP descritta da `options`. La callback riceve `(err, response)`; senza callback (nell'argomento o in `options.callback`) restituisce una promise che si risolve con `response`.\n\nL'oggetto response ha `status`, `headers`, `body`, `host`, `origin` (gli indirizzi IP risolti quando la cache DNS è attiva) e `cookies` (i cookie raccolti nei redirect). `body` è una stringa per i tipi `text/*` e `application/*` (decodificata con `encoding`) e un `Buffer` per gli altri tipi, oppure sempre un `Buffer` con `encoding: 'binary'`. Il body non viene interpretato: usa `RESTBuilder` o `AJAX()` per questo.\n\nCon `custom: true` la callback viene eseguita appena arrivano gli header e la response ha `stream` (la response di Node.js) invece di `body`.\n\nErrori: un errore di rete passa l'oggetto errore con `response.status === 0`; un timeout scaduto passa `'408: Request Timeout'` con `response.status === 408`; più di quattro redirect passano `'Too many redirects'`; un URL senza hostname passa `'Invalid hostname'`, e una stringa che non è un URL lancia `TypeError: Invalid URL`. Un codice di stato `400` o superiore non è un errore: controlla `response.status`.\n\nI redirect `301` e `302` vengono seguiti (i cookie del redirect vengono inviati alla posizione successiva). Le richieste usano il proxy della chiave di configurazione `$proxyrequest` quando è impostata, tranne che per `localhost`, `127.0.0.1` e `0.0.0.0`.\n\nExample: POST JSON\n```js\nREQUEST({\n\turl: 'https://api.example.com/orders/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ id: 'p100', count: 2 })\n}, function(err, response) {\n\tif (err || response.status !== 200)\n\t\treturn;\n\tvar order = response.body.parseJSON();\n});\n```\n\nExample: Con una promise\n```js\nvar response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });\nconsole.log(response.status, response.body);\n```\n\nExample: Caricare un file\n```js\nREQUEST({\n\turl: 'https://files.example.com/upload/',\n\tmethod: 'POST',\n\tfiles: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],\n\tbody: { folder: 'reports' }\n}, console.log);\n```\n\nExample: Leggere uno stream\n```js\nREQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));\n});\n```\n\nExample: Scrivere il body da te\n```js\nREQUEST({\n\turl: 'https://api.example.com/import/',\n\tmethod: 'POST',\n\ttype: 'plain',\n\twriter: function(req) {\n\t\tfor (var line of lines)\n\t\t\treq.write(line + '\\n');\n\t\treq.end();\n\t}\n}, console.log);\n```\n\n### AJAX('METHOD url', [data], [callback])\n\nType: `method`\n\nInvia una richiesta JSON e restituisce la risposta analizzata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `'METHOD url'`, per esempio `'POST https://example.com/api/'`. |\n| `data` | `Object` | no |  | Dati inviati come JSON. |\n| `callback` | `Function` | no |  | `function(err, response, meta)`. |\n\nReturns: `Promise` Una promise quando non viene fornita alcuna callback.\n\nInvia una richiesta e interpreta la risposta. Il primo argomento è il metodo e l'URL separati da uno spazio; senza metodo è `GET`. `data` viene inviato come body JSON. L'header `X-Requested-With: XMLHttpRequest` viene sempre aggiunto.\n\nLa risposta viene interpretata in base al suo `Content-Type`: JSON (`application/json`, `text/json`), dati URL-encoded e XML (`application/xml`, `text/xml`) diventano oggetti; gli altri tipi vengono restituiti come body grezzo. Un documento XML diventa un oggetto piatto: i nomi degli elementi annidati vengono uniti con `_` (`order_name`), gli elementi ripetuti danno un array e gli attributi di un elemento sono in un oggetto sotto il suo nome con `__` (`order__`). Un body XML vuoto dà `{}`. La callback riceve `(err, response, meta)`, dove `meta` contiene `status`, `headers` e `host`.\n\nPer uno stato `400` o superiore, `err` è il body interpretato (per un servizio Total.js l'array degli errori) e `response` è `null`. Senza callback la funzione restituisce una promise che si risolve con il body interpretato e viene rifiutata con `err`; un array di errori Total.js diventa un `Error` il cui messaggio contiene i messaggi di errore.\n\nExample: Callback\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {\n\tconsole.log(meta.status, response);\n});\n```\n\nExample: Promise\n```js\nvar products = await AJAX('GET https://api.example.com/products/?page=1');\n```\n\nExample: Risposta XML\n```js\n// the service answers <order id=\"100\"><name>Book</name><items><item>A</item><item>B</item></items></order>\nvar order = await AJAX('GET https://api.example.com/orders/100/');\n// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nScarica un file remoto su disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | L'URL, oppure `{ socket, path }` per un socket Unix. |\n| `filename` | `String` | yes |  | Il percorso del file di destinazione. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout in millisecondi. |\n\nReturns: `Promise` Una promise quando non viene fornita alcuna callback.\n\nScarica `url` e scrive il body in `filename`. La callback viene eseguita quando il file è scritto, con `(err, response)`. `response` contiene `status`, `headers`, `origin`, `filename` e `size` (il numero di byte scritti). Il body viene salvato per ogni codice di stato, quindi controlla `response.status`.\n\n`url` può essere anche un oggetto `{ socket, path }` per un socket Unix. Le risoluzioni DNS vengono messe in cache. `timeout` è in millisecondi (8 secondi se non impostato). Senza callback la funzione restituisce una promise che si risolve con `response`.\n\nExample: Scaricare un'immagine\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.filename);\n});\n```\n\nExample: Promise\n```js\nvar response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));\n```\n\n### Total.download(url, filename, [callback], [timeout])\n\nType: `method`\n\nIl metodo del framework dietro DOWNLOAD().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | L'URL, oppure `{ socket, path }` per un socket Unix. |\n| `filename` | `String` | yes |  | Il percorso del file di destinazione. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout in millisecondi. |\n\nReturns: `Promise` Una promise quando non viene fornita alcuna callback.\n\nLa stessa funzione di `DOWNLOAD()`. Scarica `url` e scrive il body in `filename`. La callback viene eseguita quando il file è scritto, con `(err, response)`. `response` contiene `status`, `headers`, `origin`, `filename` e `size` (il numero di byte scritti). Il body viene salvato per ogni codice di stato, quindi controlla `response.status`.\n\n`url` può essere anche un oggetto `{ socket, path }` per un socket Unix. Le risoluzioni DNS vengono messe in cache. `timeout` è in millisecondi (8 secondi se non impostato). Senza callback la funzione restituisce una promise che si risolve con `response`.\n\nExample: Download\n```js\nTotal.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n### new RESTBuilder([url])\n\nType: `class`\n\nUn builder per le richieste verso servizi REST.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | L'URL della richiesta. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nUna classe globale. Un nuovo builder ha il metodo `GET`, un timeout di 10 secondi, la cache DNS attiva, l'header `user-agent: Total.js/v...` e `accept: application/json, text/plain, text/plain, text/xml`. Non viene inviato nulla finché non chiami `callback()`, `promise()`, `stream()` o `exec()`.\n\nDi solito inizi con un helper statico: `RESTBuilder.GET()`, `POST()`, `PUT()`, `PATCH()`, `DELETE()`, `HEAD()`, `API()`, `url()` o `make()`. `RESTBuilder.url(url)` equivale a `new RESTBuilder(url)`.\n\nExample: Creare un builder\n```js\nvar builder = RESTBuilder.url('https://api.example.com/users/');\nbuilder.header('X-Token', CONF.apitoken);\nbuilder.callback(console.log);\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nCrea un builder 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\nCrea un builder senza URL e chiama `fn(builder)`. Imposta l'URL con `builder.url()`. Il metodo di istanza `builder.make(fn)` chiama `fn` con il builder come `this` e come argomento, per impostazioni riutilizzabili.\n\nExample: Costruire una richiesta\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.post({ name: 'Peter' });\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nCrea una richiesta GET.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Inviato come query string. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nCrea un builder con il metodo `GET`; `data` diventa la query string. Per una richiesta `HEAD` usa `RESTBuilder.HEAD(url)`: non ha dati, il valore analizzato è un oggetto vuoto e leggi `output.status` e `output.headers`.\n\nExample: Query string\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nExample: HEAD\n```js\nRESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers['last-modified']);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nCrea una richiesta POST.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Inviato come body JSON. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nCrea un builder con il metodo `POST`; `data` viene inviato come JSON. `RESTBuilder.PUT()`, `RESTBuilder.PATCH()` e `RESTBuilder.DELETE()` funzionano allo stesso modo con i rispettivi metodi.\n\nExample: POST JSON\n```js\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {\n\tconsole.log(order.id);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nCrea una richiesta PUT.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Inviato come body JSON. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nCrea un builder con il metodo `PUT`; `data` viene inviato come JSON.\n\nExample: PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nCrea una richiesta PATCH.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Inviato come body JSON. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nCrea un builder con il metodo `PATCH`; `data` viene inviato come JSON.\n\nExample: PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nCrea una richiesta DELETE.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `data` | `Object` | no |  | Inviato come body JSON. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nCrea un builder con il metodo `DELETE`; `data` viene inviato come JSON.\n\nExample: DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nChiama un endpoint API di un'applicazione Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL dell'endpoint API. |\n| `name` | `String` | yes |  | Il nome dell'operazione API. |\n| `data` | `Object` | no |  | I dati dell'operazione. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nCrea una richiesta `POST` per una route API di Total.js (`ROUTE('API /api/ ...')`). Il body è JSON: `{ schema: name, data: data }`. `name` è il nome dell'API con parametri facoltativi, per esempio `'products_detail/p100'`. `builder.get(query)` mantiene il `POST` e invia la query nel body come `query`, accanto a `data`. `builder.compress()` omette le chiavi del body il cui valore è `null` o `undefined`.\n\nExample: Chiamare un'API\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Con una query\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n### builder.compress([value])\n\nType: `method`\n\nOmette i valori vuoti dal body di una richiesta RESTBuilder.API().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` lo disattiva. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nSenza argomento o con `true`, il body JSON di una richiesta `RESTBuilder.API()` viene scritto senza le chiavi il cui valore è `null` o `undefined`, così la richiesta è più piccola. `compress(false)` lo disattiva. Gli altri builder non sono interessati.\n\nExample: Body più piccolo\n```js\nRESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);\n// data: { id: 'A1', total: 120 }\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nRegistra una funzione che modifica ogni builder prima che venga inviato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nLa funzione viene eseguita per ogni builder dell'applicazione subito prima che venga effettuata la richiesta, con il builder come argomento. Usala per header o token condivisi. Gli upgrade non possono essere rimossi.\n\nExample: Aggiungere un token a un servizio\n```js\nRESTBuilder.upgrade(function(builder) {\n\tif (builder.url().startsWith(CONF.shopapi))\n\t\tbuilder.header('X-Token', CONF.shoptoken);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nImposta o legge l'URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Il nuovo URL. |\n\nReturns: `RESTBuilder|String` Il builder, oppure l'URL quando viene chiamato senza argomento.\n\nCon un argomento imposta l'URL e restituisce il builder; senza argomento restituisce l'URL corrente.\n\nExample: Leggere l'URL\n```js\nvar url = builder.url();\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 |  | Il metodo HTTP. |\n| `data` | `Object` | no |  | Dati inviati come JSON. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nImposta il metodo (le minuscole vengono convertite in maiuscole). `data` viene inviato come JSON.\n\nScorciatoie: `builder.get([query])` imposta `GET` e la query string; `builder.post([data])`, `builder.put([data])`, `builder.patch([data])` e `builder.delete([data])` impostano il metodo e il body (nel tipo impostato prima, JSON per impostazione predefinita); `builder.head()` imposta `HEAD`. I nomi in maiuscolo (`builder.POST()`) sono alias.\n\nExample: Scorciatoie\n```js\nRESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);\n```\n\n### builder.json([data])\n\nType: `method`\n\nInvia i dati come JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | I dati. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nImposta il tipo a JSON e il body a `data` (un oggetto viene serializzato quando la richiesta viene inviata). Una richiesta `GET` diventa `POST`.\n\nExample: Body JSON\n```js\nRESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nInvia i dati come form URL-encoded.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | I campi del form. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nImposta `Content-Type: application/x-www-form-urlencoded` e il body; un oggetto viene codificato quando la richiesta viene inviata. Una richiesta `GET` diventa `POST`.\n\nExample: Form\n```js\nRESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);\n```\n\n### builder.xml([data])\n\nType: `method`\n\nInvia un body XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | L'XML. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nImposta `Content-Type: text/xml` e il body. Passa l'XML come stringa. Una richiesta `GET` diventa `POST`.\n\nExample: Body XML\n```js\nRESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);\n```\n\n### builder.raw(value, [type])\n\nType: `method`\n\nImposta il body così com'è.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Il body. |\n| `type` | `String` | no |  | Il tipo di contenuto breve. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nImposta il body senza alcuna serializzazione. `type` è uno dei tipi brevi di `REQUEST()` (`'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'`, `'raw'`); senza di esso imposta l'header con `builder.type()`. Una stringa viene inviata invariata. Un `Buffer` richiede il tipo `'raw'` (`application/octet-stream`); senza tipo viene serializzato come JSON come un oggetto.\n\nExample: Body binario\n```js\nRESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.text(value)\n\nType: `method`\n\nInvia testo semplice e lascia la risposta non analizzata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il testo. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\n`builder.plain(value)` è un alias. Imposta `Content-Type: text/plain` e il body, e la callback riceve il body grezzo della risposta invece di un valore analizzato.\n\nExample: Testo semplice\n```js\nRESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {\n\t// response is the raw body\n});\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nAggiunge un file e invia una richiesta multipart.\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 inviato al servizio. |\n| `source` | `Buffer|String` | no |  | Un buffer, un percorso o un URL. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nLa richiesta diventa `multipart/form-data` (una `GET` diventa `POST`). `source` è un `Buffer`, un percorso su disco o un URL che viene scaricato e trasmesso in streaming. Senza `source` il file viene letto da `filename`. Il body impostato con `json()` o `urlencoded()` viene inviato come campi aggiuntivi del form quando è un oggetto.\n\nExample: Caricare due file\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))\n\t.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')\n\t.callback(console.log);\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` Lo stesso builder, per il concatenamento.\n\nImposta un header. Helper per gli header comuni: `builder.referrer(url)` (alias `referer()`) imposta `Referer`, `builder.origin(url)` imposta `Origin`, `builder.csrf(token)` imposta `X-Csrf-Token` e `builder.xhr()` aggiunge `X-Requested-With: XMLHttpRequest`.\n\nExample: Header\n```js\nbuilder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();\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 tipo MIME. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nImposta `Content-Type` a un tipo MIME completo. Un tipo impostato da `json()`, `urlencoded()`, `xml()` o `text()` lo sostituisce, quindi usalo con `raw(value)`.\n\nExample: Tipo personalizzato\n```js\nbuilder.raw('{\"id\":1}').type('application/vnd.api+json');\n```\n\n### builder.accept(ext)\n\nType: `method`\n\nImposta l'header Accept.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Un'estensione o un tipo MIME. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nAccetta un'estensione di file (`'json'`, `'xml'`, `'html'`...) e la converte nel suo tipo MIME; un valore più lungo viene usato così com'è.\n\nExample: Accettare XML\n```js\nbuilder.accept('xml');\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 o l'intero valore dell'header. |\n| `password` | `String` | no |  | La password. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nCon `user` e `password` imposta l'autenticazione basic (`Basic base64(user:password)`). Con un solo argomento il valore viene usato così com'è, ad esempio `'Bearer TOKEN'`.\n\nExample: Basic e Bearer\n```js\nbuilder.auth('admin', 'secret');\nbuilder.auth('Bearer ' + CONF.apitoken);\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 del cookie. |\n| `value` | `String` | yes |  | Il valore. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nAggiunge un cookie. `builder.cookies(obj)` sostituisce tutti i cookie con un oggetto `{ name: value }`.\n\nExample: Cookie\n```js\nbuilder.cookie('session', token);\nbuilder.cookies({ lang: 'en', theme: 'dark' });\n```\n\n### builder.cook([value])\n\nType: `method`\n\nConserva i cookie della risposta nel builder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` lo disattiva. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nCon `cook()` i cookie impostati dalla risposta vengono memorizzati nel builder e inviati con la richiesta successiva effettuata dallo stesso builder. `output.cookies` li contiene allora. `cook(false)` lo disattiva.\n\nExample: Login, poi lettura\n```js\nRESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {\n\tRESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);\n});\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 |  | Millisecondi. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nIl timeout in millisecondi (10000 per impostazione predefinita). `0` lo disattiva. Quando scade l'errore è `408: Request Timeout`.\n\nExample: Cinque secondi\n```js\nbuilder.timeout(5000);\n```\n\n### builder.keepalive([val])\n\nType: `method`\n\nRiutilizza le connessioni con un agent keep-alive.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `val` | `Boolean` | no | `true` | Attiva o disattiva il keep-alive. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nSenza argomento (o con un valore truthy) la richiesta usa l'agent keep-alive condiviso del framework, così le connessioni verso lo stesso host vengono riutilizzate. `keepalive(false)` lo disattiva. Non viene usato insieme a un proxy.\n\nExample: Keep-alive\n```js\nRESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nInvia la richiesta attraverso un proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Il proxy. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\n`url` è `'host:port'` o `'http://host:port'`. Con `http://user:password@host:port` le credenziali vengono inviate come `Proxy-Authorization: Basic`. Le destinazioni HTTPS vengono incapsulate in un tunnel con `CONNECT`. Senza di esso viene usato il proxy della chiave di configurazione `$proxyrequest` quando è impostata.\n\nExample: Proxy\n```js\nbuilder.proxy('http://10.0.0.5:3128');\n```\n\nExample: Proxy con login\n```js\nbuilder.proxy('http://user:secret@10.0.0.5:3128');\n```\n\n### builder.insecure()\n\nType: `method`\n\nAccetta certificati TLS non validi.\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nAccetta certificati autofirmati o scaduti del servizio. Usalo solo per servizi interni.\n\nExample: Autofirmato\n```js\nRESTBuilder.GET('https://10.0.0.20/api/').insecure().callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nImposta un certificato TLS del client.\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` Lo stesso builder, per il concatenamento.\n\nPer i servizi che richiedono certificati client.\n\nExample: Certificato client\n```js\nbuilder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nInvia la richiesta attraverso un socket Unix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | Il file del socket. |\n| `path` | `String` | yes |  | Il percorso della richiesta, ad esempio `/api/`. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nSi connette al file del socket invece che a un host; `path` è il percorso URL della richiesta.\n\nExample: API di Docker\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/docker.sock', '/containers/json');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nDisattiva la cache DNS per questa richiesta.\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nPer impostazione predefinita il builder risolve l'hostname una volta e mette in cache i suoi indirizzi. Con `nodnscache()` Node.js lo risolve a ogni richiesta.\n\nExample: Senza cache DNS\n```js\nbuilder.nodnscache();\n```\n\n### builder.redirect(value)\n\nType: `method`\n\nAttiva o disattiva il seguire dei redirect.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | yes |  | `false` smette di seguire i redirect. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\n`redirect(false)` restituisce la risposta `301` o `302` stessa; leggi la destinazione in `output.headers.location`. Per impostazione predefinita vengono seguiti fino a quattro redirect.\n\nExample: Leggere la location\n```js\nRESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers.location);\n});\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` | yes |  | La chiave di cifratura. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nIl body viene cifrato con `key` e inviato con l'header `X-Encryption: a`; una risposta di testo viene decifrata con la stessa chiave. Entrambe le parti devono usare la stessa chiave.\n\nExample: Chiamata cifrata\n```js\nbuilder.encrypt(CONF.sharedkey);\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` Lo stesso builder, per il concatenamento.\n\nChiama `fn(percentage)` per ogni chunk ricevuto. La percentuale è nota solo quando la risposta ha `Content-Length`, altrimenti è `0`.\n\nExample: Avanzamento\n```js\nbuilder.progress(function(percentage) {\n\tconsole.log(percentage.toFixed(1) + '%');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nRestituisce il body grezzo della risposta.\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nLa callback riceve il body come stringa (o un `Buffer` per i tipi binari) invece di un valore analizzato.\n\nExample: HTML grezzo\n```js\nRESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {\n\tconsole.log(html.length);\n});\n```\n\n### builder.base64()\n\nType: `method`\n\nRestituisce il body della risposta in base64.\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nLa callback riceve il body codificato in base64, ad esempio per incorporare un'immagine come data URI.\n\nExample: Data URI\n```js\nRESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {\n\tvar uri = 'data:image/png;base64,' + data;\n});\n```\n\n### builder.debug()\n\nType: `method`\n\nStampa la richiesta e la risposta nella console.\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nDopo l'arrivo della risposta stampa lo stato, il metodo, l'URL con la query, l'errore e il body grezzo.\n\nExample: Debug\n```js\nRESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nInvia la richiesta e riceve la risposta analizzata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)` o il `$` di un'azione. |\n\nReturns: `RESTBuilder|Promise` Il builder, oppure una promise quando viene chiamato senza argomento.\n\nInvia la richiesta al tick successivo e passa il risultato a `fn(err, response, output)`:\n\n- `response`: il body interpretato in base al suo `Content-Type` (JSON, anche per `text/plain`; URL-encoded; XML tramite il parser HTML; gli altri body vengono interpretati come JSON quando sembrano JSON). Un body vuoto produce un oggetto vuoto; una risposta `204` produce `true`.\n- `output`: `status`, `headers`, `response` (il body grezzo), `hostname`, `origin`, `cookies` (con `cook()`) e `output.cookie(name)`, che legge un cookie della risposta.\n- `err`: l'errore di rete o `'408: Request Timeout'`; un `ErrorBuilder` quando il body è un array di errori Total.js (`[{ error: '...' }]`, e allora `response` è `null`); altrimenti, per uno stato `400` o superiore, un `ErrorBuilder` con un errore il cui nome è il codice di stato e il cui messaggio è il body grezzo. Un valore impostato con `builder.error()` sostituisce qualsiasi errore.\n\n`fn` può essere anche il `$` di un'azione: la risposta interpretata viene passata a `$.callback()` e un errore viene aggiunto agli errori di `$`. Senza argomento restituisce una promise che si risolve con `response` e viene rifiutata con `err`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) {\n\tif (err)\n\t\treturn console.log(err);\n\tconsole.log(output.status, response.length);\n});\n```\n\nExample: In un'azione\n```js\nNEWACTION('Products/sync', {\n\tname: 'Sync products',\n\taction: function($) {\n\t\tRESTBuilder.GET(CONF.shopapi + '/products/').callback($);\n\t}\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 |  | Il `$` di un'azione. |\n\nReturns: `Promise` Si risolve con la risposta analizzata.\n\nLa promise si risolve con la risposta analizzata. In caso di errore viene rifiutata con un `Error` creato dall'errore (un `ErrorBuilder` diventa un `Error` con i suoi messaggi). Con `$` l'errore va invece a `$.invalid()` e la promise non viene rifiutata.\n\nExample: await\n```js\nvar user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();\n```\n\nExample: Con $\n```js\nvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\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` Lo stesso builder, per il concatenamento.\n\nInvia la richiesta immediatamente e chiama `callback(err, response, output)` con gli stessi valori di `callback()`. Preferisci `callback()`, che attende il tick successivo. Quando `callback` è omessa il risultato viene ignorato.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nRestituisce la risposta come stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nInvia la richiesta al tick successivo e chiama `callback(err, response)` non appena arrivano gli header. `response` ha `status`, `headers`, `origin` e `stream` (la risposta Node.js, non ancora letta). Usalo per i file di grandi dimensioni.\n\nExample: Salvare un file di grandi dimensioni\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (!err && response.status === 200)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### builder.error(value)\n\nType: `method` · Since: `0.0.16`\n\nSostituisce qualsiasi errore con un tuo valore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String` | yes |  | L'errore da restituire, per esempio un messaggio o un `ErrorBuilder`. |\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nQuando la richiesta termina con un errore qualsiasi (di rete, di timeout o uno stato `400` o superiore), la callback o la promise ricevono invece `value`. Usalo per nascondere ai tuoi utenti i dettagli di un servizio remoto.\n\nExample: Errore personalizzato\n```js\nRESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);\n```\n\n### builder.logerror()\n\nType: `method` · Since: `0.0.16`\n\nStampa gli errori nella console.\n\nReturns: `RESTBuilder` Lo stesso builder, per il concatenamento.\n\nQuando la richiesta termina con un errore, l'errore (o il body grezzo della risposta) viene passato al gestore degli errori del framework, che lo stampa con il nome `RESTBuilder` e il metodo e l'URL della richiesta. La callback riceve comunque l'errore.\n\nExample: Registrare gli errori\n```js\nRESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"AJAX()","signature":"AJAX('METHOD url', [data], [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"Total.download()","signature":"Total.download(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"class","name":"RESTBuilder","signature":"new RESTBuilder([url])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","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.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"builder.compress()","signature":"builder.compress([value])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","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.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])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, [type])","since":"","deprecated":false},{"type":"method","name":"builder.text()","signature":"builder.text(value)","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","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(ext)","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([value])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive([val])","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.insecure()","signature":"builder.insecure()","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt(key)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.base64()","signature":"builder.base64()","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.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(value)","since":"0.0.16","deprecated":false},{"type":"method","name":"builder.logerror()","signature":"builder.logerror()","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwtJ1cx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/http-requests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"HTTP požiadavky","summary":"RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() a Total.download().","markdown":"---\ntitle: \"HTTP požiadavky\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/http-requests/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# HTTP požiadavky\n\n> RESTBuilder, REQUEST(), AJAX(), DOWNLOAD() a Total.download().\n\nGlobálne funkcie a trieda `RESTBuilder` pre HTTP požiadavky na iné služby. Úvod s príkladmi nájdeš v príručke [HTTP požiadavky](../../guides/http-requests/). WebSocket klient `OPENCLIENT()` má vlastnú stránku: [OpenClient](../openclient/).\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nPošle HTTP požiadavku s úplnou kontrolou nad voľbami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options.url` | `String` | yes |  | URL požiadavky. Prihlasovacie údaje v URL (`https://user:password@host/`) sa pošlú ako `Authorization: Basic`; percentuálne zakódované znaky v nich sa najprv dekódujú. |\n| `options.method` | `String` | no | `'GET'` | HTTP metóda veľkými písmenami. |\n| `options.headers` | `Object` | no |  | Hlavičky požiadavky. Objekt sa skopíruje, takže tvoj objekt sa nezmení. |\n| `options.type` | `String` | no |  | Nastaví `Content-Type`: `'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'` alebo `'text'`, `'raw'` (`application/octet-stream`). |\n| `options.body` | `String|Buffer` | no |  | Telo požiadavky. Reťazec sa pošle ako UTF-8; `Content-Length` sa nastaví za teba. |\n| `options.query` | `Object|String` | no |  | Pripojí sa k URL ako query string. |\n| `options.cookies` | `Object` | no |  | Cookies na odoslanie, ako `{ name: value }`. |\n| `options.cook` | `Boolean` | no |  | Uloží cookies odpovede do `options.cookies`, takže ten istý objekt volieb ich pošle s ďalšou požiadavkou. |\n| `options.timeout` | `Number` | no | `8000` | Timeout v milisekundách; `0` ho vypne. |\n| `options.encoding` | `String` | no | `'utf8'` | Kódovanie textového tela. `'binary'` vráti `Buffer`. |\n| `options.xhr` | `Boolean` | no |  | Pridá `X-Requested-With: XMLHttpRequest`. |\n| `options.files` | `Array` | no |  | Súbory pre požiadavku `multipart/form-data`: `[{ name, filename, buffer \\| path \\| url }]`. `options.body` je potom objekt ďalších polí formulára. |\n| `options.compress` | `String` | no |  | Skomprimuje telo: `'gzip'` alebo `'deflate'`, a nastaví `Content-Encoding`. |\n| `options.encrypt` | `String` | no |  | Kľúč: telo sa ním zašifruje a textová odpoveď sa ním dešifruje. |\n| `options.writer` | `Function` | no |  | `function(req)` zapíše telo sám: dostane požiadavku Node.js, zapíše dáta a zavolá `req.end()`. `body` a `files` sa potom nepoužijú. |\n| `options.custom` | `Boolean` | no |  | Namiesto čítania tela vráti `response.stream`. |\n| `options.noredirect` | `Boolean` | no |  | Nenasleduje presmerovania; callback dostane odpoveď `301`/`302`. |\n| `options.keepalive` | `Boolean` | no |  | Použije zdieľaného keep-alive agenta (jedného pre HTTP, jedného pre HTTPS). |\n| `options.resolve` | `Boolean` | no |  | Preloží hostname pomocou DNS cache. `options.dnscache` robí to isté. Vynechá sa pre `localhost` a IP adresy. |\n| `options.proxy` | `String` | no |  | Proxy pre túto požiadavku, ako `'host:port'` alebo `'http://host:port'`. S `http://user:password@host:port` sa prihlasovacie údaje pošlú ako `Proxy-Authorization: Basic`. |\n| `options.insecure` | `Boolean` | no |  | Prijme neplatné alebo self-signed TLS certifikáty. |\n| `options.key` | `Buffer` | no |  | Klientsky TLS kľúč. |\n| `options.cert` | `Buffer` | no |  | Klientsky TLS certifikát. |\n| `options.dhparam` | `Buffer` | no |  | TLS parametre Diffie-Hellman. |\n| `options.unixsocket` | `Object` | no |  | `{ socket, path }` na odoslanie požiadavky cez Unix socket namiesto `url`. |\n| `options.ondata` | `Function` | no |  | `function(chunk, percentage)` pre každý prijatý kus dát. |\n| `options.onprogress` | `Function` | no |  | `function(percentage)`; percento je známe iba s `Content-Length`. |\n| `options.callback` | `Function` | no |  | `function(err, response)`, namiesto druhého argumentu. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `Promise` Promise, keď nie je zadaný callback; inak nič.\n\nOdošle jednu HTTP požiadavku opísanú v `options`. Callback dostane `(err, response)`; bez callbacku (v argumente ani v `options.callback`) vráti promise, ktorý sa vyrieši s `response`.\n\nObjekt odpovede má `status`, `headers`, `body`, `host`, `origin` (preložené IP adresy, keď je zapnutá DNS cache) a `cookies` (cookies zozbierané pri presmerovaniach). `body` je reťazec pre typy `text/*` a `application/*` (dekódovaný pomocou `encoding`) a `Buffer` pre ostatné typy, alebo vždy `Buffer` s `encoding: 'binary'`. Telo sa neparsuje: na to použi `RESTBuilder` alebo `AJAX()`.\n\nS `custom: true` sa callback spustí hneď, ako prídu hlavičky, a odpoveď má namiesto `body` vlastnosť `stream` (odpoveď Node.js).\n\nChyby: sieťová chyba odovzdá objekt chyby s `response.status === 0`; vypršaný timeout odovzdá `'408: Request Timeout'` s `response.status === 408`; viac ako štyri presmerovania odovzdajú `'Too many redirects'`; URL bez hostname odovzdá `'Invalid hostname'` a reťazec, ktorý nie je URL, vyhodí `TypeError: Invalid URL`. Stavový kód `400` alebo vyšší nie je chyba: skontroluj `response.status`.\n\nPresmerovania `301` a `302` sa nasledujú (cookies presmerovania sa pošlú na ďalšie miesto). Požiadavky používajú proxy z konfiguračného kľúča `$proxyrequest`, keď je nastavený, okrem `localhost`, `127.0.0.1` a `0.0.0.0`.\n\nExample: POST JSON\n```js\nREQUEST({\n\turl: 'https://api.example.com/orders/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ id: 'p100', count: 2 })\n}, function(err, response) {\n\tif (err || response.status !== 200)\n\t\treturn;\n\tvar order = response.body.parseJSON();\n});\n```\n\nExample: S promise\n```js\nvar response = await REQUEST({ url: 'https://example.com/robots.txt', timeout: 3000 });\nconsole.log(response.status, response.body);\n```\n\nExample: Nahratie súboru\n```js\nREQUEST({\n\turl: 'https://files.example.com/upload/',\n\tmethod: 'POST',\n\tfiles: [{ name: 'file', filename: 'report.pdf', path: PATH.databases('report.pdf') }],\n\tbody: { folder: 'reports' }\n}, console.log);\n```\n\nExample: Čítanie streamu\n```js\nREQUEST({ url: 'https://cdn.example.com/video.mp4', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('video.mp4')));\n});\n```\n\nExample: Vlastný zápis tela\n```js\nREQUEST({\n\turl: 'https://api.example.com/import/',\n\tmethod: 'POST',\n\ttype: 'plain',\n\twriter: function(req) {\n\t\tfor (var line of lines)\n\t\t\treq.write(line + '\\n');\n\t\treq.end();\n\t}\n}, console.log);\n```\n\n### AJAX('METHOD url', [data], [callback])\n\nType: `method`\n\nPošle JSON požiadavku a vráti spracovanú odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `'METHOD url'`, napríklad `'POST https://example.com/api/'`. |\n| `data` | `Object` | no |  | Dáta odoslané ako JSON. |\n| `callback` | `Function` | no |  | `function(err, response, meta)`. |\n\nReturns: `Promise` Promise, keď nie je zadaný callback.\n\nOdošle požiadavku a spracuje odpoveď. Prvý argument je metóda a URL oddelené medzerou; bez metódy je to `GET`. `data` sa odošlú ako JSON telo. Hlavička `X-Requested-With: XMLHttpRequest` sa pridá vždy.\n\nOdpoveď sa spracuje podľa jej `Content-Type`: JSON (`application/json`, `text/json`), URL-encoded dáta a XML (`application/xml`, `text/xml`) sa stanú objektmi; ostatné typy sa vrátia ako surové telo. XML dokument sa stane plochým objektom: názvy vnorených elementov sa spoja znakom `_` (`order_name`), opakované elementy dajú pole a atribúty elementu sú v objekte pod jeho názvom s `__` (`order__`). Prázdne XML telo dá `{}`. Callback dostane `(err, response, meta)`, kde `meta` má `status`, `headers` a `host`.\n\nPri stave `400` alebo vyššom je `err` spracované telo (pri službe Total.js pole chýb) a `response` je `null`. Bez callbacku funkcia vracia promise, ktorý sa splní so spracovaným telom a zamietne s `err`; pole chýb Total.js sa zmení na `Error`, ktorého správa obsahuje chybové hlásenia.\n\nExample: Callback\n```js\nAJAX('POST https://api.example.com/login/', { email: 'peter@example.com' }, function(err, response, meta) {\n\tconsole.log(meta.status, response);\n});\n```\n\nExample: Promise\n```js\nvar products = await AJAX('GET https://api.example.com/products/?page=1');\n```\n\nExample: XML odpoveď\n```js\n// the service answers <order id=\"100\"><name>Book</name><items><item>A</item><item>B</item></items></order>\nvar order = await AJAX('GET https://api.example.com/orders/100/');\n// { order__: { id: '100' }, order_name: 'Book', order_items_item: ['A', 'B'] }\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nStiahne vzdialený súbor na disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | URL alebo `{ socket, path }` pre Unix socket. |\n| `filename` | `String` | yes |  | Cieľová cesta k súboru. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout v milisekundách. |\n\nReturns: `Promise` Promise, keď nie je zadaný callback.\n\nStiahne `url` a zapíše telo do `filename`. Callback sa spustí, keď je súbor zapísaný, s `(err, response)`. `response` má `status`, `headers`, `origin`, `filename` a `size` (počet zapísaných bajtov). Telo sa uloží pri každom stavovom kóde, preto skontroluj `response.status`.\n\n`url` môže byť aj objekt `{ socket, path }` pre Unix socket. DNS dotazy sa ukladajú do cache. `timeout` je v milisekundách (8 sekúnd, keď nie je nastavený). Bez callbacku funkcia vracia promise, ktorý sa splní s `response`.\n\nExample: Stiahnutie obrázka\n```js\nDOWNLOAD('https://cdn.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (!err && response.status === 200)\n\t\tconsole.log('Saved', response.filename);\n});\n```\n\nExample: Promise\n```js\nvar response = await DOWNLOAD('https://example.com/data.csv', PATH.tmp('data.csv'));\n```\n\n### Total.download(url, filename, [callback], [timeout])\n\nType: `method`\n\nMetóda frameworku, ktorá stojí za DOWNLOAD().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | URL alebo `{ socket, path }` pre Unix socket. |\n| `filename` | `String` | yes |  | Cieľová cesta k súboru. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `8000` | Timeout v milisekundách. |\n\nReturns: `Promise` Promise, keď nie je zadaný callback.\n\nTá istá funkcia ako `DOWNLOAD()`. Stiahne `url` a zapíše telo do `filename`. Callback sa spustí, keď je súbor zapísaný, s `(err, response)`. `response` má `status`, `headers`, `origin`, `filename` a `size` (počet zapísaných bajtov). Telo sa uloží pri každom stavovom kóde, preto skontroluj `response.status`.\n\n`url` môže byť aj objekt `{ socket, path }` pre Unix socket. DNS dotazy sa ukladajú do cache. `timeout` je v milisekundách (8 sekúnd, keď nie je nastavený). Bez callbacku funkcia vracia promise, ktorý sa splní s `response`.\n\nExample: Stiahnutie\n```js\nTotal.download('https://example.com/export.json', PATH.tmp('export.json'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n### new RESTBuilder([url])\n\nType: `class`\n\nBuilder pre požiadavky na REST služby.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | URL požiadavky. |\n\nReturns: `RESTBuilder` Nový builder.\n\nGlobálna trieda. Nový builder má metódu `GET`, timeout 10 sekúnd, zapnutú DNS cache, hlavičku `user-agent: Total.js/v...` a `accept: application/json, text/plain, text/plain, text/xml`. Nič sa neodošle, kým nezavoláš `callback()`, `promise()`, `stream()` alebo `exec()`.\n\nZvyčajne začneš statickým pomocníkom: `RESTBuilder.GET()`, `POST()`, `PUT()`, `PATCH()`, `DELETE()`, `HEAD()`, `API()`, `url()` alebo `make()`. `RESTBuilder.url(url)` je to isté ako `new RESTBuilder(url)`.\n\nExample: Vytvorenie buildera\n```js\nvar builder = RESTBuilder.url('https://api.example.com/users/');\nbuilder.header('X-Token', CONF.apitoken);\nbuilder.callback(console.log);\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nVytvorí 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\nVytvorí builder bez URL a zavolá `fn(builder)`. URL nastav pomocou `builder.url()`. Metóda inštancie `builder.make(fn)` zavolá `fn` s builderom ako `this` a ako argumentom, pre opakovane použiteľné nastavenia.\n\nExample: Zostavenie požiadavky\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/users/');\n\tbuilder.post({ name: 'Peter' });\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nVytvorí GET požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL. |\n| `data` | `Object` | no |  | Odošle sa ako query string. |\n\nReturns: `RESTBuilder` Nový builder.\n\nVytvorí builder s metódou `GET`; z `data` sa stane query string. Pre `HEAD` požiadavku použi `RESTBuilder.HEAD(url)`: nemá dáta, spracovaná hodnota je prázdny objekt a čítaš `output.status` a `output.headers`.\n\nExample: Query string\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 20 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nExample: HEAD\n```js\nRESTBuilder.HEAD('https://example.com/').callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers['last-modified']);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nVytvorí POST požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL. |\n| `data` | `Object` | no |  | Odošle sa ako JSON telo. |\n\nReturns: `RESTBuilder` Nový builder.\n\nVytvorí builder s metódou `POST`; `data` sa pošlú ako JSON. `RESTBuilder.PUT()`, `RESTBuilder.PATCH()` a `RESTBuilder.DELETE()` fungujú rovnako so svojimi metódami.\n\nExample: POST JSON\n```js\nRESTBuilder.POST('https://api.example.com/orders/', { productid: 'p100', count: 2 }).promise().then(function(order) {\n\tconsole.log(order.id);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nVytvorí PUT požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL. |\n| `data` | `Object` | no |  | Odošle sa ako JSON telo. |\n\nReturns: `RESTBuilder` Nový builder.\n\nVytvorí builder s metódou `PUT`; `data` sa pošlú ako JSON.\n\nExample: PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nVytvorí PATCH požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL. |\n| `data` | `Object` | no |  | Odošle sa ako JSON telo. |\n\nReturns: `RESTBuilder` Nový builder.\n\nVytvorí builder s metódou `PATCH`; `data` sa pošlú ako JSON.\n\nExample: PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/p100/', { price: 99 }).callback(console.log);\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nVytvorí DELETE požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL. |\n| `data` | `Object` | no |  | Odošle sa ako JSON telo. |\n\nReturns: `RESTBuilder` Nový builder.\n\nVytvorí builder s metódou `DELETE`; `data` sa pošlú ako JSON.\n\nExample: DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/p100/').callback(console.log);\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nZavolá API endpoint Total.js aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL API endpointu. |\n| `name` | `String` | yes |  | Názov API operácie. |\n| `data` | `Object` | no |  | Dáta operácie. |\n\nReturns: `RESTBuilder` Nový builder.\n\nVytvorí požiadavku `POST` na API trasu Total.js (`ROUTE('API /api/ ...')`). Telo je JSON: `{ schema: name, data: data }`. `name` je názov API s voliteľnými parametrami, napríklad `'products_detail/p100'`. `builder.get(query)` ponechá `POST` a pošle query v tele ako `query`, vedľa `data`. `builder.compress()` vynechá z tela kľúče, ktorých hodnota je `null` alebo `undefined`.\n\nExample: Volanie API\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: S query\n```js\nRESTBuilder.API('https://app.example.com/api/', 'products_list', { category: 'shoes' }).get({ page: 2 }).callback(console.log);\n// body: { data: { category: 'shoes' }, query: { page: 2 }, schema: 'products_list' }\n```\n\n### builder.compress([value])\n\nType: `method`\n\nVynechá prázdne hodnoty z tela požiadavky RESTBuilder.API().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` to vypne. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nBez argumentu alebo s `true` sa JSON telo požiadavky `RESTBuilder.API()` zapíše bez kľúčov, ktorých hodnota je `null` alebo `undefined`, takže požiadavka je menšia. `compress(false)` to vypne. Ostatné buildery to neovplyvní.\n\nExample: Menšie telo\n```js\nRESTBuilder.API(CONF.erpapi, 'orders_save', { id: 'A1', note: null, total: 120 }).compress().callback(console.log);\n// data: { id: 'A1', total: 120 }\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nZaregistruje funkciu, ktorá zmení každý builder pred odoslaním.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nFunkcia sa spustí pre každý builder v aplikácii tesne pred vykonaním požiadavky, s builderom ako argumentom. Použi ju pre spoločné hlavičky alebo tokeny. Upgrady sa nedajú odstrániť.\n\nExample: Pridanie tokenu pre jednu službu\n```js\nRESTBuilder.upgrade(function(builder) {\n\tif (builder.url().startsWith(CONF.shopapi))\n\t\tbuilder.header('X-Token', CONF.shoptoken);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nNastaví alebo prečíta URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Nová URL. |\n\nReturns: `RESTBuilder|String` Builder alebo URL pri volaní bez argumentu.\n\nS argumentom nastaví URL a vráti builder; bez neho vráti aktuálnu URL.\n\nExample: Čítanie URL\n```js\nvar url = builder.url();\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 |  | HTTP metóda. |\n| `data` | `Object` | no |  | Dáta odoslané ako JSON. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nNastaví metódu (malé písmená sa prevedú na veľké). `data` sa pošlú ako JSON.\n\nSkratky: `builder.get([query])` nastaví `GET` a query string; `builder.post([data])`, `builder.put([data])`, `builder.patch([data])` a `builder.delete([data])` nastavia metódu a telo (v type nastavenom predtým, predvolene JSON); `builder.head()` nastaví `HEAD`. Názvy veľkými písmenami (`builder.POST()`) sú aliasy.\n\nExample: Skratky\n```js\nRESTBuilder.url('https://api.example.com/products/p100/').put({ price: 99 }).callback(console.log);\n```\n\n### builder.json([data])\n\nType: `method`\n\nPošle dáta ako JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Dáta. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nNastaví typ na JSON a telo na `data` (objekt sa serializuje pri odoslaní požiadavky). Z `GET` požiadavky sa stane `POST`.\n\nExample: JSON telo\n```js\nRESTBuilder.url('https://api.example.com/users/').json({ name: 'Peter' }).callback(console.log);\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nPošle dáta ako URL-kódovaný formulár.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Polia formulára. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nNastaví `Content-Type: application/x-www-form-urlencoded` a telo; objekt sa zakóduje pri odoslaní požiadavky. Z `GET` požiadavky sa stane `POST`.\n\nExample: Formulár\n```js\nRESTBuilder.url('https://example.com/login/').urlencoded({ name: 'peter', password: 'x' }).callback(console.log);\n```\n\n### builder.xml([data])\n\nType: `method`\n\nPošle XML telo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | XML. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nNastaví `Content-Type: text/xml` a telo. XML odovzdaj ako reťazec. Z `GET` požiadavky sa stane `POST`.\n\nExample: XML telo\n```js\nRESTBuilder.url('https://soap.example.com/').xml('<request><id>100</id></request>').callback(console.log);\n```\n\n### builder.raw(value, [type])\n\nType: `method`\n\nNastaví telo tak, ako je.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Telo. |\n| `type` | `String` | no |  | Krátky typ obsahu. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nNastaví telo bez akejkoľvek serializácie. `type` je jeden z krátkych typov `REQUEST()` (`'json'`, `'urlencoded'`, `'xml'`, `'html'`, `'plain'`, `'raw'`); bez neho nastav hlavičku pomocou `builder.type()`. Reťazec sa pošle nezmenený. `Buffer` potrebuje typ `'raw'` (`application/octet-stream`); bez typu sa serializuje ako JSON, rovnako ako objekt.\n\nExample: Binárne telo\n```js\nRESTBuilder.url('https://api.example.com/images/').post().raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.text(value)\n\nType: `method`\n\nPošle čistý text a nechá odpoveď nespracovanú.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Text. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\n`builder.plain(value)` je alias. Nastaví `Content-Type: text/plain` a telo a callback dostane namiesto spracovanej hodnoty surové telo odpovede.\n\nExample: Čistý text\n```js\nRESTBuilder.url('https://api.example.com/echo/').post().text('Hello').callback(function(err, response) {\n\t// response is the raw body\n});\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nPridá súbor a pošle multipart požiadavku.\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 odoslaný službe. |\n| `source` | `Buffer|String` | no |  | Buffer, cesta alebo URL. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nZ požiadavky sa stane `multipart/form-data` (z `GET` sa stane `POST`). `source` je `Buffer`, cesta na disku alebo URL, ktorá sa stiahne a streamuje. Bez `source` sa súbor číta z `filename`. Telo nastavené pomocou `json()` alebo `urlencoded()` sa pošle ako ďalšie polia formulára, keď je to objekt.\n\nExample: Nahratie dvoch súborov\n```js\nRESTBuilder.POST('https://files.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.tmp('photo.jpg'))\n\t.file('logo', 'logo.png', 'https://cdn.example.com/logo.png')\n\t.callback(console.log);\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` Ten istý builder, pre reťazenie.\n\nNastaví jednu hlavičku. Pomocníci pre bežné hlavičky: `builder.referrer(url)` (alias `referer()`) nastaví `Referer`, `builder.origin(url)` nastaví `Origin`, `builder.csrf(token)` nastaví `X-Csrf-Token` a `builder.xhr()` pridá `X-Requested-With: XMLHttpRequest`.\n\nExample: Hlavičky\n```js\nbuilder.header('X-Token', CONF.apitoken).origin('https://www.example.com').xhr();\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 |  | MIME typ. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nNastaví `Content-Type` na úplný MIME typ. Typ nastavený pomocou `json()`, `urlencoded()`, `xml()` alebo `text()` ho nahradí, preto ho používaj s `raw(value)`.\n\nExample: Vlastný typ\n```js\nbuilder.raw('{\"id\":1}').type('application/vnd.api+json');\n```\n\n### builder.accept(ext)\n\nType: `method`\n\nNastaví hlavičku Accept.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Prípona alebo MIME typ. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nPrijme príponu súboru (`'json'`, `'xml'`, `'html'`...) a prevedie ju na jej MIME typ; dlhšia hodnota sa použije tak, ako je.\n\nExample: Prijímanie XML\n```js\nbuilder.accept('xml');\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` Ten istý builder, pre reťazenie.\n\nS `user` a `password` nastaví basic autentifikáciu (`Basic base64(user:password)`). S jedným argumentom sa hodnota použije tak, ako je, napríklad `'Bearer TOKEN'`.\n\nExample: Basic a Bearer\n```js\nbuilder.auth('admin', 'secret');\nbuilder.auth('Bearer ' + CONF.apitoken);\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 cookie. |\n| `value` | `String` | yes |  | Hodnota. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nPridá jednu cookie. `builder.cookies(obj)` nahradí všetky cookies objektom `{ name: value }`.\n\nExample: Cookies\n```js\nbuilder.cookie('session', token);\nbuilder.cookies({ lang: 'en', theme: 'dark' });\n```\n\n### builder.cook([value])\n\nType: `method`\n\nUchová cookies odpovede v builderi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | no | `true` | `false` to vypne. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nS `cook()` sa cookies nastavené odpoveďou uložia v builderi a pošlú sa s ďalšou požiadavkou toho istého buildera. Potom ich obsahuje `output.cookies`. `cook(false)` to vypne.\n\nExample: Prihlásenie, potom čítanie\n```js\nRESTBuilder.url('https://example.com/login/').cook().urlencoded({ name: 'peter', password: 'x' }).callback(function(err, response, output) {\n\tRESTBuilder.GET('https://example.com/profile/').cookies(output.cookies).callback(console.log);\n});\n```\n\n### builder.timeout(ms)\n\nType: `method`\n\nNastaví timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes |  | Milisekundy. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nTimeout v milisekundách (predvolene 10000). `0` ho vypne. Keď vyprší, chyba je `408: Request Timeout`.\n\nExample: Päť sekúnd\n```js\nbuilder.timeout(5000);\n```\n\n### builder.keepalive([val])\n\nType: `method`\n\nOpakovane používa spojenia s keep-alive agentom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `val` | `Boolean` | no | `true` | Zapne alebo vypne keep-alive. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nBez argumentu (alebo s pravdivou hodnotou) požiadavka použije zdieľaného keep-alive agenta frameworku, takže spojenia s rovnakým hostom sa opakovane používajú. `keepalive(false)` to vypne. Nepoužíva sa spolu s proxy.\n\nExample: Keep-alive\n```js\nRESTBuilder.GET('https://api.example.com/ping/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nPošle požiadavku cez proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Proxy. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\n`url` je `'host:port'` alebo `'http://host:port'`. S `http://user:password@host:port` sa prihlasovacie údaje pošlú ako `Proxy-Authorization: Basic`. HTTPS ciele sa tunelujú pomocou `CONNECT`. Bez neho sa použije proxy z konfiguračného kľúča `$proxyrequest`, keď je nastavený.\n\nExample: Proxy\n```js\nbuilder.proxy('http://10.0.0.5:3128');\n```\n\nExample: Proxy s prihlásením\n```js\nbuilder.proxy('http://user:secret@10.0.0.5:3128');\n```\n\n### builder.insecure()\n\nType: `method`\n\nPrijme neplatné TLS certifikáty.\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nPrijme self-signed alebo expirované certifikáty služby. Používaj to iba pre interné služby.\n\nExample: Self-signed\n```js\nRESTBuilder.GET('https://10.0.0.20/api/').insecure().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` Ten istý builder, pre reťazenie.\n\nPre služby, ktoré vyžadujú klientske certifikáty.\n\nExample: Klientsky certifikát\n```js\nbuilder.cert(Total.Fs.readFileSync(PATH.root('client.key')), Total.Fs.readFileSync(PATH.root('client.crt')));\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nPošle požiadavku cez Unix socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | Súbor socketu. |\n| `path` | `String` | yes |  | Cesta požiadavky, napríklad `/api/`. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nPripojí sa k súboru socketu namiesto hosta; `path` je URL cesta požiadavky.\n\nExample: Docker API\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/docker.sock', '/containers/json');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nVypne DNS cache pre túto požiadavku.\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nPredvolene builder preloží hostname raz a jeho adresy si uloží do cache. S `nodnscache()` ho Node.js preloží pri každej požiadavke.\n\nExample: Bez DNS cache\n```js\nbuilder.nodnscache();\n```\n\n### builder.redirect(value)\n\nType: `method`\n\nZapne alebo vypne nasledovanie presmerovaní.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean` | yes |  | `false` zastaví nasledovanie presmerovaní. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\n`redirect(false)` vráti samotnú odpoveď `301` alebo `302`; cieľ si prečítaj v `output.headers.location`. Predvolene sa nasledujú najviac štyri presmerovania.\n\nExample: Čítanie location\n```js\nRESTBuilder.GET('https://example.com/short/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.status, output.headers.location);\n});\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` | yes |  | Šifrovací kľúč. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nTelo sa zašifruje pomocou `key` a pošle s hlavičkou `X-Encryption: a`; textová odpoveď sa dešifruje tým istým kľúčom. Obe strany musia používať rovnaký kľúč.\n\nExample: Šifrované volanie\n```js\nbuilder.encrypt(CONF.sharedkey);\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` Ten istý builder, pre reťazenie.\n\nZavolá `fn(percentage)` pre každý prijatý chunk. Percento je známe iba vtedy, keď má odpoveď `Content-Length`, inak je `0`.\n\nExample: Priebeh\n```js\nbuilder.progress(function(percentage) {\n\tconsole.log(percentage.toFixed(1) + '%');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nVráti surové telo odpovede.\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nCallback dostane telo ako reťazec (alebo `Buffer` pre binárne typy) namiesto spracovanej hodnoty.\n\nExample: Surové HTML\n```js\nRESTBuilder.GET('https://example.com/').noparse().callback(function(err, html) {\n\tconsole.log(html.length);\n});\n```\n\n### builder.base64()\n\nType: `method`\n\nVráti telo odpovede ako base64.\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nCallback dostane telo zakódované v base64, napríklad na vloženie obrázka ako data URI.\n\nExample: Data URI\n```js\nRESTBuilder.GET('https://cdn.example.com/logo.png').base64().callback(function(err, data) {\n\tvar uri = 'data:image/png;base64,' + data;\n});\n```\n\n### builder.debug()\n\nType: `method`\n\nVypíše požiadavku a odpoveď do konzoly.\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nPo príchode odpovede vypíše stav, metódu, URL s query, chybu a surové telo.\n\nExample: Debug\n```js\nRESTBuilder.GET('https://api.example.com/products/').debug().callback(NOOP);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nPošle požiadavku a prijme spracovanú odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)` alebo `$` akcie. |\n\nReturns: `RESTBuilder|Promise` Builder alebo promise, keď sa volá bez argumentu.\n\nOdošle požiadavku v nasledujúcom ticku a výsledok odovzdá do `fn(err, response, output)`:\n\n- `response`: telo spracované podľa jeho `Content-Type` (JSON, aj pre `text/plain`; URL-encoded; XML cez HTML parser; ostatné telá sa spracujú ako JSON, keď vyzerajú ako JSON). Prázdne telo dá prázdny objekt; odpoveď `204` dá `true`.\n- `output`: `status`, `headers`, `response` (surové telo), `hostname`, `origin`, `cookies` (s `cook()`) a `output.cookie(name)`, ktorá prečíta cookie odpovede.\n- `err`: sieťová chyba alebo `'408: Request Timeout'`; `ErrorBuilder`, keď je telo pole chýb Total.js (`[{ error: '...' }]`, `response` je potom `null`); inak pri stave `400` alebo vyššom `ErrorBuilder` s jednou chybou, ktorej názov je stavový kód a správa je surové telo. Hodnota nastavená cez `builder.error()` nahradí akúkoľvek chybu.\n\n`fn` môže byť aj `$` akcie: spracovaná odpoveď sa odovzdá do `$.callback()` a chyba sa pridá k chybám `$`. Bez argumentu vracia promise, ktorý sa splní s `response` a zamietne s `err`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/products/').callback(function(err, response, output) {\n\tif (err)\n\t\treturn console.log(err);\n\tconsole.log(output.status, response.length);\n});\n```\n\nExample: V akcii\n```js\nNEWACTION('Products/sync', {\n\tname: 'Sync products',\n\taction: function($) {\n\t\tRESTBuilder.GET(CONF.shopapi + '/products/').callback($);\n\t}\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 |  | `$` akcie. |\n\nReturns: `Promise` Vyrieši sa so spracovanou odpoveďou.\n\nPromise sa vyrieši so spracovanou odpoveďou. Pri chybe sa zamietne s `Error` vytvoreným z chyby (z `ErrorBuilder` sa stane `Error` s jeho správami). S `$` ide chyba namiesto toho do `$.invalid()` a promise sa nezamietne.\n\nExample: await\n```js\nvar user = await RESTBuilder.GET('https://api.example.com/users/100/').promise();\n```\n\nExample: S $\n```js\nvar order = await RESTBuilder.POST(CONF.shopapi + '/orders/', model).promise($);\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` Ten istý builder, pre reťazenie.\n\nPošle požiadavku okamžite a zavolá `callback(err, response, output)` s rovnakými hodnotami ako `callback()`. Uprednostni `callback()`, ktorý čaká na nasledujúci tick. Keď `callback` chýba, výsledok sa ignoruje.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nVráti odpoveď ako stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nPošle požiadavku v nasledujúcom ticku a zavolá `callback(err, response)` hneď, ako prídu hlavičky. `response` má `status`, `headers`, `origin` a `stream` (Node.js odpoveď, ešte neprečítaná). Používaj to pre veľké súbory.\n\nExample: Uloženie veľkého súboru\n```js\nRESTBuilder.GET('https://cdn.example.com/backup.zip').stream(function(err, response) {\n\tif (!err && response.status === 200)\n\t\tresponse.stream.pipe(Total.Fs.createWriteStream(PATH.tmp('backup.zip')));\n});\n```\n\n### builder.error(value)\n\nType: `method` · Since: `0.0.16`\n\nNahradí akúkoľvek chybu vlastnou hodnotou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String` | yes |  | Chyba, ktorá sa vráti, napríklad správa alebo `ErrorBuilder`. |\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nKeď požiadavka skončí akoukoľvek chybou (sieť, časový limit alebo stav `400` či vyšší), callback alebo promise dostane namiesto nej `value`. Použi to na skrytie detailov vzdialenej služby pred používateľmi.\n\nExample: Vlastná chyba\n```js\nRESTBuilder.GET(CONF.stockapi).error('The stock service is not available').callback($);\n```\n\n### builder.logerror()\n\nType: `method` · Since: `0.0.16`\n\nVypisuje chyby do konzoly.\n\nReturns: `RESTBuilder` Ten istý builder, pre reťazenie.\n\nKeď požiadavka skončí chybou, chyba (alebo surové telo odpovede) sa odovzdá chybovému handleru frameworku, ktorý ju vypíše s názvom `RESTBuilder` a s metódou a URL požiadavky. Callback chybu aj tak dostane.\n\nExample: Zaznamenanie chýb\n```js\nRESTBuilder.POST(CONF.crmapi + '/contacts/', model).logerror().callback($);\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"AJAX()","signature":"AJAX('METHOD url', [data], [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"Total.download()","signature":"Total.download(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"class","name":"RESTBuilder","signature":"new RESTBuilder([url])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","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.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"builder.compress()","signature":"builder.compress([value])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","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.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])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, [type])","since":"","deprecated":false},{"type":"method","name":"builder.text()","signature":"builder.text(value)","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","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(ext)","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([value])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive([val])","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.insecure()","signature":"builder.insecure()","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt(key)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.base64()","signature":"builder.base64()","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.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(value)","since":"0.0.16","deprecated":false},{"type":"method","name":"builder.logerror()","signature":"builder.logerror()","since":"0.0.16","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafqpA1tr60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/openclient/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"OpenClient","summary":"OPENCLIENT() and the methods of a client.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/openclient/\nupdated: 2026-11-18T16:56:49.572Z\n---\n\n# OpenClient\n\n> OPENCLIENT() and the methods of a client.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nOpens a WebSocket client for request-response messages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The WebSocket URL (`ws://`, `wss://`, `http://` or `https://`). |\n| `id` | `String` | no |  | A client identifier; a random one is generated when omitted. |\n\nReturns: `Object` The client.\n\nConnects to a WebSocket endpoint (`http` in the URL is changed to `ws`). All clients with the same URL share one connection, which reconnects when the server goes away. A client created with an `id` that already exists replaces the old client.\n\nWhen the server sends a message `{ type: 'init', id: '...' }`, every client gets `client.meta` (the message), `client.type` (its `id`) and its `online()` handler runs. `client.connected` is `true` while the connection is open. Messages that are not answers to `rpc()` go to the `message()` handler.\n\nExample: Connect\n```js\nvar client = OPENCLIENT('wss://service.example.com/$client/', 'myservice');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'Connected to ' + meta.id : 'Offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### client.send(msg, [callback], [timeout])\n\nType: `method`\n\nSends a message to the server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | The message. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Milliseconds to wait for the answer. |\n\nReturns: `Object` The client, for chaining.\n\nSends `msg` (an object, as JSON). With `callback` the message gets a `callbackid` and the callback runs with `(err, response)` when the server answers `{ callbackid, error, response }`, with `'timeout'` after `timeout` milliseconds, or with `'offline'` when there is no connection. While the connection is closed the message is retried every 500 ms, up to ten times.\n\n`client.cmd(msg)` sends a message without waiting for an answer.\n\nExample: Send and wait\n```js\nclient.send({ type: 'users' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n```\n\nExample: Command\n```js\nclient.cmd({ type: 'refresh' });\n```\n\n### client.rpc(msg, [callback], [timeout])\n\nType: `method`\n\nSends a message and waits for the answer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | The message. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Milliseconds to wait. |\n\nReturns: `Promise|Object` A promise without a callback.\n\nThe same as `send()` with a callback. Without a callback it returns a promise that resolves with the response and rejects with the error (`'timeout'`, `'offline'` or the `error` of the answer).\n\nExample: await\n```js\nvar users = await client.rpc({ type: 'users', page: 1 }, 5000);\n```\n\n### client.message(fn)\n\nType: `method`\n\nSets the handler of incoming messages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Object` The client, for chaining.\n\nRuns for every message from the server that is not an answer to `send()` or `rpc()` and is not the `init` message.\n\nExample: Messages\n```js\nclient.message(function(msg) {\n\tif (msg.type === 'notify')\n\t\tconsole.log(msg.body);\n});\n```\n\n### client.online(fn)\n\nType: `method`\n\nSets the handler of online and offline changes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(meta)`. |\n\nReturns: `Object` The client, for chaining.\n\nRuns with the `init` message of the server when the service is ready, and with `null` when the connection closes.\n\nExample: Online state\n```js\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n```\n\n### client.error(fn)\n\nType: `method`\n\nSets the handler of connection errors.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `Object` The client, for chaining.\n\nRuns with the error message when the connection fails, and with `(code, message)` when the server closes it with a code of 4000 or more. Pending `rpc()` calls are rejected with the error.\n\nExample: Errors\n```js\nclient.error(function(err) {\n\tconsole.log('OPENCLIENT error', err);\n});\n```\n\n### client.close()\n\nType: `method`\n\nRemoves the client.\n\n`client.remove()` is an alias. Pending callbacks of this client receive `'offline'`. The shared connection is closed when it has no other clients.\n\nExample: Close\n```js\nclient.close();\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.rpc()","signature":"client.rpc(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.message()","signature":"client.message(fn)","since":"","deprecated":false},{"type":"method","name":"client.online()","signature":"client.online(fn)","since":"","deprecated":false},{"type":"method","name":"client.error()","signature":"client.error(fn)","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:49.572Z"}
{"id":"JafqpA1tr60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/openclient/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"OpenClient","summary":"OPENCLIENT() und die Methoden eines Clients.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/openclient/\nupdated: 2026-11-18T16:56:49.572Z\n---\n\n# OpenClient\n\n> OPENCLIENT() und die Methoden eines Clients.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nÖffnet einen WebSocket-Client für Request-Response-Nachrichten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die WebSocket-URL (`ws://`, `wss://`, `http://` oder `https://`). |\n| `id` | `String` | no |  | Ein Client-Bezeichner; wird er weggelassen, wird ein zufälliger erzeugt. |\n\nReturns: `Object` Der Client.\n\nVerbindet sich mit einem WebSocket-Endpunkt (`http` in der URL wird zu `ws` geändert). Alle Clients mit derselben URL teilen sich eine Verbindung, die sich neu verbindet, wenn der Server wegfällt. Ein Client, der mit einer bereits vorhandenen `id` erstellt wird, ersetzt den alten Client.\n\nSendet der Server eine Nachricht `{ type: 'init', id: '...' }`, erhält jeder Client `client.meta` (die Nachricht) und `client.type` (ihre `id`), und sein Handler `online()` läuft. `client.connected` ist `true`, solange die Verbindung offen ist. Nachrichten, die keine Antworten auf `rpc()` sind, gehen an den Handler `message()`.\n\nExample: Verbinden\n```js\nvar client = OPENCLIENT('wss://service.example.com/$client/', 'myservice');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'Connected to ' + meta.id : 'Offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### client.send(msg, [callback], [timeout])\n\nType: `method`\n\nSendet eine Nachricht an den Server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Die Nachricht. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Millisekunden, die auf die Antwort gewartet wird. |\n\nReturns: `Object` Der Client, für Verkettung.\n\nSendet `msg` (ein Objekt, als JSON). Mit `callback` erhält die Nachricht eine `callbackid`, und der Callback läuft mit `(err, response)`, wenn der Server mit `{ callbackid, error, response }` antwortet, mit `'timeout'` nach `timeout` Millisekunden oder mit `'offline'`, wenn keine Verbindung besteht. Solange die Verbindung geschlossen ist, wird die Nachricht alle 500 ms erneut versucht, bis zu zehnmal.\n\n`client.cmd(msg)` sendet eine Nachricht, ohne auf eine Antwort zu warten.\n\nExample: Senden und warten\n```js\nclient.send({ type: 'users' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n```\n\nExample: Befehl\n```js\nclient.cmd({ type: 'refresh' });\n```\n\n### client.rpc(msg, [callback], [timeout])\n\nType: `method`\n\nSendet eine Nachricht und wartet auf die Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Die Nachricht. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Wartezeit in Millisekunden. |\n\nReturns: `Promise|Object` Eine Promise ohne Callback.\n\nDasselbe wie `send()` mit einem Callback. Ohne Callback wird eine Promise zurückgegeben, die mit der Antwort aufgelöst und mit dem Fehler abgelehnt wird (`'timeout'`, `'offline'` oder der `error` der Antwort).\n\nExample: await\n```js\nvar users = await client.rpc({ type: 'users', page: 1 }, 5000);\n```\n\n### client.message(fn)\n\nType: `method`\n\nSetzt den Handler für eingehende Nachrichten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Object` Der Client, für Verkettung.\n\nLäuft für jede Nachricht vom Server, die keine Antwort auf `send()` oder `rpc()` und nicht die `init`-Nachricht ist.\n\nExample: Nachrichten\n```js\nclient.message(function(msg) {\n\tif (msg.type === 'notify')\n\t\tconsole.log(msg.body);\n});\n```\n\n### client.online(fn)\n\nType: `method`\n\nSetzt den Handler für Online- und Offline-Wechsel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(meta)`. |\n\nReturns: `Object` Der Client, für Verkettung.\n\nLäuft mit der `init`-Nachricht des Servers, wenn der Dienst bereit ist, und mit `null`, wenn die Verbindung geschlossen wird.\n\nExample: Online-Status\n```js\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n```\n\n### client.error(fn)\n\nType: `method`\n\nSetzt den Handler für Verbindungsfehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `Object` Der Client, für Verkettung.\n\nLäuft mit der Fehlermeldung, wenn die Verbindung fehlschlägt, und mit `(code, message)`, wenn der Server sie mit einem Code von 4000 oder höher schließt. Ausstehende `rpc()`-Aufrufe werden mit dem Fehler abgelehnt.\n\nExample: Fehler\n```js\nclient.error(function(err) {\n\tconsole.log('OPENCLIENT error', err);\n});\n```\n\n### client.close()\n\nType: `method`\n\nEntfernt den Client.\n\n`client.remove()` ist ein Alias. Ausstehende Callbacks dieses Clients erhalten `'offline'`. Die gemeinsame Verbindung wird geschlossen, wenn sie keine anderen Clients mehr hat.\n\nExample: Schließen\n```js\nclient.close();\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.rpc()","signature":"client.rpc(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.message()","signature":"client.message(fn)","since":"","deprecated":false},{"type":"method","name":"client.online()","signature":"client.online(fn)","since":"","deprecated":false},{"type":"method","name":"client.error()","signature":"client.error(fn)","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:49.572Z"}
{"id":"JafqpA1tr60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/openclient/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"OpenClient","summary":"OPENCLIENT() y los métodos de un cliente.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/openclient/\nupdated: 2026-11-18T16:56:49.572Z\n---\n\n# OpenClient\n\n> OPENCLIENT() y los métodos de un cliente.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nAbre un cliente WebSocket para mensajes de petición y respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL WebSocket (`ws://`, `wss://`, `http://` o `https://`). |\n| `id` | `String` | no |  | Un identificador del cliente; si se omite, se genera uno aleatorio. |\n\nReturns: `Object` El cliente.\n\nSe conecta a un endpoint WebSocket (`http` en la URL se cambia por `ws`). Todos los clientes con la misma URL comparten una conexión, que se reconecta cuando el servidor desaparece. Un cliente creado con un `id` que ya existe sustituye al cliente anterior.\n\nCuando el servidor envía un mensaje `{ type: 'init', id: '...' }`, cada cliente recibe `client.meta` (el mensaje) y `client.type` (su `id`), y se ejecuta su handler `online()`. `client.connected` es `true` mientras la conexión está abierta. Los mensajes que no son respuestas a `rpc()` van al handler `message()`.\n\nExample: Conectar\n```js\nvar client = OPENCLIENT('wss://service.example.com/$client/', 'myservice');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'Connected to ' + meta.id : 'Offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### client.send(msg, [callback], [timeout])\n\nType: `method`\n\nEnvía un mensaje al servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | El mensaje. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Milisegundos que se espera la respuesta. |\n\nReturns: `Object` El cliente, para encadenar.\n\nEnvía `msg` (un objeto, como JSON). Con `callback`, el mensaje recibe un `callbackid` y el callback se ejecuta con `(err, response)` cuando el servidor responde `{ callbackid, error, response }`, con `'timeout'` tras `timeout` milisegundos, o con `'offline'` cuando no hay conexión. Mientras la conexión está cerrada, el mensaje se reintenta cada 500 ms, hasta diez veces.\n\n`client.cmd(msg)` envía un mensaje sin esperar respuesta.\n\nExample: Enviar y esperar\n```js\nclient.send({ type: 'users' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n```\n\nExample: Comando\n```js\nclient.cmd({ type: 'refresh' });\n```\n\n### client.rpc(msg, [callback], [timeout])\n\nType: `method`\n\nEnvía un mensaje y espera la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | El mensaje. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Milisegundos de espera. |\n\nReturns: `Promise|Object` Una promesa sin callback.\n\nLo mismo que `send()` con un callback. Sin callback, devuelve una promesa que se resuelve con la respuesta y se rechaza con el error (`'timeout'`, `'offline'` o el `error` de la respuesta).\n\nExample: await\n```js\nvar users = await client.rpc({ type: 'users', page: 1 }, 5000);\n```\n\n### client.message(fn)\n\nType: `method`\n\nAsigna el handler de los mensajes entrantes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Object` El cliente, para encadenar.\n\nSe ejecuta para cada mensaje del servidor que no es una respuesta a `send()` o `rpc()` y no es el mensaje `init`.\n\nExample: Mensajes\n```js\nclient.message(function(msg) {\n\tif (msg.type === 'notify')\n\t\tconsole.log(msg.body);\n});\n```\n\n### client.online(fn)\n\nType: `method`\n\nAsigna el handler de los cambios de conexión y desconexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(meta)`. |\n\nReturns: `Object` El cliente, para encadenar.\n\nSe ejecuta con el mensaje `init` del servidor cuando el servicio está listo, y con `null` cuando se cierra la conexión.\n\nExample: Estado de conexión\n```js\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n```\n\n### client.error(fn)\n\nType: `method`\n\nAsigna el handler de los errores de conexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `Object` El cliente, para encadenar.\n\nSe ejecuta con el mensaje de error cuando falla la conexión, y con `(code, message)` cuando el servidor la cierra con un código de 4000 o mayor. Las llamadas `rpc()` pendientes se rechazan con el error.\n\nExample: Errores\n```js\nclient.error(function(err) {\n\tconsole.log('OPENCLIENT error', err);\n});\n```\n\n### client.close()\n\nType: `method`\n\nElimina el cliente.\n\n`client.remove()` es un alias. Los callbacks pendientes de este cliente reciben `'offline'`. La conexión compartida se cierra cuando no tiene otros clientes.\n\nExample: Cerrar\n```js\nclient.close();\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.rpc()","signature":"client.rpc(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.message()","signature":"client.message(fn)","since":"","deprecated":false},{"type":"method","name":"client.online()","signature":"client.online(fn)","since":"","deprecated":false},{"type":"method","name":"client.error()","signature":"client.error(fn)","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:49.572Z"}
{"id":"JafqpA1tr60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/openclient/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"OpenClient","summary":"OPENCLIENT() et les méthodes d'un client.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/openclient/\nupdated: 2026-11-18T16:56:49.572Z\n---\n\n# OpenClient\n\n> OPENCLIENT() et les méthodes d'un client.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nOuvre un client WebSocket pour des messages de type requête-réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL WebSocket (`ws://`, `wss://`, `http://` ou `https://`). |\n| `id` | `String` | no |  | Un identifiant de client ; un identifiant aléatoire est généré s'il est omis. |\n\nReturns: `Object` Le client.\n\nSe connecte à un endpoint WebSocket (`http` dans l'URL est remplacé par `ws`). Tous les clients avec la même URL partagent une même connexion, qui se reconnecte lorsque le serveur disparaît. Un client créé avec un `id` qui existe déjà remplace l'ancien client.\n\nLorsque le serveur envoie un message `{ type: 'init', id: '...' }`, chaque client reçoit `client.meta` (le message), `client.type` (son `id`) et son gestionnaire `online()` s'exécute. `client.connected` vaut `true` tant que la connexion est ouverte. Les messages qui ne sont pas des réponses à `rpc()` vont au gestionnaire `message()`.\n\nExample: Se connecter\n```js\nvar client = OPENCLIENT('wss://service.example.com/$client/', 'myservice');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'Connected to ' + meta.id : 'Offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### client.send(msg, [callback], [timeout])\n\nType: `method`\n\nEnvoie un message au serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Le message. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Millisecondes d'attente de la réponse. |\n\nReturns: `Object` Le client, pour le chaînage.\n\nEnvoie `msg` (un objet, en JSON). Avec `callback`, le message reçoit un `callbackid` et le callback s'exécute avec `(err, response)` lorsque le serveur répond `{ callbackid, error, response }`, avec `'timeout'` au bout de `timeout` millisecondes, ou avec `'offline'` lorsqu'il n'y a pas de connexion. Tant que la connexion est fermée, l'envoi du message est retenté toutes les 500 ms, jusqu'à dix fois.\n\n`client.cmd(msg)` envoie un message sans attendre de réponse.\n\nExample: Envoyer et attendre\n```js\nclient.send({ type: 'users' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n```\n\nExample: Commande\n```js\nclient.cmd({ type: 'refresh' });\n```\n\n### client.rpc(msg, [callback], [timeout])\n\nType: `method`\n\nEnvoie un message et attend la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Le message. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Millisecondes d'attente. |\n\nReturns: `Promise|Object` Une promesse sans callback.\n\nIdentique à `send()` avec un callback. Sans callback, elle renvoie une promesse résolue avec la réponse et rejetée avec l'erreur (`'timeout'`, `'offline'` ou le `error` de la réponse).\n\nExample: await\n```js\nvar users = await client.rpc({ type: 'users', page: 1 }, 5000);\n```\n\n### client.message(fn)\n\nType: `method`\n\nDéfinit le gestionnaire des messages entrants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Object` Le client, pour le chaînage.\n\nS'exécute pour chaque message du serveur qui n'est pas une réponse à `send()` ou `rpc()` et qui n'est pas le message `init`.\n\nExample: Messages\n```js\nclient.message(function(msg) {\n\tif (msg.type === 'notify')\n\t\tconsole.log(msg.body);\n});\n```\n\n### client.online(fn)\n\nType: `method`\n\nDéfinit le gestionnaire des passages en ligne et hors ligne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(meta)`. |\n\nReturns: `Object` Le client, pour le chaînage.\n\nS'exécute avec le message `init` du serveur lorsque le service est prêt, et avec `null` lorsque la connexion se ferme.\n\nExample: État en ligne\n```js\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n```\n\n### client.error(fn)\n\nType: `method`\n\nDéfinit le gestionnaire des erreurs de connexion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `Object` Le client, pour le chaînage.\n\nS'exécute avec le message d'erreur lorsque la connexion échoue, et avec `(code, message)` lorsque le serveur la ferme avec un code de 4000 ou plus. Les appels `rpc()` en attente sont rejetés avec l'erreur.\n\nExample: Erreurs\n```js\nclient.error(function(err) {\n\tconsole.log('OPENCLIENT error', err);\n});\n```\n\n### client.close()\n\nType: `method`\n\nRetire le client.\n\n`client.remove()` est un alias. Les callbacks en attente de ce client reçoivent `'offline'`. La connexion partagée est fermée lorsqu'elle n'a plus d'autres clients.\n\nExample: Fermer\n```js\nclient.close();\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.rpc()","signature":"client.rpc(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.message()","signature":"client.message(fn)","since":"","deprecated":false},{"type":"method","name":"client.online()","signature":"client.online(fn)","since":"","deprecated":false},{"type":"method","name":"client.error()","signature":"client.error(fn)","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:49.572Z"}
{"id":"JafqpA1tr60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/openclient/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"OpenClient","summary":"OPENCLIENT() e i metodi di un client.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/openclient/\nupdated: 2026-11-18T16:56:49.572Z\n---\n\n# OpenClient\n\n> OPENCLIENT() e i metodi di un client.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nApre un client WebSocket per messaggi richiesta-risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL WebSocket (`ws://`, `wss://`, `http://` o `https://`). |\n| `id` | `String` | no |  | Un identificatore del client; se omesso ne viene generato uno casuale. |\n\nReturns: `Object` Il client.\n\nSi connette a un endpoint WebSocket (`http` nell'URL viene cambiato in `ws`). Tutti i client con lo stesso URL condividono un'unica connessione, che si riconnette quando il server scompare. Un client creato con un `id` già esistente sostituisce il vecchio client.\n\nQuando il server invia un messaggio `{ type: 'init', id: '...' }`, ogni client riceve `client.meta` (il messaggio), `client.type` (il suo `id`) e viene eseguito il suo handler `online()`. `client.connected` è `true` finché la connessione è aperta. I messaggi che non sono risposte a `rpc()` vanno all'handler `message()`.\n\nExample: Connettersi\n```js\nvar client = OPENCLIENT('wss://service.example.com/$client/', 'myservice');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'Connected to ' + meta.id : 'Offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### client.send(msg, [callback], [timeout])\n\nType: `method`\n\nInvia un messaggio al server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Il messaggio. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Millisecondi di attesa della risposta. |\n\nReturns: `Object` Il client, per il concatenamento.\n\nInvia `msg` (un oggetto, come JSON). Con `callback` il messaggio riceve un `callbackid` e la callback viene eseguita con `(err, response)` quando il server risponde `{ callbackid, error, response }`, con `'timeout'` dopo `timeout` millisecondi, oppure con `'offline'` quando non c'è connessione. Mentre la connessione è chiusa il messaggio viene ritentato ogni 500 ms, fino a dieci volte.\n\n`client.cmd(msg)` invia un messaggio senza attendere una risposta.\n\nExample: Inviare e attendere\n```js\nclient.send({ type: 'users' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n```\n\nExample: Comando\n```js\nclient.cmd({ type: 'refresh' });\n```\n\n### client.rpc(msg, [callback], [timeout])\n\nType: `method`\n\nInvia un messaggio e attende la risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Il messaggio. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Millisecondi di attesa. |\n\nReturns: `Promise|Object` Una promise senza callback.\n\nEquivale a `send()` con una callback. Senza callback restituisce una promise che si risolve con la risposta e viene rifiutata con l'errore (`'timeout'`, `'offline'` o l'`error` della risposta).\n\nExample: await\n```js\nvar users = await client.rpc({ type: 'users', page: 1 }, 5000);\n```\n\n### client.message(fn)\n\nType: `method`\n\nImposta l'handler dei messaggi in arrivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Object` Il client, per il concatenamento.\n\nViene eseguito per ogni messaggio del server che non è una risposta a `send()` o `rpc()` e non è il messaggio `init`.\n\nExample: Messaggi\n```js\nclient.message(function(msg) {\n\tif (msg.type === 'notify')\n\t\tconsole.log(msg.body);\n});\n```\n\n### client.online(fn)\n\nType: `method`\n\nImposta l'handler dei cambi di stato online e offline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(meta)`. |\n\nReturns: `Object` Il client, per il concatenamento.\n\nViene eseguito con il messaggio `init` del server quando il servizio è pronto, e con `null` quando la connessione si chiude.\n\nExample: Stato online\n```js\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n```\n\n### client.error(fn)\n\nType: `method`\n\nImposta l'handler degli errori di connessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `Object` Il client, per il concatenamento.\n\nViene eseguito con il messaggio di errore quando la connessione fallisce, e con `(code, message)` quando il server la chiude con un codice 4000 o superiore. Le chiamate `rpc()` in sospeso vengono rifiutate con l'errore.\n\nExample: Errori\n```js\nclient.error(function(err) {\n\tconsole.log('OPENCLIENT error', err);\n});\n```\n\n### client.close()\n\nType: `method`\n\nRimuove il client.\n\n`client.remove()` è un alias. Le callback in sospeso di questo client ricevono `'offline'`. La connessione condivisa viene chiusa quando non ha altri client.\n\nExample: Chiudere\n```js\nclient.close();\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.rpc()","signature":"client.rpc(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.message()","signature":"client.message(fn)","since":"","deprecated":false},{"type":"method","name":"client.online()","signature":"client.online(fn)","since":"","deprecated":false},{"type":"method","name":"client.error()","signature":"client.error(fn)","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:49.572Z"}
{"id":"JafqpA1tr60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/openclient/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"OpenClient","summary":"OPENCLIENT() a metódy klienta.","markdown":"---\ntitle: OpenClient\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/openclient/\nupdated: 2026-11-18T16:56:49.572Z\n---\n\n# OpenClient\n\n> OPENCLIENT() a metódy klienta.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nOtvorí WebSocket klienta pre správy typu požiadavka-odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | WebSocket URL (`ws://`, `wss://`, `http://` alebo `https://`). |\n| `id` | `String` | no |  | Identifikátor klienta; ak chýba, vygeneruje sa náhodný. |\n\nReturns: `Object` Klient.\n\nPripojí sa k WebSocket endpointu (`http` v URL sa zmení na `ws`). Všetci klienti s rovnakou URL zdieľajú jedno spojenie, ktoré sa znovu pripojí, keď server zmizne. Klient vytvorený s `id`, ktoré už existuje, nahradí starého klienta.\n\nKeď server pošle správu `{ type: 'init', id: '...' }`, každý klient dostane `client.meta` (správa), `client.type` (jej `id`) a spustí sa jeho handler `online()`. `client.connected` je `true`, kým je spojenie otvorené. Správy, ktoré nie sú odpoveďami na `rpc()`, idú do handlera `message()`.\n\nExample: Pripojenie\n```js\nvar client = OPENCLIENT('wss://service.example.com/$client/', 'myservice');\n\nclient.online(function(meta) {\n\tconsole.log(meta ? 'Connected to ' + meta.id : 'Offline');\n});\n\nclient.message(function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### client.send(msg, [callback], [timeout])\n\nType: `method`\n\nPošle správu serveru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Správa. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Milisekundy čakania na odpoveď. |\n\nReturns: `Object` Klient, pre reťazenie.\n\nPošle `msg` (objekt, ako JSON). S `callback` dostane správa `callbackid` a callback sa spustí s `(err, response)`, keď server odpovie `{ callbackid, error, response }`, s `'timeout'` po `timeout` milisekundách alebo s `'offline'`, keď nie je spojenie. Kým je spojenie zatvorené, správa sa skúša znovu každých 500 ms, najviac desaťkrát.\n\n`client.cmd(msg)` pošle správu bez čakania na odpoveď.\n\nExample: Odoslanie a čakanie\n```js\nclient.send({ type: 'users' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n```\n\nExample: Príkaz\n```js\nclient.cmd({ type: 'refresh' });\n```\n\n### client.rpc(msg, [callback], [timeout])\n\nType: `method`\n\nPošle správu a počká na odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Správa. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no |  | Milisekundy čakania. |\n\nReturns: `Promise|Object` Promise bez callbacku.\n\nTo isté ako `send()` s callbackom. Bez callbacku vráti promise, ktorý sa vyrieši s odpoveďou a zamietne s chybou (`'timeout'`, `'offline'` alebo `error` z odpovede).\n\nExample: await\n```js\nvar users = await client.rpc({ type: 'users', page: 1 }, 5000);\n```\n\n### client.message(fn)\n\nType: `method`\n\nNastaví handler prichádzajúcich správ.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Object` Klient, pre reťazenie.\n\nSpustí sa pre každú správu zo servera, ktorá nie je odpoveďou na `send()` alebo `rpc()` a nie je správou `init`.\n\nExample: Správy\n```js\nclient.message(function(msg) {\n\tif (msg.type === 'notify')\n\t\tconsole.log(msg.body);\n});\n```\n\n### client.online(fn)\n\nType: `method`\n\nNastaví handler zmien online a offline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(meta)`. |\n\nReturns: `Object` Klient, pre reťazenie.\n\nSpustí sa so správou `init` servera, keď je služba pripravená, a s `null`, keď sa spojenie zatvorí.\n\nExample: Stav online\n```js\nclient.online(function(meta) {\n\tconsole.log(meta ? 'online' : 'offline');\n});\n```\n\n### client.error(fn)\n\nType: `method`\n\nNastaví handler chýb spojenia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `Object` Klient, pre reťazenie.\n\nSpustí sa s chybovou správou, keď spojenie zlyhá, a s `(code, message)`, keď ho server zatvorí s kódom 4000 alebo vyšším. Čakajúce volania `rpc()` sa zamietnu s chybou.\n\nExample: Chyby\n```js\nclient.error(function(err) {\n\tconsole.log('OPENCLIENT error', err);\n});\n```\n\n### client.close()\n\nType: `method`\n\nOdstráni klienta.\n\n`client.remove()` je alias. Čakajúce callbacky tohto klienta dostanú `'offline'`. Zdieľané spojenie sa zatvorí, keď nemá iných klientov.\n\nExample: Zatvorenie\n```js\nclient.close();\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.rpc()","signature":"client.rpc(msg, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.message()","signature":"client.message(fn)","since":"","deprecated":false},{"type":"method","name":"client.online()","signature":"client.online(fn)","since":"","deprecated":false},{"type":"method","name":"client.error()","signature":"client.error(fn)","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:49.572Z"}
{"id":"Jafwu84qx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/mail/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Sending email","summary":"MAIL(), HTMLMAIL(), LOGMAIL(), the Mail module, the message object and the SMTP keys.","markdown":"---\ntitle: Sending email\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/mail/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Sending email\n\n> MAIL(), HTMLMAIL(), LOGMAIL(), the Mail module, the message object and the SMTP keys.\n\nThis page lists the global mail functions, the `Mail` module with its events, the methods and properties of the message object, and the config keys for SMTP and the default sender. The guide [Sending email](../../guides/mail/) explains how they work together, with examples.\n\n## API\n\n### MAIL()\n\nType: `method`\n\nRenders a view and sends it as an e-mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | One address, comma-separated addresses, or an array of addresses. Each becomes a `To:` recipient. |\n| `subject` | `String` | yes |  | The subject. |\n| `view` | `String` | yes |  | The name of the view, e.g. `mail/welcome`. |\n| `model` | `Object` | no |  | The model of the view. |\n| `language` | `String` | no |  | The language for the view and the subject. |\n| `callback` | `Function` | no |  | `function(err, message)`, the same as `message.callback()`. |\n\nReturns: `Message` The message that will be sent.\n\nRenders the view `view` (a path in `/views/` without `.html`) with `model` and sends the HTML to `email`. The sender, the reply address and the copies come from `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` and `mail_bcc` (or `from`/`name` of `CONF.smtp`). With `language`, the view is rendered in that language and a subject with `@(...)` is translated. The message is sent on the next turn of the event loop, so you can still change the returned message. When `language` is a function, it is used as the callback.\n\nExample: Welcome e-mail\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n### HTMLMAIL()\n\nType: `method`\n\nSends an e-mail with an HTML body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | One address, comma-separated addresses, or an array of addresses. Each becomes a `To:` recipient. |\n| `subject` | `String` | yes |  | The subject. |\n| `body` | `String` | yes |  | The HTML. |\n| `language` | `String` | no |  | The language for translating the subject and the body. |\n| `callback` | `Function` | no |  | `function(err, message)`, the same as `message.callback()`. |\n\nReturns: `Message` The message that will be sent.\n\nSends `body` as HTML. A body without a `<body>` tag is wrapped in a simple HTML document with the subject as the title. With `language`, `@(...)` texts in the subject and the body are translated. The defaults are the same as for `MAIL()`. When `language` is a function, it is used as the callback.\n\nExample: Send HTML\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL()\n\nType: `method`\n\nSends a short report as preformatted text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | One address, comma-separated addresses, or an array of addresses. Each becomes a `To:` recipient. |\n| `subject` | `String` | no |  | The subject (default `CONF.name`). |\n| `body` | `String|Object` | yes |  | The text, or an object to serialize. |\n| `callback` | `Function` | no |  | `function(err, message)`, the same as `message.callback()`. |\n\nReturns: `Message` The message that will be sent.\n\nWraps `body` in a `<pre>` block and sends it. A string is inserted as it is, so it can contain HTML. An object is serialized to JSON and HTML-encoded. Without `subject` (two arguments, or a function as the third one), `CONF.name` is the subject. The defaults are the same as for `MAIL()`.\n\nExample: Report\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n### DEF.onMail\n\nType: `delegate`\n\nThe function that builds and sends the messages of MAIL(), HTMLMAIL() and LOGMAIL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | One address, comma-separated addresses, or an array of addresses. Each becomes a `To:` recipient. |\n| `subject` | `String` | yes |  | The subject. |\n| `body` | `String` | yes |  | The HTML body. |\n| `callback` | `Function` | no |  | The callback. |\n| `reply` | `String` | no |  | A reply address instead of `mail_reply`. |\n\nReturns: `Message` The message.\n\nCalled as `DEF.onMail(email, subject, body, callback, reply)`. It creates the message, adds the recipients, the sender (`mail_from` or `CONF.smtp.from`/`user`, `mail_from_name` or `CONF.smtp.name`), the reply address (`reply` or `mail_reply`), `mail_cc` and `mail_bcc`, sets the callback and schedules the sending. It must return the message. When `callback` is a string, it is taken as `reply`.\n\nExample: Add a header to every message\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\n### Mail\n\nType: `class`\n\nThe global SMTP client.\n\nReturns: `Object`\n\n`Mail` is the mailer of the framework. It creates messages (`Mail.create()`), sends them (`Mail.send()`, `Mail.send2()`), tests a server (`Mail.try()`) and emits the `send` and `error` events. `Mail.Message` (also `Mail.Mail`) is the constructor of messages.\n\nExample: Create and send\n```js\nvar msg = Mail.create('Hello', '<p>Hello</p>');\nmsg.from('info@example.com').to('user@example.com').send2();\n```\n\n### Mail.create()\n\nType: `method`\n\nCreates a new 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: `Message` A new message.\n\nReturns a new message with the subject and the body. Unlike `MAIL()`, nothing is set or sent for you: add the sender and the recipients and call `message.send2()` or `message.send()`.\n\nExample: Create\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.send2();\n```\n\n### Mail.send()\n\nType: `method`\n\nSends one or more messages with the given SMTP options.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | The SMTP options. |\n| `messages` | `Message|Array` | yes |  | A message or an array of messages. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nOpens a connection with `options` (the same keys as `CONF.smtp`), sends the messages one after another and closes the connection. The callback receives `err` when the connection or the login fails. Use `message.callback()` for the result of each message.\n\nExample: Two messages, one connection\n```js\nvar a = Mail.create('A', '<p>A</p>').from('info@example.com').to('a@example.com');\nvar b = Mail.create('B', '<p>B</p>').from('info@example.com').to('b@example.com');\nMail.send(CONF.smtp, [a, b]);\n```\n\n### Mail.send2()\n\nType: `method`\n\nSends messages with CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `Message|Array` | yes |  | A message or an array of messages. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nThe same as `Mail.send(CONF.smtp, messages, callback)`.\n\nExample: Send\n```js\nMail.send2([msg1, msg2]);\n```\n\n### Mail.try()\n\nType: `method`\n\nTests the connection and the login to an SMTP server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | The SMTP options. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Without a callback.\n\nConnects with `options`, logs in and quits without sending anything. Without a callback it returns a promise.\n\nExample: Check the settings\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n### Mail.debug\n\nType: `property`\n\nPrints the SMTP conversation to the console.\n\nReturns: `Boolean` Default `false`.\n\nWith `true`, every line sent to and received from the server is printed. Default `false`.\n\nExample: Debug\n```js\nMail.debug = true;\n```\n\n### Mail.on('send')\n\nType: `event`\n\nEmitted when a connection is ready to send.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | The internal connection object. |\n\n`Mail.on('send', function(connection) {})`. Emitted when the client starts the SMTP conversation of a connection.\n\nExample: Listen\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection ready');\n});\n```\n\n### Mail.on('error')\n\nType: `event`\n\nEmitted on SMTP errors.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | The error. |\n| `connection` | `Object` | yes |  | The internal connection object. |\n\n`Mail.on('error', function(err, connection) {})`. Emitted when the connection fails, the login is refused or the server answers with an error. `err` is an `Error` or the reply line of the server.\n\nExample: Log SMTP errors\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### ON('$mail')\n\nType: `event`\n\nEmitted for every message that is being sent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Message` | yes |  | The message. |\n\n`ON('$mail', function(message) {})`. Emitted just before the message is written to the SMTP server.\n\nExample: Log every e-mail\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n```\n\n### Mail.Message\n\nType: `class`\n\nThe message object.\n\nReturns: `Object`\n\nA message is returned by `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `Mail.create()`; `new Mail.Message(subject, body)` creates one too (`Mail.Mail` is an alias). Its methods return the message, so calls can be chained. The recipients are in `email_to`, `email_cc`, `email_bcc` and `email_reply` (arrays), the sender in `email_from` and `email_from_name`.\n\nExample: Chain\n```js\nMail.create('Hi', '<p>Hi</p>').from('info@example.com').to('a@example.com').cc('b@example.com').send2();\n```\n\n### message.to()\n\nType: `method`\n\nAdds a recipient.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | One address. |\n| `clear` | `Boolean` | no | `false` | Remove the current recipients first. |\n\nReturns: `Message` The message, for chaining.\n\nAdds one address to the `To:` header. With `clear`, the current recipients are removed first.\n\nExample: Recipients\n```js\nmsg.to('a@example.com').to('b@example.com');\n```\n\n### message.cc()\n\nType: `method`\n\nAdds a copy recipient.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | One address. |\n| `clear` | `Boolean` | no | `false` | Remove the current copies first. |\n\nReturns: `Message` The message, for chaining.\n\nAdds one address to the `Cc:` header. With `clear`, the current copies are removed first.\n\nExample: Copy\n```js\nmsg.cc('boss@example.com');\n```\n\n### message.bcc()\n\nType: `method`\n\nAdds a blind copy recipient.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | One address. |\n| `clear` | `Boolean` | no | `false` | Remove the current blind copies first. |\n\nReturns: `Message` The message, for chaining.\n\nAdds one address that receives the message without being listed in the headers. With `clear`, the current blind copies are removed first.\n\nExample: Blind copy\n```js\nmsg.bcc('archive@example.com');\n```\n\n### message.reply()\n\nType: `method`\n\nAdds a reply address.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | One address. |\n| `clear` | `Boolean` | no | `false` | Remove the current reply addresses first. |\n\nReturns: `Message` The message, for chaining.\n\nAdds one address to the `Reply-To:` header. With `clear`, the current reply addresses are removed first.\n\nExample: Reply to support\n```js\nmsg.reply('support@example.com');\n```\n\n### message.from()\n\nType: `method`\n\nSets the sender.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | The address. |\n| `name` | `String` | no |  | The display name. |\n\nReturns: `Message` The message, for chaining.\n\nSets the `From:` address and, optionally, the display name. `message.sender()` is the same method.\n\nExample: Sender\n```js\nmsg.from('info@example.com', 'My application');\n```\n\n### message.sender()\n\nType: `method`\n\nAn alias of message.from().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | The address. |\n| `name` | `String` | no |  | The display name. |\n\nReturns: `Message` The message, for chaining.\n\nThe same as `message.from(email, [name])`.\n\nExample: Sender\n```js\nmsg.sender('info@example.com');\n```\n\n### message.attachment()\n\nType: `method`\n\nAttaches a file from the disk or a Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Buffer` | yes |  | The path to the file, or a `Buffer` with the content. |\n| `name` | `String` | yes |  | The file name for the recipient, with its extension. |\n| `contentid` | `String` | no |  | The content ID for an inline file. |\n\nReturns: `Message` The message, for chaining.\n\nAdds the file `filename`, or the content of a `Buffer`, as an attachment. `name` is the file name shown to the recipient, and its extension sets the content type (`application/octet-stream` for unknown ones). With `contentid`, the file is an inline part that the HTML body refers to as `cid:<contentid>`. The file is read when the message is sent.\n\nExample: Attach a PDF\n```js\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\n```\n\nExample: Inline image\n```js\nvar msg = HTMLMAIL('user@example.com', 'News', '<img src=\"cid:logo\" />');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nExample: From a Buffer\n```js\nvar pdf = Buffer.from('%PDF-1.4 ...');\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.attachment(pdf, 'invoice.pdf');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nAttaches a file from a file storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | The name of the file storage. |\n| `id` | `String` | yes |  | The id of the file in the storage. |\n| `name` | `String` | no |  | The file name for the recipient, with its extension. Default: the name stored with the file. |\n| `contentid` | `String` | no |  | The content ID for an inline file. |\n\nReturns: `Message` The message, for chaining.\n\nAdds a file of a [file storage](../file-storage/) as an attachment: `storage` is the name of the storage (as in `FILESTORAGE(name)`) and `id` the id of the file. Without `name`, the recipient sees the name of the file in the storage and the content type is the type stored with the file; with `name`, its extension sets the content type. With `contentid`, the file is an inline part that the HTML body refers to as `cid:<contentid>`.\n\nThe file is read when the message is sent. When it does not exist, the error is written to the error log and the message is sent without the attachment.\n\nExample: Attach a stored file\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Contract', '<p>The contract is attached.</p>');\nmsg.attachmentfs('documents', id);\n```\n\nExample: Another name\n```js\nmsg.attachmentfs('documents', id, 'contract-2025.pdf');\n```\n\n### message.unsubscribe()\n\nType: `method`\n\nAdds the List-Unsubscribe headers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The unsubscribe URL or e-mail address. |\n\nReturns: `Message` The message, for chaining.\n\nAdds `List-Unsubscribe` and `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. A value that starts with `http:` or `https:` is used as a URL; any other value is an e-mail address (`mailto:`).\n\nExample: Newsletter\n```js\nmsg.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback()\n\nType: `method`\n\nSets the function called with the result of the message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `Message` The message, for chaining.\n\n`fn(err, message)` is called with an empty `err` when the message has been handed over to the server, or with an error: the reply line of the server (in upper case) when it refuses the message or the login, `No SMTP server configuration.`, or a connection error or timeout. An error that reaches a callback is not written to the error log. `MAIL()`, `HTMLMAIL()` and `LOGMAIL()` set it from their `callback` argument.\n\nExample: Result\n```js\nmsg.callback(function(err, message) {\n\tif (err)\n\t\tconsole.log('Not sent:', message.subject, err);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nStops the automatic sending.\n\nReturns: `Message` The message, for chaining.\n\n`MAIL()`, `HTMLMAIL()` and `LOGMAIL()` send the message on the next turn of the event loop. Call `manually()` right after them to cancel that, and send the message later with `message.send2()` or `message.send()`.\n\nExample: Send later\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n// ...\nmsg.send2();\n```\n\n### message.send2()\n\nType: `method`\n\nSends the message with CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nSends the message with the configured SMTP server (`CONF.smtp`).\n\nExample: Send\n```js\nMail.create('Hello', '<p>Hello</p>').from('info@example.com').to('user@example.com').send2(function(err) {\n\terr && console.log(err);\n});\n```\n\n### message.send(options)\n\nType: `method`\n\nSends the message with other SMTP options.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | The SMTP options. |\n\nReturns: `Message` The message, for chaining.\n\nSends the message over a new connection with `options` (the same keys as `CONF.smtp`). Use `message.callback()` for the result.\n\nExample: Another server\n```js\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send({ server: 'smtp.other.com', port: 587, user: 'me@other.com', password: 'secret' });\n```\n\n### message.subject\n\nType: `property`\n\nThe subject.\n\nReturns: `String`\n\nThe subject of the message. Non-ASCII characters are encoded for you.\n\nExample: Change\n```js\nmsg.subject = 'Updated subject';\n```\n\n### message.body\n\nType: `property`\n\nThe body.\n\nReturns: `String`\n\nThe body of the message: HTML, or plain text when `type` is `plain`.\n\nExample: Change\n```js\nmsg.body = '<p>New text</p>';\n```\n\n### message.type\n\nType: `property`\n\nThe type of the body.\n\nReturns: `String` Default `html`.\n\n`html` (default) or `plain`. It becomes the `Content-Type` of the body (`text/html` or `text/plain`).\n\nExample: Plain text\n```js\nvar msg = Mail.create('Hello', 'Hello in plain text');\nmsg.type = 'plain';\n```\n\n### message.headers\n\nType: `property`\n\nExtra headers of the message.\n\nReturns: `Object`\n\nAn object of header names and values written into the message as they are. It is not set by default.\n\nExample: Custom header\n```js\nmsg.headers = { 'X-Campaign': 'spring-2025' };\n```\n\n### message.high()\n\nType: `method`\n\nMarks the message as high priority.\n\nReturns: `Message` The same message.\n\nAdds the header `X-Priority: 1`. Returns the message.\n\nExample: Urgent\n```js\nHTMLMAIL('admin@example.com', 'Disk full', '<p>The disk is full.</p>').high();\n```\n\n### message.low()\n\nType: `method`\n\nMarks the message as low priority.\n\nReturns: `Message` The same message.\n\nAdds the header `X-Priority: 5`. Returns the message.\n\nExample: Weekly digest\n```js\nMAIL(user.email, 'Your week', 'mail/digest', model).low();\n```\n\n### message.confidential()\n\nType: `method`\n\nMarks the message as confidential.\n\nReturns: `Message` The same message.\n\nAdds the header `Sensitivity: Company-Confidential`. Returns the message.\n\nExample: Confidential report\n```js\nHTMLMAIL('board@example.com', 'Salaries', html).confidential().high();\n```\n\n### CONF.smtp\n\nType: `config`\n\nThe SMTP server and its options.\n\nReturns: `Object`\n\nAn object with `server` (or `host`, `hostname`, `smtp`, `url`), `port`, `secure`, `user`, `password`, `token`, `tls`, `timeout`, `from` and `name`. With `secure: true` the connection uses TLS from the start and `port` defaults to `465`; otherwise set `port`. The key `mail` in the config file is the same.\n\nBefore the connection, `server` is converted with `U.tohost()`: an international name is sent as punycode and an IPv4 address in its dotted form (`127.1` becomes `127.0.0.1`). A value that is not a valid host name gives the error `Invalid SMTP server hostname.` and nothing is sent.\n\nExample: /config\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nExample: STARTTLS on port 587\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_smtp\n\nType: `config`\n\nThe SMTP server name.\n\nReturns: `String`\n\nSets `CONF.smtp.server`. Use it with `mail_smtp_options` instead of one `smtp` object.\n\nExample: /config\n```text\nmail_smtp : smtp.example.com\n```\n\n### CONF.mail_smtp_options\n\nType: `config`\n\nThe SMTP options without the server.\n\nReturns: `Object`\n\nAn object whose keys are copied into `CONF.smtp` (`port`, `secure`, `user`, `password`...).\n\nExample: /config\n```text\nmail_smtp_options : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_from\n\nType: `config`\n\nThe default sender address.\n\nReturns: `String`\n\nThe `From:` address of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`. Without it, `CONF.smtp.from` or `CONF.smtp.user` is used.\n\nExample: /config\n```text\nmail_from : info@example.com\n```\n\n### CONF.mail_from_name\n\nType: `config`\n\nThe default sender name.\n\nReturns: `String`\n\nThe display name of the sender of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`. Without it, `CONF.smtp.name` is used.\n\nExample: /config\n```text\nmail_from_name : My application\n```\n\n### CONF.mail_reply\n\nType: `config`\n\nThe default reply address.\n\nReturns: `String`\n\nOne address added as `Reply-To:` to the messages of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`.\n\nExample: /config\n```text\nmail_reply : support@example.com\n```\n\n### CONF.mail_cc\n\nType: `config`\n\nA default copy recipient.\n\nReturns: `String`\n\nOne address added as `Cc:` to the messages of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`.\n\nExample: /config\n```text\nmail_cc : office@example.com\n```\n\n### CONF.mail_bcc\n\nType: `config`\n\nA default blind copy recipient.\n\nReturns: `String`\n\nOne address added as a blind copy to the messages of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()`.\n\nExample: /config\n```text\nmail_bcc : archive@example.com\n```\n\n### $tapimail : true\n\nType: `config`\n\nSends the messages through the Total.js API instead of SMTP.\n\nReturns: `Boolean`\n\nDefault `false`. With `true`, `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `message.send2()` send the message with `API('TAPI', 'mail', data)` and the token `secret_totalapi`; `$tapi` must be `true` (the default). The service gets the recipients (`to`, `cc`, `bcc`, `reply`), `from`, `subject`, `type`, `body`, `priority`, `unsubscribe` and `confidential`. Attachments and `message.headers` are not sent. The callback of the message gets the answer of the service.\n\nExample: /config\n```text\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL()","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL()","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL()","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create()","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send()","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2()","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try()","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send')","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error')","since":"","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail')","since":"","deprecated":false},{"type":"class","name":"Mail.Message","signature":"Mail.Message","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to()","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc()","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc()","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply()","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from()","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender()","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment()","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()","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback()","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2()","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(options)","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":"property","name":"message.headers","signature":"message.headers","since":"","deprecated":false},{"type":"method","name":"message.high()","signature":"message.high()","since":"","deprecated":false},{"type":"method","name":"message.low()","signature":"message.low()","since":"","deprecated":false},{"type":"method","name":"message.confidential()","signature":"message.confidential()","since":"","deprecated":false},{"type":"config","name":"CONF.smtp","signature":"CONF.smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp","signature":"CONF.mail_smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp_options","signature":"CONF.mail_smtp_options","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from","signature":"CONF.mail_from","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from_name","signature":"CONF.mail_from_name","since":"","deprecated":false},{"type":"config","name":"CONF.mail_reply","signature":"CONF.mail_reply","since":"","deprecated":false},{"type":"config","name":"CONF.mail_cc","signature":"CONF.mail_cc","since":"","deprecated":false},{"type":"config","name":"CONF.mail_bcc","signature":"CONF.mail_bcc","since":"","deprecated":false},{"type":"config","name":"CONF.$tapimail","signature":"$tapimail : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwu84qx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/mail/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"E-Mails senden","summary":"MAIL(), HTMLMAIL(), LOGMAIL(), das Modul Mail, das Nachrichtenobjekt und die SMTP-Schlüssel.","markdown":"---\ntitle: E-Mails senden\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/mail/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# E-Mails senden\n\n> MAIL(), HTMLMAIL(), LOGMAIL(), das Modul Mail, das Nachrichtenobjekt und die SMTP-Schlüssel.\n\nDiese Seite listet die globalen Mail-Funktionen, das Modul `Mail` mit seinen Events, die Methoden und Eigenschaften des Nachrichtenobjekts sowie die Konfigurationsschlüssel für SMTP und den Standardabsender auf. Der Leitfaden [E-Mails senden](../../guides/mail/) erklärt mit Beispielen, wie sie zusammenarbeiten.\n\n## API\n\n### MAIL()\n\nType: `method`\n\nRendert eine View und sendet sie als E-Mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Eine Adresse, kommagetrennte Adressen oder ein Array von Adressen. Jede wird zu einem `To:`-Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff. |\n| `view` | `String` | yes |  | Der Name der View, z. B. `mail/welcome`. |\n| `model` | `Object` | no |  | Das Modell der View. |\n| `language` | `String` | no |  | Die Sprache für die View und den Betreff. |\n| `callback` | `Function` | no |  | `function(err, message)`, dasselbe wie `message.callback()`. |\n\nReturns: `Message` Die Nachricht, die gesendet wird.\n\nRendert die View `view` (ein Pfad in `/views/` ohne `.html`) mit `model` und sendet das HTML an `email`. Der Absender, die Antwortadresse und die Kopien stammen aus `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` und `mail_bcc` (oder `from`/`name` von `CONF.smtp`). Mit `language` wird die View in dieser Sprache gerendert und ein Betreff mit `@(...)` übersetzt. Die Nachricht wird im nächsten Durchlauf der Event-Loop gesendet, sodass du die zurückgegebene Nachricht noch ändern kannst. Ist `language` eine Funktion, wird sie als Callback verwendet.\n\nExample: Willkommens-E-Mail\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n### HTMLMAIL()\n\nType: `method`\n\nSendet eine E-Mail mit HTML-Inhalt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Eine Adresse, kommagetrennte Adressen oder ein Array von Adressen. Jede wird zu einem `To:`-Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff. |\n| `body` | `String` | yes |  | Das HTML. |\n| `language` | `String` | no |  | Die Sprache für die Übersetzung des Betreffs und des Inhalts. |\n| `callback` | `Function` | no |  | `function(err, message)`, dasselbe wie `message.callback()`. |\n\nReturns: `Message` Die Nachricht, die gesendet wird.\n\nSendet `body` als HTML. Ein Inhalt ohne `<body>`-Tag wird in ein einfaches HTML-Dokument mit dem Betreff als Titel verpackt. Mit `language` werden `@(...)`-Texte im Betreff und im Inhalt übersetzt. Die Standardwerte sind dieselben wie bei `MAIL()`. Ist `language` eine Funktion, wird sie als Callback verwendet.\n\nExample: HTML senden\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL()\n\nType: `method`\n\nSendet einen kurzen Bericht als vorformatierten Text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Eine Adresse, kommagetrennte Adressen oder ein Array von Adressen. Jede wird zu einem `To:`-Empfänger. |\n| `subject` | `String` | no |  | Der Betreff (Standard `CONF.name`). |\n| `body` | `String|Object` | yes |  | Der Text oder ein zu serialisierendes Objekt. |\n| `callback` | `Function` | no |  | `function(err, message)`, dasselbe wie `message.callback()`. |\n\nReturns: `Message` Die Nachricht, die gesendet wird.\n\nVerpackt `body` in einen `<pre>`-Block und sendet ihn. Ein String wird so eingefügt, wie er ist, er kann also HTML enthalten. Ein Objekt wird zu JSON serialisiert und HTML-kodiert. Ohne `subject` (zwei Argumente oder eine Funktion als drittes) ist `CONF.name` der Betreff. Die Standardwerte sind dieselben wie bei `MAIL()`.\n\nExample: Bericht\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n### DEF.onMail\n\nType: `delegate`\n\nDie Funktion, die die Nachrichten von MAIL(), HTMLMAIL() und LOGMAIL() erstellt und sendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Eine Adresse, kommagetrennte Adressen 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 |  | Der Callback. |\n| `reply` | `String` | no |  | Eine Antwortadresse statt `mail_reply`. |\n\nReturns: `Message` Die Nachricht.\n\nWird als `DEF.onMail(email, subject, body, callback, reply)` aufgerufen. Sie erstellt die Nachricht, fügt die Empfänger, den Absender (`mail_from` oder `CONF.smtp.from`/`user`, `mail_from_name` oder `CONF.smtp.name`), die Antwortadresse (`reply` oder `mail_reply`), `mail_cc` und `mail_bcc` hinzu, setzt den Callback und plant das Senden. Sie muss die Nachricht zurückgeben. Ist `callback` ein String, wird er als `reply` verwendet.\n\nExample: Jeder Nachricht einen Header hinzufügen\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\n### Mail\n\nType: `class`\n\nDer globale SMTP-Client.\n\nReturns: `Object`\n\n`Mail` ist der Mailer des Frameworks. Er erstellt Nachrichten (`Mail.create()`), sendet sie (`Mail.send()`, `Mail.send2()`), testet einen Server (`Mail.try()`) und löst die Events `send` und `error` aus. `Mail.Message` (auch `Mail.Mail`) ist der Konstruktor der Nachrichten.\n\nExample: Erstellen und senden\n```js\nvar msg = Mail.create('Hello', '<p>Hello</p>');\nmsg.from('info@example.com').to('user@example.com').send2();\n```\n\n### Mail.create()\n\nType: `method`\n\nErstellt eine neue 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: `Message` Eine neue Nachricht.\n\nGibt eine neue Nachricht mit dem Betreff und dem Inhalt zurück. Anders als bei `MAIL()` wird nichts für dich gesetzt oder gesendet: Füge den Absender und die Empfänger hinzu und rufe `message.send2()` oder `message.send()` auf.\n\nExample: Erstellen\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.send2();\n```\n\n### Mail.send()\n\nType: `method`\n\nSendet eine oder mehrere Nachrichten mit den angegebenen SMTP-Optionen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Die SMTP-Optionen. |\n| `messages` | `Message|Array` | yes |  | Eine Nachricht oder ein Array von Nachrichten. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nÖffnet eine Verbindung mit `options` (dieselben Schlüssel wie `CONF.smtp`), sendet die Nachrichten nacheinander und schließt die Verbindung. Der Callback erhält `err`, wenn die Verbindung oder die Anmeldung fehlschlägt. Verwende `message.callback()` für das Ergebnis jeder Nachricht.\n\nExample: Zwei Nachrichten, eine Verbindung\n```js\nvar a = Mail.create('A', '<p>A</p>').from('info@example.com').to('a@example.com');\nvar b = Mail.create('B', '<p>B</p>').from('info@example.com').to('b@example.com');\nMail.send(CONF.smtp, [a, b]);\n```\n\n### Mail.send2()\n\nType: `method`\n\nSendet Nachrichten mit CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `Message|Array` | yes |  | Eine Nachricht oder ein Array von Nachrichten. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nDasselbe wie `Mail.send(CONF.smtp, messages, callback)`.\n\nExample: Senden\n```js\nMail.send2([msg1, msg2]);\n```\n\n### Mail.try()\n\nType: `method`\n\nTestet die Verbindung und die Anmeldung bei einem SMTP-Server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Die SMTP-Optionen. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Ohne Callback.\n\nVerbindet sich mit `options`, meldet sich an und beendet die Verbindung, ohne etwas zu senden. Ohne Callback gibt es ein Promise zurück.\n\nExample: Die Einstellungen prüfen\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n### Mail.debug\n\nType: `property`\n\nGibt die SMTP-Kommunikation in der Konsole aus.\n\nReturns: `Boolean` Standard `false`.\n\nMit `true` wird jede an den Server gesendete und von ihm empfangene Zeile ausgegeben. Standard `false`.\n\nExample: Debug\n```js\nMail.debug = true;\n```\n\n### Mail.on('send')\n\nType: `event`\n\nWird ausgelöst, wenn eine Verbindung zum Senden bereit ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | Das interne Verbindungsobjekt. |\n\n`Mail.on('send', function(connection) {})`. Wird ausgelöst, wenn der Client die SMTP-Kommunikation einer Verbindung beginnt.\n\nExample: Lauschen\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection ready');\n});\n```\n\n### Mail.on('error')\n\nType: `event`\n\nWird bei SMTP-Fehlern ausgelöst.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Der Fehler. |\n| `connection` | `Object` | yes |  | Das interne Verbindungsobjekt. |\n\n`Mail.on('error', function(err, connection) {})`. Wird ausgelöst, wenn die Verbindung fehlschlägt, die Anmeldung abgelehnt wird oder der Server mit einem Fehler antwortet. `err` ist ein `Error` oder die Antwortzeile des Servers.\n\nExample: SMTP-Fehler protokollieren\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### ON('$mail')\n\nType: `event`\n\nWird für jede Nachricht ausgelöst, die gesendet wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Message` | yes |  | Die Nachricht. |\n\n`ON('$mail', function(message) {})`. Wird ausgelöst, kurz bevor die Nachricht an den SMTP-Server geschrieben wird.\n\nExample: Jede E-Mail protokollieren\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n```\n\n### Mail.Message\n\nType: `class`\n\nDas Nachrichtenobjekt.\n\nReturns: `Object`\n\nEine Nachricht wird von `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` und `Mail.create()` zurückgegeben; `new Mail.Message(subject, body)` erstellt ebenfalls eine (`Mail.Mail` ist ein Alias). Ihre Methoden geben die Nachricht zurück, sodass Aufrufe verkettet werden können. Die Empfänger stehen in `email_to`, `email_cc`, `email_bcc` und `email_reply` (Arrays), der Absender in `email_from` und `email_from_name`.\n\nExample: Verketten\n```js\nMail.create('Hi', '<p>Hi</p>').from('info@example.com').to('a@example.com').cc('b@example.com').send2();\n```\n\n### message.to()\n\nType: `method`\n\nFügt einen Empfänger hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Eine Adresse. |\n| `clear` | `Boolean` | no | `false` | Zuerst die aktuellen Empfänger entfernen. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nFügt dem Header `To:` eine Adresse hinzu. Mit `clear` werden die aktuellen Empfänger zuerst entfernt.\n\nExample: Empfänger\n```js\nmsg.to('a@example.com').to('b@example.com');\n```\n\n### message.cc()\n\nType: `method`\n\nFügt einen Kopie-Empfänger hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Eine Adresse. |\n| `clear` | `Boolean` | no | `false` | Zuerst die aktuellen Kopien entfernen. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nFügt dem Header `Cc:` eine Adresse hinzu. Mit `clear` werden die aktuellen Kopien zuerst entfernt.\n\nExample: Kopie\n```js\nmsg.cc('boss@example.com');\n```\n\n### message.bcc()\n\nType: `method`\n\nFügt einen Blindkopie-Empfänger hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Eine Adresse. |\n| `clear` | `Boolean` | no | `false` | Zuerst die aktuellen Blindkopien entfernen. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nFügt eine Adresse hinzu, die die Nachricht erhält, ohne in den Headern aufgeführt zu werden. Mit `clear` werden die aktuellen Blindkopien zuerst entfernt.\n\nExample: Blindkopie\n```js\nmsg.bcc('archive@example.com');\n```\n\n### message.reply()\n\nType: `method`\n\nFügt eine Antwortadresse hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Eine Adresse. |\n| `clear` | `Boolean` | no | `false` | Zuerst die aktuellen Antwortadressen entfernen. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nFügt dem Header `Reply-To:` eine Adresse hinzu. Mit `clear` werden die aktuellen Antwortadressen zuerst entfernt.\n\nExample: Antwort an den Support\n```js\nmsg.reply('support@example.com');\n```\n\n### message.from()\n\nType: `method`\n\nSetzt den Absender.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Die Adresse. |\n| `name` | `String` | no |  | Der Anzeigename. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nSetzt die `From:`-Adresse und optional den Anzeigenamen. `message.sender()` ist dieselbe Methode.\n\nExample: Absender\n```js\nmsg.from('info@example.com', 'My application');\n```\n\n### message.sender()\n\nType: `method`\n\nEin Alias von message.from().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Die Adresse. |\n| `name` | `String` | no |  | Der Anzeigename. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nDasselbe wie `message.from(email, [name])`.\n\nExample: Absender\n```js\nmsg.sender('info@example.com');\n```\n\n### message.attachment()\n\nType: `method`\n\nHängt eine Datei von der Festplatte oder einen Buffer an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Buffer` | yes |  | Der Pfad zur Datei oder ein `Buffer` mit dem Inhalt. |\n| `name` | `String` | yes |  | Der Dateiname für den Empfänger, mit seiner Endung. |\n| `contentid` | `String` | no |  | Die Content-ID für eine Inline-Datei. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nFügt die Datei `filename` oder den Inhalt eines `Buffer` als Anhang hinzu. `name` ist der Dateiname, der dem Empfänger angezeigt wird, und seine Endung bestimmt den Content-Type (`application/octet-stream` für unbekannte). Mit `contentid` ist die Datei ein Inline-Teil, auf den der HTML-Inhalt als `cid:<contentid>` verweist. Die Datei wird beim Senden der Nachricht gelesen.\n\nExample: Ein PDF anhängen\n```js\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\n```\n\nExample: Inline-Bild\n```js\nvar msg = HTMLMAIL('user@example.com', 'News', '<img src=\"cid:logo\" />');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nExample: Aus einem Buffer\n```js\nvar pdf = Buffer.from('%PDF-1.4 ...');\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.attachment(pdf, 'invoice.pdf');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nHängt eine Datei aus einem Dateispeicher an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Der Name des Dateispeichers. |\n| `id` | `String` | yes |  | Die ID der Datei im Speicher. |\n| `name` | `String` | no |  | Der Dateiname für den Empfänger, mit seiner Endung. Standard: der mit der Datei gespeicherte Name. |\n| `contentid` | `String` | no |  | Die Content-ID für eine Inline-Datei. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nFügt eine Datei aus einem [Dateispeicher](../file-storage/) als Anhang hinzu: `storage` ist der Name des Speichers (wie in `FILESTORAGE(name)`) und `id` die ID der Datei. Ohne `name` sieht der Empfänger den Namen der Datei im Speicher, und der Content-Type ist der mit der Datei gespeicherte Typ; mit `name` bestimmt dessen Endung den Content-Type. Mit `contentid` ist die Datei ein Inline-Teil, auf den der HTML-Inhalt als `cid:<contentid>` verweist.\n\nDie Datei wird beim Senden der Nachricht gelesen. Wenn sie nicht existiert, wird der Fehler ins Fehlerlog geschrieben, und die Nachricht wird ohne den Anhang gesendet.\n\nExample: Eine gespeicherte Datei anhängen\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Contract', '<p>The contract is attached.</p>');\nmsg.attachmentfs('documents', id);\n```\n\nExample: Ein anderer Name\n```js\nmsg.attachmentfs('documents', id, 'contract-2025.pdf');\n```\n\n### message.unsubscribe()\n\nType: `method`\n\nFügt die List-Unsubscribe-Header hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Abmelde-URL oder E-Mail-Adresse. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nFügt `List-Unsubscribe` und `List-Unsubscribe-Post: List-Unsubscribe=One-Click` hinzu. Ein Wert, der mit `http:` oder `https:` beginnt, wird als URL verwendet; jeder andere Wert ist eine E-Mail-Adresse (`mailto:`).\n\nExample: Newsletter\n```js\nmsg.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback()\n\nType: `method`\n\nSetzt die Funktion, die mit dem Ergebnis der Nachricht aufgerufen wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\n`fn(err, message)` wird mit einem leeren `err` aufgerufen, wenn die Nachricht an den Server übergeben wurde, oder mit einem Fehler: die Antwortzeile des Servers (in Großbuchstaben), wenn er die Nachricht oder die Anmeldung ablehnt, `No SMTP server configuration.` oder ein Verbindungsfehler oder Timeout. Ein Fehler, der einen Callback erreicht, wird nicht ins Fehlerprotokoll geschrieben. `MAIL()`, `HTMLMAIL()` und `LOGMAIL()` setzen ihn aus ihrem Argument `callback`.\n\nExample: Ergebnis\n```js\nmsg.callback(function(err, message) {\n\tif (err)\n\t\tconsole.log('Not sent:', message.subject, err);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nStoppt das automatische Senden.\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\n`MAIL()`, `HTMLMAIL()` und `LOGMAIL()` senden die Nachricht im nächsten Durchlauf der Event-Loop. Rufe direkt danach `manually()` auf, um das abzubrechen, und sende die Nachricht später mit `message.send2()` oder `message.send()`.\n\nExample: Später senden\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n// ...\nmsg.send2();\n```\n\n### message.send2()\n\nType: `method`\n\nSendet die Nachricht mit CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nSendet die Nachricht über den konfigurierten SMTP-Server (`CONF.smtp`).\n\nExample: Senden\n```js\nMail.create('Hello', '<p>Hello</p>').from('info@example.com').to('user@example.com').send2(function(err) {\n\terr && console.log(err);\n});\n```\n\n### message.send(options)\n\nType: `method`\n\nSendet die Nachricht mit anderen SMTP-Optionen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Die SMTP-Optionen. |\n\nReturns: `Message` Die Nachricht, zum Verketten.\n\nSendet die Nachricht über eine neue Verbindung mit `options` (dieselben Schlüssel wie `CONF.smtp`). Verwende `message.callback()` für das Ergebnis.\n\nExample: Ein anderer Server\n```js\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send({ server: 'smtp.other.com', port: 587, user: 'me@other.com', password: 'secret' });\n```\n\n### message.subject\n\nType: `property`\n\nDer Betreff.\n\nReturns: `String`\n\nDer Betreff der Nachricht. Nicht-ASCII-Zeichen werden für dich kodiert.\n\nExample: Ändern\n```js\nmsg.subject = 'Updated subject';\n```\n\n### message.body\n\nType: `property`\n\nDer Inhalt.\n\nReturns: `String`\n\nDer Inhalt der Nachricht: HTML oder reiner Text, wenn `type` gleich `plain` ist.\n\nExample: Ändern\n```js\nmsg.body = '<p>New text</p>';\n```\n\n### message.type\n\nType: `property`\n\nDer Typ des Inhalts.\n\nReturns: `String` Standard `html`.\n\n`html` (Standard) oder `plain`. Er wird zum `Content-Type` des Inhalts (`text/html` oder `text/plain`).\n\nExample: Reiner Text\n```js\nvar msg = Mail.create('Hello', 'Hello in plain text');\nmsg.type = 'plain';\n```\n\n### message.headers\n\nType: `property`\n\nZusätzliche Header der Nachricht.\n\nReturns: `Object`\n\nEin Objekt mit Header-Namen und -Werten, die unverändert in die Nachricht geschrieben werden. Standardmäßig ist es nicht gesetzt.\n\nExample: Eigener Header\n```js\nmsg.headers = { 'X-Campaign': 'spring-2025' };\n```\n\n### message.high()\n\nType: `method`\n\nMarkiert die Nachricht mit hoher Priorität.\n\nReturns: `Message` Dieselbe Nachricht.\n\nFügt den Header `X-Priority: 1` hinzu. Gibt die Nachricht zurück.\n\nExample: Dringend\n```js\nHTMLMAIL('admin@example.com', 'Disk full', '<p>The disk is full.</p>').high();\n```\n\n### message.low()\n\nType: `method`\n\nMarkiert die Nachricht mit niedriger Priorität.\n\nReturns: `Message` Dieselbe Nachricht.\n\nFügt den Header `X-Priority: 5` hinzu. Gibt die Nachricht zurück.\n\nExample: Wöchentliche Zusammenfassung\n```js\nMAIL(user.email, 'Your week', 'mail/digest', model).low();\n```\n\n### message.confidential()\n\nType: `method`\n\nMarkiert die Nachricht als vertraulich.\n\nReturns: `Message` Dieselbe Nachricht.\n\nFügt den Header `Sensitivity: Company-Confidential` hinzu. Gibt die Nachricht zurück.\n\nExample: Vertraulicher Bericht\n```js\nHTMLMAIL('board@example.com', 'Salaries', html).confidential().high();\n```\n\n### CONF.smtp\n\nType: `config`\n\nDer SMTP-Server und seine Optionen.\n\nReturns: `Object`\n\nEin Objekt mit `server` (oder `host`, `hostname`, `smtp`, `url`), `port`, `secure`, `user`, `password`, `token`, `tls`, `timeout`, `from` und `name`. Mit `secure: true` verwendet die Verbindung von Anfang an TLS und `port` ist standardmäßig `465`; andernfalls setze `port`. Der Schlüssel `mail` in der Konfigurationsdatei ist dasselbe.\n\nVor der Verbindung wird `server` mit `U.tohost()` umgewandelt: Ein internationaler Name wird als Punycode gesendet und eine IPv4-Adresse in ihrer Punktschreibweise (`127.1` wird zu `127.0.0.1`). Ein Wert, der kein gültiger Hostname ist, führt zum Fehler `Invalid SMTP server hostname.`, und es wird nichts gesendet.\n\nExample: /config\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nExample: STARTTLS auf Port 587\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_smtp\n\nType: `config`\n\nDer Name des SMTP-Servers.\n\nReturns: `String`\n\nSetzt `CONF.smtp.server`. Verwende ihn mit `mail_smtp_options` statt eines einzelnen `smtp`-Objekts.\n\nExample: /config\n```text\nmail_smtp : smtp.example.com\n```\n\n### CONF.mail_smtp_options\n\nType: `config`\n\nDie SMTP-Optionen ohne den Server.\n\nReturns: `Object`\n\nEin Objekt, dessen Schlüssel in `CONF.smtp` kopiert werden (`port`, `secure`, `user`, `password`...).\n\nExample: /config\n```text\nmail_smtp_options : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_from\n\nType: `config`\n\nDie Standard-Absenderadresse.\n\nReturns: `String`\n\nDie `From:`-Adresse von `MAIL()`, `HTMLMAIL()` und `LOGMAIL()`. Ohne sie wird `CONF.smtp.from` oder `CONF.smtp.user` verwendet.\n\nExample: /config\n```text\nmail_from : info@example.com\n```\n\n### CONF.mail_from_name\n\nType: `config`\n\nDer Standard-Absendername.\n\nReturns: `String`\n\nDer Anzeigename des Absenders von `MAIL()`, `HTMLMAIL()` und `LOGMAIL()`. Ohne ihn wird `CONF.smtp.name` verwendet.\n\nExample: /config\n```text\nmail_from_name : My application\n```\n\n### CONF.mail_reply\n\nType: `config`\n\nDie Standard-Antwortadresse.\n\nReturns: `String`\n\nEine Adresse, die den Nachrichten von `MAIL()`, `HTMLMAIL()` und `LOGMAIL()` als `Reply-To:` hinzugefügt wird.\n\nExample: /config\n```text\nmail_reply : support@example.com\n```\n\n### CONF.mail_cc\n\nType: `config`\n\nEin Standard-Kopie-Empfänger.\n\nReturns: `String`\n\nEine Adresse, die den Nachrichten von `MAIL()`, `HTMLMAIL()` und `LOGMAIL()` als `Cc:` hinzugefügt wird.\n\nExample: /config\n```text\nmail_cc : office@example.com\n```\n\n### CONF.mail_bcc\n\nType: `config`\n\nEin Standard-Blindkopie-Empfänger.\n\nReturns: `String`\n\nEine Adresse, die den Nachrichten von `MAIL()`, `HTMLMAIL()` und `LOGMAIL()` als Blindkopie hinzugefügt wird.\n\nExample: /config\n```text\nmail_bcc : archive@example.com\n```\n\n### $tapimail : true\n\nType: `config`\n\nSendet die Nachrichten über die Total.js API statt über SMTP.\n\nReturns: `Boolean`\n\nStandard `false`. Mit `true` senden `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` und `message.send2()` die Nachricht mit `API('TAPI', 'mail', data)` und dem Token `secret_totalapi`; `$tapi` muss `true` sein (der Standard). Der Dienst erhält die Empfänger (`to`, `cc`, `bcc`, `reply`), `from`, `subject`, `type`, `body`, `priority`, `unsubscribe` und `confidential`. Anhänge und `message.headers` werden nicht gesendet. Der Callback der Nachricht erhält die Antwort des Dienstes.\n\nExample: /config\n```text\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL()","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL()","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL()","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create()","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send()","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2()","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try()","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send')","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error')","since":"","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail')","since":"","deprecated":false},{"type":"class","name":"Mail.Message","signature":"Mail.Message","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to()","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc()","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc()","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply()","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from()","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender()","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment()","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()","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback()","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2()","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(options)","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":"property","name":"message.headers","signature":"message.headers","since":"","deprecated":false},{"type":"method","name":"message.high()","signature":"message.high()","since":"","deprecated":false},{"type":"method","name":"message.low()","signature":"message.low()","since":"","deprecated":false},{"type":"method","name":"message.confidential()","signature":"message.confidential()","since":"","deprecated":false},{"type":"config","name":"CONF.smtp","signature":"CONF.smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp","signature":"CONF.mail_smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp_options","signature":"CONF.mail_smtp_options","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from","signature":"CONF.mail_from","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from_name","signature":"CONF.mail_from_name","since":"","deprecated":false},{"type":"config","name":"CONF.mail_reply","signature":"CONF.mail_reply","since":"","deprecated":false},{"type":"config","name":"CONF.mail_cc","signature":"CONF.mail_cc","since":"","deprecated":false},{"type":"config","name":"CONF.mail_bcc","signature":"CONF.mail_bcc","since":"","deprecated":false},{"type":"config","name":"CONF.$tapimail","signature":"$tapimail : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwu84qx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/mail/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Enviar correo electrónico","summary":"MAIL(), HTMLMAIL(), LOGMAIL(), el módulo Mail, el objeto mensaje y las claves SMTP.","markdown":"---\ntitle: \"Enviar correo electrónico\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/mail/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Enviar correo electrónico\n\n> MAIL(), HTMLMAIL(), LOGMAIL(), el módulo Mail, el objeto mensaje y las claves SMTP.\n\nEsta página enumera las funciones globales de correo, el módulo `Mail` con sus eventos, los métodos y propiedades del objeto mensaje, y las claves de configuración para SMTP y el remitente por defecto. La guía [Envío de correo electrónico](../../guides/mail/) explica cómo funcionan juntos, con ejemplos.\n\n## API\n\n### MAIL()\n\nType: `method`\n\nRenderiza una vista y la envía como correo electrónico.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Una dirección, direcciones separadas por comas 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 la vista, p. ej. `mail/welcome`. |\n| `model` | `Object` | no |  | El modelo de la vista. |\n| `language` | `String` | no |  | El idioma para la vista y el asunto. |\n| `callback` | `Function` | no |  | `function(err, message)`, igual que `message.callback()`. |\n\nReturns: `Message` El mensaje que se enviará.\n\nRenderiza la vista `view` (una ruta en `/views/` sin `.html`) con `model` y envía el HTML a `email`. El remitente, la dirección de respuesta y las copias vienen de `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` y `mail_bcc` (o de `from`/`name` de `CONF.smtp`). Con `language`, la vista se renderiza en ese idioma y se traduce un asunto con `@(...)`. El mensaje se envía en la siguiente vuelta del bucle de eventos, así que todavía puedes cambiar el mensaje devuelto. Cuando `language` es una función, se usa como callback.\n\nExample: Correo de bienvenida\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n### HTMLMAIL()\n\nType: `method`\n\nEnvía un correo electrónico con un cuerpo HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Una dirección, direcciones separadas por comas 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. |\n| `language` | `String` | no |  | El idioma para traducir el asunto y el cuerpo. |\n| `callback` | `Function` | no |  | `function(err, message)`, igual que `message.callback()`. |\n\nReturns: `Message` El mensaje que se enviará.\n\nEnvía `body` como HTML. Un cuerpo sin la etiqueta `<body>` se envuelve en un documento HTML simple con el asunto como título. Con `language`, se traducen los textos `@(...)` del asunto y del cuerpo. Los valores por defecto son los mismos que para `MAIL()`. Cuando `language` es una función, se usa como callback.\n\nExample: Enviar HTML\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL()\n\nType: `method`\n\nEnvía un informe breve como texto preformateado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Una dirección, direcciones separadas por comas o un array de direcciones. Cada una se convierte en un destinatario `To:`. |\n| `subject` | `String` | no |  | El asunto (por defecto `CONF.name`). |\n| `body` | `String|Object` | yes |  | El texto, o un objeto que se serializa. |\n| `callback` | `Function` | no |  | `function(err, message)`, igual que `message.callback()`. |\n\nReturns: `Message` El mensaje que se enviará.\n\nEnvuelve `body` en un bloque `<pre>` y lo envía. Un string se inserta tal cual, así que puede contener HTML. Un objeto se serializa a JSON y se codifica en HTML. Sin `subject` (dos argumentos, o una función como tercero), el asunto es `CONF.name`. Los valores por defecto son los mismos que para `MAIL()`.\n\nExample: Informe\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n### DEF.onMail\n\nType: `delegate`\n\nLa función que construye y envía los mensajes de MAIL(), HTMLMAIL() y LOGMAIL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Una dirección, direcciones separadas por comas 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. |\n| `reply` | `String` | no |  | Una dirección de respuesta en lugar de `mail_reply`. |\n\nReturns: `Message` El mensaje.\n\nSe llama como `DEF.onMail(email, subject, body, callback, reply)`. Crea el mensaje, añade los destinatarios, el remitente (`mail_from` o `CONF.smtp.from`/`user`, `mail_from_name` o `CONF.smtp.name`), la dirección de respuesta (`reply` o `mail_reply`), `mail_cc` y `mail_bcc`, define el callback y programa el envío. Debe devolver el mensaje. Cuando `callback` es una cadena, se toma como `reply`.\n\nExample: Añadir una cabecera a cada mensaje\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\n### Mail\n\nType: `class`\n\nEl cliente SMTP global.\n\nReturns: `Object`\n\n`Mail` es el sistema de envío de correo del framework. Crea mensajes (`Mail.create()`), los envía (`Mail.send()`, `Mail.send2()`), prueba un servidor (`Mail.try()`) y emite los eventos `send` y `error`. `Mail.Message` (también `Mail.Mail`) es el constructor de los mensajes.\n\nExample: Crear y enviar\n```js\nvar msg = Mail.create('Hello', '<p>Hello</p>');\nmsg.from('info@example.com').to('user@example.com').send2();\n```\n\n### Mail.create()\n\nType: `method`\n\nCrea un mensaje nuevo.\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: `Message` Un mensaje nuevo.\n\nDevuelve un mensaje nuevo con el asunto y el cuerpo. A diferencia de `MAIL()`, no se define ni se envía nada por ti: añade el remitente y los destinatarios y llama a `message.send2()` o `message.send()`.\n\nExample: Crear\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.send2();\n```\n\n### Mail.send()\n\nType: `method`\n\nEnvía uno o varios mensajes con las opciones SMTP indicadas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Las opciones SMTP. |\n| `messages` | `Message|Array` | yes |  | Un mensaje o un array de mensajes. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nAbre una conexión con `options` (las mismas claves que `CONF.smtp`), envía los mensajes uno tras otro y cierra la conexión. El callback recibe `err` cuando falla la conexión o el inicio de sesión. Usa `message.callback()` para el resultado de cada mensaje.\n\nExample: Dos mensajes, una conexión\n```js\nvar a = Mail.create('A', '<p>A</p>').from('info@example.com').to('a@example.com');\nvar b = Mail.create('B', '<p>B</p>').from('info@example.com').to('b@example.com');\nMail.send(CONF.smtp, [a, b]);\n```\n\n### Mail.send2()\n\nType: `method`\n\nEnvía mensajes con CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `Message|Array` | yes |  | Un mensaje o un array de mensajes. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nLo mismo que `Mail.send(CONF.smtp, messages, callback)`.\n\nExample: Enviar\n```js\nMail.send2([msg1, msg2]);\n```\n\n### Mail.try()\n\nType: `method`\n\nPrueba la conexión y el inicio de sesión en un servidor SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Las opciones SMTP. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Sin callback.\n\nSe conecta con `options`, inicia sesión y sale sin enviar nada. Sin callback devuelve una promesa.\n\nExample: Comprobar la configuración\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n### Mail.debug\n\nType: `property`\n\nImprime la conversación SMTP en la consola.\n\nReturns: `Boolean` Por defecto `false`.\n\nCon `true`, se imprime cada línea enviada al servidor y recibida de él. Por defecto `false`.\n\nExample: Debug\n```js\nMail.debug = true;\n```\n\n### Mail.on('send')\n\nType: `event`\n\nSe emite cuando una conexión está lista para enviar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | El objeto interno de la conexión. |\n\n`Mail.on('send', function(connection) {})`. Se emite cuando el cliente inicia la conversación SMTP de una conexión.\n\nExample: Escuchar\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection ready');\n});\n```\n\n### Mail.on('error')\n\nType: `event`\n\nSe emite en los errores SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | El error. |\n| `connection` | `Object` | yes |  | El objeto interno de la conexión. |\n\n`Mail.on('error', function(err, connection) {})`. Se emite cuando falla la conexión, se rechaza el inicio de sesión o el servidor responde con un error. `err` es un `Error` o la línea de respuesta del servidor.\n\nExample: Registrar errores SMTP\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### ON('$mail')\n\nType: `event`\n\nSe emite por cada mensaje que se está enviando.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Message` | yes |  | El mensaje. |\n\n`ON('$mail', function(message) {})`. Se emite justo antes de que el mensaje se escriba en el servidor SMTP.\n\nExample: Registrar cada correo en el log\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n```\n\n### Mail.Message\n\nType: `class`\n\nEl objeto mensaje.\n\nReturns: `Object`\n\nUn mensaje lo devuelven `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` y `Mail.create()`; `new Mail.Message(subject, body)` también crea uno (`Mail.Mail` es un alias). Sus métodos devuelven el mensaje, así que las llamadas se pueden encadenar. Los destinatarios están en `email_to`, `email_cc`, `email_bcc` y `email_reply` (arrays), el remitente en `email_from` y `email_from_name`.\n\nExample: Encadenar\n```js\nMail.create('Hi', '<p>Hi</p>').from('info@example.com').to('a@example.com').cc('b@example.com').send2();\n```\n\n### message.to()\n\nType: `method`\n\nAñade un destinatario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Una dirección. |\n| `clear` | `Boolean` | no | `false` | Elimina primero los destinatarios actuales. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nAñade una dirección a la cabecera `To:`. Con `clear`, primero se eliminan los destinatarios actuales.\n\nExample: Destinatarios\n```js\nmsg.to('a@example.com').to('b@example.com');\n```\n\n### message.cc()\n\nType: `method`\n\nAñade un destinatario en copia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Una dirección. |\n| `clear` | `Boolean` | no | `false` | Elimina primero las copias actuales. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nAñade una dirección a la cabecera `Cc:`. Con `clear`, primero se eliminan las copias actuales.\n\nExample: Copia\n```js\nmsg.cc('boss@example.com');\n```\n\n### message.bcc()\n\nType: `method`\n\nAñade un destinatario en copia oculta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Una dirección. |\n| `clear` | `Boolean` | no | `false` | Elimina primero las copias ocultas actuales. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nAñade una dirección que recibe el mensaje sin aparecer en las cabeceras. Con `clear`, primero se eliminan las copias ocultas actuales.\n\nExample: Copia oculta\n```js\nmsg.bcc('archive@example.com');\n```\n\n### message.reply()\n\nType: `method`\n\nAñade una dirección de respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Una dirección. |\n| `clear` | `Boolean` | no | `false` | Elimina primero las direcciones de respuesta actuales. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nAñade una dirección a la cabecera `Reply-To:`. Con `clear`, primero se eliminan las direcciones de respuesta actuales.\n\nExample: Responder a soporte\n```js\nmsg.reply('support@example.com');\n```\n\n### message.from()\n\nType: `method`\n\nDefine el remitente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | La dirección. |\n| `name` | `String` | no |  | El nombre visible. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nDefine la dirección `From:` y, opcionalmente, el nombre visible. `message.sender()` es el mismo método.\n\nExample: Remitente\n```js\nmsg.from('info@example.com', 'My application');\n```\n\n### message.sender()\n\nType: `method`\n\nUn alias de message.from().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | La dirección. |\n| `name` | `String` | no |  | El nombre visible. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nLo mismo que `message.from(email, [name])`.\n\nExample: Remitente\n```js\nmsg.sender('info@example.com');\n```\n\n### message.attachment()\n\nType: `method`\n\nAdjunta un archivo del disco o un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Buffer` | yes |  | La ruta al archivo, o un `Buffer` con el contenido. |\n| `name` | `String` | yes |  | El nombre de archivo para el destinatario, con su extensión. |\n| `contentid` | `String` | no |  | El ID de contenido para un archivo en línea. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nAñade el archivo `filename`, o el contenido de un `Buffer`, como adjunto. `name` es el nombre de archivo que se muestra al destinatario, y su extensión define el tipo de contenido (`application/octet-stream` para las desconocidas). Con `contentid`, el archivo es una parte en línea a la que el cuerpo HTML se refiere como `cid:<contentid>`. El archivo se lee cuando se envía el mensaje.\n\nExample: Adjuntar un PDF\n```js\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\n```\n\nExample: Imagen en línea\n```js\nvar msg = HTMLMAIL('user@example.com', 'News', '<img src=\"cid:logo\" />');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nExample: Desde un Buffer\n```js\nvar pdf = Buffer.from('%PDF-1.4 ...');\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.attachment(pdf, 'invoice.pdf');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nAdjunta un archivo de un almacenamiento de archivos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | El nombre del almacenamiento de archivos. |\n| `id` | `String` | yes |  | El id del archivo en el almacenamiento. |\n| `name` | `String` | no |  | El nombre de archivo para el destinatario, con su extensión. Por defecto: el nombre guardado con el archivo. |\n| `contentid` | `String` | no |  | El ID de contenido para un archivo en línea. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nAñade un archivo de un [almacenamiento de archivos](../file-storage/) como adjunto: `storage` es el nombre del almacenamiento (como en `FILESTORAGE(name)`) e `id` el id del archivo. Sin `name`, el destinatario ve el nombre del archivo en el almacenamiento y el tipo de contenido es el tipo guardado con el archivo; con `name`, su extensión define el tipo de contenido. Con `contentid`, el archivo es una parte en línea a la que el cuerpo HTML se refiere como `cid:<contentid>`.\n\nEl archivo se lee cuando se envía el mensaje. Cuando no existe, el error se escribe en el log de errores y el mensaje se envía sin el adjunto.\n\nExample: Adjuntar un archivo guardado\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Contract', '<p>The contract is attached.</p>');\nmsg.attachmentfs('documents', id);\n```\n\nExample: Otro nombre\n```js\nmsg.attachmentfs('documents', id, 'contract-2025.pdf');\n```\n\n### message.unsubscribe()\n\nType: `method`\n\nAñade las cabeceras List-Unsubscribe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL o la dirección de correo para darse de baja. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nAñade `List-Unsubscribe` y `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. Un valor que empieza por `http:` o `https:` se usa como URL; cualquier otro valor es una dirección de correo electrónico (`mailto:`).\n\nExample: Boletín\n```js\nmsg.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback()\n\nType: `method`\n\nDefine la función a la que se llama con el resultado del mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `Message` El mensaje, para encadenar.\n\n`fn(err, message)` se llama con un `err` vacío cuando el mensaje se ha entregado al servidor, o con un error: la línea de respuesta del servidor (en mayúsculas) cuando rechaza el mensaje o el inicio de sesión, `No SMTP server configuration.`, o un error de conexión o de tiempo de espera. Un error que llega a un callback no se escribe en el log de errores. `MAIL()`, `HTMLMAIL()` y `LOGMAIL()` lo establecen a partir de su argumento `callback`.\n\nExample: Resultado\n```js\nmsg.callback(function(err, message) {\n\tif (err)\n\t\tconsole.log('Not sent:', message.subject, err);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nDetiene el envío automático.\n\nReturns: `Message` El mensaje, para encadenar.\n\n`MAIL()`, `HTMLMAIL()` y `LOGMAIL()` envían el mensaje en la siguiente vuelta del bucle de eventos. Llama a `manually()` justo después de ellas para cancelarlo, y envía el mensaje más tarde con `message.send2()` o `message.send()`.\n\nExample: Enviar más tarde\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n// ...\nmsg.send2();\n```\n\n### message.send2()\n\nType: `method`\n\nEnvía el mensaje con CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nEnvía el mensaje con el servidor SMTP configurado (`CONF.smtp`).\n\nExample: Enviar\n```js\nMail.create('Hello', '<p>Hello</p>').from('info@example.com').to('user@example.com').send2(function(err) {\n\terr && console.log(err);\n});\n```\n\n### message.send(options)\n\nType: `method`\n\nEnvía el mensaje con otras opciones SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Las opciones SMTP. |\n\nReturns: `Message` El mensaje, para encadenar.\n\nEnvía el mensaje por una conexión nueva con `options` (las mismas claves que `CONF.smtp`). Usa `message.callback()` para el resultado.\n\nExample: Otro servidor\n```js\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send({ server: 'smtp.other.com', port: 587, user: 'me@other.com', password: 'secret' });\n```\n\n### message.subject\n\nType: `property`\n\nEl asunto.\n\nReturns: `String`\n\nEl asunto del mensaje. Los caracteres no ASCII se codifican por ti.\n\nExample: Cambiar\n```js\nmsg.subject = 'Updated subject';\n```\n\n### message.body\n\nType: `property`\n\nEl cuerpo.\n\nReturns: `String`\n\nEl cuerpo del mensaje: HTML, o texto plano cuando `type` es `plain`.\n\nExample: Cambiar\n```js\nmsg.body = '<p>New text</p>';\n```\n\n### message.type\n\nType: `property`\n\nEl tipo del cuerpo.\n\nReturns: `String` Por defecto `html`.\n\n`html` (por defecto) o `plain`. Se convierte en el `Content-Type` del cuerpo (`text/html` o `text/plain`).\n\nExample: Texto plano\n```js\nvar msg = Mail.create('Hello', 'Hello in plain text');\nmsg.type = 'plain';\n```\n\n### message.headers\n\nType: `property`\n\nCabeceras adicionales del mensaje.\n\nReturns: `Object`\n\nUn objeto de nombres y valores de cabeceras que se escriben en el mensaje tal cual. No está definido por defecto.\n\nExample: Cabecera personalizada\n```js\nmsg.headers = { 'X-Campaign': 'spring-2025' };\n```\n\n### message.high()\n\nType: `method`\n\nMarca el mensaje como de prioridad alta.\n\nReturns: `Message` El mismo mensaje.\n\nAñade la cabecera `X-Priority: 1`. Devuelve el mensaje.\n\nExample: Urgente\n```js\nHTMLMAIL('admin@example.com', 'Disk full', '<p>The disk is full.</p>').high();\n```\n\n### message.low()\n\nType: `method`\n\nMarca el mensaje como de prioridad baja.\n\nReturns: `Message` El mismo mensaje.\n\nAñade la cabecera `X-Priority: 5`. Devuelve el mensaje.\n\nExample: Resumen semanal\n```js\nMAIL(user.email, 'Your week', 'mail/digest', model).low();\n```\n\n### message.confidential()\n\nType: `method`\n\nMarca el mensaje como confidencial.\n\nReturns: `Message` El mismo mensaje.\n\nAñade la cabecera `Sensitivity: Company-Confidential`. Devuelve el mensaje.\n\nExample: Informe confidencial\n```js\nHTMLMAIL('board@example.com', 'Salaries', html).confidential().high();\n```\n\n### CONF.smtp\n\nType: `config`\n\nEl servidor SMTP y sus opciones.\n\nReturns: `Object`\n\nUn objeto con `server` (o `host`, `hostname`, `smtp`, `url`), `port`, `secure`, `user`, `password`, `token`, `tls`, `timeout`, `from` y `name`. Con `secure: true` la conexión usa TLS desde el principio y `port` es `465` por defecto; si no, define `port`. La clave `mail` del archivo de configuración es lo mismo.\n\nAntes de la conexión, `server` se convierte con `U.tohost()`: un nombre internacional se envía como punycode y una dirección IPv4 en su forma con puntos (`127.1` se convierte en `127.0.0.1`). Un valor que no es un nombre de host válido da el error `Invalid SMTP server hostname.` y no se envía nada.\n\nExample: /config\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nExample: STARTTLS en el puerto 587\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_smtp\n\nType: `config`\n\nEl nombre del servidor SMTP.\n\nReturns: `String`\n\nDefine `CONF.smtp.server`. Úsalo con `mail_smtp_options` en lugar de un objeto `smtp`.\n\nExample: /config\n```text\nmail_smtp : smtp.example.com\n```\n\n### CONF.mail_smtp_options\n\nType: `config`\n\nLas opciones SMTP sin el servidor.\n\nReturns: `Object`\n\nUn objeto cuyas claves se copian en `CONF.smtp` (`port`, `secure`, `user`, `password`...).\n\nExample: /config\n```text\nmail_smtp_options : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_from\n\nType: `config`\n\nLa dirección del remitente por defecto.\n\nReturns: `String`\n\nLa dirección `From:` de `MAIL()`, `HTMLMAIL()` y `LOGMAIL()`. Sin ella, se usa `CONF.smtp.from` o `CONF.smtp.user`.\n\nExample: /config\n```text\nmail_from : info@example.com\n```\n\n### CONF.mail_from_name\n\nType: `config`\n\nEl nombre del remitente por defecto.\n\nReturns: `String`\n\nEl nombre visible del remitente de `MAIL()`, `HTMLMAIL()` y `LOGMAIL()`. Sin él, se usa `CONF.smtp.name`.\n\nExample: /config\n```text\nmail_from_name : My application\n```\n\n### CONF.mail_reply\n\nType: `config`\n\nLa dirección de respuesta por defecto.\n\nReturns: `String`\n\nUna dirección que se añade como `Reply-To:` a los mensajes de `MAIL()`, `HTMLMAIL()` y `LOGMAIL()`.\n\nExample: /config\n```text\nmail_reply : support@example.com\n```\n\n### CONF.mail_cc\n\nType: `config`\n\nUn destinatario en copia por defecto.\n\nReturns: `String`\n\nUna dirección que se añade como `Cc:` a los mensajes de `MAIL()`, `HTMLMAIL()` y `LOGMAIL()`.\n\nExample: /config\n```text\nmail_cc : office@example.com\n```\n\n### CONF.mail_bcc\n\nType: `config`\n\nUn destinatario en copia oculta por defecto.\n\nReturns: `String`\n\nUna dirección que se añade como copia oculta a los mensajes de `MAIL()`, `HTMLMAIL()` y `LOGMAIL()`.\n\nExample: /config\n```text\nmail_bcc : archive@example.com\n```\n\n### $tapimail : true\n\nType: `config`\n\nEnvía los mensajes a través de Total.js API en lugar de SMTP.\n\nReturns: `Boolean`\n\nPor defecto `false`. Con `true`, `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` y `message.send2()` envían el mensaje con `API('TAPI', 'mail', data)` y el token `secret_totalapi`; `$tapi` tiene que ser `true` (el valor por defecto). El servicio recibe los destinatarios (`to`, `cc`, `bcc`, `reply`), `from`, `subject`, `type`, `body`, `priority`, `unsubscribe` y `confidential`. Los adjuntos y `message.headers` no se envían. El callback del mensaje recibe la respuesta del servicio.\n\nExample: /config\n```text\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL()","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL()","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL()","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create()","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send()","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2()","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try()","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send')","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error')","since":"","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail')","since":"","deprecated":false},{"type":"class","name":"Mail.Message","signature":"Mail.Message","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to()","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc()","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc()","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply()","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from()","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender()","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment()","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()","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback()","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2()","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(options)","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":"property","name":"message.headers","signature":"message.headers","since":"","deprecated":false},{"type":"method","name":"message.high()","signature":"message.high()","since":"","deprecated":false},{"type":"method","name":"message.low()","signature":"message.low()","since":"","deprecated":false},{"type":"method","name":"message.confidential()","signature":"message.confidential()","since":"","deprecated":false},{"type":"config","name":"CONF.smtp","signature":"CONF.smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp","signature":"CONF.mail_smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp_options","signature":"CONF.mail_smtp_options","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from","signature":"CONF.mail_from","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from_name","signature":"CONF.mail_from_name","since":"","deprecated":false},{"type":"config","name":"CONF.mail_reply","signature":"CONF.mail_reply","since":"","deprecated":false},{"type":"config","name":"CONF.mail_cc","signature":"CONF.mail_cc","since":"","deprecated":false},{"type":"config","name":"CONF.mail_bcc","signature":"CONF.mail_bcc","since":"","deprecated":false},{"type":"config","name":"CONF.$tapimail","signature":"$tapimail : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwu84qx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/mail/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Envoyer des e-mails","summary":"MAIL(), HTMLMAIL(), LOGMAIL(), le module Mail, l'objet message et les clés SMTP.","markdown":"---\ntitle: Envoyer des e-mails\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/mail/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Envoyer des e-mails\n\n> MAIL(), HTMLMAIL(), LOGMAIL(), le module Mail, l'objet message et les clés SMTP.\n\nCette page liste les fonctions d'e-mail globales, le module `Mail` avec ses événements, les méthodes et propriétés de l'objet message, et les clés de configuration pour SMTP et l'expéditeur par défaut. Le guide [Envoi d'e-mails](../../guides/mail/) explique, avec des exemples, comment ils fonctionnent ensemble.\n\n## API\n\n### MAIL()\n\nType: `method`\n\nRend une vue et l'envoie comme e-mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Une adresse, des adresses séparées par des virgules ou un tableau d'adresses. Chacune devient un destinataire `To:`. |\n| `subject` | `String` | yes |  | Le sujet. |\n| `view` | `String` | yes |  | Le nom de la vue, par ex. `mail/welcome`. |\n| `model` | `Object` | no |  | Le modèle de la vue. |\n| `language` | `String` | no |  | La langue de la vue et du sujet. |\n| `callback` | `Function` | no |  | `function(err, message)`, identique à `message.callback()`. |\n\nReturns: `Message` Le message qui sera envoyé.\n\nRend la vue `view` (un chemin dans `/views/` sans `.html`) avec `model` et envoie le HTML à `email`. L'expéditeur, l'adresse de réponse et les copies proviennent de `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` et `mail_bcc` (ou de `from`/`name` de `CONF.smtp`). Avec `language`, la vue est rendue dans cette langue et un sujet avec `@(...)` est traduit. Le message est envoyé au tour suivant de la boucle d'événements ; tu peux donc encore modifier le message renvoyé. Lorsque `language` est une fonction, elle est utilisée comme callback.\n\nExample: E-mail de bienvenue\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n### HTMLMAIL()\n\nType: `method`\n\nEnvoie un e-mail avec un corps HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Une adresse, des adresses séparées par des virgules ou un tableau d'adresses. Chacune devient un destinataire `To:`. |\n| `subject` | `String` | yes |  | Le sujet. |\n| `body` | `String` | yes |  | Le HTML. |\n| `language` | `String` | no |  | La langue de traduction du sujet et du corps. |\n| `callback` | `Function` | no |  | `function(err, message)`, identique à `message.callback()`. |\n\nReturns: `Message` Le message qui sera envoyé.\n\nEnvoie `body` en HTML. Un corps sans balise `<body>` est enveloppé dans un document HTML simple avec le sujet comme titre. Avec `language`, les textes `@(...)` du sujet et du corps sont traduits. Les valeurs par défaut sont les mêmes que pour `MAIL()`. Lorsque `language` est une fonction, elle est utilisée comme callback.\n\nExample: Envoyer du HTML\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL()\n\nType: `method`\n\nEnvoie un court rapport sous forme de texte préformaté.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Une adresse, des adresses séparées par des virgules ou un tableau d'adresses. Chacune devient un destinataire `To:`. |\n| `subject` | `String` | no |  | Le sujet (par défaut `CONF.name`). |\n| `body` | `String|Object` | yes |  | Le texte, ou un objet à sérialiser. |\n| `callback` | `Function` | no |  | `function(err, message)`, identique à `message.callback()`. |\n\nReturns: `Message` Le message qui sera envoyé.\n\nEnveloppe `body` dans un bloc `<pre>` et l'envoie. Une chaîne est insérée telle quelle, elle peut donc contenir du HTML. Un objet est sérialisé en JSON et encodé en HTML. Sans `subject` (deux arguments, ou une fonction comme troisième argument), `CONF.name` est le sujet. Les valeurs par défaut sont les mêmes que pour `MAIL()`.\n\nExample: Rapport\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n### DEF.onMail\n\nType: `delegate`\n\nLa fonction qui construit et envoie les messages de MAIL(), HTMLMAIL() et LOGMAIL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Une adresse, des adresses séparées par des virgules 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. |\n| `reply` | `String` | no |  | Une adresse de réponse à la place de `mail_reply`. |\n\nReturns: `Message` Le message.\n\nAppelée sous la forme `DEF.onMail(email, subject, body, callback, reply)`. Elle crée le message, ajoute les destinataires, l'expéditeur (`mail_from` ou `CONF.smtp.from`/`user`, `mail_from_name` ou `CONF.smtp.name`), l'adresse de réponse (`reply` ou `mail_reply`), `mail_cc` et `mail_bcc`, définit le callback et planifie l'envoi. Elle doit renvoyer le message. Lorsque `callback` est une chaîne, il est pris comme `reply`.\n\nExample: Ajouter un en-tête à chaque message\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\n### Mail\n\nType: `class`\n\nLe client SMTP global.\n\nReturns: `Object`\n\n`Mail` est le module d'envoi d'e-mails du framework. Il crée des messages (`Mail.create()`), les envoie (`Mail.send()`, `Mail.send2()`), teste un serveur (`Mail.try()`) et émet les événements `send` et `error`. `Mail.Message` (aussi `Mail.Mail`) est le constructeur des messages.\n\nExample: Créer et envoyer\n```js\nvar msg = Mail.create('Hello', '<p>Hello</p>');\nmsg.from('info@example.com').to('user@example.com').send2();\n```\n\n### Mail.create()\n\nType: `method`\n\nCrée un nouveau message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `subject` | `String` | yes |  | Le sujet. |\n| `body` | `String` | yes |  | Le corps (HTML par défaut). |\n\nReturns: `Message` Un nouveau message.\n\nRenvoie un nouveau message avec le sujet et le corps. Contrairement à `MAIL()`, rien n'est défini ni envoyé à ta place : ajoute l'expéditeur et les destinataires, puis appelle `message.send2()` ou `message.send()`.\n\nExample: Créer\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.send2();\n```\n\n### Mail.send()\n\nType: `method`\n\nEnvoie un ou plusieurs messages avec les options SMTP données.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Les options SMTP. |\n| `messages` | `Message|Array` | yes |  | Un message ou un tableau de messages. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nOuvre une connexion avec `options` (les mêmes clés que `CONF.smtp`), envoie les messages l'un après l'autre et ferme la connexion. Le callback reçoit `err` lorsque la connexion ou l'authentification échoue. Utilise `message.callback()` pour le résultat de chaque message.\n\nExample: Deux messages, une connexion\n```js\nvar a = Mail.create('A', '<p>A</p>').from('info@example.com').to('a@example.com');\nvar b = Mail.create('B', '<p>B</p>').from('info@example.com').to('b@example.com');\nMail.send(CONF.smtp, [a, b]);\n```\n\n### Mail.send2()\n\nType: `method`\n\nEnvoie des messages avec CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `Message|Array` | yes |  | Un message ou un tableau de messages. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nIdentique à `Mail.send(CONF.smtp, messages, callback)`.\n\nExample: Envoyer\n```js\nMail.send2([msg1, msg2]);\n```\n\n### Mail.try()\n\nType: `method`\n\nTeste la connexion et l'authentification sur un serveur SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Les options SMTP. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Sans callback.\n\nSe connecte avec `options`, s'authentifie et se déconnecte sans rien envoyer. Sans callback, renvoie une promesse.\n\nExample: Vérifier les paramètres\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n### Mail.debug\n\nType: `property`\n\nAffiche l'échange SMTP dans la console.\n\nReturns: `Boolean` Par défaut `false`.\n\nAvec `true`, chaque ligne envoyée au serveur et reçue de celui-ci est affichée. Par défaut `false`.\n\nExample: Debug\n```js\nMail.debug = true;\n```\n\n### Mail.on('send')\n\nType: `event`\n\nÉmis lorsqu'une connexion est prête à envoyer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | L'objet de connexion interne. |\n\n`Mail.on('send', function(connection) {})`. Émis lorsque le client commence la conversation SMTP d'une connexion.\n\nExample: Écouter\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection ready');\n});\n```\n\n### Mail.on('error')\n\nType: `event`\n\nÉmis lors des erreurs SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'erreur. |\n| `connection` | `Object` | yes |  | L'objet de connexion interne. |\n\n`Mail.on('error', function(err, connection) {})`. Émis lorsque la connexion échoue, que l'authentification est refusée ou que le serveur répond par une erreur. `err` est une `Error` ou la ligne de réponse du serveur.\n\nExample: Journaliser les erreurs SMTP\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### ON('$mail')\n\nType: `event`\n\nÉmis pour chaque message en cours d'envoi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Message` | yes |  | Le message. |\n\n`ON('$mail', function(message) {})`. Émis juste avant que le message soit écrit sur le serveur SMTP.\n\nExample: Journaliser chaque e-mail\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n```\n\n### Mail.Message\n\nType: `class`\n\nL'objet message.\n\nReturns: `Object`\n\nUn message est renvoyé par `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` et `Mail.create()` ; `new Mail.Message(subject, body)` en crée un aussi (`Mail.Mail` est un alias). Ses méthodes renvoient le message ; les appels peuvent donc être chaînés. Les destinataires se trouvent dans `email_to`, `email_cc`, `email_bcc` et `email_reply` (des tableaux), l'expéditeur dans `email_from` et `email_from_name`.\n\nExample: Chaînage\n```js\nMail.create('Hi', '<p>Hi</p>').from('info@example.com').to('a@example.com').cc('b@example.com').send2();\n```\n\n### message.to()\n\nType: `method`\n\nAjoute un destinataire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Une adresse. |\n| `clear` | `Boolean` | no | `false` | Supprime d'abord les destinataires actuels. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nAjoute une adresse à l'en-tête `To:`. Avec `clear`, les destinataires actuels sont d'abord supprimés.\n\nExample: Destinataires\n```js\nmsg.to('a@example.com').to('b@example.com');\n```\n\n### message.cc()\n\nType: `method`\n\nAjoute un destinataire en copie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Une adresse. |\n| `clear` | `Boolean` | no | `false` | Supprime d'abord les copies actuelles. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nAjoute une adresse à l'en-tête `Cc:`. Avec `clear`, les copies actuelles sont d'abord supprimées.\n\nExample: Copie\n```js\nmsg.cc('boss@example.com');\n```\n\n### message.bcc()\n\nType: `method`\n\nAjoute un destinataire en copie cachée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Une adresse. |\n| `clear` | `Boolean` | no | `false` | Supprime d'abord les copies cachées actuelles. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nAjoute une adresse qui reçoit le message sans figurer dans les en-têtes. Avec `clear`, les copies cachées actuelles sont d'abord supprimées.\n\nExample: Copie cachée\n```js\nmsg.bcc('archive@example.com');\n```\n\n### message.reply()\n\nType: `method`\n\nAjoute une adresse de réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Une adresse. |\n| `clear` | `Boolean` | no | `false` | Supprime d'abord les adresses de réponse actuelles. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nAjoute une adresse à l'en-tête `Reply-To:`. Avec `clear`, les adresses de réponse actuelles sont d'abord supprimées.\n\nExample: Répondre au support\n```js\nmsg.reply('support@example.com');\n```\n\n### message.from()\n\nType: `method`\n\nDéfinit l'expéditeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | L'adresse. |\n| `name` | `String` | no |  | Le nom affiché. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nDéfinit l'adresse `From:` et, éventuellement, le nom affiché. `message.sender()` est la même méthode.\n\nExample: Expéditeur\n```js\nmsg.from('info@example.com', 'My application');\n```\n\n### message.sender()\n\nType: `method`\n\nUn alias de message.from().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | L'adresse. |\n| `name` | `String` | no |  | Le nom affiché. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nIdentique à `message.from(email, [name])`.\n\nExample: Expéditeur\n```js\nmsg.sender('info@example.com');\n```\n\n### message.attachment()\n\nType: `method`\n\nJoint un fichier du disque ou un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Buffer` | yes |  | Le chemin du fichier, ou un `Buffer` avec le contenu. |\n| `name` | `String` | yes |  | Le nom de fichier pour le destinataire, avec son extension. |\n| `contentid` | `String` | no |  | Le Content-ID d'un fichier intégré. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nAjoute le fichier `filename`, ou le contenu d'un `Buffer`, en pièce jointe. `name` est le nom de fichier affiché au destinataire, et son extension définit le type de contenu (`application/octet-stream` pour les extensions inconnues). Avec `contentid`, le fichier est une partie intégrée que le corps HTML référence sous la forme `cid:<contentid>`. Le fichier est lu au moment de l'envoi du message.\n\nExample: Joindre un PDF\n```js\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\n```\n\nExample: Image intégrée\n```js\nvar msg = HTMLMAIL('user@example.com', 'News', '<img src=\"cid:logo\" />');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nExample: À partir d'un Buffer\n```js\nvar pdf = Buffer.from('%PDF-1.4 ...');\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.attachment(pdf, 'invoice.pdf');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nJoint un fichier d'un stockage de fichiers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Le nom du stockage de fichiers. |\n| `id` | `String` | yes |  | L'id du fichier dans le stockage. |\n| `name` | `String` | no |  | Le nom de fichier pour le destinataire, avec son extension. Par défaut : le nom enregistré avec le fichier. |\n| `contentid` | `String` | no |  | Le Content-ID d'un fichier intégré. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nAjoute un fichier d'un [stockage de fichiers](../file-storage/) en pièce jointe : `storage` est le nom du stockage (comme dans `FILESTORAGE(name)`) et `id` l'id du fichier. Sans `name`, le destinataire voit le nom du fichier dans le stockage et le type de contenu est le type enregistré avec le fichier ; avec `name`, son extension définit le type de contenu. Avec `contentid`, le fichier est une partie intégrée que le corps HTML référence sous la forme `cid:<contentid>`.\n\nLe fichier est lu au moment de l'envoi du message. Quand il n'existe pas, l'erreur est écrite dans le log des erreurs et le message est envoyé sans la pièce jointe.\n\nExample: Joindre un fichier stocké\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Contract', '<p>The contract is attached.</p>');\nmsg.attachmentfs('documents', id);\n```\n\nExample: Un autre nom\n```js\nmsg.attachmentfs('documents', id, 'contract-2025.pdf');\n```\n\n### message.unsubscribe()\n\nType: `method`\n\nAjoute les en-têtes List-Unsubscribe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL ou l'adresse e-mail de désinscription. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nAjoute `List-Unsubscribe` et `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. Une valeur qui commence par `http:` ou `https:` est utilisée comme URL ; toute autre valeur est une adresse e-mail (`mailto:`).\n\nExample: Newsletter\n```js\nmsg.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback()\n\nType: `method`\n\nDéfinit la fonction appelée avec le résultat du message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `Message` Le message, pour le chaînage.\n\n`fn(err, message)` est appelée avec un `err` vide lorsque le message a été remis au serveur, ou avec une erreur : la ligne de réponse du serveur (en majuscules) lorsqu'il refuse le message ou le login, `No SMTP server configuration.`, ou une erreur de connexion ou un délai dépassé. Une erreur qui atteint un callback n'est pas écrite dans le journal des erreurs. `MAIL()`, `HTMLMAIL()` et `LOGMAIL()` la définissent à partir de leur argument `callback`.\n\nExample: Résultat\n```js\nmsg.callback(function(err, message) {\n\tif (err)\n\t\tconsole.log('Not sent:', message.subject, err);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nArrête l'envoi automatique.\n\nReturns: `Message` Le message, pour le chaînage.\n\n`MAIL()`, `HTMLMAIL()` et `LOGMAIL()` envoient le message au tour suivant de la boucle d'événements. Appelle `manually()` juste après elles pour l'annuler, et envoie le message plus tard avec `message.send2()` ou `message.send()`.\n\nExample: Envoyer plus tard\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n// ...\nmsg.send2();\n```\n\n### message.send2()\n\nType: `method`\n\nEnvoie le message avec CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nEnvoie le message avec le serveur SMTP configuré (`CONF.smtp`).\n\nExample: Envoyer\n```js\nMail.create('Hello', '<p>Hello</p>').from('info@example.com').to('user@example.com').send2(function(err) {\n\terr && console.log(err);\n});\n```\n\n### message.send(options)\n\nType: `method`\n\nEnvoie le message avec d'autres options SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Les options SMTP. |\n\nReturns: `Message` Le message, pour le chaînage.\n\nEnvoie le message sur une nouvelle connexion avec `options` (les mêmes clés que `CONF.smtp`). Utilise `message.callback()` pour le résultat.\n\nExample: Un autre serveur\n```js\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send({ server: 'smtp.other.com', port: 587, user: 'me@other.com', password: 'secret' });\n```\n\n### message.subject\n\nType: `property`\n\nLe sujet.\n\nReturns: `String`\n\nLe sujet du message. Les caractères non ASCII sont encodés pour toi.\n\nExample: Modifier\n```js\nmsg.subject = 'Updated subject';\n```\n\n### message.body\n\nType: `property`\n\nLe corps.\n\nReturns: `String`\n\nLe corps du message : du HTML, ou du texte brut lorsque `type` vaut `plain`.\n\nExample: Modifier\n```js\nmsg.body = '<p>New text</p>';\n```\n\n### message.type\n\nType: `property`\n\nLe type du corps.\n\nReturns: `String` Par défaut `html`.\n\n`html` (par défaut) ou `plain`. Il devient le `Content-Type` du corps (`text/html` ou `text/plain`).\n\nExample: Texte brut\n```js\nvar msg = Mail.create('Hello', 'Hello in plain text');\nmsg.type = 'plain';\n```\n\n### message.headers\n\nType: `property`\n\nLes en-têtes supplémentaires du message.\n\nReturns: `Object`\n\nUn objet de noms et de valeurs d'en-têtes écrits tels quels dans le message. Il n'est pas défini par défaut.\n\nExample: En-tête personnalisé\n```js\nmsg.headers = { 'X-Campaign': 'spring-2025' };\n```\n\n### message.high()\n\nType: `method`\n\nMarque le message comme prioritaire.\n\nReturns: `Message` Le même message.\n\nAjoute l'en-tête `X-Priority: 1`. Renvoie le message.\n\nExample: Urgent\n```js\nHTMLMAIL('admin@example.com', 'Disk full', '<p>The disk is full.</p>').high();\n```\n\n### message.low()\n\nType: `method`\n\nMarque le message comme peu prioritaire.\n\nReturns: `Message` Le même message.\n\nAjoute l'en-tête `X-Priority: 5`. Renvoie le message.\n\nExample: Résumé hebdomadaire\n```js\nMAIL(user.email, 'Your week', 'mail/digest', model).low();\n```\n\n### message.confidential()\n\nType: `method`\n\nMarque le message comme confidentiel.\n\nReturns: `Message` Le même message.\n\nAjoute l'en-tête `Sensitivity: Company-Confidential`. Renvoie le message.\n\nExample: Rapport confidentiel\n```js\nHTMLMAIL('board@example.com', 'Salaries', html).confidential().high();\n```\n\n### CONF.smtp\n\nType: `config`\n\nLe serveur SMTP et ses options.\n\nReturns: `Object`\n\nUn objet avec `server` (ou `host`, `hostname`, `smtp`, `url`), `port`, `secure`, `user`, `password`, `token`, `tls`, `timeout`, `from` et `name`. Avec `secure: true`, la connexion utilise TLS dès le départ et `port` vaut `465` par défaut ; sinon, définis `port`. La clé `mail` du fichier de configuration est équivalente.\n\nAvant la connexion, `server` est converti avec `U.tohost()` : un nom international est envoyé en punycode et une adresse IPv4 dans sa forme à points (`127.1` devient `127.0.0.1`). Une valeur qui n'est pas un nom d'hôte valide donne l'erreur `Invalid SMTP server hostname.` et rien n'est envoyé.\n\nExample: /config\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nExample: STARTTLS sur le port 587\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_smtp\n\nType: `config`\n\nLe nom du serveur SMTP.\n\nReturns: `String`\n\nDéfinit `CONF.smtp.server`. Utilise-la avec `mail_smtp_options` au lieu d'un seul objet `smtp`.\n\nExample: /config\n```text\nmail_smtp : smtp.example.com\n```\n\n### CONF.mail_smtp_options\n\nType: `config`\n\nLes options SMTP sans le serveur.\n\nReturns: `Object`\n\nUn objet dont les clés sont copiées dans `CONF.smtp` (`port`, `secure`, `user`, `password`...).\n\nExample: /config\n```text\nmail_smtp_options : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_from\n\nType: `config`\n\nL'adresse d'expéditeur par défaut.\n\nReturns: `String`\n\nL'adresse `From:` de `MAIL()`, `HTMLMAIL()` et `LOGMAIL()`. Sans elle, `CONF.smtp.from` ou `CONF.smtp.user` est utilisé.\n\nExample: /config\n```text\nmail_from : info@example.com\n```\n\n### CONF.mail_from_name\n\nType: `config`\n\nLe nom d'expéditeur par défaut.\n\nReturns: `String`\n\nLe nom affiché de l'expéditeur de `MAIL()`, `HTMLMAIL()` et `LOGMAIL()`. Sans lui, `CONF.smtp.name` est utilisé.\n\nExample: /config\n```text\nmail_from_name : My application\n```\n\n### CONF.mail_reply\n\nType: `config`\n\nL'adresse de réponse par défaut.\n\nReturns: `String`\n\nUne adresse ajoutée comme `Reply-To:` aux messages de `MAIL()`, `HTMLMAIL()` et `LOGMAIL()`.\n\nExample: /config\n```text\nmail_reply : support@example.com\n```\n\n### CONF.mail_cc\n\nType: `config`\n\nUn destinataire en copie par défaut.\n\nReturns: `String`\n\nUne adresse ajoutée comme `Cc:` aux messages de `MAIL()`, `HTMLMAIL()` et `LOGMAIL()`.\n\nExample: /config\n```text\nmail_cc : office@example.com\n```\n\n### CONF.mail_bcc\n\nType: `config`\n\nUn destinataire en copie cachée par défaut.\n\nReturns: `String`\n\nUne adresse ajoutée en copie cachée aux messages de `MAIL()`, `HTMLMAIL()` et `LOGMAIL()`.\n\nExample: /config\n```text\nmail_bcc : archive@example.com\n```\n\n### $tapimail : true\n\nType: `config`\n\nEnvoie les messages via Total.js API au lieu de SMTP.\n\nReturns: `Boolean`\n\nPar défaut `false`. Avec `true`, `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` et `message.send2()` envoient le message avec `API('TAPI', 'mail', data)` et le token `secret_totalapi` ; `$tapi` doit valoir `true` (la valeur par défaut). Le service reçoit les destinataires (`to`, `cc`, `bcc`, `reply`), `from`, `subject`, `type`, `body`, `priority`, `unsubscribe` et `confidential`. Les pièces jointes et `message.headers` ne sont pas envoyés. Le callback du message reçoit la réponse du service.\n\nExample: /config\n```text\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL()","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL()","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL()","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create()","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send()","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2()","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try()","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send')","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error')","since":"","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail')","since":"","deprecated":false},{"type":"class","name":"Mail.Message","signature":"Mail.Message","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to()","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc()","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc()","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply()","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from()","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender()","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment()","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()","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback()","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2()","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(options)","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":"property","name":"message.headers","signature":"message.headers","since":"","deprecated":false},{"type":"method","name":"message.high()","signature":"message.high()","since":"","deprecated":false},{"type":"method","name":"message.low()","signature":"message.low()","since":"","deprecated":false},{"type":"method","name":"message.confidential()","signature":"message.confidential()","since":"","deprecated":false},{"type":"config","name":"CONF.smtp","signature":"CONF.smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp","signature":"CONF.mail_smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp_options","signature":"CONF.mail_smtp_options","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from","signature":"CONF.mail_from","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from_name","signature":"CONF.mail_from_name","since":"","deprecated":false},{"type":"config","name":"CONF.mail_reply","signature":"CONF.mail_reply","since":"","deprecated":false},{"type":"config","name":"CONF.mail_cc","signature":"CONF.mail_cc","since":"","deprecated":false},{"type":"config","name":"CONF.mail_bcc","signature":"CONF.mail_bcc","since":"","deprecated":false},{"type":"config","name":"CONF.$tapimail","signature":"$tapimail : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwu84qx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/mail/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Invio di email","summary":"MAIL(), HTMLMAIL(), LOGMAIL(), il modulo Mail, l'oggetto messaggio e le chiavi SMTP.","markdown":"---\ntitle: Invio di email\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/mail/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Invio di email\n\n> MAIL(), HTMLMAIL(), LOGMAIL(), il modulo Mail, l'oggetto messaggio e le chiavi SMTP.\n\nQuesta pagina elenca le funzioni globali per la posta, il modulo `Mail` con i suoi eventi, i metodi e le proprietà dell'oggetto messaggio e le chiavi di configurazione per SMTP e per il mittente predefinito. La guida [Invio di e-mail](../../guides/mail/) spiega come funzionano insieme, con esempi.\n\n## API\n\n### MAIL()\n\nType: `method`\n\nRenderizza una view e la invia come e-mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Un indirizzo, indirizzi separati da virgole o un array di indirizzi. Ognuno diventa un destinatario `To:`. |\n| `subject` | `String` | yes |  | L'oggetto. |\n| `view` | `String` | yes |  | Il nome della view, per esempio `mail/welcome`. |\n| `model` | `Object` | no |  | Il modello della view. |\n| `language` | `String` | no |  | La lingua per la view e l'oggetto. |\n| `callback` | `Function` | no |  | `function(err, message)`, la stessa di `message.callback()`. |\n\nReturns: `Message` Il messaggio che verrà inviato.\n\nRenderizza la view `view` (un percorso in `/views/` senza `.html`) con `model` e invia l'HTML a `email`. Il mittente, l'indirizzo di risposta e le copie provengono da `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` e `mail_bcc` (o da `from`/`name` di `CONF.smtp`). Con `language`, la view viene renderizzata in quella lingua e un oggetto con `@(...)` viene tradotto. Il messaggio viene inviato al giro successivo dell'event loop, quindi puoi ancora modificare il messaggio restituito. Quando `language` è una funzione, viene usata come callback.\n\nExample: E-mail di benvenuto\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n### HTMLMAIL()\n\nType: `method`\n\nInvia un'e-mail con un corpo HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Un indirizzo, indirizzi separati da virgole o un array di indirizzi. Ognuno diventa un destinatario `To:`. |\n| `subject` | `String` | yes |  | L'oggetto. |\n| `body` | `String` | yes |  | L'HTML. |\n| `language` | `String` | no |  | La lingua per tradurre l'oggetto e il corpo. |\n| `callback` | `Function` | no |  | `function(err, message)`, la stessa di `message.callback()`. |\n\nReturns: `Message` Il messaggio che verrà inviato.\n\nInvia `body` come HTML. Un corpo senza tag `<body>` viene racchiuso in un semplice documento HTML con l'oggetto come titolo. Con `language`, i testi `@(...)` nell'oggetto e nel corpo vengono tradotti. I valori predefiniti sono gli stessi di `MAIL()`. Quando `language` è una funzione, viene usata come callback.\n\nExample: Inviare HTML\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL()\n\nType: `method`\n\nInvia un breve report come testo preformattato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Un indirizzo, indirizzi separati da virgole o un array di indirizzi. Ognuno diventa un destinatario `To:`. |\n| `subject` | `String` | no |  | L'oggetto (predefinito `CONF.name`). |\n| `body` | `String|Object` | yes |  | Il testo o un oggetto da serializzare. |\n| `callback` | `Function` | no |  | `function(err, message)`, la stessa di `message.callback()`. |\n\nReturns: `Message` Il messaggio che verrà inviato.\n\nRacchiude `body` in un blocco `<pre>` e lo invia. Una stringa viene inserita così com'è, quindi può contenere HTML. Un oggetto viene serializzato in JSON e codificato in HTML. Senza `subject` (due argomenti, o una funzione come terzo), l'oggetto è `CONF.name`. I valori predefiniti sono gli stessi di `MAIL()`.\n\nExample: Report\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n### DEF.onMail\n\nType: `delegate`\n\nLa funzione che costruisce e invia i messaggi di MAIL(), HTMLMAIL() e LOGMAIL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Un indirizzo, indirizzi separati da virgole 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. |\n| `reply` | `String` | no |  | Un indirizzo di risposta al posto di `mail_reply`. |\n\nReturns: `Message` Il messaggio.\n\nViene chiamata come `DEF.onMail(email, subject, body, callback, reply)`. Crea il messaggio, aggiunge i destinatari, il mittente (`mail_from` o `CONF.smtp.from`/`user`, `mail_from_name` o `CONF.smtp.name`), l'indirizzo di risposta (`reply` o `mail_reply`), `mail_cc` e `mail_bcc`, imposta la callback e pianifica l'invio. Deve restituire il messaggio. Quando `callback` è una stringa, viene presa come `reply`.\n\nExample: Aggiungere un header a ogni messaggio\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\n### Mail\n\nType: `class`\n\nIl client SMTP globale.\n\nReturns: `Object`\n\n`Mail` è il mailer del framework. Crea messaggi (`Mail.create()`), li invia (`Mail.send()`, `Mail.send2()`), verifica un server (`Mail.try()`) ed emette gli eventi `send` ed `error`. `Mail.Message` (anche `Mail.Mail`) è il costruttore dei messaggi.\n\nExample: Creare e inviare\n```js\nvar msg = Mail.create('Hello', '<p>Hello</p>');\nmsg.from('info@example.com').to('user@example.com').send2();\n```\n\n### Mail.create()\n\nType: `method`\n\nCrea un nuovo messaggio.\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: `Message` Un nuovo messaggio.\n\nRestituisce un nuovo messaggio con l'oggetto e il corpo. A differenza di `MAIL()`, nulla viene impostato o inviato al posto tuo: aggiungi il mittente e i destinatari e chiama `message.send2()` o `message.send()`.\n\nExample: Creare\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.send2();\n```\n\n### Mail.send()\n\nType: `method`\n\nInvia uno o più messaggi con le opzioni SMTP indicate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Le opzioni SMTP. |\n| `messages` | `Message|Array` | yes |  | Un messaggio o un array di messaggi. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nApre una connessione con `options` (le stesse chiavi di `CONF.smtp`), invia i messaggi uno dopo l'altro e chiude la connessione. La callback riceve `err` quando la connessione o l'accesso falliscono. Usa `message.callback()` per il risultato di ogni messaggio.\n\nExample: Due messaggi, una connessione\n```js\nvar a = Mail.create('A', '<p>A</p>').from('info@example.com').to('a@example.com');\nvar b = Mail.create('B', '<p>B</p>').from('info@example.com').to('b@example.com');\nMail.send(CONF.smtp, [a, b]);\n```\n\n### Mail.send2()\n\nType: `method`\n\nInvia messaggi con CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `Message|Array` | yes |  | Un messaggio o un array di messaggi. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nEquivale a `Mail.send(CONF.smtp, messages, callback)`.\n\nExample: Inviare\n```js\nMail.send2([msg1, msg2]);\n```\n\n### Mail.try()\n\nType: `method`\n\nVerifica la connessione e l'accesso a un server SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Le opzioni SMTP. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Senza callback.\n\nSi connette con `options`, esegue l'accesso ed esce senza inviare nulla. Senza callback restituisce una promise.\n\nExample: Verificare le impostazioni\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n### Mail.debug\n\nType: `property`\n\nStampa nella console la conversazione SMTP.\n\nReturns: `Boolean` Default `false`.\n\nCon `true`, ogni riga inviata al server e ricevuta da esso viene stampata. Predefinito `false`.\n\nExample: Debug\n```js\nMail.debug = true;\n```\n\n### Mail.on('send')\n\nType: `event`\n\nEmesso quando una connessione è pronta per l'invio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | L'oggetto di connessione interno. |\n\n`Mail.on('send', function(connection) {})`. Emesso quando il client avvia la conversazione SMTP di una connessione.\n\nExample: Ascoltare\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection ready');\n});\n```\n\n### Mail.on('error')\n\nType: `event`\n\nEmesso in caso di errori SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'errore. |\n| `connection` | `Object` | yes |  | L'oggetto interno della connessione. |\n\n`Mail.on('error', function(err, connection) {})`. Emesso quando la connessione fallisce, l'accesso viene rifiutato o il server risponde con un errore. `err` è un `Error` o la riga di risposta del server.\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### ON('$mail')\n\nType: `event`\n\nEmesso per ogni messaggio in fase di invio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Message` | yes |  | Il messaggio. |\n\n`ON('$mail', function(message) {})`. Emesso subito prima che il messaggio venga scritto sul server SMTP.\n\nExample: Registrare ogni e-mail nel log\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n```\n\n### Mail.Message\n\nType: `class`\n\nL'oggetto messaggio.\n\nReturns: `Object`\n\nUn messaggio viene restituito da `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` e `Mail.create()`; anche `new Mail.Message(subject, body)` ne crea uno (`Mail.Mail` è un alias). I suoi metodi restituiscono il messaggio, quindi le chiamate si possono concatenare. I destinatari si trovano in `email_to`, `email_cc`, `email_bcc` ed `email_reply` (array), il mittente in `email_from` ed `email_from_name`.\n\nExample: Concatenamento\n```js\nMail.create('Hi', '<p>Hi</p>').from('info@example.com').to('a@example.com').cc('b@example.com').send2();\n```\n\n### message.to()\n\nType: `method`\n\nAggiunge un destinatario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Un indirizzo. |\n| `clear` | `Boolean` | no | `false` | Rimuove prima i destinatari attuali. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nAggiunge un indirizzo all'header `To:`. Con `clear`, i destinatari attuali vengono rimossi prima.\n\nExample: Destinatari\n```js\nmsg.to('a@example.com').to('b@example.com');\n```\n\n### message.cc()\n\nType: `method`\n\nAggiunge un destinatario in copia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Un indirizzo. |\n| `clear` | `Boolean` | no | `false` | Rimuove prima le copie attuali. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nAggiunge un indirizzo all'header `Cc:`. Con `clear`, le copie attuali vengono rimosse prima.\n\nExample: Copia\n```js\nmsg.cc('boss@example.com');\n```\n\n### message.bcc()\n\nType: `method`\n\nAggiunge un destinatario in copia nascosta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Un indirizzo. |\n| `clear` | `Boolean` | no | `false` | Rimuove prima le copie nascoste attuali. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nAggiunge un indirizzo che riceve il messaggio senza comparire negli header. Con `clear`, le copie nascoste attuali vengono rimosse prima.\n\nExample: Copia nascosta\n```js\nmsg.bcc('archive@example.com');\n```\n\n### message.reply()\n\nType: `method`\n\nAggiunge un indirizzo di risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Un indirizzo. |\n| `clear` | `Boolean` | no | `false` | Rimuove prima gli indirizzi di risposta attuali. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nAggiunge un indirizzo all'header `Reply-To:`. Con `clear`, gli indirizzi di risposta attuali vengono rimossi prima.\n\nExample: Rispondere al supporto\n```js\nmsg.reply('support@example.com');\n```\n\n### message.from()\n\nType: `method`\n\nImposta il mittente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | L'indirizzo. |\n| `name` | `String` | no |  | Il nome visualizzato. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nImposta l'indirizzo `From:` e, facoltativamente, il nome visualizzato. `message.sender()` è lo stesso metodo.\n\nExample: Mittente\n```js\nmsg.from('info@example.com', 'My application');\n```\n\n### message.sender()\n\nType: `method`\n\nUn alias di message.from().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | L'indirizzo. |\n| `name` | `String` | no |  | Il nome visualizzato. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nEquivale a `message.from(email, [name])`.\n\nExample: Mittente\n```js\nmsg.sender('info@example.com');\n```\n\n### message.attachment()\n\nType: `method`\n\nAllega un file dal disco o un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Buffer` | yes |  | Il percorso del file, oppure un `Buffer` con il contenuto. |\n| `name` | `String` | yes |  | Il nome del file per il destinatario, con la sua estensione. |\n| `contentid` | `String` | no |  | Il content ID per un file inline. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nAggiunge il file `filename`, o il contenuto di un `Buffer`, come allegato. `name` è il nome del file mostrato al destinatario e la sua estensione imposta il content type (`application/octet-stream` per quelle sconosciute). Con `contentid`, il file è una parte inline a cui il corpo HTML fa riferimento come `cid:<contentid>`. Il file viene letto quando il messaggio viene inviato.\n\nExample: Allegare un PDF\n```js\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\n```\n\nExample: Immagine inline\n```js\nvar msg = HTMLMAIL('user@example.com', 'News', '<img src=\"cid:logo\" />');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nExample: Da un Buffer\n```js\nvar pdf = Buffer.from('%PDF-1.4 ...');\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.attachment(pdf, 'invoice.pdf');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nAllega un file da un file storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Il nome del file storage. |\n| `id` | `String` | yes |  | L'id del file nello storage. |\n| `name` | `String` | no |  | Il nome del file per il destinatario, con la sua estensione. Predefinito: il nome salvato con il file. |\n| `contentid` | `String` | no |  | Il content ID per un file inline. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nAggiunge come allegato un file di un [file storage](../file-storage/): `storage` è il nome dello storage (come in `FILESTORAGE(name)`) e `id` l'id del file. Senza `name`, il destinatario vede il nome del file nello storage e il content type è il tipo salvato con il file; con `name`, la sua estensione imposta il content type. Con `contentid`, il file è una parte inline a cui il corpo HTML fa riferimento come `cid:<contentid>`.\n\nIl file viene letto quando il messaggio viene inviato. Quando non esiste, l'errore viene scritto nel log degli errori e il messaggio viene inviato senza l'allegato.\n\nExample: Allegare un file salvato\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Contract', '<p>The contract is attached.</p>');\nmsg.attachmentfs('documents', id);\n```\n\nExample: Un altro nome\n```js\nmsg.attachmentfs('documents', id, 'contract-2025.pdf');\n```\n\n### message.unsubscribe()\n\nType: `method`\n\nAggiunge gli header List-Unsubscribe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL o l'indirizzo e-mail per annullare l'iscrizione. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nAggiunge `List-Unsubscribe` e `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. Un valore che inizia con `http:` o `https:` viene usato come URL; qualsiasi altro valore è un indirizzo e-mail (`mailto:`).\n\nExample: Newsletter\n```js\nmsg.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback()\n\nType: `method`\n\nImposta la funzione chiamata con il risultato del messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\n`fn(err, message)` viene chiamata con un `err` vuoto quando il messaggio è stato consegnato al server, oppure con un errore: la riga di risposta del server (in maiuscolo) quando rifiuta il messaggio o il login, `No SMTP server configuration.`, oppure un errore di connessione o un timeout. Un errore che arriva a una callback non viene scritto nel log degli errori. `MAIL()`, `HTMLMAIL()` e `LOGMAIL()` la impostano dal loro argomento `callback`.\n\nExample: Risultato\n```js\nmsg.callback(function(err, message) {\n\tif (err)\n\t\tconsole.log('Not sent:', message.subject, err);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nBlocca l'invio automatico.\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\n`MAIL()`, `HTMLMAIL()` e `LOGMAIL()` inviano il messaggio al giro successivo dell'event loop. Chiama `manually()` subito dopo di esse per annullarlo e invia il messaggio più tardi con `message.send2()` o `message.send()`.\n\nExample: Inviare più tardi\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n// ...\nmsg.send2();\n```\n\n### message.send2()\n\nType: `method`\n\nInvia il messaggio con CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nInvia il messaggio con il server SMTP configurato (`CONF.smtp`).\n\nExample: Inviare\n```js\nMail.create('Hello', '<p>Hello</p>').from('info@example.com').to('user@example.com').send2(function(err) {\n\terr && console.log(err);\n});\n```\n\n### message.send(options)\n\nType: `method`\n\nInvia il messaggio con altre opzioni SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Le opzioni SMTP. |\n\nReturns: `Message` Il messaggio, per il concatenamento.\n\nInvia il messaggio su una nuova connessione con `options` (le stesse chiavi di `CONF.smtp`). Usa `message.callback()` per il risultato.\n\nExample: Un altro server\n```js\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send({ server: 'smtp.other.com', port: 587, user: 'me@other.com', password: 'secret' });\n```\n\n### message.subject\n\nType: `property`\n\nL'oggetto.\n\nReturns: `String`\n\nL'oggetto del messaggio. I caratteri non ASCII vengono codificati automaticamente.\n\nExample: Modificare\n```js\nmsg.subject = 'Updated subject';\n```\n\n### message.body\n\nType: `property`\n\nIl corpo.\n\nReturns: `String`\n\nIl corpo del messaggio: HTML, oppure testo semplice quando `type` è `plain`.\n\nExample: Modificare\n```js\nmsg.body = '<p>New text</p>';\n```\n\n### message.type\n\nType: `property`\n\nIl tipo del corpo.\n\nReturns: `String` Predefinito `html`.\n\n`html` (predefinito) o `plain`. Diventa il `Content-Type` del corpo (`text/html` o `text/plain`).\n\nExample: Testo semplice\n```js\nvar msg = Mail.create('Hello', 'Hello in plain text');\nmsg.type = 'plain';\n```\n\n### message.headers\n\nType: `property`\n\nHeader aggiuntivi del messaggio.\n\nReturns: `Object`\n\nUn oggetto di nomi e valori di header scritti nel messaggio così come sono. Non è impostato per impostazione predefinita.\n\nExample: Header personalizzato\n```js\nmsg.headers = { 'X-Campaign': 'spring-2025' };\n```\n\n### message.high()\n\nType: `method`\n\nContrassegna il messaggio come ad alta priorità.\n\nReturns: `Message` Lo stesso messaggio.\n\nAggiunge l'header `X-Priority: 1`. Restituisce il messaggio.\n\nExample: Urgente\n```js\nHTMLMAIL('admin@example.com', 'Disk full', '<p>The disk is full.</p>').high();\n```\n\n### message.low()\n\nType: `method`\n\nContrassegna il messaggio come a bassa priorità.\n\nReturns: `Message` Lo stesso messaggio.\n\nAggiunge l'header `X-Priority: 5`. Restituisce il messaggio.\n\nExample: Riepilogo settimanale\n```js\nMAIL(user.email, 'Your week', 'mail/digest', model).low();\n```\n\n### message.confidential()\n\nType: `method`\n\nContrassegna il messaggio come riservato.\n\nReturns: `Message` Lo stesso messaggio.\n\nAggiunge l'header `Sensitivity: Company-Confidential`. Restituisce il messaggio.\n\nExample: Report riservato\n```js\nHTMLMAIL('board@example.com', 'Salaries', html).confidential().high();\n```\n\n### CONF.smtp\n\nType: `config`\n\nIl server SMTP e le sue opzioni.\n\nReturns: `Object`\n\nUn oggetto con `server` (o `host`, `hostname`, `smtp`, `url`), `port`, `secure`, `user`, `password`, `token`, `tls`, `timeout`, `from` e `name`. Con `secure: true` la connessione usa TLS fin dall'inizio e `port` vale `465` per impostazione predefinita; altrimenti imposta `port`. La chiave `mail` nel file di configurazione è la stessa.\n\nPrima della connessione, `server` viene convertito con `U.tohost()`: un nome internazionale viene inviato come punycode e un indirizzo IPv4 nella sua forma puntata (`127.1` diventa `127.0.0.1`). Un valore che non è un nome host valido dà l'errore `Invalid SMTP server hostname.` e non viene inviato nulla.\n\nExample: /config\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nExample: STARTTLS sulla porta 587\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_smtp\n\nType: `config`\n\nIl nome del server SMTP.\n\nReturns: `String`\n\nImposta `CONF.smtp.server`. Usala con `mail_smtp_options` invece di un unico oggetto `smtp`.\n\nExample: /config\n```text\nmail_smtp : smtp.example.com\n```\n\n### CONF.mail_smtp_options\n\nType: `config`\n\nLe opzioni SMTP senza il server.\n\nReturns: `Object`\n\nUn oggetto le cui chiavi vengono copiate in `CONF.smtp` (`port`, `secure`, `user`, `password`...).\n\nExample: /config\n```text\nmail_smtp_options : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_from\n\nType: `config`\n\nL'indirizzo predefinito del mittente.\n\nReturns: `String`\n\nL'indirizzo `From:` di `MAIL()`, `HTMLMAIL()` e `LOGMAIL()`. Senza di esso viene usato `CONF.smtp.from` o `CONF.smtp.user`.\n\nExample: /config\n```text\nmail_from : info@example.com\n```\n\n### CONF.mail_from_name\n\nType: `config`\n\nIl nome predefinito del mittente.\n\nReturns: `String`\n\nIl nome visualizzato del mittente di `MAIL()`, `HTMLMAIL()` e `LOGMAIL()`. Senza di esso viene usato `CONF.smtp.name`.\n\nExample: /config\n```text\nmail_from_name : My application\n```\n\n### CONF.mail_reply\n\nType: `config`\n\nL'indirizzo di risposta predefinito.\n\nReturns: `String`\n\nUn indirizzo aggiunto come `Reply-To:` ai messaggi di `MAIL()`, `HTMLMAIL()` e `LOGMAIL()`.\n\nExample: /config\n```text\nmail_reply : support@example.com\n```\n\n### CONF.mail_cc\n\nType: `config`\n\nUn destinatario in copia predefinito.\n\nReturns: `String`\n\nUn indirizzo aggiunto come `Cc:` ai messaggi di `MAIL()`, `HTMLMAIL()` e `LOGMAIL()`.\n\nExample: /config\n```text\nmail_cc : office@example.com\n```\n\n### CONF.mail_bcc\n\nType: `config`\n\nUn destinatario in copia nascosta predefinito.\n\nReturns: `String`\n\nUn indirizzo aggiunto come copia nascosta ai messaggi di `MAIL()`, `HTMLMAIL()` e `LOGMAIL()`.\n\nExample: /config\n```text\nmail_bcc : archive@example.com\n```\n\n### $tapimail : true\n\nType: `config`\n\nInvia i messaggi tramite la Total.js API invece che via SMTP.\n\nReturns: `Boolean`\n\nPredefinito `false`. Con `true`, `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` e `message.send2()` inviano il messaggio con `API('TAPI', 'mail', data)` e il token `secret_totalapi`; `$tapi` deve essere `true` (il valore predefinito). Il servizio riceve i destinatari (`to`, `cc`, `bcc`, `reply`), `from`, `subject`, `type`, `body`, `priority`, `unsubscribe` e `confidential`. Gli allegati e `message.headers` non vengono inviati. La callback del messaggio riceve la risposta del servizio.\n\nExample: /config\n```text\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL()","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL()","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL()","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create()","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send()","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2()","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try()","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send')","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error')","since":"","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail')","since":"","deprecated":false},{"type":"class","name":"Mail.Message","signature":"Mail.Message","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to()","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc()","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc()","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply()","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from()","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender()","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment()","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()","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback()","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2()","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(options)","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":"property","name":"message.headers","signature":"message.headers","since":"","deprecated":false},{"type":"method","name":"message.high()","signature":"message.high()","since":"","deprecated":false},{"type":"method","name":"message.low()","signature":"message.low()","since":"","deprecated":false},{"type":"method","name":"message.confidential()","signature":"message.confidential()","since":"","deprecated":false},{"type":"config","name":"CONF.smtp","signature":"CONF.smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp","signature":"CONF.mail_smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp_options","signature":"CONF.mail_smtp_options","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from","signature":"CONF.mail_from","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from_name","signature":"CONF.mail_from_name","since":"","deprecated":false},{"type":"config","name":"CONF.mail_reply","signature":"CONF.mail_reply","since":"","deprecated":false},{"type":"config","name":"CONF.mail_cc","signature":"CONF.mail_cc","since":"","deprecated":false},{"type":"config","name":"CONF.mail_bcc","signature":"CONF.mail_bcc","since":"","deprecated":false},{"type":"config","name":"CONF.$tapimail","signature":"$tapimail : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwu84qx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/mail/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Odosielanie e-mailov","summary":"MAIL(), HTMLMAIL(), LOGMAIL(), modul Mail, objekt správy a SMTP kľúče.","markdown":"---\ntitle: Odosielanie e-mailov\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/mail/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Odosielanie e-mailov\n\n> MAIL(), HTMLMAIL(), LOGMAIL(), modul Mail, objekt správy a SMTP kľúče.\n\nTáto stránka uvádza globálne mailové funkcie, modul `Mail` s jeho udalosťami, metódy a vlastnosti objektu správy a konfiguračné kľúče pre SMTP a predvoleného odosielateľa. Návod [Posielanie e-mailov](../../guides/mail/) s príkladmi vysvetľuje, ako spolu fungujú.\n\n## API\n\n### MAIL()\n\nType: `method`\n\nVyrenderuje view a pošle ho ako e-mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Jedna adresa, adresy oddelené čiarkou alebo pole adries. Každá sa stane príjemcom `To:`. |\n| `subject` | `String` | yes |  | Predmet. |\n| `view` | `String` | yes |  | Názov view, napr. `mail/welcome`. |\n| `model` | `Object` | no |  | Model view. |\n| `language` | `String` | no |  | Jazyk pre view a predmet. |\n| `callback` | `Function` | no |  | `function(err, message)`, rovnaké ako `message.callback()`. |\n\nReturns: `Message` Správa, ktorá sa odošle.\n\nVyrenderuje view `view` (cesta v `/views/` bez `.html`) s `model` a pošle HTML na `email`. Odosielateľ, adresa na odpoveď a kópie sa berú z `mail_from`, `mail_from_name`, `mail_reply`, `mail_cc` a `mail_bcc` (alebo z `from`/`name` v `CONF.smtp`). S `language` sa view vyrenderuje v danom jazyku a predmet s `@(...)` sa preloží. Správa sa odošle v nasledujúcom kole event loopu, takže vrátenú správu môžeš ešte zmeniť. Keď je `language` funkcia, použije sa ako callback.\n\nExample: Uvítací e-mail\n```js\nMAIL(user.email, '@(Welcome)', 'mail/welcome', user, user.language, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n### HTMLMAIL()\n\nType: `method`\n\nPošle e-mail s HTML telom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Jedna adresa, adresy oddelené čiarkou alebo pole adries. Každá sa stane príjemcom `To:`. |\n| `subject` | `String` | yes |  | Predmet. |\n| `body` | `String` | yes |  | HTML. |\n| `language` | `String` | no |  | Jazyk na preklad predmetu a tela. |\n| `callback` | `Function` | no |  | `function(err, message)`, rovnaké ako `message.callback()`. |\n\nReturns: `Message` Správa, ktorá sa odošle.\n\nPošle `body` ako HTML. Telo bez značky `<body>` sa zabalí do jednoduchého HTML dokumentu s predmetom ako titulkom. S `language` sa preložia texty `@(...)` v predmete aj v tele. Predvolené hodnoty sú rovnaké ako pri `MAIL()`. Keď je `language` funkcia, použije sa ako callback.\n\nExample: Poslanie HTML\n```js\nHTMLMAIL('user@example.com', 'Password reset', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL()\n\nType: `method`\n\nPošle krátky report ako predformátovaný text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Jedna adresa, adresy oddelené čiarkou alebo pole adries. Každá sa stane príjemcom `To:`. |\n| `subject` | `String` | no |  | Predmet (predvolene `CONF.name`). |\n| `body` | `String|Object` | yes |  | Text alebo objekt na serializáciu. |\n| `callback` | `Function` | no |  | `function(err, message)`, rovnaké ako `message.callback()`. |\n\nReturns: `Message` Správa, ktorá sa odošle.\n\nZabalí `body` do bloku `<pre>` a pošle ho. Reťazec sa vloží tak, ako je, takže môže obsahovať HTML. Objekt sa serializuje do JSON a HTML-enkóduje. Bez `subject` (dva argumenty alebo funkcia ako tretí) je predmetom `CONF.name`. Predvolené hodnoty sú rovnaké ako pri `MAIL()`.\n\nExample: Report\n```js\nLOGMAIL('admin@example.com', 'Nightly import', { imported: 120, failed: 2 });\nLOGMAIL('admin@example.com', 'The backup has finished.');\n```\n\n### DEF.onMail\n\nType: `delegate`\n\nFunkcia, ktorá zostavuje a posiela správy funkcií MAIL(), HTMLMAIL() a LOGMAIL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String|Array` | yes |  | Jedna adresa, adresy oddelené čiarkou 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. |\n| `reply` | `String` | no |  | Adresa na odpoveď namiesto `mail_reply`. |\n\nReturns: `Message` Správa.\n\nVolá sa ako `DEF.onMail(email, subject, body, callback, reply)`. Vytvorí správu, pridá príjemcov, odosielateľa (`mail_from` alebo `CONF.smtp.from`/`user`, `mail_from_name` alebo `CONF.smtp.name`), adresu na odpoveď (`reply` alebo `mail_reply`), `mail_cc` a `mail_bcc`, nastaví callback a naplánuje odoslanie. Musí vrátiť správu. Keď je `callback` reťazec, berie sa ako `reply`.\n\nExample: Pridanie hlavičky do každej správy\n```js\nvar onmail = DEF.onMail;\nDEF.onMail = function(email, subject, body, callback, reply) {\n\tvar msg = onmail(email, subject, body, callback, reply);\n\tmsg.headers = { 'X-Application': CONF.name };\n\treturn msg;\n};\n```\n\n### Mail\n\nType: `class`\n\nGlobálny SMTP klient.\n\nReturns: `Object`\n\n`Mail` je mailer frameworku. Vytvára správy (`Mail.create()`), posiela ich (`Mail.send()`, `Mail.send2()`), testuje server (`Mail.try()`) a emituje udalosti `send` a `error`. `Mail.Message` (aj `Mail.Mail`) je konštruktor správ.\n\nExample: Vytvorenie a odoslanie\n```js\nvar msg = Mail.create('Hello', '<p>Hello</p>');\nmsg.from('info@example.com').to('user@example.com').send2();\n```\n\n### Mail.create()\n\nType: `method`\n\nVytvorí novú správu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `subject` | `String` | yes |  | Predmet. |\n| `body` | `String` | yes |  | Telo (predvolene HTML). |\n\nReturns: `Message` Nová správa.\n\nVráti novú správu s predmetom a telom. Na rozdiel od `MAIL()` sa za teba nič nenastaví ani neodošle: pridaj odosielateľa a príjemcov a zavolaj `message.send2()` alebo `message.send()`.\n\nExample: Vytvorenie\n```js\nvar msg = Mail.create('Hello', '<p>Hello from Total.js</p>');\nmsg.from('info@example.com', 'My application');\nmsg.to('user@example.com');\nmsg.send2();\n```\n\n### Mail.send()\n\nType: `method`\n\nPošle jednu alebo viac správ s danými SMTP voľbami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | SMTP voľby. |\n| `messages` | `Message|Array` | yes |  | Správa alebo pole správ. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nOtvorí spojenie s `options` (rovnaké kľúče ako `CONF.smtp`), pošle správy jednu po druhej a spojenie zatvorí. Callback dostane `err`, keď zlyhá spojenie alebo prihlásenie. Na výsledok každej správy použi `message.callback()`.\n\nExample: Dve správy, jedno spojenie\n```js\nvar a = Mail.create('A', '<p>A</p>').from('info@example.com').to('a@example.com');\nvar b = Mail.create('B', '<p>B</p>').from('info@example.com').to('b@example.com');\nMail.send(CONF.smtp, [a, b]);\n```\n\n### Mail.send2()\n\nType: `method`\n\nPošle správy s CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `Message|Array` | yes |  | Správa alebo pole správ. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nRovnaké ako `Mail.send(CONF.smtp, messages, callback)`.\n\nExample: Odoslanie\n```js\nMail.send2([msg1, msg2]);\n```\n\n### Mail.try()\n\nType: `method`\n\nOtestuje spojenie a prihlásenie k SMTP serveru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | SMTP voľby. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Bez callbacku.\n\nPripojí sa s `options`, prihlási sa a skončí bez odoslania čohokoľvek. Bez callbacku vráti promise.\n\nExample: Kontrola nastavení\n```js\nMail.try(CONF.smtp).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP error:', err);\n});\n```\n\n### Mail.debug\n\nType: `property`\n\nVypíše SMTP komunikáciu do konzoly.\n\nReturns: `Boolean` Predvolene `false`.\n\nS `true` sa vypíše každý riadok odoslaný na server a prijatý zo servera. Predvolene `false`.\n\nExample: Debug\n```js\nMail.debug = true;\n```\n\n### Mail.on('send')\n\nType: `event`\n\nEmituje sa, keď je spojenie pripravené na odosielanie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | Interný objekt spojenia. |\n\n`Mail.on('send', function(connection) {})`. Emituje sa, keď klient začne SMTP komunikáciu spojenia.\n\nExample: Počúvanie\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection ready');\n});\n```\n\n### Mail.on('error')\n\nType: `event`\n\nEmituje sa pri chybách SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Chyba. |\n| `connection` | `Object` | yes |  | Interný objekt spojenia. |\n\n`Mail.on('error', function(err, connection) {})`. Emituje sa, keď zlyhá spojenie, prihlásenie je odmietnuté alebo server odpovie chybou. `err` je `Error` alebo riadok odpovede servera.\n\nExample: Logovanie SMTP chýb\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### ON('$mail')\n\nType: `event`\n\nEmituje sa pre každú odosielanú správu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Message` | yes |  | Správa. |\n\n`ON('$mail', function(message) {})`. Emituje sa tesne pred zapísaním správy na SMTP server.\n\nExample: Logovanie každého e-mailu\n```js\nON('$mail', function(message) {\n\tconsole.log('Sending', message.subject, 'to', message.email_to);\n});\n```\n\n### Mail.Message\n\nType: `class`\n\nObjekt správy.\n\nReturns: `Object`\n\nSprávu vracajú `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` a `Mail.create()`; vytvorí ju aj `new Mail.Message(subject, body)` (`Mail.Mail` je alias). Jej metódy vracajú správu, takže volania sa dajú reťaziť. Príjemcovia sú v `email_to`, `email_cc`, `email_bcc` a `email_reply` (polia), odosielateľ v `email_from` a `email_from_name`.\n\nExample: Reťazenie\n```js\nMail.create('Hi', '<p>Hi</p>').from('info@example.com').to('a@example.com').cc('b@example.com').send2();\n```\n\n### message.to()\n\nType: `method`\n\nPridá príjemcu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Jedna adresa. |\n| `clear` | `Boolean` | no | `false` | Najprv odstrániť aktuálnych príjemcov. |\n\nReturns: `Message` Správa na reťazenie.\n\nPridá jednu adresu do hlavičky `To:`. S `clear` sa najprv odstránia aktuálni príjemcovia.\n\nExample: Príjemcovia\n```js\nmsg.to('a@example.com').to('b@example.com');\n```\n\n### message.cc()\n\nType: `method`\n\nPridá príjemcu kópie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Jedna adresa. |\n| `clear` | `Boolean` | no | `false` | Najprv odstrániť aktuálne kópie. |\n\nReturns: `Message` Správa na reťazenie.\n\nPridá jednu adresu do hlavičky `Cc:`. S `clear` sa najprv odstránia aktuálne kópie.\n\nExample: Kópia\n```js\nmsg.cc('boss@example.com');\n```\n\n### message.bcc()\n\nType: `method`\n\nPridá príjemcu skrytej kópie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Jedna adresa. |\n| `clear` | `Boolean` | no | `false` | Najprv odstrániť aktuálne skryté kópie. |\n\nReturns: `Message` Správa na reťazenie.\n\nPridá jednu adresu, ktorá dostane správu bez toho, aby bola uvedená v hlavičkách. S `clear` sa najprv odstránia aktuálne skryté kópie.\n\nExample: Skrytá kópia\n```js\nmsg.bcc('archive@example.com');\n```\n\n### message.reply()\n\nType: `method`\n\nPridá adresu na odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Jedna adresa. |\n| `clear` | `Boolean` | no | `false` | Najprv odstrániť aktuálne adresy na odpoveď. |\n\nReturns: `Message` Správa na reťazenie.\n\nPridá jednu adresu do hlavičky `Reply-To:`. S `clear` sa najprv odstránia aktuálne adresy na odpoveď.\n\nExample: Odpoveď na podporu\n```js\nmsg.reply('support@example.com');\n```\n\n### message.from()\n\nType: `method`\n\nNastaví odosielateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Adresa. |\n| `name` | `String` | no |  | Zobrazované meno. |\n\nReturns: `Message` Správa na reťazenie.\n\nNastaví adresu `From:` a voliteľne zobrazované meno. `message.sender()` je tá istá metóda.\n\nExample: Odosielateľ\n```js\nmsg.from('info@example.com', 'My application');\n```\n\n### message.sender()\n\nType: `method`\n\nAlias metódy message.from().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `email` | `String` | yes |  | Adresa. |\n| `name` | `String` | no |  | Zobrazované meno. |\n\nReturns: `Message` Správa na reťazenie.\n\nRovnaké ako `message.from(email, [name])`.\n\nExample: Odosielateľ\n```js\nmsg.sender('info@example.com');\n```\n\n### message.attachment()\n\nType: `method`\n\nPripojí súbor z disku alebo Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Buffer` | yes |  | Cesta k súboru alebo `Buffer` s obsahom. |\n| `name` | `String` | yes |  | Názov súboru pre príjemcu, s príponou. |\n| `contentid` | `String` | no |  | Content ID pre vložený súbor. |\n\nReturns: `Message` Správa na reťazenie.\n\nPridá súbor `filename` alebo obsah `Buffer` ako prílohu. `name` je názov súboru zobrazený príjemcovi a jeho prípona určuje typ obsahu (pri neznámych `application/octet-stream`). S `contentid` je súbor vloženou (inline) časťou, na ktorú sa HTML telo odkazuje ako `cid:<contentid>`. Súbor sa načíta pri odosielaní správy.\n\nExample: Pripojenie PDF\n```js\nmsg.attachment(PATH.databases('invoices/2025-001.pdf'), 'invoice.pdf');\n```\n\nExample: Vložený obrázok\n```js\nvar msg = HTMLMAIL('user@example.com', 'News', '<img src=\"cid:logo\" />');\nmsg.attachment(PATH.public('img/logo.png'), 'logo.png', 'logo');\n```\n\nExample: Z Buffera\n```js\nvar pdf = Buffer.from('%PDF-1.4 ...');\nvar msg = HTMLMAIL('user@example.com', 'Invoice', '<p>Your invoice is attached.</p>');\nmsg.attachment(pdf, 'invoice.pdf');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nPripojí súbor z úložiska súborov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Názov úložiska súborov. |\n| `id` | `String` | yes |  | Id súboru v úložisku. |\n| `name` | `String` | no |  | Názov súboru pre príjemcu, s príponou. Predvolene: názov uložený so súborom. |\n| `contentid` | `String` | no |  | Content ID pre vložený súbor. |\n\nReturns: `Message` Správa na reťazenie.\n\nPridá súbor z [úložiska súborov](../file-storage/) ako prílohu: `storage` je názov úložiska (ako v `FILESTORAGE(name)`) a `id` je id súboru. Bez `name` príjemca vidí názov súboru v úložisku a typ obsahu je typ uložený so súborom; s `name` určuje typ obsahu jeho prípona. S `contentid` je súbor vloženou (inline) časťou, na ktorú sa HTML telo odkazuje ako `cid:<contentid>`.\n\nSúbor sa načíta pri odosielaní správy. Keď neexistuje, chyba sa zapíše do chybového logu a správa sa odošle bez prílohy.\n\nExample: Pripojenie uloženého súboru\n```js\nvar id = UID();\nawait FILESTORAGE('documents').save(id, 'contract.pdf', Buffer.from('%PDF-1.4 ...'));\n\nvar msg = HTMLMAIL('user@example.com', 'Contract', '<p>The contract is attached.</p>');\nmsg.attachmentfs('documents', id);\n```\n\nExample: Iný názov\n```js\nmsg.attachmentfs('documents', id, 'contract-2025.pdf');\n```\n\n### message.unsubscribe()\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. |\n\nReturns: `Message` Správa na reťazenie.\n\nPridá `List-Unsubscribe` a `List-Unsubscribe-Post: List-Unsubscribe=One-Click`. Hodnota, ktorá začína na `http:` alebo `https:`, sa použije ako URL; akákoľvek iná hodnota je e-mailová adresa (`mailto:`).\n\nExample: Newsletter\n```js\nmsg.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback()\n\nType: `method`\n\nNastaví funkciu volanú s výsledkom správy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `Message` Správa na reťazenie.\n\n`fn(err, message)` sa zavolá s prázdnym `err`, keď bola správa odovzdaná serveru, alebo s chybou: s riadkom odpovede servera (veľkými písmenami), keď odmietne správu alebo prihlásenie, s `No SMTP server configuration.` alebo s chybou spojenia či vypršaním časového limitu. Chyba, ktorá sa dostane do callbacku, sa nezapíše do chybového logu. `MAIL()`, `HTMLMAIL()` a `LOGMAIL()` ho nastavujú zo svojho argumentu `callback`.\n\nExample: Výsledok\n```js\nmsg.callback(function(err, message) {\n\tif (err)\n\t\tconsole.log('Not sent:', message.subject, err);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nZastaví automatické odoslanie.\n\nReturns: `Message` Správa na reťazenie.\n\n`MAIL()`, `HTMLMAIL()` a `LOGMAIL()` pošlú správu v nasledujúcom kole event loopu. Ak to chceš zrušiť, zavolaj `manually()` hneď po nich a správu pošli neskôr cez `message.send2()` alebo `message.send()`.\n\nExample: Odoslanie neskôr\n```js\nvar msg = MAIL('user@example.com', 'Report', 'mail/report', data);\nmsg.manually();\n// ...\nmsg.send2();\n```\n\n### message.send2()\n\nType: `method`\n\nPošle správu s CONF.smtp.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nOdošle správu cez nakonfigurovaný SMTP server (`CONF.smtp`).\n\nExample: Odoslanie\n```js\nMail.create('Hello', '<p>Hello</p>').from('info@example.com').to('user@example.com').send2(function(err) {\n\terr && console.log(err);\n});\n```\n\n### message.send(options)\n\nType: `method`\n\nPošle správu s inými SMTP voľbami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | SMTP voľby. |\n\nReturns: `Message` Správa na reťazenie.\n\nPošle správu cez nové spojenie s `options` (rovnaké kľúče ako `CONF.smtp`). Na výsledok použi `message.callback()`.\n\nExample: Iný server\n```js\nmsg.callback(function(err) {\n\terr && console.log(err);\n});\nmsg.send({ server: 'smtp.other.com', port: 587, user: 'me@other.com', password: 'secret' });\n```\n\n### message.subject\n\nType: `property`\n\nPredmet.\n\nReturns: `String`\n\nPredmet správy. Znaky mimo ASCII sa zakódujú automaticky.\n\nExample: Zmena\n```js\nmsg.subject = 'Updated subject';\n```\n\n### message.body\n\nType: `property`\n\nTelo.\n\nReturns: `String`\n\nTelo správy: HTML, alebo čistý text, keď je `type` nastavený na `plain`.\n\nExample: Zmena\n```js\nmsg.body = '<p>New text</p>';\n```\n\n### message.type\n\nType: `property`\n\nTyp tela.\n\nReturns: `String` Predvolene `html`.\n\n`html` (predvolene) alebo `plain`. Stane sa z neho `Content-Type` tela (`text/html` alebo `text/plain`).\n\nExample: Čistý text\n```js\nvar msg = Mail.create('Hello', 'Hello in plain text');\nmsg.type = 'plain';\n```\n\n### message.headers\n\nType: `property`\n\nĎalšie hlavičky správy.\n\nReturns: `Object`\n\nObjekt s názvami a hodnotami hlavičiek, ktoré sa zapíšu do správy tak, ako sú. Predvolene nie je nastavený.\n\nExample: Vlastná hlavička\n```js\nmsg.headers = { 'X-Campaign': 'spring-2025' };\n```\n\n### message.high()\n\nType: `method`\n\nOznačí správu ako správu s vysokou prioritou.\n\nReturns: `Message` Tá istá správa.\n\nPridá hlavičku `X-Priority: 1`. Vráti správu.\n\nExample: Urgentné\n```js\nHTMLMAIL('admin@example.com', 'Disk full', '<p>The disk is full.</p>').high();\n```\n\n### message.low()\n\nType: `method`\n\nOznačí správu ako správu s nízkou prioritou.\n\nReturns: `Message` Tá istá správa.\n\nPridá hlavičku `X-Priority: 5`. Vráti správu.\n\nExample: Týždenný prehľad\n```js\nMAIL(user.email, 'Your week', 'mail/digest', model).low();\n```\n\n### message.confidential()\n\nType: `method`\n\nOznačí správu ako dôvernú.\n\nReturns: `Message` Tá istá správa.\n\nPridá hlavičku `Sensitivity: Company-Confidential`. Vráti správu.\n\nExample: Dôverná správa\n```js\nHTMLMAIL('board@example.com', 'Salaries', html).confidential().high();\n```\n\n### CONF.smtp\n\nType: `config`\n\nSMTP server a jeho voľby.\n\nReturns: `Object`\n\nObjekt so `server` (alebo `host`, `hostname`, `smtp`, `url`), `port`, `secure`, `user`, `password`, `token`, `tls`, `timeout`, `from` a `name`. S `secure: true` spojenie používa TLS hneď od začiatku a `port` je predvolene `465`; inak `port` nastav. Kľúč `mail` v konfiguračnom súbore je to isté.\n\nPred pripojením sa `server` skonvertuje cez `U.tohost()`: medzinárodný názov sa pošle ako punycode a IPv4 adresa v tvare s bodkami (`127.1` sa zmení na `127.0.0.1`). Hodnota, ktorá nie je platný hostname, vráti chybu `Invalid SMTP server hostname.` a nič sa neodošle.\n\nExample: /config\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":465,\"secure\":true,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\nExample: STARTTLS na porte 587\n```text\nsmtp (json) : {\"server\":\"smtp.example.com\",\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_smtp\n\nType: `config`\n\nNázov SMTP servera.\n\nReturns: `String`\n\nNastaví `CONF.smtp.server`. Používa sa s `mail_smtp_options` namiesto jedného objektu `smtp`.\n\nExample: /config\n```text\nmail_smtp : smtp.example.com\n```\n\n### CONF.mail_smtp_options\n\nType: `config`\n\nSMTP voľby bez servera.\n\nReturns: `Object`\n\nObjekt, ktorého kľúče sa skopírujú do `CONF.smtp` (`port`, `secure`, `user`, `password`...).\n\nExample: /config\n```text\nmail_smtp_options : {\"port\":587,\"user\":\"info@example.com\",\"password\":\"secret\"}\n```\n\n### CONF.mail_from\n\nType: `config`\n\nPredvolená adresa odosielateľa.\n\nReturns: `String`\n\nAdresa `From:` pre `MAIL()`, `HTMLMAIL()` a `LOGMAIL()`. Bez nej sa použije `CONF.smtp.from` alebo `CONF.smtp.user`.\n\nExample: /config\n```text\nmail_from : info@example.com\n```\n\n### CONF.mail_from_name\n\nType: `config`\n\nPredvolené meno odosielateľa.\n\nReturns: `String`\n\nZobrazované meno odosielateľa pre `MAIL()`, `HTMLMAIL()` a `LOGMAIL()`. Bez neho sa použije `CONF.smtp.name`.\n\nExample: /config\n```text\nmail_from_name : My application\n```\n\n### CONF.mail_reply\n\nType: `config`\n\nPredvolená adresa na odpoveď.\n\nReturns: `String`\n\nJedna adresa pridaná ako `Reply-To:` do správ funkcií `MAIL()`, `HTMLMAIL()` a `LOGMAIL()`.\n\nExample: /config\n```text\nmail_reply : support@example.com\n```\n\n### CONF.mail_cc\n\nType: `config`\n\nPredvolený príjemca kópie.\n\nReturns: `String`\n\nJedna adresa pridaná ako `Cc:` do správ funkcií `MAIL()`, `HTMLMAIL()` a `LOGMAIL()`.\n\nExample: /config\n```text\nmail_cc : office@example.com\n```\n\n### CONF.mail_bcc\n\nType: `config`\n\nPredvolený príjemca skrytej kópie.\n\nReturns: `String`\n\nJedna adresa pridaná ako skrytá kópia do správ funkcií `MAIL()`, `HTMLMAIL()` a `LOGMAIL()`.\n\nExample: /config\n```text\nmail_bcc : archive@example.com\n```\n\n### $tapimail : true\n\nType: `config`\n\nPosiela správy cez Total.js API namiesto SMTP.\n\nReturns: `Boolean`\n\nPredvolene `false`. S `true` pošlú `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` a `message.send2()` správu cez `API('TAPI', 'mail', data)` s tokenom `secret_totalapi`; `$tapi` musí byť `true` (predvolená hodnota). Služba dostane príjemcov (`to`, `cc`, `bcc`, `reply`), `from`, `subject`, `type`, `body`, `priority`, `unsubscribe` a `confidential`. Prílohy a `message.headers` sa neposielajú. Callback správy dostane odpoveď služby.\n\nExample: /config\n```text\n$tapimail       : true\nsecret_totalapi : your-totalapi-token\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL()","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL()","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL()","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create()","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send()","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2()","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try()","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send')","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error')","since":"","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail')","since":"","deprecated":false},{"type":"class","name":"Mail.Message","signature":"Mail.Message","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to()","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc()","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc()","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply()","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from()","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender()","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment()","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()","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback()","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2()","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(options)","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":"property","name":"message.headers","signature":"message.headers","since":"","deprecated":false},{"type":"method","name":"message.high()","signature":"message.high()","since":"","deprecated":false},{"type":"method","name":"message.low()","signature":"message.low()","since":"","deprecated":false},{"type":"method","name":"message.confidential()","signature":"message.confidential()","since":"","deprecated":false},{"type":"config","name":"CONF.smtp","signature":"CONF.smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp","signature":"CONF.mail_smtp","since":"","deprecated":false},{"type":"config","name":"CONF.mail_smtp_options","signature":"CONF.mail_smtp_options","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from","signature":"CONF.mail_from","since":"","deprecated":false},{"type":"config","name":"CONF.mail_from_name","signature":"CONF.mail_from_name","since":"","deprecated":false},{"type":"config","name":"CONF.mail_reply","signature":"CONF.mail_reply","since":"","deprecated":false},{"type":"config","name":"CONF.mail_cc","signature":"CONF.mail_cc","since":"","deprecated":false},{"type":"config","name":"CONF.mail_bcc","signature":"CONF.mail_bcc","since":"","deprecated":false},{"type":"config","name":"CONF.$tapimail","signature":"$tapimail : true","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvoAcx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Scheduling and events","summary":"CRON(), ON(), ONCE(), OFF(), EMIT(), the built-in events, setTimeout2(), CLEANUP() and PAUSESERVER().","markdown":"---\ntitle: Scheduling and events\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/scheduling-and-events/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Scheduling and events\n\n> CRON(), ON(), ONCE(), OFF(), EMIT(), the built-in events, setTimeout2(), CLEANUP() and PAUSESERVER().\n\nGlobal functions for scheduled and event-driven code: `CRON()` runs functions on a cron line, `ON()`, `ONCE()`, `OFF()` and `EMIT()` work with global events, and the framework emits its own events such as `ready`, `service`, `exit` and `error`. `setTimeout2()` and `clearTimeout2()` give named debounced timers, `CLEANUP()` waits for a stream and `PAUSESERVER()` holds incoming traffic.\n\nThe guide [Scheduling and events](../../guides/scheduling-and-events/) explains how they work together.\n\n## API\n\n### CRON(line, fn)\n\nType: `method`\n\nRuns a function when the date matches a cron line.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | The cron line, e.g. `0 3 * * *`. |\n| `fn` | `Function` | yes |  | `function(date)`, called when the line matches. |\n\nReturns: `Object` The cron, with `check(date)`, `exec(date)` and `remove()`.\n\nThe line has five fields: minute, hour, day of the month, month and day of the week (`0`–`6`, or `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`). Each field is `*`, a number, a list (`1,15`), a range (`8-17`) or a step: `*/15` matches every 15th value from the first value of the field (minutes `0`, `15`, `30`, `45`; days of the month `1`, `16`, `31`) and `5/20` every 20th value from `5` (`5`, `25`, `45`). The crons are checked once a minute by the service timer and `fn` gets the current date (`NOW`). Hours and days follow the time zone of the process (`$timezone`, default `utc`).\n\nExample: Every day at 03:00\n```js\nCRON('0 3 * * *', function(date) {\n\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n});\n```\n\nExample: Working days\n```js\nCRON('30 8 * * mo-fr', function() {\n\tMAIL(CONF.mail_report, 'Daily report', 'mail/report', {});\n});\n```\n\nExample: Every 15 minutes\n```js\nCRON('*/15 * * * *', function() {\n\t// at minutes 0, 15, 30 and 45\n});\n```\n\n### cron.remove()\n\nType: `method`\n\nStops a cron.\n\nRemoves the cron returned by `CRON()` from `F.crons`, so it does not run any more.\n\nExample: Run once\n```js\nvar cron = CRON('0 12 * * *', function() {\n\tsendreport();\n\tcron.remove();\n});\n```\n\n### F.crons\n\nType: `property`\n\nThe registered crons.\n\nReturns: `Array`\n\nAn array of the objects returned by `CRON()`, in the order they were registered. Each has `check(date)` (returns `true` when the line matches), `exec(date)` (your function) and `remove()`.\n\nExample: Count\n```js\nconsole.log(F.crons.length + ' crons');\n```\n\n### ON(name, fn)\n\nType: `method`\n\nAdds a listener of a global event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the event, or several names joined with `+`. |\n| `fn` | `Function` | yes |  | The listener; it gets the arguments of `EMIT()`. |\n\nJoin several names with `+` to add the same listener to each of them. A listener of `ready` added after the application is loaded is called at once. Inside the listener `this` is `F`. `F.on()` is the same method.\n\nExample: Own event\n```js\nON('order.created', function(order) {\n\tconsole.log('New order', order.id);\n});\n```\n\nExample: Several events\n```js\nON('ready + service', function() {\n\trefreshcache();\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nAdds a listener that runs only once.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the event. |\n| `fn` | `Function` | yes |  | The listener. |\n\nThe listener is removed after the first emission of the event. Names joined with `+` work as in `ON()`, and a `ready` listener added after the load runs at once. `F.once()` is the same method.\n\nExample: First minute\n```js\nONCE('service', function() {\n\tconsole.log('The first minute has passed');\n});\n```\n\n### OFF(name, [fn])\n\nType: `method`\n\nRemoves a listener of a global event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the event. |\n| `fn` | `Function` | no |  | The listener to remove. |\n\nWith `fn`, removes that listener; it must be the same function that was passed to `ON()`. Without `fn`, removes all listeners of the event, including listeners of the framework. `F.off()` is the same method.\n\nExample: Remove a listener\n```js\nfunction onservice(counter) {\n\tif (counter === 60)\n\t\tOFF('service', onservice);\n}\n\nON('service', onservice);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nEmits a global event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the event. |\n| `a...g` | `Object` | no |  | Up to seven arguments for the listeners. |\n\nCalls all listeners of `name` in the order they were added, synchronously, with up to seven arguments. Listeners added with `ONCE()` are removed afterwards. `F.emit()` is the same method.\n\nExample: Emit\n```js\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\n### setTimeout2(id, callback, timeout, [limit])\n\nType: `method`\n\nA named timer that restarts on every call (a debounce).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The name of the timer. |\n| `callback` | `Function` | yes |  | The function to run. |\n| `timeout` | `Number` | yes |  | The delay in milliseconds. |\n| `limit` | `Number` | no | `0` | How many times the timer can be postponed before a call runs the callback at once. `0` means no limit. |\n\nIf a timer with the same `id` is waiting, it is canceled and a new timer starts with the new `callback`. The callback runs only after `timeout` milliseconds without a new call with that `id`.\n\nWith `limit`, the timer can be postponed only `limit` times: the next call cancels the timer and runs its callback at once, and the counting starts again. Use it when the callback must run from time to time even while the calls do not stop.\n\nExample: Save once after changes\n```js\nfunction changed(doc) {\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nExample: With a limit\n```js\nfunction onkey(text) {\n\t// searches after a pause of 300 ms, or at once when the timer has been postponed 10 times\n\tsetTimeout2('search', function() {\n\t\tsearch(text);\n\t}, 300, 10);\n}\n```\n\n### clearTimeout2(id)\n\nType: `method`\n\nCancels a named timer of setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The name of the timer. |\n\nReturns: `Boolean` `true` when a timer was waiting.\n\nThe callback of the timer does not run.\n\nExample: Cancel\n```js\nif (clearTimeout2('save' + doc.id))\n\tconsole.log('The pending save was canceled');\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method`\n\nCalls a function when a stream is done and destroys the stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | A readable or writable stream. |\n| `callback` | `Function` | no |  | Called when the stream is done. |\n\nReturns: `Promise` Without a callback.\n\nThe callback runs once, on the first of `end`, `finish`, `close`, `aborted` or `error` (for a response, also when its socket closes or fails). The stream is destroyed and its open file descriptor closed at that moment. Without a callback, returns a promise. `F.cleanup()` is the same method.\n\nExample: Wait for a file\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.end('id;name\\n');\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\nExample: With await\n```js\nawait CLEANUP(writer);\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nPauses all incoming traffic under a name.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A name of the reason, shown on the page. |\n| `enable` | `Boolean` | no |  | `true` to pause, `false` to resume; toggles when omitted. |\n\nReturns: `Boolean` `true` when the name is paused after the call.\n\nWhile at least one name is paused, every HTTP request gets the status `503`: browsers see a \"Please wait\" page with the paused names that reloads itself after 10 seconds, XHR requests get an error response, and new WebSocket connections are closed. `enable` `true` adds the name, `false` removes it; without `enable` the name is toggled. `F.pauseserver()` is the same method.\n\nExample: During a migration\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\n### F.paused\n\nType: `property`\n\nThe names paused with PAUSESERVER().\n\nReturns: `Array`\n\nAn array of strings. The server answers with `503` while it is not empty.\n\nExample: Check\n```js\nif (F.paused.length)\n\tconsole.log('Paused:', F.paused.join(', '));\n```\n\n### ON('ready', function() {})\n\nType: `event`\n\nThe application is loaded.\n\nEmitted after the configuration, modules, actions, controllers, plugins and the other parts are loaded and the service timer is started. A listener added after that moment runs at once.\n\nExample: Start\n```js\nON('ready', function() {\n\tconsole.log('Ready on port', CONF.$port);\n});\n```\n\n### ON('load', function() {})\n\nType: `event`\n\nEmitted right after ready.\n\nEmitted once after `ready`, when the load of the application is complete. Unlike `ready`, a listener added later is not called.\n\nExample: Load\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('service', function(counter) {})\n\nType: `event`\n\nEmitted once a minute by the service timer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Minutes since the start. |\n\nEmitted after the housekeeping of the minute and after the crons have run. `counter` is the number of minutes since the start: `1`, `2`, `3`…; use `counter % n` for longer steps.\n\nExample: Every 10 minutes\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\trefresh();\n});\n```\n\n### ON('exit', function(signal) {})\n\nType: `event`\n\nThe process is stopping.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | yes |  | The signal passed to `F.exit()`; `15` by default. |\n\nEmitted by `F.exit()` on `SIGTERM`, `SIGINT`, the exit of the process or a `stop` message from the parent, after workers and FlowStreams are stopped. Work done in the listener must be synchronous: the process ends right after it.\n\nExample: Last log\n```js\nON('exit', function(signal) {\n\tconsole.log('Exit', signal);\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: String, name: String, url: String, date: Date }`. |\n\nEmitted by the default `DEF.onError` for every error passed to `F.error()` and for unhandled exceptions and rejections. `obj` is `{ error, name, url, date }`, where `error` is the error as a string. The last 10 errors are also in `F.errors`.\n\nExample: Send errors elsewhere\n```js\nON('error', function(obj) {\n\tconsole.log(obj.date, obj.name, obj.error, obj.url);\n});\n```\n\n### ON('request', function(ctrl) {})\n\nType: `event`\n\nAn HTTP request arrived.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | The controller of the request. |\n\nEmitted for every HTTP request before CORS and routing. Requests stopped earlier (a paused server, a blocked IP address, the request limit, a proxy) do not reach it. `ctrl` is the controller of the request. Call `ctrl.cancel()` to stop the processing and answer the request yourself.\n\nExample: Health check\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n### ON('controller', function(ctrl) {})\n\nType: `event`\n\nA route was found for an HTTP request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | The controller of the request. |\n\nEmitted after the route is found and the body is parsed, just before the action of the route runs (also for API routes). `ctrl.route` is the route. Call `ctrl.cancel()` to stop the processing and answer the request yourself.\n\nExample: Log routes\n```js\nON('controller', function(ctrl) {\n\tconsole.log(ctrl.method, ctrl.url);\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: String, components: String }`. |\n\n`meta` is `{ name, components }`. Change `meta.components` to change the list of components that is downloaded.\n\nExample: Add a component\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',exec';\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nA component of a FlowStream failed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ id, name, error, source, instanceid, componentid }`. |\n\nEmitted for errors of FlowStream components, after the error is printed to the console. `meta` is `{ id, name, error, source, instanceid, componentid }`: the FlowStream, its name, the error, where it happened and the instance and component.\n\nExample: Log\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### ON('flowstream', function(instance) {})\n\nType: `event` · Since: `0.0.16`\n\nA FlowStream instance was created.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | The FlowStream instance. |\n\nEmitted when a FlowStream is created, in the main process or in a worker; `instance` is the object you control the FlowStream with. See [FlowStream](../../guides/flowstream/).\n\nExample: Log\n```js\nON('flowstream', function(instance) {\n\tconsole.log('FlowStream', instance.id);\n});\n```\n\n### ON('$mail', function(message) {})\n\nType: `event`\n\nAn e-mail is being sent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | The mail message. |\n\nEmitted for each message just before it is written to the SMTP connection. `message` is the mail message (`subject`, `body`, `email_to`, `email_from`…). See [Mail](../../guides/mail/).\n\nExample: Log\n```js\nON('$mail', function(message) {\n\tconsole.log('Mail', message.subject, message.email_to);\n});\n```\n\n### ON('$stats', function(stats) {})\n\nType: `event`\n\nThe usage statistics of the process were updated.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stats` | `Object` | yes |  | The statistics of the process. |\n\nEmitted 5 seconds after the application is loaded and then once a minute by the service timer, each time after the statistics of the last minute are computed. `stats` is the same object every time; read it, do not keep a reference to its values.\n\nThe main fields: `id` and `pid` (the process), `date`, `memory` (used heap in MB), `requests`, `pending`, `errors`, `timeouts`, `online` (WebSocket clients), `download` and `upload` (MB in total), `lasterror`, `lasttimeout`, `uptime` (minutes since the start), `overload` (how many hours the process was overloaded), `mode` (`debug` or `release`) and `version` (`node`, `total`, `build`, `app`). Fields ending with `m` count the last minute: `rm` requests, `fm` files, `wm` WebSocket messages, `em` external requests, `mm` e-mails, `om` opened files, `dm`/`um` downloaded/uploaded MB, `pm`/`sm` published/subscribed messages, `cm` calls, `dbrm`/`dbwm` database reads/writes.\n\nExample: Watch memory\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory', stats.memory, 'MB');\n});\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nThe process received a message from its parent.\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 that arrives through `process.on('message')`, after the framework handled its own messages (`total:...`, `stop`). Useful when the application runs as a child process or in a cluster.\n\nExample: Command\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'reload')\n\t\treload();\n});\n```\n\n### ON('$update', function() {})\n\nType: `event`\n\nAnother process of the cluster asked for an update.\n\nEmitted when the process receives the message `total:update`. In a cluster, a process that sends `process.send('total:update')` makes the main process forward it to the other ready processes, so each of them can reload its data.\n\nExample: Keep a cluster in sync\n```js\n// the process that changed the data\nprocess.send && process.send('total:update');\n\n// all other processes\nON('$update', function() {\n\treloadsettings();\n});\n```\n","entries":[{"type":"method","name":"CRON()","signature":"CRON(line, fn)","since":"","deprecated":false},{"type":"method","name":"cron.remove()","signature":"cron.remove()","since":"","deprecated":false},{"type":"property","name":"F.crons","signature":"F.crons","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":"setTimeout2()","signature":"setTimeout2(id, callback, timeout, [limit])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(id)","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"property","name":"F.paused","signature":"F.paused","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function() {})","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', 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('error')","signature":"ON('error', function(obj) {})","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(instance) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail', function(message) {})","since":"","deprecated":false},{"type":"event","name":"ON('$stats')","signature":"ON('$stats', function(stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"event","name":"ON('$update')","signature":"ON('$update', function() {})","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvoAcx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Zeitplanung und Events","summary":"CRON(), ON(), ONCE(), OFF(), EMIT(), die eingebauten Events, setTimeout2(), CLEANUP() und PAUSESERVER().","markdown":"---\ntitle: Zeitplanung und Events\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/scheduling-and-events/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Zeitplanung und Events\n\n> CRON(), ON(), ONCE(), OFF(), EMIT(), die eingebauten Events, setTimeout2(), CLEANUP() und PAUSESERVER().\n\nGlobale Funktionen für zeitgesteuerten und eventgesteuerten Code: `CRON()` führt Funktionen nach einer Cron-Zeile aus, `ON()`, `ONCE()`, `OFF()` und `EMIT()` arbeiten mit globalen Events, und das Framework sendet eigene Events wie `ready`, `service`, `exit` und `error`. `setTimeout2()` und `clearTimeout2()` bieten benannte Timer mit Debounce, `CLEANUP()` wartet auf einen Stream und `PAUSESERVER()` hält eingehenden Traffic an.\n\nDie Anleitung [Zeitplanung und Events](../../guides/scheduling-and-events/) erklärt, wie sie zusammenspielen.\n\n## API\n\n### CRON(line, fn)\n\nType: `method`\n\nFührt eine Funktion aus, wenn das Datum zu einer Cron-Zeile passt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Die Cron-Zeile, z. B. `0 3 * * *`. |\n| `fn` | `Function` | yes |  | `function(date)`, wird aufgerufen, wenn die Zeile passt. |\n\nReturns: `Object` Der Cron, mit `check(date)`, `exec(date)` und `remove()`.\n\nDie Zeile hat fünf Felder: Minute, Stunde, Tag des Monats, Monat und Wochentag (`0`–`6` oder `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`). Jedes Feld ist `*`, eine Zahl, eine Liste (`1,15`), ein Bereich (`8-17`) oder eine Schrittweite: `*/15` trifft jeden 15. Wert ab dem ersten Wert des Feldes (Minuten `0`, `15`, `30`, `45`; Tage des Monats `1`, `16`, `31`) und `5/20` jeden 20. Wert ab `5` (`5`, `25`, `45`). Die Crons werden einmal pro Minute vom Service-Timer geprüft, und `fn` erhält das aktuelle Datum (`NOW`). Stunden und Tage richten sich nach der Zeitzone des Prozesses (`$timezone`, Standard `utc`).\n\nExample: Jeden Tag um 03:00\n```js\nCRON('0 3 * * *', function(date) {\n\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n});\n```\n\nExample: Werktage\n```js\nCRON('30 8 * * mo-fr', function() {\n\tMAIL(CONF.mail_report, 'Daily report', 'mail/report', {});\n});\n```\n\nExample: Alle 15 Minuten\n```js\nCRON('*/15 * * * *', function() {\n\t// at minutes 0, 15, 30 and 45\n});\n```\n\n### cron.remove()\n\nType: `method`\n\nStoppt einen Cron.\n\nEntfernt den von `CRON()` zurückgegebenen Cron aus `F.crons`, sodass er nicht mehr ausgeführt wird.\n\nExample: Einmal ausführen\n```js\nvar cron = CRON('0 12 * * *', function() {\n\tsendreport();\n\tcron.remove();\n});\n```\n\n### F.crons\n\nType: `property`\n\nDie registrierten Crons.\n\nReturns: `Array`\n\nEin Array der von `CRON()` zurückgegebenen Objekte, in der Reihenfolge ihrer Registrierung. Jedes hat `check(date)` (gibt `true` zurück, wenn die Zeile passt), `exec(date)` (deine Funktion) und `remove()`.\n\nExample: Anzahl\n```js\nconsole.log(F.crons.length + ' crons');\n```\n\n### ON(name, fn)\n\nType: `method`\n\nFügt einen Listener für ein globales Event hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events oder mehrere mit `+` verbundene Namen. |\n| `fn` | `Function` | yes |  | Der Listener; er erhält die Argumente von `EMIT()`. |\n\nVerbinde mehrere Namen mit `+`, um denselben Listener jedem von ihnen hinzuzufügen. Ein Listener für `ready`, der nach dem Laden der Anwendung hinzugefügt wird, wird sofort aufgerufen. Im Listener ist `this` gleich `F`. `F.on()` ist dieselbe Methode.\n\nExample: Eigenes Event\n```js\nON('order.created', function(order) {\n\tconsole.log('New order', order.id);\n});\n```\n\nExample: Mehrere Events\n```js\nON('ready + service', function() {\n\trefreshcache();\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nFügt einen Listener hinzu, der nur einmal ausgeführt wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events. |\n| `fn` | `Function` | yes |  | Der Listener. |\n\nDer Listener wird nach dem ersten Auslösen des Events entfernt. Mit `+` verbundene Namen funktionieren wie bei `ON()`, und ein `ready`-Listener, der nach dem Laden hinzugefügt wird, läuft sofort. `F.once()` ist dieselbe Methode.\n\nExample: Erste Minute\n```js\nONCE('service', function() {\n\tconsole.log('The first minute has passed');\n});\n```\n\n### OFF(name, [fn])\n\nType: `method`\n\nEntfernt einen Listener eines globalen Events.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events. |\n| `fn` | `Function` | no |  | Der zu entfernende Listener. |\n\nMit `fn` wird dieser Listener entfernt; es muss dieselbe Funktion sein, die an `ON()` übergeben wurde. Ohne `fn` werden alle Listener des Events entfernt, einschließlich der Listener des Frameworks. `F.off()` ist dieselbe Methode.\n\nExample: Einen Listener entfernen\n```js\nfunction onservice(counter) {\n\tif (counter === 60)\n\t\tOFF('service', onservice);\n}\n\nON('service', onservice);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nLöst ein globales Event aus.\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\nRuft alle Listener von `name` in der Reihenfolge ihres Hinzufügens synchron auf, mit bis zu sieben Argumenten. Mit `ONCE()` hinzugefügte Listener werden danach entfernt. `F.emit()` ist dieselbe Methode.\n\nExample: Auslösen\n```js\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\n### setTimeout2(id, callback, timeout, [limit])\n\nType: `method`\n\nEin benannter Timer, der bei jedem Aufruf neu startet (ein Debounce).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Der Name des Timers. |\n| `callback` | `Function` | yes |  | Die auszuführende Funktion. |\n| `timeout` | `Number` | yes |  | Die Verzögerung in Millisekunden. |\n| `limit` | `Number` | no | `0` | Wie oft der Timer verschoben werden kann, bevor ein Aufruf den Callback sofort ausführt. `0` bedeutet kein Limit. |\n\nWartet bereits ein Timer mit derselben `id`, wird er abgebrochen und ein neuer Timer mit dem neuen `callback` gestartet. Der Callback läuft erst nach `timeout` Millisekunden ohne neuen Aufruf mit dieser `id`.\n\nMit `limit` kann der Timer nur `limit`-mal verschoben werden: Der nächste Aufruf bricht den Timer ab und führt seinen Callback sofort aus, und die Zählung beginnt von vorn. Verwende es, wenn der Callback von Zeit zu Zeit laufen muss, auch während die Aufrufe nicht aufhören.\n\nExample: Nach Änderungen einmal speichern\n```js\nfunction changed(doc) {\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nExample: Mit einem Limit\n```js\nfunction onkey(text) {\n\t// searches after a pause of 300 ms, or at once when the timer has been postponed 10 times\n\tsetTimeout2('search', function() {\n\t\tsearch(text);\n\t}, 300, 10);\n}\n```\n\n### clearTimeout2(id)\n\nType: `method`\n\nBricht einen benannten Timer von setTimeout2() ab.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Der Name des Timers. |\n\nReturns: `Boolean` `true`, wenn ein Timer gewartet hat.\n\nDer Callback des Timers wird nicht ausgeführt.\n\nExample: Abbrechen\n```js\nif (clearTimeout2('save' + doc.id))\n\tconsole.log('The pending save was canceled');\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method`\n\nRuft eine Funktion auf, wenn ein Stream fertig ist, und zerstört den Stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Ein lesbarer oder schreibbarer Stream. |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn der Stream fertig ist. |\n\nReturns: `Promise` Ohne Callback.\n\nDer Callback läuft einmal, beim ersten von `end`, `finish`, `close`, `aborted` oder `error` (bei einer Antwort auch, wenn ihr Socket geschlossen wird oder fehlschlägt). Der Stream wird in diesem Moment zerstört und sein offener Dateideskriptor geschlossen. Ohne Callback wird eine Promise zurückgegeben. `F.cleanup()` ist dieselbe Methode.\n\nExample: Auf eine Datei warten\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.end('id;name\\n');\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\nExample: Mit await\n```js\nawait CLEANUP(writer);\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nPausiert den gesamten eingehenden Traffic unter einem Namen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein Name für den Grund, der auf der Seite angezeigt wird. |\n| `enable` | `Boolean` | no |  | `true` zum Pausieren, `false` zum Fortsetzen; schaltet um, wenn weggelassen. |\n\nReturns: `Boolean` `true`, wenn der Name nach dem Aufruf pausiert ist.\n\nSolange mindestens ein Name pausiert ist, erhält jede HTTP-Anfrage den Status `503`: Browser sehen eine Seite „Please wait“ mit den pausierten Namen, die sich nach 10 Sekunden selbst neu lädt, XHR-Anfragen erhalten eine Fehlerantwort, und neue WebSocket-Verbindungen werden geschlossen. `enable` `true` fügt den Namen hinzu, `false` entfernt ihn; ohne `enable` wird der Name umgeschaltet. `F.pauseserver()` ist dieselbe Methode.\n\nExample: Während einer Migration\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\n### F.paused\n\nType: `property`\n\nDie mit PAUSESERVER() pausierten Namen.\n\nReturns: `Array`\n\nEin Array von Strings. Der Server antwortet mit `503`, solange es nicht leer ist.\n\nExample: Prüfen\n```js\nif (F.paused.length)\n\tconsole.log('Paused:', F.paused.join(', '));\n```\n\n### ON('ready', function() {})\n\nType: `event`\n\nDie Anwendung ist geladen.\n\nWird ausgelöst, nachdem Konfiguration, Module, Actions, Controller, Plugins und die übrigen Teile geladen sind und der Service-Timer gestartet ist. Ein Listener, der nach diesem Zeitpunkt hinzugefügt wird, läuft sofort.\n\nExample: Start\n```js\nON('ready', function() {\n\tconsole.log('Ready on port', CONF.$port);\n});\n```\n\n### ON('load', function() {})\n\nType: `event`\n\nWird direkt nach ready ausgelöst.\n\nWird einmal nach `ready` ausgelöst, wenn das Laden der Anwendung abgeschlossen ist. Anders als bei `ready` wird ein später hinzugefügter Listener nicht aufgerufen.\n\nExample: Laden\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('service', function(counter) {})\n\nType: `event`\n\nWird einmal pro Minute vom Service-Timer ausgelöst.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Minuten seit dem Start. |\n\nWird nach den Aufräumarbeiten der Minute und nach der Ausführung der Crons ausgelöst. `counter` ist die Anzahl der Minuten seit dem Start: `1`, `2`, `3`…; verwende `counter % n` für längere Intervalle.\n\nExample: Alle 10 Minuten\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\trefresh();\n});\n```\n\n### ON('exit', function(signal) {})\n\nType: `event`\n\nDer Prozess wird beendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | yes |  | Das an `F.exit()` übergebene Signal; standardmäßig `15`. |\n\nWird von `F.exit()` bei `SIGTERM`, `SIGINT`, dem Beenden des Prozesses oder einer `stop`-Nachricht vom Elternprozess ausgelöst, nachdem Worker und FlowStreams gestoppt wurden. Arbeit im Listener muss synchron sein: Der Prozess endet direkt danach.\n\nExample: Letztes Log\n```js\nON('exit', function(signal) {\n\tconsole.log('Exit', signal);\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: String, name: String, url: String, date: Date }`. |\n\nWird vom Standard-`DEF.onError` für jeden an `F.error()` übergebenen Fehler sowie für unbehandelte Exceptions und Rejections ausgelöst. `obj` ist `{ error, name, url, date }`, wobei `error` der Fehler als String ist. Die letzten 10 Fehler stehen auch in `F.errors`.\n\nExample: Fehler anderswohin senden\n```js\nON('error', function(obj) {\n\tconsole.log(obj.date, obj.name, obj.error, obj.url);\n});\n```\n\n### ON('request', function(ctrl) {})\n\nType: `event`\n\nEine HTTP-Anfrage ist eingetroffen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | Der Controller der Anfrage. |\n\nWird für jede HTTP-Anfrage vor CORS und Routing ausgelöst. Früher gestoppte Anfragen (ein pausierter Server, eine blockierte IP-Adresse, das Anfragelimit, ein Proxy) erreichen es nicht. `ctrl` ist der Controller der Anfrage. Rufe `ctrl.cancel()` auf, um die Verarbeitung zu stoppen und die Anfrage selbst zu beantworten.\n\nExample: Health-Check\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n### ON('controller', function(ctrl) {})\n\nType: `event`\n\nFür eine HTTP-Anfrage wurde eine Route gefunden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | Der Controller der Anfrage. |\n\nWird ausgelöst, nachdem die Route gefunden und der Body geparst wurde, direkt bevor die Action der Route läuft (auch für API-Routes). `ctrl.route` ist die Route. Rufe `ctrl.cancel()` auf, um die Verarbeitung zu stoppen und die Anfrage selbst zu beantworten.\n\nExample: Routes protokollieren\n```js\nON('controller', function(ctrl) {\n\tconsole.log(ctrl.method, ctrl.url);\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: String, components: String }`. |\n\n`meta` ist `{ name, components }`. Ändere `meta.components`, um die Liste der heruntergeladenen Komponenten zu ändern.\n\nExample: Eine Komponente hinzufügen\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',exec';\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nEine Komponente eines FlowStreams ist fehlgeschlagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ id, name, error, source, instanceid, componentid }`. |\n\nWird für Fehler von FlowStream-Komponenten ausgelöst, nachdem der Fehler in der Konsole ausgegeben wurde. `meta` ist `{ id, name, error, source, instanceid, componentid }`: der FlowStream, sein Name, der Fehler, wo er auftrat sowie Instanz und Komponente.\n\nExample: Protokollieren\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### ON('flowstream', function(instance) {})\n\nType: `event` · Since: `0.0.16`\n\nEine FlowStream-Instanz wurde erstellt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | Die FlowStream-Instanz. |\n\nWird ausgelöst, wenn ein FlowStream erstellt wird, im Hauptprozess oder in einem Worker; `instance` ist das Objekt, mit dem du den FlowStream steuerst. Siehe [FlowStream](../../guides/flowstream/).\n\nExample: Protokollieren\n```js\nON('flowstream', function(instance) {\n\tconsole.log('FlowStream', instance.id);\n});\n```\n\n### ON('$mail', function(message) {})\n\nType: `event`\n\nEine E-Mail wird gesendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | Die Mail-Nachricht. |\n\nWird für jede Nachricht ausgelöst, direkt bevor sie in die SMTP-Verbindung geschrieben wird. `message` ist die Mail-Nachricht (`subject`, `body`, `email_to`, `email_from`…). Siehe [Mail](../../guides/mail/).\n\nExample: Protokollieren\n```js\nON('$mail', function(message) {\n\tconsole.log('Mail', message.subject, message.email_to);\n});\n```\n\n### ON('$stats', function(stats) {})\n\nType: `event`\n\nDie Nutzungsstatistiken des Prozesses wurden aktualisiert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stats` | `Object` | yes |  | Die Statistiken des Prozesses. |\n\nWird 5 Sekunden nach dem Laden der Anwendung und danach einmal pro Minute vom Service-Timer gesendet, jeweils nachdem die Statistiken der letzten Minute berechnet wurden. `stats` ist jedes Mal dasselbe Objekt; lies es, aber behalte keine Referenz auf seine Werte.\n\nDie wichtigsten Felder: `id` und `pid` (der Prozess), `date`, `memory` (genutzter Heap in MB), `requests`, `pending`, `errors`, `timeouts`, `online` (WebSocket-Clients), `download` und `upload` (MB insgesamt), `lasterror`, `lasttimeout`, `uptime` (Minuten seit dem Start), `overload` (wie viele Stunden der Prozess überlastet war), `mode` (`debug` oder `release`) und `version` (`node`, `total`, `build`, `app`). Felder, die auf `m` enden, zählen die letzte Minute: `rm` Anfragen, `fm` Dateien, `wm` WebSocket-Nachrichten, `em` externe Anfragen, `mm` E-Mails, `om` geöffnete Dateien, `dm`/`um` heruntergeladene/hochgeladene MB, `pm`/`sm` veröffentlichte/abonnierte Nachrichten, `cm` Aufrufe, `dbrm`/`dbwm` Datenbank-Lese-/Schreibvorgänge.\n\nExample: Speicher überwachen\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory', stats.memory, 'MB');\n});\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nDer Prozess hat eine Nachricht von seinem Elternprozess erhalten.\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 über `process.on('message')` eintrifft, nachdem das Framework seine eigenen Nachrichten (`total:...`, `stop`) verarbeitet hat. Nützlich, wenn die Anwendung als Kindprozess oder in einem Cluster läuft.\n\nExample: Befehl\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'reload')\n\t\treload();\n});\n```\n\n### ON('$update', function() {})\n\nType: `event`\n\nEin anderer Prozess des Clusters hat ein Update angefordert.\n\nWird ausgelöst, wenn der Prozess die Nachricht `total:update` erhält. In einem Cluster bringt ein Prozess, der `process.send('total:update')` sendet, den Hauptprozess dazu, sie an die anderen bereiten Prozesse weiterzuleiten, damit jeder von ihnen seine Daten neu laden kann.\n\nExample: Einen Cluster synchron halten\n```js\n// the process that changed the data\nprocess.send && process.send('total:update');\n\n// all other processes\nON('$update', function() {\n\treloadsettings();\n});\n```\n","entries":[{"type":"method","name":"CRON()","signature":"CRON(line, fn)","since":"","deprecated":false},{"type":"method","name":"cron.remove()","signature":"cron.remove()","since":"","deprecated":false},{"type":"property","name":"F.crons","signature":"F.crons","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":"setTimeout2()","signature":"setTimeout2(id, callback, timeout, [limit])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(id)","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"property","name":"F.paused","signature":"F.paused","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function() {})","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', 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('error')","signature":"ON('error', function(obj) {})","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(instance) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail', function(message) {})","since":"","deprecated":false},{"type":"event","name":"ON('$stats')","signature":"ON('$stats', function(stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"event","name":"ON('$update')","signature":"ON('$update', function() {})","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvoAcx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Programación y eventos","summary":"CRON(), ON(), ONCE(), OFF(), EMIT(), los eventos integrados, setTimeout2(), CLEANUP() y PAUSESERVER().","markdown":"---\ntitle: \"Programación y eventos\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/scheduling-and-events/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Programación y eventos\n\n> CRON(), ON(), ONCE(), OFF(), EMIT(), los eventos integrados, setTimeout2(), CLEANUP() y PAUSESERVER().\n\nFunciones globales para código programado y basado en eventos: `CRON()` ejecuta funciones según una línea cron, `ON()`, `ONCE()`, `OFF()` y `EMIT()` trabajan con eventos globales, y el framework emite sus propios eventos, como `ready`, `service`, `exit` y `error`. `setTimeout2()` y `clearTimeout2()` ofrecen temporizadores con nombre y debounce, `CLEANUP()` espera a que termine un stream y `PAUSESERVER()` retiene el tráfico entrante.\n\nLa guía [Programación y eventos](../../guides/scheduling-and-events/) explica cómo funcionan juntos.\n\n## API\n\n### CRON(line, fn)\n\nType: `method`\n\nEjecuta una función cuando la fecha coincide con una línea cron.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | La línea cron, p. ej. `0 3 * * *`. |\n| `fn` | `Function` | yes |  | `function(date)`, se llama cuando la línea coincide. |\n\nReturns: `Object` El cron, con `check(date)`, `exec(date)` y `remove()`.\n\nLa línea tiene cinco campos: minuto, hora, día del mes, mes y día de la semana (`0`–`6`, o `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`). Cada campo es `*`, un número, una lista (`1,15`), un rango (`8-17`) o un paso: `*/15` coincide con cada 15.º valor desde el primer valor del campo (minutos `0`, `15`, `30`, `45`; días del mes `1`, `16`, `31`) y `5/20` con cada 20.º valor desde `5` (`5`, `25`, `45`). El temporizador de servicio comprueba los crons una vez por minuto y `fn` recibe la fecha actual (`NOW`). Las horas y los días siguen la zona horaria del proceso (`$timezone`, por defecto `utc`).\n\nExample: Cada día a las 03:00\n```js\nCRON('0 3 * * *', function(date) {\n\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n});\n```\n\nExample: Días laborables\n```js\nCRON('30 8 * * mo-fr', function() {\n\tMAIL(CONF.mail_report, 'Daily report', 'mail/report', {});\n});\n```\n\nExample: Cada 15 minutos\n```js\nCRON('*/15 * * * *', function() {\n\t// at minutes 0, 15, 30 and 45\n});\n```\n\n### cron.remove()\n\nType: `method`\n\nDetiene un cron.\n\nElimina de `F.crons` el cron devuelto por `CRON()`, de modo que ya no se ejecuta.\n\nExample: Ejecutar una sola vez\n```js\nvar cron = CRON('0 12 * * *', function() {\n\tsendreport();\n\tcron.remove();\n});\n```\n\n### F.crons\n\nType: `property`\n\nLos crons registrados.\n\nReturns: `Array`\n\nUn array de los objetos devueltos por `CRON()`, en el orden en que se registraron. Cada uno tiene `check(date)` (devuelve `true` cuando la línea coincide), `exec(date)` (tu función) y `remove()`.\n\nExample: Contar\n```js\nconsole.log(F.crons.length + ' crons');\n```\n\n### ON(name, fn)\n\nType: `method`\n\nAñade un listener de un evento global.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento, o varios nombres unidos con `+`. |\n| `fn` | `Function` | yes |  | El listener; recibe los argumentos de `EMIT()`. |\n\nUne varios nombres con `+` para añadir el mismo listener a cada uno de ellos. Un listener de `ready` añadido después de cargar la aplicación se llama de inmediato. Dentro del listener, `this` es `F`. `F.on()` es el mismo método.\n\nExample: Evento propio\n```js\nON('order.created', function(order) {\n\tconsole.log('New order', order.id);\n});\n```\n\nExample: Varios eventos\n```js\nON('ready + service', function() {\n\trefreshcache();\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nAñade un listener que se ejecuta solo una vez.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento. |\n| `fn` | `Function` | yes |  | El listener. |\n\nEl listener se elimina tras la primera emisión del evento. Los nombres unidos con `+` funcionan como en `ON()`, y un listener de `ready` añadido después de la carga se ejecuta de inmediato. `F.once()` es el mismo método.\n\nExample: Primer minuto\n```js\nONCE('service', function() {\n\tconsole.log('The first minute has passed');\n});\n```\n\n### OFF(name, [fn])\n\nType: `method`\n\nElimina un listener de un evento global.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento. |\n| `fn` | `Function` | no |  | El listener que se elimina. |\n\nCon `fn`, elimina ese listener; debe ser la misma función que se pasó a `ON()`. Sin `fn`, elimina todos los listeners del evento, incluidos los del framework. `F.off()` es el mismo método.\n\nExample: Eliminar un listener\n```js\nfunction onservice(counter) {\n\tif (counter === 60)\n\t\tOFF('service', onservice);\n}\n\nON('service', onservice);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nEmite un evento global.\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\nLlama a todos los listeners de `name` en el orden en que se añadieron, de forma síncrona, con hasta siete argumentos. Los listeners añadidos con `ONCE()` se eliminan después. `F.emit()` es el mismo método.\n\nExample: Emitir\n```js\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\n### setTimeout2(id, callback, timeout, [limit])\n\nType: `method`\n\nUn temporizador con nombre que se reinicia en cada llamada (un debounce).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El nombre del temporizador. |\n| `callback` | `Function` | yes |  | La función que se ejecuta. |\n| `timeout` | `Number` | yes |  | El retardo en milisegundos. |\n| `limit` | `Number` | no | `0` | Cuántas veces se puede aplazar el temporizador antes de que una llamada ejecute el callback de inmediato. `0` significa sin límite. |\n\nSi hay un temporizador con el mismo `id` en espera, se cancela y arranca uno nuevo con el nuevo `callback`. El callback solo se ejecuta tras `timeout` milisegundos sin una nueva llamada con ese `id`.\n\nCon `limit`, el temporizador solo se puede aplazar `limit` veces: la siguiente llamada cancela el temporizador y ejecuta su callback de inmediato, y el conteo empieza de nuevo. Úsalo cuando el callback debe ejecutarse de vez en cuando aunque las llamadas no paren.\n\nExample: Guardar una vez tras los cambios\n```js\nfunction changed(doc) {\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nExample: Con un límite\n```js\nfunction onkey(text) {\n\t// searches after a pause of 300 ms, or at once when the timer has been postponed 10 times\n\tsetTimeout2('search', function() {\n\t\tsearch(text);\n\t}, 300, 10);\n}\n```\n\n### clearTimeout2(id)\n\nType: `method`\n\nCancela un temporizador con nombre de setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El nombre del temporizador. |\n\nReturns: `Boolean` `true` cuando había un temporizador en espera.\n\nEl callback del temporizador no se ejecuta.\n\nExample: Cancelar\n```js\nif (clearTimeout2('save' + doc.id))\n\tconsole.log('The pending save was canceled');\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method`\n\nLlama a una función cuando un stream termina y destruye el stream.\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 cuando el stream termina. |\n\nReturns: `Promise` Sin callback.\n\nEl callback se ejecuta una vez, con el primero de `end`, `finish`, `close`, `aborted` o `error` (en una respuesta, también cuando su socket se cierra o falla). En ese momento el stream se destruye y se cierra su descriptor de archivo abierto. Sin callback, devuelve una promesa. `F.cleanup()` es el mismo método.\n\nExample: Esperar a un archivo\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.end('id;name\\n');\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\nExample: Con await\n```js\nawait CLEANUP(writer);\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nPausa todo el tráfico entrante bajo un nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre del motivo, que se muestra en la página. |\n| `enable` | `Boolean` | no |  | `true` para pausar, `false` para reanudar; si se omite, alterna. |\n\nReturns: `Boolean` `true` cuando el nombre queda en pausa tras la llamada.\n\nMientras haya al menos un nombre en pausa, cada petición HTTP recibe el estado `503`: los navegadores ven una página \"Please wait\" con los nombres en pausa que se recarga sola cada 10 segundos, las peticiones XHR reciben una respuesta de error y las nuevas conexiones WebSocket se cierran. `enable` `true` añade el nombre y `false` lo quita; sin `enable`, el nombre se alterna. `F.pauseserver()` es el mismo método.\n\nExample: Durante una migración\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\n### F.paused\n\nType: `property`\n\nLos nombres pausados con PAUSESERVER().\n\nReturns: `Array`\n\nUn array de strings. El servidor responde con `503` mientras no esté vacío.\n\nExample: Comprobar\n```js\nif (F.paused.length)\n\tconsole.log('Paused:', F.paused.join(', '));\n```\n\n### ON('ready', function() {})\n\nType: `event`\n\nLa aplicación está cargada.\n\nSe emite después de cargar la configuración, los módulos, las acciones, los controladores, los plugins y las demás partes, y de arrancar el temporizador de servicio. Un listener añadido después de ese momento se ejecuta de inmediato.\n\nExample: Arranque\n```js\nON('ready', function() {\n\tconsole.log('Ready on port', CONF.$port);\n});\n```\n\n### ON('load', function() {})\n\nType: `event`\n\nSe emite justo después de ready.\n\nSe emite una vez después de `ready`, cuando la carga de la aplicación ha terminado. A diferencia de `ready`, un listener añadido más tarde no se llama.\n\nExample: Carga\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('service', function(counter) {})\n\nType: `event`\n\nLo emite el temporizador de servicio una vez por minuto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Minutos desde el inicio. |\n\nSe emite después de las tareas de mantenimiento del minuto y después de ejecutar los crons. `counter` es el número de minutos desde el inicio: `1`, `2`, `3`…; usa `counter % n` para intervalos más largos.\n\nExample: Cada 10 minutos\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\trefresh();\n});\n```\n\n### ON('exit', function(signal) {})\n\nType: `event`\n\nEl proceso se está deteniendo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | yes |  | La señal pasada a `F.exit()`; `15` por defecto. |\n\nLo emite `F.exit()` ante `SIGTERM`, `SIGINT`, la salida del proceso o un mensaje `stop` del padre, después de detener los workers y los FlowStreams. El trabajo que hagas en el listener debe ser síncrono: el proceso termina justo después.\n\nExample: Último log\n```js\nON('exit', function(signal) {\n\tconsole.log('Exit', signal);\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: String, name: String, url: String, date: Date }`. |\n\nLo emite el `DEF.onError` por defecto para cada error pasado a `F.error()` y para las excepciones y rechazos no gestionados. `obj` es `{ error, name, url, date }`, donde `error` es el error como string. Los 10 últimos errores también están en `F.errors`.\n\nExample: Enviar los errores a otro sitio\n```js\nON('error', function(obj) {\n\tconsole.log(obj.date, obj.name, obj.error, obj.url);\n});\n```\n\n### ON('request', function(ctrl) {})\n\nType: `event`\n\nHa llegado una petición HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | El controlador de la petición. |\n\nSe emite para cada petición HTTP antes de CORS y del enrutamiento. Las peticiones detenidas antes (un servidor en pausa, una dirección IP bloqueada, el límite de peticiones, un proxy) no llegan a él. `ctrl` es el controlador de la petición. Llama a `ctrl.cancel()` para detener el procesamiento y responder tú mismo a la petición.\n\nExample: Comprobación de estado\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n### ON('controller', function(ctrl) {})\n\nType: `event`\n\nSe ha encontrado una ruta para una petición HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | El controlador de la petición. |\n\nSe emite después de encontrar la ruta y de analizar el cuerpo, justo antes de que se ejecute la acción de la ruta (también para las rutas API). `ctrl.route` es la ruta. Llama a `ctrl.cancel()` para detener el procesamiento y responder tú mismo a la petición.\n\nExample: Registrar las rutas\n```js\nON('controller', function(ctrl) {\n\tconsole.log(ctrl.method, ctrl.url);\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: String, components: String }`. |\n\n`meta` es `{ name, components }`. Cambia `meta.components` para cambiar la lista de componentes que se descarga.\n\nExample: Añadir un componente\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',exec';\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nHa fallado un componente de un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ id, name, error, source, instanceid, componentid }`. |\n\nSe emite para los errores de los componentes de FlowStream, después de imprimir el error en la consola. `meta` es `{ id, name, error, source, instanceid, componentid }`: el FlowStream, su nombre, el error, dónde ocurrió y la instancia y el componente.\n\nExample: Log\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### ON('flowstream', function(instance) {})\n\nType: `event` · Since: `0.0.16`\n\nSe ha creado una instancia de FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | La instancia de FlowStream. |\n\nSe emite cuando se crea un FlowStream, en el proceso principal o en un worker; `instance` es el objeto con el que controlas el FlowStream. Consulta [FlowStream](../../guides/flowstream/).\n\nExample: Registrar\n```js\nON('flowstream', function(instance) {\n\tconsole.log('FlowStream', instance.id);\n});\n```\n\n### ON('$mail', function(message) {})\n\nType: `event`\n\nSe está enviando un e-mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | El mensaje de correo. |\n\nSe emite para cada mensaje justo antes de escribirlo en la conexión SMTP. `message` es el mensaje de correo (`subject`, `body`, `email_to`, `email_from`…). Consulta [Correo](../../guides/mail/).\n\nExample: Log\n```js\nON('$mail', function(message) {\n\tconsole.log('Mail', message.subject, message.email_to);\n});\n```\n\n### ON('$stats', function(stats) {})\n\nType: `event`\n\nSe han actualizado las estadísticas de uso del proceso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stats` | `Object` | yes |  | Las estadísticas del proceso. |\n\nSe emite 5 segundos después de cargar la aplicación y luego una vez por minuto desde el temporizador de servicio, cada vez después de calcular las estadísticas del último minuto. `stats` es el mismo objeto cada vez; léelo, no guardes una referencia a sus valores.\n\nLos campos principales: `id` y `pid` (el proceso), `date`, `memory` (heap usado en MB), `requests`, `pending`, `errors`, `timeouts`, `online` (clientes WebSocket), `download` y `upload` (MB en total), `lasterror`, `lasttimeout`, `uptime` (minutos desde el inicio), `overload` (cuántas horas estuvo sobrecargado el proceso), `mode` (`debug` o `release`) y `version` (`node`, `total`, `build`, `app`). Los campos que terminan en `m` cuentan el último minuto: `rm` peticiones, `fm` archivos, `wm` mensajes WebSocket, `em` peticiones externas, `mm` e-mails, `om` archivos abiertos, `dm`/`um` MB descargados/subidos, `pm`/`sm` mensajes publicados/suscritos, `cm` llamadas, `dbrm`/`dbwm` lecturas/escrituras en la base de datos.\n\nExample: Vigilar la memoria\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory', stats.memory, 'MB');\n});\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nEl proceso ha recibido un mensaje de su padre.\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 llega a través de `process.on('message')`, después de que el framework haya gestionado sus propios mensajes (`total:...`, `stop`). Útil cuando la aplicación se ejecuta como proceso hijo o en un clúster.\n\nExample: Comando\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'reload')\n\t\treload();\n});\n```\n\n### ON('$update', function() {})\n\nType: `event`\n\nOtro proceso del clúster ha pedido una actualización.\n\nSe emite cuando el proceso recibe el mensaje `total:update`. En un clúster, un proceso que envía `process.send('total:update')` hace que el proceso principal lo reenvíe a los demás procesos listos, para que cada uno pueda recargar sus datos.\n\nExample: Mantener un clúster sincronizado\n```js\n// the process that changed the data\nprocess.send && process.send('total:update');\n\n// all other processes\nON('$update', function() {\n\treloadsettings();\n});\n```\n","entries":[{"type":"method","name":"CRON()","signature":"CRON(line, fn)","since":"","deprecated":false},{"type":"method","name":"cron.remove()","signature":"cron.remove()","since":"","deprecated":false},{"type":"property","name":"F.crons","signature":"F.crons","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":"setTimeout2()","signature":"setTimeout2(id, callback, timeout, [limit])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(id)","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"property","name":"F.paused","signature":"F.paused","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function() {})","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', 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('error')","signature":"ON('error', function(obj) {})","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(instance) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail', function(message) {})","since":"","deprecated":false},{"type":"event","name":"ON('$stats')","signature":"ON('$stats', function(stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"event","name":"ON('$update')","signature":"ON('$update', function() {})","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvoAcx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Planification et événements","summary":"CRON(), ON(), ONCE(), OFF(), EMIT(), les événements intégrés, setTimeout2(), CLEANUP() et PAUSESERVER().","markdown":"---\ntitle: \"Planification et événements\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/scheduling-and-events/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Planification et événements\n\n> CRON(), ON(), ONCE(), OFF(), EMIT(), les événements intégrés, setTimeout2(), CLEANUP() et PAUSESERVER().\n\nDes fonctions globales pour le code planifié et piloté par les événements : `CRON()` exécute des fonctions selon une ligne cron, `ON()`, `ONCE()`, `OFF()` et `EMIT()` gèrent les événements globaux, et le framework émet ses propres événements comme `ready`, `service`, `exit` et `error`. `setTimeout2()` et `clearTimeout2()` fournissent des minuteurs nommés avec debounce, `CLEANUP()` attend la fin d'un flux et `PAUSESERVER()` retient le trafic entrant.\n\nLe guide [Planification et événements](../../guides/scheduling-and-events/) explique comment ils fonctionnent ensemble.\n\n## API\n\n### CRON(line, fn)\n\nType: `method`\n\nExécute une fonction lorsque la date correspond à une ligne cron.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | La ligne cron, par ex. `0 3 * * *`. |\n| `fn` | `Function` | yes |  | `function(date)`, appelée lorsque la ligne correspond. |\n\nReturns: `Object` Le cron, avec `check(date)`, `exec(date)` et `remove()`.\n\nLa ligne comporte cinq champs : minute, heure, jour du mois, mois et jour de la semaine (`0`–`6`, ou `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`). Chaque champ vaut `*`, un nombre, une liste (`1,15`), une plage (`8-17`) ou un pas : `*/15` correspond à une valeur sur 15 à partir de la première valeur du champ (minutes `0`, `15`, `30`, `45` ; jours du mois `1`, `16`, `31`) et `5/20` à une valeur sur 20 à partir de `5` (`5`, `25`, `45`). Les crons sont vérifiés une fois par minute par le minuteur de service et `fn` reçoit la date courante (`NOW`). Les heures et les jours suivent le fuseau horaire du processus (`$timezone`, `utc` par défaut).\n\nExample: Chaque jour à 03:00\n```js\nCRON('0 3 * * *', function(date) {\n\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n});\n```\n\nExample: Jours ouvrés\n```js\nCRON('30 8 * * mo-fr', function() {\n\tMAIL(CONF.mail_report, 'Daily report', 'mail/report', {});\n});\n```\n\nExample: Toutes les 15 minutes\n```js\nCRON('*/15 * * * *', function() {\n\t// at minutes 0, 15, 30 and 45\n});\n```\n\n### cron.remove()\n\nType: `method`\n\nArrête un cron.\n\nRetire de `F.crons` le cron renvoyé par `CRON()`, qui ne s'exécute donc plus.\n\nExample: Exécuter une seule fois\n```js\nvar cron = CRON('0 12 * * *', function() {\n\tsendreport();\n\tcron.remove();\n});\n```\n\n### F.crons\n\nType: `property`\n\nLes crons enregistrés.\n\nReturns: `Array`\n\nUn tableau des objets renvoyés par `CRON()`, dans l'ordre de leur enregistrement. Chacun possède `check(date)` (renvoie `true` lorsque la ligne correspond), `exec(date)` (ta fonction) et `remove()`.\n\nExample: Compter\n```js\nconsole.log(F.crons.length + ' crons');\n```\n\n### ON(name, fn)\n\nType: `method`\n\nAjoute un écouteur d'un événement global.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement, ou plusieurs noms joints avec `+`. |\n| `fn` | `Function` | yes |  | L'écouteur ; il reçoit les arguments de `EMIT()`. |\n\nJoins plusieurs noms avec `+` pour ajouter le même écouteur à chacun d'eux. Un écouteur de `ready` ajouté après le chargement de l'application est appelé immédiatement. Dans l'écouteur, `this` vaut `F`. `F.on()` est la même méthode.\n\nExample: Événement personnalisé\n```js\nON('order.created', function(order) {\n\tconsole.log('New order', order.id);\n});\n```\n\nExample: Plusieurs événements\n```js\nON('ready + service', function() {\n\trefreshcache();\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nAjoute un écouteur qui ne s'exécute qu'une seule fois.\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\nL'écouteur est retiré après la première émission de l'événement. Les noms joints avec `+` fonctionnent comme dans `ON()`, et un écouteur de `ready` ajouté après le chargement s'exécute immédiatement. `F.once()` est la même méthode.\n\nExample: Première minute\n```js\nONCE('service', function() {\n\tconsole.log('The first minute has passed');\n});\n```\n\n### OFF(name, [fn])\n\nType: `method`\n\nRetire un écouteur d'un événement global.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement. |\n| `fn` | `Function` | no |  | L'écouteur à retirer. |\n\nAvec `fn`, retire cet écouteur ; il doit s'agir de la même fonction que celle passée à `ON()`. Sans `fn`, retire tous les écouteurs de l'événement, y compris ceux du framework. `F.off()` est la même méthode.\n\nExample: Retirer un écouteur\n```js\nfunction onservice(counter) {\n\tif (counter === 60)\n\t\tOFF('service', onservice);\n}\n\nON('service', onservice);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nÉmet un événement global.\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\nAppelle tous les écouteurs de `name` dans l'ordre de leur ajout, de manière synchrone, avec jusqu'à sept arguments. Les écouteurs ajoutés avec `ONCE()` sont ensuite retirés. `F.emit()` est la même méthode.\n\nExample: Émettre\n```js\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\n### setTimeout2(id, callback, timeout, [limit])\n\nType: `method`\n\nUn minuteur nommé qui redémarre à chaque appel (un debounce).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Le nom du minuteur. |\n| `callback` | `Function` | yes |  | La fonction à exécuter. |\n| `timeout` | `Number` | yes |  | Le délai en millisecondes. |\n| `limit` | `Number` | no | `0` | Combien de fois le minuteur peut être reporté avant qu'un appel exécute le callback immédiatement. `0` signifie aucune limite. |\n\nSi un minuteur avec le même `id` est en attente, il est annulé et un nouveau minuteur démarre avec le nouveau `callback`. Le callback ne s'exécute qu'après `timeout` millisecondes sans nouvel appel avec cet `id`.\n\nAvec `limit`, le minuteur ne peut être reporté que `limit` fois : l'appel suivant annule le minuteur et exécute son callback immédiatement, et le comptage recommence. Utilise-le quand le callback doit s'exécuter de temps en temps même si les appels ne s'arrêtent pas.\n\nExample: Enregistrer une seule fois après des modifications\n```js\nfunction changed(doc) {\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nExample: Avec une limite\n```js\nfunction onkey(text) {\n\t// searches after a pause of 300 ms, or at once when the timer has been postponed 10 times\n\tsetTimeout2('search', function() {\n\t\tsearch(text);\n\t}, 300, 10);\n}\n```\n\n### clearTimeout2(id)\n\nType: `method`\n\nAnnule un minuteur nommé de setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Le nom du minuteur. |\n\nReturns: `Boolean` `true` lorsqu'un minuteur était en attente.\n\nLe callback du minuteur ne s'exécute pas.\n\nExample: Annuler\n```js\nif (clearTimeout2('save' + doc.id))\n\tconsole.log('The pending save was canceled');\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method`\n\nAppelle une fonction lorsqu'un flux est terminé et détruit le flux.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Un flux lisible ou inscriptible. |\n| `callback` | `Function` | no |  | Appelée lorsque le flux est terminé. |\n\nReturns: `Promise` Sans callback.\n\nLe callback s'exécute une seule fois, au premier des événements `end`, `finish`, `close`, `aborted` ou `error` (pour une réponse, également lorsque son socket se ferme ou échoue). Le flux est détruit et son descripteur de fichier ouvert est fermé à ce moment-là. Sans callback, renvoie une promesse. `F.cleanup()` est la même méthode.\n\nExample: Attendre un fichier\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.end('id;name\\n');\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\nExample: Avec await\n```js\nawait CLEANUP(writer);\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nMet en pause tout le trafic entrant sous un nom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom désignant la raison, affiché sur la page. |\n| `enable` | `Boolean` | no |  | `true` pour mettre en pause, `false` pour reprendre ; bascule s'il est omis. |\n\nReturns: `Boolean` `true` lorsque le nom est en pause après l'appel.\n\nTant qu'au moins un nom est en pause, chaque requête HTTP reçoit le statut `503` : les navigateurs voient une page « Please wait » avec les noms en pause, qui se recharge d'elle-même au bout de 10 secondes, les requêtes XHR reçoivent une réponse d'erreur et les nouvelles connexions WebSocket sont fermées. `enable` à `true` ajoute le nom, `false` le retire ; sans `enable`, le nom est basculé. `F.pauseserver()` est la même méthode.\n\nExample: Pendant une migration\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\n### F.paused\n\nType: `property`\n\nLes noms mis en pause avec PAUSESERVER().\n\nReturns: `Array`\n\nUn tableau de chaînes. Le serveur répond avec `503` tant qu'il n'est pas vide.\n\nExample: Vérifier\n```js\nif (F.paused.length)\n\tconsole.log('Paused:', F.paused.join(', '));\n```\n\n### ON('ready', function() {})\n\nType: `event`\n\nL'application est chargée.\n\nÉmis après le chargement de la configuration, des modules, des actions, des contrôleurs, des plugins et des autres parties, et après le démarrage du minuteur de service. Un écouteur ajouté après ce moment s'exécute immédiatement.\n\nExample: Démarrage\n```js\nON('ready', function() {\n\tconsole.log('Ready on port', CONF.$port);\n});\n```\n\n### ON('load', function() {})\n\nType: `event`\n\nÉmis juste après ready.\n\nÉmis une fois après `ready`, lorsque le chargement de l'application est terminé. Contrairement à `ready`, un écouteur ajouté plus tard n'est pas appelé.\n\nExample: Chargement\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('service', function(counter) {})\n\nType: `event`\n\nÉmis une fois par minute par le minuteur de service.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Minutes écoulées depuis le démarrage. |\n\nÉmis après les tâches de maintenance de la minute et après l'exécution des crons. `counter` est le nombre de minutes écoulées depuis le démarrage : `1`, `2`, `3`… ; utilise `counter % n` pour des intervalles plus longs.\n\nExample: Toutes les 10 minutes\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\trefresh();\n});\n```\n\n### ON('exit', function(signal) {})\n\nType: `event`\n\nLe processus s'arrête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | yes |  | Le signal passé à `F.exit()` ; `15` par défaut. |\n\nÉmis par `F.exit()` sur `SIGTERM`, `SIGINT`, la sortie du processus ou un message `stop` du parent, après l'arrêt des workers et des FlowStreams. Le travail effectué dans l'écouteur doit être synchrone : le processus se termine juste après.\n\nExample: Dernier log\n```js\nON('exit', function(signal) {\n\tconsole.log('Exit', signal);\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: String, name: String, url: String, date: Date }`. |\n\nÉmis par le `DEF.onError` par défaut pour chaque erreur passée à `F.error()` ainsi que pour les exceptions et les rejets non gérés. `obj` vaut `{ error, name, url, date }`, où `error` est l'erreur sous forme de chaîne. Les 10 dernières erreurs se trouvent aussi dans `F.errors`.\n\nExample: Envoyer les erreurs ailleurs\n```js\nON('error', function(obj) {\n\tconsole.log(obj.date, obj.name, obj.error, obj.url);\n});\n```\n\n### ON('request', function(ctrl) {})\n\nType: `event`\n\nUne requête HTTP est arrivée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | Le contrôleur de la requête. |\n\nÉmis pour chaque requête HTTP avant CORS et le routage. Les requêtes arrêtées plus tôt (un serveur en pause, une adresse IP bloquée, la limite de requêtes, un proxy) ne l'atteignent pas. `ctrl` est le contrôleur de la requête. Appelle `ctrl.cancel()` pour arrêter le traitement et répondre toi-même à la requête.\n\nExample: Vérification de santé\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n### ON('controller', function(ctrl) {})\n\nType: `event`\n\nUne route a été trouvée pour une requête HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | Le contrôleur de la requête. |\n\nÉmis une fois la route trouvée et le corps analysé, juste avant l'exécution de l'action de la route (également pour les routes API). `ctrl.route` est la route. Appelle `ctrl.cancel()` pour arrêter le traitement et répondre toi-même à la requête.\n\nExample: Journaliser les routes\n```js\nON('controller', function(ctrl) {\n\tconsole.log(ctrl.method, ctrl.url);\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: String, components: String }`. |\n\n`meta` vaut `{ name, components }`. Modifie `meta.components` pour changer la liste des composants téléchargés.\n\nExample: Ajouter un composant\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',exec';\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nUn composant d'un FlowStream a échoué.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ id, name, error, source, instanceid, componentid }`. |\n\nÉmis pour les erreurs des composants FlowStream, après l'affichage de l'erreur dans la console. `meta` vaut `{ id, name, error, source, instanceid, componentid }` : le FlowStream, son nom, l'erreur, l'endroit où elle s'est produite, ainsi que l'instance et le composant.\n\nExample: Journaliser\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### ON('flowstream', function(instance) {})\n\nType: `event` · Since: `0.0.16`\n\nUne instance FlowStream a été créée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | L'instance FlowStream. |\n\nÉmis quand un FlowStream est créé, dans le processus principal ou dans un worker ; `instance` est l'objet avec lequel tu contrôles le FlowStream. Voir [FlowStream](../../guides/flowstream/).\n\nExample: Journaliser\n```js\nON('flowstream', function(instance) {\n\tconsole.log('FlowStream', instance.id);\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` | `Object` | yes |  | Le message e-mail. |\n\nÉmis pour chaque message juste avant son écriture sur la connexion SMTP. `message` est le message e-mail (`subject`, `body`, `email_to`, `email_from`…). Voir [Mail](../../guides/mail/).\n\nExample: Journaliser\n```js\nON('$mail', function(message) {\n\tconsole.log('Mail', message.subject, message.email_to);\n});\n```\n\n### ON('$stats', function(stats) {})\n\nType: `event`\n\nLes statistiques d'utilisation du processus ont été mises à jour.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stats` | `Object` | yes |  | Les statistiques du processus. |\n\nÉmis 5 secondes après le chargement de l'application, puis une fois par minute par le timer de service, chaque fois après le calcul des statistiques de la dernière minute. `stats` est le même objet à chaque fois ; lis-le, ne garde pas de référence à ses valeurs.\n\nLes principaux champs : `id` et `pid` (le processus), `date`, `memory` (heap utilisé en Mo), `requests`, `pending`, `errors`, `timeouts`, `online` (clients WebSocket), `download` et `upload` (Mo au total), `lasterror`, `lasttimeout`, `uptime` (minutes depuis le démarrage), `overload` (nombre d'heures pendant lesquelles le processus a été surchargé), `mode` (`debug` ou `release`) et `version` (`node`, `total`, `build`, `app`). Les champs se terminant par `m` comptent la dernière minute : `rm` requêtes, `fm` fichiers, `wm` messages WebSocket, `em` requêtes externes, `mm` e-mails, `om` fichiers ouverts, `dm`/`um` Mo téléchargés/envoyés, `pm`/`sm` messages publiés/souscrits, `cm` appels, `dbrm`/`dbwm` lectures/écritures en base de données.\n\nExample: Surveiller la mémoire\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory', stats.memory, 'MB');\n});\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nLe processus a reçu un message de son parent.\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 qui arrive par `process.on('message')`, après que le framework a traité ses propres messages (`total:...`, `stop`). Utile lorsque l'application s'exécute comme processus enfant ou dans un cluster.\n\nExample: Commande\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'reload')\n\t\treload();\n});\n```\n\n### ON('$update', function() {})\n\nType: `event`\n\nUn autre processus du cluster a demandé une mise à jour.\n\nÉmis lorsque le processus reçoit le message `total:update`. Dans un cluster, un processus qui envoie `process.send('total:update')` amène le processus principal à le transmettre aux autres processus prêts, afin que chacun d'eux puisse recharger ses données.\n\nExample: Garder un cluster synchronisé\n```js\n// the process that changed the data\nprocess.send && process.send('total:update');\n\n// all other processes\nON('$update', function() {\n\treloadsettings();\n});\n```\n","entries":[{"type":"method","name":"CRON()","signature":"CRON(line, fn)","since":"","deprecated":false},{"type":"method","name":"cron.remove()","signature":"cron.remove()","since":"","deprecated":false},{"type":"property","name":"F.crons","signature":"F.crons","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":"setTimeout2()","signature":"setTimeout2(id, callback, timeout, [limit])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(id)","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"property","name":"F.paused","signature":"F.paused","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function() {})","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', 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('error')","signature":"ON('error', function(obj) {})","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(instance) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail', function(message) {})","since":"","deprecated":false},{"type":"event","name":"ON('$stats')","signature":"ON('$stats', function(stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"event","name":"ON('$update')","signature":"ON('$update', function() {})","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvoAcx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Pianificazione ed eventi","summary":"CRON(), ON(), ONCE(), OFF(), EMIT(), gli eventi integrati, setTimeout2(), CLEANUP() e PAUSESERVER().","markdown":"---\ntitle: Pianificazione ed eventi\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/scheduling-and-events/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Pianificazione ed eventi\n\n> CRON(), ON(), ONCE(), OFF(), EMIT(), gli eventi integrati, setTimeout2(), CLEANUP() e PAUSESERVER().\n\nFunzioni globali per codice pianificato e guidato dagli eventi: `CRON()` esegue funzioni secondo una riga cron, `ON()`, `ONCE()`, `OFF()` ed `EMIT()` lavorano con gli eventi globali, e il framework emette i propri eventi come `ready`, `service`, `exit` ed `error`. `setTimeout2()` e `clearTimeout2()` forniscono timer con nome e debounce, `CLEANUP()` attende uno stream e `PAUSESERVER()` trattiene il traffico in arrivo.\n\nLa guida [Pianificazione ed eventi](../../guides/scheduling-and-events/) spiega come funzionano insieme.\n\n## API\n\n### CRON(line, fn)\n\nType: `method`\n\nEsegue una funzione quando la data corrisponde a una riga cron.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | La riga cron, ad esempio `0 3 * * *`. |\n| `fn` | `Function` | yes |  | `function(date)`, chiamata quando la riga corrisponde. |\n\nReturns: `Object` Il cron, con `check(date)`, `exec(date)` e `remove()`.\n\nLa riga ha cinque campi: minuto, ora, giorno del mese, mese e giorno della settimana (`0`–`6`, oppure `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`). Ogni campo è `*`, un numero, un elenco (`1,15`), un intervallo (`8-17`) o un passo: `*/15` corrisponde a ogni 15° valore a partire dal primo valore del campo (minuti `0`, `15`, `30`, `45`; giorni del mese `1`, `16`, `31`) e `5/20` a ogni 20° valore a partire da `5` (`5`, `25`, `45`). I cron vengono controllati una volta al minuto dal timer di servizio e `fn` riceve la data corrente (`NOW`). Ore e giorni seguono il fuso orario del processo (`$timezone`, predefinito `utc`).\n\nExample: Ogni giorno alle 03:00\n```js\nCRON('0 3 * * *', function(date) {\n\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n});\n```\n\nExample: Giorni lavorativi\n```js\nCRON('30 8 * * mo-fr', function() {\n\tMAIL(CONF.mail_report, 'Daily report', 'mail/report', {});\n});\n```\n\nExample: Ogni 15 minuti\n```js\nCRON('*/15 * * * *', function() {\n\t// at minutes 0, 15, 30 and 45\n});\n```\n\n### cron.remove()\n\nType: `method`\n\nFerma un cron.\n\nRimuove da `F.crons` il cron restituito da `CRON()`, così non viene più eseguito.\n\nExample: Eseguire una sola volta\n```js\nvar cron = CRON('0 12 * * *', function() {\n\tsendreport();\n\tcron.remove();\n});\n```\n\n### F.crons\n\nType: `property`\n\nI cron registrati.\n\nReturns: `Array`\n\nUn array degli oggetti restituiti da `CRON()`, nell'ordine in cui sono stati registrati. Ognuno ha `check(date)` (restituisce `true` quando la riga corrisponde), `exec(date)` (la tua funzione) e `remove()`.\n\nExample: Conteggio\n```js\nconsole.log(F.crons.length + ' crons');\n```\n\n### ON(name, fn)\n\nType: `method`\n\nAggiunge un listener di un evento globale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento, o più nomi uniti con `+`. |\n| `fn` | `Function` | yes |  | Il listener; riceve gli argomenti di `EMIT()`. |\n\nUnisci più nomi con `+` per aggiungere lo stesso listener a ciascuno di essi. Un listener di `ready` aggiunto dopo il caricamento dell'applicazione viene chiamato subito. All'interno del listener `this` è `F`. `F.on()` è lo stesso metodo.\n\nExample: Evento proprio\n```js\nON('order.created', function(order) {\n\tconsole.log('New order', order.id);\n});\n```\n\nExample: Più eventi\n```js\nON('ready + service', function() {\n\trefreshcache();\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nAggiunge un listener che viene eseguito una sola volta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento. |\n| `fn` | `Function` | yes |  | Il listener. |\n\nIl listener viene rimosso dopo la prima emissione dell'evento. I nomi uniti con `+` funzionano come in `ON()`, e un listener di `ready` aggiunto dopo il caricamento viene eseguito subito. `F.once()` è lo stesso metodo.\n\nExample: Primo minuto\n```js\nONCE('service', function() {\n\tconsole.log('The first minute has passed');\n});\n```\n\n### OFF(name, [fn])\n\nType: `method`\n\nRimuove un listener di un evento globale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento. |\n| `fn` | `Function` | no |  | Il listener da rimuovere. |\n\nCon `fn`, rimuove quel listener; deve essere la stessa funzione passata a `ON()`. Senza `fn`, rimuove tutti i listener dell'evento, compresi quelli del framework. `F.off()` è lo stesso metodo.\n\nExample: Rimuovere un listener\n```js\nfunction onservice(counter) {\n\tif (counter === 60)\n\t\tOFF('service', onservice);\n}\n\nON('service', onservice);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nEmette un evento globale.\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\nChiama tutti i listener di `name` nell'ordine in cui sono stati aggiunti, in modo sincrono, con al massimo sette argomenti. I listener aggiunti con `ONCE()` vengono poi rimossi. `F.emit()` è lo stesso metodo.\n\nExample: Emettere\n```js\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\n### setTimeout2(id, callback, timeout, [limit])\n\nType: `method`\n\nUn timer con nome che riparte a ogni chiamata (un debounce).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Il nome del timer. |\n| `callback` | `Function` | yes |  | La funzione da eseguire. |\n| `timeout` | `Number` | yes |  | Il ritardo in millisecondi. |\n| `limit` | `Number` | no | `0` | Quante volte il timer può essere rinviato prima che una chiamata esegua subito la callback. `0` significa nessun limite. |\n\nSe un timer con lo stesso `id` è in attesa, viene annullato e parte un nuovo timer con la nuova `callback`. La callback viene eseguita solo dopo `timeout` millisecondi senza una nuova chiamata con quell'`id`.\n\nCon `limit`, il timer può essere rinviato solo `limit` volte: la chiamata successiva annulla il timer ed esegue subito la sua callback, e il conteggio ricomincia. Usalo quando la callback deve essere eseguita di tanto in tanto anche mentre le chiamate non si fermano.\n\nExample: Salvare una volta dopo le modifiche\n```js\nfunction changed(doc) {\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nExample: Con un limite\n```js\nfunction onkey(text) {\n\t// searches after a pause of 300 ms, or at once when the timer has been postponed 10 times\n\tsetTimeout2('search', function() {\n\t\tsearch(text);\n\t}, 300, 10);\n}\n```\n\n### clearTimeout2(id)\n\nType: `method`\n\nAnnulla un timer con nome di setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Il nome del timer. |\n\nReturns: `Boolean` `true` quando un timer era in attesa.\n\nLa callback del timer non viene eseguita.\n\nExample: Annullare\n```js\nif (clearTimeout2('save' + doc.id))\n\tconsole.log('The pending save was canceled');\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method`\n\nChiama una funzione quando uno stream è terminato e distrugge lo stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Uno stream leggibile o scrivibile. |\n| `callback` | `Function` | no |  | Chiamata quando lo stream è terminato. |\n\nReturns: `Promise` Senza callback.\n\nLa callback viene eseguita una volta, al primo tra `end`, `finish`, `close`, `aborted` o `error` (per una risposta, anche quando il suo socket si chiude o fallisce). In quel momento lo stream viene distrutto e il suo descrittore di file aperto viene chiuso. Senza callback, restituisce una promise. `F.cleanup()` è lo stesso metodo.\n\nExample: Attendere un file\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.end('id;name\\n');\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\nExample: Con await\n```js\nawait CLEANUP(writer);\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nMette in pausa tutto il traffico in arrivo sotto un nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome del motivo, mostrato sulla pagina. |\n| `enable` | `Boolean` | no |  | `true` per mettere in pausa, `false` per riprendere; alterna se omesso. |\n\nReturns: `Boolean` `true` quando il nome è in pausa dopo la chiamata.\n\nFinché almeno un nome è in pausa, ogni richiesta HTTP riceve lo stato `503`: i browser vedono una pagina \"Please wait\" con i nomi in pausa che si ricarica da sola dopo 10 secondi, le richieste XHR ricevono una risposta di errore e le nuove connessioni WebSocket vengono chiuse. `enable` `true` aggiunge il nome, `false` lo rimuove; senza `enable` il nome viene alternato. `F.pauseserver()` è lo stesso metodo.\n\nExample: Durante una migrazione\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\n### F.paused\n\nType: `property`\n\nI nomi messi in pausa con PAUSESERVER().\n\nReturns: `Array`\n\nUn array di stringhe. Il server risponde con `503` finché non è vuoto.\n\nExample: Controllare\n```js\nif (F.paused.length)\n\tconsole.log('Paused:', F.paused.join(', '));\n```\n\n### ON('ready', function() {})\n\nType: `event`\n\nL'applicazione è caricata.\n\nEmesso dopo che la configurazione, i moduli, le azioni, i controller, i plugin e le altre parti sono stati caricati e il timer di servizio è avviato. Un listener aggiunto dopo quel momento viene eseguito subito.\n\nExample: Avvio\n```js\nON('ready', function() {\n\tconsole.log('Ready on port', CONF.$port);\n});\n```\n\n### ON('load', function() {})\n\nType: `event`\n\nEmesso subito dopo ready.\n\nEmesso una volta dopo `ready`, quando il caricamento dell'applicazione è completo. A differenza di `ready`, un listener aggiunto più tardi non viene chiamato.\n\nExample: Caricamento\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('service', function(counter) {})\n\nType: `event`\n\nEmesso una volta al minuto dal timer di servizio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Minuti dall'avvio. |\n\nEmesso dopo le operazioni di manutenzione del minuto e dopo l'esecuzione dei cron. `counter` è il numero di minuti dall'avvio: `1`, `2`, `3`…; usa `counter % n` per intervalli più lunghi.\n\nExample: Ogni 10 minuti\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\trefresh();\n});\n```\n\n### ON('exit', function(signal) {})\n\nType: `event`\n\nIl processo si sta arrestando.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | yes |  | Il segnale passato a `F.exit()`; `15` per impostazione predefinita. |\n\nEmesso da `F.exit()` su `SIGTERM`, `SIGINT`, l'uscita del processo o un messaggio `stop` dal processo padre, dopo che i worker e i FlowStream sono stati fermati. Il lavoro svolto nel listener deve essere sincrono: il processo termina subito dopo.\n\nExample: Ultimo log\n```js\nON('exit', function(signal) {\n\tconsole.log('Exit', signal);\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: String, name: String, url: String, date: Date }`. |\n\nEmesso dal `DEF.onError` predefinito per ogni errore passato a `F.error()` e per le eccezioni e i rifiuti non gestiti. `obj` è `{ error, name, url, date }`, dove `error` è l'errore come stringa. Gli ultimi 10 errori sono anche in `F.errors`.\n\nExample: Inviare gli errori altrove\n```js\nON('error', function(obj) {\n\tconsole.log(obj.date, obj.name, obj.error, obj.url);\n});\n```\n\n### ON('request', function(ctrl) {})\n\nType: `event`\n\nÈ arrivata una richiesta HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | Il controller della richiesta. |\n\nEmesso per ogni richiesta HTTP prima di CORS e del routing. Le richieste fermate prima (un server in pausa, un indirizzo IP bloccato, il limite di richieste, un proxy) non lo raggiungono. `ctrl` è il controller della richiesta. Chiama `ctrl.cancel()` per fermare l'elaborazione e rispondere tu stesso alla richiesta.\n\nExample: Health check\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n### ON('controller', function(ctrl) {})\n\nType: `event`\n\nÈ stata trovata una route per una richiesta HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | Il controller della richiesta. |\n\nEmesso dopo che la route è stata trovata e il body è stato analizzato, subito prima che venga eseguita l'azione della route (anche per le route API). `ctrl.route` è la route. Chiama `ctrl.cancel()` per fermare l'elaborazione e rispondere tu stesso alla richiesta.\n\nExample: Registrare le route nel log\n```js\nON('controller', function(ctrl) {\n\tconsole.log(ctrl.method, ctrl.url);\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: String, components: String }`. |\n\n`meta` è `{ name, components }`. Modifica `meta.components` per cambiare l'elenco dei componenti da scaricare.\n\nExample: Aggiungere un componente\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',exec';\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nUn componente di un FlowStream ha generato un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ id, name, error, source, instanceid, componentid }`. |\n\nEmesso per gli errori dei componenti FlowStream, dopo che l'errore è stato stampato nella console. `meta` è `{ id, name, error, source, instanceid, componentid }`: il FlowStream, il suo nome, l'errore, dove si è verificato, l'istanza e il componente.\n\nExample: Log\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### ON('flowstream', function(instance) {})\n\nType: `event` · Since: `0.0.16`\n\nÈ stata creata un'istanza di FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | L'istanza di FlowStream. |\n\nEmesso quando viene creato un FlowStream, nel processo principale o in un worker; `instance` è l'oggetto con cui controlli il FlowStream. Vedi [FlowStream](../../guides/flowstream/).\n\nExample: Log\n```js\nON('flowstream', function(instance) {\n\tconsole.log('FlowStream', instance.id);\n});\n```\n\n### ON('$mail', function(message) {})\n\nType: `event`\n\nUn'e-mail sta per essere inviata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | Il messaggio di posta. |\n\nEmesso per ogni messaggio subito prima che venga scritto sulla connessione SMTP. `message` è il messaggio di posta (`subject`, `body`, `email_to`, `email_from`…). Vedi [Mail](../../guides/mail/).\n\nExample: Log\n```js\nON('$mail', function(message) {\n\tconsole.log('Mail', message.subject, message.email_to);\n});\n```\n\n### ON('$stats', function(stats) {})\n\nType: `event`\n\nLe statistiche di utilizzo del processo sono state aggiornate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stats` | `Object` | yes |  | Le statistiche del processo. |\n\nEmesso 5 secondi dopo il caricamento dell'applicazione e poi una volta al minuto dal timer di servizio, ogni volta dopo il calcolo delle statistiche dell'ultimo minuto. `stats` è sempre lo stesso oggetto; leggilo, non conservare riferimenti ai suoi valori.\n\nI campi principali: `id` e `pid` (il processo), `date`, `memory` (heap usato in MB), `requests`, `pending`, `errors`, `timeouts`, `online` (client WebSocket), `download` e `upload` (MB in totale), `lasterror`, `lasttimeout`, `uptime` (minuti dall'avvio), `overload` (per quante ore il processo è stato sovraccarico), `mode` (`debug` o `release`) e `version` (`node`, `total`, `build`, `app`). I campi che terminano con `m` contano l'ultimo minuto: `rm` richieste, `fm` file, `wm` messaggi WebSocket, `em` richieste esterne, `mm` e-mail, `om` file aperti, `dm`/`um` MB scaricati/caricati, `pm`/`sm` messaggi pubblicati/sottoscritti, `cm` chiamate, `dbrm`/`dbwm` letture/scritture del database.\n\nExample: Monitorare la memoria\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory', stats.memory, 'MB');\n});\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nIl processo ha ricevuto un messaggio dal processo padre.\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 arriva tramite `process.on('message')`, dopo che il framework ha gestito i propri messaggi (`total:...`, `stop`). Utile quando l'applicazione gira come processo figlio o in un cluster.\n\nExample: Comando\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'reload')\n\t\treload();\n});\n```\n\n### ON('$update', function() {})\n\nType: `event`\n\nUn altro processo del cluster ha richiesto un aggiornamento.\n\nEmesso quando il processo riceve il messaggio `total:update`. In un cluster, un processo che invia `process.send('total:update')` fa sì che il processo principale lo inoltri agli altri processi pronti, così ognuno di essi può ricaricare i propri dati.\n\nExample: Mantenere sincronizzato un cluster\n```js\n// the process that changed the data\nprocess.send && process.send('total:update');\n\n// all other processes\nON('$update', function() {\n\treloadsettings();\n});\n```\n","entries":[{"type":"method","name":"CRON()","signature":"CRON(line, fn)","since":"","deprecated":false},{"type":"method","name":"cron.remove()","signature":"cron.remove()","since":"","deprecated":false},{"type":"property","name":"F.crons","signature":"F.crons","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":"setTimeout2()","signature":"setTimeout2(id, callback, timeout, [limit])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(id)","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"property","name":"F.paused","signature":"F.paused","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function() {})","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', 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('error')","signature":"ON('error', function(obj) {})","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(instance) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail', function(message) {})","since":"","deprecated":false},{"type":"event","name":"ON('$stats')","signature":"ON('$stats', function(stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"event","name":"ON('$update')","signature":"ON('$update', function() {})","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvoAcx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/scheduling-and-events/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Plánovanie a udalosti","summary":"CRON(), ON(), ONCE(), OFF(), EMIT(), vstavané udalosti, setTimeout2(), CLEANUP() a PAUSESERVER().","markdown":"---\ntitle: \"Plánovanie a udalosti\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/scheduling-and-events/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Plánovanie a udalosti\n\n> CRON(), ON(), ONCE(), OFF(), EMIT(), vstavané udalosti, setTimeout2(), CLEANUP() a PAUSESERVER().\n\nGlobálne funkcie pre plánovaný kód a kód riadený udalosťami: `CRON()` spúšťa funkcie podľa cron riadku, `ON()`, `ONCE()`, `OFF()` a `EMIT()` pracujú s globálnymi udalosťami a framework vysiela vlastné udalosti, napríklad `ready`, `service`, `exit` a `error`. `setTimeout2()` a `clearTimeout2()` poskytujú pomenované časovače s debounce, `CLEANUP()` čaká na stream a `PAUSESERVER()` zadrží prichádzajúcu prevádzku.\n\nPríručka [Plánovanie a udalosti](../../guides/scheduling-and-events/) vysvetľuje, ako spolu fungujú.\n\n## API\n\n### CRON(line, fn)\n\nType: `method`\n\nSpustí funkciu, keď dátum zodpovedá cron riadku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Cron riadok, napr. `0 3 * * *`. |\n| `fn` | `Function` | yes |  | `function(date)`, volá sa, keď riadok zodpovedá. |\n\nReturns: `Object` Cron s metódami `check(date)`, `exec(date)` a `remove()`.\n\nRiadok má päť polí: minúta, hodina, deň v mesiaci, mesiac a deň v týždni (`0`–`6` alebo `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`). Každé pole je `*`, číslo, zoznam (`1,15`), rozsah (`8-17`) alebo krok: `*/15` zodpovedá každej 15. hodnote od prvej hodnoty poľa (minúty `0`, `15`, `30`, `45`; dni v mesiaci `1`, `16`, `31`) a `5/20` každej 20. hodnote od `5` (`5`, `25`, `45`). Crony kontroluje servisný časovač raz za minútu a `fn` dostane aktuálny dátum (`NOW`). Hodiny a dni sa riadia časovým pásmom procesu (`$timezone`, predvolene `utc`).\n\nExample: Každý deň o 03:00\n```js\nCRON('0 3 * * *', function(date) {\n\tNOSQL('logs').remove().where('date', '<', date.add('-30 days'));\n});\n```\n\nExample: Pracovné dni\n```js\nCRON('30 8 * * mo-fr', function() {\n\tMAIL(CONF.mail_report, 'Daily report', 'mail/report', {});\n});\n```\n\nExample: Každých 15 minút\n```js\nCRON('*/15 * * * *', function() {\n\t// at minutes 0, 15, 30 and 45\n});\n```\n\n### cron.remove()\n\nType: `method`\n\nZastaví cron.\n\nOdstráni cron vrátený z `CRON()` z `F.crons`, takže sa už nespustí.\n\nExample: Spustiť raz\n```js\nvar cron = CRON('0 12 * * *', function() {\n\tsendreport();\n\tcron.remove();\n});\n```\n\n### F.crons\n\nType: `property`\n\nZaregistrované crony.\n\nReturns: `Array`\n\nPole objektov vrátených z `CRON()` v poradí, v akom boli zaregistrované. Každý má `check(date)` (vráti `true`, keď riadok zodpovedá), `exec(date)` (tvoja funkcia) a `remove()`.\n\nExample: Počet\n```js\nconsole.log(F.crons.length + ' crons');\n```\n\n### ON(name, fn)\n\nType: `method`\n\nPridá poslucháča globálnej udalosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti alebo viac názvov spojených pomocou `+`. |\n| `fn` | `Function` | yes |  | Poslucháč; dostane argumenty z `EMIT()`. |\n\nSpoj viac názvov pomocou `+`, ak chceš pridať rovnakého poslucháča ku každému z nich. Poslucháč udalosti `ready` pridaný po načítaní aplikácie sa zavolá okamžite. Vnútri poslucháča je `this` rovné `F`. `F.on()` je tá istá metóda.\n\nExample: Vlastná udalosť\n```js\nON('order.created', function(order) {\n\tconsole.log('New order', order.id);\n});\n```\n\nExample: Viac udalostí\n```js\nON('ready + service', function() {\n\trefreshcache();\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nPridá poslucháča, ktorý sa spustí iba raz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `fn` | `Function` | yes |  | Poslucháč. |\n\nPoslucháč sa odstráni po prvom vyslaní udalosti. Názvy spojené pomocou `+` fungujú ako v `ON()` a poslucháč `ready` pridaný po načítaní sa spustí okamžite. `F.once()` je tá istá metóda.\n\nExample: Prvá minúta\n```js\nONCE('service', function() {\n\tconsole.log('The first minute has passed');\n});\n```\n\n### OFF(name, [fn])\n\nType: `method`\n\nOdstráni poslucháča globálnej udalosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `fn` | `Function` | no |  | Poslucháč, ktorý sa má odstrániť. |\n\nS `fn` odstráni daného poslucháča; musí to byť tá istá funkcia, ktorá bola odovzdaná do `ON()`. Bez `fn` odstráni všetkých poslucháčov udalosti vrátane poslucháčov frameworku. `F.off()` je tá istá metóda.\n\nExample: Odstránenie poslucháča\n```js\nfunction onservice(counter) {\n\tif (counter === 60)\n\t\tOFF('service', onservice);\n}\n\nON('service', onservice);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nVyšle globálnu udalosť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `a...g` | `Object` | no |  | Najviac sedem argumentov pre poslucháčov. |\n\nZavolá všetkých poslucháčov udalosti `name` v poradí, v akom boli pridaní, synchrónne, s najviac siedmimi argumentmi. Poslucháči pridaní pomocou `ONCE()` sa potom odstránia. `F.emit()` je tá istá metóda.\n\nExample: Vyslanie\n```js\nEMIT('order.created', { id: 123, email: 'buyer@example.com' });\n```\n\n### setTimeout2(id, callback, timeout, [limit])\n\nType: `method`\n\nPomenovaný časovač, ktorý sa pri každom volaní reštartuje (debounce).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Názov časovača. |\n| `callback` | `Function` | yes |  | Funkcia, ktorá sa má spustiť. |\n| `timeout` | `Number` | yes |  | Oneskorenie v milisekundách. |\n| `limit` | `Number` | no | `0` | Koľkokrát sa časovač dá odložiť, kým volanie hneď spustí callback. `0` znamená bez limitu. |\n\nAk čaká časovač s rovnakým `id`, zruší sa a spustí sa nový časovač s novým `callback`. Callback sa spustí až po `timeout` milisekundách bez nového volania s týmto `id`.\n\nS `limit` sa časovač dá odložiť iba `limit`-krát: ďalšie volanie časovač zruší a hneď spustí jeho callback a počítanie začne odznova. Použi to, keď sa callback musí z času na čas spustiť, aj keď volania neprestávajú.\n\nExample: Uložiť raz po zmenách\n```js\nfunction changed(doc) {\n\tsetTimeout2('save' + doc.id, function() {\n\t\tNOSQL('docs').modify(doc).where('id', doc.id);\n\t}, 2000);\n}\n```\n\nExample: S limitom\n```js\nfunction onkey(text) {\n\t// searches after a pause of 300 ms, or at once when the timer has been postponed 10 times\n\tsetTimeout2('search', function() {\n\t\tsearch(text);\n\t}, 300, 10);\n}\n```\n\n### clearTimeout2(id)\n\nType: `method`\n\nZruší pomenovaný časovač zo setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Názov časovača. |\n\nReturns: `Boolean` `true`, keď nejaký časovač čakal.\n\nCallback časovača sa nespustí.\n\nExample: Zrušenie\n```js\nif (clearTimeout2('save' + doc.id))\n\tconsole.log('The pending save was canceled');\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method`\n\nZavolá funkciu, keď stream skončí, a stream zničí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Stream na čítanie alebo zápis. |\n| `callback` | `Function` | no |  | Volá sa, keď stream skončí. |\n\nReturns: `Promise` Bez callbacku.\n\nCallback sa spustí raz, pri prvej z udalostí `end`, `finish`, `close`, `aborted` alebo `error` (pri odpovedi aj vtedy, keď sa jej socket zatvorí alebo zlyhá). V tej chvíli sa stream zničí a jeho otvorený file descriptor sa zatvorí. Bez callbacku vráti promise. `F.cleanup()` je tá istá metóda.\n\nExample: Čakanie na súbor\n```js\nvar writer = F.Fs.createWriteStream(PATH.temp('export.csv'));\nwriter.end('id;name\\n');\nCLEANUP(writer, function() {\n\tconsole.log('Written');\n});\n```\n\nExample: S await\n```js\nawait CLEANUP(writer);\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nPozastaví všetku prichádzajúcu prevádzku pod daným názvom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov dôvodu, zobrazený na stránke. |\n| `enable` | `Boolean` | no |  | `true` na pozastavenie, `false` na obnovenie; ak chýba, stav sa prepne. |\n\nReturns: `Boolean` `true`, keď je názov po volaní pozastavený.\n\nKým je pozastavený aspoň jeden názov, každá HTTP požiadavka dostane stav `503`: prehliadače uvidia stránku „Please wait“ s pozastavenými názvami, ktorá sa po 10 sekundách sama obnoví, XHR požiadavky dostanú chybovú odpoveď a nové WebSocket spojenia sa zatvoria. `enable` `true` názov pridá, `false` ho odstráni; bez `enable` sa názov prepne. `F.pauseserver()` je tá istá metóda.\n\nExample: Počas migrácie\n```js\nPAUSESERVER('Database migration', true);\n\nmigrate(function() {\n\tPAUSESERVER('Database migration', false);\n});\n```\n\n### F.paused\n\nType: `property`\n\nNázvy pozastavené pomocou PAUSESERVER().\n\nReturns: `Array`\n\nPole reťazcov. Kým nie je prázdne, server odpovedá stavom `503`.\n\nExample: Kontrola\n```js\nif (F.paused.length)\n\tconsole.log('Paused:', F.paused.join(', '));\n```\n\n### ON('ready', function() {})\n\nType: `event`\n\nAplikácia je načítaná.\n\nVysiela sa po načítaní konfigurácie, modulov, akcií, kontrolérov, pluginov a ostatných častí a po spustení servisného časovača. Poslucháč pridaný po tomto okamihu sa spustí okamžite.\n\nExample: Spustenie\n```js\nON('ready', function() {\n\tconsole.log('Ready on port', CONF.$port);\n});\n```\n\n### ON('load', function() {})\n\nType: `event`\n\nVysiela sa hneď po ready.\n\nVysiela sa raz po `ready`, keď je načítanie aplikácie dokončené. Na rozdiel od `ready` sa poslucháč pridaný neskôr nezavolá.\n\nExample: Načítanie\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('service', function(counter) {})\n\nType: `event`\n\nVysiela ho servisný časovač raz za minútu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Minúty od štartu. |\n\nVysiela sa po minútovej údržbe a po spustení cronov. `counter` je počet minút od štartu: `1`, `2`, `3`…; pre dlhšie kroky použi `counter % n`.\n\nExample: Každých 10 minút\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\trefresh();\n});\n```\n\n### ON('exit', function(signal) {})\n\nType: `event`\n\nProces sa zastavuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | yes |  | Signál odovzdaný do `F.exit()`; predvolene `15`. |\n\nVysiela ho `F.exit()` pri `SIGTERM`, `SIGINT`, ukončení procesu alebo správe `stop` od rodiča, po zastavení workerov a FlowStreamov. Práca v poslucháčovi musí byť synchrónna: proces skončí hneď po ňom.\n\nExample: Posledný log\n```js\nON('exit', function(signal) {\n\tconsole.log('Exit', signal);\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: String, name: String, url: String, date: Date }`. |\n\nVysiela ho predvolený `DEF.onError` pre každú chybu odovzdanú do `F.error()` a pre neošetrené výnimky a zamietnutia. `obj` je `{ error, name, url, date }`, kde `error` je chyba ako reťazec. Posledných 10 chýb je aj v `F.errors`.\n\nExample: Posielanie chýb inam\n```js\nON('error', function(obj) {\n\tconsole.log(obj.date, obj.name, obj.error, obj.url);\n});\n```\n\n### ON('request', function(ctrl) {})\n\nType: `event`\n\nPrišla HTTP požiadavka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | Kontrolér požiadavky. |\n\nVysiela sa pre každú HTTP požiadavku pred CORS a smerovaním. Požiadavky zastavené skôr (pozastavený server, blokovaná IP adresa, limit požiadaviek, proxy) sa k nej nedostanú. `ctrl` je kontrolér požiadavky. Zavolaj `ctrl.cancel()`, ak chceš zastaviť spracovanie a odpovedať na požiadavku sám.\n\nExample: Kontrola stavu\n```js\nON('request', function(ctrl) {\n\tif (ctrl.url === '/health/') {\n\t\tctrl.cancel();\n\t\tctrl.text('OK');\n\t}\n});\n```\n\n### ON('controller', function(ctrl) {})\n\nType: `event`\n\nPre HTTP požiadavku sa našla route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ctrl` | `Controller` | yes |  | Kontrolér požiadavky. |\n\nVysiela sa po nájdení route a spracovaní tela, tesne pred spustením akcie route (aj pre API route). `ctrl.route` je route. Zavolaj `ctrl.cancel()`, ak chceš zastaviť spracovanie a odpovedať na požiadavku sám.\n\nExample: Logovanie route\n```js\nON('controller', function(ctrl) {\n\tconsole.log(ctrl.method, ctrl.url);\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: String, components: String }`. |\n\n`meta` je `{ name, components }`. Zmeň `meta.components`, ak chceš zmeniť zoznam komponentov, ktorý sa stiahne.\n\nExample: Pridanie komponentu\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',exec';\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nKomponent FlowStreamu zlyhal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ id, name, error, source, instanceid, componentid }`. |\n\nVysiela sa pri chybách komponentov FlowStreamu, po vypísaní chyby do konzoly. `meta` je `{ id, name, error, source, instanceid, componentid }`: FlowStream, jeho názov, chyba, miesto, kde nastala, a inštancia a komponent.\n\nExample: Logovanie\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### ON('flowstream', function(instance) {})\n\nType: `event` · Since: `0.0.16`\n\nBola vytvorená inštancia FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | Inštancia FlowStream. |\n\nVyvolá sa, keď sa vytvorí FlowStream, v hlavnom procese alebo vo workeri; `instance` je objekt, ktorým FlowStream ovládaš. Pozri [FlowStream](../../guides/flowstream/).\n\nExample: Log\n```js\nON('flowstream', function(instance) {\n\tconsole.log('FlowStream', instance.id);\n});\n```\n\n### ON('$mail', function(message) {})\n\nType: `event`\n\nOdosiela sa e-mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | E-mailová správa. |\n\nVysiela sa pre každú správu tesne pred jej zápisom do SMTP spojenia. `message` je e-mailová správa (`subject`, `body`, `email_to`, `email_from`…). Pozri [E-mail](../../guides/mail/).\n\nExample: Logovanie\n```js\nON('$mail', function(message) {\n\tconsole.log('Mail', message.subject, message.email_to);\n});\n```\n\n### ON('$stats', function(stats) {})\n\nType: `event`\n\nŠtatistiky využitia procesu boli aktualizované.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stats` | `Object` | yes |  | Štatistiky procesu. |\n\nVysiela sa 5 sekúnd po načítaní aplikácie a potom raz za minútu servisným časovačom, vždy po výpočte štatistík za poslednú minútu. `stats` je zakaždým ten istý objekt; čítaj ho, neuchovávaj si referencie na jeho hodnoty.\n\nHlavné polia: `id` a `pid` (proces), `date`, `memory` (použitý heap v MB), `requests`, `pending`, `errors`, `timeouts`, `online` (WebSocket klienti), `download` a `upload` (MB celkovo), `lasterror`, `lasttimeout`, `uptime` (minúty od štartu), `overload` (koľko hodín bol proces preťažený), `mode` (`debug` alebo `release`) a `version` (`node`, `total`, `build`, `app`). Polia končiace na `m` počítajú poslednú minútu: `rm` požiadavky, `fm` súbory, `wm` WebSocket správy, `em` externé požiadavky, `mm` e-maily, `om` otvorené súbory, `dm`/`um` stiahnuté/nahrané MB, `pm`/`sm` publikované/odoberané správy, `cm` volania, `dbrm`/`dbwm` databázové čítania/zápisy.\n\nExample: Sledovanie pamäte\n```js\nON('$stats', function(stats) {\n\tif (stats.memory > 500)\n\t\tconsole.log('High memory', stats.memory, 'MB');\n});\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nProces dostal správu od svojho rodiča.\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\nVysiela sa pre každú správu, ktorá príde cez `process.on('message')`, potom ako framework spracoval svoje vlastné správy (`total:...`, `stop`). Užitočné, keď aplikácia beží ako podriadený proces alebo v klastri.\n\nExample: Príkaz\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'reload')\n\t\treload();\n});\n```\n\n### ON('$update', function() {})\n\nType: `event`\n\nIný proces klastra požiadal o aktualizáciu.\n\nVysiela sa, keď proces dostane správu `total:update`. V klastri proces, ktorý pošle `process.send('total:update')`, prinúti hlavný proces preposlať ju ostatným pripraveným procesom, aby si každý z nich mohol znovu načítať svoje dáta.\n\nExample: Synchronizácia klastra\n```js\n// the process that changed the data\nprocess.send && process.send('total:update');\n\n// all other processes\nON('$update', function() {\n\treloadsettings();\n});\n```\n","entries":[{"type":"method","name":"CRON()","signature":"CRON(line, fn)","since":"","deprecated":false},{"type":"method","name":"cron.remove()","signature":"cron.remove()","since":"","deprecated":false},{"type":"property","name":"F.crons","signature":"F.crons","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":"setTimeout2()","signature":"setTimeout2(id, callback, timeout, [limit])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(id)","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"property","name":"F.paused","signature":"F.paused","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function() {})","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', 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('error')","signature":"ON('error', function(obj) {})","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(ctrl) {})","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(instance) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('$mail')","signature":"ON('$mail', function(message) {})","since":"","deprecated":false},{"type":"event","name":"ON('$stats')","signature":"ON('$stats', function(stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"event","name":"ON('$update')","signature":"ON('$update', function() {})","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JaqmCK2Xc60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/file-storage/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"File storage","summary":"FILESTORAGE() and its methods, the file metadata, the @upload flag and file.fs().","markdown":"---\ntitle: File storage\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/file-storage/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# File storage\n\n> FILESTORAGE() and its methods, the file metadata, the @upload flag and file.fs().\n\nMethods of a file storage returned by `FILESTORAGE(name)` (written as `fs` below), the metadata of stored files, the route flag `@upload`, `file.fs()` for uploaded files and `Utils.filestreamer()`. For an introduction with examples read the guide [File storage](../../guides/file-storage/).\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nReturns a file storage by its name.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the storage. |\n\nReturns: `FileStorage` The file storage.\n\nCreates the storage on the first call and returns the same instance for the same name afterwards. The files are stored in `/databases/fs-{name}/`; the directory is created on the first save. Change it with `fs.storage(path)`.\n\nExample: Save and read a file\n```js\nvar fs = FILESTORAGE('files');\n\nfs.save('readme', 'readme.txt', Buffer.from('Hello'), function(err, meta) {\n\tfs.readbuffer('readme', function(err, buffer) {\n\t\tconsole.log(buffer.toString('utf8'));\n\t});\n});\n```\n\n### fs.name\n\nType: `property`\n\nThe name of the storage.\n\nReturns: `String`\n\nThe name given to `FILESTORAGE(name)`.\n\n### fs.directory\n\nType: `property`\n\nThe directory of the storage.\n\nReturns: `String`\n\nThe absolute path of the directory with the files, by default `/databases/fs-{name}/`. Set it with `fs.storage(path)`.\n\n### fs.storage(path)\n\nType: `method`\n\nChanges the directory of the storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | An absolute path of the directory. |\n\nReturns: `FileStorage` The storage itself.\n\nSets `fs.directory` and the path of the index `files.log` in it. Call it before you use the storage, for example in a definition file.\n\nExample: Another disk\n```js\nFILESTORAGE('videos').storage('/mnt/media/videos/');\n```\n\n### fs.save(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nSaves a file into the storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Your identifier of the file, for example from `UID()`. |\n| `name` | `String` | yes |  | The file name with its extension. |\n| `source` | `String|Buffer|Stream` | yes |  | A path, a `Buffer`, a readable stream or an `https://` URL. |\n| `custom` | `Object` | no | `null` | Custom data stored with the file. |\n| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |\n| `expire` | `String` | no |  | A time after which the file can no longer be read, such as `'1 day'`. |\n| `headers` | `Object` | no |  | HTTP headers for downloading a URL. |\n\nReturns: `FileStorage|Promise` The storage, or a `Promise` with the metadata without a callback.\n\n`source` is a path on the disk, a `Buffer`, a readable stream or an `https://` URL that is downloaded. The extension of `name` decides the content type; JPEG, PNG, GIF and SVG images get `width` and `height`. A path in `name` is removed, and a name longer than 250 characters is shortened. When you leave out `source`, `name` is used as the path of the file and its last part as the name. Saving again with an existing id replaces the file. `fs.insert()` is an alias.\n\nThe callback receives the metadata: `id`, `name`, `ext`, `type`, `size`, `width`, `height`, `custom`, `date` and `expire`.\n\nExample: From a file on the disk\n```js\nFILESTORAGE('files').save(UID(), 'report.pdf', PATH.root('report.pdf'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: With custom data and expiration\n```js\nvar meta = await FILESTORAGE('exports').save(UID(), 'export.csv', Buffer.from(csv), { userid: $.user.id }, null, '1 day');\n```\n\n### fs.insert(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nAn alias of fs.save().\n\nReturns: `FileStorage|Promise`\n\nWorks exactly as `fs.save()`.\n\n### fs.savejson(id, value, [callback])\n\nType: `method`\n\nSaves a value as a JSON file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the file. |\n| `value` | `Object` | yes |  | A value to serialize. |\n| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nSerializes `value` with `JSON.stringify()` and saves it as `{id}.json` (content type `application/json`). Read it back with `fs.readjson()`.\n\nExample: Store settings\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' }, function(err, meta) {});\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 |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |\n| `nostream` | `Boolean` | no | `false` | `true` returns only the metadata. |\n\nReturns: `FileStorage|Promise`\n\nThe callback receives the metadata with a readable stream of the content in `meta.stream`. Consume the stream: it keeps the file open until it ends. With `nostream` set to `true` only the metadata is returned. An expired file ends with the error `File is expired`, a missing one with an error of the file system.\n\nExample: Pipe into a file\n```js\nFILESTORAGE('files').read('readme', function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.tmp(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 |  | Called as `callback(err, meta, filename, fd)`. Without it the method returns a `Promise`. |\n| `keepfd` | `Boolean` | no | `false` | `true` keeps the file descriptor open and passes it to the callback. |\n\nReturns: `FileStorage|Promise`\n\nReads the header of the file and parses dates into `Date` objects. The callback also receives the path of the `.file` and, with `keepfd`, the open file descriptor, which you must close with `F.Fs.close()`. The expiration is not checked.\n\nExample: Check a file\n```js\nvar meta = await FILESTORAGE('files').readmeta('readme');\nconsole.log(meta.name, meta.size, meta.date);\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nReads the whole content into a Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the file. |\n| `callback` | `Function` | no |  | Called as `callback(err, buffer, meta)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nUse it for small files; stream big files with `fs.read()`. The promise resolves with the buffer only.\n\nExample: Read a file\n```js\nvar buffer = await FILESTORAGE('files').readbuffer('readme');\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nReads the content as a base64 string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the file. |\n| `callback` | `Function` | no |  | Called as `callback(err, base64, meta)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nHandy for data URIs and JSON APIs. The promise resolves with the string only.\n\nExample: A data URI\n```js\nFILESTORAGE('photos').readbase64('avatar', 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 |  | Called as `callback(err, value, meta)`. |\n\nReturns: `FileStorage`\n\nReads the content and parses it as JSON (dates included). 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.readfilename(id)\n\nType: `method`\n\nReturns the path of the stored file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the file. |\n\nReturns: `String` The path.\n\nReturns the absolute path of `{group}/{id}.file`. The file starts with a 2000-byte header, so do not serve it directly.\n\n### fs.makedirectory(id)\n\nType: `method`\n\nReturns the directory for an id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the file. |\n\nReturns: `String` The path.\n\nReturns the path of the four-digit group directory where the file with this id is stored. It does not create the directory.\n\n### fs.image(id, [callback])\n\nType: `method`\n\nLoads a stored file as an image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the file. |\n| `callback` | `Function` | no |  | Called as `callback(err, image, meta)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nReturns an image object of [Images](../../guides/images/) that reads the content of the file. Transform it and save or pipe it.\n\nExample: Create a thumbnail\n```js\nFILESTORAGE('photos').image('avatar', function(err, image) {\n\timage.resize(100, 100);\n\timage.save(PATH.public('thumbs/avatar.jpg'), function(err) {});\n});\n```\n\n### fs.http($, opt)\n\nType: `method`\n\nSends a stored file as an HTTP response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | The controller of the request. |\n| `opt` | `Object` | yes |  | The options: `id`, `download`, `check`, `image`, `cache`. |\n\nReturns: `undefined`\n\nSets the content type, `Last-Modified`, `X-Size` (and `X-Width`, `X-Height` for images) and the HTTP cache (not in debug mode), answers `304` for a current version in the browser and supports `Range` requests with `206`. A missing or expired file, or a `check` that returns `false`, ends with `404`; such an id keeps answering `404` until the next clean-up of the framework cache.\n\nOptions: `id`; `download` (`true` for the stored name, a string, or a function `(name, type)` returning the name); `check` (a function `(meta)`); `image` (a function `(image)` with `this` as the controller, for image files); `cache` (a key under which a transformed image is kept in the temporary directory). The controller method `$.filefs()` is a shortcut.\n\nExample: Serve and download\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id });\n\t});\n\tROUTE('GET /download/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id, download: true });\n\t});\n};\n```\n\nExample: A resized image\n```js\nROUTE('GET /thumbs/{id}/', function($) {\n\tFILESTORAGE('photos').http($, {\n\t\tid: $.params.id,\n\t\tcache: 'thumb-' + $.params.id,\n\t\timage: image => image.resize(200, 200)\n\t});\n});\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 |  | Called as `callback(err)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nDeletes the `.file` and its line in the index. The callback receives an error of the file system when the file does not exist.\n\nExample: Remove a file\n```js\nFILESTORAGE('files').remove($.params.id, function(err) {\n\t$.success();\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. |\n| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nWrites the new name into the header of the file and into the index. The id and the content stay the same. A name longer than 250 characters is shortened.\n\nExample: Rename\n```js\nawait FILESTORAGE('files').rename('readme', 'README.md');\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method`\n\nCopies the content of a file out of the storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the file. |\n| `path` | `String` | yes |  | A target file name or a directory. |\n| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |\n\nReturns: `Promise|undefined`\n\nWrites the content without the header. When `path` contains a dot it is the target file name, otherwise it is a directory and the stored name is used.\n\nExample: Export a file\n```js\nFILESTORAGE('files').copy('readme', PATH.tmp(), function(err, meta) {\n\tconsole.log(PATH.tmp(meta.name));\n});\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method`\n\nDuplicates a file under a new id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the source file. |\n| `newid` | `String` | no | `UID()` | The new id. |\n| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |\n\nReturns: `Promise|undefined`\n\nCopies the stored file with its metadata to a new id and adds it to the index. Without `newid` (also when the callback is the second argument, or in the Promise form) a new id from `UID()` is used; the callback and the Promise get the metadata with the new id.\n\nExample: Clone\n```js\nFILESTORAGE('files').clone('template', function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\nExample: Promise\n```js\nvar meta = await FILESTORAGE('files').clone('template');\nconsole.log(meta.id); // a new UID\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nLists files from the index.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called as `callback(err, files)`. |\n\nReturns: `QueryBuilder` A NoSQL query builder.\n\nReturns a NoSQL query builder over `files.log`, so you can use `where()`, `sort()`, `take()`, `fields()` and the other methods of [NoSQL](../../guides/nosql/). Each record is the metadata of a file.\n\nExample: Latest PDF files\n```js\nFILESTORAGE('files').browse().where('ext', 'pdf').sort('date', true).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 |  | Called as `callback(err, files)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nReads the header of every file in the directory and returns the array of metadata, each with `id` and `index`; expired files are skipped. It does not use the index, so it is slower than `browse()` but always matches the disk.\n\nExample: All files\n```js\nvar files = await FILESTORAGE('files').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nWalks all files of the storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | Called as `onfile(meta, next)`. |\n| `callback` | `Function` | no |  | Called when all files were processed. |\n| `workers` | `Number` | no | `2` | Parallel files. |\n\nReturns: `FileStorage`\n\nCalls `onfile(meta, next)` for every file on the disk with its metadata (without content), `id` and a sequence number `index`; expired files are skipped. Call `next()` to continue. `workers` is the number of files processed at the same time in a directory.\n\nExample: Total size\n```js\nvar size = 0;\nFILESTORAGE('files').stream(function(meta, next) {\n\tsize += meta.size;\n\tnext();\n}, () => console.log(size));\n```\n\n### fs.count2([callback])\n\nType: `method`\n\nCounts the files on the disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called as `callback(err, count)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nCounts the files in the group directories of the storage.\n\nExample: Count\n```js\nvar count = await FILESTORAGE('files').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nRebuilds the index from the disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called as `callback()`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nReads the metadata of all files and writes `files.log` again. Use it after `restore()` or after you copied `.file` files into the directory. `save()`, `read()`, `readbuffer()`, `copy()` and `clone()` wait while the index is written.\n\nExample: Rebuild\n```js\nawait FILESTORAGE('files').rebuild();\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nRemoves all files of the storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called as `callback(err, count)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nDeletes every file, the group directories and the index. `save()`, `read()`, `readbuffer()`, `copy()` and `clone()` wait until it ends. Call it only when the directory of the storage exists: otherwise it ends with an error and the storage stays paused. The callback receives the number of removed files. `fs.drop()` is an alias.\n\nExample: Clear\n```js\nFILESTORAGE('tmp').clear(function(err, count) {\n\tconsole.log('Removed', count);\n});\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nAn alias of fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called as `callback(err, count)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nWorks exactly as `fs.clear()`.\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nBacks up the whole storage into one file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | A target file name or a writable stream. |\n| `callback` | `Function` | no |  | Called as `callback(err, result)`. Without it the method returns a `Promise`. |\n\nReturns: `Promise|undefined`\n\nWrites every file, compressed with GZIP and encoded as base64, into a text file (or a writable stream). The index `files.log` is not included. The result is `{ filename, files, size }`.\n\nExample: Backup\n```js\nvar result = await FILESTORAGE('files').backup(PATH.root('files.backup'));\nconsole.log(result.files, result.size);\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nRestores a backup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | A backup file name or a readable stream. |\n| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |\n\nReturns: `Promise|undefined`\n\nRemoves all current files and extracts a file made by `fs.backup()` into the directory. `save()`, `read()`, `readbuffer()`, `copy()` and `clone()` wait until it ends. Call `fs.rebuild()` afterwards to create the index.\n\nExample: Restore and index\n```js\nvar fs = FILESTORAGE('files');\nfs.restore(PATH.root('files.backup'), function(err) {\n\t!err && fs.rebuild();\n});\n```\n\n### meta\n\nType: `type`\n\nThe metadata of a stored file.\n\nReturned by `save()`, `read()`, `readmeta()` and the other methods and stored in the header of each file:\n\n- `id` {String}: the id,\n- `name` {String}: the file name,\n- `ext` {String}: the extension without the dot,\n- `type` {String}: the content type,\n- `size` {Number}: the size of the content in bytes,\n- `width`, `height` {Number}: dimensions of JPEG, PNG, GIF and SVG images,\n- `custom` {Object}: your custom data or `null`,\n- `date` {Date}: when the file was saved,\n- `expire` {Date}: when the file expires (only when set).\n\n`read()` adds `stream`, and `stream()` and `browse2()` add `index`.\n\n### ROUTE('POST /url/ @upload')\n\nType: `type`\n\nA route flag for multipart uploads.\n\nA route with `@upload` matches only `multipart/form-data` requests. The uploaded files are in `$.files` (also in actions), the other fields in `$.body`. Combine it with a size flag such as `<10MB`.\n\nExample: An upload route\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', function($) {\n\t\tvar file = $.files[0];\n\t\tfile.fs('files', UID(), $.callback());\n\t});\n};\n```\n\n### file.fs(storage, id, [callback])\n\nType: `method`\n\nSaves an uploaded file into a file 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| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nA method of `HttpFile` (the items of `$.files`). Saves the temporary file into `FILESTORAGE(storage)` with its original file name and returns the metadata.\n\nExample: Save all uploads\n```js\nfunction upload($) {\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), next);\n\t}, () => $.success());\n}\n```\n\n### Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])\n\nType: `method`\n\nReads a file in chunks, with progress.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The path of the file. |\n| `onbuffer` | `Function` | yes |  | Called as `onbuffer(buffer, next, percentage)`; `next(true)` stops reading. |\n| `onend` | `Function` | no |  | Called as `onend(err)` at the end, after a stop or on an error. |\n| `size` | `Number` | no | `16384` | The size of a chunk in bytes. |\n| `offset` | `Number` | no | `0` | The position in bytes where reading starts. |\n\nReturns: `undefined`\n\nReads a file in chunks of `size` bytes (default 16384) from `offset` (default 0) and calls `onbuffer(buffer, next, percentage)` for each chunk. `percentage` is the part of the file read so far, from 0 to 100. Call `next()` to read the next chunk or `next(true)` to stop. `onend(err)` is called at the end of the file, after a stop, or with the error when the file does not exist. When the third argument is a number it is the size.\n\nExample: Hash a file\n```js\nvar hash = F.Crypto.createHash('sha1');\nUtils.filestreamer(PATH.root('big.iso'), function(buffer, next) {\n\thash.update(buffer);\n\tnext();\n}, function(err) {\n\tconsole.log(hash.digest('hex'));\n});\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"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":"method","name":"fs.storage()","signature":"fs.storage(path)","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback])","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.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"fs.makedirectory()","signature":"fs.makedirectory(id)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.http()","signature":"fs.http($, opt)","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [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.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([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":"type","name":"File meta","signature":"meta","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('POST /url/ @upload')","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [callback])","since":"","deprecated":false},{"type":"method","name":"Utils.filestreamer()","signature":"Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCK2Xc60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/file-storage/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Dateispeicher","summary":"FILESTORAGE() und seine Methoden, die Metadaten von Dateien, das Flag @upload und file.fs().","markdown":"---\ntitle: Dateispeicher\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/file-storage/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Dateispeicher\n\n> FILESTORAGE() und seine Methoden, die Metadaten von Dateien, das Flag @upload und file.fs().\n\nMethoden eines Dateispeichers, den `FILESTORAGE(name)` zurückgibt (unten als `fs` geschrieben), die Metadaten gespeicherter Dateien, das Routen-Flag `@upload`, `file.fs()` für hochgeladene Dateien und `Utils.filestreamer()`. Eine Einführung mit Beispielen findest du im Leitfaden [Dateispeicher](../../guides/file-storage/).\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nGibt einen Dateispeicher anhand seines Namens zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Speichers. |\n\nReturns: `FileStorage` Der Dateispeicher.\n\nErstellt den Speicher beim ersten Aufruf und gibt danach für denselben Namen dieselbe Instanz zurück. Die Dateien werden in `/databases/fs-{name}/` gespeichert; das Verzeichnis wird beim ersten Speichern erstellt. Ändere es mit `fs.storage(path)`.\n\nExample: Eine Datei speichern und lesen\n```js\nvar fs = FILESTORAGE('files');\n\nfs.save('readme', 'readme.txt', Buffer.from('Hello'), function(err, meta) {\n\tfs.readbuffer('readme', function(err, buffer) {\n\t\tconsole.log(buffer.toString('utf8'));\n\t});\n});\n```\n\n### fs.name\n\nType: `property`\n\nDer Name des Speichers.\n\nReturns: `String`\n\nDer an `FILESTORAGE(name)` übergebene Name.\n\n### fs.directory\n\nType: `property`\n\nDas Verzeichnis des Speichers.\n\nReturns: `String`\n\nDer absolute Pfad des Verzeichnisses mit den Dateien, standardmäßig `/databases/fs-{name}/`. Setze ihn mit `fs.storage(path)`.\n\n### fs.storage(path)\n\nType: `method`\n\nÄndert das Verzeichnis des Speichers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein absoluter Pfad des Verzeichnisses. |\n\nReturns: `FileStorage` Der Speicher selbst.\n\nSetzt `fs.directory` und den Pfad des darin liegenden Index `files.log`. Rufe es auf, bevor du den Speicher verwendest, zum Beispiel in einer Definitionsdatei.\n\nExample: Eine andere Festplatte\n```js\nFILESTORAGE('videos').storage('/mnt/media/videos/');\n```\n\n### fs.save(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nSpeichert eine Datei im Speicher.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Deine Kennung der Datei, zum Beispiel aus `UID()`. |\n| `name` | `String` | yes |  | Der Dateiname mit seiner Endung. |\n| `source` | `String|Buffer|Stream` | yes |  | Ein Pfad, ein `Buffer`, ein lesbarer Stream oder eine `https://`-URL. |\n| `custom` | `Object` | no | `null` | Eigene Daten, die mit der Datei gespeichert werden. |\n| `callback` | `Function` | no |  | Wird als `callback(err, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n| `expire` | `String` | no |  | Eine Zeitangabe, nach der die Datei nicht mehr gelesen werden kann, etwa `'1 day'`. |\n| `headers` | `Object` | no |  | HTTP-Header zum Herunterladen einer URL. |\n\nReturns: `FileStorage|Promise` Der Speicher oder, ohne Callback, ein `Promise` mit den Metadaten.\n\n`source` ist ein Pfad auf der Festplatte, ein `Buffer`, ein lesbarer Stream oder eine `https://`-URL, die heruntergeladen wird. Die Endung von `name` bestimmt den Content-Type; JPEG-, PNG-, GIF- und SVG-Bilder erhalten `width` und `height`. Ein Pfad in `name` wird entfernt, und ein Name mit mehr als 250 Zeichen wird gekürzt. Lässt du `source` weg, wird `name` als Pfad der Datei und sein letzter Teil als Name verwendet. Erneutes Speichern mit einer vorhandenen ID ersetzt die Datei. `fs.insert()` ist ein Alias.\n\nDer Callback erhält die Metadaten: `id`, `name`, `ext`, `type`, `size`, `width`, `height`, `custom`, `date` und `expire`.\n\nExample: Aus einer Datei auf der Festplatte\n```js\nFILESTORAGE('files').save(UID(), 'report.pdf', PATH.root('report.pdf'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Mit eigenen Daten und Ablaufzeit\n```js\nvar meta = await FILESTORAGE('exports').save(UID(), 'export.csv', Buffer.from(csv), { userid: $.user.id }, null, '1 day');\n```\n\n### fs.insert(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nEin Alias von fs.save().\n\nReturns: `FileStorage|Promise`\n\nFunktioniert genauso wie `fs.save()`.\n\n### fs.savejson(id, value, [callback])\n\nType: `method`\n\nSpeichert einen Wert als JSON-Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `value` | `Object` | yes |  | Ein zu serialisierender Wert. |\n| `callback` | `Function` | no |  | Wird als `callback(err, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nSerialisiert `value` mit `JSON.stringify()` und speichert ihn als `{id}.json` (Content-Type `application/json`). Lies ihn mit `fs.readjson()` wieder.\n\nExample: Einstellungen speichern\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' }, function(err, meta) {});\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 |  | Wird als `callback(err, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n| `nostream` | `Boolean` | no | `false` | `true` gibt nur die Metadaten zurück. |\n\nReturns: `FileStorage|Promise`\n\nDer Callback erhält die Metadaten mit einem lesbaren Stream des Inhalts in `meta.stream`. Verarbeite den Stream: Er hält die Datei offen, bis er endet. Ist `nostream` auf `true` gesetzt, werden nur die Metadaten zurückgegeben. Eine abgelaufene Datei endet mit dem Fehler `File is expired`, eine fehlende mit einem Fehler des Dateisystems.\n\nExample: In eine Datei leiten\n```js\nFILESTORAGE('files').read('readme', function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.tmp(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 |  | Wird als `callback(err, meta, filename, fd)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n| `keepfd` | `Boolean` | no | `false` | `true` hält den Dateideskriptor offen und übergibt ihn an den Callback. |\n\nReturns: `FileStorage|Promise`\n\nLiest den Header der Datei und parst Datumswerte in `Date`-Objekte. Der Callback erhält außerdem den Pfad der `.file` und, mit `keepfd`, den offenen Dateideskriptor, den du mit `F.Fs.close()` schließen musst. Die Ablaufzeit wird nicht geprüft.\n\nExample: Eine Datei prüfen\n```js\nvar meta = await FILESTORAGE('files').readmeta('readme');\nconsole.log(meta.name, meta.size, meta.date);\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nLiest den gesamten Inhalt in einen Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | no |  | Wird als `callback(err, buffer, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nVerwende es für kleine Dateien; streame große Dateien mit `fs.read()`. Das Promise wird nur mit dem Buffer erfüllt.\n\nExample: Eine Datei lesen\n```js\nvar buffer = await FILESTORAGE('files').readbuffer('readme');\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nLiest den Inhalt als Base64-String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | no |  | Wird als `callback(err, base64, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nPraktisch für Data-URIs und JSON-APIs. Das Promise wird nur mit dem String erfüllt.\n\nExample: Eine Data-URI\n```js\nFILESTORAGE('photos').readbase64('avatar', 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 |  | Wird als `callback(err, value, meta)` aufgerufen. |\n\nReturns: `FileStorage`\n\nLiest den Inhalt und parst ihn als JSON (einschließlich Datumswerten). Der Callback ist erforderlich.\n\nExample: Einstellungen lesen\n```js\nFILESTORAGE('data').readjson('settings', function(err, value) {\n\tconsole.log(value.theme);\n});\n```\n\n### fs.readfilename(id)\n\nType: `method`\n\nGibt den Pfad der gespeicherten Datei zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n\nReturns: `String` Der Pfad.\n\nGibt den absoluten Pfad von `{group}/{id}.file` zurück. Die Datei beginnt mit einem 2000 Byte großen Header, liefere sie also nicht direkt aus.\n\n### fs.makedirectory(id)\n\nType: `method`\n\nGibt das Verzeichnis für eine ID zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n\nReturns: `String` Der Pfad.\n\nGibt den Pfad des vierstelligen Gruppenverzeichnisses zurück, in dem die Datei mit dieser ID gespeichert ist. Das Verzeichnis wird nicht erstellt.\n\n### fs.image(id, [callback])\n\nType: `method`\n\nLädt eine gespeicherte Datei als Bild.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | no |  | Wird als `callback(err, image, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nGibt ein Bildobjekt aus [Bilder](../../guides/images/) zurück, das den Inhalt der Datei liest. Verändere es und speichere oder leite es weiter.\n\nExample: Ein Vorschaubild erstellen\n```js\nFILESTORAGE('photos').image('avatar', function(err, image) {\n\timage.resize(100, 100);\n\timage.save(PATH.public('thumbs/avatar.jpg'), function(err) {});\n});\n```\n\n### fs.http($, opt)\n\nType: `method`\n\nSendet eine gespeicherte Datei als HTTP-Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | Der Controller der Anfrage. |\n| `opt` | `Object` | yes |  | Die Optionen: `id`, `download`, `check`, `image`, `cache`. |\n\nReturns: `undefined`\n\nSetzt den Content-Type, `Last-Modified`, `X-Size` (sowie `X-Width`, `X-Height` bei Bildern) und den HTTP-Cache (nicht im Debug-Modus), antwortet mit `304` bei einer aktuellen Version im Browser und unterstützt `Range`-Anfragen mit `206`. Eine fehlende oder abgelaufene Datei oder ein `check`, das `false` zurückgibt, endet mit `404`; eine solche ID antwortet bis zur nächsten Bereinigung des Framework-Caches weiterhin mit `404`.\n\nOptionen: `id`; `download` (`true` für den gespeicherten Namen, ein String oder eine Funktion `(name, type)`, die den Namen zurückgibt); `check` (eine Funktion `(meta)`); `image` (eine Funktion `(image)` mit `this` als Controller, für Bilddateien); `cache` (ein Schlüssel, unter dem ein verändertes Bild im temporären Verzeichnis aufbewahrt wird). Die Controller-Methode `$.filefs()` ist eine Abkürzung.\n\nExample: Ausliefern und herunterladen\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id });\n\t});\n\tROUTE('GET /download/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id, download: true });\n\t});\n};\n```\n\nExample: Ein skaliertes Bild\n```js\nROUTE('GET /thumbs/{id}/', function($) {\n\tFILESTORAGE('photos').http($, {\n\t\tid: $.params.id,\n\t\tcache: 'thumb-' + $.params.id,\n\t\timage: image => image.resize(200, 200)\n\t});\n});\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 |  | Wird als `callback(err)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nLöscht die `.file` und ihre Zeile im Index. Der Callback erhält einen Fehler des Dateisystems, wenn die Datei nicht existiert.\n\nExample: Eine Datei entfernen\n```js\nFILESTORAGE('files').remove($.params.id, function(err) {\n\t$.success();\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. |\n| `callback` | `Function` | no |  | Wird als `callback(err, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nSchreibt den neuen Namen in den Header der Datei und in den Index. Die ID und der Inhalt bleiben gleich. Ein Name mit mehr als 250 Zeichen wird gekürzt.\n\nExample: Umbenennen\n```js\nawait FILESTORAGE('files').rename('readme', 'README.md');\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method`\n\nKopiert den Inhalt einer Datei aus dem Speicher heraus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `path` | `String` | yes |  | Ein Zieldateiname oder ein Verzeichnis. |\n| `callback` | `Function` | no |  | Wird als `callback(err, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `Promise|undefined`\n\nSchreibt den Inhalt ohne den Header. Enthält `path` einen Punkt, ist er der Name der Zieldatei, andernfalls ist er ein Verzeichnis und der gespeicherte Name wird verwendet.\n\nExample: Eine Datei exportieren\n```js\nFILESTORAGE('files').copy('readme', PATH.tmp(), function(err, meta) {\n\tconsole.log(PATH.tmp(meta.name));\n});\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method`\n\nDupliziert eine Datei unter einer neuen ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Quelldatei. |\n| `newid` | `String` | no | `UID()` | Die neue ID. |\n| `callback` | `Function` | no |  | Wird als `callback(err, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `Promise|undefined`\n\nKopiert die gespeicherte Datei mit ihren Metadaten zu einer neuen ID und fügt sie dem Index hinzu. Ohne `newid` (auch wenn der Callback das zweite Argument ist, oder in der Promise-Form) wird eine neue ID aus `UID()` verwendet; der Callback und das Promise erhalten die Metadaten mit der neuen ID.\n\nExample: Klonen\n```js\nFILESTORAGE('files').clone('template', function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\nExample: Promise\n```js\nvar meta = await FILESTORAGE('files').clone('template');\nconsole.log(meta.id); // a new UID\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nListet Dateien aus dem Index auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird als `callback(err, files)` aufgerufen. |\n\nReturns: `QueryBuilder` Ein NoSQL-Query-Builder.\n\nGibt einen NoSQL-Query-Builder über `files.log` zurück, sodass du `where()`, `sort()`, `take()`, `fields()` und die anderen Methoden von [NoSQL](../../guides/nosql/) verwenden kannst. Jeder Eintrag sind die Metadaten einer Datei.\n\nExample: Neueste PDF-Dateien\n```js\nFILESTORAGE('files').browse().where('ext', 'pdf').sort('date', true).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 |  | Wird als `callback(err, files)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nLiest den Header jeder Datei im Verzeichnis und gibt das Array der Metadaten zurück, jeweils mit `id` und `index`; abgelaufene Dateien werden übersprungen. Es verwendet den Index nicht, ist also langsamer als `browse()`, stimmt aber immer mit der Festplatte überein.\n\nExample: Alle Dateien\n```js\nvar files = await FILESTORAGE('files').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nGeht alle Dateien des Speichers durch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | Wird als `onfile(meta, next)` aufgerufen. |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn alle Dateien verarbeitet wurden. |\n| `workers` | `Number` | no | `2` | Parallele Dateien. |\n\nReturns: `FileStorage`\n\nRuft `onfile(meta, next)` für jede Datei auf der Festplatte mit ihren Metadaten (ohne Inhalt), `id` und einer laufenden Nummer `index` auf; abgelaufene Dateien werden übersprungen. Rufe `next()` auf, um fortzufahren. `workers` ist die Anzahl der Dateien, die in einem Verzeichnis gleichzeitig verarbeitet werden.\n\nExample: Gesamtgröße\n```js\nvar size = 0;\nFILESTORAGE('files').stream(function(meta, next) {\n\tsize += meta.size;\n\tnext();\n}, () => console.log(size));\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 |  | Wird als `callback(err, count)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nZählt die Dateien in den Gruppenverzeichnissen des Speichers.\n\nExample: Zählen\n```js\nvar count = await FILESTORAGE('files').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nErstellt den Index von der Festplatte neu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird als `callback()` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nLiest die Metadaten aller Dateien und schreibt `files.log` neu. Verwende es nach `restore()` oder nachdem du `.file`-Dateien in das Verzeichnis kopiert hast. `save()`, `read()`, `readbuffer()`, `copy()` und `clone()` warten, während der Index geschrieben wird.\n\nExample: Neu erstellen\n```js\nawait FILESTORAGE('files').rebuild();\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nEntfernt alle Dateien des Speichers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird als `callback(err, count)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nLöscht jede Datei, die Gruppenverzeichnisse und den Index. `save()`, `read()`, `readbuffer()`, `copy()` und `clone()` warten, bis es fertig ist. Ruf es nur auf, wenn das Verzeichnis des Speichers existiert: Sonst endet es mit einem Fehler, und der Speicher bleibt pausiert. Der Callback erhält die Anzahl der entfernten Dateien. `fs.drop()` ist ein Alias.\n\nExample: Leeren\n```js\nFILESTORAGE('tmp').clear(function(err, count) {\n\tconsole.log('Removed', count);\n});\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nEin Alias von fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird als `callback(err, count)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nFunktioniert genauso wie `fs.clear()`.\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nSichert den gesamten Speicher in eine Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Ein Zieldateiname oder ein beschreibbarer Stream. |\n| `callback` | `Function` | no |  | Wird als `callback(err, result)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `Promise|undefined`\n\nSchreibt jede Datei, mit GZIP komprimiert und als Base64 kodiert, in eine Textdatei (oder einen beschreibbaren Stream). Der Index `files.log` ist nicht enthalten. Das Ergebnis ist `{ filename, files, size }`.\n\nExample: Sicherung\n```js\nvar result = await FILESTORAGE('files').backup(PATH.root('files.backup'));\nconsole.log(result.files, result.size);\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nStellt eine Sicherung wieder her.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Ein Name einer Sicherungsdatei oder ein lesbarer Stream. |\n| `callback` | `Function` | no |  | Wird als `callback(err, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `Promise|undefined`\n\nEntfernt alle aktuellen Dateien und entpackt eine mit `fs.backup()` erstellte Datei in das Verzeichnis. `save()`, `read()`, `readbuffer()`, `copy()` und `clone()` warten, bis es fertig ist. Ruf danach `fs.rebuild()` auf, um den Index zu erstellen.\n\nExample: Wiederherstellen und indizieren\n```js\nvar fs = FILESTORAGE('files');\nfs.restore(PATH.root('files.backup'), function(err) {\n\t!err && fs.rebuild();\n});\n```\n\n### meta\n\nType: `type`\n\nDie Metadaten einer gespeicherten Datei.\n\nWird von `save()`, `read()`, `readmeta()` und den anderen Methoden zurückgegeben und im Header jeder Datei gespeichert:\n\n- `id` {String}: die ID,\n- `name` {String}: der Dateiname,\n- `ext` {String}: die Endung ohne Punkt,\n- `type` {String}: der Content-Type,\n- `size` {Number}: die Größe des Inhalts in Bytes,\n- `width`, `height` {Number}: Abmessungen von JPEG-, PNG-, GIF- und SVG-Bildern,\n- `custom` {Object}: deine eigenen Daten oder `null`,\n- `date` {Date}: wann die Datei gespeichert wurde,\n- `expire` {Date}: wann die Datei abläuft (nur wenn gesetzt).\n\n`read()` fügt `stream` hinzu, und `stream()` und `browse2()` fügen `index` hinzu.\n\n### ROUTE('POST /url/ @upload')\n\nType: `type`\n\nEin Routen-Flag für Multipart-Uploads.\n\nEine Route mit `@upload` passt nur auf `multipart/form-data`-Anfragen. Die hochgeladenen Dateien stehen in `$.files` (auch in Aktionen), die anderen Felder in `$.body`. Kombiniere es mit einem Größen-Flag wie `<10MB`.\n\nExample: Eine Upload-Route\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', function($) {\n\t\tvar file = $.files[0];\n\t\tfile.fs('files', UID(), $.callback());\n\t});\n};\n```\n\n### file.fs(storage, id, [callback])\n\nType: `method`\n\nSpeichert eine hochgeladene Datei in einem Dateispeicher.\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| `callback` | `Function` | no |  | Wird als `callback(err, meta)` aufgerufen. Ohne ihn gibt die Methode ein `Promise` zurück. |\n\nReturns: `FileStorage|Promise`\n\nEine Methode von `HttpFile` (den Elementen von `$.files`). Speichert die temporäre Datei mit ihrem ursprünglichen Dateinamen in `FILESTORAGE(storage)` und gibt die Metadaten zurück.\n\nExample: Alle Uploads speichern\n```js\nfunction upload($) {\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), next);\n\t}, () => $.success());\n}\n```\n\n### Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])\n\nType: `method`\n\nLiest eine Datei in Chunks, mit Fortschritt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der Pfad der Datei. |\n| `onbuffer` | `Function` | yes |  | Wird als `onbuffer(buffer, next, percentage)` aufgerufen; `next(true)` stoppt das Lesen. |\n| `onend` | `Function` | no |  | Wird als `onend(err)` am Ende, nach einem Stopp oder bei einem Fehler aufgerufen. |\n| `size` | `Number` | no | `16384` | Die Größe eines Chunks in Bytes. |\n| `offset` | `Number` | no | `0` | Die Position in Bytes, an der das Lesen beginnt. |\n\nReturns: `undefined`\n\nLiest eine Datei in Chunks von `size` Bytes (Standard 16384) ab `offset` (Standard 0) und ruft `onbuffer(buffer, next, percentage)` für jeden Chunk auf. `percentage` ist der bisher gelesene Anteil der Datei, von 0 bis 100. Rufe `next()` auf, um den nächsten Chunk zu lesen, oder `next(true)`, um zu stoppen. `onend(err)` wird am Ende der Datei, nach einem Stopp oder mit dem Fehler aufgerufen, wenn die Datei nicht existiert. Ist das dritte Argument eine Zahl, ist es die Größe.\n\nExample: Eine Datei hashen\n```js\nvar hash = F.Crypto.createHash('sha1');\nUtils.filestreamer(PATH.root('big.iso'), function(buffer, next) {\n\thash.update(buffer);\n\tnext();\n}, function(err) {\n\tconsole.log(hash.digest('hex'));\n});\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"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":"method","name":"fs.storage()","signature":"fs.storage(path)","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback])","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.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"fs.makedirectory()","signature":"fs.makedirectory(id)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.http()","signature":"fs.http($, opt)","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [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.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([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":"type","name":"File meta","signature":"meta","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('POST /url/ @upload')","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [callback])","since":"","deprecated":false},{"type":"method","name":"Utils.filestreamer()","signature":"Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCK2Xc60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/file-storage/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Almacenamiento de archivos","summary":"FILESTORAGE() y sus métodos, los metadatos de los archivos, el flag @upload y file.fs().","markdown":"---\ntitle: Almacenamiento de archivos\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/file-storage/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Almacenamiento de archivos\n\n> FILESTORAGE() y sus métodos, los metadatos de los archivos, el flag @upload y file.fs().\n\nMétodos de un almacenamiento de archivos devuelto por `FILESTORAGE(name)` (escrito como `fs` a continuación), los metadatos de los archivos guardados, el flag de ruta `@upload`, `file.fs()` para los archivos subidos y `Utils.filestreamer()`. Para una introducción con ejemplos lee la guía [Almacenamiento de archivos](../../guides/file-storage/).\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nDevuelve un almacenamiento de archivos por su nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del almacenamiento. |\n\nReturns: `FileStorage` El almacenamiento de archivos.\n\nCrea el almacenamiento en la primera llamada y después devuelve la misma instancia para el mismo nombre. Los archivos se guardan en `/databases/fs-{name}/`; el directorio se crea en el primer guardado. Cámbialo con `fs.storage(path)`.\n\nExample: Guardar y leer un archivo\n```js\nvar fs = FILESTORAGE('files');\n\nfs.save('readme', 'readme.txt', Buffer.from('Hello'), function(err, meta) {\n\tfs.readbuffer('readme', function(err, buffer) {\n\t\tconsole.log(buffer.toString('utf8'));\n\t});\n});\n```\n\n### fs.name\n\nType: `property`\n\nEl nombre del almacenamiento.\n\nReturns: `String`\n\nEl nombre que se pasó a `FILESTORAGE(name)`.\n\n### fs.directory\n\nType: `property`\n\nEl directorio del almacenamiento.\n\nReturns: `String`\n\nLa ruta absoluta del directorio con los archivos, por defecto `/databases/fs-{name}/`. Defínela con `fs.storage(path)`.\n\n### fs.storage(path)\n\nType: `method`\n\nCambia el directorio del almacenamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una ruta absoluta del directorio. |\n\nReturns: `FileStorage` El propio almacenamiento.\n\nDefine `fs.directory` y la ruta del índice `files.log` dentro de él. Llámalo antes de usar el almacenamiento, por ejemplo en un archivo de definiciones.\n\nExample: Otro disco\n```js\nFILESTORAGE('videos').storage('/mnt/media/videos/');\n```\n\n### fs.save(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nGuarda un archivo en el almacenamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Tu identificador del archivo, por ejemplo de `UID()`. |\n| `name` | `String` | yes |  | El nombre del archivo con su extensión. |\n| `source` | `String|Buffer|Stream` | yes |  | Una ruta, un `Buffer`, un stream de lectura o una URL `https://`. |\n| `custom` | `Object` | no | `null` | Datos personalizados que se guardan con el archivo. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, meta)`. Sin él el método devuelve una `Promise`. |\n| `expire` | `String` | no |  | Un tiempo tras el cual el archivo ya no se puede leer, como `'1 day'`. |\n| `headers` | `Object` | no |  | Cabeceras HTTP para descargar una URL. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una `Promise` con los metadatos si no hay callback.\n\n`source` es una ruta en el disco, un `Buffer`, un stream de lectura o una URL `https://` que se descarga. La extensión de `name` decide el tipo de contenido; las imágenes JPEG, PNG, GIF y SVG reciben `width` y `height`. Una ruta en `name` se elimina, y un nombre de más de 250 caracteres se acorta. Cuando omites `source`, `name` se usa como ruta del archivo y su última parte como nombre. Volver a guardar con un id existente sustituye el archivo. `fs.insert()` es un alias.\n\nEl callback recibe los metadatos: `id`, `name`, `ext`, `type`, `size`, `width`, `height`, `custom`, `date` y `expire`.\n\nExample: Desde un archivo del disco\n```js\nFILESTORAGE('files').save(UID(), 'report.pdf', PATH.root('report.pdf'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Con datos personalizados y caducidad\n```js\nvar meta = await FILESTORAGE('exports').save(UID(), 'export.csv', Buffer.from(csv), { userid: $.user.id }, null, '1 day');\n```\n\n### fs.insert(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nUn alias de fs.save().\n\nReturns: `FileStorage|Promise`\n\nFunciona exactamente igual que `fs.save()`.\n\n### fs.savejson(id, value, [callback])\n\nType: `method`\n\nGuarda un valor como archivo JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del archivo. |\n| `value` | `Object` | yes |  | Un valor que se serializa. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, meta)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nSerializa `value` con `JSON.stringify()` y lo guarda como `{id}.json` (tipo de contenido `application/json`). Vuelve a leerlo con `fs.readjson()`.\n\nExample: Guardar ajustes\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' }, function(err, meta) {});\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 |  | Se llama como `callback(err, meta)`. Sin él el método devuelve una `Promise`. |\n| `nostream` | `Boolean` | no | `false` | `true` devuelve solo los metadatos. |\n\nReturns: `FileStorage|Promise`\n\nEl callback recibe los metadatos con un stream de lectura del contenido en `meta.stream`. Consume el stream: mantiene el archivo abierto hasta que termina. Con `nostream` en `true` solo se devuelven los metadatos. Un archivo caducado termina con el error `File is expired`, uno que falta con un error del sistema de archivos.\n\nExample: Volcar en un archivo\n```js\nFILESTORAGE('files').read('readme', function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.tmp(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 |  | Se llama como `callback(err, meta, filename, fd)`. Sin él el método devuelve una `Promise`. |\n| `keepfd` | `Boolean` | no | `false` | `true` mantiene abierto el descriptor de archivo y lo pasa al callback. |\n\nReturns: `FileStorage|Promise`\n\nLee la cabecera del archivo y convierte las fechas en objetos `Date`. El callback recibe también la ruta del `.file` y, con `keepfd`, el descriptor de archivo abierto, que debes cerrar con `F.Fs.close()`. La caducidad no se comprueba.\n\nExample: Comprobar un archivo\n```js\nvar meta = await FILESTORAGE('files').readmeta('readme');\nconsole.log(meta.name, meta.size, meta.date);\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nLee todo el contenido en un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del archivo. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, buffer, meta)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nÚsalo para archivos pequeños; para archivos grandes usa un stream con `fs.read()`. La promesa se resuelve solo con el buffer.\n\nExample: Leer un archivo\n```js\nvar buffer = await FILESTORAGE('files').readbuffer('readme');\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nLee el contenido como una cadena base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del archivo. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, base64, meta)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nPráctico para data URIs y APIs JSON. La promesa se resuelve solo con la cadena.\n\nExample: Un data URI\n```js\nFILESTORAGE('photos').readbase64('avatar', 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 |  | Se llama como `callback(err, value, meta)`. |\n\nReturns: `FileStorage`\n\nLee el contenido y lo analiza como JSON (fechas incluidas). 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.readfilename(id)\n\nType: `method`\n\nDevuelve la ruta del archivo guardado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del archivo. |\n\nReturns: `String` La ruta.\n\nDevuelve la ruta absoluta de `{group}/{id}.file`. El archivo empieza con una cabecera de 2000 bytes, así que no lo sirvas directamente.\n\n### fs.makedirectory(id)\n\nType: `method`\n\nDevuelve el directorio para un id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del archivo. |\n\nReturns: `String` La ruta.\n\nDevuelve la ruta del directorio de grupo de cuatro dígitos donde se guarda el archivo con este id. No crea el directorio.\n\n### fs.image(id, [callback])\n\nType: `method`\n\nCarga un archivo guardado como imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del archivo. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, image, meta)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nDevuelve un objeto de imagen de [Imágenes](../../guides/images/) que lee el contenido del archivo. Transfórmalo y guárdalo o envíalo por un stream.\n\nExample: Crear una miniatura\n```js\nFILESTORAGE('photos').image('avatar', function(err, image) {\n\timage.resize(100, 100);\n\timage.save(PATH.public('thumbs/avatar.jpg'), function(err) {});\n});\n```\n\n### fs.http($, opt)\n\nType: `method`\n\nEnvía un archivo guardado como respuesta HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | El controlador de la petición. |\n| `opt` | `Object` | yes |  | Las opciones: `id`, `download`, `check`, `image`, `cache`. |\n\nReturns: `undefined`\n\nDefine el tipo de contenido, `Last-Modified`, `X-Size` (y `X-Width`, `X-Height` para imágenes) y la caché HTTP (no en modo debug), responde `304` cuando el navegador tiene la versión actual y admite peticiones `Range` con `206`. Un archivo que falta o ha caducado, o un `check` que devuelve `false`, termina con `404`; ese id sigue respondiendo `404` hasta la siguiente limpieza de la caché del framework.\n\nOpciones: `id`; `download` (`true` para el nombre guardado, una cadena, o una función `(name, type)` que devuelve el nombre); `check` (una función `(meta)`); `image` (una función `(image)` con `this` como el controlador, para archivos de imagen); `cache` (una clave bajo la que se guarda una imagen transformada en el directorio temporal). El método del controlador `$.filefs()` es un atajo.\n\nExample: Servir y descargar\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id });\n\t});\n\tROUTE('GET /download/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id, download: true });\n\t});\n};\n```\n\nExample: Una imagen redimensionada\n```js\nROUTE('GET /thumbs/{id}/', function($) {\n\tFILESTORAGE('photos').http($, {\n\t\tid: $.params.id,\n\t\tcache: 'thumb-' + $.params.id,\n\t\timage: image => image.resize(200, 200)\n\t});\n});\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 |  | Se llama como `callback(err)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nBorra el `.file` y su línea en el índice. El callback recibe un error del sistema de archivos cuando el archivo no existe.\n\nExample: Eliminar un archivo\n```js\nFILESTORAGE('files').remove($.params.id, function(err) {\n\t$.success();\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. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, meta)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nEscribe el nuevo nombre en la cabecera del archivo y en el índice. El id y el contenido no cambian. Un nombre de más de 250 caracteres se acorta.\n\nExample: Renombrar\n```js\nawait FILESTORAGE('files').rename('readme', 'README.md');\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method`\n\nCopia el contenido de un archivo fuera del almacenamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del archivo. |\n| `path` | `String` | yes |  | Un nombre de archivo de destino o un directorio. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, meta)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `Promise|undefined`\n\nEscribe el contenido sin la cabecera. Cuando `path` contiene un punto es el nombre del archivo de destino; si no, es un directorio y se usa el nombre guardado.\n\nExample: Exportar un archivo\n```js\nFILESTORAGE('files').copy('readme', PATH.tmp(), function(err, meta) {\n\tconsole.log(PATH.tmp(meta.name));\n});\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method`\n\nDuplica un archivo con un id nuevo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del archivo de origen. |\n| `newid` | `String` | no | `UID()` | El id nuevo. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, meta)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `Promise|undefined`\n\nCopia el archivo guardado con sus metadatos a un id nuevo y lo añade al índice. Sin `newid` (también cuando el callback es el segundo argumento, o en la forma con Promise) se usa un id nuevo de `UID()`; el callback y la Promise reciben los metadatos con el id nuevo.\n\nExample: Clonar\n```js\nFILESTORAGE('files').clone('template', function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\nExample: Promise\n```js\nvar meta = await FILESTORAGE('files').clone('template');\nconsole.log(meta.id); // a new UID\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nLista archivos desde el índice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama como `callback(err, files)`. |\n\nReturns: `QueryBuilder` Un query builder de NoSQL.\n\nDevuelve un query builder de NoSQL sobre `files.log`, así puedes usar `where()`, `sort()`, `take()`, `fields()` y los demás métodos de [NoSQL](../../guides/nosql/). Cada registro son los metadatos de un archivo.\n\nExample: Los últimos archivos PDF\n```js\nFILESTORAGE('files').browse().where('ext', 'pdf').sort('date', true).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 |  | Se llama como `callback(err, files)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nLee la cabecera de cada archivo del directorio y devuelve el array de metadatos, cada uno con `id` e `index`; los archivos caducados se omiten. No usa el índice, así que es más lento que `browse()` pero siempre coincide con el disco.\n\nExample: Todos los archivos\n```js\nvar files = await FILESTORAGE('files').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nRecorre todos los archivos del almacenamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | Se llama como `onfile(meta, next)`. |\n| `callback` | `Function` | no |  | Se llama cuando se han procesado todos los archivos. |\n| `workers` | `Number` | no | `2` | Archivos en paralelo. |\n\nReturns: `FileStorage`\n\nLlama a `onfile(meta, next)` para cada archivo del disco con sus metadatos (sin contenido), `id` y un número de secuencia `index`; los archivos caducados se omiten. Llama a `next()` para continuar. `workers` es el número de archivos que se procesan a la vez en un directorio.\n\nExample: Tamaño total\n```js\nvar size = 0;\nFILESTORAGE('files').stream(function(meta, next) {\n\tsize += meta.size;\n\tnext();\n}, () => console.log(size));\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 |  | Se llama como `callback(err, count)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nCuenta los archivos de los directorios de grupo del almacenamiento.\n\nExample: Contar\n```js\nvar count = await FILESTORAGE('files').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nReconstruye el índice a partir del disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama como `callback()`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nLee los metadatos de todos los archivos y vuelve a escribir `files.log`. Úsalo después de `restore()` o después de copiar archivos `.file` al directorio. `save()`, `read()`, `readbuffer()`, `copy()` y `clone()` esperan mientras se escribe el índice.\n\nExample: Reconstruir\n```js\nawait FILESTORAGE('files').rebuild();\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nElimina todos los archivos del almacenamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama como `callback(err, count)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nBorra todos los archivos, los directorios de grupo y el índice. `save()`, `read()`, `readbuffer()`, `copy()` y `clone()` esperan hasta que termina. Llámalo solo cuando exista el directorio del almacenamiento: si no, termina con un error y el almacenamiento se queda en pausa. El callback recibe el número de archivos eliminados. `fs.drop()` es un alias.\n\nExample: Vaciar\n```js\nFILESTORAGE('tmp').clear(function(err, count) {\n\tconsole.log('Removed', count);\n});\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nUn alias de fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama como `callback(err, count)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nFunciona exactamente igual que `fs.clear()`.\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nHace una copia de seguridad de todo el almacenamiento en un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Un nombre de archivo de destino o un stream de escritura. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, result)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `Promise|undefined`\n\nEscribe cada archivo, comprimido con GZIP y codificado en base64, en un archivo de texto (o un stream de escritura). El índice `files.log` no se incluye. El resultado es `{ filename, files, size }`.\n\nExample: Copia de seguridad\n```js\nvar result = await FILESTORAGE('files').backup(PATH.root('files.backup'));\nconsole.log(result.files, result.size);\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nRestaura una copia de seguridad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Un nombre de archivo de copia de seguridad o un stream de lectura. |\n| `callback` | `Function` | no |  | Se llama como `callback(err, meta)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `Promise|undefined`\n\nElimina todos los archivos actuales y extrae en el directorio un archivo creado con `fs.backup()`. `save()`, `read()`, `readbuffer()`, `copy()` y `clone()` esperan hasta que termina. Después, llama a `fs.rebuild()` para crear el índice.\n\nExample: Restaurar e indexar\n```js\nvar fs = FILESTORAGE('files');\nfs.restore(PATH.root('files.backup'), function(err) {\n\t!err && fs.rebuild();\n});\n```\n\n### meta\n\nType: `type`\n\nLos metadatos de un archivo guardado.\n\nLos devuelven `save()`, `read()`, `readmeta()` y los demás métodos, y se guardan en la cabecera de cada archivo:\n\n- `id` {String}: el id,\n- `name` {String}: el nombre del archivo,\n- `ext` {String}: la extensión sin el punto,\n- `type` {String}: el tipo de contenido,\n- `size` {Number}: el tamaño del contenido en bytes,\n- `width`, `height` {Number}: dimensiones de las imágenes JPEG, PNG, GIF y SVG,\n- `custom` {Object}: tus datos personalizados o `null`,\n- `date` {Date}: cuándo se guardó el archivo,\n- `expire` {Date}: cuándo caduca el archivo (solo si está definido).\n\n`read()` añade `stream`, y `stream()` y `browse2()` añaden `index`.\n\n### ROUTE('POST /url/ @upload')\n\nType: `type`\n\nUn flag de ruta para subidas multipart.\n\nUna ruta con `@upload` coincide solo con peticiones `multipart/form-data`. Los archivos subidos están en `$.files` (también en las acciones), los demás campos en `$.body`. Combínalo con un flag de tamaño como `<10MB`.\n\nExample: Una ruta de subida\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', function($) {\n\t\tvar file = $.files[0];\n\t\tfile.fs('files', UID(), $.callback());\n\t});\n};\n```\n\n### file.fs(storage, id, [callback])\n\nType: `method`\n\nGuarda un archivo subido en un almacenamiento de archivos.\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| `callback` | `Function` | no |  | Se llama como `callback(err, meta)`. Sin él el método devuelve una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nUn método de `HttpFile` (los elementos de `$.files`). Guarda el archivo temporal en `FILESTORAGE(storage)` con su nombre de archivo original y devuelve los metadatos.\n\nExample: Guardar todas las subidas\n```js\nfunction upload($) {\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), next);\n\t}, () => $.success());\n}\n```\n\n### Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])\n\nType: `method`\n\nLee un archivo por fragmentos, con progreso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | La ruta del archivo. |\n| `onbuffer` | `Function` | yes |  | Se llama como `onbuffer(buffer, next, percentage)`; `next(true)` detiene la lectura. |\n| `onend` | `Function` | no |  | Se llama como `onend(err)` al final, tras una detención o ante un error. |\n| `size` | `Number` | no | `16384` | El tamaño de un fragmento en bytes. |\n| `offset` | `Number` | no | `0` | La posición en bytes donde empieza la lectura. |\n\nReturns: `undefined`\n\nLee un archivo en fragmentos de `size` bytes (por defecto 16384) desde `offset` (por defecto 0) y llama a `onbuffer(buffer, next, percentage)` por cada fragmento. `percentage` es la parte del archivo leída hasta el momento, de 0 a 100. Llama a `next()` para leer el siguiente fragmento o a `next(true)` para detenerte. `onend(err)` se llama al final del archivo, tras una detención, o con el error cuando el archivo no existe. Cuando el tercer argumento es un número, es el tamaño.\n\nExample: Calcular el hash de un archivo\n```js\nvar hash = F.Crypto.createHash('sha1');\nUtils.filestreamer(PATH.root('big.iso'), function(buffer, next) {\n\thash.update(buffer);\n\tnext();\n}, function(err) {\n\tconsole.log(hash.digest('hex'));\n});\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"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":"method","name":"fs.storage()","signature":"fs.storage(path)","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback])","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.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"fs.makedirectory()","signature":"fs.makedirectory(id)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.http()","signature":"fs.http($, opt)","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [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.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([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":"type","name":"File meta","signature":"meta","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('POST /url/ @upload')","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [callback])","since":"","deprecated":false},{"type":"method","name":"Utils.filestreamer()","signature":"Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCK2Xc60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/file-storage/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Stockage de fichiers","summary":"FILESTORAGE() et ses méthodes, les métadonnées des fichiers, le flag @upload et file.fs().","markdown":"---\ntitle: Stockage de fichiers\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/file-storage/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Stockage de fichiers\n\n> FILESTORAGE() et ses méthodes, les métadonnées des fichiers, le flag @upload et file.fs().\n\nLes méthodes d'un stockage de fichiers renvoyé par `FILESTORAGE(name)` (noté `fs` ci-dessous), les métadonnées des fichiers stockés, le flag de route `@upload`, `file.fs()` pour les fichiers uploadés et `Utils.filestreamer()`. Pour une introduction avec des exemples, lis le guide [Stockage de fichiers](../../guides/file-storage/).\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nRenvoie un stockage de fichiers par son nom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du stockage. |\n\nReturns: `FileStorage` Le stockage de fichiers.\n\nCrée le stockage lors du premier appel et renvoie ensuite la même instance pour le même nom. Les fichiers sont stockés dans `/databases/fs-{name}/` ; le répertoire est créé lors du premier enregistrement. Change-le avec `fs.storage(path)`.\n\nExample: Enregistrer et lire un fichier\n```js\nvar fs = FILESTORAGE('files');\n\nfs.save('readme', 'readme.txt', Buffer.from('Hello'), function(err, meta) {\n\tfs.readbuffer('readme', function(err, buffer) {\n\t\tconsole.log(buffer.toString('utf8'));\n\t});\n});\n```\n\n### fs.name\n\nType: `property`\n\nLe nom du stockage.\n\nReturns: `String`\n\nLe nom passé à `FILESTORAGE(name)`.\n\n### fs.directory\n\nType: `property`\n\nLe répertoire du stockage.\n\nReturns: `String`\n\nLe chemin absolu du répertoire contenant les fichiers, par défaut `/databases/fs-{name}/`. Définis-le avec `fs.storage(path)`.\n\n### fs.storage(path)\n\nType: `method`\n\nChange le répertoire du stockage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Le chemin absolu du répertoire. |\n\nReturns: `FileStorage` Le stockage lui-même.\n\nDéfinit `fs.directory` et le chemin de l'index `files.log` qu'il contient. Appelle-la avant d'utiliser le stockage, par exemple dans un fichier de définition.\n\nExample: Un autre disque\n```js\nFILESTORAGE('videos').storage('/mnt/media/videos/');\n```\n\n### fs.save(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nEnregistre un fichier dans le stockage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Ton identifiant du fichier, par exemple issu de `UID()`. |\n| `name` | `String` | yes |  | Le nom du fichier avec son extension. |\n| `source` | `String|Buffer|Stream` | yes |  | Un chemin, un `Buffer`, un flux lisible ou une URL `https://`. |\n| `custom` | `Object` | no | `null` | Les données personnalisées stockées avec le fichier. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n| `expire` | `String` | no |  | Un délai après lequel le fichier ne peut plus être lu, comme `'1 day'`. |\n| `headers` | `Object` | no |  | Les en-têtes HTTP pour télécharger une URL. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une `Promise` avec les métadonnées sans callback.\n\n`source` est un chemin sur le disque, un `Buffer`, un flux lisible ou une URL `https://` qui est téléchargée. L'extension de `name` détermine le type de contenu ; les images JPEG, PNG, GIF et SVG reçoivent `width` et `height`. Un chemin dans `name` est retiré, et un nom de plus de 250 caractères est raccourci. Lorsque tu omets `source`, `name` est utilisé comme chemin du fichier et sa dernière partie comme nom. Enregistrer à nouveau avec un id existant remplace le fichier. `fs.insert()` est un alias.\n\nLe callback reçoit les métadonnées : `id`, `name`, `ext`, `type`, `size`, `width`, `height`, `custom`, `date` et `expire`.\n\nExample: Depuis un fichier sur le disque\n```js\nFILESTORAGE('files').save(UID(), 'report.pdf', PATH.root('report.pdf'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Avec des données personnalisées et une expiration\n```js\nvar meta = await FILESTORAGE('exports').save(UID(), 'export.csv', Buffer.from(csv), { userid: $.user.id }, null, '1 day');\n```\n\n### fs.insert(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nUn alias de fs.save().\n\nReturns: `FileStorage|Promise`\n\nFonctionne exactement comme `fs.save()`.\n\n### fs.savejson(id, value, [callback])\n\nType: `method`\n\nEnregistre une valeur sous forme de fichier JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du fichier. |\n| `value` | `Object` | yes |  | Une valeur à sérialiser. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nSérialise `value` avec `JSON.stringify()` et l'enregistre sous `{id}.json` (type de contenu `application/json`). Relis-la avec `fs.readjson()`.\n\nExample: Stocker des paramètres\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' }, function(err, meta) {});\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 |  | Appelé sous la forme `callback(err, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n| `nostream` | `Boolean` | no | `false` | `true` ne renvoie que les métadonnées. |\n\nReturns: `FileStorage|Promise`\n\nLe callback reçoit les métadonnées avec un flux lisible du contenu dans `meta.stream`. Consomme le flux : il garde le fichier ouvert jusqu'à sa fin. Avec `nostream` à `true`, seules les métadonnées sont renvoyées. Un fichier expiré se termine par l'erreur `File is expired`, un fichier absent par une erreur du système de fichiers.\n\nExample: Rediriger vers un fichier\n```js\nFILESTORAGE('files').read('readme', function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.tmp(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 |  | Appelé sous la forme `callback(err, meta, filename, fd)`. Sans lui, la méthode renvoie une `Promise`. |\n| `keepfd` | `Boolean` | no | `false` | `true` garde le descripteur de fichier ouvert et le transmet au callback. |\n\nReturns: `FileStorage|Promise`\n\nLit l'en-tête du fichier et convertit les dates en objets `Date`. Le callback reçoit aussi le chemin du `.file` et, avec `keepfd`, le descripteur de fichier ouvert, que tu dois fermer avec `F.Fs.close()`. L'expiration n'est pas vérifiée.\n\nExample: Vérifier un fichier\n```js\nvar meta = await FILESTORAGE('files').readmeta('readme');\nconsole.log(meta.name, meta.size, meta.date);\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nLit tout le contenu dans un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du fichier. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, buffer, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nUtilise-la pour les petits fichiers ; lis les gros fichiers en flux avec `fs.read()`. La promesse est résolue uniquement avec le buffer.\n\nExample: Lire un fichier\n```js\nvar buffer = await FILESTORAGE('files').readbuffer('readme');\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nLit le contenu sous forme de chaîne base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du fichier. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, base64, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nPratique pour les data URI et les API JSON. La promesse est résolue uniquement avec la chaîne.\n\nExample: Une data URI\n```js\nFILESTORAGE('photos').readbase64('avatar', 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 |  | Appelé sous la forme `callback(err, value, meta)`. |\n\nReturns: `FileStorage`\n\nLit le contenu et l'analyse en JSON (dates comprises). 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.readfilename(id)\n\nType: `method`\n\nRenvoie le chemin du fichier stocké.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du fichier. |\n\nReturns: `String` Le chemin.\n\nRenvoie le chemin absolu de `{group}/{id}.file`. Le fichier commence par un en-tête de 2000 octets ; ne le sers donc pas directement.\n\n### fs.makedirectory(id)\n\nType: `method`\n\nRenvoie le répertoire correspondant à un id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du fichier. |\n\nReturns: `String` Le chemin.\n\nRenvoie le chemin du répertoire de groupe à quatre chiffres où est stocké le fichier ayant cet id. Elle ne crée pas le répertoire.\n\n### fs.image(id, [callback])\n\nType: `method`\n\nCharge un fichier stocké comme image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du fichier. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, image, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nRenvoie un objet image de [Images](../../guides/images/) qui lit le contenu du fichier. Transforme-le, puis enregistre-le ou redirige-le vers un flux.\n\nExample: Créer une miniature\n```js\nFILESTORAGE('photos').image('avatar', function(err, image) {\n\timage.resize(100, 100);\n\timage.save(PATH.public('thumbs/avatar.jpg'), function(err) {});\n});\n```\n\n### fs.http($, opt)\n\nType: `method`\n\nEnvoie un fichier stocké comme réponse HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | Le contrôleur de la requête. |\n| `opt` | `Object` | yes |  | Les options : `id`, `download`, `check`, `image`, `cache`. |\n\nReturns: `undefined`\n\nDéfinit le type de contenu, `Last-Modified`, `X-Size` (et `X-Width`, `X-Height` pour les images) et le cache HTTP (sauf en mode debug), répond `304` lorsque le navigateur a la version actuelle et prend en charge les requêtes `Range` avec `206`. Un fichier absent ou expiré, ou un `check` qui renvoie `false`, se termine par `404` ; un tel id continue de recevoir `404` jusqu'au prochain nettoyage du cache du framework.\n\nOptions : `id` ; `download` (`true` pour le nom stocké, une chaîne, ou une fonction `(name, type)` qui renvoie le nom) ; `check` (une fonction `(meta)`) ; `image` (une fonction `(image)` avec `this` comme contrôleur, pour les fichiers image) ; `cache` (une clé sous laquelle une image transformée est conservée dans le répertoire temporaire). La méthode de contrôleur `$.filefs()` en est un raccourci.\n\nExample: Servir et télécharger\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id });\n\t});\n\tROUTE('GET /download/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id, download: true });\n\t});\n};\n```\n\nExample: Une image redimensionnée\n```js\nROUTE('GET /thumbs/{id}/', function($) {\n\tFILESTORAGE('photos').http($, {\n\t\tid: $.params.id,\n\t\tcache: 'thumb-' + $.params.id,\n\t\timage: image => image.resize(200, 200)\n\t});\n});\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 |  | Appelé sous la forme `callback(err)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nSupprime le `.file` et sa ligne dans l'index. Le callback reçoit une erreur du système de fichiers lorsque le fichier n'existe pas.\n\nExample: Supprimer un fichier\n```js\nFILESTORAGE('files').remove($.params.id, function(err) {\n\t$.success();\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. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nÉcrit le nouveau nom dans l'en-tête du fichier et dans l'index. L'id et le contenu restent les mêmes. Un nom de plus de 250 caractères est raccourci.\n\nExample: Renommer\n```js\nawait FILESTORAGE('files').rename('readme', 'README.md');\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method`\n\nCopie le contenu d'un fichier hors du stockage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du fichier. |\n| `path` | `String` | yes |  | Un nom de fichier cible ou un répertoire. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `Promise|undefined`\n\nÉcrit le contenu sans l'en-tête. Lorsque `path` contient un point, c'est le nom du fichier cible ; sinon, c'est un répertoire et le nom stocké est utilisé.\n\nExample: Exporter un fichier\n```js\nFILESTORAGE('files').copy('readme', PATH.tmp(), function(err, meta) {\n\tconsole.log(PATH.tmp(meta.name));\n});\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method`\n\nDuplique un fichier sous un nouvel id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du fichier source. |\n| `newid` | `String` | no | `UID()` | Le nouvel id. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `Promise|undefined`\n\nCopie le fichier stocké avec ses métadonnées vers un nouvel id et l'ajoute à l'index. Sans `newid` (aussi quand le callback est le deuxième argument, ou dans la forme Promise), un nouvel id de `UID()` est utilisé ; le callback et la Promise reçoivent les métadonnées avec le nouvel id.\n\nExample: Cloner\n```js\nFILESTORAGE('files').clone('template', function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\nExample: Promise\n```js\nvar meta = await FILESTORAGE('files').clone('template');\nconsole.log(meta.id); // a new UID\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nListe les fichiers à partir de l'index.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, files)`. |\n\nReturns: `QueryBuilder` Un query builder NoSQL.\n\nRenvoie un query builder NoSQL sur `files.log` ; tu peux ainsi utiliser `where()`, `sort()`, `take()`, `fields()` et les autres méthodes de [NoSQL](../../guides/nosql/). Chaque enregistrement correspond aux métadonnées d'un fichier.\n\nExample: Derniers fichiers PDF\n```js\nFILESTORAGE('files').browse().where('ext', 'pdf').sort('date', true).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 |  | Appelé sous la forme `callback(err, files)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nLit l'en-tête de chaque fichier du répertoire et renvoie le tableau des métadonnées, chacune avec `id` et `index` ; les fichiers expirés sont ignorés. Elle n'utilise pas l'index ; elle est donc plus lente que `browse()` mais correspond toujours au disque.\n\nExample: Tous les fichiers\n```js\nvar files = await FILESTORAGE('files').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nParcourt tous les fichiers du stockage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | Appelé sous la forme `onfile(meta, next)`. |\n| `callback` | `Function` | no |  | Appelé lorsque tous les fichiers ont été traités. |\n| `workers` | `Number` | no | `2` | Les fichiers en parallèle. |\n\nReturns: `FileStorage`\n\nAppelle `onfile(meta, next)` pour chaque fichier sur le disque avec ses métadonnées (sans contenu), `id` et un numéro de séquence `index` ; les fichiers expirés sont ignorés. Appelle `next()` pour continuer. `workers` est le nombre de fichiers traités simultanément dans un répertoire.\n\nExample: Taille totale\n```js\nvar size = 0;\nFILESTORAGE('files').stream(function(meta, next) {\n\tsize += meta.size;\n\tnext();\n}, () => console.log(size));\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 |  | Appelé sous la forme `callback(err, count)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nCompte les fichiers dans les répertoires de groupe du stockage.\n\nExample: Compter\n```js\nvar count = await FILESTORAGE('files').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nReconstruit l'index à partir du disque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback()`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nLit les métadonnées de tous les fichiers et réécrit `files.log`. Utilise-la après `restore()` ou après avoir copié des fichiers `.file` dans le répertoire. `save()`, `read()`, `readbuffer()`, `copy()` et `clone()` attendent pendant l'écriture de l'index.\n\nExample: Reconstruire\n```js\nawait FILESTORAGE('files').rebuild();\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nSupprime tous les fichiers du stockage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, count)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nSupprime chaque fichier, les répertoires des groupes et l'index. `save()`, `read()`, `readbuffer()`, `copy()` et `clone()` attendent jusqu'à la fin. Appelle-la seulement quand le répertoire du stockage existe : sinon elle se termine par une erreur et le stockage reste en pause. Le callback reçoit le nombre de fichiers supprimés. `fs.drop()` est un alias.\n\nExample: Vider\n```js\nFILESTORAGE('tmp').clear(function(err, count) {\n\tconsole.log('Removed', count);\n});\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nUn alias de fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, count)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nFonctionne exactement comme `fs.clear()`.\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nSauvegarde tout le stockage dans un seul fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Un nom de fichier cible ou un flux inscriptible. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, result)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `Promise|undefined`\n\nÉcrit chaque fichier, compressé en GZIP et encodé en base64, dans un fichier texte (ou un flux inscriptible). L'index `files.log` n'est pas inclus. Le résultat est `{ filename, files, size }`.\n\nExample: Sauvegarde\n```js\nvar result = await FILESTORAGE('files').backup(PATH.root('files.backup'));\nconsole.log(result.files, result.size);\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nRestaure une sauvegarde.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Un nom de fichier de sauvegarde ou un flux lisible. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `Promise|undefined`\n\nSupprime tous les fichiers actuels et extrait dans le répertoire un fichier créé par `fs.backup()`. `save()`, `read()`, `readbuffer()`, `copy()` et `clone()` attendent jusqu'à la fin. Appelle ensuite `fs.rebuild()` pour créer l'index.\n\nExample: Restaurer et indexer\n```js\nvar fs = FILESTORAGE('files');\nfs.restore(PATH.root('files.backup'), function(err) {\n\t!err && fs.rebuild();\n});\n```\n\n### meta\n\nType: `type`\n\nLes métadonnées d'un fichier stocké.\n\nRenvoyées par `save()`, `read()`, `readmeta()` et les autres méthodes, et stockées dans l'en-tête de chaque fichier :\n\n- `id` {String} : l'id,\n- `name` {String} : le nom du fichier,\n- `ext` {String} : l'extension sans le point,\n- `type` {String} : le type de contenu,\n- `size` {Number} : la taille du contenu en octets,\n- `width`, `height` {Number} : les dimensions des images JPEG, PNG, GIF et SVG,\n- `custom` {Object} : tes données personnalisées ou `null`,\n- `date` {Date} : la date d'enregistrement du fichier,\n- `expire` {Date} : la date d'expiration du fichier (uniquement si elle est définie).\n\n`read()` ajoute `stream`, et `stream()` et `browse2()` ajoutent `index`.\n\n### ROUTE('POST /url/ @upload')\n\nType: `type`\n\nUn flag de route pour les uploads multipart.\n\nUne route avec `@upload` ne correspond qu'aux requêtes `multipart/form-data`. Les fichiers uploadés se trouvent dans `$.files` (aussi dans les actions), les autres champs dans `$.body`. Combine-le avec un flag de taille comme `<10MB`.\n\nExample: Une route d'upload\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', function($) {\n\t\tvar file = $.files[0];\n\t\tfile.fs('files', UID(), $.callback());\n\t});\n};\n```\n\n### file.fs(storage, id, [callback])\n\nType: `method`\n\nEnregistre un fichier uploadé dans un stockage de fichiers.\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| `callback` | `Function` | no |  | Appelé sous la forme `callback(err, meta)`. Sans lui, la méthode renvoie une `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nUne méthode de `HttpFile` (les éléments de `$.files`). Enregistre le fichier temporaire dans `FILESTORAGE(storage)` avec son nom de fichier original et renvoie les métadonnées.\n\nExample: Enregistrer tous les uploads\n```js\nfunction upload($) {\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), next);\n\t}, () => $.success());\n}\n```\n\n### Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])\n\nType: `method`\n\nLit un fichier par morceaux, avec la progression.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le chemin du fichier. |\n| `onbuffer` | `Function` | yes |  | Appelée sous la forme `onbuffer(buffer, next, percentage)` ; `next(true)` arrête la lecture. |\n| `onend` | `Function` | no |  | Appelée sous la forme `onend(err)` à la fin, après un arrêt ou en cas d'erreur. |\n| `size` | `Number` | no | `16384` | La taille d'un morceau en octets. |\n| `offset` | `Number` | no | `0` | La position en octets où la lecture commence. |\n\nReturns: `undefined`\n\nLit un fichier par morceaux de `size` octets (par défaut 16384) à partir de `offset` (par défaut 0) et appelle `onbuffer(buffer, next, percentage)` pour chaque morceau. `percentage` est la part du fichier lue jusqu'ici, de 0 à 100. Appelle `next()` pour lire le morceau suivant ou `next(true)` pour arrêter. `onend(err)` est appelée à la fin du fichier, après un arrêt, ou avec l'erreur lorsque le fichier n'existe pas. Lorsque le troisième argument est un nombre, c'est la taille.\n\nExample: Calculer le hash d'un fichier\n```js\nvar hash = F.Crypto.createHash('sha1');\nUtils.filestreamer(PATH.root('big.iso'), function(buffer, next) {\n\thash.update(buffer);\n\tnext();\n}, function(err) {\n\tconsole.log(hash.digest('hex'));\n});\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"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":"method","name":"fs.storage()","signature":"fs.storage(path)","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback])","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.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"fs.makedirectory()","signature":"fs.makedirectory(id)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.http()","signature":"fs.http($, opt)","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [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.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([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":"type","name":"File meta","signature":"meta","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('POST /url/ @upload')","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [callback])","since":"","deprecated":false},{"type":"method","name":"Utils.filestreamer()","signature":"Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCK2Xc60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/file-storage/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Archivio di file","summary":"FILESTORAGE() e i suoi metodi, i metadati dei file, il flag @upload e file.fs().","markdown":"---\ntitle: Archivio di file\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/file-storage/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Archivio di file\n\n> FILESTORAGE() e i suoi metodi, i metadati dei file, il flag @upload e file.fs().\n\nMetodi di un file storage restituito da `FILESTORAGE(name)` (indicato più avanti come `fs`), i metadati dei file salvati, il flag di route `@upload`, `file.fs()` per i file caricati e `Utils.filestreamer()`. Per un'introduzione con esempi leggi la guida [File storage](../../guides/file-storage/).\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nRestituisce un file storage in base al suo nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'archivio. |\n\nReturns: `FileStorage` Il file storage.\n\nCrea lo storage alla prima chiamata e in seguito restituisce la stessa istanza per lo stesso nome. I file vengono salvati in `/databases/fs-{name}/`; la directory viene creata al primo salvataggio. Cambiala con `fs.storage(path)`.\n\nExample: Salvare e leggere un file\n```js\nvar fs = FILESTORAGE('files');\n\nfs.save('readme', 'readme.txt', Buffer.from('Hello'), function(err, meta) {\n\tfs.readbuffer('readme', function(err, buffer) {\n\t\tconsole.log(buffer.toString('utf8'));\n\t});\n});\n```\n\n### fs.name\n\nType: `property`\n\nIl nome dell'archivio.\n\nReturns: `String`\n\nIl nome passato a `FILESTORAGE(name)`.\n\n### fs.directory\n\nType: `property`\n\nLa directory dello storage.\n\nReturns: `String`\n\nIl percorso assoluto della directory con i file, per impostazione predefinita `/databases/fs-{name}/`. Impostalo con `fs.storage(path)`.\n\n### fs.storage(path)\n\nType: `method`\n\nCambia la directory dello storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un percorso assoluto della directory. |\n\nReturns: `FileStorage` Lo storage stesso.\n\nImposta `fs.directory` e il percorso dell'indice `files.log` al suo interno. Chiamalo prima di usare lo storage, per esempio in un file di definizione.\n\nExample: Un altro disco\n```js\nFILESTORAGE('videos').storage('/mnt/media/videos/');\n```\n\n### fs.save(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nSalva un file nello storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Il tuo identificatore del file, per esempio da `UID()`. |\n| `name` | `String` | yes |  | Il nome del file con la sua estensione. |\n| `source` | `String|Buffer|Stream` | yes |  | Un percorso, un `Buffer`, uno stream leggibile o un URL `https://`. |\n| `custom` | `Object` | no | `null` | Dati personalizzati salvati con il file. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n| `expire` | `String` | no |  | Un tempo dopo il quale il file non può più essere letto, come `'1 day'`. |\n| `headers` | `Object` | no |  | Header HTTP per scaricare un URL. |\n\nReturns: `FileStorage|Promise` Lo storage, oppure una `Promise` con i metadati senza callback.\n\n`source` è un percorso su disco, un `Buffer`, uno stream leggibile o un URL `https://` che viene scaricato. L'estensione di `name` decide il content type; le immagini JPEG, PNG, GIF e SVG ottengono `width` e `height`. Un percorso in `name` viene rimosso e un nome più lungo di 250 caratteri viene accorciato. Quando ometti `source`, `name` viene usato come percorso del file e la sua ultima parte come nome. Salvare di nuovo con un id esistente sostituisce il file. `fs.insert()` è un alias.\n\nLa callback riceve i metadati: `id`, `name`, `ext`, `type`, `size`, `width`, `height`, `custom`, `date` ed `expire`.\n\nExample: Da un file su disco\n```js\nFILESTORAGE('files').save(UID(), 'report.pdf', PATH.root('report.pdf'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Con dati personalizzati e scadenza\n```js\nvar meta = await FILESTORAGE('exports').save(UID(), 'export.csv', Buffer.from(csv), { userid: $.user.id }, null, '1 day');\n```\n\n### fs.insert(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nUn alias di fs.save().\n\nReturns: `FileStorage|Promise`\n\nFunziona esattamente come `fs.save()`.\n\n### fs.savejson(id, value, [callback])\n\nType: `method`\n\nSalva un valore come file JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del file. |\n| `value` | `Object` | yes |  | Un valore da serializzare. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nSerializza `value` con `JSON.stringify()` e lo salva come `{id}.json` (content type `application/json`). Rileggilo con `fs.readjson()`.\n\nExample: Salvare le impostazioni\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' }, function(err, meta) {});\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 |  | Chiamata come `callback(err, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n| `nostream` | `Boolean` | no | `false` | `true` restituisce solo i metadati. |\n\nReturns: `FileStorage|Promise`\n\nLa callback riceve i metadati con uno stream leggibile del contenuto in `meta.stream`. Consuma lo stream: tiene il file aperto finché non termina. Con `nostream` impostato a `true` vengono restituiti solo i metadati. Un file scaduto termina con l'errore `File is expired`, uno mancante con un errore del file system.\n\nExample: Inviare in pipe a un file\n```js\nFILESTORAGE('files').read('readme', function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.tmp(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 |  | Chiamata come `callback(err, meta, filename, fd)`. Senza di essa il metodo restituisce una `Promise`. |\n| `keepfd` | `Boolean` | no | `false` | `true` mantiene aperto il file descriptor e lo passa alla callback. |\n\nReturns: `FileStorage|Promise`\n\nLegge l'header del file e converte le date in oggetti `Date`. La callback riceve anche il percorso del `.file` e, con `keepfd`, il file descriptor aperto, che devi chiudere con `F.Fs.close()`. La scadenza non viene verificata.\n\nExample: Verificare un file\n```js\nvar meta = await FILESTORAGE('files').readmeta('readme');\nconsole.log(meta.name, meta.size, meta.date);\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nLegge l'intero contenuto in un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del file. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, buffer, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nUsalo per i file piccoli; per i file grandi usa lo stream di `fs.read()`. La promise si risolve solo con il buffer.\n\nExample: Leggere un file\n```js\nvar buffer = await FILESTORAGE('files').readbuffer('readme');\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nLegge il contenuto come stringa base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del file. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, base64, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nComodo per i data URI e le API JSON. La promise si risolve solo con la stringa.\n\nExample: Un data URI\n```js\nFILESTORAGE('photos').readbase64('avatar', 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 |  | Chiamata come `callback(err, value, meta)`. |\n\nReturns: `FileStorage`\n\nLegge il contenuto e lo analizza come JSON (date comprese). 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.readfilename(id)\n\nType: `method`\n\nRestituisce il percorso del file salvato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del file. |\n\nReturns: `String` Il percorso.\n\nRestituisce il percorso assoluto di `{group}/{id}.file`. Il file inizia con un header di 2000 byte, quindi non servirlo direttamente.\n\n### fs.makedirectory(id)\n\nType: `method`\n\nRestituisce la directory per un id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del file. |\n\nReturns: `String` Il percorso.\n\nRestituisce il percorso della directory di gruppo di quattro cifre in cui è salvato il file con questo id. Non crea la directory.\n\n### fs.image(id, [callback])\n\nType: `method`\n\nCarica un file salvato come immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del file. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, image, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nRestituisce un oggetto immagine di [Immagini](../../guides/images/) che legge il contenuto del file. Trasformalo e salvalo o invialo in pipe.\n\nExample: Creare una miniatura\n```js\nFILESTORAGE('photos').image('avatar', function(err, image) {\n\timage.resize(100, 100);\n\timage.save(PATH.public('thumbs/avatar.jpg'), function(err) {});\n});\n```\n\n### fs.http($, opt)\n\nType: `method`\n\nInvia un file salvato come risposta HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | Il controller della richiesta. |\n| `opt` | `Object` | yes |  | Le opzioni: `id`, `download`, `check`, `image`, `cache`. |\n\nReturns: `undefined`\n\nImposta il content type, `Last-Modified`, `X-Size` (e `X-Width`, `X-Height` per le immagini) e la cache HTTP (non in modalità debug), risponde `304` per una versione corrente nel browser e supporta le richieste `Range` con `206`. Un file mancante o scaduto, oppure un `check` che restituisce `false`, termina con `404`; un id di questo tipo continua a ricevere `404` fino alla successiva pulizia della cache del framework.\n\nOpzioni: `id`; `download` (`true` per il nome salvato, una stringa, oppure una funzione `(name, type)` che restituisce il nome); `check` (una funzione `(meta)`); `image` (una funzione `(image)` con il controller come `this`, per i file immagine); `cache` (una chiave con cui un'immagine trasformata viene conservata nella directory temporanea). Il metodo del controller `$.filefs()` ne è una scorciatoia.\n\nExample: Servire e scaricare\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id });\n\t});\n\tROUTE('GET /download/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id, download: true });\n\t});\n};\n```\n\nExample: Un'immagine ridimensionata\n```js\nROUTE('GET /thumbs/{id}/', function($) {\n\tFILESTORAGE('photos').http($, {\n\t\tid: $.params.id,\n\t\tcache: 'thumb-' + $.params.id,\n\t\timage: image => image.resize(200, 200)\n\t});\n});\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 |  | Chiamata come `callback(err)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nElimina il `.file` e la sua riga nell'indice. La callback riceve un errore del file system quando il file non esiste.\n\nExample: Rimuovere un file\n```js\nFILESTORAGE('files').remove($.params.id, function(err) {\n\t$.success();\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. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nScrive il nuovo nome nell'header del file e nell'indice. L'id e il contenuto restano invariati. Un nome più lungo di 250 caratteri viene accorciato.\n\nExample: Rinominare\n```js\nawait FILESTORAGE('files').rename('readme', 'README.md');\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method`\n\nCopia il contenuto di un file fuori dallo storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del file. |\n| `path` | `String` | yes |  | Un nome di file di destinazione o una directory. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `Promise|undefined`\n\nScrive il contenuto senza l'header. Quando `path` contiene un punto è il nome del file di destinazione, altrimenti è una directory e viene usato il nome salvato.\n\nExample: Esportare un file\n```js\nFILESTORAGE('files').copy('readme', PATH.tmp(), function(err, meta) {\n\tconsole.log(PATH.tmp(meta.name));\n});\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method`\n\nDuplica un file con un nuovo id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del file di origine. |\n| `newid` | `String` | no | `UID()` | Il nuovo id. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `Promise|undefined`\n\nCopia il file salvato con i suoi metadati in un nuovo id e lo aggiunge all'indice. Senza `newid` (anche quando la callback è il secondo argomento, o nella forma con Promise) viene usato un nuovo id da `UID()`; la callback e la Promise ricevono i metadati con il nuovo id.\n\nExample: Clonare\n```js\nFILESTORAGE('files').clone('template', function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\nExample: Promise\n```js\nvar meta = await FILESTORAGE('files').clone('template');\nconsole.log(meta.id); // a new UID\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nElenca i file dall'indice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, files)`. |\n\nReturns: `QueryBuilder` Un query builder NoSQL.\n\nRestituisce un query builder NoSQL su `files.log`, così puoi usare `where()`, `sort()`, `take()`, `fields()` e gli altri metodi di [NoSQL](../../guides/nosql/). Ogni record è costituito dai metadati di un file.\n\nExample: Ultimi file PDF\n```js\nFILESTORAGE('files').browse().where('ext', 'pdf').sort('date', true).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 |  | Chiamata come `callback(err, files)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nLegge l'header di ogni file nella directory e restituisce l'array dei metadati, ciascuno con `id` e `index`; i file scaduti vengono saltati. Non usa l'indice, quindi è più lento di `browse()` ma corrisponde sempre al disco.\n\nExample: Tutti i file\n```js\nvar files = await FILESTORAGE('files').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nScorre tutti i file dello storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | Chiamata come `onfile(meta, next)`. |\n| `callback` | `Function` | no |  | Chiamata quando tutti i file sono stati elaborati. |\n| `workers` | `Number` | no | `2` | File in parallelo. |\n\nReturns: `FileStorage`\n\nChiama `onfile(meta, next)` per ogni file su disco con i suoi metadati (senza contenuto), `id` e un numero progressivo `index`; i file scaduti vengono saltati. Chiama `next()` per continuare. `workers` è il numero di file elaborati contemporaneamente in una directory.\n\nExample: Dimensione totale\n```js\nvar size = 0;\nFILESTORAGE('files').stream(function(meta, next) {\n\tsize += meta.size;\n\tnext();\n}, () => console.log(size));\n```\n\n### fs.count2([callback])\n\nType: `method`\n\nConta i file su disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, count)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nConta i file nelle directory di gruppo dello storage.\n\nExample: Count\n```js\nvar count = await FILESTORAGE('files').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nRicostruisce l'indice dal disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata come `callback()`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nLegge i metadati di tutti i file e riscrive `files.log`. Usalo dopo `restore()` o dopo aver copiato file `.file` nella cartella. `save()`, `read()`, `readbuffer()`, `copy()` e `clone()` aspettano mentre l'indice viene scritto.\n\nExample: Ricostruire\n```js\nawait FILESTORAGE('files').rebuild();\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nRimuove tutti i file dello storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, count)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nElimina ogni file, le cartelle dei gruppi e l'indice. `save()`, `read()`, `readbuffer()`, `copy()` e `clone()` aspettano finché non termina. Chiamalo solo quando la cartella dello storage esiste: altrimenti termina con un errore e lo storage resta in pausa. La callback riceve il numero di file rimossi. `fs.drop()` è un alias.\n\nExample: Svuotare\n```js\nFILESTORAGE('tmp').clear(function(err, count) {\n\tconsole.log('Removed', count);\n});\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nUn alias di fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, count)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nFunziona esattamente come `fs.clear()`.\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nEsegue il backup dell'intero storage in un unico file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Un nome di file di destinazione o uno stream scrivibile. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, result)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `Promise|undefined`\n\nScrive ogni file, compresso con GZIP e codificato in base64, in un file di testo (o in uno stream scrivibile). L'indice `files.log` non è incluso. Il risultato è `{ filename, files, size }`.\n\nExample: Backup\n```js\nvar result = await FILESTORAGE('files').backup(PATH.root('files.backup'));\nconsole.log(result.files, result.size);\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nRipristina un backup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Un nome di file di backup o uno stream leggibile. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `Promise|undefined`\n\nRimuove tutti i file attuali ed estrae nella cartella un file creato da `fs.backup()`. `save()`, `read()`, `readbuffer()`, `copy()` e `clone()` aspettano finché non termina. Chiama poi `fs.rebuild()` per creare l'indice.\n\nExample: Ripristinare e indicizzare\n```js\nvar fs = FILESTORAGE('files');\nfs.restore(PATH.root('files.backup'), function(err) {\n\t!err && fs.rebuild();\n});\n```\n\n### meta\n\nType: `type`\n\nI metadati di un file salvato.\n\nRestituiti da `save()`, `read()`, `readmeta()` e dagli altri metodi e salvati nell'header di ogni file:\n\n- `id` {String}: l'id,\n- `name` {String}: il nome del file,\n- `ext` {String}: l'estensione senza il punto,\n- `type` {String}: il content type,\n- `size` {Number}: la dimensione del contenuto in byte,\n- `width`, `height` {Number}: dimensioni delle immagini JPEG, PNG, GIF e SVG,\n- `custom` {Object}: i tuoi dati personalizzati oppure `null`,\n- `date` {Date}: quando il file è stato salvato,\n- `expire` {Date}: quando il file scade (solo se impostato).\n\n`read()` aggiunge `stream`, mentre `stream()` e `browse2()` aggiungono `index`.\n\n### ROUTE('POST /url/ @upload')\n\nType: `type`\n\nUn flag di route per gli upload multipart.\n\nUna route con `@upload` corrisponde solo alle richieste `multipart/form-data`. I file caricati si trovano in `$.files` (anche nelle azioni), gli altri campi in `$.body`. Combinalo con un flag di dimensione come `<10MB`.\n\nExample: Una route di upload\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', function($) {\n\t\tvar file = $.files[0];\n\t\tfile.fs('files', UID(), $.callback());\n\t});\n};\n```\n\n### file.fs(storage, id, [callback])\n\nType: `method`\n\nSalva un file caricato in un file storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Il nome dello storage. |\n| `id` | `String` | yes |  | L'id del file. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err, meta)`. Senza di essa il metodo restituisce una `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nUn metodo di `HttpFile` (gli elementi di `$.files`). Salva il file temporaneo in `FILESTORAGE(storage)` con il suo nome di file originale e restituisce i metadati.\n\nExample: Salvare tutti gli upload\n```js\nfunction upload($) {\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), next);\n\t}, () => $.success());\n}\n```\n\n### Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])\n\nType: `method`\n\nLegge un file a blocchi, con l'avanzamento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il percorso del file. |\n| `onbuffer` | `Function` | yes |  | Chiamata come `onbuffer(buffer, next, percentage)`; `next(true)` interrompe la lettura. |\n| `onend` | `Function` | no |  | Chiamata come `onend(err)` alla fine, dopo un'interruzione o in caso di errore. |\n| `size` | `Number` | no | `16384` | La dimensione di un blocco in byte. |\n| `offset` | `Number` | no | `0` | La posizione in byte da cui inizia la lettura. |\n\nReturns: `undefined`\n\nLegge un file a blocchi di `size` byte (predefinito 16384) a partire da `offset` (predefinito 0) e chiama `onbuffer(buffer, next, percentage)` per ogni blocco. `percentage` è la parte del file letta finora, da 0 a 100. Chiama `next()` per leggere il blocco successivo o `next(true)` per fermarti. `onend(err)` viene chiamata alla fine del file, dopo un'interruzione, oppure con l'errore quando il file non esiste. Quando il terzo argomento è un numero, è la dimensione.\n\nExample: Calcolare l'hash di un file\n```js\nvar hash = F.Crypto.createHash('sha1');\nUtils.filestreamer(PATH.root('big.iso'), function(buffer, next) {\n\thash.update(buffer);\n\tnext();\n}, function(err) {\n\tconsole.log(hash.digest('hex'));\n});\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"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":"method","name":"fs.storage()","signature":"fs.storage(path)","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback])","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.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"fs.makedirectory()","signature":"fs.makedirectory(id)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.http()","signature":"fs.http($, opt)","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [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.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([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":"type","name":"File meta","signature":"meta","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('POST /url/ @upload')","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [callback])","since":"","deprecated":false},{"type":"method","name":"Utils.filestreamer()","signature":"Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCK2Xc60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/file-storage/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Úložisko súborov","summary":"FILESTORAGE() a jeho metódy, metadáta súborov, príznak @upload a file.fs().","markdown":"---\ntitle: \"Úložisko súborov\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/file-storage/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Úložisko súborov\n\n> FILESTORAGE() a jeho metódy, metadáta súborov, príznak @upload a file.fs().\n\nMetódy úložiska súborov, ktoré vracia `FILESTORAGE(name)` (nižšie zapísané ako `fs`), metadáta uložených súborov, príznak routy `@upload`, `file.fs()` pre nahrané súbory a `Utils.filestreamer()`. Úvod s príkladmi nájdeš v návode [Úložisko súborov](../../guides/file-storage/).\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nVráti úložisko súborov podľa jeho názvu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov úložiska. |\n\nReturns: `FileStorage` Úložisko súborov.\n\nPri prvom volaní vytvorí úložisko a potom pre rovnaký názov vracia tú istú inštanciu. Súbory sa ukladajú do `/databases/fs-{name}/`; priečinok sa vytvorí pri prvom uložení. Zmeníš ho cez `fs.storage(path)`.\n\nExample: Uloženie a prečítanie súboru\n```js\nvar fs = FILESTORAGE('files');\n\nfs.save('readme', 'readme.txt', Buffer.from('Hello'), function(err, meta) {\n\tfs.readbuffer('readme', function(err, buffer) {\n\t\tconsole.log(buffer.toString('utf8'));\n\t});\n});\n```\n\n### fs.name\n\nType: `property`\n\nNázov úložiska.\n\nReturns: `String`\n\nNázov zadaný do `FILESTORAGE(name)`.\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, predvolene `/databases/fs-{name}/`. Nastavíš ju cez `fs.storage(path)`.\n\n### fs.storage(path)\n\nType: `method`\n\nZmení priečinok úložiska.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Absolútna cesta k priečinku. |\n\nReturns: `FileStorage` Samotné úložisko.\n\nNastaví `fs.directory` a cestu k indexu `files.log` v ňom. Zavolaj ju skôr, než úložisko použiješ, napríklad v definičnom súbore.\n\nExample: Iný disk\n```js\nFILESTORAGE('videos').storage('/mnt/media/videos/');\n```\n\n### fs.save(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nUloží súbor do úložiska.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Tvoj identifikátor súboru, napríklad z `UID()`. |\n| `name` | `String` | yes |  | Názov súboru s príponou. |\n| `source` | `String|Buffer|Stream` | yes |  | Cesta, `Buffer`, čitateľný stream alebo URL `https://`. |\n| `custom` | `Object` | no | `null` | Vlastné dáta uložené so súborom. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, meta)`. Bez neho metóda vráti `Promise`. |\n| `expire` | `String` | no |  | Čas, po ktorom sa súbor už nedá prečítať, napríklad `'1 day'`. |\n| `headers` | `Object` | no |  | HTTP hlavičky pre stiahnutie URL. |\n\nReturns: `FileStorage|Promise` Úložisko, alebo bez callbacku `Promise` s metadátami.\n\n`source` je cesta na disku, `Buffer`, čitateľný stream alebo URL `https://`, ktorá sa stiahne. Prípona `name` určuje typ obsahu; obrázky JPEG, PNG, GIF a SVG dostanú `width` a `height`. Cesta v `name` sa odstráni a názov dlhší ako 250 znakov sa skráti. Keď `source` vynecháš, `name` sa použije ako cesta k súboru a jej posledná časť ako názov. Opätovné uloženie s existujúcim id súbor nahradí. `fs.insert()` je alias.\n\nCallback dostane metadáta: `id`, `name`, `ext`, `type`, `size`, `width`, `height`, `custom`, `date` a `expire`.\n\nExample: Zo súboru na disku\n```js\nFILESTORAGE('files').save(UID(), 'report.pdf', PATH.root('report.pdf'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: S vlastnými dátami a expiráciou\n```js\nvar meta = await FILESTORAGE('exports').save(UID(), 'export.csv', Buffer.from(csv), { userid: $.user.id }, null, '1 day');\n```\n\n### fs.insert(id, name, source, [custom], [callback], [expire], [headers])\n\nType: `method`\n\nAlias fs.save().\n\nReturns: `FileStorage|Promise`\n\nFunguje presne ako `fs.save()`.\n\n### fs.savejson(id, value, [callback])\n\nType: `method`\n\nUloží hodnotu ako JSON súbor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id súboru. |\n| `value` | `Object` | yes |  | Hodnota na serializáciu. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, meta)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nSerializuje `value` cez `JSON.stringify()` a uloží ju ako `{id}.json` (typ obsahu `application/json`). Späť ju prečítaš cez `fs.readjson()`.\n\nExample: Uloženie nastavení\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' }, function(err, meta) {});\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 |  | Volá sa ako `callback(err, meta)`. Bez neho metóda vráti `Promise`. |\n| `nostream` | `Boolean` | no | `false` | `true` vráti iba metadáta. |\n\nReturns: `FileStorage|Promise`\n\nCallback dostane metadáta s čitateľným streamom obsahu v `meta.stream`. Stream spotrebuj: drží súbor otvorený, kým neskončí. Keď je `nostream` nastavené na `true`, vrátia sa iba metadáta. Súbor s uplynutou platnosťou skončí chybou `File is expired`, chýbajúci súbor chybou súborového systému.\n\nExample: Presmerovanie do súboru\n```js\nFILESTORAGE('files').read('readme', function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.tmp(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 |  | Volá sa ako `callback(err, meta, filename, fd)`. Bez neho metóda vráti `Promise`. |\n| `keepfd` | `Boolean` | no | `false` | `true` ponechá deskriptor súboru otvorený a odovzdá ho callbacku. |\n\nReturns: `FileStorage|Promise`\n\nPrečíta hlavičku súboru a dátumy prevedie na objekty `Date`. Callback dostane aj cestu k `.file` a s `keepfd` otvorený deskriptor súboru, ktorý musíš zatvoriť cez `F.Fs.close()`. Platnosť sa nekontroluje.\n\nExample: Kontrola súboru\n```js\nvar meta = await FILESTORAGE('files').readmeta('readme');\nconsole.log(meta.name, meta.size, meta.date);\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nNačíta celý obsah do Buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id súboru. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, buffer, meta)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nPoužívaj ju pre malé súbory; veľké súbory streamuj cez `fs.read()`. Promise sa vyrieši iba s bufferom.\n\nExample: Prečítanie súboru\n```js\nvar buffer = await FILESTORAGE('files').readbuffer('readme');\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nPrečíta obsah ako base64 reťazec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id súboru. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, base64, meta)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nHodí sa pre data URI a JSON API. Promise sa vyrieši iba s reťazcom.\n\nExample: Data URI\n```js\nFILESTORAGE('photos').readbase64('avatar', 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 |  | Volá sa ako `callback(err, value, meta)`. |\n\nReturns: `FileStorage`\n\nPrečíta obsah a spracuje ho ako JSON (vrátane dátumov). 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.readfilename(id)\n\nType: `method`\n\nVráti cestu k uloženému súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id súboru. |\n\nReturns: `String` Cesta.\n\nVráti absolútnu cestu k `{group}/{id}.file`. Súbor začína 2000-bajtovou hlavičkou, preto ho neservíruj priamo.\n\n### fs.makedirectory(id)\n\nType: `method`\n\nVráti priečinok pre id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id súboru. |\n\nReturns: `String` Cesta.\n\nVráti cestu k štvorcifernému skupinovému priečinku, v ktorom je uložený súbor s týmto id. Priečinok nevytvára.\n\n### fs.image(id, [callback])\n\nType: `method`\n\nNačíta uložený súbor ako obrázok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id súboru. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, image, meta)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nVráti objekt obrázka z [Obrázky](../../guides/images/), ktorý číta obsah súboru. Transformuj ho a ulož alebo presmeruj (pipe).\n\nExample: Vytvorenie náhľadu\n```js\nFILESTORAGE('photos').image('avatar', function(err, image) {\n\timage.resize(100, 100);\n\timage.save(PATH.public('thumbs/avatar.jpg'), function(err) {});\n});\n```\n\n### fs.http($, opt)\n\nType: `method`\n\nPošle uložený súbor ako HTTP odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | Kontrolér požiadavky. |\n| `opt` | `Object` | yes |  | Voľby: `id`, `download`, `check`, `image`, `cache`. |\n\nReturns: `undefined`\n\nNastaví typ obsahu, `Last-Modified`, `X-Size` (a pri obrázkoch `X-Width`, `X-Height`) a HTTP cache (nie v režime debug), odpovie `304` pre aktuálnu verziu v prehliadači a podporuje požiadavky `Range` so `206`. Chýbajúci súbor alebo súbor s uplynutou platnosťou, prípadne `check`, ktorý vráti `false`, skončí `404`; takéto id odpovedá `404` až do nasledujúceho čistenia cache frameworku.\n\nVoľby: `id`; `download` (`true` pre uložený názov, reťazec, alebo funkcia `(name, type)`, ktorá vráti názov); `check` (funkcia `(meta)`); `image` (funkcia `(image)` s `this` ako kontrolérom, pre obrázkové súbory); `cache` (kľúč, pod ktorým sa transformovaný obrázok uchová v dočasnom priečinku). Metóda kontroléra `$.filefs()` je skratka.\n\nExample: Servírovanie a stiahnutie\n```js\nexports.install = function() {\n\tROUTE('GET /files/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id });\n\t});\n\tROUTE('GET /download/{id}/', function($) {\n\t\tFILESTORAGE('files').http($, { id: $.params.id, download: true });\n\t});\n};\n```\n\nExample: Obrázok so zmenenou veľkosťou\n```js\nROUTE('GET /thumbs/{id}/', function($) {\n\tFILESTORAGE('photos').http($, {\n\t\tid: $.params.id,\n\t\tcache: 'thumb-' + $.params.id,\n\t\timage: image => image.resize(200, 200)\n\t});\n});\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 |  | Volá sa ako `callback(err)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nVymaže `.file` a jeho riadok v indexe. Keď súbor neexistuje, callback dostane chybu súborového systému.\n\nExample: Odstránenie súboru\n```js\nFILESTORAGE('files').remove($.params.id, function(err) {\n\t$.success();\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. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, meta)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nZapíše nový názov do hlavičky súboru a do indexu. Id aj obsah zostanú rovnaké. Názov dlhší ako 250 znakov sa skráti.\n\nExample: Premenovanie\n```js\nawait FILESTORAGE('files').rename('readme', 'README.md');\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method`\n\nSkopíruje obsah súboru mimo úložiska.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id súboru. |\n| `path` | `String` | yes |  | Cieľový názov súboru alebo priečinok. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, meta)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `Promise|undefined`\n\nZapíše obsah bez hlavičky. Keď `path` obsahuje bodku, je to cieľový názov súboru, inak je to priečinok a použije sa uložený názov.\n\nExample: Export súboru\n```js\nFILESTORAGE('files').copy('readme', PATH.tmp(), function(err, meta) {\n\tconsole.log(PATH.tmp(meta.name));\n});\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method`\n\nZduplikuje súbor pod novým id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id zdrojového súboru. |\n| `newid` | `String` | no | `UID()` | Nové id. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, meta)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `Promise|undefined`\n\nSkopíruje uložený súbor s jeho metadátami pod nové id a pridá ho do indexu. Bez `newid` (aj keď je callback druhým argumentom, alebo vo forme s Promise) sa použije nové id z `UID()`; callback aj Promise dostanú metadáta s novým id.\n\nExample: Klonovanie\n```js\nFILESTORAGE('files').clone('template', function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\nExample: Promise\n```js\nvar meta = await FILESTORAGE('files').clone('template');\nconsole.log(meta.id); // a new UID\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nVypíše súbory z indexu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, files)`. |\n\nReturns: `QueryBuilder` NoSQL query builder.\n\nVráti NoSQL query builder nad `files.log`, takže môžeš použiť `where()`, `sort()`, `take()`, `fields()` a ďalšie metódy z [NoSQL](../../guides/nosql/). Každý záznam sú metadáta jedného súboru.\n\nExample: Najnovšie PDF súbory\n```js\nFILESTORAGE('files').browse().where('ext', 'pdf').sort('date', true).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 |  | Volá sa ako `callback(err, files)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nPrečíta hlavičku každého súboru v priečinku a vráti pole metadát, každé s `id` a `index`; súbory s uplynutou platnosťou sa preskočia. Nepoužíva index, preto je pomalšia ako `browse()`, ale vždy zodpovedá disku.\n\nExample: Všetky súbory\n```js\nvar files = await FILESTORAGE('files').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nPrejde všetky súbory úložiska.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | Volá sa ako `onfile(meta, next)`. |\n| `callback` | `Function` | no |  | Volá sa, keď boli spracované všetky súbory. |\n| `workers` | `Number` | no | `2` | Paralelné súbory. |\n\nReturns: `FileStorage`\n\nZavolá `onfile(meta, next)` pre každý súbor na disku s jeho metadátami (bez obsahu), `id` a poradovým číslom `index`; súbory s uplynutou platnosťou sa preskočia. Na pokračovanie zavolaj `next()`. `workers` je počet súborov spracúvaných súčasne v jednom priečinku.\n\nExample: Celková veľkosť\n```js\nvar size = 0;\nFILESTORAGE('files').stream(function(meta, next) {\n\tsize += meta.size;\n\tnext();\n}, () => console.log(size));\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 |  | Volá sa ako `callback(err, count)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nSpočíta súbory v skupinových priečinkoch úložiska.\n\nExample: Počet\n```js\nvar count = await FILESTORAGE('files').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nZnova zostaví index z disku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Volá sa ako `callback()`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nNačíta metadáta všetkých súborov a znova zapíše `files.log`. Použi to po `restore()` alebo po tom, čo si do adresára skopíroval súbory `.file`. `save()`, `read()`, `readbuffer()`, `copy()` a `clone()` počkajú, kým sa index zapíše.\n\nExample: Znovuzostavenie\n```js\nawait FILESTORAGE('files').rebuild();\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nOdstráni všetky súbory úložiska.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, count)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nVymaže každý súbor, adresáre skupín aj index. `save()`, `read()`, `readbuffer()`, `copy()` a `clone()` počkajú, kým to skončí. Volaj to iba vtedy, keď adresár úložiska existuje: inak to skončí chybou a úložisko zostane pozastavené. Callback dostane počet odstránených súborov. `fs.drop()` je alias.\n\nExample: Vymazanie\n```js\nFILESTORAGE('tmp').clear(function(err, count) {\n\tconsole.log('Removed', count);\n});\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 |  | Volá sa ako `callback(err, count)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nFunguje presne ako `fs.clear()`.\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nZálohuje celé úložisko do jedného súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Cieľový názov súboru alebo zapisovateľný stream. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, result)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `Promise|undefined`\n\nZapíše každý súbor, skomprimovaný cez GZIP a zakódovaný ako base64, do textového súboru (alebo zapisovateľného streamu). Index `files.log` sa nezahŕňa. Výsledok je `{ filename, files, size }`.\n\nExample: Záloha\n```js\nvar result = await FILESTORAGE('files').backup(PATH.root('files.backup'));\nconsole.log(result.files, result.size);\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nObnoví zálohu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Názov súboru zálohy alebo čitateľný stream. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, meta)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `Promise|undefined`\n\nOdstráni všetky aktuálne súbory a rozbalí do adresára súbor vytvorený cez `fs.backup()`. `save()`, `read()`, `readbuffer()`, `copy()` a `clone()` počkajú, kým to skončí. Potom zavolaj `fs.rebuild()`, aby sa vytvoril index.\n\nExample: Obnova a index\n```js\nvar fs = FILESTORAGE('files');\nfs.restore(PATH.root('files.backup'), function(err) {\n\t!err && fs.rebuild();\n});\n```\n\n### meta\n\nType: `type`\n\nMetadáta uloženého súboru.\n\nVracajú ich `save()`, `read()`, `readmeta()` a ďalšie metódy a ukladajú sa v hlavičke každého súboru:\n\n- `id` {String}: id,\n- `name` {String}: názov súboru,\n- `ext` {String}: prípona bez bodky,\n- `type` {String}: typ obsahu,\n- `size` {Number}: veľkosť obsahu v bajtoch,\n- `width`, `height` {Number}: rozmery obrázkov JPEG, PNG, GIF a SVG,\n- `custom` {Object}: tvoje vlastné dáta alebo `null`,\n- `date` {Date}: kedy bol súbor uložený,\n- `expire` {Date}: kedy súbor vyprší (iba ak je nastavené).\n\n`read()` pridáva `stream`, `stream()` a `browse2()` pridávajú `index`.\n\n### ROUTE('POST /url/ @upload')\n\nType: `type`\n\nPríznak routy pre multipart nahrávanie.\n\nRouta s `@upload` vyhovuje iba požiadavkám `multipart/form-data`. Nahrané súbory sú v `$.files` (aj v akciách), ostatné polia v `$.body`. Kombinuj ho s príznakom veľkosti ako `<10MB`.\n\nExample: Routa na nahrávanie\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/ @upload <10MB', function($) {\n\t\tvar file = $.files[0];\n\t\tfile.fs('files', UID(), $.callback());\n\t});\n};\n```\n\n### file.fs(storage, id, [callback])\n\nType: `method`\n\nUloží nahraný súbor do úložiska súborov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Názov úložiska. |\n| `id` | `String` | yes |  | Id súboru. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err, meta)`. Bez neho metóda vráti `Promise`. |\n\nReturns: `FileStorage|Promise`\n\nMetóda `HttpFile` (položiek `$.files`). Uloží dočasný súbor do `FILESTORAGE(storage)` s jeho pôvodným názvom súboru a vráti metadáta.\n\nExample: Uloženie všetkých nahraných súborov\n```js\nfunction upload($) {\n\t$.files.wait(function(file, next) {\n\t\tfile.fs('files', UID(), next);\n\t}, () => $.success());\n}\n```\n\n### Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])\n\nType: `method`\n\nČíta súbor po kúskoch s priebehom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Cesta k súboru. |\n| `onbuffer` | `Function` | yes |  | Volá sa ako `onbuffer(buffer, next, percentage)`; `next(true)` zastaví čítanie. |\n| `onend` | `Function` | no |  | Volá sa ako `onend(err)` na konci, po zastavení alebo pri chybe. |\n| `size` | `Number` | no | `16384` | Veľkosť kúska v bajtoch. |\n| `offset` | `Number` | no | `0` | Pozícia v bajtoch, kde čítanie začína. |\n\nReturns: `undefined`\n\nČíta súbor po kúskoch veľkosti `size` bajtov (predvolene 16384) od `offset` (predvolene 0) a pre každý kúsok zavolá `onbuffer(buffer, next, percentage)`. `percentage` je doteraz prečítaná časť súboru, od 0 do 100. Zavolaj `next()` na prečítanie ďalšieho kúska alebo `next(true)` na zastavenie. `onend(err)` sa zavolá na konci súboru, po zastavení alebo s chybou, keď súbor neexistuje. Keď je tretí argument číslo, je to veľkosť.\n\nExample: Hash súboru\n```js\nvar hash = F.Crypto.createHash('sha1');\nUtils.filestreamer(PATH.root('big.iso'), function(buffer, next) {\n\thash.update(buffer);\n\tnext();\n}, function(err) {\n\tconsole.log(hash.digest('hex'));\n});\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"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":"method","name":"fs.storage()","signature":"fs.storage(path)","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, source, [custom], [callback], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback])","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.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"fs.makedirectory()","signature":"fs.makedirectory(id)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.http()","signature":"fs.http($, opt)","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [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.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([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":"type","name":"File meta","signature":"meta","since":"","deprecated":false},{"type":"type","name":"@upload","signature":"ROUTE('POST /url/ @upload')","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [callback])","since":"","deprecated":false},{"type":"method","name":"Utils.filestreamer()","signature":"Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"Jafwv07bx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Plugins and components","summary":"The plugin definition, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() with its Component, Instance and Message objects, NPMINSTALL(), REQUIRE() and IMPORT().","markdown":"---\ntitle: Plugins and components\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/plugins-and-components/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Plugins and components\n\n> The plugin definition, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() with its Component, Instance and Message objects, NPMINSTALL(), REQUIRE() and IMPORT().\n\nProperties of a plugin `index.js`, the plugin files, `PLUGINS`, `COMPONENTATOR()`, server components compiled with `NEWCOMPONENT()` (the component, its instances and messages) and the loaders `NPMINSTALL()`, `REQUIRE()` and `IMPORT()`. For an introduction with examples read the guide [Plugins and components](../../guides/plugins-and-components/).\n\n## API\n\n### plugins/{id}/index.js\n\nType: `type`\n\nA folder in plugins/ with an index.js file, loaded at start.\n\nEvery folder in `plugins/` with an `index.js` file is a plugin; the folder name is the plugin id. A folder without `index.js` is skipped with all its subfolders, and so are folders whose name contains `-bk` or `_bk`. Total.js requires `index.js`, stores its exports in `PLUGINS[id]`, sets `exports.id` when missing and calls `exports.install()`. A `config` file in the folder is merged into `CONF`. The subfolders `controllers/`, `actions/`, `schemas/`, `models/`, `definitions/`, `extensions/` and `middleware/` are loaded like the folders of the application. An `index.flow` file is loaded as a FlowStream.\n\nExample: A minimal plugin\n```js\n// plugins/contacts/index.js\nexports.name = 'Contacts';\nexports.icon = 'ti ti-address-book';\nexports.permissions = ['contacts'];\n\nexports.install = function() {\n\tROUTE('+API    ?    contacts_list    --> Contacts/list');\n};\n```\n\n### exports.install = function() {}\n\nType: `delegate`\n\nCalled once when the plugin is loaded.\n\nRegister routes, events and other definitions of the plugin here. It runs during the loading of the application, in the same pass as the files of `controllers/`, `definitions/` and the other folders, so use `ON('ready')` when you need everything to be loaded first.\n\nExample: Routes and a ready handler\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/contacts/', function($) {\n\t\t$.view('#contacts/views/index');\n\t});\n\tON('ready', function() {\n\t\t// all plugins are loaded\n\t});\n};\n```\n\n### exports.id\n\nType: `property`\n\nThe id of the plugin.\n\nReturns: `String`\n\nWhen `index.js` does not define it, Total.js sets it to the name of the plugin folder. `PLUGINS` uses the folder name as the key in both cases.\n\n### exports.name\n\nType: `property`\n\nA human readable name of the plugin.\n\nReturns: `String`\n\nTotal.js writes it, with the id and the permissions, to the source map of the application in debug mode. Your UI can read it from `PLUGINS` to build a menu.\n\nExample: Name\n```js\nexports.name = 'Orders';\n```\n\n### exports.permissions\n\nType: `property`\n\nThe permissions the plugin defines.\n\nReturns: `Array`\n\nAn array of strings or of objects with an `id` property (and anything else you need, such as `name`). The ids are written, joined with commas, to the source map in debug mode. Read the array from `PLUGINS` to offer the permissions in a user editor and check them with the `permissions` option of your actions (see [Authorization](../../guides/authorization/)).\n\nExample: Permissions\n```js\nexports.permissions = [\n\t{ id: 'orders', name: 'Orders' },\n\t{ id: 'orders_remove', name: 'Remove orders' }\n];\n```\n\n### exports.icon, exports.visible, exports.position, ...\n\nType: `property`\n\nYour own properties of a plugin.\n\nTotal.js does not read any other property of `index.js`. Properties such as `icon`, `position` or `visible` are a convention for your administration UI, which reads them from `PLUGINS`.\n\nExample: Menu data\n```js\nexports.icon = 'ti ti-truck';\nexports.position = 5;\nexports.visible = function(user) {\n\treturn user.sa || user.permissions.includes('orders');\n};\n```\n\n### PLUGINS\n\nType: `property`\n\nAll loaded plugins by id.\n\nReturns: `Object` id: exports\n\nAn object whose keys are plugin ids and whose values are the exports of their `index.js`. It is filled during the loading of the application.\n\nExample: List plugins\n```js\nON('ready', function() {\n\tfor (var id in PLUGINS)\n\t\tconsole.log(id, PLUGINS[id].name);\n});\n```\n\n### plugins/{id}/config\n\nType: `config` · Since: `0.0.16`\n\nConfiguration file of a plugin.\n\nA `config` file in the folder of a plugin is read before the scripts of the application and the plugins run, after the main `config`. It has the same format as the main file and its keys are merged into `CONF`; a key that is also in the main file is overwritten.\n\nExample: Defaults of a plugin\n```text\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n### plugins/{id}/index.flow\n\nType: `type` · Since: `0.0.19`\n\nA FlowStream loaded with the plugin.\n\nAn `index.flow` file (a FlowStream export in JSON) in the folder of a plugin is read and started after the files of the application and the `index.js` of the plugin, before the other files of the plugin; the instance is created asynchronously and is stored in `PLUGINS[id].flowstream` once it is ready. The FlowStream gets the plugin id as `id`, the translated plugin `name` (or the id) as `name` and the plugin folder as `directory`. The instance is stored in `PLUGINS[id].flowstream`; errors are logged as `Plugin.<id>.flowstream`. See [FlowStream](../../guides/flowstream/).\n\n### PLUGINS[id].flowstream\n\nType: `property` · Since: `0.0.19`\n\nThe FlowStream instance loaded from index.flow.\n\nReturns: `FlowStream`\n\nSet when the `index.flow` file of the plugin has been loaded.\n\n### PATH.plugins([path])\n\nType: `method`\n\nReturns a path in the plugins folder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | A relative path such as \"shop/data.json\" |\n\nReturns: `String` Absolute path\n\nWithout an argument it returns the absolute path of `plugins/`; with a path it joins it. With a path, the plugins folder is created when it does not exist.\n\nExample: Read a file of a plugin\n```js\nvar filename = PATH.plugins('shop/data/countries.json');\nF.Fs.readFile(filename, 'utf8', function(err, data) {\n\t// ...\n});\n```\n\n### controller.view('#{id}/path')\n\nType: `type`\n\nRenders a view from a plugin folder.\n\nA view name that starts with `#` is relative to `plugins/`: `#shop/views/index` renders `plugins/shop/views/index.html`. The same prefix works in `TEMPLATE('#shop/templates/order.html')`, which adds `.html` when the name does not contain it.\n\nExample: A view of a plugin\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n### COMPONENTATOR(name, components, [removeprev], [attrs])\n\nType: `method`\n\nDownloads a bundle of UI components from Componentator.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the bundle; used in the file name and as the key in REPO |\n| `components` | `String` | yes |  | Comma separated component names |\n| `removeprev` | `Boolean` | no | `true` | Delete older bundles with the same name |\n| `attrs` | `String` | no | `''` | Extra URL-encoded fields sent with the download request |\n\nDownloads one minified file with the listed jComponent components from `https://componentator.com/download/` into `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` with `removeprev` set to `false`). The hash is computed from `components`, and the file is downloaded only when it does not exist. With `removeprev` (default), older `ui-<name>-*` files are deleted. The URL of the bundle is stored in `REPO[name]`. Errors are logged. When `removeprev` is a string, it is taken as `attrs`.\n\nExample: A UI bundle\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true);\n```\n\nExample: In the layout\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n### ON('componentator', function(meta) {})\n\nType: `event`\n\nEmitted before COMPONENTATOR() builds the file name.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | { name, components } |\n\n`meta` contains `name` and `components`. You can change both, for example to add a component to every bundle; the new values are used for the file name, `REPO` and the download.\n\nExample: Add a component everywhere\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',errorhandler';\n});\n```\n\n### NEWCOMPONENT(html, [callback])\n\nType: `method`\n\nCompiles a server component.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | File name, HTML or URL |\n| `callback` | `Function` | no |  | function(err, component) |\n\nReturns: `Promise<Component>` When callback is not set\n\n`html` is the name of a file in `components/` (without `.html`), the HTML content itself (anything containing `<`), or an `https://` URL that is downloaded first. The server code must be in a `<script total>` or `<script node>` block; without it you get the error \"Invalid component content\". The code runs with `exports` (the component) and `require` (`REQUIRE()`). Packages in `exports.npm` are installed, schemas of inputs and outputs are compiled and `exports.install()` is called. Returns a Promise without a callback.\n\nExample: From the components folder\n```js\nNEWCOMPONENT('uppercase', function(err, com) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar instance = com.create();\n});\n```\n\nExample: Inline\n```js\nvar html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\\'output\\', msg.data * 2); };</script>';\nvar com = await NEWCOMPONENT(html);\n```\n\n### components/{name}.html\n\nType: `type`\n\nThe format of a server component.\n\nAn HTML file with these parts: `<script total>` or `<script node>` (server code, required), `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` and `<template>`. The server code is removed from the result; the other parts are available in `component.ui` (`settings`, `css`, `js`, `html`, `readme`, `schema`, `template`).\n\nExample: A complete file\n```html\n<script total>\n\n\texports.name = 'Counter';\n\texports.config = { step: 1 };\n\texports.inputs = [{ id: 'input', name: 'Value' }];\n\texports.outputs = [{ id: 'output', name: 'Sum' }];\n\n\texports.make = function(instance, config) {\n\t\tvar sum = 0;\n\t\tinstance.message = function(msg) {\n\t\t\tsum += config.step;\n\t\t\tmsg.send('output', sum);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nCounts incoming messages.\n</readme>\n\n<settings>\n<div>Step of the counter</div>\n</settings>\n```\n\n### Component\n\nType: `class`\n\nA compiled server component.\n\nThe object returned by `NEWCOMPONENT()`. Its properties come from `exports` of the server code (`name`, `config`, `inputs`, `outputs`, `npm`, `make`, ...) plus `ui`, `instances`, `variables`, `secrets` and `debugger`.\n\n### exports.make = function(instance, config, status) {}\n\nType: `delegate`\n\nSets up a new instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | The new instance |\n| `config` | `Object` | yes |  | Its configuration |\n| `status` | `Object` | yes |  | The second argument of create() |\n\nCalled by `component.create()` with the instance as `this` and as the first argument. Assign `instance.message` (and other handlers such as `instance.close`, `instance.configure` or `instance.service`) here.\n\nExample: Handlers\n```js\nexports.make = function(instance, config) {\n\tinstance.message = function(msg) {\n\t\tmsg.send('output', msg.data);\n\t};\n\tinstance.configure = function() {\n\t\t// config has changed\n\t};\n};\n```\n\n### exports.config\n\nType: `property`\n\nDefault configuration of instances.\n\nReturns: `Object`\n\nEach instance gets a clone of this object, extended with the options passed to `component.create()`.\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nInputs and outputs of the component.\n\nReturns: `Array`\n\nArrays of `{ id, name, schema }`. A `schema` (a schema string such as `'name:String, age:Number'`) is compiled into a JSON schema. For inputs it is applied in `instance.input()`: the cleaned data replaces `msg.data` and errors are in `msg.error`.\n\nExample: With a schema\n```js\nexports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n\nexports.make = function(instance) {\n\tinstance.message = function(msg) {\n\t\tif (msg.error)\n\t\t\tmsg.send('error', msg.error.toString());\n\t\telse\n\t\t\tmsg.send('ok', msg.data);\n\t};\n};\n```\n\n### exports.npm\n\nType: `property`\n\nNPM packages the component needs.\n\nReturns: `String[]`\n\nAn array of package names (optionally `name@version`). `NEWCOMPONENT()` installs them with `NPMINSTALL()` before `install()` runs; the compilation fails with the npm error when one cannot be installed.\n\nExample: Dependencies\n```js\nexports.npm = ['mqtt'];\n\nexports.make = function(instance, config) {\n\tvar mqtt = require('mqtt');\n\t// ...\n};\n```\n\n### exports.install = function(component) {}\n\nType: `delegate`\n\nCalled once after the component is compiled.\n\nRuns with the component as `this` and as the argument, after NPM packages are installed and schemas are compiled.\n\n### exports.onextend = function(instance) {}\n\nType: `delegate`\n\nExtends each new instance before make().\n\nCalled in `component.create()` after the configuration is set and before `make()`.\n\n### exports.oncreate = function(instance) {}\n\nType: `delegate`\n\nCalled after an instance is created.\n\nRuns asynchronously (in `setImmediate`) after `make()`.\n\n### exports.onremove = function(instance) {}\n\nType: `delegate`\n\nCalled when an instance is removed.\n\nCalled by `instance.remove()` after the `close` and `destroy` handlers of the instance.\n\n### component.ui\n\nType: `property`\n\nThe UI parts of the component file.\n\nReturns: `Object`\n\nAn object with `readme`, `settings`, `css`, `js`, `html`, `schema` and `template` (only the parts found in the file).\n\n### component.instances\n\nType: `property`\n\nAll instances of the component.\n\nReturns: `Instance[]`\n\n`create()` adds an instance and `instance.remove()` removes it.\n\n### component.debugger\n\nType: `property`\n\nPrints status, debug, error and output messages to the console.\n\nReturns: `Boolean`\n\n`true` by default. Set it to `false` to keep the console quiet, or replace `component.output`, `component.status`, `component.debug`, `component.throw` or `component.dashboard` with your own functions.\n\n### component.output = function(instance, msg) {}\n\nType: `delegate`\n\nReceives every message sent to an output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | The sender |\n| `msg` | `Message` | yes |  | msg.output and msg.data |\n\nCalled for each `msg.send()` of any instance. The default prints the output and the data when `debugger` is on. Replace it to connect instances or to process results. `component.status(instance, value)`, `component.debug(instance, value)`, `component.throw(instance, err)` and `component.dashboard(instance, value)` receive the calls of the instance methods with the same name.\n\nExample: Collect results\n```js\nvar com = await NEWCOMPONENT('uppercase');\ncom.output = function(instance, msg) {\n\tconsole.log(instance.id, msg.output, msg.data);\n};\n```\n\n### component.create([options], [status])\n\nType: `method`\n\nCreates an instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Configuration of the instance |\n| `status` | `Object` | no |  | Passed to make() as the third argument |\n\nReturns: `Instance`\n\nThe instance gets a random `id`, a clone of `component.config` extended with `options`, and is added to `component.instances`. Then `onextend()`, `make()` and (asynchronously) `oncreate()` are called.\n\nExample: Two instances\n```js\nvar a = com.create({ prefix: 'A: ' });\nvar b = com.create({ prefix: 'B: ' });\n```\n\n### component.service(counter)\n\nType: `method`\n\nCalls instance.service(counter) on all instances.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Any value passed to the instances |\n\nTotal.js does not call it for you. Call it from `ON('service')` when your instances need a periodic tick.\n\nExample: Every minute\n```js\nON('service', function(counter) {\n\tcom.service(counter);\n});\n```\n\n### Instance\n\nType: `class`\n\nAn instance of a server component.\n\nReturned by `component.create()`. Properties: `id`, `config`, `module` (the component) and `cache` (an empty object for your data). Handlers you can assign in `make()`: `message`, `message_<input>`, `configure`, `close`, `destroy` and `service`.\n\n### instance.message = function(msg) {}\n\nType: `delegate`\n\nHandles data that comes to an input.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Message` | yes |  | The incoming message |\n\nCalled by `instance.input()`. `msg.input` is the input id and `msg.data` the data. A handler named `instance.message_<input>` is called too, after `message`. Without `instance.message` the input is ignored.\n\nExample: Per input\n```js\nexports.make = function(instance) {\n\tinstance.message = NOOP;\n\tinstance.message_reset = function(msg) {\n\t\t// only for input \"reset\"\n\t};\n};\n```\n\n### instance.input(input, data, [callback])\n\nType: `method`\n\nSends data to an input of the instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String` | yes |  | Input id |\n| `data` | `Object` | yes |  | The data |\n| `callback` | `Function` | no |  | function(msg) |\n\nCreates a message, validates the data with the schema of the input (if any) and calls `instance.message(msg)` and `instance.message_<input>(msg)`. The `callback` is called with the message each time it is sent to an output with `msg.send()`.\n\nExample: Call and read the result\n```js\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);\n});\n```\n\n### instance.send(output, data)\n\nType: `method` · Since: `0.0.17`\n\nSends new data to an output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Output id |\n| `data` | `Object` | yes |  | The data |\n\nCreates a new message with `data` and sends it to `output`; it ends in `instance.output(msg)` and so in `component.output()`. Use it for data the instance produces on its own (a timer, a socket).\n\nExample: A timer\n```js\nexports.make = function(instance) {\n\tvar timer = setInterval(() => instance.send('output', new Date()), 5000);\n\tinstance.close = () => clearInterval(timer);\n};\n```\n\n### instance.status(value) / debug(value) / throw(err) / dashboard(value)\n\nType: `method`\n\nReports a state of the instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Any value |\n\nEach method calls the component method with the same name (`component.status(instance, value)` and so on). By default they print to the console when `component.debugger` is on.\n\nExample: Report\n```js\ninstance.status({ connected: true });\ninstance.throw(new Error('Connection refused'));\n```\n\n### instance.activity(key, name, value)\n\nType: `method` · Since: `0.0.19`\n\nReports an activity of the instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Identifier of the activity |\n| `name` | `String` | yes |  | Label |\n| `value` | `Object` | yes |  | For example a progress |\n\nCalls `component.activity(instance, { key, name, value })`, which prints `ACTIVITY` to the console when `component.debugger` is on. Replace `component.activity` to process it.\n\n### instance.reconfigure(options)\n\nType: `method`\n\nChanges the configuration of an instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | New values |\n\nCopies the keys of `options` to `instance.config` and calls `instance.configure(config)` when it is defined.\n\nExample: Change a value\n```js\ninstance.reconfigure({ prefix: '>> ' });\n```\n\n### instance.remove()\n\nType: `method`\n\nRemoves the instance.\n\nCalls `instance.close(true)` and `instance.destroy()` when defined, then `component.onremove(instance)`, and removes the instance from `component.instances`.\n\nExample: Remove\n```js\ninstance.remove();\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nReplaces {key} placeholders in a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String|Object` | yes |  | Template |\n| `data` | `Object` | no |  | Values |\n| `encoding` | `String|Function` | no |  | Encoding of the values |\n\nReturns: `String|Object`\n\nEach `{key}` (or `{{key}}`) is taken from `component.variables`, then `component.secrets`, then `data` (nested keys with dots work). Without `data` the instance itself is used. `encoding` can be `'url'` (or `'urlencoded'`), `'json'`, `'querify'` or a `function(value, key)`. Dates are formatted. An object as `str` replaces its string values. `msg.replace()` works the same way.\n\nExample: A URL\n```js\ncom.variables.api = 'https://api.example.com';\nvar url = instance.replace('{api}/users/{id}/', { id: 15 });\n```\n\n### Message\n\nType: `class`\n\nData that flows through a component instance.\n\nCreated by `instance.input()` and `instance.send()`. Properties: `data`, `input`, `output`, `error` (an ErrorBuilder when the input schema failed, `null` when it passed, `undefined` for an input without a schema), `from` and `instance` (the instance), `repo` and `vars` (empty objects for your data).\n\n### msg.send(output, [data])\n\nType: `method`\n\nSends the message to an output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Output id |\n| `data` | `Object` | no |  | New data |\n\nSets `msg.output` and, when `data` is given, `msg.data`. Then it calls the callback of `instance.input()` and `instance.output(msg)`. Nothing happens after `msg.end()`.\n\nExample: Forward\n```js\ninstance.message = function(msg) {\n\tmsg.send('output', { received: msg.data });\n};\n```\n\n### msg.end() / msg.destroy()\n\nType: `method`\n\nReleases the message.\n\nClears `data`, `vars`, `repo` and the instance, so later `msg.send()` calls do nothing.\n\n### NPMINSTALL(name, [callback])\n\nType: `method`\n\nInstalls an NPM package.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Package name, optionally with @version |\n| `callback` | `Function` | no |  | function(err) |\n\nReturns: `Promise` When callback is not set\n\nRuns `npm install <name>` in `CONF.$nodemodules` (created when missing). When the package folder already contains a `package.json` (with the same version for `name@version`), nothing is installed. When the process runs as user 33 (www-data), `CONF.$npmcache` is used as the npm cache. Without a callback it returns a Promise. See [Configuration](../../guides/configuration/) for both keys.\n\nExample: Install and load\n```js\nNPMINSTALL('qrcode@1.5.4', function(err) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar QR = REQUIRE('qrcode');\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nLoads a Node.js or NPM module.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Module name |\n\nReturns: `Object` The module\n\nNames with the `node:` prefix and Node.js built-in modules (`fs`, `path`, `crypto`, ...) are loaded directly. Other names are loaded with `require()` and, when that fails, from `CONF.$nodemodules`, so packages installed with `NPMINSTALL()` are found. It throws when the module cannot be loaded.\n\nExample: Load\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nDownloads and loads a remote JavaScript module.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL of a .js file |\n| `callback` | `Function` | no |  | function(err, module, response) |\n\nReturns: `Promise` When callback is not set\n\nThe file is downloaded into the temporary folder and required. Further calls with the same URL in the same process return the loaded module without downloading. An answer with the status `400` or more gives the error `The address answered with the status <status>` and nothing is loaded. A file that is not a valid module gives the error of `require()`, for example a `SyntaxError`. The callback receives `(err, module, response)`; without it a Promise resolves with the module.\n\nExample: Promise\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n","entries":[{"type":"type","name":"Plugin","signature":"plugins/{id}/index.js","since":"","deprecated":false},{"type":"delegate","name":"plugin.install()","signature":"exports.install = function() {}","since":"","deprecated":false},{"type":"property","name":"plugin.id","signature":"exports.id","since":"","deprecated":false},{"type":"property","name":"plugin.name","signature":"exports.name","since":"","deprecated":false},{"type":"property","name":"plugin.permissions","signature":"exports.permissions","since":"","deprecated":false},{"type":"property","name":"plugin.icon","signature":"exports.icon, exports.visible, exports.position, ...","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"config","name":"plugins/{id}/config","signature":"plugins/{id}/config","since":"0.0.16","deprecated":false},{"type":"type","name":"plugins/{id}/index.flow","signature":"plugins/{id}/index.flow","since":"0.0.19","deprecated":false},{"type":"property","name":"plugin.flowstream","signature":"PLUGINS[id].flowstream","since":"0.0.19","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([path])","since":"","deprecated":false},{"type":"type","name":"view('#plugin/...')","signature":"controller.view('#{id}/path')","since":"","deprecated":false},{"type":"method","name":"COMPONENTATOR()","signature":"COMPONENTATOR(name, components, [removeprev], [attrs])","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"method","name":"NEWCOMPONENT()","signature":"NEWCOMPONENT(html, [callback])","since":"","deprecated":false},{"type":"type","name":"Component file","signature":"components/{name}.html","since":"","deprecated":false},{"type":"class","name":"Component","signature":"Component","since":"","deprecated":false},{"type":"delegate","name":"component.make","signature":"exports.make = function(instance, config, status) {}","since":"","deprecated":false},{"type":"property","name":"component.config","signature":"exports.config","since":"","deprecated":false},{"type":"property","name":"component.inputs","signature":"exports.inputs / exports.outputs","since":"","deprecated":false},{"type":"property","name":"component.npm","signature":"exports.npm","since":"","deprecated":false},{"type":"delegate","name":"component.install","signature":"exports.install = function(component) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onextend","signature":"exports.onextend = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.oncreate","signature":"exports.oncreate = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onremove","signature":"exports.onremove = function(instance) {}","since":"","deprecated":false},{"type":"property","name":"component.ui","signature":"component.ui","since":"","deprecated":false},{"type":"property","name":"component.instances","signature":"component.instances","since":"","deprecated":false},{"type":"property","name":"component.debugger","signature":"component.debugger","since":"","deprecated":false},{"type":"delegate","name":"component.output()","signature":"component.output = function(instance, msg) {}","since":"","deprecated":false},{"type":"method","name":"component.create()","signature":"component.create([options], [status])","since":"","deprecated":false},{"type":"method","name":"component.service()","signature":"component.service(counter)","since":"","deprecated":false},{"type":"class","name":"Instance","signature":"Instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"instance.input()","signature":"instance.input(input, data, [callback])","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data)","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(value) / debug(value) / throw(err) / dashboard(value)","since":"","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, value)","since":"0.0.19","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(options)","since":"","deprecated":false},{"type":"method","name":"instance.remove()","signature":"instance.remove()","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"class","name":"Message","signature":"Message","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"msg.send(output, [data])","since":"","deprecated":false},{"type":"method","name":"message.end()","signature":"msg.end() / msg.destroy()","since":"","deprecated":false},{"type":"method","name":"NPMINSTALL()","signature":"NPMINSTALL(name, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwv07bx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Plugins und Komponenten","summary":"Die Plugin-Definition, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() mit seinen Objekten Component, Instance und Message, NPMINSTALL(), REQUIRE() und IMPORT().","markdown":"---\ntitle: Plugins und Komponenten\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/plugins-and-components/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Plugins und Komponenten\n\n> Die Plugin-Definition, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() mit seinen Objekten Component, Instance und Message, NPMINSTALL(), REQUIRE() und IMPORT().\n\nEigenschaften der `index.js` eines Plugins, die Plugin-Dateien, `PLUGINS`, `COMPONENTATOR()`, mit `NEWCOMPONENT()` kompilierte Server-Komponenten (die Komponente, ihre Instanzen und Nachrichten) und die Loader `NPMINSTALL()`, `REQUIRE()` und `IMPORT()`. Eine Einführung mit Beispielen findest du in der Anleitung [Plugins und Komponenten](../../guides/plugins-and-components/).\n\n## API\n\n### plugins/{id}/index.js\n\nType: `type`\n\nEin Ordner in plugins/ mit einer Datei index.js, der beim Start geladen wird.\n\nJeder Ordner in `plugins/` mit einer Datei `index.js` ist ein Plugin; der Ordnername ist die id des Plugins. Ein Ordner ohne `index.js` wird mit all seinen Unterordnern übersprungen, ebenso Ordner, deren Name `-bk` oder `_bk` enthält. Total.js lädt `index.js` per require, speichert seine Exporte in `PLUGINS[id]`, setzt `exports.id`, wenn es fehlt, und ruft `exports.install()` auf. Eine Datei `config` im Ordner wird in `CONF` zusammengeführt. Die Unterordner `controllers/`, `actions/`, `schemas/`, `models/`, `definitions/`, `extensions/` und `middleware/` werden wie die Ordner der Anwendung geladen. Eine Datei `index.flow` wird als FlowStream geladen.\n\nExample: Ein minimales Plugin\n```js\n// plugins/contacts/index.js\nexports.name = 'Contacts';\nexports.icon = 'ti ti-address-book';\nexports.permissions = ['contacts'];\n\nexports.install = function() {\n\tROUTE('+API    ?    contacts_list    --> Contacts/list');\n};\n```\n\n### exports.install = function() {}\n\nType: `delegate`\n\nWird einmal aufgerufen, wenn das Plugin geladen wird.\n\nRegistriere hier Routes, Events und andere Definitionen des Plugins. Die Funktion läuft während des Ladens der Anwendung, im selben Durchgang wie die Dateien aus `controllers/`, `definitions/` und den anderen Ordnern; verwende also `ON('ready')`, wenn zuerst alles geladen sein muss.\n\nExample: Routen und ein Ready-Handler\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/contacts/', function($) {\n\t\t$.view('#contacts/views/index');\n\t});\n\tON('ready', function() {\n\t\t// all plugins are loaded\n\t});\n};\n```\n\n### exports.id\n\nType: `property`\n\nDie ID des Plugins.\n\nReturns: `String`\n\nWenn `index.js` sie nicht definiert, setzt Total.js sie auf den Namen des Plugin-Ordners. `PLUGINS` verwendet in beiden Fällen den Ordnernamen als Schlüssel.\n\n### exports.name\n\nType: `property`\n\nEin menschenlesbarer Name des Plugins.\n\nReturns: `String`\n\nTotal.js schreibt ihn zusammen mit der ID und den Berechtigungen im Debug-Modus in die Source Map der Anwendung. Deine UI kann ihn aus `PLUGINS` lesen, um ein Menü aufzubauen.\n\nExample: Name\n```js\nexports.name = 'Orders';\n```\n\n### exports.permissions\n\nType: `property`\n\nDie Berechtigungen, die das Plugin definiert.\n\nReturns: `Array`\n\nEin Array von Strings oder von Objekten mit einer Eigenschaft `id` (und allem anderen, was du brauchst, etwa `name`). Die IDs werden im Debug-Modus durch Kommas verbunden in die Source Map geschrieben. Lies das Array aus `PLUGINS`, um die Berechtigungen in einem Benutzereditor anzubieten, und prüfe sie mit der Option `permissions` deiner Actions (siehe [Autorisierung](../../guides/authorization/)).\n\nExample: Berechtigungen\n```js\nexports.permissions = [\n\t{ id: 'orders', name: 'Orders' },\n\t{ id: 'orders_remove', name: 'Remove orders' }\n];\n```\n\n### exports.icon, exports.visible, exports.position, ...\n\nType: `property`\n\nDeine eigenen Eigenschaften eines Plugins.\n\nTotal.js liest keine weitere Eigenschaft von `index.js`. Eigenschaften wie `icon`, `position` oder `visible` sind eine Konvention für deine Administrationsoberfläche, die sie aus `PLUGINS` liest.\n\nExample: Menüdaten\n```js\nexports.icon = 'ti ti-truck';\nexports.position = 5;\nexports.visible = function(user) {\n\treturn user.sa || user.permissions.includes('orders');\n};\n```\n\n### PLUGINS\n\nType: `property`\n\nAlle geladenen Plugins nach ID.\n\nReturns: `Object` id: exports\n\nEin Objekt, dessen Schlüssel Plugin-IDs und dessen Werte die Exports ihrer `index.js` sind. Es wird während des Ladens der Anwendung befüllt.\n\nExample: Plugins auflisten\n```js\nON('ready', function() {\n\tfor (var id in PLUGINS)\n\t\tconsole.log(id, PLUGINS[id].name);\n});\n```\n\n### plugins/{id}/config\n\nType: `config` · Since: `0.0.16`\n\nKonfigurationsdatei eines Plugins.\n\nEine Datei `config` im Ordner eines Plugins wird gelesen, bevor die Skripte der Anwendung und der Plugins laufen, nach der Haupt-`config`. Sie hat dasselbe Format wie die Hauptdatei, und ihre Schlüssel werden in `CONF` übernommen; ein Schlüssel, der auch in der Hauptdatei steht, wird überschrieben.\n\nExample: Standardwerte eines Plugins\n```text\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n### plugins/{id}/index.flow\n\nType: `type` · Since: `0.0.19`\n\nEin FlowStream, der mit dem Plugin geladen wird.\n\nEine Datei `index.flow` (ein FlowStream-Export in JSON) im Ordner eines Plugins wird nach den Dateien der Anwendung und der `index.js` des Plugins, vor den anderen Dateien des Plugins, gelesen und gestartet; die Instanz wird asynchron erstellt und in `PLUGINS[id].flowstream` gespeichert, sobald sie bereit ist. Der FlowStream erhält die id des Plugins als `id`, den übersetzten `name` des Plugins (oder die id) als `name` und den Plugin-Ordner als `directory`. Die Instanz wird in `PLUGINS[id].flowstream` gespeichert; Fehler werden als `Plugin.<id>.flowstream` geloggt. Siehe [FlowStream](../../guides/flowstream/).\n\n### PLUGINS[id].flowstream\n\nType: `property` · Since: `0.0.19`\n\nDie aus index.flow geladene FlowStream-Instanz.\n\nReturns: `FlowStream`\n\nWird gesetzt, wenn die Datei `index.flow` des Plugins geladen wurde.\n\n### PATH.plugins([path])\n\nType: `method`\n\nGibt einen Pfad im Plugins-Ordner zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ein relativer Pfad wie \"shop/data.json\" |\n\nReturns: `String` Absoluter Pfad\n\nOhne Argument gibt es den absoluten Pfad von `plugins/` zurück; mit einem Pfad verbindet es ihn damit. Mit einem Pfad wird der Ordner plugins erstellt, wenn er nicht existiert.\n\nExample: Eine Datei eines Plugins lesen\n```js\nvar filename = PATH.plugins('shop/data/countries.json');\nF.Fs.readFile(filename, 'utf8', function(err, data) {\n\t// ...\n});\n```\n\n### controller.view('#{id}/path')\n\nType: `type`\n\nRendert eine View aus einem Plugin-Ordner.\n\nEin View-Name, der mit `#` beginnt, ist relativ zu `plugins/`: `#shop/views/index` rendert `plugins/shop/views/index.html`. Dasselbe Präfix funktioniert in `TEMPLATE('#shop/templates/order.html')`, das `.html` hinzufügt, wenn der Name es nicht enthält.\n\nExample: Eine View eines Plugins\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n### COMPONENTATOR(name, components, [removeprev], [attrs])\n\nType: `method`\n\nLädt ein Bundle von UI-Komponenten von Componentator herunter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Bundles; wird im Dateinamen und als Schlüssel in REPO verwendet |\n| `components` | `String` | yes |  | Kommagetrennte Komponentennamen |\n| `removeprev` | `Boolean` | no | `true` | Ältere Bundles mit demselben Namen löschen |\n| `attrs` | `String` | no | `''` | Zusätzliche URL-kodierte Felder, die mit der Download-Anfrage gesendet werden |\n\nLädt eine minifizierte Datei mit den aufgeführten jComponent-Komponenten von `https://componentator.com/download/` nach `public/ui-<name>-<hash>.min.js` herunter (`public/ui-<hash>.min.js`, wenn `removeprev` auf `false` gesetzt ist). Der Hash wird aus `components` berechnet, und die Datei wird nur heruntergeladen, wenn sie nicht existiert. Mit `removeprev` (Standard) werden ältere `ui-<name>-*`-Dateien gelöscht. Die URL des Bundles wird in `REPO[name]` gespeichert. Fehler werden protokolliert. Ist `removeprev` ein String, wird er als `attrs` verwendet.\n\nExample: Ein UI-Bundle\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true);\n```\n\nExample: Im Layout\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n### ON('componentator', function(meta) {})\n\nType: `event`\n\nWird ausgelöst, bevor COMPONENTATOR() den Dateinamen bildet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | { name, components } |\n\n`meta` enthält `name` und `components`. Du kannst beide ändern, zum Beispiel um jedem Bundle eine Komponente hinzuzufügen; die neuen Werte werden für den Dateinamen, `REPO` und den Download verwendet.\n\nExample: Überall eine Komponente hinzufügen\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',errorhandler';\n});\n```\n\n### NEWCOMPONENT(html, [callback])\n\nType: `method`\n\nKompiliert eine Server-Komponente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Dateiname, HTML oder URL |\n| `callback` | `Function` | no |  | function(err, component) |\n\nReturns: `Promise<Component>` Wenn kein Callback gesetzt ist\n\n`html` ist der Name einer Datei in `components/` (ohne `.html`), der HTML-Inhalt selbst (alles, was `<` enthält) oder eine `https://`-URL, die zuerst heruntergeladen wird. Der Server-Code muss in einem Block `<script total>` oder `<script node>` stehen; ohne ihn erhältst du den Fehler \"Invalid component content\". Der Code läuft mit `exports` (die Komponente) und `require` (`REQUIRE()`). Pakete in `exports.npm` werden installiert, Schemas der Ein- und Ausgänge kompiliert und `exports.install()` aufgerufen. Ohne Callback wird eine Promise zurückgegeben.\n\nExample: Aus dem Ordner components\n```js\nNEWCOMPONENT('uppercase', function(err, com) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar instance = com.create();\n});\n```\n\nExample: Inline\n```js\nvar html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\\'output\\', msg.data * 2); };</script>';\nvar com = await NEWCOMPONENT(html);\n```\n\n### components/{name}.html\n\nType: `type`\n\nDas Format einer Server-Komponente.\n\nEine HTML-Datei mit diesen Teilen: `<script total>` oder `<script node>` (Server-Code, erforderlich), `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` und `<template>`. Der Server-Code wird aus dem Ergebnis entfernt; die anderen Teile stehen in `component.ui` zur Verfügung (`settings`, `css`, `js`, `html`, `readme`, `schema`, `template`).\n\nExample: Eine vollständige Datei\n```html\n<script total>\n\n\texports.name = 'Counter';\n\texports.config = { step: 1 };\n\texports.inputs = [{ id: 'input', name: 'Value' }];\n\texports.outputs = [{ id: 'output', name: 'Sum' }];\n\n\texports.make = function(instance, config) {\n\t\tvar sum = 0;\n\t\tinstance.message = function(msg) {\n\t\t\tsum += config.step;\n\t\t\tmsg.send('output', sum);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nCounts incoming messages.\n</readme>\n\n<settings>\n<div>Step of the counter</div>\n</settings>\n```\n\n### Component\n\nType: `class`\n\nEine kompilierte Server-Komponente.\n\nDas von `NEWCOMPONENT()` zurückgegebene Objekt. Seine Eigenschaften stammen aus `exports` des Server-Codes (`name`, `config`, `inputs`, `outputs`, `npm`, `make`, ...) sowie `ui`, `instances`, `variables`, `secrets` und `debugger`.\n\n### exports.make = function(instance, config, status) {}\n\nType: `delegate`\n\nRichtet eine neue Instanz ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | Die neue Instanz |\n| `config` | `Object` | yes |  | Ihre Konfiguration |\n| `status` | `Object` | yes |  | Das zweite Argument von create() |\n\nWird von `component.create()` mit der Instanz als `this` und als erstem Argument aufgerufen. Weise hier `instance.message` zu (und weitere Handler wie `instance.close`, `instance.configure` oder `instance.service`).\n\nExample: Handler\n```js\nexports.make = function(instance, config) {\n\tinstance.message = function(msg) {\n\t\tmsg.send('output', msg.data);\n\t};\n\tinstance.configure = function() {\n\t\t// config has changed\n\t};\n};\n```\n\n### exports.config\n\nType: `property`\n\nStandardkonfiguration der Instanzen.\n\nReturns: `Object`\n\nJede Instanz erhält einen Klon dieses Objekts, erweitert um die an `component.create()` übergebenen Optionen.\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nEin- und Ausgänge der Komponente.\n\nReturns: `Array`\n\nArrays von `{ id, name, schema }`. Ein `schema` (ein Schema-String wie `'name:String, age:Number'`) wird zu einem JSON-Schema kompiliert. Bei Eingängen wird es in `instance.input()` angewendet: Die bereinigten Daten ersetzen `msg.data`, und Fehler stehen in `msg.error`.\n\nExample: Mit einem Schema\n```js\nexports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n\nexports.make = function(instance) {\n\tinstance.message = function(msg) {\n\t\tif (msg.error)\n\t\t\tmsg.send('error', msg.error.toString());\n\t\telse\n\t\t\tmsg.send('ok', msg.data);\n\t};\n};\n```\n\n### exports.npm\n\nType: `property`\n\nNPM-Pakete, die die Komponente benötigt.\n\nReturns: `String[]`\n\nEin Array von Paketnamen (optional `name@version`). `NEWCOMPONENT()` installiert sie mit `NPMINSTALL()`, bevor `install()` läuft; die Kompilierung schlägt mit dem npm-Fehler fehl, wenn eines nicht installiert werden kann.\n\nExample: Abhängigkeiten\n```js\nexports.npm = ['mqtt'];\n\nexports.make = function(instance, config) {\n\tvar mqtt = require('mqtt');\n\t// ...\n};\n```\n\n### exports.install = function(component) {}\n\nType: `delegate`\n\nWird einmal aufgerufen, nachdem die Komponente kompiliert wurde.\n\nLäuft mit der Komponente als `this` und als Argument, nachdem die NPM-Pakete installiert und die Schemas kompiliert wurden.\n\n### exports.onextend = function(instance) {}\n\nType: `delegate`\n\nErweitert jede neue Instanz vor make().\n\nWird in `component.create()` aufgerufen, nachdem die Konfiguration gesetzt wurde und vor `make()`.\n\n### exports.oncreate = function(instance) {}\n\nType: `delegate`\n\nWird aufgerufen, nachdem eine Instanz erstellt wurde.\n\nLäuft asynchron (in `setImmediate`) nach `make()`.\n\n### exports.onremove = function(instance) {}\n\nType: `delegate`\n\nWird aufgerufen, wenn eine Instanz entfernt wird.\n\nWird von `instance.remove()` nach den Handlern `close` und `destroy` der Instanz aufgerufen.\n\n### component.ui\n\nType: `property`\n\nDie UI-Teile der Komponentendatei.\n\nReturns: `Object`\n\nEin Objekt mit `readme`, `settings`, `css`, `js`, `html`, `schema` und `template` (nur die in der Datei gefundenen Teile).\n\n### component.instances\n\nType: `property`\n\nAlle Instanzen der Komponente.\n\nReturns: `Instance[]`\n\n`create()` fügt eine Instanz hinzu, und `instance.remove()` entfernt sie.\n\n### component.debugger\n\nType: `property`\n\nGibt Status-, Debug-, Fehler- und Ausgabenachrichten in der Konsole aus.\n\nReturns: `Boolean`\n\nStandardmäßig `true`. Setze es auf `false`, um die Konsole ruhig zu halten, oder ersetze `component.output`, `component.status`, `component.debug`, `component.throw` oder `component.dashboard` durch eigene Funktionen.\n\n### component.output = function(instance, msg) {}\n\nType: `delegate`\n\nEmpfängt jede an einen Ausgang gesendete Nachricht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | Der Absender |\n| `msg` | `Message` | yes |  | msg.output und msg.data |\n\nWird für jedes `msg.send()` einer beliebigen Instanz aufgerufen. Die Standardimplementierung gibt den Ausgang und die Daten aus, wenn `debugger` aktiv ist. Ersetze sie, um Instanzen zu verbinden oder Ergebnisse zu verarbeiten. `component.status(instance, value)`, `component.debug(instance, value)`, `component.throw(instance, err)` und `component.dashboard(instance, value)` empfangen die Aufrufe der gleichnamigen Instanzmethoden.\n\nExample: Ergebnisse sammeln\n```js\nvar com = await NEWCOMPONENT('uppercase');\ncom.output = function(instance, msg) {\n\tconsole.log(instance.id, msg.output, msg.data);\n};\n```\n\n### component.create([options], [status])\n\nType: `method`\n\nErstellt eine Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Konfiguration der Instanz |\n| `status` | `Object` | no |  | Wird als drittes Argument an make() übergeben |\n\nReturns: `Instance`\n\nDie Instanz erhält eine zufällige `id` und einen Klon von `component.config`, erweitert um `options`, und wird zu `component.instances` hinzugefügt. Dann werden `onextend()`, `make()` und (asynchron) `oncreate()` aufgerufen.\n\nExample: Zwei Instanzen\n```js\nvar a = com.create({ prefix: 'A: ' });\nvar b = com.create({ prefix: 'B: ' });\n```\n\n### component.service(counter)\n\nType: `method`\n\nRuft instance.service(counter) für alle Instanzen auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Ein beliebiger Wert, der an die Instanzen übergeben wird |\n\nTotal.js ruft die Methode nicht für dich auf. Rufe sie aus `ON('service')` auf, wenn deine Instanzen einen periodischen Takt brauchen.\n\nExample: Jede Minute\n```js\nON('service', function(counter) {\n\tcom.service(counter);\n});\n```\n\n### Instance\n\nType: `class`\n\nEine Instanz einer Server-Komponente.\n\nWird von `component.create()` zurückgegeben. Eigenschaften: `id`, `config`, `module` (die Komponente) und `cache` (ein leeres Objekt für deine Daten). Handler, die du in `make()` zuweisen kannst: `message`, `message_<input>`, `configure`, `close`, `destroy` und `service`.\n\n### instance.message = function(msg) {}\n\nType: `delegate`\n\nVerarbeitet Daten, die an einem Eingang ankommen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Message` | yes |  | Die eingehende Nachricht |\n\nWird von `instance.input()` aufgerufen. `msg.input` ist die Eingangs-ID und `msg.data` die Daten. Ein Handler namens `instance.message_<input>` wird ebenfalls aufgerufen, nach `message`. Ohne `instance.message` wird der Eingang ignoriert.\n\nExample: Pro Eingang\n```js\nexports.make = function(instance) {\n\tinstance.message = NOOP;\n\tinstance.message_reset = function(msg) {\n\t\t// only for input \"reset\"\n\t};\n};\n```\n\n### instance.input(input, data, [callback])\n\nType: `method`\n\nSendet Daten an einen Eingang der Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String` | yes |  | Eingangs-ID |\n| `data` | `Object` | yes |  | Die Daten |\n| `callback` | `Function` | no |  | function(msg) |\n\nErstellt eine Nachricht, validiert die Daten mit dem Schema des Eingangs (falls vorhanden) und ruft `instance.message(msg)` und `instance.message_<input>(msg)` auf. Der `callback` wird mit der Nachricht jedes Mal aufgerufen, wenn sie mit `msg.send()` an einen Ausgang gesendet wird.\n\nExample: Aufrufen und das Ergebnis lesen\n```js\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);\n});\n```\n\n### instance.send(output, data)\n\nType: `method` · Since: `0.0.17`\n\nSendet neue Daten an einen Ausgang.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | ID des Ausgangs |\n| `data` | `Object` | yes |  | Die Daten |\n\nErstellt eine neue Nachricht mit `data` und sendet sie an `output`; sie endet in `instance.output(msg)` und damit in `component.output()`. Verwende es für Daten, die die Instanz selbst erzeugt (ein Timer, ein Socket).\n\nExample: Ein Timer\n```js\nexports.make = function(instance) {\n\tvar timer = setInterval(() => instance.send('output', new Date()), 5000);\n\tinstance.close = () => clearInterval(timer);\n};\n```\n\n### instance.status(value) / debug(value) / throw(err) / dashboard(value)\n\nType: `method`\n\nMeldet einen Zustand der Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Ein beliebiger Wert |\n\nJede Methode ruft die gleichnamige Methode der Komponente auf (`component.status(instance, value)` usw.). Standardmäßig geben sie in der Konsole aus, wenn `component.debugger` aktiv ist.\n\nExample: Melden\n```js\ninstance.status({ connected: true });\ninstance.throw(new Error('Connection refused'));\n```\n\n### instance.activity(key, name, value)\n\nType: `method` · Since: `0.0.19`\n\nMeldet eine Aktivität der Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Bezeichner der Aktivität |\n| `name` | `String` | yes |  | Bezeichnung |\n| `value` | `Object` | yes |  | Zum Beispiel ein Fortschritt |\n\nRuft `component.activity(instance, { key, name, value })` auf, das `ACTIVITY` in der Konsole ausgibt, wenn `component.debugger` aktiv ist. Ersetze `component.activity`, um sie zu verarbeiten.\n\n### instance.reconfigure(options)\n\nType: `method`\n\nÄndert die Konfiguration einer Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Neue Werte |\n\nKopiert die Schlüssel von `options` nach `instance.config` und ruft `instance.configure(config)` auf, wenn es definiert ist.\n\nExample: Einen Wert ändern\n```js\ninstance.reconfigure({ prefix: '>> ' });\n```\n\n### instance.remove()\n\nType: `method`\n\nEntfernt die Instanz.\n\nRuft `instance.close(true)` und `instance.destroy()` auf, wenn definiert, dann `component.onremove(instance)`, und entfernt die Instanz aus `component.instances`.\n\nExample: Entfernen\n```js\ninstance.remove();\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nErsetzt {key}-Platzhalter in einem String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String|Object` | yes |  | Template |\n| `data` | `Object` | no |  | Werte |\n| `encoding` | `String|Function` | no |  | Kodierung der Werte |\n\nReturns: `String|Object`\n\nJedes `{key}` (oder `{{key}}`) wird aus `component.variables`, dann `component.secrets`, dann `data` genommen (verschachtelte Schlüssel mit Punkten funktionieren). Ohne `data` wird die Instanz selbst verwendet. `encoding` kann `'url'` (oder `'urlencoded'`), `'json'`, `'querify'` oder eine `function(value, key)` sein. Datumswerte werden formatiert. Ist `str` ein Objekt, werden seine String-Werte ersetzt. `msg.replace()` funktioniert genauso.\n\nExample: Eine URL\n```js\ncom.variables.api = 'https://api.example.com';\nvar url = instance.replace('{api}/users/{id}/', { id: 15 });\n```\n\n### Message\n\nType: `class`\n\nDaten, die durch eine Komponenteninstanz fließen.\n\nWird von `instance.input()` und `instance.send()` erstellt. Eigenschaften: `data`, `input`, `output`, `error` (ein ErrorBuilder, wenn das Eingangsschema fehlschlug, `null`, wenn es bestanden wurde, `undefined` bei einem Eingang ohne Schema), `from` und `instance` (die Instanz), `repo` und `vars` (leere Objekte für deine Daten).\n\n### msg.send(output, [data])\n\nType: `method`\n\nSendet die Nachricht an einen Ausgang.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Ausgangs-ID |\n| `data` | `Object` | no |  | Neue Daten |\n\nSetzt `msg.output` und, wenn `data` übergeben wird, `msg.data`. Dann ruft die Methode den Callback von `instance.input()` und `instance.output(msg)` auf. Nach `msg.end()` passiert nichts.\n\nExample: Weiterleiten\n```js\ninstance.message = function(msg) {\n\tmsg.send('output', { received: msg.data });\n};\n```\n\n### msg.end() / msg.destroy()\n\nType: `method`\n\nGibt die Nachricht frei.\n\nLeert `data`, `vars`, `repo` und die Instanz, sodass spätere Aufrufe von `msg.send()` nichts bewirken.\n\n### NPMINSTALL(name, [callback])\n\nType: `method`\n\nInstalliert ein NPM-Paket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Paketname, optional mit @version |\n| `callback` | `Function` | no |  | function(err) |\n\nReturns: `Promise` Wenn kein Callback gesetzt ist\n\nFührt `npm install <name>` in `CONF.$nodemodules` aus (wird angelegt, wenn es fehlt). Enthält der Paketordner bereits eine `package.json` (mit derselben Version bei `name@version`), wird nichts installiert. Läuft der Prozess als Benutzer 33 (www-data), wird `CONF.$npmcache` als npm-Cache verwendet. Ohne Callback wird eine Promise zurückgegeben. Siehe [Konfiguration](../../guides/configuration/) für beide Schlüssel.\n\nExample: Installieren und laden\n```js\nNPMINSTALL('qrcode@1.5.4', function(err) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar QR = REQUIRE('qrcode');\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nLädt ein Node.js- oder NPM-Modul.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Modulname |\n\nReturns: `Object` Das Modul\n\nNamen mit dem Präfix `node:` und eingebaute Node.js-Module (`fs`, `path`, `crypto`, ...) werden direkt geladen. Andere Namen werden mit `require()` geladen und, wenn das fehlschlägt, aus `CONF.$nodemodules`, sodass mit `NPMINSTALL()` installierte Pakete gefunden werden. Die Funktion wirft einen Fehler, wenn das Modul nicht geladen werden kann.\n\nExample: Laden\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nLädt ein entferntes JavaScript-Modul herunter und lädt es.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL einer .js-Datei |\n| `callback` | `Function` | no |  | function(err, module, response) |\n\nReturns: `Promise` Wenn kein Callback gesetzt ist\n\nDie Datei wird in den temporären Ordner heruntergeladen und per require geladen. Weitere Aufrufe mit derselben URL im selben Prozess geben das geladene Modul zurück, ohne erneut herunterzuladen. Eine Antwort mit dem Status `400` oder mehr führt zum Fehler `The address answered with the status <status>`, und es wird nichts geladen. Eine Datei, die kein gültiges Modul ist, führt zum Fehler von `require()`, zum Beispiel einem `SyntaxError`. Der Callback erhält `(err, module, response)`; ohne ihn wird eine Promise mit dem Modul aufgelöst.\n\nExample: Promise\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n","entries":[{"type":"type","name":"Plugin","signature":"plugins/{id}/index.js","since":"","deprecated":false},{"type":"delegate","name":"plugin.install()","signature":"exports.install = function() {}","since":"","deprecated":false},{"type":"property","name":"plugin.id","signature":"exports.id","since":"","deprecated":false},{"type":"property","name":"plugin.name","signature":"exports.name","since":"","deprecated":false},{"type":"property","name":"plugin.permissions","signature":"exports.permissions","since":"","deprecated":false},{"type":"property","name":"plugin.icon","signature":"exports.icon, exports.visible, exports.position, ...","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"config","name":"plugins/{id}/config","signature":"plugins/{id}/config","since":"0.0.16","deprecated":false},{"type":"type","name":"plugins/{id}/index.flow","signature":"plugins/{id}/index.flow","since":"0.0.19","deprecated":false},{"type":"property","name":"plugin.flowstream","signature":"PLUGINS[id].flowstream","since":"0.0.19","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([path])","since":"","deprecated":false},{"type":"type","name":"view('#plugin/...')","signature":"controller.view('#{id}/path')","since":"","deprecated":false},{"type":"method","name":"COMPONENTATOR()","signature":"COMPONENTATOR(name, components, [removeprev], [attrs])","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"method","name":"NEWCOMPONENT()","signature":"NEWCOMPONENT(html, [callback])","since":"","deprecated":false},{"type":"type","name":"Component file","signature":"components/{name}.html","since":"","deprecated":false},{"type":"class","name":"Component","signature":"Component","since":"","deprecated":false},{"type":"delegate","name":"component.make","signature":"exports.make = function(instance, config, status) {}","since":"","deprecated":false},{"type":"property","name":"component.config","signature":"exports.config","since":"","deprecated":false},{"type":"property","name":"component.inputs","signature":"exports.inputs / exports.outputs","since":"","deprecated":false},{"type":"property","name":"component.npm","signature":"exports.npm","since":"","deprecated":false},{"type":"delegate","name":"component.install","signature":"exports.install = function(component) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onextend","signature":"exports.onextend = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.oncreate","signature":"exports.oncreate = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onremove","signature":"exports.onremove = function(instance) {}","since":"","deprecated":false},{"type":"property","name":"component.ui","signature":"component.ui","since":"","deprecated":false},{"type":"property","name":"component.instances","signature":"component.instances","since":"","deprecated":false},{"type":"property","name":"component.debugger","signature":"component.debugger","since":"","deprecated":false},{"type":"delegate","name":"component.output()","signature":"component.output = function(instance, msg) {}","since":"","deprecated":false},{"type":"method","name":"component.create()","signature":"component.create([options], [status])","since":"","deprecated":false},{"type":"method","name":"component.service()","signature":"component.service(counter)","since":"","deprecated":false},{"type":"class","name":"Instance","signature":"Instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"instance.input()","signature":"instance.input(input, data, [callback])","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data)","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(value) / debug(value) / throw(err) / dashboard(value)","since":"","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, value)","since":"0.0.19","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(options)","since":"","deprecated":false},{"type":"method","name":"instance.remove()","signature":"instance.remove()","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"class","name":"Message","signature":"Message","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"msg.send(output, [data])","since":"","deprecated":false},{"type":"method","name":"message.end()","signature":"msg.end() / msg.destroy()","since":"","deprecated":false},{"type":"method","name":"NPMINSTALL()","signature":"NPMINSTALL(name, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwv07bx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Plugins y componentes","summary":"La definición del plugin, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() con sus objetos Component, Instance y Message, NPMINSTALL(), REQUIRE() e IMPORT().","markdown":"---\ntitle: Plugins y componentes\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/plugins-and-components/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Plugins y componentes\n\n> La definición del plugin, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() con sus objetos Component, Instance y Message, NPMINSTALL(), REQUIRE() e IMPORT().\n\nPropiedades del `index.js` de un plugin, los archivos del plugin, `PLUGINS`, `COMPONENTATOR()`, los componentes de servidor compilados con `NEWCOMPONENT()` (el componente, sus instancias y mensajes) y los cargadores `NPMINSTALL()`, `REQUIRE()` e `IMPORT()`. Para una introducción con ejemplos, lee la guía [Plugins y componentes](../../guides/plugins-and-components/).\n\n## API\n\n### plugins/{id}/index.js\n\nType: `type`\n\nUna carpeta en plugins/ con un archivo index.js, que se carga al iniciar.\n\nCada carpeta de `plugins/` con un archivo `index.js` es un plugin; el nombre de la carpeta es el id del plugin. Una carpeta sin `index.js` se omite con todas sus subcarpetas, igual que las carpetas cuyo nombre contiene `-bk` o `_bk`. Total.js carga `index.js` con require, guarda sus exports en `PLUGINS[id]`, establece `exports.id` si falta y llama a `exports.install()`. Un archivo `config` en la carpeta se fusiona en `CONF`. Las subcarpetas `controllers/`, `actions/`, `schemas/`, `models/`, `definitions/`, `extensions/` y `middleware/` se cargan como las carpetas de la aplicación. Un archivo `index.flow` se carga como un FlowStream.\n\nExample: Un plugin mínimo\n```js\n// plugins/contacts/index.js\nexports.name = 'Contacts';\nexports.icon = 'ti ti-address-book';\nexports.permissions = ['contacts'];\n\nexports.install = function() {\n\tROUTE('+API    ?    contacts_list    --> Contacts/list');\n};\n```\n\n### exports.install = function() {}\n\nType: `delegate`\n\nSe llama una vez cuando se carga el plugin.\n\nRegistra aquí las rutas, los eventos y las demás definiciones del plugin. Se ejecuta durante la carga de la aplicación, en la misma pasada que los archivos de `controllers/`, `definitions/` y las demás carpetas, así que usa `ON('ready')` cuando necesites que todo esté cargado antes.\n\nExample: Rutas y un handler ready\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/contacts/', function($) {\n\t\t$.view('#contacts/views/index');\n\t});\n\tON('ready', function() {\n\t\t// all plugins are loaded\n\t});\n};\n```\n\n### exports.id\n\nType: `property`\n\nEl id del plugin.\n\nReturns: `String`\n\nCuando `index.js` no lo define, Total.js le asigna el nombre de la carpeta del plugin. `PLUGINS` usa el nombre de la carpeta como clave en ambos casos.\n\n### exports.name\n\nType: `property`\n\nUn nombre legible del plugin.\n\nReturns: `String`\n\nEn modo debug, Total.js lo escribe, junto con el id y los permisos, en el mapa de fuentes de la aplicación. Tu UI puede leerlo de `PLUGINS` para construir un menú.\n\nExample: Nombre\n```js\nexports.name = 'Orders';\n```\n\n### exports.permissions\n\nType: `property`\n\nLos permisos que define el plugin.\n\nReturns: `Array`\n\nUn array de strings o de objetos con una propiedad `id` (y lo que necesites además, como `name`). En modo debug, los ids se escriben, separados por comas, en el mapa de fuentes. Lee el array de `PLUGINS` para ofrecer los permisos en un editor de usuarios y compruébalos con la opción `permissions` de tus acciones (consulta [Autorización](../../guides/authorization/)).\n\nExample: Permisos\n```js\nexports.permissions = [\n\t{ id: 'orders', name: 'Orders' },\n\t{ id: 'orders_remove', name: 'Remove orders' }\n];\n```\n\n### exports.icon, exports.visible, exports.position, ...\n\nType: `property`\n\nTus propias propiedades de un plugin.\n\nTotal.js no lee ninguna otra propiedad de `index.js`. Propiedades como `icon`, `position` o `visible` son una convención para tu UI de administración, que las lee de `PLUGINS`.\n\nExample: Datos del menú\n```js\nexports.icon = 'ti ti-truck';\nexports.position = 5;\nexports.visible = function(user) {\n\treturn user.sa || user.permissions.includes('orders');\n};\n```\n\n### PLUGINS\n\nType: `property`\n\nTodos los plugins cargados, por id.\n\nReturns: `Object` id: exports\n\nUn objeto cuyas claves son los ids de los plugins y cuyos valores son los exports de su `index.js`. Se rellena durante la carga de la aplicación.\n\nExample: Listar los plugins\n```js\nON('ready', function() {\n\tfor (var id in PLUGINS)\n\t\tconsole.log(id, PLUGINS[id].name);\n});\n```\n\n### plugins/{id}/config\n\nType: `config` · Since: `0.0.16`\n\nArchivo de configuración de un plugin.\n\nUn archivo `config` en la carpeta de un plugin se lee antes de que se ejecuten los scripts de la aplicación y de los plugins, después del `config` principal. Tiene el mismo formato que el archivo principal y sus claves se fusionan en `CONF`; una clave que también está en el archivo principal se sobrescribe.\n\nExample: Valores por defecto de un plugin\n```text\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n### plugins/{id}/index.flow\n\nType: `type` · Since: `0.0.19`\n\nUn FlowStream que se carga con el plugin.\n\nUn archivo `index.flow` (una exportación de FlowStream en JSON) en la carpeta de un plugin se lee y se inicia después de los archivos de la aplicación y del `index.js` del plugin, antes de los demás archivos del plugin; la instancia se crea de forma asíncrona y se guarda en `PLUGINS[id].flowstream` cuando está lista. El FlowStream recibe el id del plugin como `id`, el `name` traducido del plugin (o el id) como `name` y la carpeta del plugin como `directory`. La instancia se guarda en `PLUGINS[id].flowstream`; los errores se registran como `Plugin.<id>.flowstream`. Consulta [FlowStream](../../guides/flowstream/).\n\n### PLUGINS[id].flowstream\n\nType: `property` · Since: `0.0.19`\n\nLa instancia de FlowStream cargada desde index.flow.\n\nReturns: `FlowStream`\n\nSe establece cuando se ha cargado el archivo `index.flow` del plugin.\n\n### PATH.plugins([path])\n\nType: `method`\n\nDevuelve una ruta en la carpeta de plugins.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Una ruta relativa como \"shop/data.json\" |\n\nReturns: `String` Ruta absoluta\n\nSin argumento devuelve la ruta absoluta de `plugins/`; con una ruta, la une. Con una ruta, la carpeta de plugins se crea cuando no existe.\n\nExample: Leer un archivo de un plugin\n```js\nvar filename = PATH.plugins('shop/data/countries.json');\nF.Fs.readFile(filename, 'utf8', function(err, data) {\n\t// ...\n});\n```\n\n### controller.view('#{id}/path')\n\nType: `type`\n\nRenderiza una vista desde la carpeta de un plugin.\n\nUn nombre de vista que empieza por `#` es relativo a `plugins/`: `#shop/views/index` renderiza `plugins/shop/views/index.html`. El mismo prefijo funciona en `TEMPLATE('#shop/templates/order.html')`, que añade `.html` cuando el nombre no lo contiene.\n\nExample: Una vista de un plugin\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n### COMPONENTATOR(name, components, [removeprev], [attrs])\n\nType: `method`\n\nDescarga un bundle de componentes de UI desde Componentator.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del bundle; se usa en el nombre del archivo y como clave en REPO |\n| `components` | `String` | yes |  | Nombres de componentes separados por comas |\n| `removeprev` | `Boolean` | no | `true` | Borra los bundles anteriores con el mismo nombre |\n| `attrs` | `String` | no | `''` | Campos adicionales codificados como URL que se envían con la petición de descarga |\n\nDescarga un archivo minificado con los componentes de jComponent indicados desde `https://componentator.com/download/` en `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` con `removeprev` a `false`). El hash se calcula a partir de `components` y el archivo solo se descarga si no existe. Con `removeprev` (por defecto), se borran los archivos `ui-<name>-*` anteriores. La URL del bundle se guarda en `REPO[name]`. Los errores se registran en el log. Cuando `removeprev` es un string, se toma como `attrs`.\n\nExample: Un bundle de UI\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true);\n```\n\nExample: En la plantilla (layout)\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n### ON('componentator', function(meta) {})\n\nType: `event`\n\nSe emite antes de que COMPONENTATOR() construya el nombre del archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | { name, components } |\n\n`meta` contiene `name` y `components`. Puedes cambiar ambos, por ejemplo para añadir un componente a todos los bundles; los nuevos valores se usan para el nombre del archivo, `REPO` y la descarga.\n\nExample: Añadir un componente en todas partes\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',errorhandler';\n});\n```\n\n### NEWCOMPONENT(html, [callback])\n\nType: `method`\n\nCompila un componente de servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Nombre de archivo, HTML o URL |\n| `callback` | `Function` | no |  | function(err, component) |\n\nReturns: `Promise<Component>` Cuando no se indica callback\n\n`html` es el nombre de un archivo en `components/` (sin `.html`), el propio contenido HTML (cualquier cosa que contenga `<`) o una URL `https://` que se descarga primero. El código de servidor debe estar en un bloque `<script total>` o `<script node>`; sin él obtienes el error \"Invalid component content\". El código se ejecuta con `exports` (el componente) y `require` (`REQUIRE()`). Se instalan los paquetes de `exports.npm`, se compilan los esquemas de las entradas y salidas y se llama a `exports.install()`. Sin callback, devuelve una Promise.\n\nExample: Desde la carpeta components\n```js\nNEWCOMPONENT('uppercase', function(err, com) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar instance = com.create();\n});\n```\n\nExample: En línea\n```js\nvar html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\\'output\\', msg.data * 2); };</script>';\nvar com = await NEWCOMPONENT(html);\n```\n\n### components/{name}.html\n\nType: `type`\n\nEl formato de un componente de servidor.\n\nUn archivo HTML con estas partes: `<script total>` o `<script node>` (código de servidor, obligatorio), `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` y `<template>`. El código de servidor se elimina del resultado; las demás partes están disponibles en `component.ui` (`settings`, `css`, `js`, `html`, `readme`, `schema`, `template`).\n\nExample: Un archivo completo\n```html\n<script total>\n\n\texports.name = 'Counter';\n\texports.config = { step: 1 };\n\texports.inputs = [{ id: 'input', name: 'Value' }];\n\texports.outputs = [{ id: 'output', name: 'Sum' }];\n\n\texports.make = function(instance, config) {\n\t\tvar sum = 0;\n\t\tinstance.message = function(msg) {\n\t\t\tsum += config.step;\n\t\t\tmsg.send('output', sum);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nCounts incoming messages.\n</readme>\n\n<settings>\n<div>Step of the counter</div>\n</settings>\n```\n\n### Component\n\nType: `class`\n\nUn componente de servidor compilado.\n\nEl objeto devuelto por `NEWCOMPONENT()`. Sus propiedades vienen de los `exports` del código de servidor (`name`, `config`, `inputs`, `outputs`, `npm`, `make`, ...) más `ui`, `instances`, `variables`, `secrets` y `debugger`.\n\n### exports.make = function(instance, config, status) {}\n\nType: `delegate`\n\nPrepara una nueva instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | La nueva instancia |\n| `config` | `Object` | yes |  | Su configuración |\n| `status` | `Object` | yes |  | El segundo argumento de create() |\n\nLo llama `component.create()` con la instancia como `this` y como primer argumento. Asigna aquí `instance.message` (y otros handlers como `instance.close`, `instance.configure` o `instance.service`).\n\nExample: Handlers\n```js\nexports.make = function(instance, config) {\n\tinstance.message = function(msg) {\n\t\tmsg.send('output', msg.data);\n\t};\n\tinstance.configure = function() {\n\t\t// config has changed\n\t};\n};\n```\n\n### exports.config\n\nType: `property`\n\nConfiguración por defecto de las instancias.\n\nReturns: `Object`\n\nCada instancia recibe un clon de este objeto, ampliado con las opciones pasadas a `component.create()`.\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nEntradas y salidas del componente.\n\nReturns: `Array`\n\nArrays de `{ id, name, schema }`. Un `schema` (un string de esquema como `'name:String, age:Number'`) se compila en un esquema JSON. En las entradas se aplica en `instance.input()`: los datos limpios sustituyen a `msg.data` y los errores están en `msg.error`.\n\nExample: Con un esquema\n```js\nexports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n\nexports.make = function(instance) {\n\tinstance.message = function(msg) {\n\t\tif (msg.error)\n\t\t\tmsg.send('error', msg.error.toString());\n\t\telse\n\t\t\tmsg.send('ok', msg.data);\n\t};\n};\n```\n\n### exports.npm\n\nType: `property`\n\nPaquetes NPM que necesita el componente.\n\nReturns: `String[]`\n\nUn array de nombres de paquetes (opcionalmente `name@version`). `NEWCOMPONENT()` los instala con `NPMINSTALL()` antes de que se ejecute `install()`; la compilación falla con el error de npm si alguno no se puede instalar.\n\nExample: Dependencias\n```js\nexports.npm = ['mqtt'];\n\nexports.make = function(instance, config) {\n\tvar mqtt = require('mqtt');\n\t// ...\n};\n```\n\n### exports.install = function(component) {}\n\nType: `delegate`\n\nSe llama una vez después de compilar el componente.\n\nSe ejecuta con el componente como `this` y como argumento, después de instalar los paquetes NPM y compilar los esquemas.\n\n### exports.onextend = function(instance) {}\n\nType: `delegate`\n\nAmplía cada nueva instancia antes de make().\n\nSe llama en `component.create()` después de asignar la configuración y antes de `make()`.\n\n### exports.oncreate = function(instance) {}\n\nType: `delegate`\n\nSe llama después de crear una instancia.\n\nSe ejecuta de forma asíncrona (en `setImmediate`) después de `make()`.\n\n### exports.onremove = function(instance) {}\n\nType: `delegate`\n\nSe llama cuando se elimina una instancia.\n\nLo llama `instance.remove()` después de los handlers `close` y `destroy` de la instancia.\n\n### component.ui\n\nType: `property`\n\nLas partes de UI del archivo del componente.\n\nReturns: `Object`\n\nUn objeto con `readme`, `settings`, `css`, `js`, `html`, `schema` y `template` (solo las partes que hay en el archivo).\n\n### component.instances\n\nType: `property`\n\nTodas las instancias del componente.\n\nReturns: `Instance[]`\n\n`create()` añade una instancia e `instance.remove()` la elimina.\n\n### component.debugger\n\nType: `property`\n\nImprime en la consola los mensajes de estado, depuración, error y salida.\n\nReturns: `Boolean`\n\n`true` por defecto. Ponlo a `false` para que la consola no muestre nada, o sustituye `component.output`, `component.status`, `component.debug`, `component.throw` o `component.dashboard` por tus propias funciones.\n\n### component.output = function(instance, msg) {}\n\nType: `delegate`\n\nRecibe cada mensaje enviado a una salida.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | El emisor |\n| `msg` | `Message` | yes |  | msg.output y msg.data |\n\nSe llama en cada `msg.send()` de cualquier instancia. Por defecto imprime la salida y los datos cuando `debugger` está activo. Sustitúyelo para conectar instancias o procesar resultados. `component.status(instance, value)`, `component.debug(instance, value)`, `component.throw(instance, err)` y `component.dashboard(instance, value)` reciben las llamadas de los métodos de la instancia con el mismo nombre.\n\nExample: Recoger los resultados\n```js\nvar com = await NEWCOMPONENT('uppercase');\ncom.output = function(instance, msg) {\n\tconsole.log(instance.id, msg.output, msg.data);\n};\n```\n\n### component.create([options], [status])\n\nType: `method`\n\nCrea una instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Configuración de la instancia |\n| `status` | `Object` | no |  | Se pasa a make() como tercer argumento |\n\nReturns: `Instance`\n\nLa instancia recibe un `id` aleatorio y un clon de `component.config` ampliado con `options`, y se añade a `component.instances`. Después se llama a `onextend()`, `make()` y (de forma asíncrona) `oncreate()`.\n\nExample: Dos instancias\n```js\nvar a = com.create({ prefix: 'A: ' });\nvar b = com.create({ prefix: 'B: ' });\n```\n\n### component.service(counter)\n\nType: `method`\n\nLlama a instance.service(counter) en todas las instancias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Cualquier valor que se pasa a las instancias |\n\nTotal.js no lo llama por ti. Llámalo desde `ON('service')` cuando tus instancias necesiten un tick periódico.\n\nExample: Cada minuto\n```js\nON('service', function(counter) {\n\tcom.service(counter);\n});\n```\n\n### Instance\n\nType: `class`\n\nUna instancia de un componente de servidor.\n\nLa devuelve `component.create()`. Propiedades: `id`, `config`, `module` (el componente) y `cache` (un objeto vacío para tus datos). Handlers que puedes asignar en `make()`: `message`, `message_<input>`, `configure`, `close`, `destroy` y `service`.\n\n### instance.message = function(msg) {}\n\nType: `delegate`\n\nGestiona los datos que llegan a una entrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Message` | yes |  | El mensaje entrante |\n\nLo llama `instance.input()`. `msg.input` es el id de la entrada y `msg.data` los datos. También se llama a un handler llamado `instance.message_<input>`, después de `message`. Sin `instance.message`, la entrada se ignora.\n\nExample: Por entrada\n```js\nexports.make = function(instance) {\n\tinstance.message = NOOP;\n\tinstance.message_reset = function(msg) {\n\t\t// only for input \"reset\"\n\t};\n};\n```\n\n### instance.input(input, data, [callback])\n\nType: `method`\n\nEnvía datos a una entrada de la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String` | yes |  | Id de la entrada |\n| `data` | `Object` | yes |  | Los datos |\n| `callback` | `Function` | no |  | function(msg) |\n\nCrea un mensaje, valida los datos con el esquema de la entrada (si lo hay) y llama a `instance.message(msg)` y a `instance.message_<input>(msg)`. El `callback` se llama con el mensaje cada vez que se envía a una salida con `msg.send()`.\n\nExample: Llamar y leer el resultado\n```js\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);\n});\n```\n\n### instance.send(output, data)\n\nType: `method` · Since: `0.0.17`\n\nEnvía datos nuevos a una salida.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id de la salida |\n| `data` | `Object` | yes |  | Los datos |\n\nCrea un nuevo mensaje con `data` y lo envía a `output`; termina en `instance.output(msg)` y, por tanto, en `component.output()`. Úsalo para datos que la instancia produce por sí misma (un temporizador, un socket).\n\nExample: Un temporizador\n```js\nexports.make = function(instance) {\n\tvar timer = setInterval(() => instance.send('output', new Date()), 5000);\n\tinstance.close = () => clearInterval(timer);\n};\n```\n\n### instance.status(value) / debug(value) / throw(err) / dashboard(value)\n\nType: `method`\n\nInforma de un estado de la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Cualquier valor |\n\nCada método llama al método del componente con el mismo nombre (`component.status(instance, value)`, etc.). Por defecto imprimen en la consola cuando `component.debugger` está activo.\n\nExample: Informar\n```js\ninstance.status({ connected: true });\ninstance.throw(new Error('Connection refused'));\n```\n\n### instance.activity(key, name, value)\n\nType: `method` · Since: `0.0.19`\n\nInforma de una actividad de la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Identificador de la actividad |\n| `name` | `String` | yes |  | Etiqueta |\n| `value` | `Object` | yes |  | Por ejemplo, un progreso |\n\nLlama a `component.activity(instance, { key, name, value })`, que imprime `ACTIVITY` en la consola cuando `component.debugger` está activado. Reemplaza `component.activity` para procesarla.\n\n### instance.reconfigure(options)\n\nType: `method`\n\nCambia la configuración de una instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Nuevos valores |\n\nCopia las claves de `options` en `instance.config` y llama a `instance.configure(config)` si está definido.\n\nExample: Cambiar un valor\n```js\ninstance.reconfigure({ prefix: '>> ' });\n```\n\n### instance.remove()\n\nType: `method`\n\nElimina la instancia.\n\nLlama a `instance.close(true)` y a `instance.destroy()` si están definidos, después a `component.onremove(instance)`, y elimina la instancia de `component.instances`.\n\nExample: Eliminar\n```js\ninstance.remove();\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nSustituye los marcadores {key} en un string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String|Object` | yes |  | Plantilla |\n| `data` | `Object` | no |  | Valores |\n| `encoding` | `String|Function` | no |  | Codificación de los valores |\n\nReturns: `String|Object`\n\nCada `{key}` (o `{{key}}`) se toma de `component.variables`, después de `component.secrets` y después de `data` (las claves anidadas con puntos funcionan). Sin `data`, se usa la propia instancia. `encoding` puede ser `'url'` (o `'urlencoded'`), `'json'`, `'querify'` o una `function(value, key)`. Las fechas se formatean. Un objeto como `str` sustituye sus valores de tipo string. `msg.replace()` funciona igual.\n\nExample: Una URL\n```js\ncom.variables.api = 'https://api.example.com';\nvar url = instance.replace('{api}/users/{id}/', { id: 15 });\n```\n\n### Message\n\nType: `class`\n\nDatos que fluyen por una instancia de componente.\n\nLos crean `instance.input()` e `instance.send()`. Propiedades: `data`, `input`, `output`, `error` (un ErrorBuilder cuando el esquema de entrada ha fallado, `null` cuando lo ha superado, `undefined` para una entrada sin esquema), `from` e `instance` (la instancia), `repo` y `vars` (objetos vacíos para tus datos).\n\n### msg.send(output, [data])\n\nType: `method`\n\nEnvía el mensaje a una salida.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id de la salida |\n| `data` | `Object` | no |  | Nuevos datos |\n\nAsigna `msg.output` y, si se indica `data`, `msg.data`. Después llama al callback de `instance.input()` y a `instance.output(msg)`. Después de `msg.end()` no ocurre nada.\n\nExample: Reenviar\n```js\ninstance.message = function(msg) {\n\tmsg.send('output', { received: msg.data });\n};\n```\n\n### msg.end() / msg.destroy()\n\nType: `method`\n\nLibera el mensaje.\n\nVacía `data`, `vars`, `repo` y la instancia, de modo que las llamadas posteriores a `msg.send()` no hacen nada.\n\n### NPMINSTALL(name, [callback])\n\nType: `method`\n\nInstala un paquete NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del paquete, opcionalmente con @version |\n| `callback` | `Function` | no |  | function(err) |\n\nReturns: `Promise` Cuando no se indica callback\n\nEjecuta `npm install <name>` en `CONF.$nodemodules` (se crea si falta). Si la carpeta del paquete ya contiene un `package.json` (con la misma versión en el caso de `name@version`), no se instala nada. Cuando el proceso se ejecuta como el usuario 33 (www-data), se usa `CONF.$npmcache` como caché de npm. Sin callback, devuelve una Promise. Consulta [Configuración](../../guides/configuration/) para ambas claves.\n\nExample: Instalar y cargar\n```js\nNPMINSTALL('qrcode@1.5.4', function(err) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar QR = REQUIRE('qrcode');\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nCarga un módulo de Node.js o de NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del módulo |\n\nReturns: `Object` El módulo\n\nLos nombres con el prefijo `node:` y los módulos integrados de Node.js (`fs`, `path`, `crypto`, ...) se cargan directamente. Los demás nombres se cargan con `require()` y, si eso falla, desde `CONF.$nodemodules`, de modo que se encuentran los paquetes instalados con `NPMINSTALL()`. Lanza un error si el módulo no se puede cargar.\n\nExample: Cargar\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nDescarga y carga un módulo JavaScript remoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL de un archivo .js |\n| `callback` | `Function` | no |  | function(err, module, response) |\n\nReturns: `Promise` Cuando no se indica callback\n\nEl archivo se descarga en la carpeta temporal y se carga con require. Las siguientes llamadas con la misma URL en el mismo proceso devuelven el módulo ya cargado sin descargarlo. Una respuesta con el estado `400` o más da el error `The address answered with the status <status>` y no se carga nada. Un archivo que no es un módulo válido da el error de `require()`, por ejemplo un `SyntaxError`. El callback recibe `(err, module, response)`; sin él, una Promise se resuelve con el módulo.\n\nExample: Promesa\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n","entries":[{"type":"type","name":"Plugin","signature":"plugins/{id}/index.js","since":"","deprecated":false},{"type":"delegate","name":"plugin.install()","signature":"exports.install = function() {}","since":"","deprecated":false},{"type":"property","name":"plugin.id","signature":"exports.id","since":"","deprecated":false},{"type":"property","name":"plugin.name","signature":"exports.name","since":"","deprecated":false},{"type":"property","name":"plugin.permissions","signature":"exports.permissions","since":"","deprecated":false},{"type":"property","name":"plugin.icon","signature":"exports.icon, exports.visible, exports.position, ...","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"config","name":"plugins/{id}/config","signature":"plugins/{id}/config","since":"0.0.16","deprecated":false},{"type":"type","name":"plugins/{id}/index.flow","signature":"plugins/{id}/index.flow","since":"0.0.19","deprecated":false},{"type":"property","name":"plugin.flowstream","signature":"PLUGINS[id].flowstream","since":"0.0.19","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([path])","since":"","deprecated":false},{"type":"type","name":"view('#plugin/...')","signature":"controller.view('#{id}/path')","since":"","deprecated":false},{"type":"method","name":"COMPONENTATOR()","signature":"COMPONENTATOR(name, components, [removeprev], [attrs])","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"method","name":"NEWCOMPONENT()","signature":"NEWCOMPONENT(html, [callback])","since":"","deprecated":false},{"type":"type","name":"Component file","signature":"components/{name}.html","since":"","deprecated":false},{"type":"class","name":"Component","signature":"Component","since":"","deprecated":false},{"type":"delegate","name":"component.make","signature":"exports.make = function(instance, config, status) {}","since":"","deprecated":false},{"type":"property","name":"component.config","signature":"exports.config","since":"","deprecated":false},{"type":"property","name":"component.inputs","signature":"exports.inputs / exports.outputs","since":"","deprecated":false},{"type":"property","name":"component.npm","signature":"exports.npm","since":"","deprecated":false},{"type":"delegate","name":"component.install","signature":"exports.install = function(component) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onextend","signature":"exports.onextend = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.oncreate","signature":"exports.oncreate = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onremove","signature":"exports.onremove = function(instance) {}","since":"","deprecated":false},{"type":"property","name":"component.ui","signature":"component.ui","since":"","deprecated":false},{"type":"property","name":"component.instances","signature":"component.instances","since":"","deprecated":false},{"type":"property","name":"component.debugger","signature":"component.debugger","since":"","deprecated":false},{"type":"delegate","name":"component.output()","signature":"component.output = function(instance, msg) {}","since":"","deprecated":false},{"type":"method","name":"component.create()","signature":"component.create([options], [status])","since":"","deprecated":false},{"type":"method","name":"component.service()","signature":"component.service(counter)","since":"","deprecated":false},{"type":"class","name":"Instance","signature":"Instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"instance.input()","signature":"instance.input(input, data, [callback])","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data)","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(value) / debug(value) / throw(err) / dashboard(value)","since":"","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, value)","since":"0.0.19","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(options)","since":"","deprecated":false},{"type":"method","name":"instance.remove()","signature":"instance.remove()","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"class","name":"Message","signature":"Message","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"msg.send(output, [data])","since":"","deprecated":false},{"type":"method","name":"message.end()","signature":"msg.end() / msg.destroy()","since":"","deprecated":false},{"type":"method","name":"NPMINSTALL()","signature":"NPMINSTALL(name, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwv07bx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Plugins et composants","summary":"La définition d'un plugin, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() avec ses objets Component, Instance et Message, NPMINSTALL(), REQUIRE() et IMPORT().","markdown":"---\ntitle: Plugins et composants\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/plugins-and-components/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Plugins et composants\n\n> La définition d'un plugin, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() avec ses objets Component, Instance et Message, NPMINSTALL(), REQUIRE() et IMPORT().\n\nLes propriétés du `index.js` d'un plugin, les fichiers du plugin, `PLUGINS`, `COMPONENTATOR()`, les composants serveur compilés avec `NEWCOMPONENT()` (le composant, ses instances et ses messages) et les chargeurs `NPMINSTALL()`, `REQUIRE()` et `IMPORT()`. Pour une introduction avec des exemples, lis le guide [Plugins et composants](../../guides/plugins-and-components/).\n\n## API\n\n### plugins/{id}/index.js\n\nType: `type`\n\nUn dossier de plugins/ avec un fichier index.js, chargé au démarrage.\n\nChaque dossier de `plugins/` contenant un fichier `index.js` est un plugin ; le nom du dossier est l'id du plugin. Un dossier sans `index.js` est ignoré avec tous ses sous-dossiers, de même que les dossiers dont le nom contient `-bk` ou `_bk`. Total.js charge `index.js` avec require, stocke ses exports dans `PLUGINS[id]`, définit `exports.id` s'il manque et appelle `exports.install()`. Un fichier `config` dans le dossier est fusionné dans `CONF`. Les sous-dossiers `controllers/`, `actions/`, `schemas/`, `models/`, `definitions/`, `extensions/` et `middleware/` sont chargés comme les dossiers de l'application. Un fichier `index.flow` est chargé comme FlowStream.\n\nExample: Un plugin minimal\n```js\n// plugins/contacts/index.js\nexports.name = 'Contacts';\nexports.icon = 'ti ti-address-book';\nexports.permissions = ['contacts'];\n\nexports.install = function() {\n\tROUTE('+API    ?    contacts_list    --> Contacts/list');\n};\n```\n\n### exports.install = function() {}\n\nType: `delegate`\n\nAppelée une fois au chargement du plugin.\n\nEnregistre ici les routes, les événements et les autres définitions du plugin. Elle s'exécute pendant le chargement de l'application, dans la même passe que les fichiers de `controllers/`, `definitions/` et des autres dossiers : utilise donc `ON('ready')` lorsque tout doit d'abord être chargé.\n\nExample: Routes et un handler ready\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/contacts/', function($) {\n\t\t$.view('#contacts/views/index');\n\t});\n\tON('ready', function() {\n\t\t// all plugins are loaded\n\t});\n};\n```\n\n### exports.id\n\nType: `property`\n\nL'id du plugin.\n\nReturns: `String`\n\nLorsque `index.js` ne la définit pas, Total.js lui donne le nom du dossier du plugin. `PLUGINS` utilise le nom du dossier comme clé dans les deux cas.\n\n### exports.name\n\nType: `property`\n\nUn nom lisible du plugin.\n\nReturns: `String`\n\nTotal.js l'écrit, avec l'id et les permissions, dans la source map de l'application en mode debug. Ton UI peut le lire dans `PLUGINS` pour construire un menu.\n\nExample: Nom\n```js\nexports.name = 'Orders';\n```\n\n### exports.permissions\n\nType: `property`\n\nLes permissions définies par le plugin.\n\nReturns: `Array`\n\nUn tableau de chaînes ou d'objets avec une propriété `id` (et tout ce dont tu as besoin, comme `name`). Les ids sont écrits, séparés par des virgules, dans la source map en mode debug. Lis le tableau dans `PLUGINS` pour proposer les permissions dans un éditeur d'utilisateurs et vérifie-les avec l'option `permissions` de tes actions (voir [Autorisation](../../guides/authorization/)).\n\nExample: Permissions\n```js\nexports.permissions = [\n\t{ id: 'orders', name: 'Orders' },\n\t{ id: 'orders_remove', name: 'Remove orders' }\n];\n```\n\n### exports.icon, exports.visible, exports.position, ...\n\nType: `property`\n\nTes propres propriétés d'un plugin.\n\nTotal.js ne lit aucune autre propriété de `index.js`. Des propriétés comme `icon`, `position` ou `visible` sont une convention pour ton interface d'administration, qui les lit dans `PLUGINS`.\n\nExample: Données de menu\n```js\nexports.icon = 'ti ti-truck';\nexports.position = 5;\nexports.visible = function(user) {\n\treturn user.sa || user.permissions.includes('orders');\n};\n```\n\n### PLUGINS\n\nType: `property`\n\nTous les plugins chargés, par id.\n\nReturns: `Object` id: exports\n\nUn objet dont les clés sont les ids des plugins et les valeurs les exports de leur `index.js`. Il est rempli pendant le chargement de l'application.\n\nExample: Lister les plugins\n```js\nON('ready', function() {\n\tfor (var id in PLUGINS)\n\t\tconsole.log(id, PLUGINS[id].name);\n});\n```\n\n### plugins/{id}/config\n\nType: `config` · Since: `0.0.16`\n\nFichier de configuration d'un plugin.\n\nUn fichier `config` dans le dossier d'un plugin est lu avant l'exécution des scripts de l'application et des plugins, après le `config` principal. Il a le même format que le fichier principal et ses clés sont fusionnées dans `CONF` ; une clé également présente dans le fichier principal est écrasée.\n\nExample: Valeurs par défaut d'un plugin\n```text\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n### plugins/{id}/index.flow\n\nType: `type` · Since: `0.0.19`\n\nUn FlowStream chargé avec le plugin.\n\nUn fichier `index.flow` (un export FlowStream en JSON) dans le dossier d'un plugin est lu et démarré après les fichiers de l'application et le `index.js` du plugin, avant les autres fichiers du plugin ; l'instance est créée de manière asynchrone et est stockée dans `PLUGINS[id].flowstream` dès qu'elle est prête. Le FlowStream reçoit l'id du plugin comme `id`, le `name` traduit du plugin (ou l'id) comme `name` et le dossier du plugin comme `directory`. L'instance est stockée dans `PLUGINS[id].flowstream` ; les erreurs sont journalisées sous `Plugin.<id>.flowstream`. Voir [FlowStream](../../guides/flowstream/).\n\n### PLUGINS[id].flowstream\n\nType: `property` · Since: `0.0.19`\n\nL'instance FlowStream chargée depuis index.flow.\n\nReturns: `FlowStream`\n\nDéfinie lorsque le fichier `index.flow` du plugin a été chargé.\n\n### PATH.plugins([path])\n\nType: `method`\n\nRenvoie un chemin dans le dossier des plugins.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un chemin relatif comme \"shop/data.json\" |\n\nReturns: `String` Chemin absolu\n\nSans argument, elle renvoie le chemin absolu de `plugins/` ; avec un chemin, elle le joint. Avec un chemin, le dossier des plugins est créé s'il n'existe pas.\n\nExample: Lire un fichier d'un plugin\n```js\nvar filename = PATH.plugins('shop/data/countries.json');\nF.Fs.readFile(filename, 'utf8', function(err, data) {\n\t// ...\n});\n```\n\n### controller.view('#{id}/path')\n\nType: `type`\n\nRend une vue depuis le dossier d'un plugin.\n\nUn nom de vue qui commence par `#` est relatif à `plugins/` : `#shop/views/index` rend `plugins/shop/views/index.html`. Le même préfixe fonctionne dans `TEMPLATE('#shop/templates/order.html')`, qui ajoute `.html` lorsque le nom ne le contient pas.\n\nExample: Une vue d'un plugin\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n### COMPONENTATOR(name, components, [removeprev], [attrs])\n\nType: `method`\n\nTélécharge un bundle de composants UI depuis Componentator.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du bundle ; utilisé dans le nom du fichier et comme clé dans REPO |\n| `components` | `String` | yes |  | Noms des composants séparés par des virgules |\n| `removeprev` | `Boolean` | no | `true` | Supprimer les anciens bundles du même nom |\n| `attrs` | `String` | no | `''` | Champs supplémentaires encodés pour l'URL, envoyés avec la requête de téléchargement |\n\nTélécharge un fichier minifié contenant les composants jComponent listés depuis `https://componentator.com/download/` dans `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` lorsque `removeprev` vaut `false`). Le hash est calculé à partir de `components`, et le fichier n'est téléchargé que s'il n'existe pas. Avec `removeprev` (par défaut), les anciens fichiers `ui-<name>-*` sont supprimés. L'URL du bundle est stockée dans `REPO[name]`. Les erreurs sont journalisées. Lorsque `removeprev` est une chaîne, elle est prise comme `attrs`.\n\nExample: Un bundle UI\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true);\n```\n\nExample: Dans le layout\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n### ON('componentator', function(meta) {})\n\nType: `event`\n\nÉmis avant que COMPONENTATOR() ne construise le nom du fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | { name, components } |\n\n`meta` contient `name` et `components`. Tu peux modifier les deux, par exemple pour ajouter un composant à chaque bundle ; les nouvelles valeurs sont utilisées pour le nom du fichier, `REPO` et le téléchargement.\n\nExample: Ajouter un composant partout\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',errorhandler';\n});\n```\n\n### NEWCOMPONENT(html, [callback])\n\nType: `method`\n\nCompile un composant serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Nom de fichier, HTML ou URL |\n| `callback` | `Function` | no |  | function(err, component) |\n\nReturns: `Promise<Component>` Lorsque le callback n'est pas défini\n\n`html` est le nom d'un fichier de `components/` (sans `.html`), le contenu HTML lui-même (tout ce qui contient `<`), ou une URL `https://` téléchargée au préalable. Le code serveur doit se trouver dans un bloc `<script total>` ou `<script node>` ; sans lui, tu obtiens l'erreur « Invalid component content ». Le code s'exécute avec `exports` (le composant) et `require` (`REQUIRE()`). Les paquets de `exports.npm` sont installés, les schémas des entrées et des sorties sont compilés et `exports.install()` est appelée. Renvoie une Promise sans callback.\n\nExample: Depuis le dossier components\n```js\nNEWCOMPONENT('uppercase', function(err, com) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar instance = com.create();\n});\n```\n\nExample: En ligne\n```js\nvar html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\\'output\\', msg.data * 2); };</script>';\nvar com = await NEWCOMPONENT(html);\n```\n\n### components/{name}.html\n\nType: `type`\n\nLe format d'un composant serveur.\n\nUn fichier HTML composé de ces parties : `<script total>` ou `<script node>` (code serveur, obligatoire), `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` et `<template>`. Le code serveur est retiré du résultat ; les autres parties sont disponibles dans `component.ui` (`settings`, `css`, `js`, `html`, `readme`, `schema`, `template`).\n\nExample: Un fichier complet\n```html\n<script total>\n\n\texports.name = 'Counter';\n\texports.config = { step: 1 };\n\texports.inputs = [{ id: 'input', name: 'Value' }];\n\texports.outputs = [{ id: 'output', name: 'Sum' }];\n\n\texports.make = function(instance, config) {\n\t\tvar sum = 0;\n\t\tinstance.message = function(msg) {\n\t\t\tsum += config.step;\n\t\t\tmsg.send('output', sum);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nCounts incoming messages.\n</readme>\n\n<settings>\n<div>Step of the counter</div>\n</settings>\n```\n\n### Component\n\nType: `class`\n\nUn composant serveur compilé.\n\nL'objet renvoyé par `NEWCOMPONENT()`. Ses propriétés proviennent des `exports` du code serveur (`name`, `config`, `inputs`, `outputs`, `npm`, `make`, ...) auxquelles s'ajoutent `ui`, `instances`, `variables`, `secrets` et `debugger`.\n\n### exports.make = function(instance, config, status) {}\n\nType: `delegate`\n\nConfigure une nouvelle instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | La nouvelle instance |\n| `config` | `Object` | yes |  | Sa configuration |\n| `status` | `Object` | yes |  | Le deuxième argument de create() |\n\nAppelée par `component.create()` avec l'instance comme `this` et comme premier argument. Assigne ici `instance.message` (et d'autres gestionnaires comme `instance.close`, `instance.configure` ou `instance.service`).\n\nExample: Gestionnaires\n```js\nexports.make = function(instance, config) {\n\tinstance.message = function(msg) {\n\t\tmsg.send('output', msg.data);\n\t};\n\tinstance.configure = function() {\n\t\t// config has changed\n\t};\n};\n```\n\n### exports.config\n\nType: `property`\n\nConfiguration par défaut des instances.\n\nReturns: `Object`\n\nChaque instance reçoit un clone de cet objet, étendu avec les options passées à `component.create()`.\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nEntrées et sorties du composant.\n\nReturns: `Array`\n\nDes tableaux de `{ id, name, schema }`. Un `schema` (une chaîne de schéma comme `'name:String, age:Number'`) est compilé en schéma JSON. Pour les entrées, il est appliqué dans `instance.input()` : les données nettoyées remplacent `msg.data` et les erreurs se trouvent dans `msg.error`.\n\nExample: Avec un schéma\n```js\nexports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n\nexports.make = function(instance) {\n\tinstance.message = function(msg) {\n\t\tif (msg.error)\n\t\t\tmsg.send('error', msg.error.toString());\n\t\telse\n\t\t\tmsg.send('ok', msg.data);\n\t};\n};\n```\n\n### exports.npm\n\nType: `property`\n\nLes paquets NPM dont le composant a besoin.\n\nReturns: `String[]`\n\nUn tableau de noms de paquets (éventuellement `name@version`). `NEWCOMPONENT()` les installe avec `NPMINSTALL()` avant l'exécution de `install()` ; la compilation échoue avec l'erreur de npm lorsqu'un paquet ne peut pas être installé.\n\nExample: Dépendances\n```js\nexports.npm = ['mqtt'];\n\nexports.make = function(instance, config) {\n\tvar mqtt = require('mqtt');\n\t// ...\n};\n```\n\n### exports.install = function(component) {}\n\nType: `delegate`\n\nAppelée une fois après la compilation du composant.\n\nS'exécute avec le composant comme `this` et comme argument, après l'installation des paquets NPM et la compilation des schémas.\n\n### exports.onextend = function(instance) {}\n\nType: `delegate`\n\nÉtend chaque nouvelle instance avant make().\n\nAppelée dans `component.create()` après la définition de la configuration et avant `make()`.\n\n### exports.oncreate = function(instance) {}\n\nType: `delegate`\n\nAppelée après la création d'une instance.\n\nS'exécute de manière asynchrone (dans `setImmediate`) après `make()`.\n\n### exports.onremove = function(instance) {}\n\nType: `delegate`\n\nAppelée lorsqu'une instance est retirée.\n\nAppelée par `instance.remove()` après les gestionnaires `close` et `destroy` de l'instance.\n\n### component.ui\n\nType: `property`\n\nLes parties UI du fichier du composant.\n\nReturns: `Object`\n\nUn objet avec `readme`, `settings`, `css`, `js`, `html`, `schema` et `template` (uniquement les parties trouvées dans le fichier).\n\n### component.instances\n\nType: `property`\n\nToutes les instances du composant.\n\nReturns: `Instance[]`\n\n`create()` ajoute une instance et `instance.remove()` la retire.\n\n### component.debugger\n\nType: `property`\n\nAffiche dans la console les messages de statut, de debug, d'erreur et de sortie.\n\nReturns: `Boolean`\n\n`true` par défaut. Définis-la à `false` pour garder la console silencieuse, ou remplace `component.output`, `component.status`, `component.debug`, `component.throw` ou `component.dashboard` par tes propres fonctions.\n\n### component.output = function(instance, msg) {}\n\nType: `delegate`\n\nReçoit chaque message envoyé à une sortie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | L'émetteur |\n| `msg` | `Message` | yes |  | msg.output et msg.data |\n\nAppelée pour chaque `msg.send()` de n'importe quelle instance. Par défaut, elle affiche la sortie et les données lorsque `debugger` est activé. Remplace-la pour connecter des instances ou traiter les résultats. `component.status(instance, value)`, `component.debug(instance, value)`, `component.throw(instance, err)` et `component.dashboard(instance, value)` reçoivent les appels des méthodes de l'instance portant le même nom.\n\nExample: Collecter les résultats\n```js\nvar com = await NEWCOMPONENT('uppercase');\ncom.output = function(instance, msg) {\n\tconsole.log(instance.id, msg.output, msg.data);\n};\n```\n\n### component.create([options], [status])\n\nType: `method`\n\nCrée une instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Configuration de l'instance |\n| `status` | `Object` | no |  | Passé à make() comme troisième argument |\n\nReturns: `Instance`\n\nL'instance reçoit un `id` aléatoire, un clone de `component.config` étendu avec `options`, et est ajoutée à `component.instances`. Ensuite `onextend()`, `make()` et (de manière asynchrone) `oncreate()` sont appelées.\n\nExample: Deux instances\n```js\nvar a = com.create({ prefix: 'A: ' });\nvar b = com.create({ prefix: 'B: ' });\n```\n\n### component.service(counter)\n\nType: `method`\n\nAppelle instance.service(counter) sur toutes les instances.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Une valeur quelconque passée aux instances |\n\nTotal.js ne l'appelle pas pour toi. Appelle-la depuis `ON('service')` lorsque tes instances ont besoin d'un battement périodique.\n\nExample: Chaque minute\n```js\nON('service', function(counter) {\n\tcom.service(counter);\n});\n```\n\n### Instance\n\nType: `class`\n\nUne instance d'un composant serveur.\n\nRenvoyée par `component.create()`. Propriétés : `id`, `config`, `module` (le composant) et `cache` (un objet vide pour tes données). Gestionnaires que tu peux assigner dans `make()` : `message`, `message_<input>`, `configure`, `close`, `destroy` et `service`.\n\n### instance.message = function(msg) {}\n\nType: `delegate`\n\nTraite les données qui arrivent sur une entrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Message` | yes |  | Le message entrant |\n\nAppelée par `instance.input()`. `msg.input` est l'id de l'entrée et `msg.data` les données. Un gestionnaire nommé `instance.message_<input>` est appelé aussi, après `message`. Sans `instance.message`, l'entrée est ignorée.\n\nExample: Par entrée\n```js\nexports.make = function(instance) {\n\tinstance.message = NOOP;\n\tinstance.message_reset = function(msg) {\n\t\t// only for input \"reset\"\n\t};\n};\n```\n\n### instance.input(input, data, [callback])\n\nType: `method`\n\nEnvoie des données à une entrée de l'instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String` | yes |  | Id de l'entrée |\n| `data` | `Object` | yes |  | Les données |\n| `callback` | `Function` | no |  | function(msg) |\n\nCrée un message, valide les données avec le schéma de l'entrée (s'il existe) et appelle `instance.message(msg)` et `instance.message_<input>(msg)`. Le `callback` est appelé avec le message chaque fois que celui-ci est envoyé à une sortie avec `msg.send()`.\n\nExample: Appeler et lire le résultat\n```js\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);\n});\n```\n\n### instance.send(output, data)\n\nType: `method` · Since: `0.0.17`\n\nEnvoie de nouvelles données vers une sortie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id de la sortie |\n| `data` | `Object` | yes |  | Les données |\n\nCrée un nouveau message avec `data` et l'envoie vers `output` ; il aboutit dans `instance.output(msg)` et donc dans `component.output()`. Utilise-la pour les données que l'instance produit d'elle-même (un timer, un socket).\n\nExample: Un timer\n```js\nexports.make = function(instance) {\n\tvar timer = setInterval(() => instance.send('output', new Date()), 5000);\n\tinstance.close = () => clearInterval(timer);\n};\n```\n\n### instance.status(value) / debug(value) / throw(err) / dashboard(value)\n\nType: `method`\n\nSignale un état de l'instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Une valeur quelconque |\n\nChaque méthode appelle la méthode du composant portant le même nom (`component.status(instance, value)`, etc.). Par défaut, elles affichent dans la console lorsque `component.debugger` est activé.\n\nExample: Signaler\n```js\ninstance.status({ connected: true });\ninstance.throw(new Error('Connection refused'));\n```\n\n### instance.activity(key, name, value)\n\nType: `method` · Since: `0.0.19`\n\nSignale une activité de l'instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Identifiant de l'activité |\n| `name` | `String` | yes |  | Libellé |\n| `value` | `Object` | yes |  | Par exemple une progression |\n\nAppelle `component.activity(instance, { key, name, value })`, qui affiche `ACTIVITY` dans la console lorsque `component.debugger` est activé. Remplace `component.activity` pour la traiter.\n\n### instance.reconfigure(options)\n\nType: `method`\n\nModifie la configuration d'une instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Nouvelles valeurs |\n\nCopie les clés de `options` dans `instance.config` et appelle `instance.configure(config)` lorsqu'elle est définie.\n\nExample: Modifier une valeur\n```js\ninstance.reconfigure({ prefix: '>> ' });\n```\n\n### instance.remove()\n\nType: `method`\n\nRetire l'instance.\n\nAppelle `instance.close(true)` et `instance.destroy()` lorsqu'elles sont définies, puis `component.onremove(instance)`, et retire l'instance de `component.instances`.\n\nExample: Retirer\n```js\ninstance.remove();\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nRemplace les placeholders {key} dans une chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String|Object` | yes |  | Template |\n| `data` | `Object` | no |  | Valeurs |\n| `encoding` | `String|Function` | no |  | Encodage des valeurs |\n\nReturns: `String|Object`\n\nChaque `{key}` (ou `{{key}}`) est pris dans `component.variables`, puis dans `component.secrets`, puis dans `data` (les clés imbriquées avec des points fonctionnent). Sans `data`, l'instance elle-même est utilisée. `encoding` peut valoir `'url'` (ou `'urlencoded'`), `'json'`, `'querify'` ou une `function(value, key)`. Les dates sont formatées. Un objet passé comme `str` voit ses valeurs de type chaîne remplacées. `msg.replace()` fonctionne de la même manière.\n\nExample: Une URL\n```js\ncom.variables.api = 'https://api.example.com';\nvar url = instance.replace('{api}/users/{id}/', { id: 15 });\n```\n\n### Message\n\nType: `class`\n\nLes données qui circulent dans une instance de composant.\n\nCréé par `instance.input()` et `instance.send()`. Propriétés : `data`, `input`, `output`, `error` (un ErrorBuilder lorsque le schéma de l'entrée a échoué, `null` lorsqu'il a réussi, `undefined` pour une entrée sans schéma), `from` et `instance` (l'instance), `repo` et `vars` (des objets vides pour tes données).\n\n### msg.send(output, [data])\n\nType: `method`\n\nEnvoie le message à une sortie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id de la sortie |\n| `data` | `Object` | no |  | Nouvelles données |\n\nDéfinit `msg.output` et, lorsque `data` est fourni, `msg.data`. Appelle ensuite le callback de `instance.input()` et `instance.output(msg)`. Rien ne se passe après `msg.end()`.\n\nExample: Transmettre\n```js\ninstance.message = function(msg) {\n\tmsg.send('output', { received: msg.data });\n};\n```\n\n### msg.end() / msg.destroy()\n\nType: `method`\n\nLibère le message.\n\nVide `data`, `vars`, `repo` et l'instance, si bien que les appels ultérieurs à `msg.send()` ne font rien.\n\n### NPMINSTALL(name, [callback])\n\nType: `method`\n\nInstalle un paquet NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du paquet, éventuellement avec @version |\n| `callback` | `Function` | no |  | function(err) |\n\nReturns: `Promise` Lorsque le callback n'est pas défini\n\nExécute `npm install <name>` dans `CONF.$nodemodules` (créé s'il manque). Lorsque le dossier du paquet contient déjà un `package.json` (avec la même version pour `name@version`), rien n'est installé. Lorsque le processus s'exécute en tant qu'utilisateur 33 (www-data), `CONF.$npmcache` est utilisé comme cache npm. Sans callback, elle renvoie une Promise. Voir [Configuration](../../guides/configuration/) pour les deux clés.\n\nExample: Installer et charger\n```js\nNPMINSTALL('qrcode@1.5.4', function(err) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar QR = REQUIRE('qrcode');\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nCharge un module Node.js ou NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du module |\n\nReturns: `Object` Le module\n\nLes noms avec le préfixe `node:` et les modules intégrés de Node.js (`fs`, `path`, `crypto`, ...) sont chargés directement. Les autres noms sont chargés avec `require()` et, en cas d'échec, depuis `CONF.$nodemodules`, de sorte que les paquets installés avec `NPMINSTALL()` sont trouvés. Elle lève une exception lorsque le module ne peut pas être chargé.\n\nExample: Charger\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nTélécharge et charge un module JavaScript distant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL d'un fichier .js |\n| `callback` | `Function` | no |  | function(err, module, response) |\n\nReturns: `Promise` Lorsque le callback n'est pas défini\n\nLe fichier est téléchargé dans le dossier temporaire et chargé avec require. Les appels suivants avec la même URL dans le même processus renvoient le module chargé sans le télécharger. Une réponse avec le statut `400` ou plus donne l'erreur `The address answered with the status <status>` et rien n'est chargé. Un fichier qui n'est pas un module valide donne l'erreur de `require()`, par exemple une `SyntaxError`. Le callback reçoit `(err, module, response)` ; sans lui, une Promise est résolue avec le module.\n\nExample: Promise\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n","entries":[{"type":"type","name":"Plugin","signature":"plugins/{id}/index.js","since":"","deprecated":false},{"type":"delegate","name":"plugin.install()","signature":"exports.install = function() {}","since":"","deprecated":false},{"type":"property","name":"plugin.id","signature":"exports.id","since":"","deprecated":false},{"type":"property","name":"plugin.name","signature":"exports.name","since":"","deprecated":false},{"type":"property","name":"plugin.permissions","signature":"exports.permissions","since":"","deprecated":false},{"type":"property","name":"plugin.icon","signature":"exports.icon, exports.visible, exports.position, ...","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"config","name":"plugins/{id}/config","signature":"plugins/{id}/config","since":"0.0.16","deprecated":false},{"type":"type","name":"plugins/{id}/index.flow","signature":"plugins/{id}/index.flow","since":"0.0.19","deprecated":false},{"type":"property","name":"plugin.flowstream","signature":"PLUGINS[id].flowstream","since":"0.0.19","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([path])","since":"","deprecated":false},{"type":"type","name":"view('#plugin/...')","signature":"controller.view('#{id}/path')","since":"","deprecated":false},{"type":"method","name":"COMPONENTATOR()","signature":"COMPONENTATOR(name, components, [removeprev], [attrs])","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"method","name":"NEWCOMPONENT()","signature":"NEWCOMPONENT(html, [callback])","since":"","deprecated":false},{"type":"type","name":"Component file","signature":"components/{name}.html","since":"","deprecated":false},{"type":"class","name":"Component","signature":"Component","since":"","deprecated":false},{"type":"delegate","name":"component.make","signature":"exports.make = function(instance, config, status) {}","since":"","deprecated":false},{"type":"property","name":"component.config","signature":"exports.config","since":"","deprecated":false},{"type":"property","name":"component.inputs","signature":"exports.inputs / exports.outputs","since":"","deprecated":false},{"type":"property","name":"component.npm","signature":"exports.npm","since":"","deprecated":false},{"type":"delegate","name":"component.install","signature":"exports.install = function(component) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onextend","signature":"exports.onextend = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.oncreate","signature":"exports.oncreate = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onremove","signature":"exports.onremove = function(instance) {}","since":"","deprecated":false},{"type":"property","name":"component.ui","signature":"component.ui","since":"","deprecated":false},{"type":"property","name":"component.instances","signature":"component.instances","since":"","deprecated":false},{"type":"property","name":"component.debugger","signature":"component.debugger","since":"","deprecated":false},{"type":"delegate","name":"component.output()","signature":"component.output = function(instance, msg) {}","since":"","deprecated":false},{"type":"method","name":"component.create()","signature":"component.create([options], [status])","since":"","deprecated":false},{"type":"method","name":"component.service()","signature":"component.service(counter)","since":"","deprecated":false},{"type":"class","name":"Instance","signature":"Instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"instance.input()","signature":"instance.input(input, data, [callback])","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data)","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(value) / debug(value) / throw(err) / dashboard(value)","since":"","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, value)","since":"0.0.19","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(options)","since":"","deprecated":false},{"type":"method","name":"instance.remove()","signature":"instance.remove()","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"class","name":"Message","signature":"Message","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"msg.send(output, [data])","since":"","deprecated":false},{"type":"method","name":"message.end()","signature":"msg.end() / msg.destroy()","since":"","deprecated":false},{"type":"method","name":"NPMINSTALL()","signature":"NPMINSTALL(name, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwv07bx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Plugin e componenti","summary":"La definizione di un plugin, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() con i suoi oggetti Component, Instance e Message, NPMINSTALL(), REQUIRE() e IMPORT().","markdown":"---\ntitle: Plugin e componenti\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/plugins-and-components/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Plugin e componenti\n\n> La definizione di un plugin, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() con i suoi oggetti Component, Instance e Message, NPMINSTALL(), REQUIRE() e IMPORT().\n\nProprietà dell'`index.js` di un plugin, i file del plugin, `PLUGINS`, `COMPONENTATOR()`, i componenti server compilati con `NEWCOMPONENT()` (il componente, le sue istanze e i messaggi) e i loader `NPMINSTALL()`, `REQUIRE()` e `IMPORT()`. Per un'introduzione con esempi leggi la guida [Plugin e componenti](../../guides/plugins-and-components/).\n\n## API\n\n### plugins/{id}/index.js\n\nType: `type`\n\nUna cartella in plugins/ con un file index.js, caricata all'avvio.\n\nOgni cartella in `plugins/` con un file `index.js` è un plugin; il nome della cartella è l'id del plugin. Una cartella senza `index.js` viene saltata con tutte le sue sottocartelle, così come le cartelle il cui nome contiene `-bk` o `_bk`. Total.js carica `index.js` con require, salva i suoi export in `PLUGINS[id]`, imposta `exports.id` se manca e chiama `exports.install()`. Un file `config` nella cartella viene unito in `CONF`. Le sottocartelle `controllers/`, `actions/`, `schemas/`, `models/`, `definitions/`, `extensions/` e `middleware/` vengono caricate come le cartelle dell'applicazione. Un file `index.flow` viene caricato come FlowStream.\n\nExample: Un plugin minimo\n```js\n// plugins/contacts/index.js\nexports.name = 'Contacts';\nexports.icon = 'ti ti-address-book';\nexports.permissions = ['contacts'];\n\nexports.install = function() {\n\tROUTE('+API    ?    contacts_list    --> Contacts/list');\n};\n```\n\n### exports.install = function() {}\n\nType: `delegate`\n\nChiamata una volta quando il plugin viene caricato.\n\nRegistra qui le route, gli eventi e le altre definizioni del plugin. Viene eseguita durante il caricamento dell'applicazione, nello stesso passaggio dei file di `controllers/`, `definitions/` e delle altre cartelle, quindi usa `ON('ready')` quando ti serve che tutto sia già caricato.\n\nExample: Route e un handler ready\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/contacts/', function($) {\n\t\t$.view('#contacts/views/index');\n\t});\n\tON('ready', function() {\n\t\t// all plugins are loaded\n\t});\n};\n```\n\n### exports.id\n\nType: `property`\n\nL'id del plugin.\n\nReturns: `String`\n\nQuando `index.js` non lo definisce, Total.js lo imposta al nome della cartella del plugin. `PLUGINS` usa in entrambi i casi il nome della cartella come chiave.\n\n### exports.name\n\nType: `property`\n\nUn nome leggibile del plugin.\n\nReturns: `String`\n\nTotal.js lo scrive, con l'id e i permessi, nella source map dell'applicazione in modalità debug. La tua UI può leggerlo da `PLUGINS` per costruire un menu.\n\nExample: Nome\n```js\nexports.name = 'Orders';\n```\n\n### exports.permissions\n\nType: `property`\n\nI permessi definiti dal plugin.\n\nReturns: `Array`\n\nUn array di stringhe o di oggetti con una proprietà `id` (e tutto ciò che ti serve, come `name`). Gli id vengono scritti, uniti da virgole, nella source map in modalità debug. Leggi l'array da `PLUGINS` per proporre i permessi in un editor degli utenti e verificali con l'opzione `permissions` delle tue azioni (vedi [Autorizzazione](../../guides/authorization/)).\n\nExample: Permessi\n```js\nexports.permissions = [\n\t{ id: 'orders', name: 'Orders' },\n\t{ id: 'orders_remove', name: 'Remove orders' }\n];\n```\n\n### exports.icon, exports.visible, exports.position, ...\n\nType: `property`\n\nLe tue proprietà personalizzate di un plugin.\n\nTotal.js non legge nessun'altra proprietà di `index.js`. Proprietà come `icon`, `position` o `visible` sono una convenzione per la tua UI di amministrazione, che le legge da `PLUGINS`.\n\nExample: Dati del menu\n```js\nexports.icon = 'ti ti-truck';\nexports.position = 5;\nexports.visible = function(user) {\n\treturn user.sa || user.permissions.includes('orders');\n};\n```\n\n### PLUGINS\n\nType: `property`\n\nTutti i plugin caricati, per id.\n\nReturns: `Object` id: export\n\nUn oggetto le cui chiavi sono gli id dei plugin e i cui valori sono gli export dei rispettivi `index.js`. Viene riempito durante il caricamento dell'applicazione.\n\nExample: Elencare i plugin\n```js\nON('ready', function() {\n\tfor (var id in PLUGINS)\n\t\tconsole.log(id, PLUGINS[id].name);\n});\n```\n\n### plugins/{id}/config\n\nType: `config` · Since: `0.0.16`\n\nFile di configurazione di un plugin.\n\nUn file `config` nella cartella di un plugin viene letto prima che vengano eseguiti gli script dell'applicazione e dei plugin, dopo il `config` principale. Ha lo stesso formato del file principale e le sue chiavi vengono unite a `CONF`; una chiave presente anche nel file principale viene sovrascritta.\n\nExample: Valori predefiniti di un plugin\n```text\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n### plugins/{id}/index.flow\n\nType: `type` · Since: `0.0.19`\n\nUn FlowStream caricato con il plugin.\n\nUn file `index.flow` (un export FlowStream in JSON) nella cartella di un plugin viene letto e avviato dopo i file dell'applicazione e l'`index.js` del plugin, prima degli altri file del plugin; l'istanza viene creata in modo asincrono e viene salvata in `PLUGINS[id].flowstream` quando è pronta. Il FlowStream riceve l'id del plugin come `id`, il `name` tradotto del plugin (o l'id) come `name` e la cartella del plugin come `directory`. L'istanza viene salvata in `PLUGINS[id].flowstream`; gli errori vengono registrati come `Plugin.<id>.flowstream`. Vedi [FlowStream](../../guides/flowstream/).\n\n### PLUGINS[id].flowstream\n\nType: `property` · Since: `0.0.19`\n\nL'istanza FlowStream caricata da index.flow.\n\nReturns: `FlowStream`\n\nImpostata quando il file `index.flow` del plugin è stato caricato.\n\n### PATH.plugins([path])\n\nType: `method`\n\nRestituisce un percorso nella cartella dei plugin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un percorso relativo come \"shop/data.json\" |\n\nReturns: `String` Percorso assoluto\n\nSenza argomenti restituisce il percorso assoluto di `plugins/`; con un percorso lo unisce. Con un percorso, la cartella dei plugin viene creata quando non esiste.\n\nExample: Leggere un file di un plugin\n```js\nvar filename = PATH.plugins('shop/data/countries.json');\nF.Fs.readFile(filename, 'utf8', function(err, data) {\n\t// ...\n});\n```\n\n### controller.view('#{id}/path')\n\nType: `type`\n\nRenderizza una view da una cartella di plugin.\n\nUn nome di view che inizia con `#` è relativo a `plugins/`: `#shop/views/index` renderizza `plugins/shop/views/index.html`. Lo stesso prefisso funziona in `TEMPLATE('#shop/templates/order.html')`, che aggiunge `.html` quando il nome non lo contiene.\n\nExample: Una view di un plugin\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n### COMPONENTATOR(name, components, [removeprev], [attrs])\n\nType: `method`\n\nScarica un bundle di componenti UI da Componentator.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del bundle; usato nel nome del file e come chiave in REPO |\n| `components` | `String` | yes |  | Nomi dei componenti separati da virgole |\n| `removeprev` | `Boolean` | no | `true` | Elimina i bundle più vecchi con lo stesso nome |\n| `attrs` | `String` | no | `''` | Campi aggiuntivi codificati come URL inviati con la richiesta di download |\n\nScarica da `https://componentator.com/download/` un unico file minificato con i componenti jComponent elencati in `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js` con `removeprev` impostato a `false`). L'hash viene calcolato da `components` e il file viene scaricato solo quando non esiste. Con `removeprev` (predefinito), i file `ui-<name>-*` più vecchi vengono eliminati. L'URL del bundle viene memorizzato in `REPO[name]`. Gli errori vengono registrati nel log. Quando `removeprev` è una stringa, viene considerato come `attrs`.\n\nExample: Un bundle UI\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true);\n```\n\nExample: Nel layout\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n### ON('componentator', function(meta) {})\n\nType: `event`\n\nEmesso prima che COMPONENTATOR() costruisca il nome del file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | { name, components } |\n\n`meta` contiene `name` e `components`. Puoi modificarli entrambi, ad esempio per aggiungere un componente a ogni bundle; i nuovi valori vengono usati per il nome del file, `REPO` e il download.\n\nExample: Aggiungere un componente ovunque\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',errorhandler';\n});\n```\n\n### NEWCOMPONENT(html, [callback])\n\nType: `method`\n\nCompila un componente server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Nome del file, HTML o URL |\n| `callback` | `Function` | no |  | function(err, component) |\n\nReturns: `Promise<Component>` Quando callback non è impostata\n\n`html` è il nome di un file in `components/` (senza `.html`), il contenuto HTML stesso (qualsiasi cosa contenga `<`) oppure un URL `https://` che viene prima scaricato. Il codice server deve trovarsi in un blocco `<script total>` o `<script node>`; senza di esso ottieni l'errore \"Invalid component content\". Il codice viene eseguito con `exports` (il componente) e `require` (`REQUIRE()`). I pacchetti in `exports.npm` vengono installati, gli schemi degli input e degli output vengono compilati e viene chiamato `exports.install()`. Senza callback restituisce una Promise.\n\nExample: Dalla cartella components\n```js\nNEWCOMPONENT('uppercase', function(err, com) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar instance = com.create();\n});\n```\n\nExample: Inline\n```js\nvar html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\\'output\\', msg.data * 2); };</script>';\nvar com = await NEWCOMPONENT(html);\n```\n\n### components/{name}.html\n\nType: `type`\n\nIl formato di un componente server.\n\nUn file HTML con queste parti: `<script total>` o `<script node>` (codice server, obbligatorio), `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` e `<template>`. Il codice server viene rimosso dal risultato; le altre parti sono disponibili in `component.ui` (`settings`, `css`, `js`, `html`, `readme`, `schema`, `template`).\n\nExample: Un file completo\n```html\n<script total>\n\n\texports.name = 'Counter';\n\texports.config = { step: 1 };\n\texports.inputs = [{ id: 'input', name: 'Value' }];\n\texports.outputs = [{ id: 'output', name: 'Sum' }];\n\n\texports.make = function(instance, config) {\n\t\tvar sum = 0;\n\t\tinstance.message = function(msg) {\n\t\t\tsum += config.step;\n\t\t\tmsg.send('output', sum);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nCounts incoming messages.\n</readme>\n\n<settings>\n<div>Step of the counter</div>\n</settings>\n```\n\n### Component\n\nType: `class`\n\nUn componente server compilato.\n\nL'oggetto restituito da `NEWCOMPONENT()`. Le sue proprietà provengono dagli `exports` del codice server (`name`, `config`, `inputs`, `outputs`, `npm`, `make`, ...) più `ui`, `instances`, `variables`, `secrets` e `debugger`.\n\n### exports.make = function(instance, config, status) {}\n\nType: `delegate`\n\nConfigura una nuova istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | La nuova istanza |\n| `config` | `Object` | yes |  | La sua configurazione |\n| `status` | `Object` | yes |  | Il secondo argomento di create() |\n\nChiamata da `component.create()` con l'istanza come `this` e come primo argomento. Assegna qui `instance.message` (e altri handler come `instance.close`, `instance.configure` o `instance.service`).\n\nExample: Handler\n```js\nexports.make = function(instance, config) {\n\tinstance.message = function(msg) {\n\t\tmsg.send('output', msg.data);\n\t};\n\tinstance.configure = function() {\n\t\t// config has changed\n\t};\n};\n```\n\n### exports.config\n\nType: `property`\n\nConfigurazione predefinita delle istanze.\n\nReturns: `Object`\n\nOgni istanza riceve un clone di questo oggetto, esteso con le opzioni passate a `component.create()`.\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nInput e output del componente.\n\nReturns: `Array`\n\nArray di `{ id, name, schema }`. Uno `schema` (una stringa di schema come `'name:String, age:Number'`) viene compilato in uno schema JSON. Per gli input viene applicato in `instance.input()`: i dati ripuliti sostituiscono `msg.data` e gli errori sono in `msg.error`.\n\nExample: Con uno schema\n```js\nexports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n\nexports.make = function(instance) {\n\tinstance.message = function(msg) {\n\t\tif (msg.error)\n\t\t\tmsg.send('error', msg.error.toString());\n\t\telse\n\t\t\tmsg.send('ok', msg.data);\n\t};\n};\n```\n\n### exports.npm\n\nType: `property`\n\nPacchetti NPM necessari al componente.\n\nReturns: `String[]`\n\nUn array di nomi di pacchetti (facoltativamente `name@version`). `NEWCOMPONENT()` li installa con `NPMINSTALL()` prima che venga eseguito `install()`; la compilazione fallisce con l'errore di npm quando uno non può essere installato.\n\nExample: Dipendenze\n```js\nexports.npm = ['mqtt'];\n\nexports.make = function(instance, config) {\n\tvar mqtt = require('mqtt');\n\t// ...\n};\n```\n\n### exports.install = function(component) {}\n\nType: `delegate`\n\nChiamata una volta dopo la compilazione del componente.\n\nViene eseguita con il componente come `this` e come argomento, dopo che i pacchetti NPM sono stati installati e gli schemi compilati.\n\n### exports.onextend = function(instance) {}\n\nType: `delegate`\n\nEstende ogni nuova istanza prima di make().\n\nChiamata in `component.create()` dopo che la configurazione è stata impostata e prima di `make()`.\n\n### exports.oncreate = function(instance) {}\n\nType: `delegate`\n\nChiamata dopo la creazione di un'istanza.\n\nViene eseguita in modo asincrono (in `setImmediate`) dopo `make()`.\n\n### exports.onremove = function(instance) {}\n\nType: `delegate`\n\nChiamata quando un'istanza viene rimossa.\n\nChiamata da `instance.remove()` dopo gli handler `close` e `destroy` dell'istanza.\n\n### component.ui\n\nType: `property`\n\nLe parti UI del file del componente.\n\nReturns: `Object`\n\nUn oggetto con `readme`, `settings`, `css`, `js`, `html`, `schema` e `template` (solo le parti trovate nel file).\n\n### component.instances\n\nType: `property`\n\nTutte le istanze del componente.\n\nReturns: `Instance[]`\n\n`create()` aggiunge un'istanza e `instance.remove()` la rimuove.\n\n### component.debugger\n\nType: `property`\n\nStampa nella console i messaggi di stato, debug, errore e output.\n\nReturns: `Boolean`\n\n`true` per impostazione predefinita. Impostalo a `false` per mantenere silenziosa la console, oppure sostituisci `component.output`, `component.status`, `component.debug`, `component.throw` o `component.dashboard` con funzioni tue.\n\n### component.output = function(instance, msg) {}\n\nType: `delegate`\n\nRiceve ogni messaggio inviato a un output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | Il mittente |\n| `msg` | `Message` | yes |  | msg.output e msg.data |\n\nChiamata per ogni `msg.send()` di qualsiasi istanza. Quella predefinita stampa l'output e i dati quando `debugger` è attivo. Sostituiscila per collegare le istanze o per elaborare i risultati. `component.status(instance, value)`, `component.debug(instance, value)`, `component.throw(instance, err)` e `component.dashboard(instance, value)` ricevono le chiamate dei metodi dell'istanza con lo stesso nome.\n\nExample: Raccogliere i risultati\n```js\nvar com = await NEWCOMPONENT('uppercase');\ncom.output = function(instance, msg) {\n\tconsole.log(instance.id, msg.output, msg.data);\n};\n```\n\n### component.create([options], [status])\n\nType: `method`\n\nCrea un'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Configurazione dell'istanza |\n| `status` | `Object` | no |  | Passato a make() come terzo argomento |\n\nReturns: `Instance`\n\nL'istanza riceve un `id` casuale, un clone di `component.config` esteso con `options`, e viene aggiunta a `component.instances`. Poi vengono chiamati `onextend()`, `make()` e (in modo asincrono) `oncreate()`.\n\nExample: Due istanze\n```js\nvar a = com.create({ prefix: 'A: ' });\nvar b = com.create({ prefix: 'B: ' });\n```\n\n### component.service(counter)\n\nType: `method`\n\nChiama instance.service(counter) su tutte le istanze.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Qualsiasi valore passato alle istanze |\n\nTotal.js non la chiama al posto tuo. Chiamala da `ON('service')` quando le tue istanze hanno bisogno di un tick periodico.\n\nExample: Ogni minuto\n```js\nON('service', function(counter) {\n\tcom.service(counter);\n});\n```\n\n### Instance\n\nType: `class`\n\nUn'istanza di un componente server.\n\nRestituita da `component.create()`. Proprietà: `id`, `config`, `module` (il componente) e `cache` (un oggetto vuoto per i tuoi dati). Handler che puoi assegnare in `make()`: `message`, `message_<input>`, `configure`, `close`, `destroy` e `service`.\n\n### instance.message = function(msg) {}\n\nType: `delegate`\n\nGestisce i dati che arrivano a un input.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Message` | yes |  | Il messaggio in arrivo |\n\nChiamata da `instance.input()`. `msg.input` è l'id dell'input e `msg.data` i dati. Viene chiamato anche un handler di nome `instance.message_<input>`, dopo `message`. Senza `instance.message` l'input viene ignorato.\n\nExample: Per input\n```js\nexports.make = function(instance) {\n\tinstance.message = NOOP;\n\tinstance.message_reset = function(msg) {\n\t\t// only for input \"reset\"\n\t};\n};\n```\n\n### instance.input(input, data, [callback])\n\nType: `method`\n\nInvia dati a un input dell'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String` | yes |  | Id dell'input |\n| `data` | `Object` | yes |  | I dati |\n| `callback` | `Function` | no |  | function(msg) |\n\nCrea un messaggio, valida i dati con lo schema dell'input (se presente) e chiama `instance.message(msg)` e `instance.message_<input>(msg)`. La `callback` viene chiamata con il messaggio ogni volta che questo viene inviato a un output con `msg.send()`.\n\nExample: Chiamare e leggere il risultato\n```js\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);\n});\n```\n\n### instance.send(output, data)\n\nType: `method` · Since: `0.0.17`\n\nInvia nuovi dati a un output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id dell'output |\n| `data` | `Object` | yes |  | I dati |\n\nCrea un nuovo messaggio con `data` e lo invia a `output`; finisce in `instance.output(msg)` e quindi in `component.output()`. Usalo per i dati che l'istanza produce da sola (un timer, un socket).\n\nExample: Un timer\n```js\nexports.make = function(instance) {\n\tvar timer = setInterval(() => instance.send('output', new Date()), 5000);\n\tinstance.close = () => clearInterval(timer);\n};\n```\n\n### instance.status(value) / debug(value) / throw(err) / dashboard(value)\n\nType: `method`\n\nSegnala uno stato dell'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Qualsiasi valore |\n\nOgni metodo chiama il metodo del componente con lo stesso nome (`component.status(instance, value)` e così via). Per impostazione predefinita stampano nella console quando `component.debugger` è attivo.\n\nExample: Segnalare\n```js\ninstance.status({ connected: true });\ninstance.throw(new Error('Connection refused'));\n```\n\n### instance.activity(key, name, value)\n\nType: `method` · Since: `0.0.19`\n\nSegnala un'attività dell'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Identificatore dell'attività |\n| `name` | `String` | yes |  | Etichetta |\n| `value` | `Object` | yes |  | Per esempio un avanzamento |\n\nChiama `component.activity(instance, { key, name, value })`, che stampa `ACTIVITY` nella console quando `component.debugger` è attivo. Sostituisci `component.activity` per elaborarla.\n\n### instance.reconfigure(options)\n\nType: `method`\n\nModifica la configurazione di un'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Nuovi valori |\n\nCopia le chiavi di `options` in `instance.config` e chiama `instance.configure(config)` quando è definito.\n\nExample: Modificare un valore\n```js\ninstance.reconfigure({ prefix: '>> ' });\n```\n\n### instance.remove()\n\nType: `method`\n\nRimuove l'istanza.\n\nChiama `instance.close(true)` e `instance.destroy()` quando sono definiti, poi `component.onremove(instance)`, e rimuove l'istanza da `component.instances`.\n\nExample: Rimuovere\n```js\ninstance.remove();\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nSostituisce i segnaposto {key} in una stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String|Object` | yes |  | Template |\n| `data` | `Object` | no |  | Valori |\n| `encoding` | `String|Function` | no |  | Codifica dei valori |\n\nReturns: `String|Object`\n\nOgni `{key}` (o `{{key}}`) viene preso da `component.variables`, poi da `component.secrets`, poi da `data` (funzionano le chiavi annidate con i punti). Senza `data` viene usata l'istanza stessa. `encoding` può essere `'url'` (o `'urlencoded'`), `'json'`, `'querify'` oppure una `function(value, key)`. Le date vengono formattate. Un oggetto come `str` sostituisce i suoi valori stringa. `msg.replace()` funziona allo stesso modo.\n\nExample: Un URL\n```js\ncom.variables.api = 'https://api.example.com';\nvar url = instance.replace('{api}/users/{id}/', { id: 15 });\n```\n\n### Message\n\nType: `class`\n\nDati che scorrono attraverso un'istanza di componente.\n\nCreato da `instance.input()` e `instance.send()`. Proprietà: `data`, `input`, `output`, `error` (un ErrorBuilder quando lo schema dell'input non è stato superato, `null` quando è stato superato, `undefined` per un input senza schema), `from` e `instance` (l'istanza), `repo` e `vars` (oggetti vuoti per i tuoi dati).\n\n### msg.send(output, [data])\n\nType: `method`\n\nInvia il messaggio a un output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id dell'output |\n| `data` | `Object` | no |  | Nuovi dati |\n\nImposta `msg.output` e, quando `data` è fornito, `msg.data`. Poi chiama la callback di `instance.input()` e `instance.output(msg)`. Dopo `msg.end()` non succede nulla.\n\nExample: Inoltrare\n```js\ninstance.message = function(msg) {\n\tmsg.send('output', { received: msg.data });\n};\n```\n\n### msg.end() / msg.destroy()\n\nType: `method`\n\nRilascia il messaggio.\n\nSvuota `data`, `vars`, `repo` e l'istanza, così le successive chiamate a `msg.send()` non fanno nulla.\n\n### NPMINSTALL(name, [callback])\n\nType: `method`\n\nInstalla un pacchetto NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del pacchetto, facoltativamente con @version |\n| `callback` | `Function` | no |  | function(err) |\n\nReturns: `Promise` Quando callback non è impostata\n\nEsegue `npm install <name>` in `CONF.$nodemodules` (creata se manca). Quando la cartella del pacchetto contiene già un `package.json` (con la stessa versione per `name@version`), non viene installato nulla. Quando il processo gira come utente 33 (www-data), `CONF.$npmcache` viene usata come cache di npm. Senza callback restituisce una Promise. Vedi [Configurazione](../../guides/configuration/) per entrambe le chiavi.\n\nExample: Installare e caricare\n```js\nNPMINSTALL('qrcode@1.5.4', function(err) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar QR = REQUIRE('qrcode');\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nCarica un modulo Node.js o NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del modulo |\n\nReturns: `Object` Il modulo\n\nI nomi con il prefisso `node:` e i moduli integrati di Node.js (`fs`, `path`, `crypto`, ...) vengono caricati direttamente. Gli altri nomi vengono caricati con `require()` e, quando questo fallisce, da `CONF.$nodemodules`, così i pacchetti installati con `NPMINSTALL()` vengono trovati. Lancia un'eccezione quando il modulo non può essere caricato.\n\nExample: Caricare\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nScarica e carica un modulo JavaScript remoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL di un file .js |\n| `callback` | `Function` | no |  | function(err, module, response) |\n\nReturns: `Promise` Quando callback non è impostata\n\nIl file viene scaricato nella cartella temporanea e caricato con require. Le chiamate successive con lo stesso URL nello stesso processo restituiscono il modulo caricato senza scaricarlo. Una risposta con lo stato `400` o superiore dà l'errore `The address answered with the status <status>` e non viene caricato nulla. Un file che non è un modulo valido dà l'errore di `require()`, per esempio un `SyntaxError`. La callback riceve `(err, module, response)`; senza di essa una Promise si risolve con il modulo.\n\nExample: Promise\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n","entries":[{"type":"type","name":"Plugin","signature":"plugins/{id}/index.js","since":"","deprecated":false},{"type":"delegate","name":"plugin.install()","signature":"exports.install = function() {}","since":"","deprecated":false},{"type":"property","name":"plugin.id","signature":"exports.id","since":"","deprecated":false},{"type":"property","name":"plugin.name","signature":"exports.name","since":"","deprecated":false},{"type":"property","name":"plugin.permissions","signature":"exports.permissions","since":"","deprecated":false},{"type":"property","name":"plugin.icon","signature":"exports.icon, exports.visible, exports.position, ...","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"config","name":"plugins/{id}/config","signature":"plugins/{id}/config","since":"0.0.16","deprecated":false},{"type":"type","name":"plugins/{id}/index.flow","signature":"plugins/{id}/index.flow","since":"0.0.19","deprecated":false},{"type":"property","name":"plugin.flowstream","signature":"PLUGINS[id].flowstream","since":"0.0.19","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([path])","since":"","deprecated":false},{"type":"type","name":"view('#plugin/...')","signature":"controller.view('#{id}/path')","since":"","deprecated":false},{"type":"method","name":"COMPONENTATOR()","signature":"COMPONENTATOR(name, components, [removeprev], [attrs])","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"method","name":"NEWCOMPONENT()","signature":"NEWCOMPONENT(html, [callback])","since":"","deprecated":false},{"type":"type","name":"Component file","signature":"components/{name}.html","since":"","deprecated":false},{"type":"class","name":"Component","signature":"Component","since":"","deprecated":false},{"type":"delegate","name":"component.make","signature":"exports.make = function(instance, config, status) {}","since":"","deprecated":false},{"type":"property","name":"component.config","signature":"exports.config","since":"","deprecated":false},{"type":"property","name":"component.inputs","signature":"exports.inputs / exports.outputs","since":"","deprecated":false},{"type":"property","name":"component.npm","signature":"exports.npm","since":"","deprecated":false},{"type":"delegate","name":"component.install","signature":"exports.install = function(component) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onextend","signature":"exports.onextend = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.oncreate","signature":"exports.oncreate = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onremove","signature":"exports.onremove = function(instance) {}","since":"","deprecated":false},{"type":"property","name":"component.ui","signature":"component.ui","since":"","deprecated":false},{"type":"property","name":"component.instances","signature":"component.instances","since":"","deprecated":false},{"type":"property","name":"component.debugger","signature":"component.debugger","since":"","deprecated":false},{"type":"delegate","name":"component.output()","signature":"component.output = function(instance, msg) {}","since":"","deprecated":false},{"type":"method","name":"component.create()","signature":"component.create([options], [status])","since":"","deprecated":false},{"type":"method","name":"component.service()","signature":"component.service(counter)","since":"","deprecated":false},{"type":"class","name":"Instance","signature":"Instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"instance.input()","signature":"instance.input(input, data, [callback])","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data)","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(value) / debug(value) / throw(err) / dashboard(value)","since":"","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, value)","since":"0.0.19","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(options)","since":"","deprecated":false},{"type":"method","name":"instance.remove()","signature":"instance.remove()","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"class","name":"Message","signature":"Message","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"msg.send(output, [data])","since":"","deprecated":false},{"type":"method","name":"message.end()","signature":"msg.end() / msg.destroy()","since":"","deprecated":false},{"type":"method","name":"NPMINSTALL()","signature":"NPMINSTALL(name, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"Jafwv07bx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/plugins-and-components/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Pluginy a komponenty","summary":"Definícia pluginu, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() s jeho objektmi Component, Instance a Message, NPMINSTALL(), REQUIRE() a IMPORT().","markdown":"---\ntitle: Pluginy a komponenty\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/plugins-and-components/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Pluginy a komponenty\n\n> Definícia pluginu, PLUGINS, COMPONENTATOR(), NEWCOMPONENT() s jeho objektmi Component, Instance a Message, NPMINSTALL(), REQUIRE() a IMPORT().\n\nVlastnosti súboru `index.js` pluginu, súbory pluginu, `PLUGINS`, `COMPONENTATOR()`, serverové komponenty skompilované pomocou `NEWCOMPONENT()` (komponent, jeho inštancie a správy) a načítavače `NPMINSTALL()`, `REQUIRE()` a `IMPORT()`. Úvod s príkladmi nájdeš v príručke [Pluginy a komponenty](../../guides/plugins-and-components/).\n\n## API\n\n### plugins/{id}/index.js\n\nType: `type`\n\nPriečinok v plugins/ so súborom index.js, načítaný pri štarte.\n\nKaždý priečinok v `plugins/` so súborom `index.js` je plugin; názov priečinka je id pluginu. Priečinok bez `index.js` sa preskočí so všetkými podpriečinkami, rovnako ako priečinky, ktorých názov obsahuje `-bk` alebo `_bk`. Total.js načíta `index.js` cez require, uloží jeho exporty do `PLUGINS[id]`, nastaví `exports.id`, keď chýba, a zavolá `exports.install()`. Súbor `config` v priečinku sa zlúči do `CONF`. Podpriečinky `controllers/`, `actions/`, `schemas/`, `models/`, `definitions/`, `extensions/` a `middleware/` sa načítajú ako priečinky aplikácie. Súbor `index.flow` sa načíta ako FlowStream.\n\nExample: Minimálny plugin\n```js\n// plugins/contacts/index.js\nexports.name = 'Contacts';\nexports.icon = 'ti ti-address-book';\nexports.permissions = ['contacts'];\n\nexports.install = function() {\n\tROUTE('+API    ?    contacts_list    --> Contacts/list');\n};\n```\n\n### exports.install = function() {}\n\nType: `delegate`\n\nZavolá sa raz, keď sa plugin načíta.\n\nTu zaregistruj route, udalosti a ďalšie definície pluginu. Spúšťa sa počas načítania aplikácie, v tom istom prechode ako súbory z `controllers/`, `definitions/` a ostatných priečinkov, preto použi `ON('ready')`, keď potrebuješ, aby bolo najprv načítané všetko.\n\nExample: Routy a handler pripravenosti\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/contacts/', function($) {\n\t\t$.view('#contacts/views/index');\n\t});\n\tON('ready', function() {\n\t\t// all plugins are loaded\n\t});\n};\n```\n\n### exports.id\n\nType: `property`\n\nId pluginu.\n\nReturns: `String`\n\nKeď ho `index.js` nedefinuje, Total.js ho nastaví na názov priečinka pluginu. `PLUGINS` v oboch prípadoch používa ako kľúč názov priečinka.\n\n### exports.name\n\nType: `property`\n\nČitateľný názov pluginu.\n\nReturns: `String`\n\nTotal.js ho v režime debug zapíše spolu s id a oprávneniami do source mapy aplikácie. Tvoje UI ho môže čítať z `PLUGINS` a zostaviť z neho menu.\n\nExample: Názov\n```js\nexports.name = 'Orders';\n```\n\n### exports.permissions\n\nType: `property`\n\nOprávnenia, ktoré plugin definuje.\n\nReturns: `Array`\n\nPole reťazcov alebo objektov s vlastnosťou `id` (a čímkoľvek ďalším, čo potrebuješ, napríklad `name`). Id sa v režime debug zapíšu, spojené čiarkami, do source mapy. Čítaj pole z `PLUGINS`, aby si ponúkol oprávnenia v editore používateľov, a kontroluj ich pomocou voľby `permissions` tvojich akcií (pozri [Autorizácia](../../guides/authorization/)).\n\nExample: Oprávnenia\n```js\nexports.permissions = [\n\t{ id: 'orders', name: 'Orders' },\n\t{ id: 'orders_remove', name: 'Remove orders' }\n];\n```\n\n### exports.icon, exports.visible, exports.position, ...\n\nType: `property`\n\nTvoje vlastné vlastnosti pluginu.\n\nTotal.js nečíta žiadnu inú vlastnosť súboru `index.js`. Vlastnosti ako `icon`, `position` alebo `visible` sú konvencia pre tvoje administračné UI, ktoré ich číta z `PLUGINS`.\n\nExample: Dáta pre menu\n```js\nexports.icon = 'ti ti-truck';\nexports.position = 5;\nexports.visible = function(user) {\n\treturn user.sa || user.permissions.includes('orders');\n};\n```\n\n### PLUGINS\n\nType: `property`\n\nVšetky načítané pluginy podľa id.\n\nReturns: `Object` id: exports\n\nObjekt, ktorého kľúče sú id pluginov a hodnoty sú exporty ich súborov `index.js`. Napĺňa sa počas načítania aplikácie.\n\nExample: Výpis pluginov\n```js\nON('ready', function() {\n\tfor (var id in PLUGINS)\n\t\tconsole.log(id, PLUGINS[id].name);\n});\n```\n\n### plugins/{id}/config\n\nType: `config` · Since: `0.0.16`\n\nKonfiguračný súbor pluginu.\n\nSúbor `config` v priečinku pluginu sa načíta pred spustením skriptov aplikácie a pluginov, po hlavnom `config`. Má rovnaký formát ako hlavný súbor a jeho kľúče sa zlúčia do `CONF`; kľúč, ktorý je aj v hlavnom súbore, sa prepíše.\n\nExample: Predvolené hodnoty pluginu\n```text\nshop_currency    : EUR\nshop_pagesize    : 20\n```\n\n### plugins/{id}/index.flow\n\nType: `type` · Since: `0.0.19`\n\nFlowStream načítaný s pluginom.\n\nSúbor `index.flow` (export FlowStreamu v JSON) v priečinku pluginu sa prečíta a spustí po súboroch aplikácie a `index.js` pluginu, pred ostatnými súbormi pluginu; inštancia sa vytvára asynchrónne a uloží sa do `PLUGINS[id].flowstream`, keď je pripravená. FlowStream dostane id pluginu ako `id`, preložený `name` pluginu (alebo id) ako `name` a priečinok pluginu ako `directory`. Inštancia sa uloží do `PLUGINS[id].flowstream`; chyby sa logujú ako `Plugin.<id>.flowstream`. Pozri [FlowStream](../../guides/flowstream/).\n\n### PLUGINS[id].flowstream\n\nType: `property` · Since: `0.0.19`\n\nInštancia FlowStreamu načítaná z index.flow.\n\nReturns: `FlowStream`\n\nNastaví sa, keď sa načíta súbor `index.flow` pluginu.\n\n### PATH.plugins([path])\n\nType: `method`\n\nVráti cestu v priečinku pluginov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Relatívna cesta, napríklad \"shop/data.json\" |\n\nReturns: `String` Absolútna cesta\n\nBez argumentu vráti absolútnu cestu k `plugins/`; s cestou ju k nej pripojí. S cestou sa priečinok pluginov vytvorí, keď neexistuje.\n\nExample: Čítanie súboru pluginu\n```js\nvar filename = PATH.plugins('shop/data/countries.json');\nF.Fs.readFile(filename, 'utf8', function(err, data) {\n\t// ...\n});\n```\n\n### controller.view('#{id}/path')\n\nType: `type`\n\nVykreslí pohľad z priečinka pluginu.\n\nNázov view, ktorý začína `#`, je relatívny k `plugins/`: `#shop/views/index` vykreslí `plugins/shop/views/index.html`. Rovnaký prefix funguje v `TEMPLATE('#shop/templates/order.html')`, ktorý pridá `.html`, keď ho názov neobsahuje.\n\nExample: View pluginu\n```js\nexports.install = function() {\n\tROUTE('+GET /admin/shop/', function($) {\n\t\t$.view('#shop/views/index');\n\t});\n};\n```\n\n### COMPONENTATOR(name, components, [removeprev], [attrs])\n\nType: `method`\n\nStiahne balík UI komponentov z Componentatora.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov balíka; používa sa v názve súboru a ako kľúč v REPO |\n| `components` | `String` | yes |  | Názvy komponentov oddelené čiarkami |\n| `removeprev` | `Boolean` | no | `true` | Zmazať staršie balíky s rovnakým názvom |\n| `attrs` | `String` | no | `''` | Ďalšie URL-kódované polia odoslané s požiadavkou na stiahnutie |\n\nStiahne jeden minifikovaný súbor s uvedenými jComponent komponentmi z `https://componentator.com/download/` do `public/ui-<name>-<hash>.min.js` (`public/ui-<hash>.min.js`, keď je `removeprev` nastavené na `false`). Hash sa vypočíta z `components` a súbor sa stiahne iba vtedy, keď neexistuje. S `removeprev` (predvolene) sa staršie súbory `ui-<name>-*` zmažú. URL balíka sa uloží do `REPO[name]`. Chyby sa logujú. Keď je `removeprev` reťazec, berie sa ako `attrs`.\n\nExample: UI balík\n```js\n// definitions/ui.js\nCOMPONENTATOR('ui', 'exec,locale,input,box,validate,loading,notify,datagrid', true);\n```\n\nExample: V layoute\n```html\n<script src=\"@{REPO.ui}\"></script>\n```\n\n### ON('componentator', function(meta) {})\n\nType: `event`\n\nVysiela sa predtým, ako COMPONENTATOR() zostaví názov súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | { name, components } |\n\n`meta` obsahuje `name` a `components`. Môžeš zmeniť oboje, napríklad pridať komponent do každého balíka; nové hodnoty sa použijú pre názov súboru, `REPO` a sťahovanie.\n\nExample: Pridanie komponentu všade\n```js\nON('componentator', function(meta) {\n\tmeta.components += ',errorhandler';\n});\n```\n\n### NEWCOMPONENT(html, [callback])\n\nType: `method`\n\nSkompiluje serverový komponent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Názov súboru, HTML alebo URL |\n| `callback` | `Function` | no |  | function(err, component) |\n\nReturns: `Promise<Component>` Keď nie je nastavený callback\n\n`html` je názov súboru v `components/` (bez `.html`), samotný HTML obsah (čokoľvek, čo obsahuje `<`) alebo URL `https://`, ktorá sa najprv stiahne. Serverový kód musí byť v bloku `<script total>` alebo `<script node>`; bez neho dostaneš chybu \"Invalid component content\". Kód beží s `exports` (komponent) a `require` (`REQUIRE()`). Balíky v `exports.npm` sa nainštalujú, schémy vstupov a výstupov sa skompilujú a zavolá sa `exports.install()`. Bez callbacku vráti Promise.\n\nExample: Z priečinka components\n```js\nNEWCOMPONENT('uppercase', function(err, com) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar instance = com.create();\n});\n```\n\nExample: Inline\n```js\nvar html = '<script total>exports.make = function(instance) { instance.message = msg => msg.send(\\'output\\', msg.data * 2); };</script>';\nvar com = await NEWCOMPONENT(html);\n```\n\n### components/{name}.html\n\nType: `type`\n\nFormát serverového komponentu.\n\nHTML súbor s týmito časťami: `<script total>` alebo `<script node>` (serverový kód, povinný), `<settings>`, `<style>`, `<script>`, `<body>`, `<readme>`, `<schema>` a `<template>`. Serverový kód sa z výsledku odstráni; ostatné časti sú dostupné v `component.ui` (`settings`, `css`, `js`, `html`, `readme`, `schema`, `template`).\n\nExample: Kompletný súbor\n```html\n<script total>\n\n\texports.name = 'Counter';\n\texports.config = { step: 1 };\n\texports.inputs = [{ id: 'input', name: 'Value' }];\n\texports.outputs = [{ id: 'output', name: 'Sum' }];\n\n\texports.make = function(instance, config) {\n\t\tvar sum = 0;\n\t\tinstance.message = function(msg) {\n\t\t\tsum += config.step;\n\t\t\tmsg.send('output', sum);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nCounts incoming messages.\n</readme>\n\n<settings>\n<div>Step of the counter</div>\n</settings>\n```\n\n### Component\n\nType: `class`\n\nSkompilovaný serverový komponent.\n\nObjekt vrátený z `NEWCOMPONENT()`. Jeho vlastnosti pochádzajú z `exports` serverového kódu (`name`, `config`, `inputs`, `outputs`, `npm`, `make`, ...) a k nim `ui`, `instances`, `variables`, `secrets` a `debugger`.\n\n### exports.make = function(instance, config, status) {}\n\nType: `delegate`\n\nPripraví novú inštanciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | Nová inštancia |\n| `config` | `Object` | yes |  | Jej konfigurácia |\n| `status` | `Object` | yes |  | Druhý argument create() |\n\nVolá ho `component.create()` s inštanciou ako `this` a ako prvým argumentom. Tu priraď `instance.message` (a ďalšie handlery, napríklad `instance.close`, `instance.configure` alebo `instance.service`).\n\nExample: Handlery\n```js\nexports.make = function(instance, config) {\n\tinstance.message = function(msg) {\n\t\tmsg.send('output', msg.data);\n\t};\n\tinstance.configure = function() {\n\t\t// config has changed\n\t};\n};\n```\n\n### exports.config\n\nType: `property`\n\nPredvolená konfigurácia inštancií.\n\nReturns: `Object`\n\nKaždá inštancia dostane klon tohto objektu, rozšírený o voľby odovzdané do `component.create()`.\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nVstupy a výstupy komponentu.\n\nReturns: `Array`\n\nPolia `{ id, name, schema }`. `schema` (reťazec schémy, napríklad `'name:String, age:Number'`) sa skompiluje do JSON schémy. Pri vstupoch sa uplatní v `instance.input()`: vyčistené dáta nahradia `msg.data` a chyby sú v `msg.error`.\n\nExample: So schémou\n```js\nexports.inputs = [{ id: 'user', name: 'User', schema: 'name:String, email:Email' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n\nexports.make = function(instance) {\n\tinstance.message = function(msg) {\n\t\tif (msg.error)\n\t\t\tmsg.send('error', msg.error.toString());\n\t\telse\n\t\t\tmsg.send('ok', msg.data);\n\t};\n};\n```\n\n### exports.npm\n\nType: `property`\n\nNPM balíky, ktoré komponent potrebuje.\n\nReturns: `String[]`\n\nPole názvov balíkov (voliteľne `name@version`). `NEWCOMPONENT()` ich nainštaluje pomocou `NPMINSTALL()` pred spustením `install()`; ak sa niektorý nedá nainštalovať, kompilácia zlyhá s chybou npm.\n\nExample: Závislosti\n```js\nexports.npm = ['mqtt'];\n\nexports.make = function(instance, config) {\n\tvar mqtt = require('mqtt');\n\t// ...\n};\n```\n\n### exports.install = function(component) {}\n\nType: `delegate`\n\nZavolá sa raz po skompilovaní komponentu.\n\nBeží s komponentom ako `this` a ako argumentom, po nainštalovaní NPM balíkov a skompilovaní schém.\n\n### exports.onextend = function(instance) {}\n\nType: `delegate`\n\nRozšíri každú novú inštanciu pred make().\n\nVolá sa v `component.create()` po nastavení konfigurácie a pred `make()`.\n\n### exports.oncreate = function(instance) {}\n\nType: `delegate`\n\nZavolá sa po vytvorení inštancie.\n\nBeží asynchrónne (v `setImmediate`) po `make()`.\n\n### exports.onremove = function(instance) {}\n\nType: `delegate`\n\nZavolá sa pri odstránení inštancie.\n\nVolá ho `instance.remove()` po handleroch `close` a `destroy` inštancie.\n\n### component.ui\n\nType: `property`\n\nUI časti súboru komponentu.\n\nReturns: `Object`\n\nObjekt s `readme`, `settings`, `css`, `js`, `html`, `schema` a `template` (iba časti nájdené v súbore).\n\n### component.instances\n\nType: `property`\n\nVšetky inštancie komponentu.\n\nReturns: `Instance[]`\n\n`create()` inštanciu pridá a `instance.remove()` ju odstráni.\n\n### component.debugger\n\nType: `property`\n\nVypisuje do konzoly správy o stave, debug, chybách a výstupoch.\n\nReturns: `Boolean`\n\nPredvolene `true`. Nastav ho na `false`, ak chceš mať v konzole ticho, alebo nahraď `component.output`, `component.status`, `component.debug`, `component.throw` či `component.dashboard` vlastnými funkciami.\n\n### component.output = function(instance, msg) {}\n\nType: `delegate`\n\nPrijíma každú správu odoslanú na výstup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Instance` | yes |  | Odosielateľ |\n| `msg` | `Message` | yes |  | msg.output a msg.data |\n\nVolá sa pre každé `msg.send()` akejkoľvek inštancie. Predvolená implementácia vypíše výstup a dáta, keď je zapnutý `debugger`. Nahraď ju, ak chceš prepojiť inštancie alebo spracovať výsledky. `component.status(instance, value)`, `component.debug(instance, value)`, `component.throw(instance, err)` a `component.dashboard(instance, value)` prijímajú volania rovnomenných metód inštancie.\n\nExample: Zber výsledkov\n```js\nvar com = await NEWCOMPONENT('uppercase');\ncom.output = function(instance, msg) {\n\tconsole.log(instance.id, msg.output, msg.data);\n};\n```\n\n### component.create([options], [status])\n\nType: `method`\n\nVytvorí inštanciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Konfigurácia inštancie |\n| `status` | `Object` | no |  | Odovzdá sa do make() ako tretí argument |\n\nReturns: `Instance`\n\nInštancia dostane náhodné `id`, klon `component.config` rozšírený o `options` a pridá sa do `component.instances`. Potom sa zavolajú `onextend()`, `make()` a (asynchrónne) `oncreate()`.\n\nExample: Dve inštancie\n```js\nvar a = com.create({ prefix: 'A: ' });\nvar b = com.create({ prefix: 'B: ' });\n```\n\n### component.service(counter)\n\nType: `method`\n\nZavolá instance.service(counter) na všetkých inštanciách.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Ľubovoľná hodnota odovzdaná inštanciám |\n\nTotal.js ho za teba nevolá. Zavolaj ho z `ON('service')`, keď tvoje inštancie potrebujú pravidelný tik.\n\nExample: Každú minútu\n```js\nON('service', function(counter) {\n\tcom.service(counter);\n});\n```\n\n### Instance\n\nType: `class`\n\nInštancia serverového komponentu.\n\nVracia ju `component.create()`. Vlastnosti: `id`, `config`, `module` (komponent) a `cache` (prázdny objekt pre tvoje dáta). Handlery, ktoré môžeš priradiť v `make()`: `message`, `message_<input>`, `configure`, `close`, `destroy` a `service`.\n\n### instance.message = function(msg) {}\n\nType: `delegate`\n\nSpracuje dáta, ktoré prídu na vstup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Message` | yes |  | Prichádzajúca správa |\n\nVolá ho `instance.input()`. `msg.input` je id vstupu a `msg.data` dáta. Zavolá sa aj handler s názvom `instance.message_<input>`, po `message`. Bez `instance.message` sa vstup ignoruje.\n\nExample: Pre každý vstup\n```js\nexports.make = function(instance) {\n\tinstance.message = NOOP;\n\tinstance.message_reset = function(msg) {\n\t\t// only for input \"reset\"\n\t};\n};\n```\n\n### instance.input(input, data, [callback])\n\nType: `method`\n\nPošle dáta na vstup inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String` | yes |  | Id vstupu |\n| `data` | `Object` | yes |  | Dáta |\n| `callback` | `Function` | no |  | function(msg) |\n\nVytvorí správu, overí dáta schémou vstupu (ak existuje) a zavolá `instance.message(msg)` a `instance.message_<input>(msg)`. `callback` sa zavolá so správou zakaždým, keď sa pošle na výstup pomocou `msg.send()`.\n\nExample: Volanie a čítanie výsledku\n```js\ninstance.input('input', 'hello', function(msg) {\n\tconsole.log(msg.output, msg.data);\n});\n```\n\n### instance.send(output, data)\n\nType: `method` · Since: `0.0.17`\n\nPošle nové dáta na výstup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id výstupu |\n| `data` | `Object` | yes |  | Dáta |\n\nVytvorí novú správu s `data` a pošle ju na `output`; skončí v `instance.output(msg)` a teda v `component.output()`. Použi to pre dáta, ktoré inštancia vytvára sama (časovač, socket).\n\nExample: Časovač\n```js\nexports.make = function(instance) {\n\tvar timer = setInterval(() => instance.send('output', new Date()), 5000);\n\tinstance.close = () => clearInterval(timer);\n};\n```\n\n### instance.status(value) / debug(value) / throw(err) / dashboard(value)\n\nType: `method`\n\nOhlási stav inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Ľubovoľná hodnota |\n\nKaždá metóda zavolá rovnomennú metódu komponentu (`component.status(instance, value)` atď.). Predvolene vypisujú do konzoly, keď je zapnutý `component.debugger`.\n\nExample: Hlásenie\n```js\ninstance.status({ connected: true });\ninstance.throw(new Error('Connection refused'));\n```\n\n### instance.activity(key, name, value)\n\nType: `method` · Since: `0.0.19`\n\nNahlási aktivitu inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Identifikátor aktivity |\n| `name` | `String` | yes |  | Popis |\n| `value` | `Object` | yes |  | Napríklad priebeh |\n\nZavolá `component.activity(instance, { key, name, value })`, ktorá vypíše `ACTIVITY` do konzoly, keď je zapnutý `component.debugger`. Ak ju chceš spracovať, nahraď `component.activity`.\n\n### instance.reconfigure(options)\n\nType: `method`\n\nZmení konfiguráciu inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Nové hodnoty |\n\nSkopíruje kľúče z `options` do `instance.config` a zavolá `instance.configure(config)`, keď je definovaný.\n\nExample: Zmena hodnoty\n```js\ninstance.reconfigure({ prefix: '>> ' });\n```\n\n### instance.remove()\n\nType: `method`\n\nOdstráni inštanciu.\n\nZavolá `instance.close(true)` a `instance.destroy()`, keď sú definované, potom `component.onremove(instance)` a odstráni inštanciu z `component.instances`.\n\nExample: Odstránenie\n```js\ninstance.remove();\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nNahradí zástupné symboly {key} v reťazci.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String|Object` | yes |  | Šablóna |\n| `data` | `Object` | no |  | Hodnoty |\n| `encoding` | `String|Function` | no |  | Kódovanie hodnôt |\n\nReturns: `String|Object`\n\nKaždý `{key}` (alebo `{{key}}`) sa vezme z `component.variables`, potom z `component.secrets`, potom z `data` (fungujú aj vnorené kľúče s bodkami). Bez `data` sa použije samotná inštancia. `encoding` môže byť `'url'` (alebo `'urlencoded'`), `'json'`, `'querify'` alebo `function(value, key)`. Dátumy sa formátujú. Objekt ako `str` nahradí svoje reťazcové hodnoty. `msg.replace()` funguje rovnako.\n\nExample: URL\n```js\ncom.variables.api = 'https://api.example.com';\nvar url = instance.replace('{api}/users/{id}/', { id: 15 });\n```\n\n### Message\n\nType: `class`\n\nDáta, ktoré tečú cez inštanciu komponentu.\n\nVytvárajú ju `instance.input()` a `instance.send()`. Vlastnosti: `data`, `input`, `output`, `error` (ErrorBuilder, keď schéma vstupu zlyhala, `null`, keď prešla, `undefined` pre vstup bez schémy), `from` a `instance` (inštancia), `repo` a `vars` (prázdne objekty pre tvoje dáta).\n\n### msg.send(output, [data])\n\nType: `method`\n\nPošle správu na výstup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id výstupu |\n| `data` | `Object` | no |  | Nové dáta |\n\nNastaví `msg.output` a, keď je zadané `data`, aj `msg.data`. Potom zavolá callback z `instance.input()` a `instance.output(msg)`. Po `msg.end()` sa nič nestane.\n\nExample: Preposlanie\n```js\ninstance.message = function(msg) {\n\tmsg.send('output', { received: msg.data });\n};\n```\n\n### msg.end() / msg.destroy()\n\nType: `method`\n\nUvoľní správu.\n\nVymaže `data`, `vars`, `repo` a inštanciu, takže neskoršie volania `msg.send()` nerobia nič.\n\n### NPMINSTALL(name, [callback])\n\nType: `method`\n\nNainštaluje NPM balík.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov balíka, voliteľne s @version |\n| `callback` | `Function` | no |  | function(err) |\n\nReturns: `Promise` Keď nie je nastavený callback\n\nSpustí `npm install <name>` v `CONF.$nodemodules` (vytvorí sa, ak chýba). Keď priečinok balíka už obsahuje `package.json` (s rovnakou verziou pri `name@version`), nič sa neinštaluje. Keď proces beží ako používateľ 33 (www-data), ako npm cache sa použije `CONF.$npmcache`. Bez callbacku vráti Promise. Oba kľúče sú popísané v [Konfigurácia](../../guides/configuration/).\n\nExample: Inštalácia a načítanie\n```js\nNPMINSTALL('qrcode@1.5.4', function(err) {\n\tif (err) {\n\t\tconsole.error(err);\n\t\treturn;\n\t}\n\tvar QR = REQUIRE('qrcode');\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nNačíta Node.js alebo NPM modul.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov modulu |\n\nReturns: `Object` Modul\n\nNázvy s prefixom `node:` a vstavané moduly Node.js (`fs`, `path`, `crypto`, ...) sa načítajú priamo. Ostatné názvy sa načítajú pomocou `require()` a ak to zlyhá, z `CONF.$nodemodules`, takže sa nájdu aj balíky nainštalované pomocou `NPMINSTALL()`. Keď sa modul nedá načítať, vyhodí výnimku.\n\nExample: Načítanie\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nStiahne a načíta vzdialený JavaScript modul.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL súboru .js |\n| `callback` | `Function` | no |  | function(err, module, response) |\n\nReturns: `Promise` Keď nie je nastavený callback\n\nSúbor sa stiahne do dočasného priečinka a načíta pomocou require. Ďalšie volania s rovnakou URL v tom istom procese vrátia načítaný modul bez sťahovania. Odpoveď so stavom `400` alebo vyšším vráti chybu `The address answered with the status <status>` a nič sa nenačíta. Súbor, ktorý nie je platný modul, vráti chybu z `require()`, napríklad `SyntaxError`. Callback dostane `(err, module, response)`; bez neho sa Promise vyrieši s modulom.\n\nExample: Promise\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n","entries":[{"type":"type","name":"Plugin","signature":"plugins/{id}/index.js","since":"","deprecated":false},{"type":"delegate","name":"plugin.install()","signature":"exports.install = function() {}","since":"","deprecated":false},{"type":"property","name":"plugin.id","signature":"exports.id","since":"","deprecated":false},{"type":"property","name":"plugin.name","signature":"exports.name","since":"","deprecated":false},{"type":"property","name":"plugin.permissions","signature":"exports.permissions","since":"","deprecated":false},{"type":"property","name":"plugin.icon","signature":"exports.icon, exports.visible, exports.position, ...","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"config","name":"plugins/{id}/config","signature":"plugins/{id}/config","since":"0.0.16","deprecated":false},{"type":"type","name":"plugins/{id}/index.flow","signature":"plugins/{id}/index.flow","since":"0.0.19","deprecated":false},{"type":"property","name":"plugin.flowstream","signature":"PLUGINS[id].flowstream","since":"0.0.19","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([path])","since":"","deprecated":false},{"type":"type","name":"view('#plugin/...')","signature":"controller.view('#{id}/path')","since":"","deprecated":false},{"type":"method","name":"COMPONENTATOR()","signature":"COMPONENTATOR(name, components, [removeprev], [attrs])","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta) {})","since":"","deprecated":false},{"type":"method","name":"NEWCOMPONENT()","signature":"NEWCOMPONENT(html, [callback])","since":"","deprecated":false},{"type":"type","name":"Component file","signature":"components/{name}.html","since":"","deprecated":false},{"type":"class","name":"Component","signature":"Component","since":"","deprecated":false},{"type":"delegate","name":"component.make","signature":"exports.make = function(instance, config, status) {}","since":"","deprecated":false},{"type":"property","name":"component.config","signature":"exports.config","since":"","deprecated":false},{"type":"property","name":"component.inputs","signature":"exports.inputs / exports.outputs","since":"","deprecated":false},{"type":"property","name":"component.npm","signature":"exports.npm","since":"","deprecated":false},{"type":"delegate","name":"component.install","signature":"exports.install = function(component) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onextend","signature":"exports.onextend = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.oncreate","signature":"exports.oncreate = function(instance) {}","since":"","deprecated":false},{"type":"delegate","name":"component.onremove","signature":"exports.onremove = function(instance) {}","since":"","deprecated":false},{"type":"property","name":"component.ui","signature":"component.ui","since":"","deprecated":false},{"type":"property","name":"component.instances","signature":"component.instances","since":"","deprecated":false},{"type":"property","name":"component.debugger","signature":"component.debugger","since":"","deprecated":false},{"type":"delegate","name":"component.output()","signature":"component.output = function(instance, msg) {}","since":"","deprecated":false},{"type":"method","name":"component.create()","signature":"component.create([options], [status])","since":"","deprecated":false},{"type":"method","name":"component.service()","signature":"component.service(counter)","since":"","deprecated":false},{"type":"class","name":"Instance","signature":"Instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"instance.input()","signature":"instance.input(input, data, [callback])","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data)","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(value) / debug(value) / throw(err) / dashboard(value)","since":"","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, value)","since":"0.0.19","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(options)","since":"","deprecated":false},{"type":"method","name":"instance.remove()","signature":"instance.remove()","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"class","name":"Message","signature":"Message","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"msg.send(output, [data])","since":"","deprecated":false},{"type":"method","name":"message.end()","signature":"msg.end() / msg.destroy()","since":"","deprecated":false},{"type":"method","name":"NPMINSTALL()","signature":"NPMINSTALL(name, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwTf7Ix61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/flowstream/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"FlowStream","summary":"The Flow global, running FlowStreams, components, instances, messages and the flow5 command.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/flowstream/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# FlowStream\n\n> The Flow global, running FlowStreams, components, instances, messages and the flow5 command.\n\nMethods, properties and events of the `Flow` global, of a running FlowStream (`Flow.instances[id]`), of component definitions, component instances and messages, plus the `flow5` command. For an introduction with examples read the guide [FlowStream](../../guides/flowstream/).\n\n## API\n\n### Flow / FlowStream\n\nType: `class`\n\nThe global object of the FlowStream engine.\n\n`Flow` and `FlowStream` are the same object. It loads flows, keeps them in `Flow.instances` and emits the events `load`, `save` and `remove`. The running flows are objects described here as `flowstream`.\n\nExample: List running flows\n```js\nfor (var id in Flow.instances)\n\tconsole.log(id, Flow.instances[id].stats);\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nStarts a FlowStream from its schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | The FlowStream schema |\n| `callback` | `Function` | no |  | `function(err, flowstream)` |\n\nMissing keys get defaults: a random `id`, `name` = `id`, empty `components`, `design`, `sources` and `variables`. When a FlowStream with the same `id` is running, it is reloaded with the new schema instead. The callback runs when the components and the design are loaded. See [FlowStream](../../guides/flowstream/) for the keys of the schema.\n\nExample: Load a file\n```js\nvar schema = (await F.readfile(PATH.root('orders.json'), 'utf8')).parseJSON();\nFlow.load(schema, function(err, flowstream) {\n\terr && console.error(err);\n});\n```\n\nExample: Run in a worker thread\n```js\nFlow.load({ id: 'import', worker: 'worker', components: {}, design: {} });\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')` | Directory with .flow files |\n| `callback` | `Function` | no |  | Called when all files are loaded |\n\nReads every `*.flow` file (a JSON schema) of the directory and loads it with `Flow.load()`. Files with `-bk` or `_bk` in the name are skipped. The directory defaults to `/flowstreams/` in the app root. The framework calls it once at start, so you only need it for other directories. The `index.flow` file of a plugin is loaded with the plugin.\n\nExample: Another directory\n```js\nFlow.init(PATH.root('data/flows'), function() {\n\tconsole.log('Loaded:', Object.keys(Flow.instances));\n});\n```\n\n### Flow.reload(schema, [restart])\n\nType: `method`\n\nApplies a new schema to a running FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | The new schema |\n| `restart` | `Boolean` | no | `false` | Restart the worker |\n\nReturns: `Boolean` `true` when the FlowStream exists\n\nThe schema must have the `id` of a running FlowStream. The components and the design are replaced in place and removed components are unregistered. With `restart` (workers only) the worker is ended and started again with its current schema; the new schema is not applied. Returns `false` when no FlowStream has this id.\n\n### Flow.remove(id)\n\nType: `method`\n\nStops and removes a FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | FlowStream id |\n\nCloses all instances, ends the worker, removes the FlowStream from `Flow.instances` and emits `remove`.\n\nExample: Remove\n```js\nFlow.remove('orders');\n```\n\n### Flow.restart(id)\n\nType: `method`\n\nRestarts a FlowStream that runs in a worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | FlowStream id |\n\nReturns: `Boolean` `true` when found\n\nEnds the worker thread or the child process; it is started again automatically with the current schema after a second. Returns `true` when the FlowStream exists (otherwise `undefined`). A FlowStream in the main process is ended and not started again.\n\n### Flow.socket(id, websocket, [verify], [check])\n\nType: `method`\n\nConnects the Total.js Flow editor to a FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | FlowStream id |\n| `websocket` | `WebSocket` | yes |  | The WebSocket of the route |\n| `verify` | `Function` | no |  | `function(client, next)` |\n| `check` | `Function` | no |  | `function(client, message)` returns `true` or an error |\n\nPass the WebSocket object of a `SOCKET` route. `verify(client, next)` can accept a new client before it gets the flow (call `next()`), and `check(client, message)` can block single commands: return `true` to allow, or an error text. An unknown id closes the WebSocket.\n\nExample: Route for the editor\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', function($) {\n\t\t$.autodestroy();\n\t\tFlow.socket($.params.id, $, null, function(client, msg) {\n\t\t\treturn client.user.sa ? true : 'Only for admins';\n\t\t});\n\t});\n};\n```\n\n### Flow.notify($, id)\n\nType: `method`\n\nPasses an HTTP request to the notify delegate of an instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | The controller of the route |\n| `id` | `String` | yes |  | `flowid-instanceid` |\n\n`id` is `flowid-instanceid` (more `-` parts become `params`). The `notify` delegate of the instance gets `{ id, method, headers, query, body, url, ip, params }`, and the editor gets the same object. Then the response redirects to `?REDIRECT=url`, sends a small page that closes the window (for browsers) or a success JSON.\n\nExample: Routes\n```js\nROUTE('GET /notify/{id}/', $ => Flow.notify($, $.params.id));\nROUTE('POST /notify/{id}/ <1MB', $ => Flow.notify($, $.params.id));\n```\n\nExample: In a component\n```js\ninstance.notify = function(data) {\n\tinstance.send('output', data.body);\n};\n```\n\n### Flow.test(name, source, [config], init)\n\nType: `method`\n\nLoads one component in a test flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Component id |\n| `source` | `String` | yes |  | Source of the component |\n| `config` | `Object` | no | `{}` | Configuration of the instance |\n| `init` | `Function` | yes |  | `function(test)` |\n\nCreates a flow with the component (instance id `component`) and a helper instance connected to all its inputs and outputs. `init(test)` gets the `Test` object:\n\n| Member | Use |\n| --- | --- |\n| `test.send(input, data)` | Sends data to an input of the component (alias `input`) |\n| `test.message = function($, data)` | Receives what the component sends to its outputs |\n| `test.status = function(status)` | Receives the status of the component |\n| `test.debug = function(...)` | Receives `instance.debug()` calls |\n| `test.configure = function(config)` | Called after a reconfiguration |\n| `test.trigger(data)` | Runs the `trigger` delegate |\n| `test.reconfigure(config)` | Changes the configuration |\n| `test.variables(obj)` | Sets the variables |\n| `test.assert(ok, text)`, `test.ok(text)`, `test.fail(text)` | Print the result; `fail` throws |\n\nAn error in the flow ends the process.\n\nExample: Test\n```js\nvar source = await F.readfile(PATH.root('components/uppercase.html'), 'utf8');\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nThe running FlowStreams by id.\n\nReturns: `Object`\n\nAn object: FlowStream id → `flowstream` object. `Flow.db` holds the last schema of each FlowStream (updated on every save).\n\nExample: Get one\n```js\nvar flowstream = Flow.instances.orders;\n```\n\n### Flow.on('load', function(flowstream, schema) {})\n\nType: `event`\n\nA FlowStream is loaded.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | The running FlowStream |\n| `schema` | `Object` | yes |  | The schema |\n\nEmitted after `Flow.load()` has loaded the components and the design.\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nThe schema of a FlowStream has changed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | The whole schema |\n\nEmitted about 5 seconds after a change in the editor or a call of `instance.save()`. The schema contains `id`, `name`, `components`, `design`, `variables`, `sources`, `paused` and the other keys. Store it yourself, for example in a `.flow` file. Flows with `readonly: true` are not saved.\n\nExample: Save to a file\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### Flow.on('remove', function(schema) {})\n\nType: `event`\n\nA FlowStream was removed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | The schema |\n\nEmitted by `Flow.remove()` with the last schema of the removed FlowStream.\n\n### Flow.on('stats', function(id, stats) {})\n\nType: `event`\n\nCounters of a FlowStream that runs in a worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | FlowStream id |\n| `stats` | `Object` | yes |  | Counters |\n\nEmitted every 15 seconds for each FlowStream in a worker thread or child process. `stats` has `paused`, `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` and `pid`.\n\n### ON('flowstream', function(flowstream) {})\n\nType: `event` · Since: `0.0.16`\n\nA FlowStream has started.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | The running FlowStream |\n\nGlobal framework event emitted when a FlowStream is created, also after the automatic restart of a worker.\n\nExample: Log\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream', flowstream.id);\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nAn error occurred in a FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Error details |\n\nErrors are printed to the console and emitted as this global event. `meta` has `id` and `name` (of the FlowStream), `error`, `source`, `instanceid` and `componentid`.\n\nExample: Audit errors\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### { id, name, components, design, variables, ... }\n\nType: `type`\n\nThe object that describes a FlowStream.\n\n`components` maps a component id to its source code. `design` maps an instance id to `{ component, config, connections, x, y, note, tab }`; `connections` maps an output id to an array of `{ id, index }` (target instance and its input). Further keys: `variables`, `sources` (TMS), `worker`, `memory` (with `worker`: the heap limit of the worker thread or the child process in MB), `proxypath`, `cloning`, `paused`, `readonly`, `import`, `initscript`, `env`, `directory` and `asfiles` (`true` compiles the components into files in `/tmp/`). Descriptive keys like `icon`, `color`, `author`, `version` and `readme` are shown in the editor.\n\nExample: Two connected instances\n```json\n{\n\t\"id\": \"demo\",\n\t\"name\": \"Demo\",\n\t\"components\": { \"uppercase\": \"<script total>...</script>\", \"print\": \"<script total>...</script>\" },\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\": {}\n}\n```\n\n### schema.proxytimeout\n\nType: `config` · Since: `0.0.18`\n\nTimeout of the proxy of a worker with proxypath.\n\nReturns: `Number`\n\nMilliseconds for the timeout of the proxy that forwards requests under `proxypath` to the worker. It is applied when the schema is loaded again into the running FlowStream (`Flow.load()` with the same id or `Flow.reload()`).\n\nExample: Reload with a timeout\n```js\nFlow.reload({ id: 'api', worker: 'worker', proxypath: '/api/', proxytimeout: 10000, components: components, design: design });\n```\n\n### flowstream.stats\n\nType: `property`\n\nCounters of the FlowStream.\n\nReturns: `Object`\n\n`messages` (total), `pending`, `memory` (bytes), `minutes` (uptime), `errors` (the number of the last errors, at most 10), `mm` (messages in the last minute) and `paused`. For a flow in the main process, `online` is the number of connected editors. For a worker the values arrive every 15 seconds.\n\n### flowstream.trigger(id, [data])\n\nType: `method`\n\nRuns the trigger delegate of instances.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Instance id, `@componentid` or `#name` |\n| `data` | `Object` | no |  | Passed to the delegate |\n\nReturns: `Object` The flowstream\n\nCalls `instance.trigger(data)` of the instance `id`, of all instances of a component (`@componentid`) or of a component name (`#name`). Nothing runs while the flow is paused.\n\nExample: Start all timers\n```js\nFlow.instances.orders.trigger('@timer');\n```\n\n### flowstream.send(id, data, [callback])\n\nType: `method`\n\nSends data into an instance and waits for the result.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Target, optionally with `/input` |\n| `data` | `Object` | yes |  | Payload |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nCreates a new message with `data` and passes it to the `message` delegate of the instance (`id`, `@componentid` or `#name`; the first match). Add `/inputid` to set `$.input`. The callback runs when the message and all its clones are ended, with `{ error, repo, data, count, cloned, duration, meta: { id, component } }`.\n\nExample: Call a flow from an API\n```js\nNEWACTION('Orders/process', {\n\taction: function($, model) {\n\t\tFlow.instances.orders.send('@order/input', model, function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback(response.data);\n\t\t});\n\t}\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nSends a message to all matching instances.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Options |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nLike `send()`, but for every matching instance. `opt.id` is the target (`id`, `@componentid` or `#name`), `opt.data` the payload, `opt.vars` and `opt.repo` the `$.vars` and `$.repo`, `opt.timeout` a timeout in ms (the message ends with error `408`). `opt.uid` and `opt.ref` come back in the response. The callback runs for each target (for a flow in a worker only for the first one), or with `404` when nothing matches.\n\nExample: Exec with a timeout\n```js\nFlow.instances.orders.exec({ id: '#Validate', data: model, timeout: 5000, uid: model.id }, function(err, response) {\n\tconsole.log(response.uid, response.data);\n});\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: `Object` The flowstream\n\nA paused flow does not deliver messages. Without the argument the state is toggled. The `pause` delegate of each instance is called.\n\n### flowstream.variables(obj)\n\nType: `method`\n\nReplaces the variables of the FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | New variables |\n\nReturns: `Object` The flowstream\n\nCalls the `variables` delegate of each instance (and `vary('variables')` for a flow in the main process), sends the variables to the editor and saves the flow.\n\nExample: Rotate a token\n```js\nFlow.instances.orders.variables({ token: newtoken });\n```\n\n### flowstream.reconfigure(id, config)\n\nType: `method`\n\nChanges the configuration of an instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Instance id |\n| `config` | `Object` | yes |  | Values to merge |\n\nReturns: `Object` The flowstream\n\nThe values are merged into `instance.config`, the `configure` delegate is called, the editor is updated and the flow is saved.\n\n### flowstream.export(callback)\n\nType: `method`\n\nReads the current schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)` |\n\nThe callback gets the whole schema, the same object as the `save` event.\n\nExample: Backup\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('backup.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.restart()\n\nType: `method`\n\nRestarts a FlowStream that runs in a worker.\n\nCloses the editor connections and ends the worker; it starts again automatically with the current schema.\n\n### flowstream.remove()\n\nType: `method`\n\nRemoves the FlowStream.\n\nThe same as `Flow.remove(flowstream.id)`.\n\n### flowstream.edit([url])\n\nType: `method` · Since: `0.0.16`\n\nConnects the FlowStream to a remote editing proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `'wss://flow.totaljs.com/{0}/'` | Proxy WebSocket URL |\n\nReturns: `WebSocketClient` The client\n\nOpens a WebSocket client to the URL (`{0}` is replaced by the FlowStream id) and lets the editor work through it, so the application does not need a public WebSocket route. A previous connection is closed. Returns the WebSocket client.\n\nExample: Remote editing\n```js\nFlow.instances.orders.edit();\n```\n\n### exports.* in <script total>\n\nType: `type`\n\nThe definition of a FlowStream component.\n\nThe server part of the component sets properties of `exports`:\n\n| Property | Meaning |\n| --- | --- |\n| `name`, `icon`, `color`, `group`, `version`, `author` | Shown in the editor |\n| `type` | For example `input`, `output` or `config`; these appear in `io()` listings |\n| `inputs`, `outputs` | Arrays of `{ id, name }` |\n| `config` | Default configuration of new instances |\n| `npm` | NPM packages installed before registering |\n| `permissions`, `meta` | Custom data passed to the editor |\n| `make` | `function(instance, config)` for each instance |\n| `install`, `uninstall` | `function(component)` when the component is registered and removed |\n| `call` | `function(data, callback)` called by the editor with `@componentid` |\n\nThe other parts of the file: `<settings>` (the configuration form), `<body>`, `<style>`, `<script>` (editor code), `<readme>`, `<template>` and `<schema>`.\n\nExample: Minimal component\n```html\n<script total>\n\texports.name = 'Print';\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.make = function(instance) {\n\t\tinstance.message = function($) {\n\t\t\tconsole.log($.data);\n\t\t\t$.end();\n\t\t};\n\t};\n</script>\n```\n\n### exports.make = function(instance, config) {}\n\nType: `method`\n\nCreates an instance of the component.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | The instance |\n| `config` | `Object` | yes |  | Its configuration |\n\nRuns for each instance placed on the canvas, and again when the component code changes. `config` is `instance.config`. Assign the delegates of the instance here.\n\nExample: Interval\n```js\nexports.make = function(instance, config) {\n\tvar timer;\n\tinstance.configure = function() {\n\t\tclearInterval(timer);\n\t\ttimer = setInterval(() => instance.send('output', { ts: NOW }), (instance.config.interval || 10) * 1000);\n\t};\n\tinstance.close = () => clearInterval(timer);\n\tinstance.configure();\n};\n```\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nThe inputs and outputs of a component.\n\nReturns: `Array`\n\nArrays of `{ id, name }`. The `id` is what `$.input` contains and what `$.send(id)` and `instance.send(id)` use. An instance can override them with its own `inputs` / `outputs`.\n\nExample: Two outputs\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'OK' }, { id: 'error', name: 'Error' }];\n```\n\n### instance\n\nType: `type`\n\nOne placed instance of a component.\n\nThe first argument of `exports.make()`. Properties: `id`, `component` (component id), `config`, `cache`, `main` (the flow engine), `module` (the component), `env`, `stats` (`pending`, `input`, `output`, `duration`, `destroyed`), `instances` (all instances of the flow) and `components`.\n\nDelegates you can assign: `message($)`, `message_INPUTID($)`, `configure(config)`, `close()`, `init()` (after the first load), `refresh()` (after each change of the design), `trigger(data)`, `notify(data)`, `call(data, callback)`, `service(minutes)` (every minute), `pause(is)`, `variables(obj)`, `secrets(obj)` and `vary(type)`.\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nReceives a message on an input.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | The message |\n\n`$.input` is the input id. `instance.message_INPUTID` receives messages of one input only; when both exist, both are called. A message that is not sent further must be ended with `$.end()`.\n\nExample: Route by input\n```js\ninstance.message = function($) {\n\tif ($.input === 'reset') {\n\t\tcount = 0;\n\t\t$.end();\n\t} else {\n\t\tcount++;\n\t\t$.send('output', { count: count });\n\t}\n};\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nThe configuration has changed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | The configuration |\n\nCalled after a change in the editor or a call of `reconfigure()`. `instance.config` already contains the new values.\n\n### instance.close = function() {}\n\nType: `delegate`\n\nThe instance is being removed.\n\nCalled when the instance is removed from the design, the component is unregistered or the flow ends. Clear timers and close connections here.\n\n### instance.send(output, [data])\n\nType: `method`\n\nStarts a new message from an output or from all outputs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Output id, or `null` for all outputs |\n| `data` | `Object` | no |  | Payload |\n\nReturns: `Number` Count of sent messages\n\nSends `data` to every instance connected to the output. With `output` `null` it sends to all outputs. For the second and next connection the data are cloned (unless `cloning: false`). Returns the number of sent messages; `0` when nothing is connected or the flow is paused.\n\nExample: From a timer\n```js\nsetInterval(() => instance.send('output', { ts: NOW }), 1000);\n```\n\nExample: All outputs\n```js\ninstance.send(null, { ts: NOW });\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nCreates a message without sending it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Payload |\n\nReturns: `Message` A new message\n\nThe message belongs to the instance; set `$.repo`, listen to `end` and then call `$.send(output)`.\n\nExample: Wait for the end\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.on('end', function($) {\n\tconsole.log('Done', $.data);\n});\nmsg.send('output');\n```\n\n### instance.status([data], [delay])\n\nType: `method`\n\nSets the status shown under the instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Any JSON value |\n| `delay` | `Number` | no |  | Throttle in ms |\n\nThe status is sent to the editor and emitted as `status` on `instance.main`. With `delay` (ms) many calls are merged into one update. Without arguments the last status is sent again.\n\nExample: Counter\n```js\ninstance.status({ count: count }, 1000);\n```\n\n### instance.dashboard([data])\n\nType: `method`\n\nSends data to the dashboard of the editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Any JSON value |\n\nThe data are kept and sent to the editor; without arguments the last data are sent again.\n\n### instance.throw(error)\n\nType: `method`\n\nReports an error of the instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | The error |\n\nThe error is added to the last 10 errors of the flow (`instance.main.errors`), shown in the editor, printed to the console and emitted as `ON('flowstream_error')`. `$.throw(error)` does the same and sets `$.error`.\n\nExample: In a callback\n```js\nRESTBuilder.GET(config.url).callback(function(err, response) {\n\tif (err) {\n\t\tinstance.throw(err);\n\t\t$.end();\n\t} else\n\t\t$.send('output', response);\n});\n```\n\n### instance.debug(a, [b], [c], [d])\n\nType: `method`\n\nEmits a debug event.\n\nEmits `debug` on `instance.main` with the instance and the arguments. `Flow.test()` passes it to `test.debug`.\n\n### instance.save([redraw])\n\nType: `method`\n\nSaves the instance after a change from code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `redraw` | `Boolean` | no | `true` | Redraw the instance in the editor |\n\nUse it after you change `instance.config`, `x`, `y`, `note`, `inputs` or `outputs` in the code. The flow is saved (the `save` event follows after about 5 seconds) and, unless `redraw` is `false`, the editor redraws the instance.\n\nExample: Remember a value\n```js\ninstance.config.lastid = $.data.id;\ninstance.save();\n```\n\nExample: Without redraw\n```js\ninstance.config.counter++;\ninstance.save(false);\n```\n\n### instance.reconfigure(config)\n\nType: `method`\n\nChanges the configuration of this instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Values to merge |\n\nThe same as `flowstream.reconfigure(instance.id, config)` called from the component.\n\n### instance.replace(text, [data], [encoding])\n\nType: `method`\n\nReplaces {variables} in a text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String|Object` | yes |  | Text with placeholders |\n| `data` | `Object` | no |  | Extra values |\n| `encoding` | `String|Function` | no |  | Encoding of the values |\n\nReturns: `String` The text\n\nA `{name}` (or `{{name}}`) takes the value from the variables of the flow, the global variables, the secrets, `{hostname}` (origin plus `proxypath`) or the `data` object (nested keys with dots). `encoding` can be `url`, `json`, `querify` or a `function(value, key)`. An object replaces each string value. In a message use `$.variables()` (alias `$.replace()`), where `data` defaults to the message.\n\nExample: URL\n```js\nvar url = instance.replace('https://api.example.com/{token}/orders/?id={id}', { id: 5 }, 'url');\n```\n\n### instance.cache\n\nType: `property`\n\nAn in-memory object for runtime data of the instance.\n\nReturns: `Object`\n\nA plain object in memory, kept by the flow for the instance id: when the instance is initialized again (for example when its component is updated), it gets the same object back. It is not saved, so it is empty after a restart.\n\nExample: Last value\n```js\ninstance.message = function($) {\n\tinstance.cache.last = $.data;\n\t$.send('output');\n};\n```\n\n### instance.repo\n\nType: `property` · Since: `0.0.17`\n\nPersistent data of the instance stored in the design.\n\nReturns: `Object`\n\nAn object saved in the schema together with the instance. It survives a reload and a restart, and the editor keeps it unchanged when it saves the design. Call `instance.save()` after a change.\n\nExample: Keep a cursor\n```js\ninstance.repo.lastid = $.data.id;\ninstance.save();\n```\n\n### instance.activity(key, name, [progress])\n\nType: `method` · Since: `0.0.19`\n\nReports a running activity of the instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Activity id |\n| `name` | `String` | yes |  | Description |\n| `progress` | `Number` | no |  | Percent |\n\nCreates or updates the activity `key`, shows it in the editor and emits `activity` on `instance.main` with `(instance, key, name, progress)`. An empty `name` or `progress` `100` removes it. Activities of instances removed from the design are dropped.\n\nExample: Progress\n```js\ninstance.activity('sync', 'Synchronizing', 40);\n// ...\ninstance.activity('sync', 'Synchronizing', 100);\n```\n\n### instance.main\n\nType: `property`\n\nThe flow engine of the instance.\n\nReturns: `FlowStream`\n\nUseful members: `variables`, `secrets`, `stats` (with `online`, the number of connected editors), `errors`, `paused`, `env`, `activities`, `find(id)` (an instance), `instances()` (ready instances), `send('ID__OUTPUT', data)`, `trigger('ID__INPUT', data)` (sends a new message to an input), `pause(is)`, `save()` and `restart()` (restarts the worker of the flow; in the main process it asks the Total.js process manager to restart the application). It emits `status`, `debug`, `activity`, `message`, `end` and `reset` events.\n\nExample: Send to another instance\n```js\ninstance.main.trigger('b1__input', { id: 1 });\n```\n\n### instance.main.on('reset', function() {})\n\nType: `event`\n\nThe errors of the flow were reset.\n\nEmitted by the flow engine when the editor sends the reset command: the last errors of the flow (`instance.main.errors`) are cleared first, then the event runs without arguments. In a flow that runs in a worker it is emitted inside the worker. The engine stays when an instance is created again, so remove the listener in `instance.close`.\n\nExample: Reset a counter\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\n### $\n\nType: `class`\n\nA message travelling through the flow.\n\nProperties: `data`, `repo` (shared by all clones), `vars`, `input`, `output`, `from`/`fromid`, `to`/`toid` (instances), `instance`, `main`, `id`, `count`, `duration`, `error`, `controller`, and from the controller `user`, `body`, `query`, `params`, `headers`, `ip`, `language`.\n\nMethods: `send()`, `end()` (alias `destroy()`), `rewrite(data)`, `clone()`, `variables()`, `timeout()`, `status()`, `dashboard()`, `debug()`, `throw()` and `on(name, fn)`. Events: `end` (the message and all clones are ended), `timeout` and `message`.\n\n### $.send(output, [data], [clone], [check])\n\nType: `method`\n\nSends the message to an output or to all outputs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Output id, or `null` for all outputs |\n| `data` | `Object` | no |  | New payload |\n| `clone` | `Boolean` | no | `the `cloning` of the flow` | Clone the data |\n| `check` | `Function` | no |  | `function(from, to, output, input)` returns a Boolean |\n\nReturns: `Number` Count of targets\n\nSends a clone of the message to every instance connected to the output. With `output` `null` it sends to all outputs: an output without a ready target is skipped, the other outputs still get the message, and the message ends once, when all its clones end. `data` replaces the payload; `clone` (default: the `cloning` of the flow) deep-copies object data for each target. `check(from, to, output, input)` is called for each target of a named output (`from` and `to` are instances); return `false` to skip the target. Returns the number of targets; with `0` the message ends.\n\nExample: Pass on\n```js\ninstance.message = function($) {\n\t$.data.checked = true;\n\t$.send('output');\n};\n```\n\nExample: Skip some targets\n```js\n$.send('output', null, null, function(from, to, output, input) {\n\treturn to.component !== 'debug';\n});\n```\n\nExample: All outputs\n```js\ninstance.message = function($) {\n\t$.send(null);\n};\n```\n\n### $.end()\n\nType: `method`\n\nEnds the message.\n\nCall it when the message is not sent further. When the message and all its clones are ended, its `end` event fires (and the `callback` of `flowstream.send()`).\n\nExample: Stop here\n```js\ninstance.message = function($) {\n\tsave($.data);\n\t$.end();\n};\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nSets a timeout for the next instances.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function($)` |\n| `time` | `Number` | yes |  | Milliseconds |\n\nReturns: `Message`\n\nEach clone sent after this call must be processed within `time` ms; otherwise it ends with `$.error = 408` and the callback runs. `$.totaltimeout([callback], time)` limits the whole message instead.\n\nExample: Timeout\n```js\n$.timeout(function($) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n\n### flow5 [path or URL ...] [port]\n\nType: `command`\n\nRuns FlowStream schemas from the command line.\n\nLoads each JSON file (one schema, or an object with several schemas) or HTTPS URL, starts an HTTP server on the port (default `8000`) with the route `SOCKET /flowstreams/{id}/` and the `/notify/{id}/` routes, and prints the editor link for each flow. Changes from the editor are written back to the local files. Without arguments it prints help.\n\nExample: Two flows on port 8001\n```bash\nflow5 orders.json import.json 8001\n```\n","entries":[{"type":"class","name":"Flow","signature":"Flow / FlowStream","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":"method","name":"Flow.reload()","signature":"Flow.reload(schema, [restart])","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.restart()","signature":"Flow.restart(id)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [verify], [check])","since":"","deprecated":false},{"type":"method","name":"Flow.notify()","signature":"Flow.notify($, id)","since":"","deprecated":false},{"type":"method","name":"Flow.test()","signature":"Flow.test(name, source, [config], init)","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(flowstream, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('remove')","signature":"Flow.on('remove', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('stats')","signature":"Flow.on('stats', function(id, stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(flowstream) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"type","name":"FlowStream schema","signature":"{ id, name, components, design, variables, ... }","since":"","deprecated":false},{"type":"config","name":"proxytimeout","signature":"schema.proxytimeout","since":"0.0.18","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, [data])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(id, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(obj)","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.restart()","signature":"flowstream.restart()","since":"","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"flowstream.edit()","signature":"flowstream.edit([url])","since":"0.0.16","deprecated":false},{"type":"type","name":"Component","signature":"exports.* in <script total>","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 / exports.outputs","since":"","deprecated":false},{"type":"type","name":"instance","signature":"instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","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() {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, [data])","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(error)","since":"","deprecated":false},{"type":"method","name":"instance.debug()","signature":"instance.debug(a, [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save([redraw])","since":"","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(config)","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(text, [data], [encoding])","since":"","deprecated":false},{"type":"property","name":"instance.cache","signature":"instance.cache","since":"","deprecated":false},{"type":"property","name":"instance.repo","signature":"instance.repo","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, [progress])","since":"0.0.19","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"event","name":"instance.main.on('reset')","signature":"instance.main.on('reset', function() {})","since":"","deprecated":false},{"type":"class","name":"Message","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send(output, [data], [clone], [check])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end()","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5 [path or URL ...] [port]","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwTf7Ix61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/flowstream/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"FlowStream","summary":"Das globale Flow, laufende FlowStreams, Komponenten, Instanzen, Nachrichten und der Befehl flow5.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/flowstream/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# FlowStream\n\n> Das globale Flow, laufende FlowStreams, Komponenten, Instanzen, Nachrichten und der Befehl flow5.\n\nMethoden, Eigenschaften und Events des globalen `Flow`, eines laufenden FlowStreams (`Flow.instances[id]`), von Komponentendefinitionen, Komponenteninstanzen und Nachrichten sowie der Befehl `flow5`. Eine Einführung mit Beispielen findest du in der Anleitung [FlowStream](../../guides/flowstream/).\n\n## API\n\n### Flow / FlowStream\n\nType: `class`\n\nDas globale Objekt der FlowStream-Engine.\n\n`Flow` und `FlowStream` sind dasselbe Objekt. Es lädt Flows, hält sie in `Flow.instances` und löst die Events `load`, `save` und `remove` aus. Die laufenden Flows sind Objekte, die hier als `flowstream` beschrieben werden.\n\nExample: Laufende Flows auflisten\n```js\nfor (var id in Flow.instances)\n\tconsole.log(id, Flow.instances[id].stats);\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nStartet einen FlowStream aus seinem Schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Das FlowStream-Schema |\n| `callback` | `Function` | no |  | `function(err, flowstream)` |\n\nFehlende Schlüssel erhalten Standardwerte: eine zufällige `id`, `name` = `id`, leere `components`, `design`, `sources` und `variables`. Läuft bereits ein FlowStream mit derselben `id`, wird er stattdessen mit dem neuen Schema neu geladen. Der Callback läuft, wenn die Komponenten und das Design geladen sind. Siehe [FlowStream](../../guides/flowstream/) für die Schlüssel des Schemas.\n\nExample: Eine Datei laden\n```js\nvar schema = (await F.readfile(PATH.root('orders.json'), 'utf8')).parseJSON();\nFlow.load(schema, function(err, flowstream) {\n\terr && console.error(err);\n});\n```\n\nExample: In einem Worker-Thread ausführen\n```js\nFlow.load({ id: 'import', worker: 'worker', components: {}, design: {} });\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')` | Verzeichnis mit .flow-Dateien |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn alle Dateien geladen sind |\n\nLiest jede Datei `*.flow` (ein JSON-Schema) des Verzeichnisses und lädt sie mit `Flow.load()`. Dateien mit `-bk` oder `_bk` im Namen werden übersprungen. Das Verzeichnis ist standardmäßig `/flowstreams/` im Stammverzeichnis der Anwendung. Das Framework ruft es beim Start einmal auf, daher brauchst du es nur für andere Verzeichnisse. Die Datei `index.flow` eines Plugins wird mit dem Plugin geladen.\n\nExample: Ein anderes Verzeichnis\n```js\nFlow.init(PATH.root('data/flows'), function() {\n\tconsole.log('Loaded:', Object.keys(Flow.instances));\n});\n```\n\n### Flow.reload(schema, [restart])\n\nType: `method`\n\nWendet ein neues Schema auf einen laufenden FlowStream an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Das neue Schema |\n| `restart` | `Boolean` | no | `false` | Den Worker neu starten |\n\nReturns: `Boolean` `true`, wenn der FlowStream existiert\n\nDas Schema muss die `id` eines laufenden FlowStreams haben. Die Komponenten und das Design werden an Ort und Stelle ersetzt, und entfernte Komponenten werden abgemeldet. Mit `restart` (nur Worker) wird der Worker beendet und mit seinem aktuellen Schema neu gestartet; das neue Schema wird nicht angewendet. Gibt `false` zurück, wenn kein FlowStream diese ID hat.\n\n### Flow.remove(id)\n\nType: `method`\n\nStoppt und entfernt einen FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | FlowStream-ID |\n\nSchließt alle Instanzen, beendet den Worker, entfernt den FlowStream aus `Flow.instances` und löst `remove` aus.\n\nExample: Entfernen\n```js\nFlow.remove('orders');\n```\n\n### Flow.restart(id)\n\nType: `method`\n\nStartet einen FlowStream neu, der in einem Worker läuft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | FlowStream-ID |\n\nReturns: `Boolean` `true`, wenn gefunden\n\nBeendet den Worker-Thread oder den Kindprozess; er wird nach einer Sekunde automatisch mit dem aktuellen Schema neu gestartet. Gibt `true` zurück, wenn der FlowStream existiert (sonst `undefined`). Ein FlowStream im Hauptprozess wird beendet und nicht neu gestartet.\n\n### Flow.socket(id, websocket, [verify], [check])\n\nType: `method`\n\nVerbindet den Editor Total.js Flow mit einem FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | FlowStream-ID |\n| `websocket` | `WebSocket` | yes |  | Der WebSocket der Route |\n| `verify` | `Function` | no |  | `function(client, next)` |\n| `check` | `Function` | no |  | `function(client, message)` gibt `true` oder einen Fehler zurück |\n\nÜbergib das WebSocket-Objekt einer `SOCKET`-Route. `verify(client, next)` kann einen neuen Client akzeptieren, bevor er den Flow erhält (rufe `next()` auf), und `check(client, message)` kann einzelne Befehle blockieren: Gib `true` zum Erlauben zurück oder einen Fehlertext. Eine unbekannte ID schließt den WebSocket.\n\nExample: Route für den Editor\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', function($) {\n\t\t$.autodestroy();\n\t\tFlow.socket($.params.id, $, null, function(client, msg) {\n\t\t\treturn client.user.sa ? true : 'Only for admins';\n\t\t});\n\t});\n};\n```\n\n### Flow.notify($, id)\n\nType: `method`\n\nÜbergibt eine HTTP-Anfrage an den Delegate notify einer Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | Der Controller der Route |\n| `id` | `String` | yes |  | `flowid-instanceid` |\n\n`id` ist `flowid-instanceid` (weitere `-`-Teile werden zu `params`). Der Delegate `notify` der Instanz erhält `{ id, method, headers, query, body, url, ip, params }`, und der Editor erhält dasselbe Objekt. Dann leitet die Antwort auf `?REDIRECT=url` weiter, sendet eine kleine Seite, die das Fenster schließt (für Browser), oder ein Erfolgs-JSON.\n\nExample: Routes\n```js\nROUTE('GET /notify/{id}/', $ => Flow.notify($, $.params.id));\nROUTE('POST /notify/{id}/ <1MB', $ => Flow.notify($, $.params.id));\n```\n\nExample: In einer Komponente\n```js\ninstance.notify = function(data) {\n\tinstance.send('output', data.body);\n};\n```\n\n### Flow.test(name, source, [config], init)\n\nType: `method`\n\nLädt eine Komponente in einen Test-Flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Komponenten-ID |\n| `source` | `String` | yes |  | Quellcode der Komponente |\n| `config` | `Object` | no | `{}` | Konfiguration der Instanz |\n| `init` | `Function` | yes |  | `function(test)` |\n\nErstellt einen Flow mit der Komponente (Instanz-ID `component`) und einer Hilfsinstanz, die mit all ihren Ein- und Ausgängen verbunden ist. `init(test)` erhält das `Test`-Objekt:\n\n| Member | Verwendung |\n| --- | --- |\n| `test.send(input, data)` | Sendet Daten an einen Eingang der Komponente (Alias `input`) |\n| `test.message = function($, data)` | Empfängt, was die Komponente an ihre Ausgänge sendet |\n| `test.status = function(status)` | Empfängt den Status der Komponente |\n| `test.debug = function(...)` | Empfängt Aufrufe von `instance.debug()` |\n| `test.configure = function(config)` | Wird nach einer Neukonfiguration aufgerufen |\n| `test.trigger(data)` | Führt den Delegate `trigger` aus |\n| `test.reconfigure(config)` | Ändert die Konfiguration |\n| `test.variables(obj)` | Setzt die Variablen |\n| `test.assert(ok, text)`, `test.ok(text)`, `test.fail(text)` | Geben das Ergebnis aus; `fail` wirft einen Fehler |\n\nEin Fehler im Flow beendet den Prozess.\n\nExample: Test\n```js\nvar source = await F.readfile(PATH.root('components/uppercase.html'), 'utf8');\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nDie laufenden FlowStreams nach ID.\n\nReturns: `Object`\n\nEin Objekt: FlowStream-ID → `flowstream`-Objekt. `Flow.db` enthält das letzte Schema jedes FlowStreams (wird bei jedem Speichern aktualisiert).\n\nExample: Einen abrufen\n```js\nvar flowstream = Flow.instances.orders;\n```\n\n### Flow.on('load', function(flowstream, schema) {})\n\nType: `event`\n\nEin FlowStream ist geladen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | Der laufende FlowStream |\n| `schema` | `Object` | yes |  | Das Schema |\n\nWird ausgelöst, nachdem `Flow.load()` die Komponenten und das Design geladen hat.\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nDas Schema eines FlowStreams hat sich geändert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Das gesamte Schema |\n\nWird etwa 5 Sekunden nach einer Änderung im Editor oder einem Aufruf von `instance.save()` ausgelöst. Das Schema enthält `id`, `name`, `components`, `design`, `variables`, `sources`, `paused` und die anderen Schlüssel. Speichere es selbst, zum Beispiel in einer `.flow`-Datei. Flows mit `readonly: true` werden nicht gespeichert.\n\nExample: In eine Datei speichern\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### Flow.on('remove', function(schema) {})\n\nType: `event`\n\nEin FlowStream wurde entfernt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Das Schema |\n\nWird von `Flow.remove()` mit dem letzten Schema des entfernten FlowStreams ausgelöst.\n\n### Flow.on('stats', function(id, stats) {})\n\nType: `event`\n\nZähler eines FlowStreams, der in einem Worker läuft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | FlowStream-ID |\n| `stats` | `Object` | yes |  | Zähler |\n\nWird alle 15 Sekunden für jeden FlowStream in einem Worker-Thread oder Kindprozess ausgelöst. `stats` hat `paused`, `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` und `pid`.\n\n### ON('flowstream', function(flowstream) {})\n\nType: `event` · Since: `0.0.16`\n\nEin FlowStream wurde gestartet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | Der laufende FlowStream |\n\nGlobales Framework-Event, das ausgelöst wird, wenn ein FlowStream erstellt wird, auch nach dem automatischen Neustart eines Workers.\n\nExample: Protokollieren\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream', flowstream.id);\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nIn einem FlowStream ist ein Fehler aufgetreten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Fehlerdetails |\n\nFehler werden in der Konsole ausgegeben und als dieses globale Event ausgelöst. `meta` hat `id` und `name` (des FlowStreams), `error`, `source`, `instanceid` und `componentid`.\n\nExample: Fehler protokollieren\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### { id, name, components, design, variables, ... }\n\nType: `type`\n\nDas Objekt, das einen FlowStream beschreibt.\n\n`components` ordnet einer Komponenten-ID ihren Quellcode zu. `design` ordnet einer Instanz-ID `{ component, config, connections, x, y, note, tab }` zu; `connections` ordnet einer Ausgangs-ID ein Array von `{ id, index }` zu (Zielinstanz und ihr Eingang). Weitere Schlüssel: `variables`, `sources` (TMS), `worker`, `memory` (mit `worker`: das Heap-Limit des Worker-Threads oder des Kindprozesses in MB), `proxypath`, `cloning`, `paused`, `readonly`, `import`, `initscript`, `env`, `directory` und `asfiles` (`true` kompiliert die Komponenten in Dateien in `/tmp/`). Beschreibende Schlüssel wie `icon`, `color`, `author`, `version` und `readme` werden im Editor angezeigt.\n\nExample: Zwei verbundene Instanzen\n```json\n{\n\t\"id\": \"demo\",\n\t\"name\": \"Demo\",\n\t\"components\": { \"uppercase\": \"<script total>...</script>\", \"print\": \"<script total>...</script>\" },\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\": {}\n}\n```\n\n### schema.proxytimeout\n\nType: `config` · Since: `0.0.18`\n\nTimeout des Proxys eines Workers mit proxypath.\n\nReturns: `Number`\n\nMillisekunden für den Timeout des Proxys, der Anfragen unter `proxypath` an den Worker weiterleitet. Er wird angewendet, wenn das Schema erneut in den laufenden FlowStream geladen wird (`Flow.load()` mit derselben id oder `Flow.reload()`).\n\nExample: Mit einem Timeout neu laden\n```js\nFlow.reload({ id: 'api', worker: 'worker', proxypath: '/api/', proxytimeout: 10000, components: components, design: design });\n```\n\n### flowstream.stats\n\nType: `property`\n\nZähler des FlowStreams.\n\nReturns: `Object`\n\n`messages` (insgesamt), `pending`, `memory` (Bytes), `minutes` (Laufzeit), `errors` (die Anzahl der letzten Fehler, höchstens 10), `mm` (Nachrichten in der letzten Minute) und `paused`. Bei einem Flow im Hauptprozess ist `online` die Anzahl der verbundenen Editoren. Bei einem Worker kommen die Werte alle 15 Sekunden an.\n\n### flowstream.trigger(id, [data])\n\nType: `method`\n\nFührt den Delegate trigger von Instanzen aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Instanz-ID, `@componentid` oder `#name` |\n| `data` | `Object` | no |  | Wird an den Delegate übergeben |\n\nReturns: `Object` Der flowstream\n\nRuft `instance.trigger(data)` der Instanz `id`, aller Instanzen einer Komponente (`@componentid`) oder eines Komponentennamens (`#name`) auf. Solange der Flow pausiert ist, läuft nichts.\n\nExample: Alle Timer starten\n```js\nFlow.instances.orders.trigger('@timer');\n```\n\n### flowstream.send(id, data, [callback])\n\nType: `method`\n\nSendet Daten in eine Instanz und wartet auf das Ergebnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Ziel, optional mit `/input` |\n| `data` | `Object` | yes |  | Nutzlast |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nErstellt eine neue Nachricht mit `data` und übergibt sie an den Delegate `message` der Instanz (`id`, `@componentid` oder `#name`; der erste Treffer). Hänge `/inputid` an, um `$.input` zu setzen. Der Callback läuft, wenn die Nachricht und alle ihre Klone beendet sind, mit `{ error, repo, data, count, cloned, duration, meta: { id, component } }`.\n\nExample: Einen Flow aus einer API aufrufen\n```js\nNEWACTION('Orders/process', {\n\taction: function($, model) {\n\t\tFlow.instances.orders.send('@order/input', model, function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback(response.data);\n\t\t});\n\t}\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nSendet eine Nachricht an alle passenden Instanzen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Optionen |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nWie `send()`, aber für jede passende Instanz. `opt.id` ist das Ziel (`id`, `@componentid` oder `#name`), `opt.data` der Payload, `opt.vars` und `opt.repo` die `$.vars` und `$.repo`, `opt.timeout` ein Timeout in ms (die Nachricht endet mit dem Fehler `408`). `opt.uid` und `opt.ref` kommen in der Antwort zurück. Der Callback läuft für jedes Ziel (bei einem Flow in einem Worker nur für das erste) oder mit `404`, wenn nichts passt.\n\nExample: Exec mit einem Timeout\n```js\nFlow.instances.orders.exec({ id: '#Validate', data: model, timeout: 5000, uid: model.id }, function(err, response) {\n\tconsole.log(response.uid, response.data);\n});\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: `Object` Der flowstream\n\nEin pausierter Flow stellt keine Nachrichten zu. Ohne Argument wird der Zustand umgeschaltet. Der Delegate `pause` jeder Instanz wird aufgerufen.\n\n### flowstream.variables(obj)\n\nType: `method`\n\nErsetzt die Variablen des FlowStreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Neue Variablen |\n\nReturns: `Object` Der flowstream\n\nRuft das Delegate `variables` jeder Instanz auf (und `vary('variables')` bei einem Flow im Hauptprozess), sendet die Variablen an den Editor und speichert den Flow.\n\nExample: Ein Token rotieren\n```js\nFlow.instances.orders.variables({ token: newtoken });\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 |  | Instanz-ID |\n| `config` | `Object` | yes |  | Zusammenzuführende Werte |\n\nReturns: `Object` Der flowstream\n\nDie Werte werden in `instance.config` zusammengeführt, der Delegate `configure` wird aufgerufen, der Editor aktualisiert und der Flow gespeichert.\n\n### flowstream.export(callback)\n\nType: `method`\n\nLiest das aktuelle Schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)` |\n\nDer Callback erhält das gesamte Schema, dasselbe Objekt wie beim Event `save`.\n\nExample: Backup\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('backup.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.restart()\n\nType: `method`\n\nStartet einen FlowStream neu, der in einem Worker läuft.\n\nSchließt die Editor-Verbindungen und beendet den Worker; er startet automatisch mit dem aktuellen Schema neu.\n\n### flowstream.remove()\n\nType: `method`\n\nEntfernt den FlowStream.\n\nDasselbe wie `Flow.remove(flowstream.id)`.\n\n### flowstream.edit([url])\n\nType: `method` · Since: `0.0.16`\n\nVerbindet den FlowStream mit einem entfernten Bearbeitungs-Proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `'wss://flow.totaljs.com/{0}/'` | WebSocket-URL des Proxys |\n\nReturns: `WebSocketClient` Der Client\n\nÖffnet einen WebSocket-Client zur URL (`{0}` wird durch die ID des FlowStream ersetzt) und lässt den Editor darüber arbeiten, sodass die Anwendung keine öffentliche WebSocket-Route braucht. Eine vorherige Verbindung wird geschlossen. Gibt den WebSocket-Client zurück.\n\nExample: Entfernte Bearbeitung\n```js\nFlow.instances.orders.edit();\n```\n\n### exports.* in <script total>\n\nType: `type`\n\nDie Definition einer FlowStream-Komponente.\n\nDer Server-Teil der Komponente setzt Eigenschaften von `exports`:\n\n| Eigenschaft | Bedeutung |\n| --- | --- |\n| `name`, `icon`, `color`, `group`, `version`, `author` | Werden im Editor angezeigt |\n| `type` | Zum Beispiel `input`, `output` oder `config`; diese erscheinen in `io()`-Auflistungen |\n| `inputs`, `outputs` | Arrays von `{ id, name }` |\n| `config` | Standardkonfiguration neuer Instanzen |\n| `npm` | NPM-Pakete, die vor der Registrierung installiert werden |\n| `permissions`, `meta` | Eigene Daten, die an den Editor übergeben werden |\n| `make` | `function(instance, config)` für jede Instanz |\n| `install`, `uninstall` | `function(component)`, wenn die Komponente registriert bzw. entfernt wird |\n| `call` | `function(data, callback)`, wird vom Editor mit `@componentid` aufgerufen |\n\nDie anderen Teile der Datei: `<settings>` (das Konfigurationsformular), `<body>`, `<style>`, `<script>` (Editor-Code), `<readme>`, `<template>` und `<schema>`.\n\nExample: Minimale Komponente\n```html\n<script total>\n\texports.name = 'Print';\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.make = function(instance) {\n\t\tinstance.message = function($) {\n\t\t\tconsole.log($.data);\n\t\t\t$.end();\n\t\t};\n\t};\n</script>\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 Instanz |\n| `config` | `Object` | yes |  | Ihre Konfiguration |\n\nLäuft für jede auf der Arbeitsfläche platzierte Instanz und erneut, wenn sich der Code der Komponente ändert. `config` ist `instance.config`. Weise hier die Delegates der Instanz zu.\n\nExample: Intervall\n```js\nexports.make = function(instance, config) {\n\tvar timer;\n\tinstance.configure = function() {\n\t\tclearInterval(timer);\n\t\ttimer = setInterval(() => instance.send('output', { ts: NOW }), (instance.config.interval || 10) * 1000);\n\t};\n\tinstance.close = () => clearInterval(timer);\n\tinstance.configure();\n};\n```\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nDie Ein- und Ausgänge einer Komponente.\n\nReturns: `Array`\n\nArrays von `{ id, name }`. Die `id` ist das, was `$.input` enthält und was `$.send(id)` und `instance.send(id)` verwenden. Eine Instanz kann sie mit eigenen `inputs` / `outputs` überschreiben.\n\nExample: Zwei Ausgänge\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'OK' }, { id: 'error', name: 'Error' }];\n```\n\n### instance\n\nType: `type`\n\nEine platzierte Instanz einer Komponente.\n\nDas erste Argument von `exports.make()`. Eigenschaften: `id`, `component` (Komponenten-ID), `config`, `cache`, `main` (die Flow-Engine), `module` (die Komponente), `env`, `stats` (`pending`, `input`, `output`, `duration`, `destroyed`), `instances` (alle Instanzen des Flows) und `components`.\n\nDelegates, die du zuweisen kannst: `message($)`, `message_INPUTID($)`, `configure(config)`, `close()`, `init()` (nach dem ersten Laden), `refresh()` (nach jeder Änderung des Designs), `trigger(data)`, `notify(data)`, `call(data, callback)`, `service(minutes)` (jede Minute), `pause(is)`, `variables(obj)`, `secrets(obj)` und `vary(type)`.\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nEmpfängt eine Nachricht an einem Eingang.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | Die Nachricht |\n\n`$.input` ist die Eingangs-ID. `instance.message_INPUTID` empfängt nur Nachrichten eines Eingangs; existieren beide, werden beide aufgerufen. Eine Nachricht, die nicht weitergesendet wird, muss mit `$.end()` beendet werden.\n\nExample: Nach Eingang verteilen\n```js\ninstance.message = function($) {\n\tif ($.input === 'reset') {\n\t\tcount = 0;\n\t\t$.end();\n\t} else {\n\t\tcount++;\n\t\t$.send('output', { count: count });\n\t}\n};\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nDie Konfiguration hat sich geändert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Die Konfiguration |\n\nWird nach einer Änderung im Editor oder einem Aufruf von `reconfigure()` aufgerufen. `instance.config` enthält bereits die neuen Werte.\n\n### instance.close = function() {}\n\nType: `delegate`\n\nDie Instanz wird entfernt.\n\nWird aufgerufen, wenn die Instanz aus dem Design entfernt, die Komponente abgemeldet wird oder der Flow endet. Lösche hier Timer und schließe Verbindungen.\n\n### instance.send(output, [data])\n\nType: `method`\n\nStartet eine neue Nachricht von einem Ausgang oder von allen Ausgängen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id des Ausgangs oder `null` für alle Ausgänge |\n| `data` | `Object` | no |  | Payload |\n\nReturns: `Number` Anzahl der gesendeten Nachrichten\n\nSendet `data` an jede Instanz, die mit dem Ausgang verbunden ist. Mit `output` `null` sendet es an alle Ausgänge. Für die zweite und jede weitere Verbindung werden die Daten geklont (außer bei `cloning: false`). Gibt die Anzahl der gesendeten Nachrichten zurück; `0`, wenn nichts verbunden ist oder der Flow pausiert ist.\n\nExample: Aus einem Timer\n```js\nsetInterval(() => instance.send('output', { ts: NOW }), 1000);\n```\n\nExample: Alle Ausgänge\n```js\ninstance.send(null, { ts: NOW });\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nErstellt eine Nachricht, ohne sie zu senden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Nutzlast |\n\nReturns: `Message` Eine neue Nachricht\n\nDie Nachricht gehört zur Instanz; setze `$.repo`, höre auf `end` und rufe dann `$.send(output)` auf.\n\nExample: Auf das Ende warten\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.on('end', function($) {\n\tconsole.log('Done', $.data);\n});\nmsg.send('output');\n```\n\n### instance.status([data], [delay])\n\nType: `method`\n\nSetzt den unter der Instanz angezeigten Status.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Ein beliebiger JSON-Wert |\n| `delay` | `Number` | no |  | Drosselung in ms |\n\nDer Status wird an den Editor gesendet und als `status` auf `instance.main` ausgelöst. Mit `delay` (ms) werden viele Aufrufe zu einem Update zusammengefasst. Ohne Argumente wird der letzte Status erneut gesendet.\n\nExample: Zähler\n```js\ninstance.status({ count: count }, 1000);\n```\n\n### instance.dashboard([data])\n\nType: `method`\n\nSendet Daten an das Dashboard des Editors.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Ein beliebiger JSON-Wert |\n\nDie Daten werden behalten und an den Editor gesendet; ohne Argumente werden die letzten Daten erneut gesendet.\n\n### instance.throw(error)\n\nType: `method`\n\nMeldet einen Fehler der Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | Der Fehler |\n\nDer Fehler wird zu den letzten 10 Fehlern des Flows hinzugefügt (`instance.main.errors`), im Editor angezeigt, in der Konsole ausgegeben und als `ON('flowstream_error')` ausgelöst. `$.throw(error)` bewirkt dasselbe und setzt `$.error`.\n\nExample: In einem Callback\n```js\nRESTBuilder.GET(config.url).callback(function(err, response) {\n\tif (err) {\n\t\tinstance.throw(err);\n\t\t$.end();\n\t} else\n\t\t$.send('output', response);\n});\n```\n\n### instance.debug(a, [b], [c], [d])\n\nType: `method`\n\nLöst ein Debug-Event aus.\n\nLöst `debug` auf `instance.main` mit der Instanz und den Argumenten aus. `Flow.test()` übergibt es an `test.debug`.\n\n### instance.save([redraw])\n\nType: `method`\n\nSpeichert die Instanz nach einer Änderung aus dem Code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `redraw` | `Boolean` | no | `true` | Die Instanz im Editor neu zeichnen |\n\nVerwende es, nachdem du `instance.config`, `x`, `y`, `note`, `inputs` oder `outputs` im Code geändert hast. Der Flow wird gespeichert (das Event `save` folgt nach etwa 5 Sekunden), und sofern `redraw` nicht `false` ist, zeichnet der Editor die Instanz neu.\n\nExample: Einen Wert merken\n```js\ninstance.config.lastid = $.data.id;\ninstance.save();\n```\n\nExample: Ohne Neuzeichnen\n```js\ninstance.config.counter++;\ninstance.save(false);\n```\n\n### instance.reconfigure(config)\n\nType: `method`\n\nÄndert die Konfiguration dieser Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Zusammenzuführende Werte |\n\nDasselbe wie `flowstream.reconfigure(instance.id, config)`, aus der Komponente aufgerufen.\n\n### instance.replace(text, [data], [encoding])\n\nType: `method`\n\nErsetzt {variables} in einem Text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String|Object` | yes |  | Text mit Platzhaltern |\n| `data` | `Object` | no |  | Zusätzliche Werte |\n| `encoding` | `String|Function` | no |  | Kodierung der Werte |\n\nReturns: `String` Der Text\n\nEin `{name}` (oder `{{name}}`) nimmt den Wert aus den Variablen des Flows, den globalen Variablen, den Secrets, `{hostname}` (Origin plus `proxypath`) oder dem Objekt `data` (verschachtelte Schlüssel mit Punkten). `encoding` kann `url`, `json`, `querify` oder eine `function(value, key)` sein. Bei einem Objekt wird jeder String-Wert ersetzt. Verwende in einer Nachricht `$.variables()` (Alias `$.replace()`), wo `data` standardmäßig die Nachricht ist.\n\nExample: URL\n```js\nvar url = instance.replace('https://api.example.com/{token}/orders/?id={id}', { id: 5 }, 'url');\n```\n\n### instance.cache\n\nType: `property`\n\nEin In-Memory-Objekt für Laufzeitdaten der Instanz.\n\nReturns: `Object`\n\nEin einfaches Objekt im Speicher, das der Flow für die Instanz-id aufbewahrt: Wenn die Instanz erneut initialisiert wird (zum Beispiel wenn ihre Komponente aktualisiert wird), erhält sie dasselbe Objekt zurück. Es wird nicht gespeichert, daher ist es nach einem Neustart leer.\n\nExample: Letzter Wert\n```js\ninstance.message = function($) {\n\tinstance.cache.last = $.data;\n\t$.send('output');\n};\n```\n\n### instance.repo\n\nType: `property` · Since: `0.0.17`\n\nPersistente Daten der Instanz, im Design gespeichert.\n\nReturns: `Object`\n\nEin Objekt, das zusammen mit der Instanz im Schema gespeichert wird. Es übersteht ein Neuladen und einen Neustart, und der Editor lässt es unverändert, wenn er das Design speichert. Rufe nach einer Änderung `instance.save()` auf.\n\nExample: Einen Cursor speichern\n```js\ninstance.repo.lastid = $.data.id;\ninstance.save();\n```\n\n### instance.activity(key, name, [progress])\n\nType: `method` · Since: `0.0.19`\n\nMeldet eine laufende Aktivität der Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Id der Aktivität |\n| `name` | `String` | yes |  | Beschreibung |\n| `progress` | `Number` | no |  | Prozent |\n\nErstellt oder aktualisiert die Aktivität `key`, zeigt sie im Editor an und sendet `activity` auf `instance.main` mit `(instance, key, name, progress)`. Ein leerer `name` oder `progress` `100` entfernt sie. Aktivitäten von Instanzen, die aus dem Design entfernt wurden, werden verworfen.\n\nExample: Fortschritt\n```js\ninstance.activity('sync', 'Synchronizing', 40);\n// ...\ninstance.activity('sync', 'Synchronizing', 100);\n```\n\n### instance.main\n\nType: `property`\n\nDie Flow-Engine der Instanz.\n\nReturns: `FlowStream`\n\nNützliche Mitglieder: `variables`, `secrets`, `stats` (mit `online`, der Anzahl der verbundenen Editoren), `errors`, `paused`, `env`, `activities`, `find(id)` (eine Instanz), `instances()` (bereite Instanzen), `send('ID__OUTPUT', data)`, `trigger('ID__INPUT', data)` (sendet eine neue Nachricht an einen Eingang), `pause(is)`, `save()` und `restart()` (startet den Worker des Flows neu; im Hauptprozess bittet es den Total.js-Prozessmanager, die Anwendung neu zu starten). Es sendet die Events `status`, `debug`, `activity`, `message`, `end` und `reset`.\n\nExample: An eine andere Instanz senden\n```js\ninstance.main.trigger('b1__input', { id: 1 });\n```\n\n### instance.main.on('reset', function() {})\n\nType: `event`\n\nDie Fehler des Flows wurden zurückgesetzt.\n\nWird von der Flow-Engine gesendet, wenn der Editor den Reset-Befehl sendet: Zuerst werden die letzten Fehler des Flows (`instance.main.errors`) gelöscht, dann läuft das Event ohne Argumente. In einem Flow, der in einem Worker läuft, wird es innerhalb des Workers gesendet. Die Engine bleibt bestehen, wenn eine Instanz neu erstellt wird, also entferne den Listener in `instance.close`.\n\nExample: Einen Zähler zurücksetzen\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\n### $\n\nType: `class`\n\nEine Nachricht, die durch den Flow wandert.\n\nEigenschaften: `data`, `repo` (von allen Klonen geteilt), `vars`, `input`, `output`, `from`/`fromid`, `to`/`toid` (Instanzen), `instance`, `main`, `id`, `count`, `duration`, `error`, `controller` und vom Controller `user`, `body`, `query`, `params`, `headers`, `ip`, `language`.\n\nMethoden: `send()`, `end()` (Alias `destroy()`), `rewrite(data)`, `clone()`, `variables()`, `timeout()`, `status()`, `dashboard()`, `debug()`, `throw()` und `on(name, fn)`. Events: `end` (die Nachricht und alle Klone sind beendet), `timeout` und `message`.\n\n### $.send(output, [data], [clone], [check])\n\nType: `method`\n\nSendet die Nachricht an einen Ausgang oder an alle Ausgänge.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Ausgangs-ID oder `null` für alle Ausgänge |\n| `data` | `Object` | no |  | Neue Nutzdaten |\n| `clone` | `Boolean` | no | `the `cloning` of the flow` | Die Daten klonen |\n| `check` | `Function` | no |  | `function(from, to, output, input)` gibt einen Boolean zurück |\n\nReturns: `Number` Anzahl der Ziele\n\nSendet einen Klon der Nachricht an jede Instanz, die mit dem Ausgang verbunden ist. Mit `output` `null` sendet sie an alle Ausgänge: Ein Ausgang ohne bereites Ziel wird übersprungen, die anderen Ausgänge erhalten die Nachricht trotzdem, und die Nachricht endet einmal, wenn alle ihre Klone enden. `data` ersetzt die Nutzdaten; `clone` (Standard: das `cloning` des Flows) kopiert Objektdaten für jedes Ziel tief. `check(from, to, output, input)` wird für jedes Ziel eines benannten Ausgangs aufgerufen (`from` und `to` sind Instanzen); gib `false` zurück, um das Ziel zu überspringen. Gibt die Anzahl der Ziele zurück; bei `0` endet die Nachricht.\n\nExample: Weitergeben\n```js\ninstance.message = function($) {\n\t$.data.checked = true;\n\t$.send('output');\n};\n```\n\nExample: Einige Ziele überspringen\n```js\n$.send('output', null, null, function(from, to, output, input) {\n\treturn to.component !== 'debug';\n});\n```\n\nExample: Alle Ausgänge\n```js\ninstance.message = function($) {\n\t$.send(null);\n};\n```\n\n### $.end()\n\nType: `method`\n\nBeendet die Nachricht.\n\nRufe es auf, wenn die Nachricht nicht weitergesendet wird. Wenn die Nachricht und alle ihre Klone beendet sind, wird ihr Event `end` ausgelöst (und der `callback` von `flowstream.send()`).\n\nExample: Hier anhalten\n```js\ninstance.message = function($) {\n\tsave($.data);\n\t$.end();\n};\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nSetzt ein Timeout für die nächsten Instanzen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function($)` |\n| `time` | `Number` | yes |  | Millisekunden |\n\nReturns: `Message`\n\nJeder nach diesem Aufruf gesendete Klon muss innerhalb von `time` ms verarbeitet werden; andernfalls endet er mit `$.error = 408`, und der Callback läuft. `$.totaltimeout([callback], time)` begrenzt stattdessen die gesamte Nachricht.\n\nExample: Timeout\n```js\n$.timeout(function($) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n\n### flow5 [path or URL ...] [port]\n\nType: `command`\n\nFührt FlowStream-Schemas über die Kommandozeile aus.\n\nLädt jede JSON-Datei (ein Schema oder ein Objekt mit mehreren Schemas) oder HTTPS-URL, startet einen HTTP-Server auf dem Port (Standard `8000`) mit der Route `SOCKET /flowstreams/{id}/` und den Routes `/notify/{id}/` und gibt für jeden Flow den Editor-Link aus. Änderungen aus dem Editor werden in die lokalen Dateien zurückgeschrieben. Ohne Argumente wird die Hilfe ausgegeben.\n\nExample: Zwei Flows auf Port 8001\n```bash\nflow5 orders.json import.json 8001\n```\n","entries":[{"type":"class","name":"Flow","signature":"Flow / FlowStream","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":"method","name":"Flow.reload()","signature":"Flow.reload(schema, [restart])","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.restart()","signature":"Flow.restart(id)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [verify], [check])","since":"","deprecated":false},{"type":"method","name":"Flow.notify()","signature":"Flow.notify($, id)","since":"","deprecated":false},{"type":"method","name":"Flow.test()","signature":"Flow.test(name, source, [config], init)","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(flowstream, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('remove')","signature":"Flow.on('remove', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('stats')","signature":"Flow.on('stats', function(id, stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(flowstream) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"type","name":"FlowStream schema","signature":"{ id, name, components, design, variables, ... }","since":"","deprecated":false},{"type":"config","name":"proxytimeout","signature":"schema.proxytimeout","since":"0.0.18","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, [data])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(id, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(obj)","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.restart()","signature":"flowstream.restart()","since":"","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"flowstream.edit()","signature":"flowstream.edit([url])","since":"0.0.16","deprecated":false},{"type":"type","name":"Component","signature":"exports.* in <script total>","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 / exports.outputs","since":"","deprecated":false},{"type":"type","name":"instance","signature":"instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","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() {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, [data])","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(error)","since":"","deprecated":false},{"type":"method","name":"instance.debug()","signature":"instance.debug(a, [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save([redraw])","since":"","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(config)","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(text, [data], [encoding])","since":"","deprecated":false},{"type":"property","name":"instance.cache","signature":"instance.cache","since":"","deprecated":false},{"type":"property","name":"instance.repo","signature":"instance.repo","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, [progress])","since":"0.0.19","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"event","name":"instance.main.on('reset')","signature":"instance.main.on('reset', function() {})","since":"","deprecated":false},{"type":"class","name":"Message","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send(output, [data], [clone], [check])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end()","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5 [path or URL ...] [port]","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwTf7Ix61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/flowstream/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"FlowStream","summary":"El global Flow, los FlowStreams en marcha, los componentes, las instancias, los mensajes y el comando flow5.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/flowstream/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# FlowStream\n\n> El global Flow, los FlowStreams en marcha, los componentes, las instancias, los mensajes y el comando flow5.\n\nMétodos, propiedades y eventos del global `Flow`, de un FlowStream en marcha (`Flow.instances[id]`), de las definiciones de componentes, de las instancias de componentes y de los mensajes, además del comando `flow5`. Para una introducción con ejemplos, lee la guía [FlowStream](../../guides/flowstream/).\n\n## API\n\n### Flow / FlowStream\n\nType: `class`\n\nEl objeto global del motor FlowStream.\n\n`Flow` y `FlowStream` son el mismo objeto. Carga los flujos, los guarda en `Flow.instances` y emite los eventos `load`, `save` y `remove`. Los flujos en marcha son los objetos que aquí se describen como `flowstream`.\n\nExample: Listar los flujos en marcha\n```js\nfor (var id in Flow.instances)\n\tconsole.log(id, Flow.instances[id].stats);\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nArranca un FlowStream a partir de su esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | El esquema del FlowStream |\n| `callback` | `Function` | no |  | `function(err, flowstream)` |\n\nLas claves que faltan reciben valores por defecto: un `id` aleatorio, `name` = `id` y `components`, `design`, `sources` y `variables` vacíos. Si ya hay en marcha un FlowStream con el mismo `id`, se recarga con el nuevo esquema. El callback se ejecuta cuando se han cargado los componentes y el diseño. Consulta [FlowStream](../../guides/flowstream/) para ver las claves del esquema.\n\nExample: Cargar un archivo\n```js\nvar schema = (await F.readfile(PATH.root('orders.json'), 'utf8')).parseJSON();\nFlow.load(schema, function(err, flowstream) {\n\terr && console.error(err);\n});\n```\n\nExample: Ejecutar en un worker thread\n```js\nFlow.load({ id: 'import', worker: 'worker', components: {}, design: {} });\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')` | Directorio con archivos .flow |\n| `callback` | `Function` | no |  | Se llama cuando todos los archivos están cargados |\n\nLee cada archivo `*.flow` (un esquema JSON) del directorio y lo carga con `Flow.load()`. Se omiten los archivos con `-bk` o `_bk` en el nombre. El directorio por defecto es `/flowstreams/` en la raíz de la aplicación. El framework lo llama una vez al arrancar, así que solo lo necesitas para otros directorios. El archivo `index.flow` de un plugin se carga con el plugin.\n\nExample: Otro directorio\n```js\nFlow.init(PATH.root('data/flows'), function() {\n\tconsole.log('Loaded:', Object.keys(Flow.instances));\n});\n```\n\n### Flow.reload(schema, [restart])\n\nType: `method`\n\nAplica un nuevo esquema a un FlowStream en ejecución.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | El nuevo esquema |\n| `restart` | `Boolean` | no | `false` | Reiniciar el worker |\n\nReturns: `Boolean` `true` cuando el FlowStream existe\n\nEl esquema debe tener el `id` de un FlowStream en ejecución. Los componentes y el diseño se reemplazan en su sitio y los componentes eliminados se dan de baja. Con `restart` (solo workers) el worker se termina y se vuelve a iniciar con su esquema actual; el nuevo esquema no se aplica. Devuelve `false` cuando ningún FlowStream tiene este id.\n\n### Flow.remove(id)\n\nType: `method`\n\nDetiene y elimina un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id del FlowStream |\n\nCierra todas las instancias, termina el worker, elimina el FlowStream de `Flow.instances` y emite `remove`.\n\nExample: Eliminar\n```js\nFlow.remove('orders');\n```\n\n### Flow.restart(id)\n\nType: `method`\n\nReinicia un FlowStream que se ejecuta en un worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id del FlowStream |\n\nReturns: `Boolean` `true` si se encuentra\n\nTermina el worker thread o el proceso hijo; se vuelve a iniciar automáticamente con el esquema actual al cabo de un segundo. Devuelve `true` cuando el FlowStream existe (si no, `undefined`). Un FlowStream en el proceso principal se termina y no se vuelve a iniciar.\n\n### Flow.socket(id, websocket, [verify], [check])\n\nType: `method`\n\nConecta el editor Total.js Flow a un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id del FlowStream |\n| `websocket` | `WebSocket` | yes |  | El WebSocket de la ruta |\n| `verify` | `Function` | no |  | `function(client, next)` |\n| `check` | `Function` | no |  | `function(client, message)` devuelve `true` o un error |\n\nPasa el objeto WebSocket de una ruta `SOCKET`. `verify(client, next)` puede aceptar a un cliente nuevo antes de que reciba el flujo (llama a `next()`), y `check(client, message)` puede bloquear comandos concretos: devuelve `true` para permitirlo, o un texto de error. Un id desconocido cierra el WebSocket.\n\nExample: Ruta para el editor\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', function($) {\n\t\t$.autodestroy();\n\t\tFlow.socket($.params.id, $, null, function(client, msg) {\n\t\t\treturn client.user.sa ? true : 'Only for admins';\n\t\t});\n\t});\n};\n```\n\n### Flow.notify($, id)\n\nType: `method`\n\nPasa una petición HTTP al delegado notify de una instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | El controlador de la ruta |\n| `id` | `String` | yes |  | `flowid-instanceid` |\n\n`id` es `flowid-instanceid` (las partes `-` adicionales pasan a `params`). El delegado `notify` de la instancia recibe `{ id, method, headers, query, body, url, ip, params }`, y el editor recibe el mismo objeto. Después, la respuesta redirige a `?REDIRECT=url`, envía una pequeña página que cierra la ventana (para navegadores) o un JSON de éxito.\n\nExample: Rutas\n```js\nROUTE('GET /notify/{id}/', $ => Flow.notify($, $.params.id));\nROUTE('POST /notify/{id}/ <1MB', $ => Flow.notify($, $.params.id));\n```\n\nExample: En un componente\n```js\ninstance.notify = function(data) {\n\tinstance.send('output', data.body);\n};\n```\n\n### Flow.test(name, source, [config], init)\n\nType: `method`\n\nCarga un componente en un flujo de prueba.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Id del componente |\n| `source` | `String` | yes |  | Código fuente del componente |\n| `config` | `Object` | no | `{}` | Configuración de la instancia |\n| `init` | `Function` | yes |  | `function(test)` |\n\nCrea un flujo con el componente (id de instancia `component`) y una instancia auxiliar conectada a todas sus entradas y salidas. `init(test)` recibe el objeto `Test`:\n\n| Miembro | Uso |\n| --- | --- |\n| `test.send(input, data)` | Envía datos a una entrada del componente (alias `input`) |\n| `test.message = function($, data)` | Recibe lo que el componente envía a sus salidas |\n| `test.status = function(status)` | Recibe el estado del componente |\n| `test.debug = function(...)` | Recibe las llamadas a `instance.debug()` |\n| `test.configure = function(config)` | Se llama tras una reconfiguración |\n| `test.trigger(data)` | Ejecuta el delegado `trigger` |\n| `test.reconfigure(config)` | Cambia la configuración |\n| `test.variables(obj)` | Asigna las variables |\n| `test.assert(ok, text)`, `test.ok(text)`, `test.fail(text)` | Imprimen el resultado; `fail` lanza un error |\n\nUn error en el flujo termina el proceso.\n\nExample: Prueba\n```js\nvar source = await F.readfile(PATH.root('components/uppercase.html'), 'utf8');\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nLos FlowStreams en ejecución, por id.\n\nReturns: `Object`\n\nUn objeto: id del FlowStream → objeto `flowstream`. `Flow.db` contiene el último esquema de cada FlowStream (se actualiza en cada guardado).\n\nExample: Obtener uno\n```js\nvar flowstream = Flow.instances.orders;\n```\n\n### Flow.on('load', function(flowstream, schema) {})\n\nType: `event`\n\nSe ha cargado un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | El FlowStream en ejecución |\n| `schema` | `Object` | yes |  | El esquema |\n\nSe emite después de que `Flow.load()` haya cargado los componentes y el diseño.\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nEl esquema de un FlowStream ha cambiado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | El esquema completo |\n\nSe emite unos 5 segundos después de un cambio en el editor o de una llamada a `instance.save()`. El esquema contiene `id`, `name`, `components`, `design`, `variables`, `sources`, `paused` y las demás claves. Guárdalo tú, por ejemplo en un archivo `.flow`. Los flujos con `readonly: true` no se guardan.\n\nExample: Guardar en un archivo\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### Flow.on('remove', function(schema) {})\n\nType: `event`\n\nSe ha eliminado un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | El esquema |\n\nLo emite `Flow.remove()` con el último esquema del FlowStream eliminado.\n\n### Flow.on('stats', function(id, stats) {})\n\nType: `event`\n\nContadores de un FlowStream que se ejecuta en un worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id del FlowStream |\n| `stats` | `Object` | yes |  | Contadores |\n\nSe emite cada 15 segundos para cada FlowStream en un hilo worker o proceso hijo. `stats` tiene `paused`, `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` y `pid`.\n\n### ON('flowstream', function(flowstream) {})\n\nType: `event` · Since: `0.0.16`\n\nSe ha iniciado un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | El FlowStream en ejecución |\n\nEvento global del framework emitido cuando se crea un FlowStream, también tras el reinicio automático de un worker.\n\nExample: Registro\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream', flowstream.id);\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nSe ha producido un error en un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Detalles del error |\n\nLos errores se imprimen en la consola y se emiten como este evento global. `meta` tiene `id` y `name` (del FlowStream), `error`, `source`, `instanceid` y `componentid`.\n\nExample: Auditar los errores\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### { id, name, components, design, variables, ... }\n\nType: `type`\n\nEl objeto que describe un FlowStream.\n\nReturns: `undefined` Nada\n\n`components` asigna a cada id de componente su código fuente. `design` asigna a cada id de instancia `{ component, config, connections, x, y, note, tab }`; `connections` asigna a cada id de salida un array de `{ id, index }` (la instancia de destino y su entrada). Más claves: `variables`, `sources` (TMS), `worker`, `memory` (con `worker`: el límite de heap del hilo worker o del proceso hijo en MB), `proxypath`, `cloning`, `paused`, `readonly`, `import`, `initscript`, `env`, `directory` y `asfiles` (`true` compila los componentes en archivos de `/tmp/`). Las claves descriptivas como `icon`, `color`, `author`, `version` y `readme` se muestran en el editor.\n\nExample: Dos instancias conectadas\n```json\n{\n\t\"id\": \"demo\",\n\t\"name\": \"Demo\",\n\t\"components\": { \"uppercase\": \"<script total>...</script>\", \"print\": \"<script total>...</script>\" },\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\": {}\n}\n```\n\n### schema.proxytimeout\n\nType: `config` · Since: `0.0.18`\n\nTimeout del proxy de un worker con proxypath.\n\nReturns: `Number`\n\nMilisegundos del timeout del proxy que reenvía al worker las peticiones bajo `proxypath`. Se aplica cuando el esquema se vuelve a cargar en el FlowStream en ejecución (`Flow.load()` con el mismo id o `Flow.reload()`).\n\nExample: Recargar con un timeout\n```js\nFlow.reload({ id: 'api', worker: 'worker', proxypath: '/api/', proxytimeout: 10000, components: components, design: design });\n```\n\n### flowstream.stats\n\nType: `property`\n\nContadores del FlowStream.\n\nReturns: `Object`\n\n`messages` (total), `pending`, `memory` (bytes), `minutes` (tiempo activo), `errors` (el número de los últimos errores, como máximo 10), `mm` (mensajes del último minuto) y `paused`. Para un flujo en el proceso principal, `online` es el número de editores conectados. Para un worker, los valores llegan cada 15 segundos.\n\n### flowstream.trigger(id, [data])\n\nType: `method`\n\nEjecuta el delegado trigger de las instancias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id de la instancia, `@componentid` o `#name` |\n| `data` | `Object` | no |  | Se pasa al delegado |\n\nReturns: `Object` El flowstream\n\nLlama a `instance.trigger(data)` de la instancia `id`, de todas las instancias de un componente (`@componentid`) o de un nombre de componente (`#name`). No se ejecuta nada mientras el flujo está en pausa.\n\nExample: Arrancar todos los temporizadores\n```js\nFlow.instances.orders.trigger('@timer');\n```\n\n### flowstream.send(id, data, [callback])\n\nType: `method`\n\nEnvía datos a una instancia y espera el resultado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Destino, opcionalmente con `/input` |\n| `data` | `Object` | yes |  | Carga útil |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nCrea un mensaje nuevo con `data` y lo pasa al delegado `message` de la instancia (`id`, `@componentid` o `#name`; la primera coincidencia). Añade `/inputid` para asignar `$.input`. El callback se ejecuta cuando el mensaje y todos sus clones han terminado, con `{ error, repo, data, count, cloned, duration, meta: { id, component } }`.\n\nExample: Llamar a un flujo desde una API\n```js\nNEWACTION('Orders/process', {\n\taction: function($, model) {\n\t\tFlow.instances.orders.send('@order/input', model, function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback(response.data);\n\t\t});\n\t}\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nEnvía un mensaje a todas las instancias que coinciden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Opciones |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nComo `send()`, pero para cada instancia que coincide. `opt.id` es el destino (`id`, `@componentid` o `#name`), `opt.data` la carga útil, `opt.vars` y `opt.repo` los `$.vars` y `$.repo`, `opt.timeout` un tiempo de espera en ms (el mensaje termina con el error `408`). `opt.uid` y `opt.ref` vuelven en la respuesta. El callback se ejecuta para cada destino (para un flujo en un worker, solo para el primero), o con `404` cuando nada coincide.\n\nExample: Exec con un timeout\n```js\nFlow.instances.orders.exec({ id: '#Validate', data: model, timeout: 5000, uid: model.id }, function(err, response) {\n\tconsole.log(response.uid, response.data);\n});\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: `Object` El flowstream\n\nUn flujo en pausa no entrega mensajes. Sin el argumento, el estado se alterna. Se llama al delegado `pause` de cada instancia.\n\n### flowstream.variables(obj)\n\nType: `method`\n\nSustituye las variables del FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Nuevas variables |\n\nReturns: `Object` El flowstream\n\nLlama al delegado `variables` de cada instancia (y a `vary('variables')` para un flujo en el proceso principal), envía las variables al editor y guarda el flujo.\n\nExample: Rotar un token\n```js\nFlow.instances.orders.variables({ token: newtoken });\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 |  | Id de la instancia |\n| `config` | `Object` | yes |  | Valores que se combinan |\n\nReturns: `Object` El flowstream\n\nLos valores se combinan en `instance.config`, se llama al delegado `configure`, se actualiza el editor y se guarda el flujo.\n\n### flowstream.export(callback)\n\nType: `method`\n\nLee el esquema actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)` |\n\nEl callback recibe el esquema completo, el mismo objeto que el evento `save`.\n\nExample: Copia de seguridad\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('backup.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.restart()\n\nType: `method`\n\nReinicia un FlowStream que se ejecuta en un worker.\n\nCierra las conexiones del editor y termina el worker; se vuelve a arrancar automáticamente con el esquema actual.\n\n### flowstream.remove()\n\nType: `method`\n\nElimina el FlowStream.\n\nLo mismo que `Flow.remove(flowstream.id)`.\n\n### flowstream.edit([url])\n\nType: `method` · Since: `0.0.16`\n\nConecta el FlowStream a un proxy de edición remoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `'wss://flow.totaljs.com/{0}/'` | URL WebSocket del proxy |\n\nReturns: `WebSocketClient` El cliente\n\nAbre un cliente WebSocket a la URL (`{0}` se sustituye por el id del FlowStream) y deja que el editor trabaje a través de él, así que la aplicación no necesita una ruta WebSocket pública. Se cierra una conexión anterior. Devuelve el cliente WebSocket.\n\nExample: Edición remota\n```js\nFlow.instances.orders.edit();\n```\n\n### exports.* in <script total>\n\nType: `type`\n\nLa definición de un componente de FlowStream.\n\nLa parte de servidor del componente asigna propiedades de `exports`:\n\n| Propiedad | Significado |\n| --- | --- |\n| `name`, `icon`, `color`, `group`, `version`, `author` | Se muestran en el editor |\n| `type` | Por ejemplo `input`, `output` o `config`; aparecen en los listados de `io()` |\n| `inputs`, `outputs` | Arrays de `{ id, name }` |\n| `config` | Configuración por defecto de las nuevas instancias |\n| `npm` | Paquetes NPM que se instalan antes del registro |\n| `permissions`, `meta` | Datos personalizados que se pasan al editor |\n| `make` | `function(instance, config)` para cada instancia |\n| `install`, `uninstall` | `function(component)` cuando el componente se registra y se elimina |\n| `call` | `function(data, callback)` que el editor llama con `@componentid` |\n\nLas demás partes del archivo: `<settings>` (el formulario de configuración), `<body>`, `<style>`, `<script>` (código del editor), `<readme>`, `<template>` y `<schema>`.\n\nExample: Componente mínimo\n```html\n<script total>\n\texports.name = 'Print';\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.make = function(instance) {\n\t\tinstance.message = function($) {\n\t\t\tconsole.log($.data);\n\t\t\t$.end();\n\t\t};\n\t};\n</script>\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 instancia |\n| `config` | `Object` | yes |  | Su configuración |\n\nSe ejecuta para cada instancia colocada en el lienzo, y de nuevo cuando cambia el código del componente. `config` es `instance.config`. Asigna aquí los delegados de la instancia.\n\nExample: Intervalo\n```js\nexports.make = function(instance, config) {\n\tvar timer;\n\tinstance.configure = function() {\n\t\tclearInterval(timer);\n\t\ttimer = setInterval(() => instance.send('output', { ts: NOW }), (instance.config.interval || 10) * 1000);\n\t};\n\tinstance.close = () => clearInterval(timer);\n\tinstance.configure();\n};\n```\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nLas entradas y salidas de un componente.\n\nReturns: `Array`\n\nArrays de `{ id, name }`. El `id` es lo que contiene `$.input` y lo que usan `$.send(id)` e `instance.send(id)`. Una instancia puede sobrescribirlos con sus propios `inputs` / `outputs`.\n\nExample: Dos salidas\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'OK' }, { id: 'error', name: 'Error' }];\n```\n\n### instance\n\nType: `type`\n\nUna instancia colocada de un componente.\n\nEl primer argumento de `exports.make()`. Propiedades: `id`, `component` (id del componente), `config`, `cache`, `main` (el motor del flujo), `module` (el componente), `env`, `stats` (`pending`, `input`, `output`, `duration`, `destroyed`), `instances` (todas las instancias del flujo) y `components`.\n\nDelegados que puedes asignar: `message($)`, `message_INPUTID($)`, `configure(config)`, `close()`, `init()` (tras la primera carga), `refresh()` (tras cada cambio del diseño), `trigger(data)`, `notify(data)`, `call(data, callback)`, `service(minutes)` (cada minuto), `pause(is)`, `variables(obj)`, `secrets(obj)` y `vary(type)`.\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nRecibe un mensaje en una entrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | El mensaje |\n\n`$.input` es el id de la entrada. `instance.message_INPUTID` recibe solo los mensajes de una entrada; si existen ambos, se llama a los dos. Un mensaje que no se envía más allá debe terminarse con `$.end()`.\n\nExample: Encaminar por entrada\n```js\ninstance.message = function($) {\n\tif ($.input === 'reset') {\n\t\tcount = 0;\n\t\t$.end();\n\t} else {\n\t\tcount++;\n\t\t$.send('output', { count: count });\n\t}\n};\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nLa configuración ha cambiado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | La configuración |\n\nSe llama tras un cambio en el editor o una llamada a `reconfigure()`. `instance.config` ya contiene los nuevos valores.\n\n### instance.close = function() {}\n\nType: `delegate`\n\nLa instancia se está eliminando.\n\nSe llama cuando la instancia se elimina del diseño, el componente se da de baja o el flujo termina. Limpia aquí los temporizadores y cierra las conexiones.\n\n### instance.send(output, [data])\n\nType: `method`\n\nInicia un nuevo mensaje desde una salida o desde todas las salidas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id de la salida, o `null` para todas las salidas |\n| `data` | `Object` | no |  | Carga útil |\n\nReturns: `Number` Número de mensajes enviados\n\nEnvía `data` a cada instancia conectada a la salida. Con `output` `null` lo envía a todas las salidas. Para la segunda conexión y las siguientes, los datos se clonan (salvo con `cloning: false`). Devuelve el número de mensajes enviados; `0` cuando no hay nada conectado o el flujo está en pausa.\n\nExample: Desde un temporizador\n```js\nsetInterval(() => instance.send('output', { ts: NOW }), 1000);\n```\n\nExample: Todas las salidas\n```js\ninstance.send(null, { ts: NOW });\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nCrea un mensaje sin enviarlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Carga útil |\n\nReturns: `Message` Un mensaje nuevo\n\nEl mensaje pertenece a la instancia; asigna `$.repo`, escucha `end` y después llama a `$.send(output)`.\n\nExample: Esperar al final\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.on('end', function($) {\n\tconsole.log('Done', $.data);\n});\nmsg.send('output');\n```\n\n### instance.status([data], [delay])\n\nType: `method`\n\nAsigna el estado que se muestra debajo de la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Cualquier valor JSON |\n| `delay` | `Number` | no |  | Limitación en ms |\n\nEl estado se envía al editor y se emite como `status` en `instance.main`. Con `delay` (ms), muchas llamadas se agrupan en una sola actualización. Sin argumentos, se vuelve a enviar el último estado.\n\nExample: Contador\n```js\ninstance.status({ count: count }, 1000);\n```\n\n### instance.dashboard([data])\n\nType: `method`\n\nEnvía datos al dashboard del editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Cualquier valor JSON |\n\nLos datos se guardan y se envían al editor; sin argumentos, se vuelven a enviar los últimos datos.\n\n### instance.throw(error)\n\nType: `method`\n\nInforma de un error de la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | El error |\n\nEl error se añade a los 10 últimos errores del flujo (`instance.main.errors`), se muestra en el editor, se imprime en la consola y se emite como `ON('flowstream_error')`. `$.throw(error)` hace lo mismo y asigna `$.error`.\n\nExample: En un callback\n```js\nRESTBuilder.GET(config.url).callback(function(err, response) {\n\tif (err) {\n\t\tinstance.throw(err);\n\t\t$.end();\n\t} else\n\t\t$.send('output', response);\n});\n```\n\n### instance.debug(a, [b], [c], [d])\n\nType: `method`\n\nEmite un evento de depuración.\n\nEmite `debug` en `instance.main` con la instancia y los argumentos. `Flow.test()` lo pasa a `test.debug`.\n\n### instance.save([redraw])\n\nType: `method`\n\nGuarda la instancia tras un cambio desde el código.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `redraw` | `Boolean` | no | `true` | Redibujar la instancia en el editor |\n\nÚsalo después de cambiar `instance.config`, `x`, `y`, `note`, `inputs` u `outputs` en el código. El flujo se guarda (el evento `save` llega unos 5 segundos después) y, salvo que `redraw` sea `false`, el editor redibuja la instancia.\n\nExample: Recordar un valor\n```js\ninstance.config.lastid = $.data.id;\ninstance.save();\n```\n\nExample: Sin redibujar\n```js\ninstance.config.counter++;\ninstance.save(false);\n```\n\n### instance.reconfigure(config)\n\nType: `method`\n\nCambia la configuración de esta instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Valores que se combinan |\n\nLo mismo que `flowstream.reconfigure(instance.id, config)` llamado desde el componente.\n\n### instance.replace(text, [data], [encoding])\n\nType: `method`\n\nSustituye {variables} en un texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String|Object` | yes |  | Texto con marcadores |\n| `data` | `Object` | no |  | Valores adicionales |\n| `encoding` | `String|Function` | no |  | Codificación de los valores |\n\nReturns: `String` El texto\n\nUn `{name}` (o `{{name}}`) toma el valor de las variables del flujo, de las variables globales, de los secretos, de `{hostname}` (el origen más `proxypath`) o del objeto `data` (claves anidadas con puntos). `encoding` puede ser `url`, `json`, `querify` o una `function(value, key)`. Un objeto sustituye cada valor de tipo string. En un mensaje usa `$.variables()` (alias `$.replace()`), donde `data` es por defecto el mensaje.\n\nExample: URL\n```js\nvar url = instance.replace('https://api.example.com/{token}/orders/?id={id}', { id: 5 }, 'url');\n```\n\n### instance.cache\n\nType: `property`\n\nUn objeto en memoria para los datos en tiempo de ejecución de la instancia.\n\nReturns: `Object`\n\nUn objeto simple en memoria, que el flujo conserva para el id de la instancia: cuando la instancia se vuelve a inicializar (por ejemplo cuando se actualiza su componente), recibe de nuevo el mismo objeto. No se guarda, así que está vacío tras un reinicio.\n\nExample: Último valor\n```js\ninstance.message = function($) {\n\tinstance.cache.last = $.data;\n\t$.send('output');\n};\n```\n\n### instance.repo\n\nType: `property` · Since: `0.0.17`\n\nDatos persistentes de la instancia guardados en el diseño.\n\nReturns: `Object`\n\nUn objeto guardado en el esquema junto con la instancia. Sobrevive a una recarga y a un reinicio, y el editor lo mantiene sin cambios cuando guarda el diseño. Llama a `instance.save()` después de un cambio.\n\nExample: Guardar un cursor\n```js\ninstance.repo.lastid = $.data.id;\ninstance.save();\n```\n\n### instance.activity(key, name, [progress])\n\nType: `method` · Since: `0.0.19`\n\nInforma de una actividad en curso de la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Id de la actividad |\n| `name` | `String` | yes |  | Descripción |\n| `progress` | `Number` | no |  | Porcentaje |\n\nCrea o actualiza la actividad `key`, la muestra en el editor y emite `activity` en `instance.main` con `(instance, key, name, progress)`. Un `name` vacío o un `progress` `100` la elimina. Las actividades de las instancias eliminadas del diseño se descartan.\n\nExample: Progreso\n```js\ninstance.activity('sync', 'Synchronizing', 40);\n// ...\ninstance.activity('sync', 'Synchronizing', 100);\n```\n\n### instance.main\n\nType: `property`\n\nEl motor del flujo de la instancia.\n\nReturns: `FlowStream`\n\nMiembros útiles: `variables`, `secrets`, `stats` (con `online`, el número de editores conectados), `errors`, `paused`, `env`, `activities`, `find(id)` (una instancia), `instances()` (instancias listas), `send('ID__OUTPUT', data)`, `trigger('ID__INPUT', data)` (envía un nuevo mensaje a una entrada), `pause(is)`, `save()` y `restart()` (reinicia el worker del flujo; en el proceso principal pide al gestor de procesos de Total.js que reinicie la aplicación). Emite los eventos `status`, `debug`, `activity`, `message`, `end` y `reset`.\n\nExample: Enviar a otra instancia\n```js\ninstance.main.trigger('b1__input', { id: 1 });\n```\n\n### instance.main.on('reset', function() {})\n\nType: `event`\n\nSe han reiniciado los errores del flujo.\n\nLo emite el motor del flujo cuando el editor envía el comando de reinicio: primero se borran los últimos errores del flujo (`instance.main.errors`) y después el evento se ejecuta sin argumentos. En un flujo que se ejecuta en un worker se emite dentro del worker. El motor se mantiene cuando se vuelve a crear una instancia, así que elimina el listener en `instance.close`.\n\nExample: Reiniciar un contador\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\n### $\n\nType: `class`\n\nUn mensaje que viaja por el flujo.\n\nPropiedades: `data`, `repo` (compartido por todos los clones), `vars`, `input`, `output`, `from`/`fromid`, `to`/`toid` (instancias), `instance`, `main`, `id`, `count`, `duration`, `error`, `controller` y, del controlador, `user`, `body`, `query`, `params`, `headers`, `ip`, `language`.\n\nMétodos: `send()`, `end()` (alias `destroy()`), `rewrite(data)`, `clone()`, `variables()`, `timeout()`, `status()`, `dashboard()`, `debug()`, `throw()` y `on(name, fn)`. Eventos: `end` (el mensaje y todos sus clones han terminado), `timeout` y `message`.\n\n### $.send(output, [data], [clone], [check])\n\nType: `method`\n\nEnvía el mensaje a una salida o a todas las salidas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id de la salida, o `null` para todas las salidas |\n| `data` | `Object` | no |  | Nuevo payload |\n| `clone` | `Boolean` | no | `the `cloning` of the flow` | Clonar los datos |\n| `check` | `Function` | no |  | `function(from, to, output, input)` devuelve un Boolean |\n\nReturns: `Number` Número de destinos\n\nEnvía un clon del mensaje a cada instancia conectada a la salida. Con `output` `null` lo envía a todas las salidas: una salida sin un destino listo se omite, las demás salidas reciben igualmente el mensaje, y el mensaje termina una sola vez, cuando terminan todos sus clones. `data` sustituye el payload; `clone` (por defecto: el `cloning` del flujo) hace una copia profunda de los datos de tipo objeto para cada destino. `check(from, to, output, input)` se llama para cada destino de una salida con nombre (`from` y `to` son instancias); devuelve `false` para omitir el destino. Devuelve el número de destinos; con `0` el mensaje termina.\n\nExample: Pasarlo\n```js\ninstance.message = function($) {\n\t$.data.checked = true;\n\t$.send('output');\n};\n```\n\nExample: Omitir algunos destinos\n```js\n$.send('output', null, null, function(from, to, output, input) {\n\treturn to.component !== 'debug';\n});\n```\n\nExample: Todas las salidas\n```js\ninstance.message = function($) {\n\t$.send(null);\n};\n```\n\n### $.end()\n\nType: `method`\n\nTermina el mensaje.\n\nLlámalo cuando el mensaje no se envía más allá. Cuando el mensaje y todos sus clones han terminado, se dispara su evento `end` (y el `callback` de `flowstream.send()`).\n\nExample: Detenerse aquí\n```js\ninstance.message = function($) {\n\tsave($.data);\n\t$.end();\n};\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nAsigna un timeout para las siguientes instancias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function($)` |\n| `time` | `Number` | yes |  | Milisegundos |\n\nReturns: `Message`\n\nCada clon enviado después de esta llamada debe procesarse en `time` ms; si no, termina con `$.error = 408` y se ejecuta el callback. `$.totaltimeout([callback], time)` limita en cambio el mensaje completo.\n\nExample: Timeout\n```js\n$.timeout(function($) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n\n### flow5 [path or URL ...] [port]\n\nType: `command`\n\nEjecuta esquemas de FlowStream desde la línea de comandos.\n\nCarga cada archivo JSON (un esquema, o un objeto con varios esquemas) o URL HTTPS, arranca un servidor HTTP en el puerto (por defecto `8000`) con la ruta `SOCKET /flowstreams/{id}/` y las rutas `/notify/{id}/`, e imprime el enlace del editor de cada flujo. Los cambios del editor se escriben de vuelta en los archivos locales. Sin argumentos, imprime la ayuda.\n\nExample: Dos flujos en el puerto 8001\n```bash\nflow5 orders.json import.json 8001\n```\n","entries":[{"type":"class","name":"Flow","signature":"Flow / FlowStream","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":"method","name":"Flow.reload()","signature":"Flow.reload(schema, [restart])","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.restart()","signature":"Flow.restart(id)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [verify], [check])","since":"","deprecated":false},{"type":"method","name":"Flow.notify()","signature":"Flow.notify($, id)","since":"","deprecated":false},{"type":"method","name":"Flow.test()","signature":"Flow.test(name, source, [config], init)","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(flowstream, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('remove')","signature":"Flow.on('remove', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('stats')","signature":"Flow.on('stats', function(id, stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(flowstream) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"type","name":"FlowStream schema","signature":"{ id, name, components, design, variables, ... }","since":"","deprecated":false},{"type":"config","name":"proxytimeout","signature":"schema.proxytimeout","since":"0.0.18","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, [data])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(id, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(obj)","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.restart()","signature":"flowstream.restart()","since":"","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"flowstream.edit()","signature":"flowstream.edit([url])","since":"0.0.16","deprecated":false},{"type":"type","name":"Component","signature":"exports.* in <script total>","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 / exports.outputs","since":"","deprecated":false},{"type":"type","name":"instance","signature":"instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","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() {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, [data])","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(error)","since":"","deprecated":false},{"type":"method","name":"instance.debug()","signature":"instance.debug(a, [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save([redraw])","since":"","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(config)","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(text, [data], [encoding])","since":"","deprecated":false},{"type":"property","name":"instance.cache","signature":"instance.cache","since":"","deprecated":false},{"type":"property","name":"instance.repo","signature":"instance.repo","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, [progress])","since":"0.0.19","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"event","name":"instance.main.on('reset')","signature":"instance.main.on('reset', function() {})","since":"","deprecated":false},{"type":"class","name":"Message","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send(output, [data], [clone], [check])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end()","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5 [path or URL ...] [port]","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwTf7Ix61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/flowstream/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"FlowStream","summary":"La variable globale Flow, les FlowStreams en cours d'exécution, les composants, les instances, les messages et la commande flow5.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/flowstream/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# FlowStream\n\n> La variable globale Flow, les FlowStreams en cours d'exécution, les composants, les instances, les messages et la commande flow5.\n\nMéthodes, propriétés et événements de la variable globale `Flow`, d'un FlowStream en cours d'exécution (`Flow.instances[id]`), des définitions de composants, des instances de composants et des messages, ainsi que la commande `flow5`. Pour une introduction avec des exemples, lis le guide [FlowStream](../../guides/flowstream/).\n\n## API\n\n### Flow / FlowStream\n\nType: `class`\n\nL'objet global du moteur FlowStream.\n\n`Flow` et `FlowStream` sont le même objet. Il charge les flux, les conserve dans `Flow.instances` et émet les événements `load`, `save` et `remove`. Les flux en cours d'exécution sont des objets désignés ici par `flowstream`.\n\nExample: Lister les flux en cours d'exécution\n```js\nfor (var id in Flow.instances)\n\tconsole.log(id, Flow.instances[id].stats);\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nDémarre un FlowStream à partir de son schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Le schéma du FlowStream |\n| `callback` | `Function` | no |  | `function(err, flowstream)` |\n\nLes clés manquantes reçoivent des valeurs par défaut : un `id` aléatoire, `name` = `id`, des `components`, `design`, `sources` et `variables` vides. Lorsqu'un FlowStream avec le même `id` est en cours d'exécution, il est rechargé avec le nouveau schéma. Le callback s'exécute une fois les composants et le design chargés. Voir [FlowStream](../../guides/flowstream/) pour les clés du schéma.\n\nExample: Charger un fichier\n```js\nvar schema = (await F.readfile(PATH.root('orders.json'), 'utf8')).parseJSON();\nFlow.load(schema, function(err, flowstream) {\n\terr && console.error(err);\n});\n```\n\nExample: Exécuter dans un worker thread\n```js\nFlow.load({ id: 'import', worker: 'worker', components: {}, design: {} });\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')` | Répertoire contenant les fichiers .flow |\n| `callback` | `Function` | no |  | Appelé une fois tous les fichiers chargés |\n\nLit chaque fichier `*.flow` (un schéma JSON) du répertoire et le charge avec `Flow.load()`. Les fichiers avec `-bk` ou `_bk` dans le nom sont ignorés. Le répertoire par défaut est `/flowstreams/` à la racine de l'application. Le framework l'appelle une fois au démarrage : tu n'en as donc besoin que pour d'autres répertoires. Le fichier `index.flow` d'un plugin est chargé avec le plugin.\n\nExample: Un autre répertoire\n```js\nFlow.init(PATH.root('data/flows'), function() {\n\tconsole.log('Loaded:', Object.keys(Flow.instances));\n});\n```\n\n### Flow.reload(schema, [restart])\n\nType: `method`\n\nApplique un nouveau schéma à un FlowStream en cours d'exécution.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Le nouveau schéma |\n| `restart` | `Boolean` | no | `false` | Redémarrer le worker |\n\nReturns: `Boolean` `true` lorsque le FlowStream existe\n\nLe schéma doit avoir l'`id` d'un FlowStream en cours d'exécution. Les composants et le design sont remplacés sur place et les composants supprimés sont désenregistrés. Avec `restart` (workers uniquement), le worker est arrêté puis redémarré avec son schéma actuel ; le nouveau schéma n'est pas appliqué. Renvoie `false` lorsqu'aucun FlowStream n'a cet id.\n\n### Flow.remove(id)\n\nType: `method`\n\nArrête et retire un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id du FlowStream |\n\nFerme toutes les instances, termine le worker, retire le FlowStream de `Flow.instances` et émet `remove`.\n\nExample: Supprimer\n```js\nFlow.remove('orders');\n```\n\n### Flow.restart(id)\n\nType: `method`\n\nRedémarre un FlowStream qui s'exécute dans un worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id du FlowStream |\n\nReturns: `Boolean` `true` lorsqu'il est trouvé\n\nArrête le worker thread ou le processus enfant ; il est redémarré automatiquement avec le schéma actuel au bout d'une seconde. Renvoie `true` lorsque le FlowStream existe (sinon `undefined`). Un FlowStream du processus principal est arrêté et n'est pas redémarré.\n\n### Flow.socket(id, websocket, [verify], [check])\n\nType: `method`\n\nConnecte l'éditeur Total.js Flow à un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id du FlowStream |\n| `websocket` | `WebSocket` | yes |  | Le WebSocket de la route |\n| `verify` | `Function` | no |  | `function(client, next)` |\n| `check` | `Function` | no |  | `function(client, message)` renvoie `true` ou une erreur |\n\nPasse l'objet WebSocket d'une route `SOCKET`. `verify(client, next)` peut accepter un nouveau client avant qu'il ne reçoive le flux (appelle `next()`), et `check(client, message)` peut bloquer des commandes individuelles : renvoie `true` pour autoriser, ou un texte d'erreur. Un id inconnu ferme le WebSocket.\n\nExample: Route pour l'éditeur\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', function($) {\n\t\t$.autodestroy();\n\t\tFlow.socket($.params.id, $, null, function(client, msg) {\n\t\t\treturn client.user.sa ? true : 'Only for admins';\n\t\t});\n\t});\n};\n```\n\n### Flow.notify($, id)\n\nType: `method`\n\nTransmet une requête HTTP au délégué notify d'une instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | Le contrôleur de la route |\n| `id` | `String` | yes |  | `flowid-instanceid` |\n\n`id` vaut `flowid-instanceid` (les parties `-` supplémentaires deviennent `params`). Le délégué `notify` de l'instance reçoit `{ id, method, headers, query, body, url, ip, params }`, et l'éditeur reçoit le même objet. Ensuite, la réponse redirige vers `?REDIRECT=url`, envoie une petite page qui ferme la fenêtre (pour les navigateurs) ou un JSON de succès.\n\nExample: Routes\n```js\nROUTE('GET /notify/{id}/', $ => Flow.notify($, $.params.id));\nROUTE('POST /notify/{id}/ <1MB', $ => Flow.notify($, $.params.id));\n```\n\nExample: Dans un composant\n```js\ninstance.notify = function(data) {\n\tinstance.send('output', data.body);\n};\n```\n\n### Flow.test(name, source, [config], init)\n\nType: `method`\n\nCharge un composant dans un flux de test.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Id du composant |\n| `source` | `String` | yes |  | Source du composant |\n| `config` | `Object` | no | `{}` | Configuration de l'instance |\n| `init` | `Function` | yes |  | `function(test)` |\n\nCrée un flux avec le composant (id d'instance `component`) et une instance auxiliaire connectée à toutes ses entrées et sorties. `init(test)` reçoit l'objet `Test` :\n\n| Membre | Usage |\n| --- | --- |\n| `test.send(input, data)` | Envoie des données à une entrée du composant (alias `input`) |\n| `test.message = function($, data)` | Reçoit ce que le composant envoie à ses sorties |\n| `test.status = function(status)` | Reçoit le statut du composant |\n| `test.debug = function(...)` | Reçoit les appels à `instance.debug()` |\n| `test.configure = function(config)` | Appelée après une reconfiguration |\n| `test.trigger(data)` | Exécute le délégué `trigger` |\n| `test.reconfigure(config)` | Modifie la configuration |\n| `test.variables(obj)` | Définit les variables |\n| `test.assert(ok, text)`, `test.ok(text)`, `test.fail(text)` | Affichent le résultat ; `fail` lève une exception |\n\nUne erreur dans le flux termine le processus.\n\nExample: Test\n```js\nvar source = await F.readfile(PATH.root('components/uppercase.html'), 'utf8');\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nLes FlowStreams en cours d'exécution, par id.\n\nReturns: `Object`\n\nUn objet : id du FlowStream → objet `flowstream`. `Flow.db` contient le dernier schéma de chaque FlowStream (mis à jour à chaque enregistrement).\n\nExample: En obtenir un\n```js\nvar flowstream = Flow.instances.orders;\n```\n\n### Flow.on('load', function(flowstream, schema) {})\n\nType: `event`\n\nUn FlowStream est chargé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | Le FlowStream en cours d'exécution |\n| `schema` | `Object` | yes |  | Le schéma |\n\nÉmis après que `Flow.load()` a chargé les composants et le design.\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nLe schéma d'un FlowStream a changé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Le schéma complet |\n\nÉmis environ 5 secondes après une modification dans l'éditeur ou un appel à `instance.save()`. Le schéma contient `id`, `name`, `components`, `design`, `variables`, `sources`, `paused` et les autres clés. Stocke-le toi-même, par exemple dans un fichier `.flow`. Les flux avec `readonly: true` ne sont pas enregistrés.\n\nExample: Enregistrer dans un fichier\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### Flow.on('remove', function(schema) {})\n\nType: `event`\n\nUn FlowStream a été retiré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Le schéma |\n\nÉmis par `Flow.remove()` avec le dernier schéma du FlowStream retiré.\n\n### Flow.on('stats', function(id, stats) {})\n\nType: `event`\n\nCompteurs d'un FlowStream qui s'exécute dans un worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id du FlowStream |\n| `stats` | `Object` | yes |  | Compteurs |\n\nÉmis toutes les 15 secondes pour chaque FlowStream exécuté dans un worker thread ou un processus enfant. `stats` possède `paused`, `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` et `pid`.\n\n### ON('flowstream', function(flowstream) {})\n\nType: `event` · Since: `0.0.16`\n\nUn FlowStream a démarré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | Le FlowStream en cours d'exécution |\n\nÉvénement global du framework émis lorsqu'un FlowStream est créé, y compris après le redémarrage automatique d'un worker.\n\nExample: Journal\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream', flowstream.id);\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nUne erreur s'est produite dans un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Détails de l'erreur |\n\nLes erreurs sont affichées dans la console et émises sous forme de cet événement global. `meta` possède `id` et `name` (du FlowStream), `error`, `source`, `instanceid` et `componentid`.\n\nExample: Auditer les erreurs\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### { id, name, components, design, variables, ... }\n\nType: `type`\n\nL'objet qui décrit un FlowStream.\n\n`components` associe un id de composant à son code source. `design` associe un id d'instance à `{ component, config, connections, x, y, note, tab }` ; `connections` associe un id de sortie à un tableau de `{ id, index }` (l'instance cible et son entrée). Autres clés : `variables`, `sources` (TMS), `worker`, `memory` (avec `worker` : la limite du heap du worker thread ou du processus enfant en Mo), `proxypath`, `cloning`, `paused`, `readonly`, `import`, `initscript`, `env`, `directory` et `asfiles` (`true` compile les composants dans des fichiers de `/tmp/`). Les clés descriptives comme `icon`, `color`, `author`, `version` et `readme` sont affichées dans l'éditeur.\n\nExample: Deux instances connectées\n```json\n{\n\t\"id\": \"demo\",\n\t\"name\": \"Demo\",\n\t\"components\": { \"uppercase\": \"<script total>...</script>\", \"print\": \"<script total>...</script>\" },\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\": {}\n}\n```\n\n### schema.proxytimeout\n\nType: `config` · Since: `0.0.18`\n\nTimeout du proxy d'un worker avec proxypath.\n\nReturns: `Number`\n\nMillisecondes du timeout du proxy qui transmet au worker les requêtes sous `proxypath`. Il est appliqué quand le schéma est rechargé dans le FlowStream en cours d'exécution (`Flow.load()` avec le même id ou `Flow.reload()`).\n\nExample: Recharger avec un timeout\n```js\nFlow.reload({ id: 'api', worker: 'worker', proxypath: '/api/', proxytimeout: 10000, components: components, design: design });\n```\n\n### flowstream.stats\n\nType: `property`\n\nCompteurs du FlowStream.\n\nReturns: `Object`\n\n`messages` (total), `pending`, `memory` (octets), `minutes` (uptime), `errors` (le nombre des dernières erreurs, 10 au plus), `mm` (messages de la dernière minute) et `paused`. Pour un flux du processus principal, `online` est le nombre d'éditeurs connectés. Pour un worker, les valeurs arrivent toutes les 15 secondes.\n\n### flowstream.trigger(id, [data])\n\nType: `method`\n\nExécute le délégué trigger des instances.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id d'instance, `@componentid` ou `#name` |\n| `data` | `Object` | no |  | Passé au délégué |\n\nReturns: `Object` Le flowstream\n\nAppelle `instance.trigger(data)` de l'instance `id`, de toutes les instances d'un composant (`@componentid`) ou d'un nom de composant (`#name`). Rien ne s'exécute tant que le flux est en pause.\n\nExample: Démarrer tous les minuteurs\n```js\nFlow.instances.orders.trigger('@timer');\n```\n\n### flowstream.send(id, data, [callback])\n\nType: `method`\n\nEnvoie des données dans une instance et attend le résultat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Cible, éventuellement avec `/input` |\n| `data` | `Object` | yes |  | Charge utile |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nCrée un nouveau message avec `data` et le passe au délégué `message` de l'instance (`id`, `@componentid` ou `#name` ; la première correspondance). Ajoute `/inputid` pour définir `$.input`. Le callback s'exécute lorsque le message et tous ses clones sont terminés, avec `{ error, repo, data, count, cloned, duration, meta: { id, component } }`.\n\nExample: Appeler un flux depuis une API\n```js\nNEWACTION('Orders/process', {\n\taction: function($, model) {\n\t\tFlow.instances.orders.send('@order/input', model, function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback(response.data);\n\t\t});\n\t}\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nEnvoie un message à toutes les instances correspondantes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Options |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nComme `send()`, mais pour chaque instance correspondante. `opt.id` est la cible (`id`, `@componentid` ou `#name`), `opt.data` les données utiles, `opt.vars` et `opt.repo` les `$.vars` et `$.repo`, `opt.timeout` un délai en ms (le message se termine avec l'erreur `408`). `opt.uid` et `opt.ref` reviennent dans la réponse. Le callback s'exécute pour chaque cible (pour un flux dans un worker, seulement pour la première), ou avec `404` lorsque rien ne correspond.\n\nExample: Exec avec un délai\n```js\nFlow.instances.orders.exec({ id: '#Validate', data: model, timeout: 5000, uid: model.id }, function(err, response) {\n\tconsole.log(response.uid, response.data);\n});\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` reprend |\n\nReturns: `Object` Le flowstream\n\nUn flux en pause ne délivre pas de messages. Sans argument, l'état est basculé. Le délégué `pause` de chaque instance est appelé.\n\n### flowstream.variables(obj)\n\nType: `method`\n\nRemplace les variables du FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Nouvelles variables |\n\nReturns: `Object` Le flowstream\n\nAppelle le délégué `variables` de chaque instance (et `vary('variables')` pour un flux du processus principal), envoie les variables à l'éditeur et enregistre le flux.\n\nExample: Renouveler un jeton\n```js\nFlow.instances.orders.variables({ token: newtoken });\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 |  | Id de l'instance |\n| `config` | `Object` | yes |  | Valeurs à fusionner |\n\nReturns: `Object` Le flowstream\n\nLes valeurs sont fusionnées dans `instance.config`, le délégué `configure` est appelé, l'éditeur est mis à jour et le flux est enregistré.\n\n### flowstream.export(callback)\n\nType: `method`\n\nLit le schéma courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)` |\n\nLe callback reçoit le schéma complet, le même objet que celui de l'événement `save`.\n\nExample: Sauvegarde\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('backup.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.restart()\n\nType: `method`\n\nRedémarre un FlowStream qui s'exécute dans un worker.\n\nFerme les connexions de l'éditeur et termine le worker ; il redémarre automatiquement avec le schéma courant.\n\n### flowstream.remove()\n\nType: `method`\n\nRetire le FlowStream.\n\nÉquivaut à `Flow.remove(flowstream.id)`.\n\n### flowstream.edit([url])\n\nType: `method` · Since: `0.0.16`\n\nConnecte le FlowStream à un proxy d'édition distant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `'wss://flow.totaljs.com/{0}/'` | URL WebSocket du proxy |\n\nReturns: `WebSocketClient` Le client\n\nOuvre un client WebSocket vers l'URL (`{0}` est remplacé par l'id du FlowStream) et permet à l'éditeur de passer par celui-ci : l'application n'a donc pas besoin d'une route WebSocket publique. Une connexion précédente est fermée. Renvoie le client WebSocket.\n\nExample: Édition à distance\n```js\nFlow.instances.orders.edit();\n```\n\n### exports.* in <script total>\n\nType: `type`\n\nLa définition d'un composant FlowStream.\n\nLa partie serveur du composant définit des propriétés de `exports` :\n\n| Propriété | Signification |\n| --- | --- |\n| `name`, `icon`, `color`, `group`, `version`, `author` | Affichées dans l'éditeur |\n| `type` | Par exemple `input`, `output` ou `config` ; ces types apparaissent dans les listes de `io()` |\n| `inputs`, `outputs` | Tableaux de `{ id, name }` |\n| `config` | Configuration par défaut des nouvelles instances |\n| `npm` | Paquets NPM installés avant l'enregistrement |\n| `permissions`, `meta` | Données personnalisées transmises à l'éditeur |\n| `make` | `function(instance, config)` pour chaque instance |\n| `install`, `uninstall` | `function(component)` lorsque le composant est enregistré et retiré |\n| `call` | `function(data, callback)` appelée par l'éditeur avec `@componentid` |\n\nLes autres parties du fichier : `<settings>` (le formulaire de configuration), `<body>`, `<style>`, `<script>` (code de l'éditeur), `<readme>`, `<template>` et `<schema>`.\n\nExample: Composant minimal\n```html\n<script total>\n\texports.name = 'Print';\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.make = function(instance) {\n\t\tinstance.message = function($) {\n\t\t\tconsole.log($.data);\n\t\t\t$.end();\n\t\t};\n\t};\n</script>\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 |  | L'instance |\n| `config` | `Object` | yes |  | Sa configuration |\n\nS'exécute pour chaque instance placée sur le canevas, et à nouveau lorsque le code du composant change. `config` vaut `instance.config`. Assigne ici les délégués de l'instance.\n\nExample: Intervalle\n```js\nexports.make = function(instance, config) {\n\tvar timer;\n\tinstance.configure = function() {\n\t\tclearInterval(timer);\n\t\ttimer = setInterval(() => instance.send('output', { ts: NOW }), (instance.config.interval || 10) * 1000);\n\t};\n\tinstance.close = () => clearInterval(timer);\n\tinstance.configure();\n};\n```\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nLes entrées et les sorties d'un composant.\n\nReturns: `Array`\n\nDes tableaux de `{ id, name }`. L'`id` est ce que contient `$.input` et ce qu'utilisent `$.send(id)` et `instance.send(id)`. Une instance peut les redéfinir avec ses propres `inputs` / `outputs`.\n\nExample: Deux sorties\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'OK' }, { id: 'error', name: 'Error' }];\n```\n\n### instance\n\nType: `type`\n\nUne instance placée d'un composant.\n\nLe premier argument de `exports.make()`. Propriétés : `id`, `component` (id du composant), `config`, `cache`, `main` (le moteur du flux), `module` (le composant), `env`, `stats` (`pending`, `input`, `output`, `duration`, `destroyed`), `instances` (toutes les instances du flux) et `components`.\n\nDélégués que tu peux assigner : `message($)`, `message_INPUTID($)`, `configure(config)`, `close()`, `init()` (après le premier chargement), `refresh()` (après chaque modification du design), `trigger(data)`, `notify(data)`, `call(data, callback)`, `service(minutes)` (chaque minute), `pause(is)`, `variables(obj)`, `secrets(obj)` et `vary(type)`.\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nReçoit un message sur une entrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | Le message |\n\n`$.input` est l'id de l'entrée. `instance.message_INPUTID` ne reçoit que les messages d'une seule entrée ; lorsque les deux existent, les deux sont appelés. Un message qui n'est pas transmis plus loin doit être terminé avec `$.end()`.\n\nExample: Router selon l'entrée\n```js\ninstance.message = function($) {\n\tif ($.input === 'reset') {\n\t\tcount = 0;\n\t\t$.end();\n\t} else {\n\t\tcount++;\n\t\t$.send('output', { count: count });\n\t}\n};\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nLa configuration a changé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | La configuration |\n\nAppelé après une modification dans l'éditeur ou un appel à `reconfigure()`. `instance.config` contient déjà les nouvelles valeurs.\n\n### instance.close = function() {}\n\nType: `delegate`\n\nL'instance est en cours de retrait.\n\nAppelé lorsque l'instance est retirée du design, que le composant est désenregistré ou que le flux se termine. Arrête ici les minuteurs et ferme les connexions.\n\n### instance.send(output, [data])\n\nType: `method`\n\nDémarre un nouveau message depuis une sortie ou depuis toutes les sorties.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id de la sortie, ou `null` pour toutes les sorties |\n| `data` | `Object` | no |  | Données utiles |\n\nReturns: `Number` Nombre de messages envoyés\n\nEnvoie `data` à chaque instance connectée à la sortie. Avec `output` à `null`, il envoie à toutes les sorties. Pour la deuxième connexion et les suivantes, les données sont clonées (sauf avec `cloning: false`). Renvoie le nombre de messages envoyés ; `0` quand rien n'est connecté ou que le flux est en pause.\n\nExample: Depuis un timer\n```js\nsetInterval(() => instance.send('output', { ts: NOW }), 1000);\n```\n\nExample: Toutes les sorties\n```js\ninstance.send(null, { ts: NOW });\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nCrée un message sans l'envoyer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Charge utile |\n\nReturns: `Message` Un nouveau message\n\nLe message appartient à l'instance ; définis `$.repo`, écoute `end` puis appelle `$.send(output)`.\n\nExample: Attendre la fin\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.on('end', function($) {\n\tconsole.log('Done', $.data);\n});\nmsg.send('output');\n```\n\n### instance.status([data], [delay])\n\nType: `method`\n\nDéfinit le statut affiché sous l'instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Une valeur JSON quelconque |\n| `delay` | `Number` | no |  | Limitation en ms |\n\nLe statut est envoyé à l'éditeur et émis comme `status` sur `instance.main`. Avec `delay` (ms), de nombreux appels sont fusionnés en une seule mise à jour. Sans arguments, le dernier statut est renvoyé.\n\nExample: Compteur\n```js\ninstance.status({ count: count }, 1000);\n```\n\n### instance.dashboard([data])\n\nType: `method`\n\nEnvoie des données au tableau de bord de l'éditeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Une valeur JSON quelconque |\n\nLes données sont conservées et envoyées à l'éditeur ; sans arguments, les dernières données sont renvoyées.\n\n### instance.throw(error)\n\nType: `method`\n\nSignale une erreur de l'instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | L'erreur |\n\nL'erreur est ajoutée aux 10 dernières erreurs du flux (`instance.main.errors`), affichée dans l'éditeur, affichée dans la console et émise comme `ON('flowstream_error')`. `$.throw(error)` fait de même et définit `$.error`.\n\nExample: Dans un callback\n```js\nRESTBuilder.GET(config.url).callback(function(err, response) {\n\tif (err) {\n\t\tinstance.throw(err);\n\t\t$.end();\n\t} else\n\t\t$.send('output', response);\n});\n```\n\n### instance.debug(a, [b], [c], [d])\n\nType: `method`\n\nÉmet un événement de debug.\n\nÉmet `debug` sur `instance.main` avec l'instance et les arguments. `Flow.test()` le transmet à `test.debug`.\n\n### instance.save([redraw])\n\nType: `method`\n\nEnregistre l'instance après une modification depuis le code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `redraw` | `Boolean` | no | `true` | Redessiner l'instance dans l'éditeur |\n\nUtilise-la après avoir modifié `instance.config`, `x`, `y`, `note`, `inputs` ou `outputs` dans le code. Le flux est enregistré (l'événement `save` suit environ 5 secondes plus tard) et, sauf si `redraw` vaut `false`, l'éditeur redessine l'instance.\n\nExample: Mémoriser une valeur\n```js\ninstance.config.lastid = $.data.id;\ninstance.save();\n```\n\nExample: Sans redessiner\n```js\ninstance.config.counter++;\ninstance.save(false);\n```\n\n### instance.reconfigure(config)\n\nType: `method`\n\nModifie la configuration de cette instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Valeurs à fusionner |\n\nÉquivaut à `flowstream.reconfigure(instance.id, config)` appelée depuis le composant.\n\n### instance.replace(text, [data], [encoding])\n\nType: `method`\n\nRemplace les {variables} dans un texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String|Object` | yes |  | Texte avec des placeholders |\n| `data` | `Object` | no |  | Valeurs supplémentaires |\n| `encoding` | `String|Function` | no |  | Encodage des valeurs |\n\nReturns: `String` Le texte\n\nUn `{name}` (ou `{{name}}`) prend la valeur dans les variables du flux, les variables globales, les secrets, `{hostname}` (l'origine plus `proxypath`) ou l'objet `data` (clés imbriquées avec des points). `encoding` peut valoir `url`, `json`, `querify` ou une `function(value, key)`. Pour un objet, chaque valeur de type chaîne est remplacée. Dans un message, utilise `$.variables()` (alias `$.replace()`), où `data` vaut par défaut le message.\n\nExample: URL\n```js\nvar url = instance.replace('https://api.example.com/{token}/orders/?id={id}', { id: 5 }, 'url');\n```\n\n### instance.cache\n\nType: `property`\n\nUn objet en mémoire pour les données d'exécution de l'instance.\n\nReturns: `Object`\n\nUn objet simple en mémoire, conservé par le flux pour l'id de l'instance : lorsque l'instance est réinitialisée (par exemple quand son composant est mis à jour), elle récupère le même objet. Il n'est pas enregistré, il est donc vide après un redémarrage.\n\nExample: Dernière valeur\n```js\ninstance.message = function($) {\n\tinstance.cache.last = $.data;\n\t$.send('output');\n};\n```\n\n### instance.repo\n\nType: `property` · Since: `0.0.17`\n\nDonnées persistantes de l'instance, stockées dans le design.\n\nReturns: `Object`\n\nUn objet enregistré dans le schéma avec l'instance. Il survit à un rechargement et à un redémarrage, et l'éditeur le garde inchangé quand il enregistre le design. Appelle `instance.save()` après une modification.\n\nExample: Conserver un curseur\n```js\ninstance.repo.lastid = $.data.id;\ninstance.save();\n```\n\n### instance.activity(key, name, [progress])\n\nType: `method` · Since: `0.0.19`\n\nSignale une activité en cours de l'instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Id de l'activité |\n| `name` | `String` | yes |  | Description |\n| `progress` | `Number` | no |  | Pourcentage |\n\nCrée ou met à jour l'activité `key`, l'affiche dans l'éditeur et émet `activity` sur `instance.main` avec `(instance, key, name, progress)`. Un `name` vide ou une `progress` de `100` la supprime. Les activités des instances retirées du design sont abandonnées.\n\nExample: Progression\n```js\ninstance.activity('sync', 'Synchronizing', 40);\n// ...\ninstance.activity('sync', 'Synchronizing', 100);\n```\n\n### instance.main\n\nType: `property`\n\nLe moteur du flux de l'instance.\n\nReturns: `FlowStream`\n\nMembres utiles : `variables`, `secrets`, `stats` (avec `online`, le nombre d'éditeurs connectés), `errors`, `paused`, `env`, `activities`, `find(id)` (une instance), `instances()` (instances prêtes), `send('ID__OUTPUT', data)`, `trigger('ID__INPUT', data)` (envoie un nouveau message à une entrée), `pause(is)`, `save()` et `restart()` (redémarre le worker du flux ; dans le processus principal, il demande au gestionnaire de processus de Total.js de redémarrer l'application). Il émet les événements `status`, `debug`, `activity`, `message`, `end` et `reset`.\n\nExample: Envoyer à une autre instance\n```js\ninstance.main.trigger('b1__input', { id: 1 });\n```\n\n### instance.main.on('reset', function() {})\n\nType: `event`\n\nLes erreurs du flux ont été réinitialisées.\n\nÉmis par le moteur de flux quand l'éditeur envoie la commande reset : les dernières erreurs du flux (`instance.main.errors`) sont d'abord effacées, puis l'événement s'exécute sans arguments. Dans un flux qui s'exécute dans un worker, il est émis dans le worker. Le moteur reste en place quand une instance est recréée, donc retire l'écouteur dans `instance.close`.\n\nExample: Réinitialiser un compteur\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\n### $\n\nType: `class`\n\nUn message qui circule dans le flux.\n\nPropriétés : `data`, `repo` (partagé par tous les clones), `vars`, `input`, `output`, `from`/`fromid`, `to`/`toid` (instances), `instance`, `main`, `id`, `count`, `duration`, `error`, `controller`, et, depuis le contrôleur, `user`, `body`, `query`, `params`, `headers`, `ip`, `language`.\n\nMéthodes : `send()`, `end()` (alias `destroy()`), `rewrite(data)`, `clone()`, `variables()`, `timeout()`, `status()`, `dashboard()`, `debug()`, `throw()` et `on(name, fn)`. Événements : `end` (le message et tous ses clones sont terminés), `timeout` et `message`.\n\n### $.send(output, [data], [clone], [check])\n\nType: `method`\n\nEnvoie le message vers une sortie ou vers toutes les sorties.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id de la sortie, ou `null` pour toutes les sorties |\n| `data` | `Object` | no |  | Nouveau payload |\n| `clone` | `Boolean` | no | `the `cloning` of the flow` | Cloner les données |\n| `check` | `Function` | no |  | `function(from, to, output, input)` renvoie un Boolean |\n\nReturns: `Number` Nombre de cibles\n\nEnvoie un clone du message à chaque instance connectée à la sortie. Avec `output` à `null`, il envoie vers toutes les sorties : une sortie sans cible prête est ignorée, les autres sorties reçoivent quand même le message, et le message se termine une seule fois, quand tous ses clones se terminent. `data` remplace le payload ; `clone` (par défaut : le `cloning` du flow) copie en profondeur les données objet pour chaque cible. `check(from, to, output, input)` est appelée pour chaque cible d'une sortie nommée (`from` et `to` sont des instances) ; renvoie `false` pour ignorer la cible. Renvoie le nombre de cibles ; avec `0`, le message se termine.\n\nExample: Transmettre\n```js\ninstance.message = function($) {\n\t$.data.checked = true;\n\t$.send('output');\n};\n```\n\nExample: Ignorer certaines cibles\n```js\n$.send('output', null, null, function(from, to, output, input) {\n\treturn to.component !== 'debug';\n});\n```\n\nExample: Toutes les sorties\n```js\ninstance.message = function($) {\n\t$.send(null);\n};\n```\n\n### $.end()\n\nType: `method`\n\nTermine le message.\n\nAppelle-la lorsque le message n'est pas transmis plus loin. Lorsque le message et tous ses clones sont terminés, son événement `end` est déclenché (ainsi que le `callback` de `flowstream.send()`).\n\nExample: S'arrêter ici\n```js\ninstance.message = function($) {\n\tsave($.data);\n\t$.end();\n};\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nDéfinit un délai pour les instances suivantes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function($)` |\n| `time` | `Number` | yes |  | Millisecondes |\n\nReturns: `Message`\n\nChaque clone envoyé après cet appel doit être traité en moins de `time` ms ; sinon il se termine avec `$.error = 408` et le callback s'exécute. `$.totaltimeout([callback], time)` limite plutôt le message entier.\n\nExample: Délai\n```js\n$.timeout(function($) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n\n### flow5 [path or URL ...] [port]\n\nType: `command`\n\nExécute des schémas FlowStream depuis la ligne de commande.\n\nCharge chaque fichier JSON (un schéma, ou un objet contenant plusieurs schémas) ou URL HTTPS, démarre un serveur HTTP sur le port (`8000` par défaut) avec la route `SOCKET /flowstreams/{id}/` et les routes `/notify/{id}/`, et affiche le lien de l'éditeur pour chaque flux. Les modifications faites dans l'éditeur sont réécrites dans les fichiers locaux. Sans arguments, elle affiche l'aide.\n\nExample: Deux flux sur le port 8001\n```bash\nflow5 orders.json import.json 8001\n```\n","entries":[{"type":"class","name":"Flow","signature":"Flow / FlowStream","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":"method","name":"Flow.reload()","signature":"Flow.reload(schema, [restart])","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.restart()","signature":"Flow.restart(id)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [verify], [check])","since":"","deprecated":false},{"type":"method","name":"Flow.notify()","signature":"Flow.notify($, id)","since":"","deprecated":false},{"type":"method","name":"Flow.test()","signature":"Flow.test(name, source, [config], init)","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(flowstream, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('remove')","signature":"Flow.on('remove', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('stats')","signature":"Flow.on('stats', function(id, stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(flowstream) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"type","name":"FlowStream schema","signature":"{ id, name, components, design, variables, ... }","since":"","deprecated":false},{"type":"config","name":"proxytimeout","signature":"schema.proxytimeout","since":"0.0.18","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, [data])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(id, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(obj)","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.restart()","signature":"flowstream.restart()","since":"","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"flowstream.edit()","signature":"flowstream.edit([url])","since":"0.0.16","deprecated":false},{"type":"type","name":"Component","signature":"exports.* in <script total>","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 / exports.outputs","since":"","deprecated":false},{"type":"type","name":"instance","signature":"instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","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() {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, [data])","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(error)","since":"","deprecated":false},{"type":"method","name":"instance.debug()","signature":"instance.debug(a, [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save([redraw])","since":"","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(config)","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(text, [data], [encoding])","since":"","deprecated":false},{"type":"property","name":"instance.cache","signature":"instance.cache","since":"","deprecated":false},{"type":"property","name":"instance.repo","signature":"instance.repo","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, [progress])","since":"0.0.19","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"event","name":"instance.main.on('reset')","signature":"instance.main.on('reset', function() {})","since":"","deprecated":false},{"type":"class","name":"Message","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send(output, [data], [clone], [check])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end()","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5 [path or URL ...] [port]","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwTf7Ix61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/flowstream/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"FlowStream","summary":"L'oggetto globale Flow, i FlowStream in esecuzione, componenti, istanze, messaggi e il comando flow5.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/flowstream/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# FlowStream\n\n> L'oggetto globale Flow, i FlowStream in esecuzione, componenti, istanze, messaggi e il comando flow5.\n\nMetodi, proprietà ed eventi dell'oggetto globale `Flow`, di un FlowStream in esecuzione (`Flow.instances[id]`), delle definizioni dei componenti, delle istanze dei componenti e dei messaggi, più il comando `flow5`. Per un'introduzione con esempi leggi la guida [FlowStream](../../guides/flowstream/).\n\n## API\n\n### Flow / FlowStream\n\nType: `class`\n\nL'oggetto globale del motore FlowStream.\n\n`Flow` e `FlowStream` sono lo stesso oggetto. Carica i flussi, li conserva in `Flow.instances` ed emette gli eventi `load`, `save` e `remove`. I flussi in esecuzione sono oggetti descritti qui come `flowstream`.\n\nExample: Elencare i flussi in esecuzione\n```js\nfor (var id in Flow.instances)\n\tconsole.log(id, Flow.instances[id].stats);\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nAvvia un FlowStream dal suo schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Lo schema del FlowStream |\n| `callback` | `Function` | no |  | `function(err, flowstream)` |\n\nLe chiavi mancanti ricevono valori predefiniti: un `id` casuale, `name` = `id`, `components`, `design`, `sources` e `variables` vuoti. Quando un FlowStream con lo stesso `id` è in esecuzione, viene invece ricaricato con il nuovo schema. La callback viene eseguita quando i componenti e il design sono caricati. Vedi [FlowStream](../../guides/flowstream/) per le chiavi dello schema.\n\nExample: Caricare un file\n```js\nvar schema = (await F.readfile(PATH.root('orders.json'), 'utf8')).parseJSON();\nFlow.load(schema, function(err, flowstream) {\n\terr && console.error(err);\n});\n```\n\nExample: Eseguire in un worker thread\n```js\nFlow.load({ id: 'import', worker: 'worker', components: {}, design: {} });\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')` | Directory con i file .flow |\n| `callback` | `Function` | no |  | Chiamata quando tutti i file sono caricati |\n\nLegge ogni file `*.flow` (uno schema JSON) della directory e lo carica con `Flow.load()`. I file con `-bk` o `_bk` nel nome vengono saltati. La directory predefinita è `/flowstreams/` nella radice dell'app. Il framework lo chiama una volta all'avvio, quindi ti serve solo per altre directory. Il file `index.flow` di un plugin viene caricato con il plugin.\n\nExample: Un'altra directory\n```js\nFlow.init(PATH.root('data/flows'), function() {\n\tconsole.log('Loaded:', Object.keys(Flow.instances));\n});\n```\n\n### Flow.reload(schema, [restart])\n\nType: `method`\n\nApplica un nuovo schema a un FlowStream in esecuzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Il nuovo schema |\n| `restart` | `Boolean` | no | `false` | Riavviare il worker |\n\nReturns: `Boolean` `true` quando il FlowStream esiste\n\nLo schema deve avere l'`id` di un FlowStream in esecuzione. I componenti e il design vengono sostituiti sul posto e i componenti rimossi vengono deregistrati. Con `restart` (solo worker) il worker viene terminato e riavviato con il suo schema attuale; il nuovo schema non viene applicato. Restituisce `false` quando nessun FlowStream ha questo id.\n\n### Flow.remove(id)\n\nType: `method`\n\nFerma e rimuove un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id del FlowStream |\n\nChiude tutte le istanze, termina il worker, rimuove il FlowStream da `Flow.instances` ed emette `remove`.\n\nExample: Rimuovere\n```js\nFlow.remove('orders');\n```\n\n### Flow.restart(id)\n\nType: `method`\n\nRiavvia un FlowStream che gira in un worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id del FlowStream |\n\nReturns: `Boolean` `true` se trovato\n\nTermina il worker thread o il processo figlio; viene riavviato automaticamente con lo schema attuale dopo un secondo. Restituisce `true` quando il FlowStream esiste (altrimenti `undefined`). Un FlowStream nel processo principale viene terminato e non viene riavviato.\n\n### Flow.socket(id, websocket, [verify], [check])\n\nType: `method`\n\nCollega l'editor Total.js Flow a un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id del FlowStream |\n| `websocket` | `WebSocket` | yes |  | Il WebSocket della route |\n| `verify` | `Function` | no |  | `function(client, next)` |\n| `check` | `Function` | no |  | `function(client, message)` restituisce `true` o un errore |\n\nPassa l'oggetto WebSocket di una route `SOCKET`. `verify(client, next)` può accettare un nuovo client prima che riceva il flusso (chiama `next()`), e `check(client, message)` può bloccare singoli comandi: restituisci `true` per consentire, oppure un testo di errore. Un id sconosciuto chiude il WebSocket.\n\nExample: Route per l'editor\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', function($) {\n\t\t$.autodestroy();\n\t\tFlow.socket($.params.id, $, null, function(client, msg) {\n\t\t\treturn client.user.sa ? true : 'Only for admins';\n\t\t});\n\t});\n};\n```\n\n### Flow.notify($, id)\n\nType: `method`\n\nPassa una richiesta HTTP al delegate notify di un'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | Il controller della route |\n| `id` | `String` | yes |  | `flowid-instanceid` |\n\n`id` è `flowid-instanceid` (ulteriori parti separate da `-` diventano `params`). Il delegate `notify` dell'istanza riceve `{ id, method, headers, query, body, url, ip, params }`, e l'editor riceve lo stesso oggetto. Poi la risposta reindirizza a `?REDIRECT=url`, invia una piccola pagina che chiude la finestra (per i browser) oppure un JSON di successo.\n\nExample: Route\n```js\nROUTE('GET /notify/{id}/', $ => Flow.notify($, $.params.id));\nROUTE('POST /notify/{id}/ <1MB', $ => Flow.notify($, $.params.id));\n```\n\nExample: In un componente\n```js\ninstance.notify = function(data) {\n\tinstance.send('output', data.body);\n};\n```\n\n### Flow.test(name, source, [config], init)\n\nType: `method`\n\nCarica un componente in un flusso di test.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Id del componente |\n| `source` | `String` | yes |  | Sorgente del componente |\n| `config` | `Object` | no | `{}` | Configurazione dell'istanza |\n| `init` | `Function` | yes |  | `function(test)` |\n\nCrea un flusso con il componente (id dell'istanza `component`) e un'istanza di supporto collegata a tutti i suoi input e output. `init(test)` riceve l'oggetto `Test`:\n\n| Membro | Uso |\n| --- | --- |\n| `test.send(input, data)` | Invia dati a un input del componente (alias `input`) |\n| `test.message = function($, data)` | Riceve ciò che il componente invia ai suoi output |\n| `test.status = function(status)` | Riceve lo stato del componente |\n| `test.debug = function(...)` | Riceve le chiamate a `instance.debug()` |\n| `test.configure = function(config)` | Chiamata dopo una riconfigurazione |\n| `test.trigger(data)` | Esegue il delegate `trigger` |\n| `test.reconfigure(config)` | Modifica la configurazione |\n| `test.variables(obj)` | Imposta le variabili |\n| `test.assert(ok, text)`, `test.ok(text)`, `test.fail(text)` | Stampano il risultato; `fail` lancia un'eccezione |\n\nUn errore nel flusso termina il processo.\n\nExample: Test\n```js\nvar source = await F.readfile(PATH.root('components/uppercase.html'), 'utf8');\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nI FlowStream in esecuzione, per id.\n\nReturns: `Object`\n\nUn oggetto: id del FlowStream → oggetto `flowstream`. `Flow.db` contiene l'ultimo schema di ogni FlowStream (aggiornato a ogni salvataggio).\n\nExample: Ottenerne uno\n```js\nvar flowstream = Flow.instances.orders;\n```\n\n### Flow.on('load', function(flowstream, schema) {})\n\nType: `event`\n\nUn FlowStream è stato caricato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | Il FlowStream in esecuzione |\n| `schema` | `Object` | yes |  | Lo schema |\n\nEmesso dopo che `Flow.load()` ha caricato i componenti e il design.\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nLo schema di un FlowStream è cambiato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | L'intero schema |\n\nEmesso circa 5 secondi dopo una modifica nell'editor o una chiamata a `instance.save()`. Lo schema contiene `id`, `name`, `components`, `design`, `variables`, `sources`, `paused` e le altre chiavi. Memorizzalo tu stesso, ad esempio in un file `.flow`. I flussi con `readonly: true` non vengono salvati.\n\nExample: Salvare in un file\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### Flow.on('remove', function(schema) {})\n\nType: `event`\n\nUn FlowStream è stato rimosso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Lo schema |\n\nEmesso da `Flow.remove()` con l'ultimo schema del FlowStream rimosso.\n\n### Flow.on('stats', function(id, stats) {})\n\nType: `event`\n\nContatori di un FlowStream che gira in un worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id del FlowStream |\n| `stats` | `Object` | yes |  | Contatori |\n\nEmesso ogni 15 secondi per ogni FlowStream in un worker thread o in un processo figlio. `stats` ha `paused`, `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` e `pid`.\n\n### ON('flowstream', function(flowstream) {})\n\nType: `event` · Since: `0.0.16`\n\nUn FlowStream è stato avviato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | Il FlowStream in esecuzione |\n\nEvento globale del framework emesso quando viene creato un FlowStream, anche dopo il riavvio automatico di un worker.\n\nExample: Log\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream', flowstream.id);\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nSi è verificato un errore in un FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Dettagli dell'errore |\n\nGli errori vengono stampati nella console ed emessi come questo evento globale. `meta` ha `id` e `name` (del FlowStream), `error`, `source`, `instanceid` e `componentid`.\n\nExample: Tracciare gli errori\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### { id, name, components, design, variables, ... }\n\nType: `type`\n\nL'oggetto che descrive un FlowStream.\n\n`components` associa l'id di un componente al suo codice sorgente. `design` associa l'id di un'istanza a `{ component, config, connections, x, y, note, tab }`; `connections` associa l'id di un output a un array di `{ id, index }` (l'istanza di destinazione e il suo input). Altre chiavi: `variables`, `sources` (TMS), `worker`, `memory` (con `worker`: il limite di heap del worker thread o del processo figlio in MB), `proxypath`, `cloning`, `paused`, `readonly`, `import`, `initscript`, `env`, `directory` e `asfiles` (`true` compila i componenti in file in `/tmp/`). Le chiavi descrittive come `icon`, `color`, `author`, `version` e `readme` vengono mostrate nell'editor.\n\nExample: Due istanze collegate\n```json\n{\n\t\"id\": \"demo\",\n\t\"name\": \"Demo\",\n\t\"components\": { \"uppercase\": \"<script total>...</script>\", \"print\": \"<script total>...</script>\" },\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\": {}\n}\n```\n\n### schema.proxytimeout\n\nType: `config` · Since: `0.0.18`\n\nTimeout del proxy di un worker con proxypath.\n\nReturns: `Number`\n\nMillisecondi per il timeout del proxy che inoltra al worker le richieste sotto `proxypath`. Viene applicato quando lo schema viene ricaricato nel FlowStream in esecuzione (`Flow.load()` con lo stesso id o `Flow.reload()`).\n\nExample: Ricaricare con un timeout\n```js\nFlow.reload({ id: 'api', worker: 'worker', proxypath: '/api/', proxytimeout: 10000, components: components, design: design });\n```\n\n### flowstream.stats\n\nType: `property`\n\nContatori del FlowStream.\n\nReturns: `Object`\n\n`messages` (totale), `pending`, `memory` (byte), `minutes` (uptime), `errors` (il numero degli ultimi errori, al massimo 10), `mm` (messaggi nell'ultimo minuto) e `paused`. Per un flusso nel processo principale, `online` è il numero di editor collegati. Per un worker i valori arrivano ogni 15 secondi.\n\n### flowstream.trigger(id, [data])\n\nType: `method`\n\nEsegue il delegate trigger delle istanze.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id dell'istanza, `@componentid` o `#name` |\n| `data` | `Object` | no |  | Passato al delegate |\n\nReturns: `Object` Il flowstream\n\nChiama `instance.trigger(data)` dell'istanza `id`, di tutte le istanze di un componente (`@componentid`) o di un nome di componente (`#name`). Non viene eseguito nulla mentre il flusso è in pausa.\n\nExample: Avviare tutti i timer\n```js\nFlow.instances.orders.trigger('@timer');\n```\n\n### flowstream.send(id, data, [callback])\n\nType: `method`\n\nInvia dati a un'istanza e attende il risultato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Destinazione, facoltativamente con `/input` |\n| `data` | `Object` | yes |  | Payload |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nCrea un nuovo messaggio con `data` e lo passa al delegate `message` dell'istanza (`id`, `@componentid` o `#name`; la prima corrispondenza). Aggiungi `/inputid` per impostare `$.input`. La callback viene eseguita quando il messaggio e tutti i suoi cloni sono terminati, con `{ error, repo, data, count, cloned, duration, meta: { id, component } }`.\n\nExample: Chiamare un flusso da un'API\n```js\nNEWACTION('Orders/process', {\n\taction: function($, model) {\n\t\tFlow.instances.orders.send('@order/input', model, function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback(response.data);\n\t\t});\n\t}\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nInvia un messaggio a tutte le istanze corrispondenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Opzioni |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nCome `send()`, ma per ogni istanza corrispondente. `opt.id` è la destinazione (`id`, `@componentid` o `#name`), `opt.data` il payload, `opt.vars` e `opt.repo` i `$.vars` e `$.repo`, `opt.timeout` un timeout in ms (il messaggio termina con l'errore `408`). `opt.uid` e `opt.ref` tornano nella risposta. La callback viene eseguita per ogni destinazione (per un flusso in un worker solo per la prima), oppure con `404` quando nulla corrisponde.\n\nExample: Exec con un timeout\n```js\nFlow.instances.orders.exec({ id: '#Validate', data: model, timeout: 5000, uid: model.id }, function(err, response) {\n\tconsole.log(response.uid, response.data);\n});\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: `Object` Il flowstream\n\nUn flusso in pausa non consegna messaggi. Senza argomento lo stato viene alternato. Viene chiamato il delegate `pause` di ogni istanza.\n\n### flowstream.variables(obj)\n\nType: `method`\n\nSostituisce le variabili del FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Nuove variabili |\n\nReturns: `Object` Il flowstream\n\nChiama il delegate `variables` di ogni istanza (e `vary('variables')` per un flusso nel processo principale), invia le variabili all'editor e salva il flusso.\n\nExample: Ruotare un token\n```js\nFlow.instances.orders.variables({ token: newtoken });\n```\n\n### flowstream.reconfigure(id, config)\n\nType: `method`\n\nModifica la configurazione di un'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id dell'istanza |\n| `config` | `Object` | yes |  | Valori da unire |\n\nReturns: `Object` Il flowstream\n\nI valori vengono uniti in `instance.config`, viene chiamato il delegate `configure`, l'editor viene aggiornato e il flusso viene salvato.\n\n### flowstream.export(callback)\n\nType: `method`\n\nLegge lo schema corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)` |\n\nLa callback riceve l'intero schema, lo stesso oggetto dell'evento `save`.\n\nExample: Backup\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('backup.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.restart()\n\nType: `method`\n\nRiavvia un FlowStream che gira in un worker.\n\nChiude le connessioni dell'editor e termina il worker; questo riparte automaticamente con lo schema corrente.\n\n### flowstream.remove()\n\nType: `method`\n\nRimuove il FlowStream.\n\nEquivale a `Flow.remove(flowstream.id)`.\n\n### flowstream.edit([url])\n\nType: `method` · Since: `0.0.16`\n\nCollega il FlowStream a un proxy di modifica remoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `'wss://flow.totaljs.com/{0}/'` | URL WebSocket del proxy |\n\nReturns: `WebSocketClient` Il client\n\nApre un client WebSocket verso l'URL (`{0}` viene sostituito con l'id del FlowStream) e permette all'editor di lavorare tramite esso, così l'applicazione non ha bisogno di una route WebSocket pubblica. Una connessione precedente viene chiusa. Restituisce il client WebSocket.\n\nExample: Modifica remota\n```js\nFlow.instances.orders.edit();\n```\n\n### exports.* in <script total>\n\nType: `type`\n\nLa definizione di un componente FlowStream.\n\nLa parte server del componente imposta proprietà di `exports`:\n\n| Proprietà | Significato |\n| --- | --- |\n| `name`, `icon`, `color`, `group`, `version`, `author` | Mostrate nell'editor |\n| `type` | Ad esempio `input`, `output` o `config`; questi compaiono negli elenchi di `io()` |\n| `inputs`, `outputs` | Array di `{ id, name }` |\n| `config` | Configurazione predefinita delle nuove istanze |\n| `npm` | Pacchetti NPM installati prima della registrazione |\n| `permissions`, `meta` | Dati personalizzati passati all'editor |\n| `make` | `function(instance, config)` per ogni istanza |\n| `install`, `uninstall` | `function(component)` quando il componente viene registrato e rimosso |\n| `call` | `function(data, callback)` chiamata dall'editor con `@componentid` |\n\nLe altre parti del file: `<settings>` (il form di configurazione), `<body>`, `<style>`, `<script>` (codice dell'editor), `<readme>`, `<template>` e `<schema>`.\n\nExample: Componente minimo\n```html\n<script total>\n\texports.name = 'Print';\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.make = function(instance) {\n\t\tinstance.message = function($) {\n\t\t\tconsole.log($.data);\n\t\t\t$.end();\n\t\t};\n\t};\n</script>\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 |  | L'istanza |\n| `config` | `Object` | yes |  | La sua configurazione |\n\nViene eseguito per ogni istanza posizionata sul canvas, e di nuovo quando il codice del componente cambia. `config` è `instance.config`. Assegna qui i delegate dell'istanza.\n\nExample: Intervallo\n```js\nexports.make = function(instance, config) {\n\tvar timer;\n\tinstance.configure = function() {\n\t\tclearInterval(timer);\n\t\ttimer = setInterval(() => instance.send('output', { ts: NOW }), (instance.config.interval || 10) * 1000);\n\t};\n\tinstance.close = () => clearInterval(timer);\n\tinstance.configure();\n};\n```\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nGli input e gli output di un componente.\n\nReturns: `Array`\n\nArray di `{ id, name }`. L'`id` è ciò che contiene `$.input` e ciò che usano `$.send(id)` e `instance.send(id)`. Un'istanza può sovrascriverli con i propri `inputs` / `outputs`.\n\nExample: Due output\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'OK' }, { id: 'error', name: 'Error' }];\n```\n\n### instance\n\nType: `type`\n\nUn'istanza posizionata di un componente.\n\nIl primo argomento di `exports.make()`. Proprietà: `id`, `component` (id del componente), `config`, `cache`, `main` (il motore del flusso), `module` (il componente), `env`, `stats` (`pending`, `input`, `output`, `duration`, `destroyed`), `instances` (tutte le istanze del flusso) e `components`.\n\nDelegate che puoi assegnare: `message($)`, `message_INPUTID($)`, `configure(config)`, `close()`, `init()` (dopo il primo caricamento), `refresh()` (dopo ogni modifica del design), `trigger(data)`, `notify(data)`, `call(data, callback)`, `service(minutes)` (ogni minuto), `pause(is)`, `variables(obj)`, `secrets(obj)` e `vary(type)`.\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nRiceve un messaggio su un input.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | Il messaggio |\n\n`$.input` è l'id dell'input. `instance.message_INPUTID` riceve solo i messaggi di un input; quando esistono entrambi, vengono chiamati entrambi. Un messaggio che non viene inviato oltre deve essere terminato con `$.end()`.\n\nExample: Smistare per input\n```js\ninstance.message = function($) {\n\tif ($.input === 'reset') {\n\t\tcount = 0;\n\t\t$.end();\n\t} else {\n\t\tcount++;\n\t\t$.send('output', { count: count });\n\t}\n};\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nLa configurazione è cambiata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | La configurazione |\n\nChiamato dopo una modifica nell'editor o una chiamata a `reconfigure()`. `instance.config` contiene già i nuovi valori.\n\n### instance.close = function() {}\n\nType: `delegate`\n\nL'istanza sta per essere rimossa.\n\nChiamato quando l'istanza viene rimossa dal design, il componente viene deregistrato o il flusso termina. Cancella qui i timer e chiudi le connessioni.\n\n### instance.send(output, [data])\n\nType: `method`\n\nAvvia un nuovo messaggio da un output o da tutti gli output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id dell'output, oppure `null` per tutti gli output |\n| `data` | `Object` | no |  | Payload |\n\nReturns: `Number` Numero di messaggi inviati\n\nInvia `data` a ogni istanza collegata all'output. Con `output` `null` invia a tutti gli output. Per la seconda connessione e le successive i dati vengono clonati (a meno di `cloning: false`). Restituisce il numero di messaggi inviati; `0` quando non è collegato nulla o il flusso è in pausa.\n\nExample: Da un timer\n```js\nsetInterval(() => instance.send('output', { ts: NOW }), 1000);\n```\n\nExample: Tutti gli output\n```js\ninstance.send(null, { ts: NOW });\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nCrea un messaggio senza inviarlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Payload |\n\nReturns: `Message` Un nuovo messaggio\n\nIl messaggio appartiene all'istanza; imposta `$.repo`, ascolta `end` e poi chiama `$.send(output)`.\n\nExample: Attendere la fine\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.on('end', function($) {\n\tconsole.log('Done', $.data);\n});\nmsg.send('output');\n```\n\n### instance.status([data], [delay])\n\nType: `method`\n\nImposta lo stato mostrato sotto l'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Qualsiasi valore JSON |\n| `delay` | `Number` | no |  | Limitazione in ms |\n\nLo stato viene inviato all'editor ed emesso come `status` su `instance.main`. Con `delay` (ms) molte chiamate vengono unite in un unico aggiornamento. Senza argomenti l'ultimo stato viene inviato di nuovo.\n\nExample: Contatore\n```js\ninstance.status({ count: count }, 1000);\n```\n\n### instance.dashboard([data])\n\nType: `method`\n\nInvia dati alla dashboard dell'editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Qualsiasi valore JSON |\n\nI dati vengono conservati e inviati all'editor; senza argomenti gli ultimi dati vengono inviati di nuovo.\n\n### instance.throw(error)\n\nType: `method`\n\nSegnala un errore dell'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | L'errore |\n\nL'errore viene aggiunto agli ultimi 10 errori del flusso (`instance.main.errors`), mostrato nell'editor, stampato nella console ed emesso come `ON('flowstream_error')`. `$.throw(error)` fa lo stesso e imposta `$.error`.\n\nExample: In una callback\n```js\nRESTBuilder.GET(config.url).callback(function(err, response) {\n\tif (err) {\n\t\tinstance.throw(err);\n\t\t$.end();\n\t} else\n\t\t$.send('output', response);\n});\n```\n\n### instance.debug(a, [b], [c], [d])\n\nType: `method`\n\nEmette un evento di debug.\n\nEmette `debug` su `instance.main` con l'istanza e gli argomenti. `Flow.test()` lo passa a `test.debug`.\n\n### instance.save([redraw])\n\nType: `method`\n\nSalva l'istanza dopo una modifica dal codice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `redraw` | `Boolean` | no | `true` | Ridisegna l'istanza nell'editor |\n\nUsalo dopo aver modificato nel codice `instance.config`, `x`, `y`, `note`, `inputs` o `outputs`. Il flusso viene salvato (l'evento `save` segue dopo circa 5 secondi) e, a meno che `redraw` non sia `false`, l'editor ridisegna l'istanza.\n\nExample: Ricordare un valore\n```js\ninstance.config.lastid = $.data.id;\ninstance.save();\n```\n\nExample: Senza ridisegnare\n```js\ninstance.config.counter++;\ninstance.save(false);\n```\n\n### instance.reconfigure(config)\n\nType: `method`\n\nModifica la configurazione di questa istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Valori da unire |\n\nEquivale a `flowstream.reconfigure(instance.id, config)` chiamato dal componente.\n\n### instance.replace(text, [data], [encoding])\n\nType: `method`\n\nSostituisce le {variabili} in un testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String|Object` | yes |  | Testo con segnaposto |\n| `data` | `Object` | no |  | Valori aggiuntivi |\n| `encoding` | `String|Function` | no |  | Codifica dei valori |\n\nReturns: `String` Il testo\n\nUn `{name}` (o `{{name}}`) prende il valore dalle variabili del flusso, dalle variabili globali, dai secret, da `{hostname}` (origin più `proxypath`) o dall'oggetto `data` (chiavi annidate con i punti). `encoding` può essere `url`, `json`, `querify` oppure una `function(value, key)`. Un oggetto sostituisce ogni suo valore stringa. In un messaggio usa `$.variables()` (alias `$.replace()`), dove `data` è per impostazione predefinita il messaggio.\n\nExample: URL\n```js\nvar url = instance.replace('https://api.example.com/{token}/orders/?id={id}', { id: 5 }, 'url');\n```\n\n### instance.cache\n\nType: `property`\n\nUn oggetto in memoria per i dati di runtime dell'istanza.\n\nReturns: `Object`\n\nUn semplice oggetto in memoria, conservato dal flusso per l'id dell'istanza: quando l'istanza viene reinizializzata (per esempio quando il suo componente viene aggiornato), riceve di nuovo lo stesso oggetto. Non viene salvato, quindi è vuoto dopo un riavvio.\n\nExample: Ultimo valore\n```js\ninstance.message = function($) {\n\tinstance.cache.last = $.data;\n\t$.send('output');\n};\n```\n\n### instance.repo\n\nType: `property` · Since: `0.0.17`\n\nDati persistenti dell'istanza salvati nel design.\n\nReturns: `Object`\n\nUn oggetto salvato nello schema insieme all'istanza. Sopravvive a un ricaricamento e a un riavvio, e l'editor lo lascia invariato quando salva il design. Chiama `instance.save()` dopo una modifica.\n\nExample: Mantenere un cursore\n```js\ninstance.repo.lastid = $.data.id;\ninstance.save();\n```\n\n### instance.activity(key, name, [progress])\n\nType: `method` · Since: `0.0.19`\n\nSegnala un'attività in corso dell'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Id dell'attività |\n| `name` | `String` | yes |  | Descrizione |\n| `progress` | `Number` | no |  | Percentuale |\n\nCrea o aggiorna l'attività `key`, la mostra nell'editor ed emette `activity` su `instance.main` con `(instance, key, name, progress)`. Un `name` vuoto o `progress` `100` la rimuove. Le attività delle istanze rimosse dal design vengono eliminate.\n\nExample: Avanzamento\n```js\ninstance.activity('sync', 'Synchronizing', 40);\n// ...\ninstance.activity('sync', 'Synchronizing', 100);\n```\n\n### instance.main\n\nType: `property`\n\nIl motore del flusso dell'istanza.\n\nReturns: `FlowStream`\n\nMembri utili: `variables`, `secrets`, `stats` (con `online`, il numero di editor collegati), `errors`, `paused`, `env`, `activities`, `find(id)` (un'istanza), `instances()` (istanze pronte), `send('ID__OUTPUT', data)`, `trigger('ID__INPUT', data)` (invia un nuovo messaggio a un input), `pause(is)`, `save()` e `restart()` (riavvia il worker del flusso; nel processo principale chiede al process manager di Total.js di riavviare l'applicazione). Emette gli eventi `status`, `debug`, `activity`, `message`, `end` e `reset`.\n\nExample: Inviare a un'altra istanza\n```js\ninstance.main.trigger('b1__input', { id: 1 });\n```\n\n### instance.main.on('reset', function() {})\n\nType: `event`\n\nGli errori del flusso sono stati azzerati.\n\nEmesso dal motore del flusso quando l'editor invia il comando di reset: prima vengono cancellati gli ultimi errori del flusso (`instance.main.errors`), poi l'evento viene eseguito senza argomenti. In un flusso che gira in un worker viene emesso dentro il worker. Il motore resta quando un'istanza viene ricreata, quindi rimuovi il listener in `instance.close`.\n\nExample: Azzerare un contatore\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\n### $\n\nType: `class`\n\nUn messaggio che viaggia attraverso il flusso.\n\nProprietà: `data`, `repo` (condiviso da tutti i cloni), `vars`, `input`, `output`, `from`/`fromid`, `to`/`toid` (istanze), `instance`, `main`, `id`, `count`, `duration`, `error`, `controller` e, dal controller, `user`, `body`, `query`, `params`, `headers`, `ip`, `language`.\n\nMetodi: `send()`, `end()` (alias `destroy()`), `rewrite(data)`, `clone()`, `variables()`, `timeout()`, `status()`, `dashboard()`, `debug()`, `throw()` e `on(name, fn)`. Eventi: `end` (il messaggio e tutti i cloni sono terminati), `timeout` e `message`.\n\n### $.send(output, [data], [clone], [check])\n\nType: `method`\n\nInvia il messaggio a un output o a tutti gli output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id dell'output, o `null` per tutti gli output |\n| `data` | `Object` | no |  | Nuovo payload |\n| `clone` | `Boolean` | no | `the `cloning` of the flow` | Clona i dati |\n| `check` | `Function` | no |  | `function(from, to, output, input)` restituisce un Boolean |\n\nReturns: `Number` Numero di destinazioni\n\nInvia un clone del messaggio a ogni istanza collegata all'output. Con `output` `null` lo invia a tutti gli output: un output senza una destinazione pronta viene saltato, gli altri output ricevono comunque il messaggio, e il messaggio termina una sola volta, quando terminano tutti i suoi cloni. `data` sostituisce il payload; `clone` (predefinito: il `cloning` del flow) copia in profondità i dati oggetto per ogni destinazione. `check(from, to, output, input)` viene chiamata per ogni destinazione di un output con nome (`from` e `to` sono istanze); restituisci `false` per saltare la destinazione. Restituisce il numero di destinazioni; con `0` il messaggio termina.\n\nExample: Passare oltre\n```js\ninstance.message = function($) {\n\t$.data.checked = true;\n\t$.send('output');\n};\n```\n\nExample: Saltare alcune destinazioni\n```js\n$.send('output', null, null, function(from, to, output, input) {\n\treturn to.component !== 'debug';\n});\n```\n\nExample: Tutti gli output\n```js\ninstance.message = function($) {\n\t$.send(null);\n};\n```\n\n### $.end()\n\nType: `method`\n\nTermina il messaggio.\n\nChiamalo quando il messaggio non viene inviato oltre. Quando il messaggio e tutti i suoi cloni sono terminati, scatta il suo evento `end` (e la `callback` di `flowstream.send()`).\n\nExample: Fermarsi qui\n```js\ninstance.message = function($) {\n\tsave($.data);\n\t$.end();\n};\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nImposta un timeout per le istanze successive.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function($)` |\n| `time` | `Number` | yes |  | Millisecondi |\n\nReturns: `Message`\n\nOgni clone inviato dopo questa chiamata deve essere elaborato entro `time` ms; altrimenti termina con `$.error = 408` e viene eseguita la callback. `$.totaltimeout([callback], time)` limita invece l'intero messaggio.\n\nExample: Timeout\n```js\n$.timeout(function($) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n\n### flow5 [path or URL ...] [port]\n\nType: `command`\n\nEsegue schemi FlowStream dalla riga di comando.\n\nCarica ogni file JSON (uno schema, o un oggetto con più schemi) o URL HTTPS, avvia un server HTTP sulla porta (predefinita `8000`) con la route `SOCKET /flowstreams/{id}/` e le route `/notify/{id}/`, e stampa il link dell'editor per ogni flusso. Le modifiche dall'editor vengono riscritte nei file locali. Senza argomenti stampa l'aiuto.\n\nExample: Due flussi sulla porta 8001\n```bash\nflow5 orders.json import.json 8001\n```\n","entries":[{"type":"class","name":"Flow","signature":"Flow / FlowStream","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":"method","name":"Flow.reload()","signature":"Flow.reload(schema, [restart])","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.restart()","signature":"Flow.restart(id)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [verify], [check])","since":"","deprecated":false},{"type":"method","name":"Flow.notify()","signature":"Flow.notify($, id)","since":"","deprecated":false},{"type":"method","name":"Flow.test()","signature":"Flow.test(name, source, [config], init)","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(flowstream, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('remove')","signature":"Flow.on('remove', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('stats')","signature":"Flow.on('stats', function(id, stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(flowstream) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"type","name":"FlowStream schema","signature":"{ id, name, components, design, variables, ... }","since":"","deprecated":false},{"type":"config","name":"proxytimeout","signature":"schema.proxytimeout","since":"0.0.18","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, [data])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(id, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(obj)","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.restart()","signature":"flowstream.restart()","since":"","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"flowstream.edit()","signature":"flowstream.edit([url])","since":"0.0.16","deprecated":false},{"type":"type","name":"Component","signature":"exports.* in <script total>","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 / exports.outputs","since":"","deprecated":false},{"type":"type","name":"instance","signature":"instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","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() {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, [data])","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(error)","since":"","deprecated":false},{"type":"method","name":"instance.debug()","signature":"instance.debug(a, [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save([redraw])","since":"","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(config)","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(text, [data], [encoding])","since":"","deprecated":false},{"type":"property","name":"instance.cache","signature":"instance.cache","since":"","deprecated":false},{"type":"property","name":"instance.repo","signature":"instance.repo","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, [progress])","since":"0.0.19","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"event","name":"instance.main.on('reset')","signature":"instance.main.on('reset', function() {})","since":"","deprecated":false},{"type":"class","name":"Message","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send(output, [data], [clone], [check])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end()","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5 [path or URL ...] [port]","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwTf7Ix61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/flowstream/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"FlowStream","summary":"Globálny objekt Flow, bežiace FlowStreamy, komponenty, inštancie, správy a príkaz flow5.","markdown":"---\ntitle: FlowStream\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/flowstream/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# FlowStream\n\n> Globálny objekt Flow, bežiace FlowStreamy, komponenty, inštancie, správy a príkaz flow5.\n\nMetódy, vlastnosti a udalosti globálneho objektu `Flow`, bežiaceho FlowStreamu (`Flow.instances[id]`), definícií komponentov, inštancií komponentov a správ, a k tomu príkaz `flow5`. Úvod s príkladmi nájdeš v príručke [FlowStream](../../guides/flowstream/).\n\n## API\n\n### Flow / FlowStream\n\nType: `class`\n\nGlobálny objekt enginu FlowStream.\n\n`Flow` a `FlowStream` sú ten istý objekt. Načítava toky, uchováva ich v `Flow.instances` a vysiela udalosti `load`, `save` a `remove`. Bežiace toky sú objekty, ktoré sú tu popísané ako `flowstream`.\n\nExample: Výpis bežiacich tokov\n```js\nfor (var id in Flow.instances)\n\tconsole.log(id, Flow.instances[id].stats);\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nSpustí FlowStream z jeho schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Schéma FlowStreamu |\n| `callback` | `Function` | no |  | `function(err, flowstream)` |\n\nChýbajúce kľúče dostanú predvolené hodnoty: náhodné `id`, `name` = `id`, prázdne `components`, `design`, `sources` a `variables`. Keď beží FlowStream s rovnakým `id`, namiesto toho sa znovu načíta s novou schémou. Callback sa spustí, keď sú komponenty a návrh načítané. Kľúče schémy sú popísané v [FlowStream](../../guides/flowstream/).\n\nExample: Načítanie súboru\n```js\nvar schema = (await F.readfile(PATH.root('orders.json'), 'utf8')).parseJSON();\nFlow.load(schema, function(err, flowstream) {\n\terr && console.error(err);\n});\n```\n\nExample: Spustenie vo worker vlákne\n```js\nFlow.load({ id: 'import', worker: 'worker', components: {}, design: {} });\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')` | Adresár so súbormi .flow |\n| `callback` | `Function` | no |  | Zavolá sa, keď sú všetky súbory načítané |\n\nPrečíta každý súbor `*.flow` (JSON schéma) z adresára a načíta ho cez `Flow.load()`. Súbory s `-bk` alebo `_bk` v názve sa preskočia. Adresár je predvolene `/flowstreams/` v koreni aplikácie. Framework ju volá raz pri štarte, takže ju potrebuješ iba pre iné adresáre. Súbor `index.flow` pluginu sa načíta s pluginom.\n\nExample: Iný adresár\n```js\nFlow.init(PATH.root('data/flows'), function() {\n\tconsole.log('Loaded:', Object.keys(Flow.instances));\n});\n```\n\n### Flow.reload(schema, [restart])\n\nType: `method`\n\nPoužije novú schému na bežiaci FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Nová schéma |\n| `restart` | `Boolean` | no | `false` | Reštartovať workera |\n\nReturns: `Boolean` `true`, keď FlowStream existuje\n\nSchéma musí mať `id` bežiaceho FlowStreamu. Komponenty a dizajn sa nahradia na mieste a odstránené komponenty sa odregistrujú. S `restart` (iba workery) sa worker ukončí a znova spustí so svojou aktuálnou schémou; nová schéma sa nepoužije. Vráti `false`, keď žiadny FlowStream nemá toto id.\n\n### Flow.remove(id)\n\nType: `method`\n\nZastaví a odstráni FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id FlowStreamu |\n\nZatvorí všetky inštancie, ukončí workera, odstráni FlowStream z `Flow.instances` a vyšle `remove`.\n\nExample: Odstránenie\n```js\nFlow.remove('orders');\n```\n\n### Flow.restart(id)\n\nType: `method`\n\nReštartuje FlowStream, ktorý beží vo workeri.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id FlowStreamu |\n\nReturns: `Boolean` `true`, keď sa nájde\n\nUkončí worker vlákno alebo podriadený proces; po sekunde sa automaticky znova spustí s aktuálnou schémou. Vráti `true`, keď FlowStream existuje (inak `undefined`). FlowStream v hlavnom procese sa ukončí a znova sa nespustí.\n\n### Flow.socket(id, websocket, [verify], [check])\n\nType: `method`\n\nPripojí editor Total.js Flow k FlowStreamu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id FlowStreamu |\n| `websocket` | `WebSocket` | yes |  | WebSocket route |\n| `verify` | `Function` | no |  | `function(client, next)` |\n| `check` | `Function` | no |  | `function(client, message)` vráti `true` alebo chybu |\n\nOdovzdaj WebSocket objekt route `SOCKET`. `verify(client, next)` môže prijať nového klienta predtým, ako dostane tok (zavolaj `next()`), a `check(client, message)` môže blokovať jednotlivé príkazy: vráť `true` na povolenie alebo text chyby. Neznáme id zatvorí WebSocket.\n\nExample: Route pre editor\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/ <8MB', function($) {\n\t\t$.autodestroy();\n\t\tFlow.socket($.params.id, $, null, function(client, msg) {\n\t\t\treturn client.user.sa ? true : 'Only for admins';\n\t\t});\n\t});\n};\n```\n\n### Flow.notify($, id)\n\nType: `method`\n\nOdovzdá HTTP požiadavku delegátu notify inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller` | yes |  | Kontrolér route |\n| `id` | `String` | yes |  | `flowid-instanceid` |\n\n`id` je `flowid-instanceid` (ďalšie časti oddelené `-` sa stanú `params`). Delegát `notify` inštancie dostane `{ id, method, headers, query, body, url, ip, params }` a editor dostane ten istý objekt. Potom odpoveď presmeruje na `?REDIRECT=url`, pošle malú stránku, ktorá zatvorí okno (pre prehliadače), alebo úspešný JSON.\n\nExample: Route\n```js\nROUTE('GET /notify/{id}/', $ => Flow.notify($, $.params.id));\nROUTE('POST /notify/{id}/ <1MB', $ => Flow.notify($, $.params.id));\n```\n\nExample: V komponente\n```js\ninstance.notify = function(data) {\n\tinstance.send('output', data.body);\n};\n```\n\n### Flow.test(name, source, [config], init)\n\nType: `method`\n\nNačíta jeden komponent v testovacom toku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Id komponentu |\n| `source` | `String` | yes |  | Zdrojový kód komponentu |\n| `config` | `Object` | no | `{}` | Konfigurácia inštancie |\n| `init` | `Function` | yes |  | `function(test)` |\n\nVytvorí tok s komponentom (id inštancie `component`) a pomocnou inštanciou prepojenou so všetkými jeho vstupmi a výstupmi. `init(test)` dostane objekt `Test`:\n\n| Člen | Použitie |\n| --- | --- |\n| `test.send(input, data)` | Pošle dáta na vstup komponentu (alias `input`) |\n| `test.message = function($, data)` | Prijíma, čo komponent posiela na svoje výstupy |\n| `test.status = function(status)` | Prijíma stav komponentu |\n| `test.debug = function(...)` | Prijíma volania `instance.debug()` |\n| `test.configure = function(config)` | Volá sa po zmene konfigurácie |\n| `test.trigger(data)` | Spustí delegát `trigger` |\n| `test.reconfigure(config)` | Zmení konfiguráciu |\n| `test.variables(obj)` | Nastaví premenné |\n| `test.assert(ok, text)`, `test.ok(text)`, `test.fail(text)` | Vypíšu výsledok; `fail` vyhodí výnimku |\n\nChyba v toku ukončí proces.\n\nExample: Test\n```js\nvar source = await F.readfile(PATH.root('components/uppercase.html'), 'utf8');\nFlow.test('uppercase', source, { field: 'name' }, function(test) {\n\ttest.message = function($, data) {\n\t\ttest.assert(data.name === 'PETER');\n\t};\n\ttest.send('input', { name: 'Peter' });\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nBežiace FlowStreamy podľa id.\n\nReturns: `Object`\n\nObjekt: id FlowStreamu → objekt `flowstream`. `Flow.db` obsahuje poslednú schému každého FlowStreamu (aktualizuje sa pri každom uložení).\n\nExample: Získanie jedného\n```js\nvar flowstream = Flow.instances.orders;\n```\n\n### Flow.on('load', function(flowstream, schema) {})\n\nType: `event`\n\nFlowStream je načítaný.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | Bežiaci FlowStream |\n| `schema` | `Object` | yes |  | Schéma |\n\nVysiela sa potom, ako `Flow.load()` načítal komponenty a návrh.\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nSchéma FlowStreamu sa zmenila.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Celá schéma |\n\nVysiela sa približne 5 sekúnd po zmene v editore alebo po volaní `instance.save()`. Schéma obsahuje `id`, `name`, `components`, `design`, `variables`, `sources`, `paused` a ostatné kľúče. Ulož ju sám, napríklad do súboru `.flow`. Toky s `readonly: true` sa neukladajú.\n\nExample: Uloženie do súboru\n```js\nFlow.on('save', function(schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### Flow.on('remove', function(schema) {})\n\nType: `event`\n\nFlowStream bol odstránený.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Schéma |\n\nVysiela ho `Flow.remove()` s poslednou schémou odstráneného FlowStreamu.\n\n### Flow.on('stats', function(id, stats) {})\n\nType: `event`\n\nPočítadlá FlowStreamu, ktorý beží vo workeri.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id FlowStreamu |\n| `stats` | `Object` | yes |  | Počítadlá |\n\nVysiela sa každých 15 sekúnd pre každý FlowStream vo worker vlákne alebo podriadenom procese. `stats` má `paused`, `messages`, `pending`, `memory`, `minutes`, `errors`, `mm` a `pid`.\n\n### ON('flowstream', function(flowstream) {})\n\nType: `event` · Since: `0.0.16`\n\nFlowStream sa spustil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flowstream` | `Object` | yes |  | Bežiaci FlowStream |\n\nGlobálna udalosť frameworku vyvolaná pri vytvorení FlowStreamu, aj po automatickom reštarte workera.\n\nExample: Záznam\n```js\nON('flowstream', function(flowstream) {\n\tconsole.log('FlowStream', flowstream.id);\n});\n```\n\n### ON('flowstream_error', function(meta) {})\n\nType: `event`\n\nVo FlowStreame nastala chyba.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Podrobnosti chyby |\n\nChyby sa vypisujú do konzoly a vysielajú ako táto globálna udalosť. `meta` má `id` a `name` (FlowStreamu), `error`, `source`, `instanceid` a `componentid`.\n\nExample: Audit chýb\n```js\nON('flowstream_error', function(meta) {\n\tconsole.log(meta.name, meta.componentid, meta.error);\n});\n```\n\n### { id, name, components, design, variables, ... }\n\nType: `type`\n\nObjekt, ktorý popisuje FlowStream.\n\n`components` mapuje id komponentu na jeho zdrojový kód. `design` mapuje id inštancie na `{ component, config, connections, x, y, note, tab }`; `connections` mapuje id výstupu na pole `{ id, index }` (cieľová inštancia a jej vstup). Ďalšie kľúče: `variables`, `sources` (TMS), `worker`, `memory` (s `worker`: limit heapu worker vlákna alebo podriadeného procesu v MB), `proxypath`, `cloning`, `paused`, `readonly`, `import`, `initscript`, `env`, `directory` a `asfiles` (`true` skompiluje komponenty do súborov v `/tmp/`). Popisné kľúče ako `icon`, `color`, `author`, `version` a `readme` sa zobrazujú v editore.\n\nExample: Dve prepojené inštancie\n```json\n{\n\t\"id\": \"demo\",\n\t\"name\": \"Demo\",\n\t\"components\": { \"uppercase\": \"<script total>...</script>\", \"print\": \"<script total>...</script>\" },\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\": {}\n}\n```\n\n### schema.proxytimeout\n\nType: `config` · Since: `0.0.18`\n\nTimeout proxy workera s proxypath.\n\nReturns: `Number`\n\nMilisekundy pre timeout proxy, ktorá preposiela požiadavky pod `proxypath` workerovi. Aplikuje sa, keď sa schéma znova načíta do bežiaceho FlowStreamu (`Flow.load()` s rovnakým id alebo `Flow.reload()`).\n\nExample: Opätovné načítanie s timeoutom\n```js\nFlow.reload({ id: 'api', worker: 'worker', proxypath: '/api/', proxytimeout: 10000, components: components, design: design });\n```\n\n### flowstream.stats\n\nType: `property`\n\nPočítadlá FlowStreamu.\n\nReturns: `Object`\n\n`messages` (celkovo), `pending`, `memory` (bajty), `minutes` (doba behu), `errors` (počet posledných chýb, najviac 10), `mm` (správy za poslednú minútu) a `paused`. Pre flow v hlavnom procese je `online` počet pripojených editorov. Pre workera hodnoty prichádzajú každých 15 sekúnd.\n\n### flowstream.trigger(id, [data])\n\nType: `method`\n\nSpustí delegát trigger inštancií.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id inštancie, `@componentid` alebo `#name` |\n| `data` | `Object` | no |  | Odovzdá sa delegátu |\n\nReturns: `Object` Flowstream\n\nZavolá `instance.trigger(data)` inštancie `id`, všetkých inštancií komponentu (`@componentid`) alebo názvu komponentu (`#name`). Kým je tok pozastavený, nespustí sa nič.\n\nExample: Spustenie všetkých časovačov\n```js\nFlow.instances.orders.trigger('@timer');\n```\n\n### flowstream.send(id, data, [callback])\n\nType: `method`\n\nPošle dáta do inštancie a počká na výsledok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Cieľ, voliteľne s `/input` |\n| `data` | `Object` | yes |  | Obsah |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nVytvorí novú správu s `data` a odovzdá ju delegátu `message` inštancie (`id`, `@componentid` alebo `#name`; prvá zhoda). Pridaj `/inputid`, ak chceš nastaviť `$.input`. Callback sa spustí, keď sú správa a všetky jej klony ukončené, s `{ error, repo, data, count, cloned, duration, meta: { id, component } }`.\n\nExample: Volanie toku z API\n```js\nNEWACTION('Orders/process', {\n\taction: function($, model) {\n\t\tFlow.instances.orders.send('@order/input', model, function(err, response) {\n\t\t\tif (err)\n\t\t\t\t$.invalid(err);\n\t\t\telse\n\t\t\t\t$.callback(response.data);\n\t\t});\n\t}\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nPošle správu všetkým zodpovedajúcim inštanciám.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Voľby |\n| `callback` | `Function` | no |  | `function(err, response)` |\n\nAko `send()`, ale pre každú vyhovujúcu inštanciu. `opt.id` je cieľ (`id`, `@componentid` alebo `#name`), `opt.data` payload, `opt.vars` a `opt.repo` sú `$.vars` a `$.repo`, `opt.timeout` je timeout v ms (správa skončí chybou `408`). `opt.uid` a `opt.ref` sa vrátia v odpovedi. Callback sa spustí pre každý cieľ (pre flow vo workeri iba pre prvý), alebo s `404`, keď nič nevyhovuje.\n\nExample: Exec s timeoutom\n```js\nFlow.instances.orders.exec({ id: '#Validate', data: model, timeout: 5000, uid: model.id }, function(err, response) {\n\tconsole.log(response.uid, response.data);\n});\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: `Object` Flowstream\n\nPozastavený tok nedoručuje správy. Bez argumentu sa stav prepne. Zavolá sa delegát `pause` každej inštancie.\n\n### flowstream.variables(obj)\n\nType: `method`\n\nNahradí premenné FlowStreamu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Nové premenné |\n\nReturns: `Object` Flowstream\n\nZavolá delegát `variables` každej inštancie (a `vary('variables')` pre flow v hlavnom procese), pošle premenné do editora a uloží flow.\n\nExample: Rotácia tokenu\n```js\nFlow.instances.orders.variables({ token: newtoken });\n```\n\n### flowstream.reconfigure(id, config)\n\nType: `method`\n\nZmení konfiguráciu inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id inštancie |\n| `config` | `Object` | yes |  | Hodnoty na zlúčenie |\n\nReturns: `Object` Flowstream\n\nHodnoty sa zlúčia do `instance.config`, zavolá sa delegát `configure`, editor sa aktualizuje a tok sa uloží.\n\n### flowstream.export(callback)\n\nType: `method`\n\nPrečíta aktuálnu schému.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)` |\n\nCallback dostane celú schému, ten istý objekt ako pri udalosti `save`.\n\nExample: Záloha\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('backup.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.restart()\n\nType: `method`\n\nReštartuje FlowStream, ktorý beží vo workeri.\n\nZatvorí spojenia editora a ukončí workera; ten sa automaticky znovu spustí s aktuálnou schémou.\n\n### flowstream.remove()\n\nType: `method`\n\nOdstráni FlowStream.\n\nTo isté ako `Flow.remove(flowstream.id)`.\n\n### flowstream.edit([url])\n\nType: `method` · Since: `0.0.16`\n\nPripojí FlowStream k vzdialenej editačnej proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no | `'wss://flow.totaljs.com/{0}/'` | URL proxy WebSocketu |\n\nReturns: `WebSocketClient` Klient\n\nOtvorí WebSocket klienta na URL (`{0}` sa nahradí id FlowStreamu) a umožní editoru pracovať cez neho, takže aplikácia nepotrebuje verejnú WebSocket trasu. Predchádzajúce spojenie sa zatvorí. Vracia WebSocket klienta.\n\nExample: Vzdialená editácia\n```js\nFlow.instances.orders.edit();\n```\n\n### exports.* in <script total>\n\nType: `type`\n\nDefinícia komponentu FlowStreamu.\n\nServerová časť komponentu nastavuje vlastnosti `exports`:\n\n| Vlastnosť | Význam |\n| --- | --- |\n| `name`, `icon`, `color`, `group`, `version`, `author` | Zobrazujú sa v editore |\n| `type` | Napríklad `input`, `output` alebo `config`; tieto sa objavujú vo výpisoch `io()` |\n| `inputs`, `outputs` | Polia `{ id, name }` |\n| `config` | Predvolená konfigurácia nových inštancií |\n| `npm` | NPM balíky nainštalované pred zaregistrovaním |\n| `permissions`, `meta` | Vlastné dáta odovzdané editoru |\n| `make` | `function(instance, config)` pre každú inštanciu |\n| `install`, `uninstall` | `function(component)` pri zaregistrovaní a odstránení komponentu |\n| `call` | `function(data, callback)`, ktorú editor volá s `@componentid` |\n\nOstatné časti súboru: `<settings>` (formulár konfigurácie), `<body>`, `<style>`, `<script>` (kód editora), `<readme>`, `<template>` a `<schema>`.\n\nExample: Minimálny komponent\n```html\n<script total>\n\texports.name = 'Print';\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.make = function(instance) {\n\t\tinstance.message = function($) {\n\t\t\tconsole.log($.data);\n\t\t\t$.end();\n\t\t};\n\t};\n</script>\n```\n\n### exports.make = function(instance, config) {}\n\nType: `method`\n\nVytvorí inštanciu komponentu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | Inštancia |\n| `config` | `Object` | yes |  | Jej konfigurácia |\n\nSpustí sa pre každú inštanciu umiestnenú na plátne a znovu, keď sa zmení kód komponentu. `config` je `instance.config`. Tu priraď delegáty inštancie.\n\nExample: Interval\n```js\nexports.make = function(instance, config) {\n\tvar timer;\n\tinstance.configure = function() {\n\t\tclearInterval(timer);\n\t\ttimer = setInterval(() => instance.send('output', { ts: NOW }), (instance.config.interval || 10) * 1000);\n\t};\n\tinstance.close = () => clearInterval(timer);\n\tinstance.configure();\n};\n```\n\n### exports.inputs / exports.outputs\n\nType: `property`\n\nVstupy a výstupy komponentu.\n\nReturns: `Array`\n\nPolia `{ id, name }`. `id` je to, čo obsahuje `$.input` a čo používajú `$.send(id)` a `instance.send(id)`. Inštancia ich môže prepísať vlastnými `inputs` / `outputs`.\n\nExample: Dva výstupy\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'OK' }, { id: 'error', name: 'Error' }];\n```\n\n### instance\n\nType: `type`\n\nJedna umiestnená inštancia komponentu.\n\nPrvý argument `exports.make()`. Vlastnosti: `id`, `component` (id komponentu), `config`, `cache`, `main` (engine toku), `module` (komponent), `env`, `stats` (`pending`, `input`, `output`, `duration`, `destroyed`), `instances` (všetky inštancie toku) a `components`.\n\nDelegáty, ktoré môžeš priradiť: `message($)`, `message_INPUTID($)`, `configure(config)`, `close()`, `init()` (po prvom načítaní), `refresh()` (po každej zmene návrhu), `trigger(data)`, `notify(data)`, `call(data, callback)`, `service(minutes)` (každú minútu), `pause(is)`, `variables(obj)`, `secrets(obj)` a `vary(type)`.\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nPrijme správu na vstupe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | Správa |\n\n`$.input` je id vstupu. `instance.message_INPUTID` prijíma správy iba jedného vstupu; keď existujú oba, zavolajú sa oba. Správa, ktorá sa ďalej neposiela, sa musí ukončiť pomocou `$.end()`.\n\nExample: Smerovanie podľa vstupu\n```js\ninstance.message = function($) {\n\tif ($.input === 'reset') {\n\t\tcount = 0;\n\t\t$.end();\n\t} else {\n\t\tcount++;\n\t\t$.send('output', { count: count });\n\t}\n};\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nKonfigurácia sa zmenila.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Konfigurácia |\n\nVolá sa po zmene v editore alebo po volaní `reconfigure()`. `instance.config` už obsahuje nové hodnoty.\n\n### instance.close = function() {}\n\nType: `delegate`\n\nInštancia sa odstraňuje.\n\nVolá sa, keď sa inštancia odstráni z návrhu, komponent sa odregistruje alebo tok skončí. Tu vyčisti časovače a zatvor spojenia.\n\n### instance.send(output, [data])\n\nType: `method`\n\nZačne novú správu z výstupu alebo zo všetkých výstupov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id výstupu alebo `null` pre všetky výstupy |\n| `data` | `Object` | no |  | Payload |\n\nReturns: `Number` Počet odoslaných správ\n\nPošle `data` každej inštancii pripojenej k výstupu. S `output` `null` posiela na všetky výstupy. Pre druhé a ďalšie spojenie sa dáta klonujú (ak nie je `cloning: false`). Vráti počet odoslaných správ; `0`, keď nie je nič pripojené alebo je flow pozastavený.\n\nExample: Z časovača\n```js\nsetInterval(() => instance.send('output', { ts: NOW }), 1000);\n```\n\nExample: Všetky výstupy\n```js\ninstance.send(null, { ts: NOW });\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nVytvorí správu bez jej odoslania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Obsah |\n\nReturns: `Message` Nová správa\n\nSpráva patrí inštancii; nastav `$.repo`, počúvaj na `end` a potom zavolaj `$.send(output)`.\n\nExample: Čakanie na koniec\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.on('end', function($) {\n\tconsole.log('Done', $.data);\n});\nmsg.send('output');\n```\n\n### instance.status([data], [delay])\n\nType: `method`\n\nNastaví stav zobrazený pod inštanciou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Ľubovoľná JSON hodnota |\n| `delay` | `Number` | no |  | Throttling v ms |\n\nStav sa pošle do editora a vyšle ako `status` na `instance.main`. S `delay` (ms) sa viac volaní zlúči do jednej aktualizácie. Bez argumentov sa znovu pošle posledný stav.\n\nExample: Počítadlo\n```js\ninstance.status({ count: count }, 1000);\n```\n\n### instance.dashboard([data])\n\nType: `method`\n\nPošle dáta na dashboard editora.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Ľubovoľná JSON hodnota |\n\nDáta sa uchovajú a pošlú do editora; bez argumentov sa znovu pošlú posledné dáta.\n\n### instance.throw(error)\n\nType: `method`\n\nNahlási chybu inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | yes |  | Chyba |\n\nChyba sa pridá k posledným 10 chybám toku (`instance.main.errors`), zobrazí sa v editore, vypíše do konzoly a vyšle ako `ON('flowstream_error')`. `$.throw(error)` robí to isté a nastaví `$.error`.\n\nExample: V callbacku\n```js\nRESTBuilder.GET(config.url).callback(function(err, response) {\n\tif (err) {\n\t\tinstance.throw(err);\n\t\t$.end();\n\t} else\n\t\t$.send('output', response);\n});\n```\n\n### instance.debug(a, [b], [c], [d])\n\nType: `method`\n\nVyšle debug udalosť.\n\nVyšle `debug` na `instance.main` s inštanciou a argumentmi. `Flow.test()` ju odovzdá do `test.debug`.\n\n### instance.save([redraw])\n\nType: `method`\n\nUloží inštanciu po zmene z kódu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `redraw` | `Boolean` | no | `true` | Prekresliť inštanciu v editore |\n\nPouži ju, keď v kóde zmeníš `instance.config`, `x`, `y`, `note`, `inputs` alebo `outputs`. Flow sa uloží (udalosť `save` nasleduje asi po 5 sekundách) a ak `redraw` nie je `false`, editor inštanciu prekreslí.\n\nExample: Zapamätanie hodnoty\n```js\ninstance.config.lastid = $.data.id;\ninstance.save();\n```\n\nExample: Bez prekreslenia\n```js\ninstance.config.counter++;\ninstance.save(false);\n```\n\n### instance.reconfigure(config)\n\nType: `method`\n\nZmení konfiguráciu tejto inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Hodnoty na zlúčenie |\n\nTo isté ako `flowstream.reconfigure(instance.id, config)` zavolané z komponentu.\n\n### instance.replace(text, [data], [encoding])\n\nType: `method`\n\nNahradí {premenné} v texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String|Object` | yes |  | Text so zástupnými symbolmi |\n| `data` | `Object` | no |  | Ďalšie hodnoty |\n| `encoding` | `String|Function` | no |  | Kódovanie hodnôt |\n\nReturns: `String` Text\n\n`{name}` (alebo `{{name}}`) vezme hodnotu z premenných toku, globálnych premenných, zo secrets, z `{hostname}` (origin plus `proxypath`) alebo z objektu `data` (vnorené kľúče s bodkami). `encoding` môže byť `url`, `json`, `querify` alebo `function(value, key)`. Objekt nahradí každú svoju reťazcovú hodnotu. V správe použi `$.variables()` (alias `$.replace()`), kde je `data` predvolene správa.\n\nExample: URL\n```js\nvar url = instance.replace('https://api.example.com/{token}/orders/?id={id}', { id: 5 }, 'url');\n```\n\n### instance.cache\n\nType: `property`\n\nObjekt v pamäti pre runtime dáta inštancie.\n\nReturns: `Object`\n\nObyčajný objekt v pamäti, ktorý flow uchováva pre id inštancie: keď sa inštancia znova inicializuje (napríklad keď sa jej komponent aktualizuje), dostane späť ten istý objekt. Neukladá sa, takže po reštarte je prázdny.\n\nExample: Posledná hodnota\n```js\ninstance.message = function($) {\n\tinstance.cache.last = $.data;\n\t$.send('output');\n};\n```\n\n### instance.repo\n\nType: `property` · Since: `0.0.17`\n\nTrvalé dáta inštancie uložené v dizajne.\n\nReturns: `Object`\n\nObjekt uložený v schéme spolu s inštanciou. Prežije opätovné načítanie aj reštart a editor ho pri ukladaní dizajnu nemení. Po zmene zavolaj `instance.save()`.\n\nExample: Uchovanie kurzora\n```js\ninstance.repo.lastid = $.data.id;\ninstance.save();\n```\n\n### instance.activity(key, name, [progress])\n\nType: `method` · Since: `0.0.19`\n\nNahlási prebiehajúcu aktivitu inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Id aktivity |\n| `name` | `String` | yes |  | Popis |\n| `progress` | `Number` | no |  | Percentá |\n\nVytvorí alebo aktualizuje aktivitu `key`, zobrazí ju v editore a vyšle `activity` na `instance.main` s `(instance, key, name, progress)`. Prázdny `name` alebo `progress` `100` ju odstráni. Aktivity inštancií odstránených z dizajnu sa zahodia.\n\nExample: Priebeh\n```js\ninstance.activity('sync', 'Synchronizing', 40);\n// ...\ninstance.activity('sync', 'Synchronizing', 100);\n```\n\n### instance.main\n\nType: `property`\n\nEngine toku, ku ktorému inštancia patrí.\n\nReturns: `FlowStream`\n\nUžitočné členy: `variables`, `secrets`, `stats` (s `online`, počtom pripojených editorov), `errors`, `paused`, `env`, `activities`, `find(id)` (inštancia), `instances()` (pripravené inštancie), `send('ID__OUTPUT', data)`, `trigger('ID__INPUT', data)` (pošle novú správu na vstup), `pause(is)`, `save()` a `restart()` (reštartuje workera flowu; v hlavnom procese požiada správcu procesov Total.js o reštart aplikácie). Vysiela udalosti `status`, `debug`, `activity`, `message`, `end` a `reset`.\n\nExample: Odoslanie inej inštancii\n```js\ninstance.main.trigger('b1__input', { id: 1 });\n```\n\n### instance.main.on('reset', function() {})\n\nType: `event`\n\nChyby flowu boli resetované.\n\nVysiela ju flow engine, keď editor pošle príkaz reset: najprv sa vymažú posledné chyby flowu (`instance.main.errors`), potom sa udalosť spustí bez argumentov. Vo flowe, ktorý beží vo workeri, sa vysiela vo vnútri workera. Engine zostáva, aj keď sa inštancia vytvorí znova, takže listener odstráň v `instance.close`.\n\nExample: Resetovanie počítadla\n```js\nexports.make = function(instance) {\n\n\tinstance.cache.count = 0;\n\n\tvar onreset = function() {\n\t\tinstance.cache.count = 0;\n\t\tinstance.status({ count: 0 });\n\t};\n\n\tinstance.main.on('reset', onreset);\n\n\tinstance.close = function() {\n\t\tinstance.main.off('reset', onreset);\n\t};\n\n};\n```\n\n### $\n\nType: `class`\n\nSpráva putujúca tokom.\n\nVlastnosti: `data`, `repo` (zdieľané všetkými klonmi), `vars`, `input`, `output`, `from`/`fromid`, `to`/`toid` (inštancie), `instance`, `main`, `id`, `count`, `duration`, `error`, `controller` a z kontroléra `user`, `body`, `query`, `params`, `headers`, `ip`, `language`.\n\nMetódy: `send()`, `end()` (alias `destroy()`), `rewrite(data)`, `clone()`, `variables()`, `timeout()`, `status()`, `dashboard()`, `debug()`, `throw()` a `on(name, fn)`. Udalosti: `end` (správa a všetky klony sú ukončené), `timeout` a `message`.\n\n### $.send(output, [data], [clone], [check])\n\nType: `method`\n\nPošle správu na výstup alebo na všetky výstupy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id výstupu alebo `null` pre všetky výstupy |\n| `data` | `Object` | no |  | Nový payload |\n| `clone` | `Boolean` | no | `the `cloning` of the flow` | Naklonovať dáta |\n| `check` | `Function` | no |  | `function(from, to, output, input)` vráti Boolean |\n\nReturns: `Number` Počet cieľov\n\nPošle klon správy každej inštancii pripojenej k výstupu. S `output` `null` posiela na všetky výstupy: výstup bez pripraveného cieľa sa preskočí, ostatné výstupy správu aj tak dostanú a správa skončí raz, keď skončia všetky jej klony. `data` nahradí payload; `clone` (predvolene `cloning` flowu) pre každý cieľ hĺbkovo skopíruje objektové dáta. `check(from, to, output, input)` sa volá pre každý cieľ pomenovaného výstupu (`from` a `to` sú inštancie); vráť `false`, aby sa cieľ preskočil. Vráti počet cieľov; pri `0` správa skončí.\n\nExample: Odovzdanie ďalej\n```js\ninstance.message = function($) {\n\t$.data.checked = true;\n\t$.send('output');\n};\n```\n\nExample: Preskočenie niektorých cieľov\n```js\n$.send('output', null, null, function(from, to, output, input) {\n\treturn to.component !== 'debug';\n});\n```\n\nExample: Všetky výstupy\n```js\ninstance.message = function($) {\n\t$.send(null);\n};\n```\n\n### $.end()\n\nType: `method`\n\nUkončí správu.\n\nZavolaj ju, keď sa správa ďalej neposiela. Keď sú správa a všetky jej klony ukončené, spustí sa jej udalosť `end` (a `callback` z `flowstream.send()`).\n\nExample: Zastavenie tu\n```js\ninstance.message = function($) {\n\tsave($.data);\n\t$.end();\n};\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nNastaví timeout pre ďalšie inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function($)` |\n| `time` | `Number` | yes |  | Milisekundy |\n\nReturns: `Message`\n\nKaždý klon odoslaný po tomto volaní sa musí spracovať do `time` ms; inak skončí s `$.error = 408` a spustí sa callback. `$.totaltimeout([callback], time)` namiesto toho obmedzí celú správu.\n\nExample: Timeout\n```js\n$.timeout(function($) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n\n### flow5 [path or URL ...] [port]\n\nType: `command`\n\nSpúšťa schémy FlowStreamu z príkazového riadka.\n\nNačíta každý JSON súbor (jednu schému alebo objekt s viacerými schémami) alebo HTTPS URL, spustí HTTP server na porte (predvolene `8000`) s route `SOCKET /flowstreams/{id}/` a route `/notify/{id}/` a pre každý tok vypíše odkaz na editor. Zmeny z editora sa zapisujú späť do lokálnych súborov. Bez argumentov vypíše nápovedu.\n\nExample: Dva toky na porte 8001\n```bash\nflow5 orders.json import.json 8001\n```\n","entries":[{"type":"class","name":"Flow","signature":"Flow / FlowStream","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":"method","name":"Flow.reload()","signature":"Flow.reload(schema, [restart])","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.restart()","signature":"Flow.restart(id)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [verify], [check])","since":"","deprecated":false},{"type":"method","name":"Flow.notify()","signature":"Flow.notify($, id)","since":"","deprecated":false},{"type":"method","name":"Flow.test()","signature":"Flow.test(name, source, [config], init)","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(flowstream, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('remove')","signature":"Flow.on('remove', function(schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('stats')","signature":"Flow.on('stats', function(id, stats) {})","since":"","deprecated":false},{"type":"event","name":"ON('flowstream')","signature":"ON('flowstream', function(flowstream) {})","since":"0.0.16","deprecated":false},{"type":"event","name":"ON('flowstream_error')","signature":"ON('flowstream_error', function(meta) {})","since":"","deprecated":false},{"type":"type","name":"FlowStream schema","signature":"{ id, name, components, design, variables, ... }","since":"","deprecated":false},{"type":"config","name":"proxytimeout","signature":"schema.proxytimeout","since":"0.0.18","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, [data])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(id, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(obj)","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.restart()","signature":"flowstream.restart()","since":"","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"flowstream.edit()","signature":"flowstream.edit([url])","since":"0.0.16","deprecated":false},{"type":"type","name":"Component","signature":"exports.* in <script total>","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 / exports.outputs","since":"","deprecated":false},{"type":"type","name":"instance","signature":"instance","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","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() {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, [data])","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(error)","since":"","deprecated":false},{"type":"method","name":"instance.debug()","signature":"instance.debug(a, [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save([redraw])","since":"","deprecated":false},{"type":"method","name":"instance.reconfigure()","signature":"instance.reconfigure(config)","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(text, [data], [encoding])","since":"","deprecated":false},{"type":"property","name":"instance.cache","signature":"instance.cache","since":"","deprecated":false},{"type":"property","name":"instance.repo","signature":"instance.repo","since":"0.0.17","deprecated":false},{"type":"method","name":"instance.activity()","signature":"instance.activity(key, name, [progress])","since":"0.0.19","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"event","name":"instance.main.on('reset')","signature":"instance.main.on('reset', function() {})","since":"","deprecated":false},{"type":"class","name":"Message","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send(output, [data], [clone], [check])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end()","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5 [path or URL ...] [port]","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JaqmDW4pc60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Message Service (TMS)","summary":"TMS functions, the TMS client and their configuration keys.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/message-service-and-apis/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# Message Service (TMS)\n\n> TMS functions, the TMS client and their configuration keys.\n\nThe functions and configuration keys of TMS (Total.js Message Service), including the TMS client. The guide [Message Service (TMS)](../../guides/message-service-and-apis/) explains how they work together with examples; this page is the exact reference.\n\nNamed APIs and the Total.js API service have their own page: [APIs](../apis/).\n\n## API\n\n### $tms : true\n\nType: `config`\n\nOpens the TMS WebSocket endpoint.\n\nReturns: `Boolean`\n\nDefault `false`. When `true`, the app registers a WebSocket route on `$tmsurl` that accepts TMS clients. Turning it on with `LOADCONFIG()` adds the route, and turning it off removes it.\n\nExample: Enable TMS\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\n### $tmsurl : /$tms/\n\nType: `config`\n\nThe path of the TMS endpoint.\n\nReturns: `String`\n\nDefault `/$tms/`. Clients connect to this path with `ws://` or `wss://`. When it changes through `LOADCONFIG()`, the old route is removed and a new one is registered.\n\n### $tmsmaxsize : 256\n\nType: `config`\n\nThe maximum size of one TMS message in kB.\n\nReturns: `Number`\n\nDefault `256`. The value is used when the TMS route is registered.\n\n### secret_tms : token\n\nType: `config`\n\nThe token TMS clients must send.\n\nReturns: `String`\n\nDefault empty (no token required). A client sends it in the `x-token` header (`TMSCLIENT()` does this for you). A wrong token closes the connection with code `4001` and counts as a failed attempt for that IP address; after more than five attempts the IP address is refused until `$tmsclearblocked` clears the list. When the value changes through `LOADCONFIG()`, all connected clients are disconnected.\n\n### $tmsclearblocked : 60\n\nType: `config`\n\nHow often, in minutes, the list of blocked TMS clients is cleared.\n\nReturns: `Number`\n\nDefault `60`. IP addresses blocked for wrong tokens can connect again after the list is cleared.\n\n### NEWPUBLISH(name, schema)\n\nType: `method`\n\nDeclares an event that the app publishes to TMS clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the event. |\n| `schema` | `String|Object` | yes |  | An inline schema (`'id:UID, name:String'`), `'@name'` of a registered JSON schema, or `null` to remove the event. |\n\nThe schema is announced to clients in the `meta` message, and `TMSCLIENT()` uses it to clean the data it receives. Pass `null` as the schema to remove the event. The list of names is sent to connected clients 500 ms after the last change.\n\nExample: Declare and publish\n```js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\nPUBLISH('orders_created', { id: UID(), email: 'a@b.com', total: 100 });\n```\n\n### PUBLISH(name, data)\n\nType: `method`\n\nSends data of a declared event to subscribed TMS clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of an event declared with `NEWPUBLISH()`. |\n| `data` | `Object` | yes |  | The data to send. |\n\nThe message goes only to connected clients that subscribed to `name`. Nothing is sent when TMS is off, when no client is connected or when `name` was not declared with `NEWPUBLISH()`. The server does not validate `data`.\n\nExample: Publish after a change\n```js\nNEWACTION('orders_create', {\n\tinput: '*email:Email, *total:Number',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tPUBLISH('orders_created', model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n### NEWSUBSCRIBE(name, schema, [callback])\n\nType: `method`\n\nDeclares a message that TMS clients may send to the app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the message. |\n| `schema` | `String|Object` | yes |  | An inline schema, `'@name'` of a registered JSON schema, or `null`. |\n| `callback` | `Function` | no |  | `function(msg, client)`, the same as a `SUBSCRIBE()` handler. |\n\nA message is accepted only when its name has a schema and the data passes it; other messages are dropped. Accepted messages go to the handlers added with `SUBSCRIBE()`. The optional `callback` is added as a handler, the same as calling `SUBSCRIBE(name, callback)`. Pass `null` as the schema to stop accepting the message.\n\nExample: Accept a message\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String', function(msg, client) {\n\tconsole.log(msg.response.name);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method`\n\nAdds a handler for a message sent by TMS clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the message. |\n| `callback` | `Function` | yes |  | `function(msg, client)`. |\n\nThe handler runs for every valid message of `name`. Its first argument is the result of the validation: `msg.response` is the validated data and `msg.error` is `null`. The second argument is the WebSocket client that sent the message. The name is announced to clients in the `meta` message. Declare the schema with `NEWSUBSCRIBE()`, otherwise no message arrives.\n\nExample: Handle a message\n```js\nSUBSCRIBE('users_updated', function(msg, client) {\n\tvar user = msg.response;\n\tconsole.log('User', user.id, 'is now', user.name);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method`\n\nRemoves handlers added with SUBSCRIBE().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the message. |\n| `callback` | `Function` | no |  | The handler to remove. |\n\nReturns: `Boolean` `true` when something was removed.\n\nWith `callback`, removes that handler only; without it, removes all handlers of the name. When no handler is left, the name is removed from the `meta` message.\n\nExample: Remove one handler\n```js\nfunction onuser(msg) {\n\tconsole.log(msg.response);\n}\n\nSUBSCRIBE('users_updated', onuser);\n// later\nUNSUBSCRIBE('users_updated', onuser);\n```\n\n### NEWCALL(name, schema, callback)\n\nType: `method`\n\nDeclares a procedure that TMS clients can call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the call. |\n| `schema` | `String|Object` | yes |  | An inline schema, `'@name'` of a registered JSON schema, or `null` to remove the call. |\n| `callback` | `Function` | yes |  | `function(data, next, client)`. |\n\nThe data of a call is validated first; invalid data is answered with the validation errors and the callback does not run. `next(err, response)` answers the client: an `ErrorBuilder` is sent as its output and any other error as `[{ error: '...' }]`. Pass `null` as the schema to remove the call.\n\nExample: Answer a call\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard' });\n});\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method`\n\nConnects the app to a TMS endpoint.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address of the endpoint, e.g. `https://app.example.com/$tms/`. |\n| `token` | `String` | no |  | The `secret_tms` of the server. |\n| `callback` | `Function` | no |  | `function(err, client, meta)`. |\n\nReturns: `WebSocketClient` The client, with the TMS methods below.\n\nConnects to the TMS endpoint of another app and returns a WebSocket client. An `http://` or `https://` address is changed to `ws://` or `wss://`. The token is sent in the `x-token` header. The client reconnects automatically. The callback runs once: with `(null, client, meta)` when the first `meta` message arrives, or with the close code as `err` when the connection closes before that.\n\nExample: Connect\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log(order);\n\t});\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method`\n\nReceives events that the server publishes with PUBLISH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the event. |\n| `callback` | `Function` | yes |  | `function(data)`. |\n\nThe list of names is sent to the server (30 ms after the last call and after each connection), so the server pushes only these events. The data is cleaned with the schema the server declared with `NEWPUBLISH()`; events not declared by the server are ignored. You can call it before the connection is ready.\n\nExample: Listen to an event\n```js\nvar client = TMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token);\n\nclient.subscribe('orders_created', function(order) {\n\tconsole.log(order.id, order.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method`\n\nSends a message to a NEWSUBSCRIBE() of the server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name declared with `NEWSUBSCRIBE()` on the server. |\n| `data` | `Object` | yes |  | The data. |\n\nThe message is sent only while the client is connected; otherwise it is dropped. The server validates it with its schema.\n\nExample: Send a message\n```js\nclient.publish('users_updated', { id: user.id, name: user.name });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method`\n\nCalls a NEWCALL() procedure of the server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name declared with `NEWCALL()`. |\n| `data` | `Object` | yes |  | The data of the call. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `10000` | The timeout in milliseconds. |\n\nReturns: `Promise` Only when the callback is omitted.\n\nWithout a callback, the method returns a promise. It fails with `TMS is offline` when the client is not connected, with `408: Timeout` when no answer arrives in time, and with an `ErrorBuilder` when the server answers with an error.\n\nExample: Call with a promise\n```js\nvar product = await client.call('products_detail', { id: '123' });\n```\n\n### client.destroy()\n\nType: `method`\n\nCloses the TMS client for good.\n\nStops the reconnecting and fails every pending `client.call()` with `TMS has been destroyed`.\n\nExample: Close\n```js\nclient.destroy();\n```\n\n### client.ready\n\nType: `property`\n\n`true` while the TMS client is connected and has the meta of the server.\n\nReturns: `Boolean`\n\nIt becomes `true` when a `meta` message arrives and `false` when the connection closes.\n\nExample: Check\n```js\nif (client.ready)\n\tclient.publish('users_updated', user);\n```\n\n### client.meta\n\nType: `property`\n\nThe last meta message received from the server.\n\nReturns: `Object`\n\nAn object with `name` (the `CONF.name` of the server), `publish`, `subscribe` and `call` (arrays of `{ id, schema }`) and `subscribers` (the names with `SUBSCRIBE()` handlers).\n\nExample: List the calls\n```js\nclient.meta.call.forEach(function(item) {\n\tconsole.log(item.id);\n});\n```\n\n### client.on('ready', callback)\n\nType: `event`\n\nFires every time the TMS client is connected and ready.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function()`. |\n\nFires after each `meta` message, so also after a reconnection.\n\nExample: Ready\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### client.on('meta', callback)\n\nType: `event`\n\nFires when the server sends its meta message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(meta)`. |\n\nFires after each connection and whenever the server changes its publishers, subscribers or calls.\n\nExample: Meta\n```js\nclient.on('meta', function(meta) {\n\tconsole.log(meta.name, meta.publish.length);\n});\n```\n","entries":[{"type":"config","name":"CONF.$tms","signature":"$tms : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsurl","signature":"$tmsurl : /$tms/","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsmaxsize","signature":"$tmsmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"CONF.secret_tms","signature":"secret_tms : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsclearblocked","signature":"$tmsclearblocked : 60","since":"","deprecated":false},{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, schema)","since":"","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, schema, [callback])","since":"","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, callback)","since":"","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"","deprecated":false},{"type":"method","name":"client.subscribe()","signature":"client.subscribe(name, callback)","since":"","deprecated":false},{"type":"method","name":"client.publish()","signature":"client.publish(name, data)","since":"","deprecated":false},{"type":"method","name":"client.call()","signature":"client.call(name, data, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"property","name":"client.ready","signature":"client.ready","since":"","deprecated":false},{"type":"property","name":"client.meta","signature":"client.meta","since":"","deprecated":false},{"type":"event","name":"client.on('ready')","signature":"client.on('ready', callback)","since":"","deprecated":false},{"type":"event","name":"client.on('meta')","signature":"client.on('meta', callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JaqmDW4pc60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Message Service (TMS)","summary":"TMS-Funktionen, der TMS-Client und ihre Konfigurationsschlüssel.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/message-service-and-apis/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# Message Service (TMS)\n\n> TMS-Funktionen, der TMS-Client und ihre Konfigurationsschlüssel.\n\nDie Funktionen und Konfigurationsschlüssel von TMS (Total.js Message Service), einschließlich des TMS-Clients. Der Leitfaden [Message Service (TMS)](../../guides/message-service-and-apis/) erklärt mit Beispielen, wie sie zusammenarbeiten; diese Seite ist die genaue Referenz.\n\nBenannte APIs und der Dienst Total.js API haben eine eigene Seite: [APIs](../apis/).\n\n## API\n\n### $tms : true\n\nType: `config`\n\nÖffnet den TMS-WebSocket-Endpunkt.\n\nReturns: `Boolean`\n\nStandard `false`. Bei `true` registriert die App unter `$tmsurl` eine WebSocket-Route, die TMS-Clients annimmt. Schaltest du es mit `LOADCONFIG()` ein, wird die Route hinzugefügt, und schaltest du es aus, wird sie entfernt.\n\nExample: TMS aktivieren\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\n### $tmsurl : /$tms/\n\nType: `config`\n\nDer Pfad des TMS-Endpunkts.\n\nReturns: `String`\n\nStandard `/$tms/`. Clients verbinden sich mit `ws://` oder `wss://` mit diesem Pfad. Wenn er sich über `LOADCONFIG()` ändert, wird die alte Route entfernt und eine neue registriert.\n\n### $tmsmaxsize : 256\n\nType: `config`\n\nDie maximale Größe einer TMS-Nachricht in kB.\n\nReturns: `Number`\n\nStandard `256`. Der Wert wird verwendet, wenn die TMS-Route registriert wird.\n\n### secret_tms : token\n\nType: `config`\n\nDas Token, das TMS-Clients senden müssen.\n\nReturns: `String`\n\nStandardmäßig leer (kein Token erforderlich). Ein Client sendet es im Header `x-token` (`TMSCLIENT()` erledigt das für dich). Ein falsches Token schließt die Verbindung mit dem Code `4001` und zählt als fehlgeschlagener Versuch für diese IP-Adresse; nach mehr als fünf Versuchen wird die IP-Adresse abgewiesen, bis `$tmsclearblocked` die Liste leert. Wenn sich der Wert über `LOADCONFIG()` ändert, werden alle verbundenen Clients getrennt.\n\n### $tmsclearblocked : 60\n\nType: `config`\n\nWie oft, in Minuten, die Liste der gesperrten TMS-Clients geleert wird.\n\nReturns: `Number`\n\nStandard `60`. Wegen falscher Tokens gesperrte IP-Adressen können sich wieder verbinden, nachdem die Liste geleert wurde.\n\n### NEWPUBLISH(name, schema)\n\nType: `method`\n\nDeklariert ein Ereignis, das die App an TMS-Clients veröffentlicht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Ereignisses. |\n| `schema` | `String|Object` | yes |  | Ein Inline-Schema (`'id:UID, name:String'`), `'@name'` eines registrierten JSON-Schemas oder `null`, um das Ereignis zu entfernen. |\n\nDas Schema wird den Clients in der `meta`-Nachricht mitgeteilt, und `TMSCLIENT()` verwendet es, um die empfangenen Daten zu bereinigen. Übergib `null` als Schema, um das Ereignis zu entfernen. Die Liste der Namen wird 500 ms nach der letzten Änderung an verbundene Clients gesendet.\n\nExample: Deklarieren und veröffentlichen\n```js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\nPUBLISH('orders_created', { id: UID(), email: 'a@b.com', total: 100 });\n```\n\n### PUBLISH(name, data)\n\nType: `method`\n\nSendet Daten eines deklarierten Ereignisses an abonnierte TMS-Clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name eines mit `NEWPUBLISH()` deklarierten Ereignisses. |\n| `data` | `Object` | yes |  | Die zu sendenden Daten. |\n\nDie Nachricht geht nur an verbundene Clients, die `name` abonniert haben. Nichts wird gesendet, wenn TMS ausgeschaltet ist, wenn kein Client verbunden ist oder wenn `name` nicht mit `NEWPUBLISH()` deklariert wurde. Der Server validiert `data` nicht.\n\nExample: Nach einer Änderung veröffentlichen\n```js\nNEWACTION('orders_create', {\n\tinput: '*email:Email, *total:Number',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tPUBLISH('orders_created', model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n### NEWSUBSCRIBE(name, schema, [callback])\n\nType: `method`\n\nDeklariert eine Nachricht, die TMS-Clients an die App senden dürfen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Nachricht. |\n| `schema` | `String|Object` | yes |  | Ein Inline-Schema, `'@name'` eines registrierten JSON-Schemas oder `null`. |\n| `callback` | `Function` | no |  | `function(msg, client)`, wie ein `SUBSCRIBE()`-Handler. |\n\nEine Nachricht wird nur angenommen, wenn ihr Name ein Schema hat und die Daten es bestehen; andere Nachrichten werden verworfen. Angenommene Nachrichten gehen an die mit `SUBSCRIBE()` hinzugefügten Handler. Der optionale `callback` wird als Handler hinzugefügt, genau wie beim Aufruf von `SUBSCRIBE(name, callback)`. Übergib `null` als Schema, um die Nachricht nicht mehr anzunehmen.\n\nExample: Eine Nachricht annehmen\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String', function(msg, client) {\n\tconsole.log(msg.response.name);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method`\n\nFügt einen Handler für eine von TMS-Clients gesendete Nachricht hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Nachricht. |\n| `callback` | `Function` | yes |  | `function(msg, client)`. |\n\nDer Handler läuft für jede gültige Nachricht von `name`. Sein erstes Argument ist das Ergebnis der Validierung: `msg.response` sind die validierten Daten und `msg.error` ist `null`. Das zweite Argument ist der WebSocket-Client, der die Nachricht gesendet hat. Der Name wird den Clients in der `meta`-Nachricht mitgeteilt. Deklariere das Schema mit `NEWSUBSCRIBE()`, sonst kommt keine Nachricht an.\n\nExample: Eine Nachricht verarbeiten\n```js\nSUBSCRIBE('users_updated', function(msg, client) {\n\tvar user = msg.response;\n\tconsole.log('User', user.id, 'is now', user.name);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method`\n\nEntfernt mit SUBSCRIBE() hinzugefügte Handler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Nachricht. |\n| `callback` | `Function` | no |  | Der zu entfernende Handler. |\n\nReturns: `Boolean` `true`, wenn etwas entfernt wurde.\n\nMit `callback` wird nur dieser Handler entfernt; ohne ihn alle Handler des Namens. Wenn kein Handler übrig ist, wird der Name aus der `meta`-Nachricht entfernt.\n\nExample: Einen Handler entfernen\n```js\nfunction onuser(msg) {\n\tconsole.log(msg.response);\n}\n\nSUBSCRIBE('users_updated', onuser);\n// later\nUNSUBSCRIBE('users_updated', onuser);\n```\n\n### NEWCALL(name, schema, callback)\n\nType: `method`\n\nDeklariert eine Prozedur, die TMS-Clients aufrufen können.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Aufrufs. |\n| `schema` | `String|Object` | yes |  | Ein Inline-Schema, `'@name'` eines registrierten JSON-Schemas oder `null`, um den Aufruf zu entfernen. |\n| `callback` | `Function` | yes |  | `function(data, next, client)`. |\n\nDie Daten eines Aufrufs werden zuerst validiert; ungültige Daten werden mit den Validierungsfehlern beantwortet und der Callback läuft nicht. `next(err, response)` antwortet dem Client: Ein `ErrorBuilder` wird als seine Ausgabe gesendet und jeder andere Fehler als `[{ error: '...' }]`. Übergib `null` als Schema, um den Aufruf zu entfernen.\n\nExample: Einen Aufruf beantworten\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard' });\n});\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method`\n\nVerbindet die App mit einem TMS-Endpunkt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse des Endpunkts, z. B. `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 Client mit den unten aufgeführten TMS-Methoden.\n\nVerbindet sich mit dem TMS-Endpunkt einer anderen Anwendung und gibt einen WebSocket-Client zurück. Eine `http://`- oder `https://`-Adresse wird zu `ws://` oder `wss://` geändert. Das Token wird im Header `x-token` gesendet. Der Client verbindet sich automatisch neu. Der Callback läuft einmal: mit `(null, client, meta)`, wenn die erste Nachricht `meta` eintrifft, oder mit dem Close-Code als `err`, wenn die Verbindung vorher geschlossen wird.\n\nExample: Verbinden\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log(order);\n\t});\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method`\n\nEmpfängt Ereignisse, die der Server mit PUBLISH() veröffentlicht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Ereignisses. |\n| `callback` | `Function` | yes |  | `function(data)`. |\n\nDie Liste der Namen wird an den Server gesendet (30 ms nach dem letzten Aufruf und nach jeder Verbindung), sodass der Server nur diese Ereignisse schickt. Die Daten werden mit dem Schema bereinigt, das der Server mit `NEWPUBLISH()` deklariert hat; vom Server nicht deklarierte Ereignisse werden ignoriert. Du kannst es aufrufen, bevor die Verbindung bereit ist.\n\nExample: Auf ein Ereignis hören\n```js\nvar client = TMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token);\n\nclient.subscribe('orders_created', function(order) {\n\tconsole.log(order.id, order.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method`\n\nSendet eine Nachricht an ein NEWSUBSCRIBE() des Servers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der auf dem Server mit `NEWSUBSCRIBE()` deklarierte Name. |\n| `data` | `Object` | yes |  | Die Daten. |\n\nDie Nachricht wird nur gesendet, solange der Client verbunden ist; sonst wird sie verworfen. Der Server validiert sie mit seinem Schema.\n\nExample: Eine Nachricht senden\n```js\nclient.publish('users_updated', { id: user.id, name: user.name });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method`\n\nRuft eine NEWCALL()-Prozedur des Servers auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der mit `NEWCALL()` deklarierte Name. |\n| `data` | `Object` | yes |  | Die Daten des Aufrufs. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `10000` | Das Timeout in Millisekunden. |\n\nReturns: `Promise` Nur wenn der Callback weggelassen wird.\n\nOhne Callback gibt die Methode eine Promise zurück. Sie schlägt mit `TMS is offline` fehl, wenn der Client nicht verbunden ist, mit `408: Timeout`, wenn keine Antwort rechtzeitig eintrifft, und mit einem `ErrorBuilder`, wenn der Server mit einem Fehler antwortet.\n\nExample: Mit einer Promise aufrufen\n```js\nvar product = await client.call('products_detail', { id: '123' });\n```\n\n### client.destroy()\n\nType: `method`\n\nSchließt den TMS-Client endgültig.\n\nBeendet das Neuverbinden und lässt jeden ausstehenden `client.call()` mit `TMS has been destroyed` fehlschlagen.\n\nExample: Schließen\n```js\nclient.destroy();\n```\n\n### client.ready\n\nType: `property`\n\n`true`, solange der TMS-Client verbunden ist und die Metadaten des Servers hat.\n\nReturns: `Boolean`\n\nEs wird `true`, wenn eine `meta`-Nachricht eintrifft, und `false`, wenn die Verbindung geschlossen wird.\n\nExample: Prüfen\n```js\nif (client.ready)\n\tclient.publish('users_updated', user);\n```\n\n### client.meta\n\nType: `property`\n\nDie letzte vom Server empfangene Meta-Nachricht.\n\nReturns: `Object`\n\nEin Objekt mit `name` (dem `CONF.name` des Servers), `publish`, `subscribe` und `call` (Arrays von `{ id, schema }`) und `subscribers` (den Namen mit `SUBSCRIBE()`-Handlern).\n\nExample: Die Aufrufe auflisten\n```js\nclient.meta.call.forEach(function(item) {\n\tconsole.log(item.id);\n});\n```\n\n### client.on('ready', callback)\n\nType: `event`\n\nWird jedes Mal ausgelöst, wenn der TMS-Client verbunden und bereit ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function()`. |\n\nWird nach jeder `meta`-Nachricht ausgelöst, also auch nach einer Neuverbindung.\n\nExample: Bereit\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### client.on('meta', callback)\n\nType: `event`\n\nWird ausgelöst, wenn der Server seine Meta-Nachricht sendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(meta)`. |\n\nWird nach jeder Verbindung ausgelöst und immer, wenn der Server seine Publisher, Subscriber oder Aufrufe ändert.\n\nExample: Meta\n```js\nclient.on('meta', function(meta) {\n\tconsole.log(meta.name, meta.publish.length);\n});\n```\n","entries":[{"type":"config","name":"CONF.$tms","signature":"$tms : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsurl","signature":"$tmsurl : /$tms/","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsmaxsize","signature":"$tmsmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"CONF.secret_tms","signature":"secret_tms : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsclearblocked","signature":"$tmsclearblocked : 60","since":"","deprecated":false},{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, schema)","since":"","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, schema, [callback])","since":"","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, callback)","since":"","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"","deprecated":false},{"type":"method","name":"client.subscribe()","signature":"client.subscribe(name, callback)","since":"","deprecated":false},{"type":"method","name":"client.publish()","signature":"client.publish(name, data)","since":"","deprecated":false},{"type":"method","name":"client.call()","signature":"client.call(name, data, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"property","name":"client.ready","signature":"client.ready","since":"","deprecated":false},{"type":"property","name":"client.meta","signature":"client.meta","since":"","deprecated":false},{"type":"event","name":"client.on('ready')","signature":"client.on('ready', callback)","since":"","deprecated":false},{"type":"event","name":"client.on('meta')","signature":"client.on('meta', callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JaqmDW4pc60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Message Service (TMS)","summary":"Funciones de TMS, el cliente TMS y sus claves de configuración.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/message-service-and-apis/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# Message Service (TMS)\n\n> Funciones de TMS, el cliente TMS y sus claves de configuración.\n\nLas funciones y claves de configuración de TMS (Total.js Message Service), incluido el cliente TMS. La guía [Message Service (TMS)](../../guides/message-service-and-apis/) explica con ejemplos cómo funcionan juntos; esta página es la referencia exacta.\n\nLas APIs con nombre y el servicio Total.js API tienen su propia página: [APIs](../apis/).\n\n## API\n\n### $tms : true\n\nType: `config`\n\nAbre el endpoint WebSocket de TMS.\n\nReturns: `Boolean`\n\nPor defecto `false`. Con `true`, la aplicación registra una ruta WebSocket en `$tmsurl` que acepta clientes TMS. Activarlo con `LOADCONFIG()` añade la ruta, y desactivarlo la elimina.\n\nExample: Activar TMS\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\n### $tmsurl : /$tms/\n\nType: `config`\n\nLa ruta del endpoint TMS.\n\nReturns: `String`\n\nPor defecto `/$tms/`. Los clientes se conectan a esta ruta con `ws://` o `wss://`. Cuando cambia mediante `LOADCONFIG()`, se elimina la ruta antigua y se registra una nueva.\n\n### $tmsmaxsize : 256\n\nType: `config`\n\nEl tamaño máximo de un mensaje TMS en kB.\n\nReturns: `Number`\n\nPor defecto `256`. El valor se usa cuando se registra la ruta TMS.\n\n### secret_tms : token\n\nType: `config`\n\nEl token que deben enviar los clientes TMS.\n\nReturns: `String`\n\nPor defecto vacío (no se requiere token). Un cliente lo envía en la cabecera `x-token` (`TMSCLIENT()` lo hace por ti). Un token incorrecto cierra la conexión con el código `4001` y cuenta como un intento fallido para esa dirección IP; tras más de cinco intentos la dirección IP se rechaza hasta que `$tmsclearblocked` limpia la lista. Cuando el valor cambia mediante `LOADCONFIG()`, se desconectan todos los clientes conectados.\n\n### $tmsclearblocked : 60\n\nType: `config`\n\nCada cuántos minutos se limpia la lista de clientes TMS bloqueados.\n\nReturns: `Number`\n\nPor defecto `60`. Las direcciones IP bloqueadas por tokens incorrectos pueden volver a conectarse después de limpiar la lista.\n\n### NEWPUBLISH(name, schema)\n\nType: `method`\n\nDeclara un evento que la app publica a los clientes TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento. |\n| `schema` | `String|Object` | yes |  | Un esquema inline (`'id:UID, name:String'`), `'@name'` de un esquema JSON registrado, o `null` para eliminar el evento. |\n\nEl esquema se anuncia a los clientes en el mensaje `meta`, y `TMSCLIENT()` lo usa para limpiar los datos que recibe. Pasa `null` como esquema para eliminar el evento. La lista de nombres se envía a los clientes conectados 500 ms después del último cambio.\n\nExample: Declarar y publicar\n```js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\nPUBLISH('orders_created', { id: UID(), email: 'a@b.com', total: 100 });\n```\n\n### PUBLISH(name, data)\n\nType: `method`\n\nEnvía datos de un evento declarado a los clientes TMS suscritos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de un evento declarado con `NEWPUBLISH()`. |\n| `data` | `Object` | yes |  | Los datos a enviar. |\n\nEl mensaje solo va a los clientes conectados que se suscribieron a `name`. No se envía nada cuando TMS está desactivado, cuando no hay ningún cliente conectado o cuando `name` no se declaró con `NEWPUBLISH()`. El servidor no valida `data`.\n\nExample: Publicar tras un cambio\n```js\nNEWACTION('orders_create', {\n\tinput: '*email:Email, *total:Number',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tPUBLISH('orders_created', model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n### NEWSUBSCRIBE(name, schema, [callback])\n\nType: `method`\n\nDeclara un mensaje que los clientes TMS pueden enviar a la app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del mensaje. |\n| `schema` | `String|Object` | yes |  | Un esquema inline, `'@name'` de un esquema JSON registrado, o `null`. |\n| `callback` | `Function` | no |  | `function(msg, client)`, igual que un handler de `SUBSCRIBE()`. |\n\nUn mensaje solo se acepta cuando su nombre tiene un esquema y los datos lo pasan; los demás mensajes se descartan. Los mensajes aceptados van a los handlers añadidos con `SUBSCRIBE()`. El `callback` opcional se añade como handler, igual que llamar a `SUBSCRIBE(name, callback)`. Pasa `null` como esquema para dejar de aceptar el mensaje.\n\nExample: Aceptar un mensaje\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String', function(msg, client) {\n\tconsole.log(msg.response.name);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method`\n\nAñade un handler para un mensaje enviado por los clientes TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del mensaje. |\n| `callback` | `Function` | yes |  | `function(msg, client)`. |\n\nEl handler se ejecuta para cada mensaje válido de `name`. Su primer argumento es el resultado de la validación: `msg.response` son los datos validados y `msg.error` es `null`. El segundo argumento es el cliente WebSocket que envió el mensaje. El nombre se anuncia a los clientes en el mensaje `meta`. Declara el esquema con `NEWSUBSCRIBE()`; si no, no llega ningún mensaje.\n\nExample: Gestionar un mensaje\n```js\nSUBSCRIBE('users_updated', function(msg, client) {\n\tvar user = msg.response;\n\tconsole.log('User', user.id, 'is now', user.name);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method`\n\nElimina handlers añadidos con SUBSCRIBE().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del mensaje. |\n| `callback` | `Function` | no |  | El handler a eliminar. |\n\nReturns: `Boolean` `true` cuando se eliminó algo.\n\nCon `callback`, elimina solo ese handler; sin él, elimina todos los handlers del nombre. Cuando no queda ningún handler, el nombre se elimina del mensaje `meta`.\n\nExample: Eliminar un handler\n```js\nfunction onuser(msg) {\n\tconsole.log(msg.response);\n}\n\nSUBSCRIBE('users_updated', onuser);\n// later\nUNSUBSCRIBE('users_updated', onuser);\n```\n\n### NEWCALL(name, schema, callback)\n\nType: `method`\n\nDeclara un procedimiento que los clientes TMS pueden llamar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la llamada. |\n| `schema` | `String|Object` | yes |  | Un esquema inline, `'@name'` de un esquema JSON registrado, o `null` para eliminar la llamada. |\n| `callback` | `Function` | yes |  | `function(data, next, client)`. |\n\nPrimero se validan los datos de una llamada; los datos no válidos se responden con los errores de validación y el callback no se ejecuta. `next(err, response)` responde al cliente: un `ErrorBuilder` se envía como su salida y cualquier otro error como `[{ error: '...' }]`. Pasa `null` como esquema para eliminar la llamada.\n\nExample: Responder una llamada\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard' });\n});\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method`\n\nConecta la app a un endpoint TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección del endpoint, p. ej. `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, con los métodos TMS de abajo.\n\nSe conecta al endpoint TMS de otra aplicación y devuelve un cliente WebSocket. Una dirección `http://` o `https://` se cambia a `ws://` o `wss://`. El token se envía en la cabecera `x-token`. El cliente se reconecta automáticamente. El callback se ejecuta una vez: con `(null, client, meta)` cuando llega el primer mensaje `meta`, o con el código de cierre como `err` cuando la conexión se cierra antes.\n\nExample: Conectar\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log(order);\n\t});\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method`\n\nRecibe los eventos que el servidor publica con PUBLISH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento. |\n| `callback` | `Function` | yes |  | `function(data)`. |\n\nLa lista de nombres se envía al servidor (30 ms después de la última llamada y tras cada conexión), así que el servidor solo envía estos eventos. Los datos se limpian con el esquema que el servidor declaró con `NEWPUBLISH()`; los eventos no declarados por el servidor se ignoran. Puedes llamarlo antes de que la conexión esté lista.\n\nExample: Escuchar un evento\n```js\nvar client = TMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token);\n\nclient.subscribe('orders_created', function(order) {\n\tconsole.log(order.id, order.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method`\n\nEnvía un mensaje a un NEWSUBSCRIBE() del servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre declarado con `NEWSUBSCRIBE()` en el servidor. |\n| `data` | `Object` | yes |  | Los datos. |\n\nEl mensaje solo se envía mientras el cliente está conectado; en otro caso se descarta. El servidor lo valida con su esquema.\n\nExample: Enviar un mensaje\n```js\nclient.publish('users_updated', { id: user.id, name: user.name });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method`\n\nLlama a un procedimiento NEWCALL() del servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre declarado con `NEWCALL()`. |\n| `data` | `Object` | yes |  | Los datos de la llamada. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `10000` | El timeout en milisegundos. |\n\nReturns: `Promise` Solo cuando se omite el callback.\n\nSin callback, el método devuelve una promesa. Falla con `TMS is offline` cuando el cliente no está conectado, con `408: Timeout` cuando no llega respuesta a tiempo, y con un `ErrorBuilder` cuando el servidor responde con un error.\n\nExample: Llamar con una promesa\n```js\nvar product = await client.call('products_detail', { id: '123' });\n```\n\n### client.destroy()\n\nType: `method`\n\nCierra el cliente TMS definitivamente.\n\nDetiene la reconexión y hace fallar cada `client.call()` pendiente con `TMS has been destroyed`.\n\nExample: Cerrar\n```js\nclient.destroy();\n```\n\n### client.ready\n\nType: `property`\n\n`true` mientras el cliente TMS está conectado y tiene el meta del servidor.\n\nReturns: `Boolean`\n\nPasa a `true` cuando llega un mensaje `meta` y a `false` cuando se cierra la conexión.\n\nExample: Comprobar\n```js\nif (client.ready)\n\tclient.publish('users_updated', user);\n```\n\n### client.meta\n\nType: `property`\n\nEl último mensaje meta recibido del servidor.\n\nReturns: `Object`\n\nUn objeto con `name` (el `CONF.name` del servidor), `publish`, `subscribe` y `call` (arrays de `{ id, schema }`) y `subscribers` (los nombres con handlers de `SUBSCRIBE()`).\n\nExample: Listar las llamadas\n```js\nclient.meta.call.forEach(function(item) {\n\tconsole.log(item.id);\n});\n```\n\n### client.on('ready', callback)\n\nType: `event`\n\nSe dispara cada vez que el cliente TMS está conectado y listo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function()`. |\n\nSe dispara tras cada mensaje `meta`, así que también tras una reconexión.\n\nExample: Listo\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### client.on('meta', callback)\n\nType: `event`\n\nSe dispara cuando el servidor envía su mensaje meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(meta)`. |\n\nSe dispara tras cada conexión y cada vez que el servidor cambia sus publicadores, suscriptores o llamadas.\n\nExample: Meta\n```js\nclient.on('meta', function(meta) {\n\tconsole.log(meta.name, meta.publish.length);\n});\n```\n","entries":[{"type":"config","name":"CONF.$tms","signature":"$tms : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsurl","signature":"$tmsurl : /$tms/","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsmaxsize","signature":"$tmsmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"CONF.secret_tms","signature":"secret_tms : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsclearblocked","signature":"$tmsclearblocked : 60","since":"","deprecated":false},{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, schema)","since":"","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, schema, [callback])","since":"","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, callback)","since":"","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"","deprecated":false},{"type":"method","name":"client.subscribe()","signature":"client.subscribe(name, callback)","since":"","deprecated":false},{"type":"method","name":"client.publish()","signature":"client.publish(name, data)","since":"","deprecated":false},{"type":"method","name":"client.call()","signature":"client.call(name, data, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"property","name":"client.ready","signature":"client.ready","since":"","deprecated":false},{"type":"property","name":"client.meta","signature":"client.meta","since":"","deprecated":false},{"type":"event","name":"client.on('ready')","signature":"client.on('ready', callback)","since":"","deprecated":false},{"type":"event","name":"client.on('meta')","signature":"client.on('meta', callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JaqmDW4pc60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Message Service (TMS)","summary":"Les fonctions TMS, le client TMS et leurs clés de configuration.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/message-service-and-apis/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# Message Service (TMS)\n\n> Les fonctions TMS, le client TMS et leurs clés de configuration.\n\nLes fonctions et les clés de configuration de TMS (Total.js Message Service), y compris le client TMS. Le guide [Message Service (TMS)](../../guides/message-service-and-apis/) explique comment ils fonctionnent ensemble avec des exemples ; cette page est la référence exacte.\n\nLes API nommées et le service Total.js API ont leur propre page : [API](../apis/).\n\n## API\n\n### $tms : true\n\nType: `config`\n\nOuvre le point de terminaison WebSocket de TMS.\n\nReturns: `Boolean`\n\nPar défaut `false`. Avec `true`, l'application enregistre une route WebSocket sur `$tmsurl` qui accepte les clients TMS. L'activer avec `LOADCONFIG()` ajoute la route, et la désactiver la supprime.\n\nExample: Activer TMS\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\n### $tmsurl : /$tms/\n\nType: `config`\n\nLe chemin du point de terminaison TMS.\n\nReturns: `String`\n\nPar défaut `/$tms/`. Les clients se connectent à ce chemin avec `ws://` ou `wss://`. Quand il change via `LOADCONFIG()`, l'ancienne route est supprimée et une nouvelle est enregistrée.\n\n### $tmsmaxsize : 256\n\nType: `config`\n\nLa taille maximale d'un message TMS en kB.\n\nReturns: `Number`\n\nPar défaut `256`. La valeur est utilisée lors de l'enregistrement de la route TMS.\n\n### secret_tms : token\n\nType: `config`\n\nLe jeton que les clients TMS doivent envoyer.\n\nReturns: `String`\n\nVide par défaut (aucun jeton requis). Un client l'envoie dans l'en-tête `x-token` (`TMSCLIENT()` le fait pour toi). Un jeton incorrect ferme la connexion avec le code `4001` et compte comme une tentative échouée pour cette adresse IP ; après plus de cinq tentatives, l'adresse IP est refusée jusqu'à ce que `$tmsclearblocked` vide la liste. Quand la valeur change via `LOADCONFIG()`, tous les clients connectés sont déconnectés.\n\n### $tmsclearblocked : 60\n\nType: `config`\n\nLa fréquence, en minutes, à laquelle la liste des clients TMS bloqués est vidée.\n\nReturns: `Number`\n\nPar défaut `60`. Les adresses IP bloquées pour des jetons incorrects peuvent se reconnecter une fois la liste vidée.\n\n### NEWPUBLISH(name, schema)\n\nType: `method`\n\nDéclare un événement que l'application publie vers les clients TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement. |\n| `schema` | `String|Object` | yes |  | Un schéma en ligne (`'id:UID, name:String'`), `'@name'` d'un schéma JSON enregistré, ou `null` pour supprimer l'événement. |\n\nLe schéma est annoncé aux clients dans le message `meta`, et `TMSCLIENT()` l'utilise pour nettoyer les données qu'il reçoit. Passe `null` comme schéma pour supprimer l'événement. La liste des noms est envoyée aux clients connectés 500 ms après la dernière modification.\n\nExample: Déclarer et publier\n```js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\nPUBLISH('orders_created', { id: UID(), email: 'a@b.com', total: 100 });\n```\n\n### PUBLISH(name, data)\n\nType: `method`\n\nEnvoie les données d'un événement déclaré aux clients TMS abonnés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom d'un événement déclaré avec `NEWPUBLISH()`. |\n| `data` | `Object` | yes |  | Les données à envoyer. |\n\nLe message ne va qu'aux clients connectés abonnés à `name`. Rien n'est envoyé quand TMS est désactivé, quand aucun client n'est connecté ou quand `name` n'a pas été déclaré avec `NEWPUBLISH()`. Le serveur ne valide pas `data`.\n\nExample: Publier après une modification\n```js\nNEWACTION('orders_create', {\n\tinput: '*email:Email, *total:Number',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tPUBLISH('orders_created', model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n### NEWSUBSCRIBE(name, schema, [callback])\n\nType: `method`\n\nDéclare un message que les clients TMS peuvent envoyer à l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du message. |\n| `schema` | `String|Object` | yes |  | Un schéma en ligne, `'@name'` d'un schéma JSON enregistré, ou `null`. |\n| `callback` | `Function` | no |  | `function(msg, client)`, comme un gestionnaire `SUBSCRIBE()`. |\n\nUn message n'est accepté que si son nom a un schéma et que les données le passent ; les autres messages sont ignorés. Les messages acceptés vont aux gestionnaires ajoutés avec `SUBSCRIBE()`. Le `callback` facultatif est ajouté comme gestionnaire, comme si tu appelais `SUBSCRIBE(name, callback)`. Passe `null` comme schéma pour ne plus accepter le message.\n\nExample: Accepter un message\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String', function(msg, client) {\n\tconsole.log(msg.response.name);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method`\n\nAjoute un gestionnaire pour un message envoyé par les clients TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du message. |\n| `callback` | `Function` | yes |  | `function(msg, client)`. |\n\nLe gestionnaire s'exécute pour chaque message valide de `name`. Son premier argument est le résultat de la validation : `msg.response` contient les données validées et `msg.error` vaut `null`. Le deuxième argument est le client WebSocket qui a envoyé le message. Le nom est annoncé aux clients dans le message `meta`. Déclare le schéma avec `NEWSUBSCRIBE()`, sinon aucun message n'arrive.\n\nExample: Traiter un message\n```js\nSUBSCRIBE('users_updated', function(msg, client) {\n\tvar user = msg.response;\n\tconsole.log('User', user.id, 'is now', user.name);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method`\n\nSupprime les gestionnaires ajoutés avec SUBSCRIBE().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du message. |\n| `callback` | `Function` | no |  | Le gestionnaire à supprimer. |\n\nReturns: `Boolean` `true` quand quelque chose a été supprimé.\n\nAvec `callback`, supprime seulement ce gestionnaire ; sans lui, supprime tous les gestionnaires du nom. Quand il ne reste aucun gestionnaire, le nom est retiré du message `meta`.\n\nExample: Supprimer un gestionnaire\n```js\nfunction onuser(msg) {\n\tconsole.log(msg.response);\n}\n\nSUBSCRIBE('users_updated', onuser);\n// later\nUNSUBSCRIBE('users_updated', onuser);\n```\n\n### NEWCALL(name, schema, callback)\n\nType: `method`\n\nDéclare une procédure que les clients TMS peuvent appeler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'appel. |\n| `schema` | `String|Object` | yes |  | Un schéma en ligne, `'@name'` d'un schéma JSON enregistré, ou `null` pour supprimer l'appel. |\n| `callback` | `Function` | yes |  | `function(data, next, client)`. |\n\nLes données d'un appel sont d'abord validées ; des données invalides reçoivent en réponse les erreurs de validation et le callback ne s'exécute pas. `next(err, response)` répond au client : un `ErrorBuilder` est envoyé sous forme de sa sortie et toute autre erreur sous forme de `[{ error: '...' }]`. Passe `null` comme schéma pour supprimer l'appel.\n\nExample: Répondre à un appel\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard' });\n});\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method`\n\nConnecte l'application à un point de terminaison TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse du point de terminaison, par ex. `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, avec les méthodes TMS ci-dessous.\n\nSe connecte à l'endpoint TMS d'une autre application et renvoie un client WebSocket. Une adresse `http://` ou `https://` est changée en `ws://` ou `wss://`. Le token est envoyé dans l'en-tête `x-token`. Le client se reconnecte automatiquement. Le callback s'exécute une fois : avec `(null, client, meta)` quand le premier message `meta` arrive, ou avec le code de fermeture comme `err` si la connexion se ferme avant.\n\nExample: Se connecter\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log(order);\n\t});\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method`\n\nReçoit les événements que le serveur publie avec PUBLISH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement. |\n| `callback` | `Function` | yes |  | `function(data)`. |\n\nLa liste des noms est envoyée au serveur (30 ms après le dernier appel et après chaque connexion), donc le serveur ne pousse que ces événements. Les données sont nettoyées avec le schéma que le serveur a déclaré avec `NEWPUBLISH()` ; les événements non déclarés par le serveur sont ignorés. Tu peux l'appeler avant que la connexion soit prête.\n\nExample: Écouter un événement\n```js\nvar client = TMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token);\n\nclient.subscribe('orders_created', function(order) {\n\tconsole.log(order.id, order.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method`\n\nEnvoie un message à un NEWSUBSCRIBE() du serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom déclaré avec `NEWSUBSCRIBE()` sur le serveur. |\n| `data` | `Object` | yes |  | Les données. |\n\nLe message n'est envoyé que tant que le client est connecté ; sinon, il est ignoré. Le serveur le valide avec son schéma.\n\nExample: Envoyer un message\n```js\nclient.publish('users_updated', { id: user.id, name: user.name });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method`\n\nAppelle une procédure NEWCALL() du serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom déclaré avec `NEWCALL()`. |\n| `data` | `Object` | yes |  | Les données de l'appel. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `10000` | Le délai en millisecondes. |\n\nReturns: `Promise` Seulement quand le callback est omis.\n\nSans callback, la méthode renvoie une promesse. Elle échoue avec `TMS is offline` quand le client n'est pas connecté, avec `408: Timeout` quand aucune réponse n'arrive à temps, et avec un `ErrorBuilder` quand le serveur répond par une erreur.\n\nExample: Appeler avec une promesse\n```js\nvar product = await client.call('products_detail', { id: '123' });\n```\n\n### client.destroy()\n\nType: `method`\n\nFerme définitivement le client TMS.\n\nArrête la reconnexion et fait échouer chaque `client.call()` en attente avec `TMS has been destroyed`.\n\nExample: Fermer\n```js\nclient.destroy();\n```\n\n### client.ready\n\nType: `property`\n\n`true` tant que le client TMS est connecté et dispose des métadonnées du serveur.\n\nReturns: `Boolean`\n\nIl devient `true` à l'arrivée d'un message `meta` et `false` à la fermeture de la connexion.\n\nExample: Vérifier\n```js\nif (client.ready)\n\tclient.publish('users_updated', user);\n```\n\n### client.meta\n\nType: `property`\n\nLe dernier message meta reçu du serveur.\n\nReturns: `Object`\n\nUn objet avec `name` (le `CONF.name` du serveur), `publish`, `subscribe` et `call` (des tableaux de `{ id, schema }`) et `subscribers` (les noms ayant des gestionnaires `SUBSCRIBE()`).\n\nExample: Lister les appels\n```js\nclient.meta.call.forEach(function(item) {\n\tconsole.log(item.id);\n});\n```\n\n### client.on('ready', callback)\n\nType: `event`\n\nSe déclenche chaque fois que le client TMS est connecté et prêt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function()`. |\n\nSe déclenche après chaque message `meta`, donc aussi après une reconnexion.\n\nExample: Prêt\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### client.on('meta', callback)\n\nType: `event`\n\nSe déclenche quand le serveur envoie son message meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(meta)`. |\n\nSe déclenche après chaque connexion et chaque fois que le serveur modifie ses éditeurs, ses abonnés ou ses appels.\n\nExample: Meta\n```js\nclient.on('meta', function(meta) {\n\tconsole.log(meta.name, meta.publish.length);\n});\n```\n","entries":[{"type":"config","name":"CONF.$tms","signature":"$tms : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsurl","signature":"$tmsurl : /$tms/","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsmaxsize","signature":"$tmsmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"CONF.secret_tms","signature":"secret_tms : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsclearblocked","signature":"$tmsclearblocked : 60","since":"","deprecated":false},{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, schema)","since":"","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, schema, [callback])","since":"","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, callback)","since":"","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"","deprecated":false},{"type":"method","name":"client.subscribe()","signature":"client.subscribe(name, callback)","since":"","deprecated":false},{"type":"method","name":"client.publish()","signature":"client.publish(name, data)","since":"","deprecated":false},{"type":"method","name":"client.call()","signature":"client.call(name, data, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"property","name":"client.ready","signature":"client.ready","since":"","deprecated":false},{"type":"property","name":"client.meta","signature":"client.meta","since":"","deprecated":false},{"type":"event","name":"client.on('ready')","signature":"client.on('ready', callback)","since":"","deprecated":false},{"type":"event","name":"client.on('meta')","signature":"client.on('meta', callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JaqmDW4pc60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Message Service (TMS)","summary":"Funzioni TMS, il client TMS e le relative chiavi di configurazione.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/message-service-and-apis/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# Message Service (TMS)\n\n> Funzioni TMS, il client TMS e le relative chiavi di configurazione.\n\nLe funzioni e le chiavi di configurazione di TMS (Total.js Message Service), incluso il client TMS. La guida [Message Service (TMS)](../../guides/message-service-and-apis/) spiega come funzionano insieme con esempi; questa pagina è il riferimento esatto.\n\nLe API con nome e il servizio Total.js API hanno una pagina propria: [API](../apis/).\n\n## API\n\n### $tms : true\n\nType: `config`\n\nApre l'endpoint WebSocket TMS.\n\nReturns: `Boolean`\n\nPredefinito `false`. Quando è `true`, l'app registra una route WebSocket su `$tmsurl` che accetta i client TMS. Attivarlo con `LOADCONFIG()` aggiunge la route, e disattivarlo la rimuove.\n\nExample: Abilitare TMS\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\n### $tmsurl : /$tms/\n\nType: `config`\n\nIl percorso dell'endpoint TMS.\n\nReturns: `String`\n\nPredefinito `/$tms/`. I client si connettono a questo percorso con `ws://` o `wss://`. Quando cambia tramite `LOADCONFIG()`, la vecchia route viene rimossa e ne viene registrata una nuova.\n\n### $tmsmaxsize : 256\n\nType: `config`\n\nLa dimensione massima di un messaggio TMS in kB.\n\nReturns: `Number`\n\nPredefinito `256`. Il valore viene usato quando viene registrata la route TMS.\n\n### secret_tms : token\n\nType: `config`\n\nIl token che i client TMS devono inviare.\n\nReturns: `String`\n\nPredefinito vuoto (nessun token richiesto). Un client lo invia nell'header `x-token` (`TMSCLIENT()` lo fa per te). Un token errato chiude la connessione con il codice `4001` e conta come tentativo fallito per quell'indirizzo IP; dopo più di cinque tentativi l'indirizzo IP viene rifiutato finché `$tmsclearblocked` non svuota l'elenco. Quando il valore cambia tramite `LOADCONFIG()`, tutti i client connessi vengono disconnessi.\n\n### $tmsclearblocked : 60\n\nType: `config`\n\nOgni quanti minuti viene svuotato l'elenco dei client TMS bloccati.\n\nReturns: `Number`\n\nPredefinito `60`. Gli indirizzi IP bloccati per token errati possono connettersi di nuovo dopo lo svuotamento dell'elenco.\n\n### NEWPUBLISH(name, schema)\n\nType: `method`\n\nDichiara un evento che l'app pubblica verso i client TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento. |\n| `schema` | `String|Object` | yes |  | Uno schema inline (`'id:UID, name:String'`), `'@name'` di uno schema JSON registrato, oppure `null` per rimuovere l'evento. |\n\nLo schema viene comunicato ai client nel messaggio `meta`, e `TMSCLIENT()` lo usa per pulire i dati che riceve. Passa `null` come schema per rimuovere l'evento. L'elenco dei nomi viene inviato ai client connessi 500 ms dopo l'ultima modifica.\n\nExample: Dichiarare e pubblicare\n```js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\nPUBLISH('orders_created', { id: UID(), email: 'a@b.com', total: 100 });\n```\n\n### PUBLISH(name, data)\n\nType: `method`\n\nInvia i dati di un evento dichiarato ai client TMS iscritti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome di un evento dichiarato con `NEWPUBLISH()`. |\n| `data` | `Object` | yes |  | I dati da inviare. |\n\nIl messaggio va solo ai client connessi che si sono iscritti a `name`. Non viene inviato nulla quando TMS è disattivato, quando nessun client è connesso o quando `name` non è stato dichiarato con `NEWPUBLISH()`. Il server non valida `data`.\n\nExample: Pubblicare dopo una modifica\n```js\nNEWACTION('orders_create', {\n\tinput: '*email:Email, *total:Number',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tPUBLISH('orders_created', model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n### NEWSUBSCRIBE(name, schema, [callback])\n\nType: `method`\n\nDichiara un messaggio che i client TMS possono inviare all'app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del messaggio. |\n| `schema` | `String|Object` | yes |  | Uno schema inline, `'@name'` di uno schema JSON registrato, oppure `null`. |\n| `callback` | `Function` | no |  | `function(msg, client)`, come un handler di `SUBSCRIBE()`. |\n\nUn messaggio viene accettato solo quando il suo nome ha uno schema e i dati lo superano; gli altri messaggi vengono scartati. I messaggi accettati vanno agli handler aggiunti con `SUBSCRIBE()`. La `callback` opzionale viene aggiunta come handler, come chiamare `SUBSCRIBE(name, callback)`. Passa `null` come schema per smettere di accettare il messaggio.\n\nExample: Accettare un messaggio\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String', function(msg, client) {\n\tconsole.log(msg.response.name);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method`\n\nAggiunge un handler per un messaggio inviato dai client TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del messaggio. |\n| `callback` | `Function` | yes |  | `function(msg, client)`. |\n\nL'handler viene eseguito per ogni messaggio valido di `name`. Il suo primo argomento è il risultato della validazione: `msg.response` sono i dati validati e `msg.error` è `null`. Il secondo argomento è il client WebSocket che ha inviato il messaggio. Il nome viene comunicato ai client nel messaggio `meta`. Dichiara lo schema con `NEWSUBSCRIBE()`, altrimenti non arriva nessun messaggio.\n\nExample: Gestire un messaggio\n```js\nSUBSCRIBE('users_updated', function(msg, client) {\n\tvar user = msg.response;\n\tconsole.log('User', user.id, 'is now', user.name);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method`\n\nRimuove gli handler aggiunti con SUBSCRIBE().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del messaggio. |\n| `callback` | `Function` | no |  | L'handler da rimuovere. |\n\nReturns: `Boolean` `true` quando è stato rimosso qualcosa.\n\nCon `callback`, rimuove solo quell'handler; senza, rimuove tutti gli handler del nome. Quando non rimane nessun handler, il nome viene rimosso dal messaggio `meta`.\n\nExample: Rimuovere un handler\n```js\nfunction onuser(msg) {\n\tconsole.log(msg.response);\n}\n\nSUBSCRIBE('users_updated', onuser);\n// later\nUNSUBSCRIBE('users_updated', onuser);\n```\n\n### NEWCALL(name, schema, callback)\n\nType: `method`\n\nDichiara una procedura che i client TMS possono chiamare.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della chiamata. |\n| `schema` | `String|Object` | yes |  | Uno schema inline, `'@name'` di uno schema JSON registrato, oppure `null` per rimuovere la chiamata. |\n| `callback` | `Function` | yes |  | `function(data, next, client)`. |\n\nI dati di una chiamata vengono prima validati; ai dati non validi si risponde con gli errori di validazione e la callback non viene eseguita. `next(err, response)` risponde al client: un `ErrorBuilder` viene inviato come suo output e qualsiasi altro errore come `[{ error: '...' }]`. Passa `null` come schema per rimuovere la chiamata.\n\nExample: Rispondere a una chiamata\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard' });\n});\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method`\n\nConnette l'app a un endpoint TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo dell'endpoint, es. `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, con i metodi TMS descritti sotto.\n\nSi collega all'endpoint TMS di un'altra app e restituisce un client WebSocket. Un indirizzo `http://` o `https://` viene cambiato in `ws://` o `wss://`. Il token viene inviato nell'header `x-token`. Il client si riconnette automaticamente. La callback viene eseguita una volta: con `(null, client, meta)` quando arriva il primo messaggio `meta`, oppure con il codice di chiusura come `err` quando la connessione si chiude prima.\n\nExample: Connettersi\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log(order);\n\t});\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method`\n\nRiceve gli eventi che il server pubblica con PUBLISH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento. |\n| `callback` | `Function` | yes |  | `function(data)`. |\n\nL'elenco dei nomi viene inviato al server (30 ms dopo l'ultima chiamata e dopo ogni connessione), così il server invia solo questi eventi. I dati vengono puliti con lo schema che il server ha dichiarato con `NEWPUBLISH()`; gli eventi non dichiarati dal server vengono ignorati. Puoi chiamarlo prima che la connessione sia pronta.\n\nExample: Ascoltare un evento\n```js\nvar client = TMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token);\n\nclient.subscribe('orders_created', function(order) {\n\tconsole.log(order.id, order.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method`\n\nInvia un messaggio a un NEWSUBSCRIBE() del server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dichiarato con `NEWSUBSCRIBE()` sul server. |\n| `data` | `Object` | yes |  | I dati. |\n\nIl messaggio viene inviato solo mentre il client è connesso; altrimenti viene scartato. Il server lo valida con il suo schema.\n\nExample: Inviare un messaggio\n```js\nclient.publish('users_updated', { id: user.id, name: user.name });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method`\n\nChiama una procedura NEWCALL() del server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dichiarato con `NEWCALL()`. |\n| `data` | `Object` | yes |  | I dati della chiamata. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `10000` | Il timeout in millisecondi. |\n\nReturns: `Promise` Solo quando la callback è omessa.\n\nSenza callback, il metodo restituisce una promise. Fallisce con `TMS is offline` quando il client non è connesso, con `408: Timeout` quando non arriva una risposta in tempo, e con un `ErrorBuilder` quando il server risponde con un errore.\n\nExample: Chiamare con una promise\n```js\nvar product = await client.call('products_detail', { id: '123' });\n```\n\n### client.destroy()\n\nType: `method`\n\nChiude definitivamente il client TMS.\n\nInterrompe la riconnessione e fa fallire ogni `client.call()` in sospeso con `TMS has been destroyed`.\n\nExample: Chiudere\n```js\nclient.destroy();\n```\n\n### client.ready\n\nType: `property`\n\n`true` mentre il client TMS è connesso e ha i meta del server.\n\nReturns: `Boolean`\n\nDiventa `true` quando arriva un messaggio `meta` e `false` quando la connessione si chiude.\n\nExample: Verificare\n```js\nif (client.ready)\n\tclient.publish('users_updated', user);\n```\n\n### client.meta\n\nType: `property`\n\nL'ultimo messaggio meta ricevuto dal server.\n\nReturns: `Object`\n\nUn oggetto con `name` (il `CONF.name` del server), `publish`, `subscribe` e `call` (array di `{ id, schema }`) e `subscribers` (i nomi con handler `SUBSCRIBE()`).\n\nExample: Elencare le chiamate\n```js\nclient.meta.call.forEach(function(item) {\n\tconsole.log(item.id);\n});\n```\n\n### client.on('ready', callback)\n\nType: `event`\n\nSi attiva ogni volta che il client TMS è connesso e pronto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function()`. |\n\nSi attiva dopo ogni messaggio `meta`, quindi anche dopo una riconnessione.\n\nExample: Pronto\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### client.on('meta', callback)\n\nType: `event`\n\nSi attiva quando il server invia il suo messaggio meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(meta)`. |\n\nSi attiva dopo ogni connessione e ogni volta che il server cambia i suoi publisher, subscriber o chiamate.\n\nExample: Meta\n```js\nclient.on('meta', function(meta) {\n\tconsole.log(meta.name, meta.publish.length);\n});\n```\n","entries":[{"type":"config","name":"CONF.$tms","signature":"$tms : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsurl","signature":"$tmsurl : /$tms/","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsmaxsize","signature":"$tmsmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"CONF.secret_tms","signature":"secret_tms : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsclearblocked","signature":"$tmsclearblocked : 60","since":"","deprecated":false},{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, schema)","since":"","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, schema, [callback])","since":"","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, callback)","since":"","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"","deprecated":false},{"type":"method","name":"client.subscribe()","signature":"client.subscribe(name, callback)","since":"","deprecated":false},{"type":"method","name":"client.publish()","signature":"client.publish(name, data)","since":"","deprecated":false},{"type":"method","name":"client.call()","signature":"client.call(name, data, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"property","name":"client.ready","signature":"client.ready","since":"","deprecated":false},{"type":"property","name":"client.meta","signature":"client.meta","since":"","deprecated":false},{"type":"event","name":"client.on('ready')","signature":"client.on('ready', callback)","since":"","deprecated":false},{"type":"event","name":"client.on('meta')","signature":"client.on('meta', callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JaqmDW4pc60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/message-service-and-apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Message Service (TMS)","summary":"Funkcie TMS, TMS klient a ich konfiguračné kľúče.","markdown":"---\ntitle: Message Service (TMS)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/message-service-and-apis/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# Message Service (TMS)\n\n> Funkcie TMS, TMS klient a ich konfiguračné kľúče.\n\nFunkcie a konfiguračné kľúče TMS (Total.js Message Service) vrátane TMS klienta. Návod [Message Service (TMS)](../../guides/message-service-and-apis/) vysvetľuje na príkladoch, ako spolu fungujú; táto stránka je presná referencia.\n\nPomenované API a služba Total.js API majú vlastnú stránku: [API](../apis/).\n\n## API\n\n### $tms : true\n\nType: `config`\n\nOtvorí TMS WebSocket endpoint.\n\nReturns: `Boolean`\n\nPredvolene `false`. Keď je `true`, aplikácia zaregistruje na `$tmsurl` WebSocket trasu, ktorá prijíma TMS klientov. Zapnutie cez `LOADCONFIG()` trasu pridá a vypnutie ju odstráni.\n\nExample: Zapnutie TMS\n```js\n// /config\n$tms           : true\nsecret_tms     : a-long-random-token\n```\n\n### $tmsurl : /$tms/\n\nType: `config`\n\nCesta TMS endpointu.\n\nReturns: `String`\n\nPredvolene `/$tms/`. Klienti sa na túto cestu pripájajú cez `ws://` alebo `wss://`. Keď sa zmení cez `LOADCONFIG()`, stará route sa odstráni a zaregistruje sa nová.\n\n### $tmsmaxsize : 256\n\nType: `config`\n\nMaximálna veľkosť jednej TMS správy v kB.\n\nReturns: `Number`\n\nPredvolene `256`. Hodnota sa použije pri registrácii TMS route.\n\n### secret_tms : token\n\nType: `config`\n\nToken, ktorý musia TMS klienti poslať.\n\nReturns: `String`\n\nPredvolene prázdny (token sa nevyžaduje). Klient ho pošle v hlavičke `x-token` (`TMSCLIENT()` to urobí za teba). Nesprávny token zatvorí spojenie s kódom `4001` a započíta sa ako neúspešný pokus pre danú IP adresu; po viac ako piatich pokusoch je IP adresa odmietaná, kým `$tmsclearblocked` zoznam nevyčistí. Keď sa hodnota zmení cez `LOADCONFIG()`, všetci pripojení klienti sa odpoja.\n\n### $tmsclearblocked : 60\n\nType: `config`\n\nAko často, v minútach, sa čistí zoznam blokovaných TMS klientov.\n\nReturns: `Number`\n\nPredvolene `60`. IP adresy zablokované pre nesprávne tokeny sa môžu po vyčistení zoznamu znova pripojiť.\n\n### NEWPUBLISH(name, schema)\n\nType: `method`\n\nDeklaruje udalosť, ktorú aplikácia publikuje TMS klientom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `schema` | `String|Object` | yes |  | Inline schéma (`'id:UID, name:String'`), `'@name'` registrovanej JSON schémy alebo `null` na odstránenie udalosti. |\n\nSchéma sa oznámi klientom v správe `meta` a `TMSCLIENT()` ju použije na vyčistenie prijatých dát. Na odstránenie udalosti odovzdaj ako schému `null`. Zoznam názvov sa pripojeným klientom pošle 500 ms po poslednej zmene.\n\nExample: Deklarovanie a publikovanie\n```js\nNEWPUBLISH('orders_created', 'id:UID, email:Email, total:Number');\n\nPUBLISH('orders_created', { id: UID(), email: 'a@b.com', total: 100 });\n```\n\n### PUBLISH(name, data)\n\nType: `method`\n\nPošle dáta deklarovanej udalosti prihláseným TMS klientom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti deklarovanej cez `NEWPUBLISH()`. |\n| `data` | `Object` | yes |  | Dáta na odoslanie. |\n\nSpráva ide iba pripojeným klientom, ktorí sa prihlásili na `name`. Nič sa neodošle, keď je TMS vypnuté, keď nie je pripojený žiadny klient alebo keď `name` nebol deklarovaný cez `NEWPUBLISH()`. Server `data` nevaliduje.\n\nExample: Publikovanie po zmene\n```js\nNEWACTION('orders_create', {\n\tinput: '*email:Email, *total:Number',\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tPUBLISH('orders_created', model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n### NEWSUBSCRIBE(name, schema, [callback])\n\nType: `method`\n\nDeklaruje správu, ktorú môžu TMS klienti poslať aplikácii.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov správy. |\n| `schema` | `String|Object` | yes |  | Inline schéma, `'@name'` registrovanej JSON schémy alebo `null`. |\n| `callback` | `Function` | no |  | `function(msg, client)`, rovnako ako handler `SUBSCRIBE()`. |\n\nSpráva sa prijme iba vtedy, keď jej názov má schému a dáta ňou prejdú; ostatné správy sa zahodia. Prijaté správy idú do handlerov pridaných cez `SUBSCRIBE()`. Voliteľný `callback` sa pridá ako handler, rovnako ako pri volaní `SUBSCRIBE(name, callback)`. Ak chceš správu prestať prijímať, odovzdaj ako schému `null`.\n\nExample: Prijatie správy\n```js\nNEWSUBSCRIBE('users_updated', 'id:UID, *name:String', function(msg, client) {\n\tconsole.log(msg.response.name);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method`\n\nPridá handler pre správu, ktorú posielajú TMS klienti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov správy. |\n| `callback` | `Function` | yes |  | `function(msg, client)`. |\n\nHandler sa spustí pre každú platnú správu `name`. Jeho prvý argument je výsledok validácie: `msg.response` sú validované dáta a `msg.error` je `null`. Druhý argument je WebSocket klient, ktorý správu poslal. Názov sa oznámi klientom v správe `meta`. Schému deklaruj cez `NEWSUBSCRIBE()`, inak žiadna správa nepríde.\n\nExample: Spracovanie správy\n```js\nSUBSCRIBE('users_updated', function(msg, client) {\n\tvar user = msg.response;\n\tconsole.log('User', user.id, 'is now', user.name);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method`\n\nOdstráni handlery pridané cez SUBSCRIBE().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov správy. |\n| `callback` | `Function` | no |  | Handler na odstránenie. |\n\nReturns: `Boolean` `true`, keď sa niečo odstránilo.\n\nS `callback` odstráni iba tento handler; bez neho odstráni všetky handlery daného názvu. Keď nezostane žiadny handler, názov sa odstráni zo správy `meta`.\n\nExample: Odstránenie jedného handlera\n```js\nfunction onuser(msg) {\n\tconsole.log(msg.response);\n}\n\nSUBSCRIBE('users_updated', onuser);\n// later\nUNSUBSCRIBE('users_updated', onuser);\n```\n\n### NEWCALL(name, schema, callback)\n\nType: `method`\n\nDeklaruje procedúru, ktorú môžu TMS klienti volať.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov volania. |\n| `schema` | `String|Object` | yes |  | Inline schéma, `'@name'` registrovanej JSON schémy alebo `null` na odstránenie volania. |\n| `callback` | `Function` | yes |  | `function(data, next, client)`. |\n\nDáta volania sa najprv validujú; na neplatné dáta sa odpovie chybami validácie a callback sa nespustí. `next(err, response)` odpovie klientovi: `ErrorBuilder` sa pošle ako jeho výstup a akákoľvek iná chyba ako `[{ error: '...' }]`. Na odstránenie volania odovzdaj ako schému `null`.\n\nExample: Odpoveď na volanie\n```js\nNEWCALL('products_detail', 'id:UID', function(data, next, client) {\n\tif (data.id === '404')\n\t\tnext('Product not found');\n\telse\n\t\tnext(null, { id: data.id, name: 'Keyboard' });\n});\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method`\n\nPripojí aplikáciu k TMS endpointu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa endpointu, napr. `https://app.example.com/$tms/`. |\n| `token` | `String` | no |  | `secret_tms` servera. |\n| `callback` | `Function` | no |  | `function(err, client, meta)`. |\n\nReturns: `WebSocketClient` Klient s nižšie uvedenými metódami TMS.\n\nPripojí sa k TMS endpointu inej aplikácie a vráti WebSocket klienta. Adresa `http://` alebo `https://` sa zmení na `ws://` alebo `wss://`. Token sa posiela v hlavičke `x-token`. Klient sa automaticky znova pripája. Callback sa spustí raz: s `(null, client, meta)`, keď príde prvá správa `meta`, alebo s kódom zatvorenia ako `err`, keď sa spojenie zatvorí skôr.\n\nExample: Pripojenie\n```js\nTMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token, function(err, client, meta) {\n\tclient.subscribe('orders_created', function(order) {\n\t\tconsole.log(order);\n\t});\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method`\n\nPrijíma udalosti, ktoré server publikuje cez PUBLISH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `callback` | `Function` | yes |  | `function(data)`. |\n\nZoznam názvov sa pošle serveru (30 ms po poslednom volaní a po každom pripojení), takže server posiela iba tieto udalosti. Dáta sa vyčistia schémou, ktorú server deklaroval cez `NEWPUBLISH()`; udalosti, ktoré server nedeklaroval, sa ignorujú. Môžeš ju zavolať ešte predtým, ako je spojenie pripravené.\n\nExample: Počúvanie udalosti\n```js\nvar client = TMSCLIENT('https://orders.example.com/$tms/', CONF.orders_token);\n\nclient.subscribe('orders_created', function(order) {\n\tconsole.log(order.id, order.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method`\n\nPošle správu do NEWSUBSCRIBE() servera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov deklarovaný cez `NEWSUBSCRIBE()` na serveri. |\n| `data` | `Object` | yes |  | Dáta. |\n\nSpráva sa pošle iba vtedy, keď je klient pripojený; inak sa zahodí. Server ju validuje svojou schémou.\n\nExample: Odoslanie správy\n```js\nclient.publish('users_updated', { id: user.id, name: user.name });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method`\n\nZavolá procedúru NEWCALL() servera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov deklarovaný cez `NEWCALL()`. |\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` Iba keď vynecháš callback.\n\nBez callbacku metóda vracia promise. Zlyhá s `TMS is offline`, keď klient nie je pripojený, s `408: Timeout`, keď odpoveď nepríde včas, a s `ErrorBuilder`, keď server odpovie chybou.\n\nExample: Volanie s promise\n```js\nvar product = await client.call('products_detail', { id: '123' });\n```\n\n### client.destroy()\n\nType: `method`\n\nNatrvalo zatvorí TMS klienta.\n\nZastaví opätovné pripájanie a každé čakajúce `client.call()` nechá zlyhať s `TMS has been destroyed`.\n\nExample: Zatvorenie\n```js\nclient.destroy();\n```\n\n### client.ready\n\nType: `property`\n\n`true`, kým je TMS klient pripojený a má meta servera.\n\nReturns: `Boolean`\n\nZmení sa na `true`, keď príde správa `meta`, a na `false`, keď sa spojenie zatvorí.\n\nExample: Kontrola\n```js\nif (client.ready)\n\tclient.publish('users_updated', user);\n```\n\n### client.meta\n\nType: `property`\n\nPosledná meta správa prijatá zo servera.\n\nReturns: `Object`\n\nObjekt s `name` (`CONF.name` servera), `publish`, `subscribe` a `call` (polia `{ id, schema }`) a `subscribers` (názvy s handlermi `SUBSCRIBE()`).\n\nExample: Výpis volaní\n```js\nclient.meta.call.forEach(function(item) {\n\tconsole.log(item.id);\n});\n```\n\n### client.on('ready', callback)\n\nType: `event`\n\nVyvolá sa vždy, keď je TMS klient pripojený a pripravený.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function()`. |\n\nVyvolá sa po každej správe `meta`, teda aj po opätovnom pripojení.\n\nExample: Ready\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### client.on('meta', callback)\n\nType: `event`\n\nVyvolá sa, keď server pošle svoju správu meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(meta)`. |\n\nVyvolá sa po každom pripojení a vždy, keď server zmení svojich publisherov, subscriberov alebo volania.\n\nExample: Meta\n```js\nclient.on('meta', function(meta) {\n\tconsole.log(meta.name, meta.publish.length);\n});\n```\n","entries":[{"type":"config","name":"CONF.$tms","signature":"$tms : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsurl","signature":"$tmsurl : /$tms/","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsmaxsize","signature":"$tmsmaxsize : 256","since":"","deprecated":false},{"type":"config","name":"CONF.secret_tms","signature":"secret_tms : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tmsclearblocked","signature":"$tmsclearblocked : 60","since":"","deprecated":false},{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, schema)","since":"","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, schema, [callback])","since":"","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, callback)","since":"","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"","deprecated":false},{"type":"method","name":"client.subscribe()","signature":"client.subscribe(name, callback)","since":"","deprecated":false},{"type":"method","name":"client.publish()","signature":"client.publish(name, data)","since":"","deprecated":false},{"type":"method","name":"client.call()","signature":"client.call(name, data, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"client.destroy()","signature":"client.destroy()","since":"","deprecated":false},{"type":"property","name":"client.ready","signature":"client.ready","since":"","deprecated":false},{"type":"property","name":"client.meta","signature":"client.meta","since":"","deprecated":false},{"type":"event","name":"client.on('ready')","signature":"client.on('ready', callback)","since":"","deprecated":false},{"type":"event","name":"client.on('meta')","signature":"client.on('meta', callback)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JafMu547H60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"APIs","summary":"NEWAPI(), API() and its methods, TotalAPI() and their configuration keys.","markdown":"---\ntitle: APIs\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/apis/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# APIs\n\n> NEWAPI(), API() and its methods, TotalAPI() and their configuration keys.\n\nThe functions and configuration keys of named APIs, including the Total.js API service. The guide [APIs](../../guides/apis/) explains how they work together with examples; this page is the exact reference.\n\n## API\n\n### NEWAPI(name, [config], callback)\n\nType: `method`\n\nRegisters the code that calls one API service.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name, or names separated by commas. |\n| `config` | `Object` | no |  | Default settings copied into `opt.config`. |\n| `callback` | `Function` | yes |  | `function(opt, next)`; `next(err, response)` ends the call. |\n\nRegisters the handler of an API service. `this` in the handler is the API call. A name is found in the spelling given to `NEWAPI()` or in lower case; several names separated by commas share one handler. The name `*` handles every name without its own handler. A function alone, or a config object and a function, registers the name `default`. The optional `config` holds default settings: before each call its keys are copied into `opt.config`, unless the call already set them with `.configure()`. Pass `null` as the callback to remove a handler. `F.newapi()` is the same function.\n\nExample: Register a service\n```js\nNEWAPI('Weather', { region: 'eu' }, function(opt, next) {\n\tREQUEST({ url: 'https://' + opt.config.region + '.weather.example/' + opt.schema + '/', method: 'POST', type: 'json', body: JSON.stringify(opt.data), callback: function(err, response) {\n\t\tnext(err, response && response.body.parseJSON());\n\t}});\n});\n```\n\n### function(opt, next)\n\nType: `type`\n\nThe options a NEWAPI() handler receives.\n\nThe first argument of a `NEWAPI()` handler. It holds `opt.name` (the lower-case name of the service), `opt.schema` (the operation), `opt.data`, `opt.controller` (the `$` of the call), `opt.output` (set by `.output()`), `opt.files` (an array of `{ name, filename, path }` added by `.file()`), `opt.retries` (how many times the call was retried), `opt.config` (the config of `NEWAPI()` merged with `.configure()`) and `opt.api` (the API call). `opt.retry()` runs the handler again on the next tick and increases `opt.retries`.\n\nExample: Retry\n```js\nNEWAPI('Weather', function(opt, next) {\n\tcallservice(opt.schema, opt.data, function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response);\n\t});\n});\n```\n\n### API(name, schema, data, [$])\n\nType: `method`\n\nCalls a service registered with NEWAPI().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the service. |\n| `schema` | `String` | yes |  | The operation, passed as `opt.schema`. |\n| `data` | `Object` | yes |  | The payload, passed as `opt.data`. |\n| `$` | `Object` | no |  | The `$` of an action or a controller. |\n\nReturns: `APICall` The call with the methods below.\n\nCreates the call and runs the handler on the next tick, so you configure the call with its methods right away. `$` becomes `opt.controller`. When no handler matches (and no `*` handler exists), the call fails with `API is not initialized`. `F.api()` is the same function.\n\nExample: Inside an action\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).callback($);\n\t}\n});\n```\n\n### API().callback(fn)\n\nType: `method`\n\nSets the callback of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | A callback, or `$`. |\n\nReturns: `APICall`\n\n`fn` is `function(err, response)`, or the `$` of an action, whose `$.callback()` receives the result. `.pipe()` is an alias.\n\nExample: Callback\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### API().promise([$])\n\nType: `method`\n\nReturns a promise of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | The `$` of an action. |\n\nReturns: `Promise`\n\nThe promise resolves with the response. On an error it rejects with an `Error`; when `$` is given, the error goes to `$.invalid()` instead.\n\nExample: Await\n```js\nvar weather = await API('Weather', 'current', { city: 'Oslo' }).promise($);\n```\n\n### API().data(fn)\n\nType: `method`\n\nRuns a function with the response of a successful call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `APICall`\n\n`fn(response)` runs before the callback.\n\nExample: Data\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).data(function(response) {\n\tMAIN.weather = response;\n});\n```\n\n### API().fail(fn)\n\nType: `method`\n\nRuns a function with the error of a failed call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `APICall`\n\n`fn(err)` runs before the callback.\n\nExample: Fail\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).fail(function(err) {\n\tconsole.error(err);\n});\n```\n\n### API().error(message, [reverse])\n\nType: `method`\n\nTurns an empty response into an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | The error. |\n| `reverse` | `Boolean` | no | `false` | Fail on a non-empty response. |\n\nReturns: `APICall`\n\nWhen the handler answers without an error but the response is empty (a falsy value or an empty array), the call fails with `message`. With `reverse`, it fails when the response is truthy (an empty array too). `.err()` is an alias.\n\nExample: Not found\n```js\nAPI('Weather', 'current', model).error('City not found').callback($);\n```\n\n### API().output(type)\n\nType: `method`\n\nSets the output format of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The format, e.g. `json`, `base64`, `stream`. |\n\nReturns: `APICall`\n\nThe value is stored in `opt.output` for the handler. See `TotalAPI()` for the formats of the `TAPI` service.\n\nExample: Base64\n```js\nAPI('Weather', 'map', { city: 'Oslo' }).output('base64').callback(console.log);\n```\n\n### API().file(filename, path, [name])\n\nType: `method`\n\nAdds a file to the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The name of the file. |\n| `path` | `String` | yes |  | The path of the file on the disk. |\n| `name` | `String` | no | `file + index` | The field name. |\n\nReturns: `APICall`\n\nThe file is added to `opt.files` as `{ name, filename, path }`. The default name is `file0`, `file1`, ...\n\nExample: Upload\n```js\nAPI('Storage', 'upload', { folder: 'invoices' }).file('invoice.png', PATH.public('invoice.png')).callback(console.log);\n```\n\n### API().controller($)\n\nType: `method`\n\nSets the controller of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action or a controller. |\n\nReturns: `APICall`\n\nStores `$.controller` (or `$` itself when it has none) in `opt.controller`.\n\nExample: Controller\n```js\nAPI('Weather', 'current', model).controller($).callback($);\n```\n\n### API().audit($, message, [type])\n\nType: `method`\n\nWrites an audit log after a successful call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action. |\n| `message` | `String` | yes |  | The message. |\n| `type` | `String` | no |  | The type of the log. |\n\nReturns: `APICall`\n\nCalls `$.audit(message, type)` once the call succeeds. Placeholders in the message such as `{data.id}` are filled from the data of the call, and `{user.name}` from the user of `$`.\n\nExample: Audit\n```js\nAPI('Billing', 'invoice_create', model).audit($, 'Invoice for {data.email}').callback($);\n```\n\n### API().debug()\n\nType: `method`\n\nPrints the result of the call to the console.\n\nReturns: `APICall`\n\nPrints the name, the operation, the error and the response.\n\nExample: Debug\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).debug().callback(NOOP);\n```\n\n### API().configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nSets configuration keys of the call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The keys to set. |\n\nReturns: `APICall`\n\nCopies the keys of `obj` into `opt.config`. They override the config given to `NEWAPI()`. The `TAPI` service reads `token` from it.\n\nExample: Another token\n```js\nAPI('TAPI', 'check', {}).configure({ token: CONF.customer_token }).callback(console.log);\n```\n\n### TotalAPI(schema, data, [callback])\n\nType: `method`\n\nCalls an operation of Total.js API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | The operation, e.g. `check`. |\n| `data` | `Object` | yes |  | The payload. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `APICall` Configure it like any `API()` call.\n\nThe same as `API('TAPI', schema, data)`. The `TAPI` (or `TotalAPI`) service sends a `POST` request to `https://<$tapiurl>.api.totaljs.com/<schema>/` with the token from `.configure({ token })`, `CONF.totalapi`, `CONF.secret_totalapi` or `CONF.$tapisecret` and the app name. When `$tapi` is `false`, every operation except `check` fails with `totalapi_inactive`. A non-object `data` is sent as `{ value: data }`. With `.output()` the response is `json` (default), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream`, or `#storage [id] [filename]`, which saves it into that FileStorage. A response with a status above `200` fails with the error from Total API.\n\nExample: Check the token\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Save into FileStorage\n```js\n// operation: a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\n### totalapi : token\n\nType: `config`\n\nThe token of Total.js API.\n\nReturns: `String`\n\nA string longer than five characters is stored as `CONF.secret_totalapi` and sent by the `TAPI` service. Any other value (`true`, `false`) is stored as `$tapi`.\n\nExample: Config\n```js\n// /config\ntotalapi       : your-totalapi-token\n```\n\n### $tapi : true\n\nType: `config`\n\nAllows calls of the TAPI service.\n\nReturns: `Boolean`\n\nDefault `true`. When `false`, every `TAPI` operation except `check` fails with `totalapi_inactive`.\n\n### $tapiurl : eu\n\nType: `config`\n\nThe region of Total.js API.\n\nReturns: `String`\n\nDefault `eu`. Requests go to `https://<$tapiurl>.api.totaljs.com/`.\n","entries":[{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [config], callback)","since":"","deprecated":false},{"type":"type","name":"opt","signature":"function(opt, next)","since":"","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, data, [$])","since":"","deprecated":false},{"type":"method","name":"API().callback()","signature":"API().callback(fn)","since":"","deprecated":false},{"type":"method","name":"API().promise()","signature":"API().promise([$])","since":"","deprecated":false},{"type":"method","name":"API().data()","signature":"API().data(fn)","since":"","deprecated":false},{"type":"method","name":"API().fail()","signature":"API().fail(fn)","since":"","deprecated":false},{"type":"method","name":"API().error()","signature":"API().error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"API().output()","signature":"API().output(type)","since":"","deprecated":false},{"type":"method","name":"API().file()","signature":"API().file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"API().controller()","signature":"API().controller($)","since":"","deprecated":false},{"type":"method","name":"API().audit()","signature":"API().audit($, message, [type])","since":"","deprecated":false},{"type":"method","name":"API().debug()","signature":"API().debug()","since":"","deprecated":false},{"type":"method","name":"API().configure()","signature":"API().configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI(schema, data, [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tapi","signature":"$tapi : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tapiurl","signature":"$tapiurl : eu","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafMu547H60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"APIs","summary":"NEWAPI(), API() und seine Methoden, TotalAPI() und ihre Konfigurationsschlüssel.","markdown":"---\ntitle: APIs\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/apis/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# APIs\n\n> NEWAPI(), API() und seine Methoden, TotalAPI() und ihre Konfigurationsschlüssel.\n\nDie Funktionen und Konfigurationsschlüssel von benannten APIs, einschließlich des Dienstes Total.js API. Der Leitfaden [APIs](../../guides/apis/) erklärt mit Beispielen, wie sie zusammenarbeiten; diese Seite ist die genaue Referenz.\n\n## API\n\n### NEWAPI(name, [config], callback)\n\nType: `method`\n\nRegistriert den Code, der einen API-Dienst aufruft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name oder durch Kommas getrennte Namen. |\n| `config` | `Object` | no |  | Standardeinstellungen, die in `opt.config` kopiert werden. |\n| `callback` | `Function` | yes |  | `function(opt, next)`; `next(err, response)` beendet den Aufruf. |\n\nRegistriert den Handler eines API-Services. `this` im Handler ist der API-Aufruf. Ein Name wird in der an `NEWAPI()` übergebenen Schreibweise oder in Kleinbuchstaben gefunden; mehrere durch Kommas getrennte Namen teilen sich einen Handler. Der Name `*` behandelt jeden Namen ohne eigenen Handler. Eine Funktion allein oder ein Konfigurationsobjekt und eine Funktion registrieren den Namen `default`. Die optionale `config` enthält Standardeinstellungen: Vor jedem Aufruf werden ihre Schlüssel in `opt.config` kopiert, außer der Aufruf hat sie bereits mit `.configure()` gesetzt. Übergib `null` als Callback, um einen Handler zu entfernen. `F.newapi()` ist dieselbe Funktion.\n\nExample: Einen Service registrieren\n```js\nNEWAPI('Weather', { region: 'eu' }, function(opt, next) {\n\tREQUEST({ url: 'https://' + opt.config.region + '.weather.example/' + opt.schema + '/', method: 'POST', type: 'json', body: JSON.stringify(opt.data), callback: function(err, response) {\n\t\tnext(err, response && response.body.parseJSON());\n\t}});\n});\n```\n\n### function(opt, next)\n\nType: `type`\n\nDie Optionen, die ein NEWAPI()-Handler erhält.\n\nDas erste Argument eines `NEWAPI()`-Handlers. Es enthält `opt.name` (den kleingeschriebenen Namen des Dienstes), `opt.schema` (die Operation), `opt.data`, `opt.controller` (das `$` des Aufrufs), `opt.output` (gesetzt von `.output()`), `opt.files` (ein Array von `{ name, filename, path }`, hinzugefügt von `.file()`), `opt.retries` (wie oft der Aufruf wiederholt wurde), `opt.config` (die Konfiguration von `NEWAPI()`, zusammengeführt mit `.configure()`) und `opt.api` (den API-Aufruf). `opt.retry()` führt den Handler im nächsten Tick erneut aus und erhöht `opt.retries`.\n\nExample: Wiederholen\n```js\nNEWAPI('Weather', function(opt, next) {\n\tcallservice(opt.schema, opt.data, function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response);\n\t});\n});\n```\n\n### API(name, schema, data, [$])\n\nType: `method`\n\nRuft einen mit NEWAPI() registrierten Dienst auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Dienstes. |\n| `schema` | `String` | yes |  | Die Operation, übergeben als `opt.schema`. |\n| `data` | `Object` | yes |  | Die Nutzdaten, übergeben als `opt.data`. |\n| `$` | `Object` | no |  | Der `$` einer Aktion oder eines Controllers. |\n\nReturns: `APICall` Der Aufruf mit den unten aufgeführten Methoden.\n\nErstellt den Aufruf und führt den Handler im nächsten Tick aus, sodass du den Aufruf sofort mit seinen Methoden konfigurierst. `$` wird zu `opt.controller`. Wenn kein Handler passt (und kein `*`-Handler existiert), schlägt der Aufruf mit `API is not initialized` fehl. `F.api()` ist dieselbe Funktion.\n\nExample: In einer Aktion\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).callback($);\n\t}\n});\n```\n\n### API().callback(fn)\n\nType: `method`\n\nSetzt den Callback des Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | Ein Callback oder `$`. |\n\nReturns: `APICall`\n\n`fn` ist `function(err, response)` oder der `$` einer Aktion, dessen `$.callback()` das Ergebnis erhält. `.pipe()` ist ein Alias.\n\nExample: Callback\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### API().promise([$])\n\nType: `method`\n\nGibt eine Promise des Aufrufs zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Das `$` einer Aktion. |\n\nReturns: `Promise`\n\nDie Promise wird mit der Antwort erfüllt. Bei einem Fehler wird sie mit einem `Error` abgelehnt; wenn `$` angegeben ist, geht der Fehler stattdessen an `$.invalid()`.\n\nExample: Await\n```js\nvar weather = await API('Weather', 'current', { city: 'Oslo' }).promise($);\n```\n\n### API().data(fn)\n\nType: `method`\n\nFührt eine Funktion mit der Antwort eines erfolgreichen Aufrufs aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `APICall`\n\n`fn(response)` läuft vor dem Callback.\n\nExample: Data\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).data(function(response) {\n\tMAIN.weather = response;\n});\n```\n\n### API().fail(fn)\n\nType: `method`\n\nFührt eine Funktion mit dem Fehler eines fehlgeschlagenen Aufrufs aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `APICall`\n\n`fn(err)` läuft vor dem Callback.\n\nExample: Fail\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).fail(function(err) {\n\tconsole.error(err);\n});\n```\n\n### API().error(message, [reverse])\n\nType: `method`\n\nMacht aus einer leeren Antwort einen Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Der Fehler. |\n| `reverse` | `Boolean` | no | `false` | Bei einer nicht leeren Antwort fehlschlagen. |\n\nReturns: `APICall`\n\nWenn der Handler ohne Fehler antwortet, die Antwort aber leer ist (ein falsy Wert oder ein leeres Array), schlägt der Aufruf mit `message` fehl. Mit `reverse` schlägt er fehl, wenn die Antwort truthy ist (auch ein leeres Array). `.err()` ist ein Alias.\n\nExample: Nicht gefunden\n```js\nAPI('Weather', 'current', model).error('City not found').callback($);\n```\n\n### API().output(type)\n\nType: `method`\n\nSetzt das Ausgabeformat des Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Das Format, z. B. `json`, `base64`, `stream`. |\n\nReturns: `APICall`\n\nDer Wert wird für den Handler in `opt.output` gespeichert. Siehe `TotalAPI()` für die Formate des Dienstes `TAPI`.\n\nExample: Base64\n```js\nAPI('Weather', 'map', { city: 'Oslo' }).output('base64').callback(console.log);\n```\n\n### API().file(filename, path, [name])\n\nType: `method`\n\nFügt dem Aufruf eine Datei hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der Name der Datei. |\n| `path` | `String` | yes |  | Der Pfad der Datei auf dem Datenträger. |\n| `name` | `String` | no | `file + index` | Der Feldname. |\n\nReturns: `APICall`\n\nDie Datei wird zu `opt.files` als `{ name, filename, path }` hinzugefügt. Der Standardname ist `file0`, `file1`, ...\n\nExample: Hochladen\n```js\nAPI('Storage', 'upload', { folder: 'invoices' }).file('invoice.png', PATH.public('invoice.png')).callback(console.log);\n```\n\n### API().controller($)\n\nType: `method`\n\nSetzt den Controller des Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Der `$` einer Aktion oder eines Controllers. |\n\nReturns: `APICall`\n\nSpeichert `$.controller` (oder `$` selbst, wenn es keinen hat) in `opt.controller`.\n\nExample: Controller\n```js\nAPI('Weather', 'current', model).controller($).callback($);\n```\n\n### API().audit($, message, [type])\n\nType: `method`\n\nSchreibt nach einem erfolgreichen Aufruf ein Audit-Log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Der `$` einer Aktion. |\n| `message` | `String` | yes |  | Die Nachricht. |\n| `type` | `String` | no |  | Der Typ des Logs. |\n\nReturns: `APICall`\n\nRuft `$.audit(message, type)` auf, sobald der Aufruf erfolgreich ist. Platzhalter in der Nachricht wie `{data.id}` werden aus den Daten des Aufrufs gefüllt und `{user.name}` aus dem Benutzer von `$`.\n\nExample: Audit\n```js\nAPI('Billing', 'invoice_create', model).audit($, 'Invoice for {data.email}').callback($);\n```\n\n### API().debug()\n\nType: `method`\n\nGibt das Ergebnis des Aufrufs in der Konsole aus.\n\nReturns: `APICall`\n\nGibt den Namen, die Operation, den Fehler und die Antwort aus.\n\nExample: Debug\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).debug().callback(NOOP);\n```\n\n### API().configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nSetzt Konfigurationsschlüssel des Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Die zu setzenden Schlüssel. |\n\nReturns: `APICall`\n\nKopiert die Schlüssel von `obj` nach `opt.config`. Sie überschreiben die an `NEWAPI()` übergebene Konfiguration. Der Dienst `TAPI` liest daraus `token`.\n\nExample: Ein anderes Token\n```js\nAPI('TAPI', 'check', {}).configure({ token: CONF.customer_token }).callback(console.log);\n```\n\n### TotalAPI(schema, data, [callback])\n\nType: `method`\n\nRuft eine Operation von Total.js API auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Die Operation, z. B. `check`. |\n| `data` | `Object` | yes |  | Die Nutzdaten. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `APICall` Konfiguriere ihn wie jeden `API()`-Aufruf.\n\nDasselbe wie `API('TAPI', schema, data)`. Der Dienst `TAPI` (oder `TotalAPI`) sendet eine `POST`-Anfrage an `https://<$tapiurl>.api.totaljs.com/<schema>/` mit dem Token aus `.configure({ token })`, `CONF.totalapi`, `CONF.secret_totalapi` oder `CONF.$tapisecret` und dem Namen der Anwendung. Ist `$tapi` gleich `false`, schlägt jede Operation außer `check` mit `totalapi_inactive` fehl. Ein `data`, das kein Objekt ist, wird als `{ value: data }` gesendet. Mit `.output()` ist die Antwort `json` (Standard), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream` oder `#storage [id] [filename]`, das sie in diesem FileStorage speichert. Eine Antwort mit einem Status über `200` schlägt mit dem Fehler der Total API fehl.\n\nExample: Das Token prüfen\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: In FileStorage speichern\n```js\n// operation: a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\n### totalapi : token\n\nType: `config`\n\nDas Token von Total.js API.\n\nReturns: `String`\n\nEin String mit mehr als fünf Zeichen wird als `CONF.secret_totalapi` gespeichert und vom Dienst `TAPI` gesendet. Jeder andere Wert (`true`, `false`) wird als `$tapi` gespeichert.\n\nExample: Konfiguration\n```js\n// /config\ntotalapi       : your-totalapi-token\n```\n\n### $tapi : true\n\nType: `config`\n\nErlaubt Aufrufe des Dienstes TAPI.\n\nReturns: `Boolean`\n\nStandard `true`. Bei `false` schlägt jede `TAPI`-Operation außer `check` mit `totalapi_inactive` fehl.\n\n### $tapiurl : eu\n\nType: `config`\n\nDie Region von Total.js API.\n\nReturns: `String`\n\nStandard `eu`. Anfragen gehen an `https://<$tapiurl>.api.totaljs.com/`.\n","entries":[{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [config], callback)","since":"","deprecated":false},{"type":"type","name":"opt","signature":"function(opt, next)","since":"","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, data, [$])","since":"","deprecated":false},{"type":"method","name":"API().callback()","signature":"API().callback(fn)","since":"","deprecated":false},{"type":"method","name":"API().promise()","signature":"API().promise([$])","since":"","deprecated":false},{"type":"method","name":"API().data()","signature":"API().data(fn)","since":"","deprecated":false},{"type":"method","name":"API().fail()","signature":"API().fail(fn)","since":"","deprecated":false},{"type":"method","name":"API().error()","signature":"API().error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"API().output()","signature":"API().output(type)","since":"","deprecated":false},{"type":"method","name":"API().file()","signature":"API().file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"API().controller()","signature":"API().controller($)","since":"","deprecated":false},{"type":"method","name":"API().audit()","signature":"API().audit($, message, [type])","since":"","deprecated":false},{"type":"method","name":"API().debug()","signature":"API().debug()","since":"","deprecated":false},{"type":"method","name":"API().configure()","signature":"API().configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI(schema, data, [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tapi","signature":"$tapi : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tapiurl","signature":"$tapiurl : eu","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafMu547H60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"APIs","summary":"NEWAPI(), API() y sus métodos, TotalAPI() y sus claves de configuración.","markdown":"---\ntitle: APIs\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/apis/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# APIs\n\n> NEWAPI(), API() y sus métodos, TotalAPI() y sus claves de configuración.\n\nLas funciones y claves de configuración de las APIs con nombre, incluido el servicio Total.js API. La guía [APIs](../../guides/apis/) explica con ejemplos cómo funcionan juntas; esta página es la referencia exacta.\n\n## API\n\n### NEWAPI(name, [config], callback)\n\nType: `method`\n\nRegistra el código que llama a un servicio API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre, o nombres separados por comas. |\n| `config` | `Object` | no |  | Ajustes por defecto que se copian en `opt.config`. |\n| `callback` | `Function` | yes |  | `function(opt, next)`; `next(err, response)` termina la llamada. |\n\nRegistra el handler de un servicio API. `this` en el handler es la llamada a la API. Un nombre se encuentra con la grafía que se le dio en `NEWAPI()` o en minúsculas; varios nombres separados por comas comparten un handler. El nombre `*` gestiona todos los nombres sin handler propio. Una función sola, o un objeto de configuración y una función, registra el nombre `default`. El `config` opcional contiene ajustes por defecto: antes de cada llamada sus claves se copian en `opt.config`, salvo que la llamada ya las haya establecido con `.configure()`. Pasa `null` como callback para eliminar un handler. `F.newapi()` es la misma función.\n\nExample: Registrar un servicio\n```js\nNEWAPI('Weather', { region: 'eu' }, function(opt, next) {\n\tREQUEST({ url: 'https://' + opt.config.region + '.weather.example/' + opt.schema + '/', method: 'POST', type: 'json', body: JSON.stringify(opt.data), callback: function(err, response) {\n\t\tnext(err, response && response.body.parseJSON());\n\t}});\n});\n```\n\n### function(opt, next)\n\nType: `type`\n\nLas opciones que recibe un handler de NEWAPI().\n\nEl primer argumento de un handler de `NEWAPI()`. Contiene `opt.name` (el nombre del servicio en minúsculas), `opt.schema` (la operación), `opt.data`, `opt.controller` (el `$` de la llamada), `opt.output` (establecido por `.output()`), `opt.files` (un array de `{ name, filename, path }` añadidos por `.file()`), `opt.retries` (cuántas veces se reintentó la llamada), `opt.config` (la config de `NEWAPI()` fusionada con `.configure()`) y `opt.api` (la llamada API). `opt.retry()` ejecuta de nuevo el handler en el siguiente tick e incrementa `opt.retries`.\n\nExample: Reintentar\n```js\nNEWAPI('Weather', function(opt, next) {\n\tcallservice(opt.schema, opt.data, function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response);\n\t});\n});\n```\n\n### API(name, schema, data, [$])\n\nType: `method`\n\nLlama a un servicio registrado con NEWAPI().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del servicio. |\n| `schema` | `String` | yes |  | La operación, pasada como `opt.schema`. |\n| `data` | `Object` | yes |  | El payload, pasado como `opt.data`. |\n| `$` | `Object` | no |  | El `$` de una acción o de un controlador. |\n\nReturns: `APICall` La llamada con los métodos de abajo.\n\nCrea la llamada y ejecuta el handler en el siguiente tick, así que configuras la llamada con sus métodos de inmediato. `$` se convierte en `opt.controller`. Cuando ningún handler coincide (y no existe un handler `*`), la llamada falla con `API is not initialized`. `F.api()` es la misma función.\n\nExample: Dentro de una acción\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).callback($);\n\t}\n});\n```\n\n### API().callback(fn)\n\nType: `method`\n\nDefine el callback de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | Un callback, o `$`. |\n\nReturns: `APICall`\n\n`fn` es `function(err, response)`, o el `$` de una acción, cuyo `$.callback()` recibe el resultado. `.pipe()` es un alias.\n\nExample: Callback\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### API().promise([$])\n\nType: `method`\n\nDevuelve una promesa de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | El `$` de una acción. |\n\nReturns: `Promise`\n\nLa promesa se resuelve con la respuesta. En caso de error se rechaza con un `Error`; cuando se da `$`, el error va a `$.invalid()` en su lugar.\n\nExample: Await\n```js\nvar weather = await API('Weather', 'current', { city: 'Oslo' }).promise($);\n```\n\n### API().data(fn)\n\nType: `method`\n\nEjecuta una función con la respuesta de una llamada correcta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `APICall`\n\n`fn(response)` se ejecuta antes del callback.\n\nExample: Data\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).data(function(response) {\n\tMAIN.weather = response;\n});\n```\n\n### API().fail(fn)\n\nType: `method`\n\nEjecuta una función con el error de una llamada fallida.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `APICall`\n\n`fn(err)` se ejecuta antes del callback.\n\nExample: Fail\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).fail(function(err) {\n\tconsole.error(err);\n});\n```\n\n### API().error(message, [reverse])\n\nType: `method`\n\nConvierte una respuesta vacía en un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | El error. |\n| `reverse` | `Boolean` | no | `false` | Fallar con una respuesta no vacía. |\n\nReturns: `APICall`\n\nCuando el handler responde sin error pero la respuesta está vacía (un valor falsy o un array vacío), la llamada falla con `message`. Con `reverse`, falla cuando la respuesta es truthy (también un array vacío). `.err()` es un alias.\n\nExample: No encontrado\n```js\nAPI('Weather', 'current', model).error('City not found').callback($);\n```\n\n### API().output(type)\n\nType: `method`\n\nDefine el formato de salida de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El formato, p. ej. `json`, `base64`, `stream`. |\n\nReturns: `APICall`\n\nEl valor se guarda en `opt.output` para el handler. Consulta `TotalAPI()` para los formatos del servicio `TAPI`.\n\nExample: Base64\n```js\nAPI('Weather', 'map', { city: 'Oslo' }).output('base64').callback(console.log);\n```\n\n### API().file(filename, path, [name])\n\nType: `method`\n\nAñade un archivo a la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El nombre del archivo. |\n| `path` | `String` | yes |  | La ruta del archivo en el disco. |\n| `name` | `String` | no | `file + index` | El nombre del campo. |\n\nReturns: `APICall`\n\nEl archivo se añade a `opt.files` como `{ name, filename, path }`. El nombre por defecto es `file0`, `file1`, ...\n\nExample: Subir\n```js\nAPI('Storage', 'upload', { folder: 'invoices' }).file('invoice.png', PATH.public('invoice.png')).callback(console.log);\n```\n\n### API().controller($)\n\nType: `method`\n\nDefine el controlador de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción o de un controlador. |\n\nReturns: `APICall`\n\nGuarda `$.controller` (o el propio `$` cuando no tiene) en `opt.controller`.\n\nExample: Controlador\n```js\nAPI('Weather', 'current', model).controller($).callback($);\n```\n\n### API().audit($, message, [type])\n\nType: `method`\n\nEscribe un log de auditoría tras una llamada correcta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción. |\n| `message` | `String` | yes |  | El mensaje. |\n| `type` | `String` | no |  | El tipo del log. |\n\nReturns: `APICall`\n\nLlama a `$.audit(message, type)` cuando la llamada termina con éxito. Los placeholders del mensaje como `{data.id}` se rellenan con los datos de la llamada, y `{user.name}` con el usuario de `$`.\n\nExample: Auditoría\n```js\nAPI('Billing', 'invoice_create', model).audit($, 'Invoice for {data.email}').callback($);\n```\n\n### API().debug()\n\nType: `method`\n\nImprime el resultado de la llamada en la consola.\n\nReturns: `APICall`\n\nImprime el nombre, la operación, el error y la respuesta.\n\nExample: Depurar\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).debug().callback(NOOP);\n```\n\n### API().configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nEstablece claves de configuración de la llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Las claves que establecer. |\n\nReturns: `APICall`\n\nCopia las claves de `obj` en `opt.config`. Sobrescriben la config dada a `NEWAPI()`. El servicio `TAPI` lee `token` de ella.\n\nExample: Otro token\n```js\nAPI('TAPI', 'check', {}).configure({ token: CONF.customer_token }).callback(console.log);\n```\n\n### TotalAPI(schema, data, [callback])\n\nType: `method`\n\nLlama a una operación de Total.js API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | La operación, p. ej. `check`. |\n| `data` | `Object` | yes |  | El payload. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `APICall` Configúrala como cualquier llamada `API()`.\n\nLo mismo que `API('TAPI', schema, data)`. El servicio `TAPI` (o `TotalAPI`) envía una petición `POST` a `https://<$tapiurl>.api.totaljs.com/<schema>/` con el token de `.configure({ token })`, `CONF.totalapi`, `CONF.secret_totalapi` o `CONF.$tapisecret` y el nombre de la aplicación. Cuando `$tapi` es `false`, todas las operaciones excepto `check` fallan con `totalapi_inactive`. Un `data` que no es un objeto se envía como `{ value: data }`. Con `.output()` la respuesta es `json` (por defecto), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream` o `#storage [id] [filename]`, que la guarda en ese FileStorage. Una respuesta con un estado superior a `200` falla con el error de Total API.\n\nExample: Comprobar el token\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Guardar en FileStorage\n```js\n// operation: a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\n### totalapi : token\n\nType: `config`\n\nEl token de Total.js API.\n\nReturns: `String`\n\nUna cadena de más de cinco caracteres se guarda como `CONF.secret_totalapi` y la envía el servicio `TAPI`. Cualquier otro valor (`true`, `false`) se guarda como `$tapi`.\n\nExample: Configuración\n```js\n// /config\ntotalapi       : your-totalapi-token\n```\n\n### $tapi : true\n\nType: `config`\n\nPermite las llamadas del servicio TAPI.\n\nReturns: `Boolean`\n\nPor defecto `true`. Con `false`, todas las operaciones de `TAPI` excepto `check` fallan con `totalapi_inactive`.\n\n### $tapiurl : eu\n\nType: `config`\n\nLa región de Total.js API.\n\nReturns: `String`\n\nPor defecto `eu`. Las peticiones van a `https://<$tapiurl>.api.totaljs.com/`.\n","entries":[{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [config], callback)","since":"","deprecated":false},{"type":"type","name":"opt","signature":"function(opt, next)","since":"","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, data, [$])","since":"","deprecated":false},{"type":"method","name":"API().callback()","signature":"API().callback(fn)","since":"","deprecated":false},{"type":"method","name":"API().promise()","signature":"API().promise([$])","since":"","deprecated":false},{"type":"method","name":"API().data()","signature":"API().data(fn)","since":"","deprecated":false},{"type":"method","name":"API().fail()","signature":"API().fail(fn)","since":"","deprecated":false},{"type":"method","name":"API().error()","signature":"API().error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"API().output()","signature":"API().output(type)","since":"","deprecated":false},{"type":"method","name":"API().file()","signature":"API().file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"API().controller()","signature":"API().controller($)","since":"","deprecated":false},{"type":"method","name":"API().audit()","signature":"API().audit($, message, [type])","since":"","deprecated":false},{"type":"method","name":"API().debug()","signature":"API().debug()","since":"","deprecated":false},{"type":"method","name":"API().configure()","signature":"API().configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI(schema, data, [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tapi","signature":"$tapi : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tapiurl","signature":"$tapiurl : eu","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafMu547H60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"API","summary":"NEWAPI(), API() et ses méthodes, TotalAPI() et leurs clés de configuration.","markdown":"---\ntitle: API\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/apis/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# API\n\n> NEWAPI(), API() et ses méthodes, TotalAPI() et leurs clés de configuration.\n\nLes fonctions et les clés de configuration des API nommées, y compris le service Total.js API. Le guide [API](../../guides/apis/) explique comment elles fonctionnent ensemble avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### NEWAPI(name, [config], callback)\n\nType: `method`\n\nEnregistre le code qui appelle un service d'API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom, ou des noms séparés par des virgules. |\n| `config` | `Object` | no |  | Réglages par défaut copiés dans `opt.config`. |\n| `callback` | `Function` | yes |  | `function(opt, next)` ; `next(err, response)` termine l'appel. |\n\nEnregistre le handler d'un service API. `this` dans le handler est l'appel API. Un nom est trouvé dans l'orthographe donnée à `NEWAPI()` ou en minuscules ; plusieurs noms séparés par des virgules partagent un même handler. Le nom `*` traite chaque nom sans handler propre. Une fonction seule, ou un objet de configuration et une fonction, enregistre le nom `default`. Le `config` optionnel contient des réglages par défaut : avant chaque appel, ses clés sont copiées dans `opt.config`, sauf si l'appel les a déjà définies avec `.configure()`. Passe `null` comme callback pour supprimer un handler. `F.newapi()` est la même fonction.\n\nExample: Enregistrer un service\n```js\nNEWAPI('Weather', { region: 'eu' }, function(opt, next) {\n\tREQUEST({ url: 'https://' + opt.config.region + '.weather.example/' + opt.schema + '/', method: 'POST', type: 'json', body: JSON.stringify(opt.data), callback: function(err, response) {\n\t\tnext(err, response && response.body.parseJSON());\n\t}});\n});\n```\n\n### function(opt, next)\n\nType: `type`\n\nLes options que reçoit un gestionnaire NEWAPI().\n\nLe premier argument d'un handler `NEWAPI()`. Il contient `opt.name` (le nom du service en minuscules), `opt.schema` (l'opération), `opt.data`, `opt.controller` (le `$` de l'appel), `opt.output` (défini par `.output()`), `opt.files` (un tableau de `{ name, filename, path }` ajoutés par `.file()`), `opt.retries` (le nombre de fois où l'appel a été relancé), `opt.config` (la configuration de `NEWAPI()` fusionnée avec `.configure()`) et `opt.api` (l'appel d'API). `opt.retry()` exécute à nouveau le handler au tick suivant et incrémente `opt.retries`.\n\nExample: Relancer\n```js\nNEWAPI('Weather', function(opt, next) {\n\tcallservice(opt.schema, opt.data, function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response);\n\t});\n});\n```\n\n### API(name, schema, data, [$])\n\nType: `method`\n\nAppelle un service enregistré avec NEWAPI().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du service. |\n| `schema` | `String` | yes |  | L'opération, transmise comme `opt.schema`. |\n| `data` | `Object` | yes |  | Les données utiles, transmises comme `opt.data`. |\n| `$` | `Object` | no |  | Le `$` d'une action ou d'un contrôleur. |\n\nReturns: `APICall` L'appel avec les méthodes ci-dessous.\n\nCrée l'appel et exécute le gestionnaire au tick suivant, pour que tu configures l'appel tout de suite avec ses méthodes. `$` devient `opt.controller`. Quand aucun gestionnaire ne correspond (et qu'il n'existe pas de gestionnaire `*`), l'appel échoue avec `API is not initialized`. `F.api()` est la même fonction.\n\nExample: Dans une action\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).callback($);\n\t}\n});\n```\n\n### API().callback(fn)\n\nType: `method`\n\nDéfinit le callback de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | Un callback, ou `$`. |\n\nReturns: `APICall`\n\n`fn` est `function(err, response)`, ou le `$` d'une action, dont `$.callback()` reçoit le résultat. `.pipe()` est un alias.\n\nExample: Callback\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### API().promise([$])\n\nType: `method`\n\nRenvoie une promesse de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Le `$` d'une action. |\n\nReturns: `Promise`\n\nLa promesse est résolue avec la réponse. En cas d'erreur, elle est rejetée avec une `Error` ; quand `$` est fourni, l'erreur va plutôt dans `$.invalid()`.\n\nExample: Await\n```js\nvar weather = await API('Weather', 'current', { city: 'Oslo' }).promise($);\n```\n\n### API().data(fn)\n\nType: `method`\n\nExécute une fonction avec la réponse d'un appel réussi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `APICall`\n\n`fn(response)` s'exécute avant le callback.\n\nExample: Data\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).data(function(response) {\n\tMAIN.weather = response;\n});\n```\n\n### API().fail(fn)\n\nType: `method`\n\nExécute une fonction avec l'erreur d'un appel échoué.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `APICall`\n\n`fn(err)` s'exécute avant le callback.\n\nExample: Fail\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).fail(function(err) {\n\tconsole.error(err);\n});\n```\n\n### API().error(message, [reverse])\n\nType: `method`\n\nTransforme une réponse vide en erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | L'erreur. |\n| `reverse` | `Boolean` | no | `false` | Échoue sur une réponse non vide. |\n\nReturns: `APICall`\n\nLorsque le handler répond sans erreur mais que la réponse est vide (une valeur falsy ou un tableau vide), l'appel échoue avec `message`. Avec `reverse`, il échoue lorsque la réponse est truthy (un tableau vide aussi). `.err()` est un alias.\n\nExample: Introuvable\n```js\nAPI('Weather', 'current', model).error('City not found').callback($);\n```\n\n### API().output(type)\n\nType: `method`\n\nDéfinit le format de sortie de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le format, par ex. `json`, `base64`, `stream`. |\n\nReturns: `APICall`\n\nLa valeur est stockée dans `opt.output` pour le gestionnaire. Consulte `TotalAPI()` pour les formats du service `TAPI`.\n\nExample: Base64\n```js\nAPI('Weather', 'map', { city: 'Oslo' }).output('base64').callback(console.log);\n```\n\n### API().file(filename, path, [name])\n\nType: `method`\n\nAjoute un fichier à l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le nom du fichier. |\n| `path` | `String` | yes |  | Le chemin du fichier sur le disque. |\n| `name` | `String` | no | `file + index` | Le nom du champ. |\n\nReturns: `APICall`\n\nLe fichier est ajouté à `opt.files` sous la forme `{ name, filename, path }`. Le nom par défaut est `file0`, `file1`, ...\n\nExample: Téléversement\n```js\nAPI('Storage', 'upload', { folder: 'invoices' }).file('invoice.png', PATH.public('invoice.png')).callback(console.log);\n```\n\n### API().controller($)\n\nType: `method`\n\nDéfinit le contrôleur de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action ou d'un contrôleur. |\n\nReturns: `APICall`\n\nStocke `$.controller` (ou `$` lui-même s'il n'en a pas) dans `opt.controller`.\n\nExample: Contrôleur\n```js\nAPI('Weather', 'current', model).controller($).callback($);\n```\n\n### API().audit($, message, [type])\n\nType: `method`\n\nÉcrit un journal d'audit après un appel réussi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action. |\n| `message` | `String` | yes |  | Le message. |\n| `type` | `String` | no |  | Le type du journal. |\n\nReturns: `APICall`\n\nAppelle `$.audit(message, type)` une fois l'appel réussi. Les placeholders du message comme `{data.id}` sont remplis à partir des données de l'appel, et `{user.name}` à partir de l'utilisateur de `$`.\n\nExample: Audit\n```js\nAPI('Billing', 'invoice_create', model).audit($, 'Invoice for {data.email}').callback($);\n```\n\n### API().debug()\n\nType: `method`\n\nAffiche le résultat de l'appel dans la console.\n\nReturns: `APICall`\n\nAffiche le nom, l'opération, l'erreur et la réponse.\n\nExample: Débogage\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).debug().callback(NOOP);\n```\n\n### API().configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nDéfinit des clés de configuration de l'appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Les clés à définir. |\n\nReturns: `APICall`\n\nCopie les clés de `obj` dans `opt.config`. Elles remplacent la configuration donnée à `NEWAPI()`. Le service `TAPI` y lit `token`.\n\nExample: Un autre token\n```js\nAPI('TAPI', 'check', {}).configure({ token: CONF.customer_token }).callback(console.log);\n```\n\n### TotalAPI(schema, data, [callback])\n\nType: `method`\n\nAppelle une opération de Total.js API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | L'opération, par ex. `check`. |\n| `data` | `Object` | yes |  | Les données utiles. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `APICall` Configure-le comme n'importe quel appel `API()`.\n\nIdentique à `API('TAPI', schema, data)`. Le service `TAPI` (ou `TotalAPI`) envoie une requête `POST` à `https://<$tapiurl>.api.totaljs.com/<schema>/` avec le token provenant de `.configure({ token })`, `CONF.totalapi`, `CONF.secret_totalapi` ou `CONF.$tapisecret` et le nom de l'application. Lorsque `$tapi` vaut `false`, toute opération sauf `check` échoue avec `totalapi_inactive`. Une `data` qui n'est pas un objet est envoyée sous la forme `{ value: data }`. Avec `.output()`, la réponse est `json` (par défaut), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream`, ou `#storage [id] [filename]`, qui l'enregistre dans ce FileStorage. Une réponse avec un statut supérieur à `200` échoue avec l'erreur de Total API.\n\nExample: Vérifier le jeton\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Enregistrer dans FileStorage\n```js\n// operation: a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\n### totalapi : token\n\nType: `config`\n\nLe jeton de Total.js API.\n\nReturns: `String`\n\nUne chaîne de plus de cinq caractères est stockée comme `CONF.secret_totalapi` et envoyée par le service `TAPI`. Toute autre valeur (`true`, `false`) est stockée comme `$tapi`.\n\nExample: Configuration\n```js\n// /config\ntotalapi       : your-totalapi-token\n```\n\n### $tapi : true\n\nType: `config`\n\nAutorise les appels du service TAPI.\n\nReturns: `Boolean`\n\nPar défaut `true`. Avec `false`, chaque opération `TAPI` sauf `check` échoue avec `totalapi_inactive`.\n\n### $tapiurl : eu\n\nType: `config`\n\nLa région de Total.js API.\n\nReturns: `String`\n\nPar défaut `eu`. Les requêtes vont vers `https://<$tapiurl>.api.totaljs.com/`.\n","entries":[{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [config], callback)","since":"","deprecated":false},{"type":"type","name":"opt","signature":"function(opt, next)","since":"","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, data, [$])","since":"","deprecated":false},{"type":"method","name":"API().callback()","signature":"API().callback(fn)","since":"","deprecated":false},{"type":"method","name":"API().promise()","signature":"API().promise([$])","since":"","deprecated":false},{"type":"method","name":"API().data()","signature":"API().data(fn)","since":"","deprecated":false},{"type":"method","name":"API().fail()","signature":"API().fail(fn)","since":"","deprecated":false},{"type":"method","name":"API().error()","signature":"API().error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"API().output()","signature":"API().output(type)","since":"","deprecated":false},{"type":"method","name":"API().file()","signature":"API().file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"API().controller()","signature":"API().controller($)","since":"","deprecated":false},{"type":"method","name":"API().audit()","signature":"API().audit($, message, [type])","since":"","deprecated":false},{"type":"method","name":"API().debug()","signature":"API().debug()","since":"","deprecated":false},{"type":"method","name":"API().configure()","signature":"API().configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI(schema, data, [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tapi","signature":"$tapi : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tapiurl","signature":"$tapiurl : eu","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafMu547H60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"API","summary":"NEWAPI(), API() e i suoi metodi, TotalAPI() e le relative chiavi di configurazione.","markdown":"---\ntitle: API\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/apis/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# API\n\n> NEWAPI(), API() e i suoi metodi, TotalAPI() e le relative chiavi di configurazione.\n\nLe funzioni e le chiavi di configurazione delle API con nome, incluso il servizio Total.js API. La guida [API](../../guides/apis/) spiega come funzionano insieme con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### NEWAPI(name, [config], callback)\n\nType: `method`\n\nRegistra il codice che chiama un servizio API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome, o più nomi separati da virgole. |\n| `config` | `Object` | no |  | Impostazioni predefinite copiate in `opt.config`. |\n| `callback` | `Function` | yes |  | `function(opt, next)`; `next(err, response)` termina la chiamata. |\n\nRegistra l'handler di un servizio API. `this` nell'handler è la chiamata API. Un nome viene trovato nella grafia data a `NEWAPI()` o in minuscolo; più nomi separati da virgole condividono un unico handler. Il nome `*` gestisce ogni nome senza un handler proprio. Una funzione da sola, o un oggetto di configurazione e una funzione, registra il nome `default`. Il `config` opzionale contiene le impostazioni predefinite: prima di ogni chiamata le sue chiavi vengono copiate in `opt.config`, a meno che la chiamata non le abbia già impostate con `.configure()`. Passa `null` come callback per rimuovere un handler. `F.newapi()` è la stessa funzione.\n\nExample: Registrare un servizio\n```js\nNEWAPI('Weather', { region: 'eu' }, function(opt, next) {\n\tREQUEST({ url: 'https://' + opt.config.region + '.weather.example/' + opt.schema + '/', method: 'POST', type: 'json', body: JSON.stringify(opt.data), callback: function(err, response) {\n\t\tnext(err, response && response.body.parseJSON());\n\t}});\n});\n```\n\n### function(opt, next)\n\nType: `type`\n\nLe opzioni che riceve un handler di NEWAPI().\n\nIl primo argomento di un handler di `NEWAPI()`. Contiene `opt.name` (il nome del servizio in minuscolo), `opt.schema` (l'operazione), `opt.data`, `opt.controller` (il `$` della chiamata), `opt.output` (impostato da `.output()`), `opt.files` (un array di `{ name, filename, path }` aggiunti da `.file()`), `opt.retries` (quante volte la chiamata è stata ritentata), `opt.config` (la config di `NEWAPI()` unita a `.configure()`) e `opt.api` (la chiamata API). `opt.retry()` esegue di nuovo l'handler al tick successivo e incrementa `opt.retries`.\n\nExample: Ripetere\n```js\nNEWAPI('Weather', function(opt, next) {\n\tcallservice(opt.schema, opt.data, function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response);\n\t});\n});\n```\n\n### API(name, schema, data, [$])\n\nType: `method`\n\nChiama un servizio registrato con NEWAPI().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del servizio. |\n| `schema` | `String` | yes |  | L'operazione, passata come `opt.schema`. |\n| `data` | `Object` | yes |  | Il payload, passato come `opt.data`. |\n| `$` | `Object` | no |  | Il `$` di un'azione o di un controller. |\n\nReturns: `APICall` La chiamata con i metodi descritti sotto.\n\nCrea la chiamata ed esegue l'handler al tick successivo, così configuri subito la chiamata con i suoi metodi. `$` diventa `opt.controller`. Quando nessun handler corrisponde (e non esiste un handler `*`), la chiamata fallisce con `API is not initialized`. `F.api()` è la stessa funzione.\n\nExample: Dentro un'azione\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).callback($);\n\t}\n});\n```\n\n### API().callback(fn)\n\nType: `method`\n\nImposta la callback della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | Una callback, oppure `$`. |\n\nReturns: `APICall`\n\n`fn` è `function(err, response)`, oppure il `$` di un'azione, il cui `$.callback()` riceve il risultato. `.pipe()` è un alias.\n\nExample: Callback\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### API().promise([$])\n\nType: `method`\n\nRestituisce una promise della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Il `$` di un'azione. |\n\nReturns: `Promise`\n\nLa promise si risolve con la risposta. In caso di errore viene rifiutata con un `Error`; quando è dato `$`, l'errore va invece a `$.invalid()`.\n\nExample: Await\n```js\nvar weather = await API('Weather', 'current', { city: 'Oslo' }).promise($);\n```\n\n### API().data(fn)\n\nType: `method`\n\nEsegue una funzione con la risposta di una chiamata riuscita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `APICall`\n\n`fn(response)` viene eseguita prima della callback.\n\nExample: Dati\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).data(function(response) {\n\tMAIN.weather = response;\n});\n```\n\n### API().fail(fn)\n\nType: `method`\n\nEsegue una funzione con l'errore di una chiamata fallita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `APICall`\n\n`fn(err)` viene eseguita prima della callback.\n\nExample: Fallimento\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).fail(function(err) {\n\tconsole.error(err);\n});\n```\n\n### API().error(message, [reverse])\n\nType: `method`\n\nTrasforma una risposta vuota in un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | L'errore. |\n| `reverse` | `Boolean` | no | `false` | Fallire con una risposta non vuota. |\n\nReturns: `APICall`\n\nQuando l'handler risponde senza errore ma la risposta è vuota (un valore falsy o un array vuoto), la chiamata fallisce con `message`. Con `reverse`, fallisce quando la risposta è truthy (anche un array vuoto). `.err()` è un alias.\n\nExample: Non trovato\n```js\nAPI('Weather', 'current', model).error('City not found').callback($);\n```\n\n### API().output(type)\n\nType: `method`\n\nImposta il formato di output della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il formato, es. `json`, `base64`, `stream`. |\n\nReturns: `APICall`\n\nIl valore viene memorizzato in `opt.output` per l'handler. Vedi `TotalAPI()` per i formati del servizio `TAPI`.\n\nExample: Base64\n```js\nAPI('Weather', 'map', { city: 'Oslo' }).output('base64').callback(console.log);\n```\n\n### API().file(filename, path, [name])\n\nType: `method`\n\nAggiunge un file alla chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il nome del file. |\n| `path` | `String` | yes |  | Il percorso del file sul disco. |\n| `name` | `String` | no | `file + index` | Il nome del campo. |\n\nReturns: `APICall`\n\nIl file viene aggiunto a `opt.files` come `{ name, filename, path }`. Il nome predefinito è `file0`, `file1`, ...\n\nExample: Upload\n```js\nAPI('Storage', 'upload', { folder: 'invoices' }).file('invoice.png', PATH.public('invoice.png')).callback(console.log);\n```\n\n### API().controller($)\n\nType: `method`\n\nImposta il controller della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione o di un controller. |\n\nReturns: `APICall`\n\nMemorizza `$.controller` (o `$` stesso quando non ne ha uno) in `opt.controller`.\n\nExample: Controller\n```js\nAPI('Weather', 'current', model).controller($).callback($);\n```\n\n### API().audit($, message, [type])\n\nType: `method`\n\nScrive un log di audit dopo una chiamata riuscita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione. |\n| `message` | `String` | yes |  | Il messaggio. |\n| `type` | `String` | no |  | Il tipo del log. |\n\nReturns: `APICall`\n\nChiama `$.audit(message, type)` quando la chiamata riesce. I segnaposto nel messaggio come `{data.id}` vengono riempiti con i dati della chiamata, e `{user.name}` con l'utente di `$`.\n\nExample: Audit\n```js\nAPI('Billing', 'invoice_create', model).audit($, 'Invoice for {data.email}').callback($);\n```\n\n### API().debug()\n\nType: `method`\n\nStampa il risultato della chiamata nella console.\n\nReturns: `APICall`\n\nStampa il nome, l'operazione, l'errore e la risposta.\n\nExample: Debug\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).debug().callback(NOOP);\n```\n\n### API().configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nImposta le chiavi di configurazione della chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Le chiavi da impostare. |\n\nReturns: `APICall`\n\nCopia le chiavi di `obj` in `opt.config`. Hanno la precedenza sulla config data a `NEWAPI()`. Il servizio `TAPI` legge `token` da qui.\n\nExample: Un altro token\n```js\nAPI('TAPI', 'check', {}).configure({ token: CONF.customer_token }).callback(console.log);\n```\n\n### TotalAPI(schema, data, [callback])\n\nType: `method`\n\nChiama un'operazione di Total.js API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | L'operazione, es. `check`. |\n| `data` | `Object` | yes |  | Il payload. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `APICall` Configurala come qualsiasi chiamata `API()`.\n\nEquivale a `API('TAPI', schema, data)`. Il servizio `TAPI` (o `TotalAPI`) invia una richiesta `POST` a `https://<$tapiurl>.api.totaljs.com/<schema>/` con il token da `.configure({ token })`, `CONF.totalapi`, `CONF.secret_totalapi` o `CONF.$tapisecret` e il nome dell'app. Quando `$tapi` è `false`, ogni operazione tranne `check` fallisce con `totalapi_inactive`. Un `data` che non è un oggetto viene inviato come `{ value: data }`. Con `.output()` la risposta è `json` (predefinito), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream` oppure `#storage [id] [filename]`, che la salva in quel FileStorage. Una risposta con uno stato superiore a `200` fallisce con l'errore di Total API.\n\nExample: Verificare il token\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Salvare in FileStorage\n```js\n// operation: a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\n### totalapi : token\n\nType: `config`\n\nIl token di Total.js API.\n\nReturns: `String`\n\nUna stringa più lunga di cinque caratteri viene memorizzata come `CONF.secret_totalapi` e inviata dal servizio `TAPI`. Qualsiasi altro valore (`true`, `false`) viene memorizzato come `$tapi`.\n\nExample: Configurazione\n```js\n// /config\ntotalapi       : your-totalapi-token\n```\n\n### $tapi : true\n\nType: `config`\n\nConsente le chiamate del servizio TAPI.\n\nReturns: `Boolean`\n\nPredefinito `true`. Quando è `false`, ogni operazione `TAPI` tranne `check` fallisce con `totalapi_inactive`.\n\n### $tapiurl : eu\n\nType: `config`\n\nLa regione di Total.js API.\n\nReturns: `String`\n\nPredefinito `eu`. Le richieste vanno a `https://<$tapiurl>.api.totaljs.com/`.\n","entries":[{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [config], callback)","since":"","deprecated":false},{"type":"type","name":"opt","signature":"function(opt, next)","since":"","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, data, [$])","since":"","deprecated":false},{"type":"method","name":"API().callback()","signature":"API().callback(fn)","since":"","deprecated":false},{"type":"method","name":"API().promise()","signature":"API().promise([$])","since":"","deprecated":false},{"type":"method","name":"API().data()","signature":"API().data(fn)","since":"","deprecated":false},{"type":"method","name":"API().fail()","signature":"API().fail(fn)","since":"","deprecated":false},{"type":"method","name":"API().error()","signature":"API().error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"API().output()","signature":"API().output(type)","since":"","deprecated":false},{"type":"method","name":"API().file()","signature":"API().file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"API().controller()","signature":"API().controller($)","since":"","deprecated":false},{"type":"method","name":"API().audit()","signature":"API().audit($, message, [type])","since":"","deprecated":false},{"type":"method","name":"API().debug()","signature":"API().debug()","since":"","deprecated":false},{"type":"method","name":"API().configure()","signature":"API().configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI(schema, data, [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tapi","signature":"$tapi : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tapiurl","signature":"$tapiurl : eu","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafMu547H60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/apis/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"API","summary":"NEWAPI(), API() a jeho metódy, TotalAPI() a ich konfiguračné kľúče.","markdown":"---\ntitle: API\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/apis/\nupdated: 2026-11-18T16:57:19.575Z\n---\n\n# API\n\n> NEWAPI(), API() a jeho metódy, TotalAPI() a ich konfiguračné kľúče.\n\nFunkcie a konfiguračné kľúče pomenovaných API vrátane služby Total.js API. Návod [API](../../guides/apis/) vysvetľuje na príkladoch, ako spolu fungujú; táto stránka je presná referencia.\n\n## API\n\n### NEWAPI(name, [config], callback)\n\nType: `method`\n\nZaregistruje kód, ktorý volá jednu API službu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Meno alebo mená oddelené čiarkami. |\n| `config` | `Object` | no |  | Predvolené nastavenia skopírované do `opt.config`. |\n| `callback` | `Function` | yes |  | `function(opt, next)`; `next(err, response)` ukončí volanie. |\n\nZaregistruje handler API služby. `this` v handleri je volanie API. Meno sa nájde v podobe zadanej do `NEWAPI()` alebo malými písmenami; viac mien oddelených čiarkami zdieľa jeden handler. Meno `*` obsluhuje každé meno bez vlastného handlera. Samotná funkcia alebo konfiguračný objekt a funkcia zaregistruje meno `default`. Voliteľný `config` obsahuje predvolené nastavenia: pred každým volaním sa jeho kľúče skopírujú do `opt.config`, pokiaľ ich volanie už nenastavilo cez `.configure()`. Odovzdaj `null` ako callback, aby si handler odstránil. `F.newapi()` je tá istá funkcia.\n\nExample: Registrácia služby\n```js\nNEWAPI('Weather', { region: 'eu' }, function(opt, next) {\n\tREQUEST({ url: 'https://' + opt.config.region + '.weather.example/' + opt.schema + '/', method: 'POST', type: 'json', body: JSON.stringify(opt.data), callback: function(err, response) {\n\t\tnext(err, response && response.body.parseJSON());\n\t}});\n});\n```\n\n### function(opt, next)\n\nType: `type`\n\nVoľby, ktoré dostane handler NEWAPI().\n\nPrvý argument handlera `NEWAPI()`. Obsahuje `opt.name` (názov služby malými písmenami), `opt.schema` (operácia), `opt.data`, `opt.controller` (`$` volania), `opt.output` (nastavené cez `.output()`), `opt.files` (pole `{ name, filename, path }` pridaných cez `.file()`), `opt.retries` (koľkokrát sa volanie opakovalo), `opt.config` (konfigurácia z `NEWAPI()` zlúčená s `.configure()`) a `opt.api` (volanie API). `opt.retry()` spustí handler znova v nasledujúcom ticku a zvýši `opt.retries`.\n\nExample: Opakovanie\n```js\nNEWAPI('Weather', function(opt, next) {\n\tcallservice(opt.schema, opt.data, function(err, response) {\n\t\tif (err && opt.retries < 3)\n\t\t\topt.retry();\n\t\telse\n\t\t\tnext(err, response);\n\t});\n});\n```\n\n### API(name, schema, data, [$])\n\nType: `method`\n\nZavolá službu zaregistrovanú cez NEWAPI().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov služby. |\n| `schema` | `String` | yes |  | Operácia, odovzdá sa ako `opt.schema`. |\n| `data` | `Object` | yes |  | Payload, odovzdá sa ako `opt.data`. |\n| `$` | `Object` | no |  | `$` akcie alebo controllera. |\n\nReturns: `APICall` Volanie s nižšie uvedenými metódami.\n\nVytvorí volanie a spustí handler v nasledujúcom ticku, takže volanie môžeš hneď nastaviť jeho metódami. `$` sa stane `opt.controller`. Keď nezodpovedá žiadny handler (a neexistuje handler `*`), volanie zlyhá s `API is not initialized`. `F.api()` je tá istá funkcia.\n\nExample: V akcii\n```js\nNEWACTION('weather_read', {\n\tinput: '*city:String',\n\taction: function($, model) {\n\t\tAPI('Weather', 'current', model).callback($);\n\t}\n});\n```\n\n### API().callback(fn)\n\nType: `method`\n\nNastaví callback volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | Callback alebo `$`. |\n\nReturns: `APICall`\n\n`fn` je `function(err, response)` alebo `$` akcie, ktorej `$.callback()` dostane výsledok. `.pipe()` je alias.\n\nExample: Callback\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### API().promise([$])\n\nType: `method`\n\nVráti promise volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | `$` akcie. |\n\nReturns: `Promise`\n\nPromise sa vyrieši s odpoveďou. Pri chybe sa zamietne s `Error`; keď je zadaný `$`, chyba ide namiesto toho do `$.invalid()`.\n\nExample: Await\n```js\nvar weather = await API('Weather', 'current', { city: 'Oslo' }).promise($);\n```\n\n### API().data(fn)\n\nType: `method`\n\nSpustí funkciu s odpoveďou úspešného volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `APICall`\n\n`fn(response)` sa spustí pred callbackom.\n\nExample: Dáta\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).data(function(response) {\n\tMAIN.weather = response;\n});\n```\n\n### API().fail(fn)\n\nType: `method`\n\nSpustí funkciu s chybou neúspešného volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)`. |\n\nReturns: `APICall`\n\n`fn(err)` sa spustí pred callbackom.\n\nExample: Zlyhanie\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).fail(function(err) {\n\tconsole.error(err);\n});\n```\n\n### API().error(message, [reverse])\n\nType: `method`\n\nZmení prázdnu odpoveď na chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Chyba. |\n| `reverse` | `Boolean` | no | `false` | Zlyhať pri neprázdnej odpovedi. |\n\nReturns: `APICall`\n\nKeď handler odpovie bez chyby, ale odpoveď je prázdna (nepravdivá hodnota alebo prázdne pole), volanie zlyhá s `message`. S `reverse` zlyhá, keď je odpoveď pravdivá (aj prázdne pole). `.err()` je alias.\n\nExample: Nenájdené\n```js\nAPI('Weather', 'current', model).error('City not found').callback($);\n```\n\n### API().output(type)\n\nType: `method`\n\nNastaví výstupný formát volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Formát, napr. `json`, `base64`, `stream`. |\n\nReturns: `APICall`\n\nHodnota sa pre handler uloží do `opt.output`. Formáty služby `TAPI` nájdeš pri `TotalAPI()`.\n\nExample: Base64\n```js\nAPI('Weather', 'map', { city: 'Oslo' }).output('base64').callback(console.log);\n```\n\n### API().file(filename, path, [name])\n\nType: `method`\n\nPridá k volaniu súbor.\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. |\n\nReturns: `APICall`\n\nSúbor sa pridá do `opt.files` ako `{ name, filename, path }`. Predvolený názov je `file0`, `file1`, ...\n\nExample: Nahranie\n```js\nAPI('Storage', 'upload', { folder: 'invoices' }).file('invoice.png', PATH.public('invoice.png')).callback(console.log);\n```\n\n### API().controller($)\n\nType: `method`\n\nNastaví controller volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie alebo controllera. |\n\nReturns: `APICall`\n\nUloží `$.controller` (alebo samotný `$`, keď žiadny nemá) do `opt.controller`.\n\nExample: Controller\n```js\nAPI('Weather', 'current', model).controller($).callback($);\n```\n\n### API().audit($, message, [type])\n\nType: `method`\n\nPo úspešnom volaní zapíše audit log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie. |\n| `message` | `String` | yes |  | Správa. |\n| `type` | `String` | no |  | Typ logu. |\n\nReturns: `APICall`\n\nPo úspechu volania zavolá `$.audit(message, type)`. Zástupné symboly v správe ako `{data.id}` sa vyplnia z dát volania a `{user.name}` z používateľa `$`.\n\nExample: Audit\n```js\nAPI('Billing', 'invoice_create', model).audit($, 'Invoice for {data.email}').callback($);\n```\n\n### API().debug()\n\nType: `method`\n\nVypíše výsledok volania do konzoly.\n\nReturns: `APICall`\n\nVypíše názov, operáciu, chybu a odpoveď.\n\nExample: Ladenie\n```js\nAPI('Weather', 'current', { city: 'Oslo' }).debug().callback(NOOP);\n```\n\n### API().configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nNastaví konfiguračné kľúče volania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Kľúče na nastavenie. |\n\nReturns: `APICall`\n\nSkopíruje kľúče `obj` do `opt.config`. Prepíšu konfiguráciu zadanú do `NEWAPI()`. Služba `TAPI` z nej číta `token`.\n\nExample: Iný token\n```js\nAPI('TAPI', 'check', {}).configure({ token: CONF.customer_token }).callback(console.log);\n```\n\n### TotalAPI(schema, data, [callback])\n\nType: `method`\n\nZavolá operáciu Total.js API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Operácia, napr. `check`. |\n| `data` | `Object` | yes |  | Payload. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `APICall` Nastav ho ako akékoľvek volanie `API()`.\n\nTo isté ako `API('TAPI', schema, data)`. Služba `TAPI` (alebo `TotalAPI`) odošle požiadavku `POST` na `https://<$tapiurl>.api.totaljs.com/<schema>/` s tokenom z `.configure({ token })`, `CONF.totalapi`, `CONF.secret_totalapi` alebo `CONF.$tapisecret` a s názvom aplikácie. Keď je `$tapi` rovné `false`, každá operácia okrem `check` zlyhá s `totalapi_inactive`. Neobjektové `data` sa odošlú ako `{ value: data }`. S `.output()` je odpoveď `json` (predvolene), `html`, `plain`, `text`, `buffer`, `binary`, `base64`, `stream` alebo `#storage [id] [filename]`, čo ju uloží do daného FileStorage. Odpoveď so stavom vyšším ako `200` zlyhá s chybou z Total API.\n\nExample: Kontrola tokenu\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Uloženie do FileStorage\n```js\n// operation: a Total API operation that returns a file\nAPI('TAPI', operation, data).output('#files').callback(console.log);\n```\n\n### totalapi : token\n\nType: `config`\n\nToken Total.js API.\n\nReturns: `String`\n\nReťazec dlhší ako päť znakov sa uloží ako `CONF.secret_totalapi` a posiela ho služba `TAPI`. Akákoľvek iná hodnota (`true`, `false`) sa uloží ako `$tapi`.\n\nExample: Konfigurácia\n```js\n// /config\ntotalapi       : your-totalapi-token\n```\n\n### $tapi : true\n\nType: `config`\n\nPovolí volania služby TAPI.\n\nReturns: `Boolean`\n\nPredvolene `true`. Pri `false` každá operácia `TAPI` okrem `check` zlyhá s `totalapi_inactive`.\n\n### $tapiurl : eu\n\nType: `config`\n\nRegión Total.js API.\n\nReturns: `String`\n\nPredvolene `eu`. Požiadavky idú na `https://<$tapiurl>.api.totaljs.com/`.\n","entries":[{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [config], callback)","since":"","deprecated":false},{"type":"type","name":"opt","signature":"function(opt, next)","since":"","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, data, [$])","since":"","deprecated":false},{"type":"method","name":"API().callback()","signature":"API().callback(fn)","since":"","deprecated":false},{"type":"method","name":"API().promise()","signature":"API().promise([$])","since":"","deprecated":false},{"type":"method","name":"API().data()","signature":"API().data(fn)","since":"","deprecated":false},{"type":"method","name":"API().fail()","signature":"API().fail(fn)","since":"","deprecated":false},{"type":"method","name":"API().error()","signature":"API().error(message, [reverse])","since":"","deprecated":false},{"type":"method","name":"API().output()","signature":"API().output(type)","since":"","deprecated":false},{"type":"method","name":"API().file()","signature":"API().file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"API().controller()","signature":"API().controller($)","since":"","deprecated":false},{"type":"method","name":"API().audit()","signature":"API().audit($, message, [type])","since":"","deprecated":false},{"type":"method","name":"API().debug()","signature":"API().debug()","since":"","deprecated":false},{"type":"method","name":"API().configure()","signature":"API().configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI(schema, data, [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"CONF.$tapi","signature":"$tapi : true","since":"","deprecated":false},{"type":"config","name":"CONF.$tapiurl","signature":"$tapiurl : eu","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:19.575Z"}
{"id":"JafwvT9Ex61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Workers, threads and cluster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, the cluster options, SHELL(), F.python(), F.pipinstall() and PYPELINE().","markdown":"---\ntitle: Workers, threads and cluster\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/workers-and-threads/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Workers, threads and cluster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, the cluster options, SHELL(), F.python(), F.pipinstall() and PYPELINE().\n\nMethods, properties, start options and events for worker threads, forked processes, thread pools, the cluster, `SHELL()` and `PYPELINE()`. For an introduction with examples read the guide [Workers, threads and cluster](../../guides/workers-and-threads/).\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nStarts a worker thread from the workers/ folder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file name in `workers/` without `.js`, or `~` and an absolute path |\n| `data` | `Object` | no |  | Data copied into the thread as `F.worker.data` |\n\nReturns: `Worker` The Node.js worker thread\n\nRuns `workers/{name}.js` in a new Node.js worker thread. A name that starts with `~` is an absolute path to the script. `data` is copied into the thread and is available there as `F.worker.data`. The thread receives `--worker` in its `process.argv`.\n\nThe result is the Node.js `Worker` object: use `postMessage()` to send a message and `on('message')`, `on('error')` and `on('exit')` to listen. The framework adds `kill()` and `exit()`, which call `terminate()`.\n\nExample: Start a thread\n```js\nvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\nthread.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tthread.kill();\n});\n\nthread.postMessage({ a: 1, b: 2 });\n```\n\n### NEWTHREAD()\n\nType: `method`\n\nInside a worker script: returns the worker object F.worker.\n\nReturns: `Object` F.worker\n\nCalled without a name in a script that runs as a worker, `NEWTHREAD()` creates `F.worker` (or returns it when it exists), sets the application directory to the current working directory and starts passing the messages from the parent to `F.worker.message`. Load the framework with `require('total5')` before you call it.\n\nExample: workers/calc.js\n```js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tworker.send({ sum: msg.a + msg.b });\n};\n```\n\n### F.worker\n\nType: `property`\n\nThe worker object of a script that runs as a worker.\n\nReturns: `Object`\n\nCreated by `NEWTHREAD()` (or `NEWFORK()`) without a name. It holds the data from the parent and the methods to receive and send messages and to end the worker. In the main application it is `undefined`.\n\nExample: Check the data\n```js\nvar worker = NEWTHREAD();\nconsole.log(F.worker === worker); // true\nconsole.log(worker.data);\n```\n\n### F.worker.data\n\nType: `property`\n\nThe data passed to NEWTHREAD(name, data).\n\nReturns: `Object`\n\nA copy of the second argument of `NEWTHREAD()` in the main thread. It is an empty object `{}` when no data were passed, in a fork and in the threads of a pool.\n\nExample: Read the data\n```js\nvar worker = NEWTHREAD();\nvar user = worker.data.user;\n```\n\n### F.worker.is\n\nType: `property`\n\ntrue when the script runs as a worker.\n\nReturns: `Boolean`\n\n`true` in a thread from `NEWTHREAD()`, in a fork from `NEWFORK()` and in the workers of `NEWTHREADPOOL()`: they all get the argument `--worker` in `process.argv`.\n\nExample: Run as a worker or alone\n```js\nvar worker = NEWTHREAD();\nif (!worker.is)\n\tconsole.log('Started directly with node, not as a worker');\n```\n\n### F.worker.isfork\n\nType: `property`\n\ntrue in a forked process, false in a worker thread.\n\nReturns: `Boolean`\n\n`true` when the worker is a process from `NEWFORK()` (messages go through `process.send()`), `false` in a worker thread.\n\nExample: Thread or process\n```js\nvar worker = NEWTHREAD();\nconsole.log(worker.isfork ? 'process ' + process.pid : 'thread');\n```\n\n### F.worker.message = function(msg) {}\n\nType: `delegate`\n\nReceives the messages from the parent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | The message from the parent |\n\nAssign a function. It is called with every message the parent sends with `postMessage()`. The default does nothing.\n\nExample: Answer messages\n```js\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tif (msg.type === 'ping')\n\t\tworker.send({ type: 'pong' });\n};\n```\n\n### F.worker.send(msg)\n\nType: `method`\n\nSends a message to the parent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | The message; it is copied, functions are not allowed |\n\nSends the message to the process or thread that started the worker. `F.worker.postMessage()` is the same method. The parent receives it in `on('message')`.\n\nExample: Send a result\n```js\nworker.send({ id: msg.id, result: result });\n```\n\n### F.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)`. Inside a thread it ends the thread; the parent gets the `exit` event with the code. `F.worker.kill()` and `F.worker.close()` are the same method.\n\nExample: End after the job\n```js\nworker.message = function(msg) {\n\twork(msg);\n\tworker.exit();\n};\n```\n\n### F.worker.setTimeout(timeout)\n\nType: `method`\n\nEnds the worker with code 1 after a timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Milliseconds |\n\nStarts a countdown. When it runs out, the worker ends with exit code `1`. A new call clears the previous countdown and starts a new one, so call it at the start of each job.\n\nExample: Watchdog\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\tjob(msg, function(response) {\n\t\tworker.send(response);\n\t});\n};\n```\n\n### thread.kill()\n\nType: `method`\n\nStops a thread started with NEWTHREAD().\n\nCalls `terminate()` of the Node.js `Worker`. `thread.exit()` is the same method.\n\nExample: Stop a thread\n```js\nvar thread = NEWTHREAD('calc');\nsetTimeout(() => thread.kill(), 5000);\n```\n\n### NEWFORK(name)\n\nType: `method` · Since: `0.0.16`\n\nRuns a script from the workers/ folder in a new Node.js process.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file name in `workers/` without `.js`, or `~` and an absolute path |\n\nReturns: `ChildProcess` The forked process\n\nStarts `workers/{name}.js` with `child_process.fork()`. A name that starts with `~` is an absolute path. The result is the Node.js `ChildProcess`; the framework adds `postMessage()` (the same as `send()`) and `terminate()`. Messages are serialized as JSON.\n\nThe working directory of the fork is the folder of its script. The framework in the fork sends the string `total:init` to the parent after it starts, so skip string messages in the parent. Called without a name inside the fork, `NEWFORK()` returns `F.worker`, as `NEWTHREAD()` does in a thread; `F.worker.data` is then an empty object.\n\nExample: Main application\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn;\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nExample: workers/report.js\n```js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n### fork.terminate()\n\nType: `method` · Since: `0.0.16`\n\nKills a process started with NEWFORK().\n\nSends `SIGKILL` to the process. The process ends at once, without running its exit handlers.\n\nExample: Kill a fork\n```js\nvar fork = NEWFORK('report');\nsetTimeout(() => fork.terminate(), 60000);\n```\n\n### fork.postMessage(msg)\n\nType: `method` · Since: `0.0.16`\n\nSends a message to a process started with NEWFORK().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | The message; it is serialized as JSON |\n\nThe same method as `fork.send()` of Node.js, so the code for threads and forks can look the same. The fork receives the message in `F.worker.message`.\n\nExample: Send a job\n```js\nfork.postMessage({ id: 100, type: 'pdf' });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nStarts a pool of worker threads or forks 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 |  | The number of workers |\n| `isfork` | `Boolean` | no | `false` | Start the workers with `NEWFORK()` instead of threads |\n\nReturns: `Object` The pool\n\nStarts `count` workers of `workers/{name}.js` at once and returns a pool: worker threads, or processes from `NEWFORK()` when `isfork` is `true`. Jobs get the workers through `pool.exec()`; a worker goes to the next job only after the current job calls `release()`. Jobs that arrive while all workers are busy wait in `pool.pending`. A worker that exits is replaced by a new one, which is given to the next waiting job. The workers get no data (`F.worker.data` is `{}`). The pool is also stored in `F.workers[name]`.\n\nExample: Pool of four threads\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\nExample: Pool of forks\n```js\nvar pool = NEWTHREADPOOL('report', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nRuns a job on the next free worker of the pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Only without `fn`: resolves with the worker\n\nAdds the job to the queue and starts it as soon as a worker is free. The function gets `(worker, release)`; call `release()` when the job is done. Without a function the method returns a promise that resolves with the worker; release it with `worker.release()`.\n\nBefore a worker starts a job, the pool removes all its `message` listeners, so each job attaches its own.\n\nExample: With a callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 1, b: 2 });\n});\n```\n\nExample: With a promise\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 2 });\n```\n\n### worker.release()\n\nType: `method`\n\nReturns a worker of a pool back to the pool.\n\nEvery worker of a pool has this method. It marks the worker as free and gives it to the next waiting job. It is the same function as the `release` argument of `pool.exec(fn)`.\n\nExample: Release\n```js\nvar worker = await pool.exec();\nworker.on('message', () => worker.release());\nworker.postMessage({});\n```\n\n### pool.workers\n\nType: `property`\n\nThe workers of the pool.\n\nReturns: `Array`\n\nAn array of the `Worker` objects that the pool started.\n\nExample: Send to all\n```js\npool.workers.forEach(w => w.postMessage({ type: 'reload' }));\n```\n\n### pool.pending\n\nType: `property`\n\nThe jobs that wait for a free worker.\n\nReturns: `Array`\n\nAn array of the functions passed to `pool.exec()` that have not started yet. Its length tells how busy the pool is.\n\nExample: Queue length\n```js\nconsole.log('Waiting jobs:', pool.pending.length);\n```\n\n### pool.count\n\nType: `property`\n\nThe number of workers of the pool.\n\nReturns: `Number`\n\nThe `count` given to `NEWTHREADPOOL()`. The pool keeps this number of workers: a worker that exits is replaced.\n\nExample: Size\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\nconsole.log(pool.count); // 4\n```\n\n### F.workers\n\nType: `property`\n\nThe thread pools of the application by name.\n\nReturns: `Object`\n\n`NEWTHREADPOOL(name, count)` stores the pool here under its name.\n\nExample: Get a pool\n```js\nvar pool = F.workers.calc;\n```\n\n### options.cluster = 4\n\nType: `config`\n\nStart option: runs the application in a cluster of processes.\n\nA number of processes, or `'auto'`. Set it in the options of `Total.run()`. The first process becomes the master: it starts the processes one after another, each of them loads the application and listens on the same port. A process that exits is started again after one second. The processes run in release mode with `options.release = true` or `options.watcher = false`; otherwise they run in debug mode and the master restarts them all when a source file changes.\n\nWith `'auto'` the master starts one process, pings all processes every 5 seconds and adds one when the average answer takes longer than 70 ms (up to `limit`). When they answer fast again, it removes the last process if it has fewer than two pending requests.\n\nExample: Start script\n```js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n\nTotal.run(options);\n```\n\n### options.limit = 10\n\nType: `config`\n\nStart option: the maximum number of processes of an 'auto' cluster.\n\nUsed only with `cluster: 'auto'`. Without it the master can add processes without a limit.\n\nExample: Auto cluster\n```js\nrequire('total5');\n\nTotal.run({ release: true, port: 8000, cluster: 'auto', limit: 8 });\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nStart option of a cluster: the time zone of the processes.\n\nIn cluster mode the framework sets `process.env.TZ` to this value before it starts the processes. The default is `'utc'`.\n\nExample: Time zone\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 4, tz: 'Europe/Madrid' });\n```\n\n### options.logs = 'isolated'\n\nType: `config`\n\nStart option of a cluster: always print the cluster header.\n\nThe master prints the `CLUSTER` header (PID, versions, thread count, mode) when it runs on its own. When it runs under another Node.js process (with an IPC channel) the header is skipped, unless `logs` is `'isolated'`.\n\nExample: Header\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 2, logs: 'isolated' });\n```\n\n### options.callback = function(forks) {}\n\nType: `delegate`\n\nStart option of a cluster: called after all processes have started.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forks` | `Array` | yes |  | The cluster workers |\n\nRuns in the master once every process of the cluster has started. `forks` is the array of the `cluster.Worker` objects.\n\nExample: After start\n```js\nrequire('total5');\n\nTotal.run({\n\trelease: true,\n\tcluster: 2,\n\tcallback: function(forks) {\n\t\tconsole.log('Started', forks.length, 'processes');\n\t}\n});\n```\n\n### F.isCluster\n\nType: `property`\n\ntrue in a process of a cluster.\n\nReturns: `Boolean`\n\nThe framework sets it when the master sends the start options to the process. In other cases it is `undefined`.\n\nExample: Check\n```js\nif (F.isCluster)\n\tprocess.send({ type: 'clearcache' });\n```\n\n### F.isWorker\n\nType: `property`\n\ntrue when the process is a worker of the Node.js cluster.\n\nReturns: `Boolean`\n\nThe value of `cluster.isWorker` of Node.js, so it is `true` in the processes of a Total.js cluster. It is `false` when the environment variable `PASSENGER_APP_ENV` is set. Processes with `F.isWorker` send their statistics to the master.\n\nExample: Check\n```js\nconsole.log(F.isWorker);\n```\n\n### F.clusterid\n\nType: `property`\n\nThe identifier of the process in a cluster.\n\nReturns: `String`\n\nA string such as `'1'` or `'2'`, the same value as `F.id`. Outside a cluster it is an empty string. The framework adds it to the names of temporary files and to the statistics.\n\nExample: Per-process file\n```js\nvar filename = PATH.tmp('export' + F.clusterid + '.csv');\n```\n\n### F.id\n\nType: `property`\n\nThe identifier of the process in a cluster.\n\nReturns: `String`\n\nThe same value as `F.clusterid`: a string with the number of the process, or an empty string outside a cluster.\n\nExample: Log\n```js\nconsole.log('Process', F.id);\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nEvery message the process receives through its IPC channel.\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 each message from the parent process. In a cluster an object that one process sends with `process.send()` is passed by the master to all ready processes, the sender included, and each of them gets it here. Do not use the `TYPE` property and strings that start with `total:` in your messages: the framework uses them.\n\nExample: Sync caches\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// in any process\nprocess.send({ type: 'clearcache' });\n```\n\n### restart (file)\n\nType: `command`\n\nA file that restarts all processes of a cluster.\n\nThe master of a cluster checks every 5 seconds whether a file named `restart` exists in the application directory. If it does, the master deletes it and restarts the processes one by one, two seconds apart. A second restart within 30 seconds is ignored.\n\nExample: Restart from the shell\n```bash\n$ touch restart\n```\n\n### SHELL(cmd, [callback], [cwd])\n\nType: `method`\n\nRuns a shell command.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cmd` | `String` | yes |  | The command |\n| `callback` | `Function` | no |  | `function(err, stdout)`; or the working directory as a string |\n| `cwd` | `String` | no | `the application root` | The working directory |\n\nReturns: `Promise` Only without a callback: resolves with the standard output\n\nRuns the command with `child_process.exec()` in the system shell. With a callback it calls `callback(err, stdout)`; without one it returns a promise that resolves with the standard output or rejects with the error. A string as the second argument is the working directory. The default directory is the application root. The config key `$shell` sets the shell to use. The output can have up to 100 MB (`maxBuffer`); a larger output ends with an error.\n\nExample: Callback\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n```\n\nExample: Promise and directory\n```js\nvar list = await SHELL('ls -1', PATH.public());\n```\n\n### $shell : /bin/bash\n\nType: `config`\n\nThe shell that SHELL() uses.\n\nThe path of the shell for `SHELL()`. Not set by default, which uses the default shell of Node.js (`/bin/sh`, or `cmd.exe` on Windows).\n\nExample: config\n```text\n$shell : /bin/bash\n```\n\n### F.python(filename, [callback])\n\nType: `method`\n\nRuns a Python script and returns its output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The absolute path to the `.py` file. |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)`. |\n\nReturns: `Promise` Only without a callback: resolves with the standard output.\n\nRuns `$python <filename>` with `child_process.exec()` in the folder of the script. With a callback it calls `callback(err, stdout, stderr)`; without one it returns a promise that resolves with the standard output. A script that ends with an exit code other than `0` gives an error (`err.code` is the exit code) and the promise rejects. `$python` is the config key with the Python command (`python3` by default).\n\nExample: Promise\n```js\nvar output = await F.python(PATH.root('scripts/report.py'));\n```\n\nExample: Callback\n```js\nF.python(PATH.root('scripts/report.py'), function(err, stdout, stderr) {\n\tif (err)\n\t\tconsole.log(stderr);\n\telse\n\t\tconsole.log(stdout);\n});\n```\n\n### PYPELINE(name, [options])\n\nType: `method`\n\nStarts a Python script and exchanges messages with it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file name in `pypelines/` without `.py`, `~` and an absolute path, or inline code |\n| `options` | `Object` | no |  | `{ autorestart, type, socket }` |\n\nReturns: `Pypeline` An object with events and the methods below\n\nRuns `python3` with `pypelines/{name}.py` (or an absolute path that starts with `~`) in the folder of the script. A `name` that contains a new line, `;` or a quote is inline code, run with `python3 -c` in the application root.\n\nThe framework listens on a Unix socket in `tmp/` and passes its path to the script as `sys.argv[1]`. Each message in both directions is a 4-byte big-endian length followed by the payload. The script's standard output and error go to the console of the application. When the application exits, all Python processes are killed.\n\nThe options are `autorestart` (default `true`: start the script again when it ends), `type` (`'json'` by default, `'text'` for strings, or any other value for raw buffers) and `socket` (`false` runs the script without a socket, for scripts that only run).\n\nExample: Start a pipeline\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text);\n});\n\npy.send({ text: 'hello' });\n```\n\nExample: Text messages\n```js\nvar py = PYPELINE('tokenizer', { type: 'text' });\n```\n\n### F.pipinstall(name, [callback])\n\nType: `method`\n\nInstalls a Python package with pip.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The package, optionally with a version (`requests==2.32.3`). |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Only without a callback.\n\nRuns `$python -m pip install <name>` in the application directory. With a callback it calls `callback(err)`; without one it returns a promise. When pip fails, the error is the error output of pip (a string), or the error of the process.\n\nExample: Install before use\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/download.py'));\n```\n\n### pypeline.send(data)\n\nType: `method`\n\nSends a message to the Python script.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|Buffer|String` | yes |  | The message |\n\nReturns: `Pypeline` The pipeline (only when the script is connected)\n\nAn object is sent as JSON, a `Buffer` as it is and other values as text, each with a 4-byte length in front. Messages sent before the script connects wait and are sent when it connects.\n\nExample: Send\n```js\npy.send({ text: 'hello' });\n```\n\n### pypeline.close()\n\nType: `method`\n\nStops the Python script for good.\n\nReturns: `Pypeline`\n\nTurns `autorestart` off, closes the socket server and kills the Python process.\n\nExample: Stop\n```js\npy.close();\n```\n\n### pypeline.restart()\n\nType: `method`\n\nKills the Python process and starts it again.\n\nKills the current process and starts the script again. `pypeline.run()` is the same method.\n\nExample: Reload\n```js\npy.restart();\n```\n\n### pypeline.on('data', function(msg) {})\n\nType: `event`\n\nA message from the Python script.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object|String|Buffer` | yes |  | The message |\n\nEmitted for every complete message. With `type: 'json'` the message is parsed, with `'text'` it is a string, otherwise a `Buffer`.\n\nExample: Read\n```js\npy.on('data', function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### pypeline.on('open', function() {})\n\nType: `event`\n\nThe Python script connected to the socket.\n\nEmitted each time the script connects, after the waiting messages have been sent.\n\nExample: Connected\n```js\npy.on('open', function() {\n\tconsole.log('Python is ready');\n});\n```\n\n### pypeline.on('restart', function() {})\n\nType: `event`\n\nThe Python script ended and was started again.\n\nEmitted with `autorestart: true` after the framework has started the script again.\n\nExample: Log restarts\n```js\npy.on('restart', function() {\n\tconsole.log('Python restarted');\n});\n```\n\n### pypeline.name\n\nType: `property`\n\nThe name of the pipeline.\n\nReturns: `String`\n\nThe `name` passed to `PYPELINE()`, or `Inline Python Code` for inline code.\n\nExample: Log\n```js\nconsole.log(py.name);\n```\n","entries":[{"type":"method","name":"NEWTHREAD(name, [data])","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD()","since":"","deprecated":false},{"type":"property","name":"F.worker","signature":"F.worker","since":"","deprecated":false},{"type":"property","name":"F.worker.data","signature":"F.worker.data","since":"","deprecated":false},{"type":"property","name":"F.worker.is","signature":"F.worker.is","since":"","deprecated":false},{"type":"property","name":"F.worker.isfork","signature":"F.worker.isfork","since":"","deprecated":false},{"type":"delegate","name":"F.worker.message","signature":"F.worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"F.worker.send(msg)","signature":"F.worker.send(msg)","since":"","deprecated":false},{"type":"method","name":"F.worker.exit([code])","signature":"F.worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"F.worker.setTimeout(timeout)","signature":"F.worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"thread.kill()","signature":"thread.kill()","since":"","deprecated":false},{"type":"method","name":"NEWFORK(name)","signature":"NEWFORK(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.terminate()","signature":"fork.terminate()","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.postMessage(msg)","signature":"fork.postMessage(msg)","since":"0.0.16","deprecated":false},{"type":"method","name":"NEWTHREADPOOL(name, count)","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec([fn])","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"method","name":"worker.release()","signature":"worker.release()","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"pool.pending","signature":"pool.pending","since":"","deprecated":false},{"type":"property","name":"pool.count","signature":"pool.count","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"config","name":"cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"limit","signature":"options.limit = 10","since":"","deprecated":false},{"type":"config","name":"tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"delegate","name":"callback","signature":"options.callback = function(forks) {}","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.isWorker","signature":"F.isWorker","since":"","deprecated":false},{"type":"property","name":"F.clusterid","signature":"F.clusterid","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart (file)","since":"","deprecated":false},{"type":"method","name":"SHELL(cmd, [callback], [cwd])","signature":"SHELL(cmd, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : /bin/bash","since":"","deprecated":false},{"type":"method","name":"F.python()","signature":"F.python(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"PYPELINE(name, [options])","signature":"PYPELINE(name, [options])","since":"","deprecated":false},{"type":"method","name":"F.pipinstall()","signature":"F.pipinstall(name, [callback])","since":"","deprecated":false},{"type":"method","name":"pypeline.send(data)","signature":"pypeline.send(data)","since":"","deprecated":false},{"type":"method","name":"pypeline.close()","signature":"pypeline.close()","since":"","deprecated":false},{"type":"method","name":"pypeline.restart()","signature":"pypeline.restart()","since":"","deprecated":false},{"type":"event","name":"pypeline.on('data')","signature":"pypeline.on('data', function(msg) {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('open')","signature":"pypeline.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('restart')","signature":"pypeline.on('restart', function() {})","since":"","deprecated":false},{"type":"property","name":"pypeline.name","signature":"pypeline.name","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvT9Ex61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Worker, Threads und Cluster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, die Cluster-Optionen, SHELL(), F.python(), F.pipinstall() und PYPELINE().","markdown":"---\ntitle: Worker, Threads und Cluster\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/workers-and-threads/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Worker, Threads und Cluster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, die Cluster-Optionen, SHELL(), F.python(), F.pipinstall() und PYPELINE().\n\nMethoden, Eigenschaften, Startoptionen und Ereignisse für Worker-Threads, geforkte Prozesse, Thread-Pools, den Cluster, `SHELL()` und `PYPELINE()`. Für eine Einführung mit Beispielen lies den Leitfaden [Worker, Threads und Cluster](../../guides/workers-and-threads/).\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nStartet einen Worker-Thread aus dem Ordner workers/.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Dateiname in `workers/` ohne `.js` oder `~` und ein absoluter Pfad |\n| `data` | `Object` | no |  | Daten, die als `F.worker.data` in den Thread kopiert werden |\n\nReturns: `Worker` Der Node.js-Worker-Thread\n\nFührt `workers/{name}.js` in einem neuen Node.js-Worker-Thread aus. Ein Name, der mit `~` beginnt, ist ein absoluter Pfad zum Skript. `data` wird in den Thread kopiert und ist dort als `F.worker.data` verfügbar. Der Thread erhält `--worker` in seinem `process.argv`.\n\nDas Ergebnis ist das Node.js-Objekt `Worker`: Verwende `postMessage()`, um eine Nachricht zu senden, und `on('message')`, `on('error')` und `on('exit')`, um zuzuhören. Das Framework fügt `kill()` und `exit()` hinzu, die `terminate()` aufrufen.\n\nExample: Einen Thread starten\n```js\nvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\nthread.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tthread.kill();\n});\n\nthread.postMessage({ a: 1, b: 2 });\n```\n\n### NEWTHREAD()\n\nType: `method`\n\nIn einem Worker-Skript: gibt das Worker-Objekt F.worker zurück.\n\nReturns: `Object` F.worker\n\nOhne Namen in einem Skript aufgerufen, das als Worker läuft, erstellt `NEWTHREAD()` das Objekt `F.worker` (oder gibt es zurück, wenn es existiert), setzt das Anwendungsverzeichnis auf das aktuelle Arbeitsverzeichnis und beginnt, die Nachrichten vom Elternprozess an `F.worker.message` weiterzugeben. Lade das Framework mit `require('total5')`, bevor du es aufrufst.\n\nExample: workers/calc.js\n```js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tworker.send({ sum: msg.a + msg.b });\n};\n```\n\n### F.worker\n\nType: `property`\n\nDas Worker-Objekt eines Skripts, das als Worker läuft.\n\nReturns: `Object`\n\nWird von `NEWTHREAD()` (oder `NEWFORK()`) ohne Namen erstellt. Es enthält die Daten vom Elternprozess und die Methoden, um Nachrichten zu empfangen und zu senden und den Worker zu beenden. In der Hauptanwendung ist es `undefined`.\n\nExample: Die Daten prüfen\n```js\nvar worker = NEWTHREAD();\nconsole.log(F.worker === worker); // true\nconsole.log(worker.data);\n```\n\n### F.worker.data\n\nType: `property`\n\nDie an NEWTHREAD(name, data) übergebenen Daten.\n\nReturns: `Object`\n\nEine Kopie des zweiten Arguments von `NEWTHREAD()` im Hauptthread. Es ist ein leeres Objekt `{}`, wenn keine Daten übergeben wurden, in einem Fork und in den Threads eines Pools.\n\nExample: Die Daten lesen\n```js\nvar worker = NEWTHREAD();\nvar user = worker.data.user;\n```\n\n### F.worker.is\n\nType: `property`\n\ntrue, wenn das Skript als Worker läuft.\n\nReturns: `Boolean`\n\n`true` in einem Thread aus `NEWTHREAD()`, in einem Fork aus `NEWFORK()` und in den Workern von `NEWTHREADPOOL()`: Sie alle erhalten das Argument `--worker` in `process.argv`.\n\nExample: Als Worker oder allein ausführen\n```js\nvar worker = NEWTHREAD();\nif (!worker.is)\n\tconsole.log('Started directly with node, not as a worker');\n```\n\n### F.worker.isfork\n\nType: `property`\n\ntrue in einem geforkten Prozess, false in einem Worker-Thread.\n\nReturns: `Boolean`\n\n`true`, wenn der Worker ein Prozess aus `NEWFORK()` ist (Nachrichten laufen über `process.send()`), `false` in einem Worker-Thread.\n\nExample: Thread oder Prozess\n```js\nvar worker = NEWTHREAD();\nconsole.log(worker.isfork ? 'process ' + process.pid : 'thread');\n```\n\n### F.worker.message = function(msg) {}\n\nType: `delegate`\n\nEmpfängt die Nachrichten vom Elternprozess.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Die Nachricht des Elternprozesses |\n\nWeise eine Funktion zu. Sie wird mit jeder Nachricht aufgerufen, die der Elternprozess mit `postMessage()` sendet. Der Standard tut nichts.\n\nExample: Nachrichten beantworten\n```js\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tif (msg.type === 'ping')\n\t\tworker.send({ type: 'pong' });\n};\n```\n\n### F.worker.send(msg)\n\nType: `method`\n\nSendet eine Nachricht an den Elternprozess.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Die Nachricht; sie wird kopiert, Funktionen sind nicht erlaubt |\n\nSendet die Nachricht an den Prozess oder Thread, der den Worker gestartet hat. `F.worker.postMessage()` ist dieselbe Methode. Der Elternprozess empfängt sie in `on('message')`.\n\nExample: Ein Ergebnis senden\n```js\nworker.send({ id: msg.id, result: result });\n```\n\n### F.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. In einem Thread beendet es den Thread; der Elternprozess erhält das Ereignis `exit` mit dem Code. `F.worker.kill()` und `F.worker.close()` sind dieselbe Methode.\n\nExample: Nach dem Job beenden\n```js\nworker.message = function(msg) {\n\twork(msg);\n\tworker.exit();\n};\n```\n\n### F.worker.setTimeout(timeout)\n\nType: `method`\n\nBeendet den Worker nach einem Timeout mit dem Code 1.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Millisekunden |\n\nStartet einen Countdown. Wenn er abläuft, endet der Worker mit dem Exit-Code `1`. Ein neuer Aufruf löscht den vorherigen Countdown und startet einen neuen, also ruf es am Anfang jedes Jobs auf.\n\nExample: Watchdog\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\tjob(msg, function(response) {\n\t\tworker.send(response);\n\t});\n};\n```\n\n### thread.kill()\n\nType: `method`\n\nStoppt einen mit NEWTHREAD() gestarteten Thread.\n\nRuft `terminate()` des Node.js-`Worker` auf. `thread.exit()` ist dieselbe Methode.\n\nExample: Einen Thread stoppen\n```js\nvar thread = NEWTHREAD('calc');\nsetTimeout(() => thread.kill(), 5000);\n```\n\n### NEWFORK(name)\n\nType: `method` · Since: `0.0.16`\n\nFührt ein Skript aus dem Ordner workers/ in einem neuen Node.js-Prozess aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Dateiname in `workers/` ohne `.js` oder `~` und ein absoluter Pfad |\n\nReturns: `ChildProcess` Der geforkte Prozess\n\nStartet `workers/{name}.js` mit `child_process.fork()`. Ein Name, der mit `~` beginnt, ist ein absoluter Pfad. Das Ergebnis ist der Node.js-`ChildProcess`; das Framework fügt `postMessage()` (dasselbe wie `send()`) und `terminate()` hinzu. Nachrichten werden als JSON serialisiert.\n\nDas Arbeitsverzeichnis des Forks ist der Ordner seines Skripts. Das Framework im Fork sendet nach dem Start den String `total:init` an den Elternprozess, überspringe also String-Nachrichten im Elternprozess. Ohne Namen innerhalb des Forks aufgerufen, gibt `NEWFORK()` `F.worker` zurück, so wie `NEWTHREAD()` in einem Thread; `F.worker.data` ist dann ein leeres Objekt.\n\nExample: Hauptanwendung\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn;\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nExample: workers/report.js\n```js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n### fork.terminate()\n\nType: `method` · Since: `0.0.16`\n\nBeendet einen mit NEWFORK() gestarteten Prozess.\n\nSendet `SIGKILL` an den Prozess. Der Prozess endet sofort, ohne seine Exit-Handler auszuführen.\n\nExample: Einen Fork beenden\n```js\nvar fork = NEWFORK('report');\nsetTimeout(() => fork.terminate(), 60000);\n```\n\n### fork.postMessage(msg)\n\nType: `method` · Since: `0.0.16`\n\nSendet eine Nachricht an einen mit NEWFORK() gestarteten Prozess.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Die Nachricht; sie wird als JSON serialisiert |\n\nDieselbe Methode wie `fork.send()` von Node.js, sodass der Code für Threads und Forks gleich aussehen kann. Der Fork empfängt die Nachricht in `F.worker.message`.\n\nExample: Einen Job senden\n```js\nfork.postMessage({ id: 100, type: 'pdf' });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nStartet einen Pool von Worker-Threads oder Forks 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 |  | Die Anzahl der Worker |\n| `isfork` | `Boolean` | no | `false` | Die Worker mit `NEWFORK()` statt als Threads starten |\n\nReturns: `Object` Der Pool\n\nStartet sofort `count` Worker von `workers/{name}.js` und gibt einen Pool zurück: Worker-Threads oder, wenn `isfork` `true` ist, Prozesse aus `NEWFORK()`. Jobs erhalten die Worker über `pool.exec()`; ein Worker geht erst zum nächsten Job, nachdem der aktuelle Job `release()` aufgerufen hat. Jobs, die eintreffen, während alle Worker beschäftigt sind, warten in `pool.pending`. Ein Worker, der sich beendet, wird durch einen neuen ersetzt, der dem nächsten wartenden Job übergeben wird. Die Worker erhalten keine Daten (`F.worker.data` ist `{}`). Der Pool wird auch in `F.workers[name]` gespeichert.\n\nExample: Pool mit vier Threads\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\nExample: Pool von Forks\n```js\nvar pool = NEWTHREADPOOL('report', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nFührt einen Job auf dem nächsten freien Worker des Pools aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Nur ohne `fn`: wird mit dem Worker erfüllt\n\nFügt den Job zur Warteschlange hinzu und startet ihn, sobald ein Worker frei ist. Die Funktion erhält `(worker, release)`; ruf `release()` auf, wenn der Job fertig ist. Ohne Funktion gibt die Methode eine Promise zurück, die mit dem Worker erfüllt wird; gib ihn mit `worker.release()` frei.\n\nBevor ein Worker einen Job startet, entfernt der Pool alle seine `message`-Listener, sodass jeder Job seine eigenen anhängt.\n\nExample: Mit einem Callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 1, b: 2 });\n});\n```\n\nExample: Mit einer Promise\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 2 });\n```\n\n### worker.release()\n\nType: `method`\n\nGibt einen Worker eines Pools an den Pool zurück.\n\nJeder Worker eines Pools hat diese Methode. Sie markiert den Worker als frei und gibt ihn dem nächsten wartenden Job. Es ist dieselbe Funktion wie das Argument `release` von `pool.exec(fn)`.\n\nExample: Freigeben\n```js\nvar worker = await pool.exec();\nworker.on('message', () => worker.release());\nworker.postMessage({});\n```\n\n### pool.workers\n\nType: `property`\n\nDie Worker des Pools.\n\nReturns: `Array`\n\nEin Array der `Worker`-Objekte, die der Pool gestartet hat.\n\nExample: An alle senden\n```js\npool.workers.forEach(w => w.postMessage({ type: 'reload' }));\n```\n\n### pool.pending\n\nType: `property`\n\nDie Jobs, die auf einen freien Worker warten.\n\nReturns: `Array`\n\nEin Array der an `pool.exec()` übergebenen Funktionen, die noch nicht gestartet sind. Seine Länge zeigt, wie ausgelastet der Pool ist.\n\nExample: Länge der Warteschlange\n```js\nconsole.log('Waiting jobs:', pool.pending.length);\n```\n\n### pool.count\n\nType: `property`\n\nDie Anzahl der Worker des Pools.\n\nReturns: `Number`\n\nDer an `NEWTHREADPOOL()` übergebene Wert `count`. Der Pool hält diese Anzahl von Workern: Ein Worker, der sich beendet, wird ersetzt.\n\nExample: Größe\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\nconsole.log(pool.count); // 4\n```\n\n### F.workers\n\nType: `property`\n\nDie Thread-Pools der Anwendung nach Namen.\n\nReturns: `Object`\n\n`NEWTHREADPOOL(name, count)` speichert den Pool hier unter seinem Namen.\n\nExample: Einen Pool holen\n```js\nvar pool = F.workers.calc;\n```\n\n### options.cluster = 4\n\nType: `config`\n\nStartoption: führt die Anwendung in einem Cluster von Prozessen aus.\n\nEine Anzahl von Prozessen oder `'auto'`. Setze sie in den Optionen von `Total.run()`. Der erste Prozess wird zum Master: Er startet die Prozesse nacheinander, jeder von ihnen lädt die Anwendung und lauscht auf demselben Port. Ein Prozess, der endet, wird nach einer Sekunde neu gestartet. Die Prozesse laufen im Release-Modus mit `options.release = true` oder `options.watcher = false`; sonst laufen sie im Debug-Modus und der Master startet alle neu, wenn sich eine Quelldatei ändert.\n\nMit `'auto'` startet der Master einen Prozess, pingt alle 5 Sekunden alle Prozesse an und fügt einen hinzu, wenn die durchschnittliche Antwort länger als 70 ms dauert (bis zu `limit`). Wenn sie wieder schnell antworten, entfernt er den letzten Prozess, sofern dieser weniger als zwei ausstehende Anfragen hat.\n\nExample: Startskript\n```js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n\nTotal.run(options);\n```\n\n### options.limit = 10\n\nType: `config`\n\nStartoption: die maximale Anzahl der Prozesse eines 'auto'-Clusters.\n\nWird nur mit `cluster: 'auto'` verwendet. Ohne sie kann der Master unbegrenzt Prozesse hinzufügen.\n\nExample: Auto-Cluster\n```js\nrequire('total5');\n\nTotal.run({ release: true, port: 8000, cluster: 'auto', limit: 8 });\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nStartoption eines Clusters: die Zeitzone der Prozesse.\n\nIm Cluster-Modus setzt das Framework `process.env.TZ` auf diesen Wert, bevor es die Prozesse startet. Der Standard ist `'utc'`.\n\nExample: Zeitzone\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 4, tz: 'Europe/Madrid' });\n```\n\n### options.logs = 'isolated'\n\nType: `config`\n\nStartoption eines Clusters: den Cluster-Header immer ausgeben.\n\nDer Master gibt den `CLUSTER`-Header (PID, Versionen, Thread-Anzahl, Modus) aus, wenn er eigenständig läuft. Wenn er unter einem anderen Node.js-Prozess läuft (mit einem IPC-Kanal), wird der Header übersprungen, es sei denn, `logs` ist `'isolated'`.\n\nExample: Header\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 2, logs: 'isolated' });\n```\n\n### options.callback = function(forks) {}\n\nType: `delegate`\n\nStartoption eines Clusters: wird aufgerufen, nachdem alle Prozesse gestartet sind.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forks` | `Array` | yes |  | Die Cluster-Worker |\n\nLäuft im Master, sobald jeder Prozess des Clusters gestartet ist. `forks` ist das Array der `cluster.Worker`-Objekte.\n\nExample: Nach dem Start\n```js\nrequire('total5');\n\nTotal.run({\n\trelease: true,\n\tcluster: 2,\n\tcallback: function(forks) {\n\t\tconsole.log('Started', forks.length, 'processes');\n\t}\n});\n```\n\n### F.isCluster\n\nType: `property`\n\ntrue in einem Prozess eines Clusters.\n\nReturns: `Boolean`\n\nDas Framework setzt es, wenn der Master die Startoptionen an den Prozess sendet. In anderen Fällen ist es `undefined`.\n\nExample: Prüfen\n```js\nif (F.isCluster)\n\tprocess.send({ type: 'clearcache' });\n```\n\n### F.isWorker\n\nType: `property`\n\ntrue, wenn der Prozess ein Worker des Node.js-Clusters ist.\n\nReturns: `Boolean`\n\nDer Wert von `cluster.isWorker` von Node.js, daher ist er in den Prozessen eines Total.js-Clusters `true`. Er ist `false`, wenn die Umgebungsvariable `PASSENGER_APP_ENV` gesetzt ist. Prozesse mit `F.isWorker` senden ihre Statistiken an den Master.\n\nExample: Prüfen\n```js\nconsole.log(F.isWorker);\n```\n\n### F.clusterid\n\nType: `property`\n\nDie Kennung des Prozesses in einem Cluster.\n\nReturns: `String`\n\nEin String wie `'1'` oder `'2'`, derselbe Wert wie `F.id`. Außerhalb eines Clusters ist es ein leerer String. Das Framework fügt ihn zu den Namen temporärer Dateien und zu den Statistiken hinzu.\n\nExample: Datei pro Prozess\n```js\nvar filename = PATH.tmp('export' + F.clusterid + '.csv');\n```\n\n### F.id\n\nType: `property`\n\nDie Kennung des Prozesses in einem Cluster.\n\nReturns: `String`\n\nDerselbe Wert wie `F.clusterid`: ein String mit der Nummer des Prozesses oder ein leerer String außerhalb eines Clusters.\n\nExample: Log\n```js\nconsole.log('Process', F.id);\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nJede Nachricht, die der Prozess über seinen IPC-Kanal empfängt.\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 vom Elternprozess ausgelöst. In einem Cluster gibt der Master ein Objekt, das ein Prozess mit `process.send()` sendet, an alle bereiten Prozesse weiter, einschließlich des Absenders, und jeder von ihnen erhält es hier. Verwende die Eigenschaft `TYPE` und Strings, die mit `total:` beginnen, nicht in deinen Nachrichten: Das Framework verwendet sie.\n\nExample: Caches synchronisieren\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// in any process\nprocess.send({ type: 'clearcache' });\n```\n\n### restart (file)\n\nType: `command`\n\nEine Datei, die alle Prozesse eines Clusters neu startet.\n\nDer Master eines Clusters prüft alle 5 Sekunden, ob eine Datei namens `restart` im Anwendungsverzeichnis existiert. Wenn ja, löscht der Master sie und startet die Prozesse nacheinander im Abstand von zwei Sekunden neu. Ein zweiter Neustart innerhalb von 30 Sekunden wird ignoriert.\n\nExample: Neustart aus der Shell\n```bash\n$ touch restart\n```\n\n### SHELL(cmd, [callback], [cwd])\n\nType: `method`\n\nFührt einen Shell-Befehl aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cmd` | `String` | yes |  | Der Befehl |\n| `callback` | `Function` | no |  | `function(err, stdout)`; oder das Arbeitsverzeichnis als String |\n| `cwd` | `String` | no | `the application root` | Das Arbeitsverzeichnis |\n\nReturns: `Promise` Nur ohne Callback: wird mit der Standardausgabe erfüllt\n\nFührt den Befehl mit `child_process.exec()` in der System-Shell aus. Mit einem Callback ruft es `callback(err, stdout)` auf; ohne gibt es ein Promise zurück, das mit der Standardausgabe aufgelöst oder mit dem Fehler abgelehnt wird. Ein String als zweites Argument ist das Arbeitsverzeichnis. Das Standardverzeichnis ist das Stammverzeichnis der Anwendung. Der Konfigurationsschlüssel `$shell` legt die zu verwendende Shell fest. Die Ausgabe kann bis zu 100 MB groß sein (`maxBuffer`); eine größere Ausgabe endet mit einem Fehler.\n\nExample: Callback\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n```\n\nExample: Promise und Verzeichnis\n```js\nvar list = await SHELL('ls -1', PATH.public());\n```\n\n### $shell : /bin/bash\n\nType: `config`\n\nDie Shell, die SHELL() verwendet.\n\nDer Pfad der Shell für `SHELL()`. Standardmäßig nicht gesetzt, dann wird die Standard-Shell von Node.js verwendet (`/bin/sh` oder `cmd.exe` unter Windows).\n\nExample: config\n```text\n$shell : /bin/bash\n```\n\n### F.python(filename, [callback])\n\nType: `method`\n\nFührt ein Python-Skript aus und gibt seine Ausgabe zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der absolute Pfad zur `.py`-Datei. |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)`. |\n\nReturns: `Promise` Nur ohne Callback: wird mit der Standardausgabe aufgelöst.\n\nFührt `$python <filename>` mit `child_process.exec()` im Ordner des Skripts aus. Mit einem Callback ruft es `callback(err, stdout, stderr)` auf; ohne gibt es eine Promise zurück, die mit der Standardausgabe aufgelöst wird. Ein Skript, das mit einem anderen Exit-Code als `0` endet, führt zu einem Fehler (`err.code` ist der Exit-Code), und die Promise wird abgelehnt. `$python` ist der Konfigurationsschlüssel mit dem Python-Befehl (standardmäßig `python3`).\n\nExample: Promise\n```js\nvar output = await F.python(PATH.root('scripts/report.py'));\n```\n\nExample: Callback\n```js\nF.python(PATH.root('scripts/report.py'), function(err, stdout, stderr) {\n\tif (err)\n\t\tconsole.log(stderr);\n\telse\n\t\tconsole.log(stdout);\n});\n```\n\n### PYPELINE(name, [options])\n\nType: `method`\n\nStartet ein Python-Skript und tauscht Nachrichten mit ihm aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Dateiname in `pypelines/` ohne `.py`, `~` und ein absoluter Pfad oder Inline-Code |\n| `options` | `Object` | no |  | `{ autorestart, type, socket }` |\n\nReturns: `Pypeline` Ein Objekt mit Ereignissen und den unten aufgeführten Methoden\n\nFührt `python3` mit `pypelines/{name}.py` (oder einem absoluten Pfad, der mit `~` beginnt) im Ordner des Skripts aus. Ein `name`, der einen Zeilenumbruch, `;` oder ein Anführungszeichen enthält, ist Inline-Code und wird mit `python3 -c` im Stammverzeichnis der Anwendung ausgeführt.\n\nDas Framework lauscht auf einem Unix-Socket in `tmp/` und übergibt seinen Pfad als `sys.argv[1]` an das Skript. Jede Nachricht in beide Richtungen ist eine 4-Byte-Länge im Big-Endian-Format, gefolgt von den Nutzdaten. Standardausgabe und Standardfehlerausgabe des Skripts gehen an die Konsole der Anwendung. Wenn die Anwendung beendet wird, werden alle Python-Prozesse beendet.\n\nDie Optionen sind `autorestart` (Standard `true`: das Skript erneut starten, wenn es endet), `type` (standardmäßig `'json'`, `'text'` für Strings oder jeder andere Wert für rohe Buffer) und `socket` (`false` führt das Skript ohne Socket aus, für Skripte, die nur laufen).\n\nExample: Eine Pipeline starten\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text);\n});\n\npy.send({ text: 'hello' });\n```\n\nExample: Textnachrichten\n```js\nvar py = PYPELINE('tokenizer', { type: 'text' });\n```\n\n### F.pipinstall(name, [callback])\n\nType: `method`\n\nInstalliert ein Python-Paket mit pip.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Das Paket, optional mit einer Version (`requests==2.32.3`). |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Nur ohne Callback.\n\nFührt `$python -m pip install <name>` im Anwendungsverzeichnis aus. Mit einem Callback ruft es `callback(err)` auf; ohne gibt es eine Promise zurück. Wenn pip fehlschlägt, ist der Fehler die Fehlerausgabe von pip (ein String) oder der Fehler des Prozesses.\n\nExample: Vor der Verwendung installieren\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/download.py'));\n```\n\n### pypeline.send(data)\n\nType: `method`\n\nSendet eine Nachricht an das Python-Skript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|Buffer|String` | yes |  | Die Nachricht |\n\nReturns: `Pypeline` Die Pipeline (nur wenn das Skript verbunden ist)\n\nEin Objekt wird als JSON gesendet, ein `Buffer` unverändert und andere Werte als Text, jeweils mit einer vorangestellten 4-Byte-Länge. Nachrichten, die gesendet werden, bevor sich das Skript verbindet, warten und werden gesendet, wenn es sich verbindet.\n\nExample: Senden\n```js\npy.send({ text: 'hello' });\n```\n\n### pypeline.close()\n\nType: `method`\n\nStoppt das Python-Skript endgültig.\n\nReturns: `Pypeline`\n\nSchaltet `autorestart` aus, schließt den Socket-Server und beendet den Python-Prozess.\n\nExample: Stoppen\n```js\npy.close();\n```\n\n### pypeline.restart()\n\nType: `method`\n\nBeendet den Python-Prozess und startet ihn erneut.\n\nBeendet den aktuellen Prozess und startet das Skript erneut. `pypeline.run()` ist dieselbe Methode.\n\nExample: Neu laden\n```js\npy.restart();\n```\n\n### pypeline.on('data', function(msg) {})\n\nType: `event`\n\nEine Nachricht vom Python-Skript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object|String|Buffer` | yes |  | Die Nachricht |\n\nWird für jede vollständige Nachricht ausgelöst. Mit `type: 'json'` wird die Nachricht geparst, mit `'text'` ist sie ein String, sonst ein `Buffer`.\n\nExample: Lesen\n```js\npy.on('data', function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### pypeline.on('open', function() {})\n\nType: `event`\n\nDas Python-Skript hat sich mit dem Socket verbunden.\n\nWird jedes Mal ausgelöst, wenn sich das Skript verbindet, nachdem die wartenden Nachrichten gesendet wurden.\n\nExample: Verbunden\n```js\npy.on('open', function() {\n\tconsole.log('Python is ready');\n});\n```\n\n### pypeline.on('restart', function() {})\n\nType: `event`\n\nDas Python-Skript wurde beendet und erneut gestartet.\n\nWird mit `autorestart: true` ausgelöst, nachdem das Framework das Skript erneut gestartet hat.\n\nExample: Neustarts protokollieren\n```js\npy.on('restart', function() {\n\tconsole.log('Python restarted');\n});\n```\n\n### pypeline.name\n\nType: `property`\n\nDer Name der Pipeline.\n\nReturns: `String`\n\nDer an `PYPELINE()` übergebene `name` oder `Inline Python Code` bei Inline-Code.\n\nExample: Log\n```js\nconsole.log(py.name);\n```\n","entries":[{"type":"method","name":"NEWTHREAD(name, [data])","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD()","since":"","deprecated":false},{"type":"property","name":"F.worker","signature":"F.worker","since":"","deprecated":false},{"type":"property","name":"F.worker.data","signature":"F.worker.data","since":"","deprecated":false},{"type":"property","name":"F.worker.is","signature":"F.worker.is","since":"","deprecated":false},{"type":"property","name":"F.worker.isfork","signature":"F.worker.isfork","since":"","deprecated":false},{"type":"delegate","name":"F.worker.message","signature":"F.worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"F.worker.send(msg)","signature":"F.worker.send(msg)","since":"","deprecated":false},{"type":"method","name":"F.worker.exit([code])","signature":"F.worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"F.worker.setTimeout(timeout)","signature":"F.worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"thread.kill()","signature":"thread.kill()","since":"","deprecated":false},{"type":"method","name":"NEWFORK(name)","signature":"NEWFORK(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.terminate()","signature":"fork.terminate()","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.postMessage(msg)","signature":"fork.postMessage(msg)","since":"0.0.16","deprecated":false},{"type":"method","name":"NEWTHREADPOOL(name, count)","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec([fn])","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"method","name":"worker.release()","signature":"worker.release()","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"pool.pending","signature":"pool.pending","since":"","deprecated":false},{"type":"property","name":"pool.count","signature":"pool.count","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"config","name":"cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"limit","signature":"options.limit = 10","since":"","deprecated":false},{"type":"config","name":"tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"delegate","name":"callback","signature":"options.callback = function(forks) {}","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.isWorker","signature":"F.isWorker","since":"","deprecated":false},{"type":"property","name":"F.clusterid","signature":"F.clusterid","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart (file)","since":"","deprecated":false},{"type":"method","name":"SHELL(cmd, [callback], [cwd])","signature":"SHELL(cmd, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : /bin/bash","since":"","deprecated":false},{"type":"method","name":"F.python()","signature":"F.python(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"PYPELINE(name, [options])","signature":"PYPELINE(name, [options])","since":"","deprecated":false},{"type":"method","name":"F.pipinstall()","signature":"F.pipinstall(name, [callback])","since":"","deprecated":false},{"type":"method","name":"pypeline.send(data)","signature":"pypeline.send(data)","since":"","deprecated":false},{"type":"method","name":"pypeline.close()","signature":"pypeline.close()","since":"","deprecated":false},{"type":"method","name":"pypeline.restart()","signature":"pypeline.restart()","since":"","deprecated":false},{"type":"event","name":"pypeline.on('data')","signature":"pypeline.on('data', function(msg) {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('open')","signature":"pypeline.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('restart')","signature":"pypeline.on('restart', function() {})","since":"","deprecated":false},{"type":"property","name":"pypeline.name","signature":"pypeline.name","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvT9Ex61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Workers, hilos y clúster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, las opciones del clúster, SHELL(), F.python(), F.pipinstall() y PYPELINE().","markdown":"---\ntitle: \"Workers, hilos y clúster\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/workers-and-threads/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Workers, hilos y clúster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, las opciones del clúster, SHELL(), F.python(), F.pipinstall() y PYPELINE().\n\nMétodos, propiedades, opciones de inicio y eventos para hilos worker, procesos forkeados, pools de hilos, el clúster, `SHELL()` y `PYPELINE()`. Para una introducción con ejemplos lee la guía [Workers, hilos y clúster](../../guides/workers-and-threads/).\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nInicia un hilo worker desde la carpeta workers/.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del archivo en `workers/` sin `.js`, o `~` y una ruta absoluta |\n| `data` | `Object` | no |  | Datos copiados en el hilo como `F.worker.data` |\n\nReturns: `Worker` El hilo worker de Node.js\n\nEjecuta `workers/{name}.js` en un nuevo hilo worker de Node.js. Un nombre que empieza por `~` es una ruta absoluta al script. `data` se copia en el hilo y allí está disponible como `F.worker.data`. El hilo recibe `--worker` en su `process.argv`.\n\nEl resultado es el objeto `Worker` de Node.js: usa `postMessage()` para enviar un mensaje y `on('message')`, `on('error')` y `on('exit')` para escuchar. El framework añade `kill()` y `exit()`, que llaman a `terminate()`.\n\nExample: Iniciar un hilo\n```js\nvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\nthread.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tthread.kill();\n});\n\nthread.postMessage({ a: 1, b: 2 });\n```\n\n### NEWTHREAD()\n\nType: `method`\n\nDentro de un script worker: devuelve el objeto worker F.worker.\n\nReturns: `Object` F.worker\n\nLlamado sin nombre en un script que se ejecuta como worker, `NEWTHREAD()` crea `F.worker` (o lo devuelve si ya existe), define el directorio de la aplicación como el directorio de trabajo actual y empieza a pasar los mensajes del padre a `F.worker.message`. Carga el framework con `require('total5')` antes de llamarlo.\n\nExample: workers/calc.js\n```js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tworker.send({ sum: msg.a + msg.b });\n};\n```\n\n### F.worker\n\nType: `property`\n\nEl objeto worker de un script que se ejecuta como worker.\n\nReturns: `Object`\n\nLo crea `NEWTHREAD()` (o `NEWFORK()`) sin nombre. Contiene los datos del padre y los métodos para recibir y enviar mensajes y para terminar el worker. En la aplicación principal es `undefined`.\n\nExample: Comprobar los datos\n```js\nvar worker = NEWTHREAD();\nconsole.log(F.worker === worker); // true\nconsole.log(worker.data);\n```\n\n### F.worker.data\n\nType: `property`\n\nLos datos pasados a NEWTHREAD(name, data).\n\nReturns: `Object`\n\nUna copia del segundo argumento de `NEWTHREAD()` en el hilo principal. Es un objeto vacío `{}` cuando no se pasaron datos, en un fork y en los hilos de un pool.\n\nExample: Leer los datos\n```js\nvar worker = NEWTHREAD();\nvar user = worker.data.user;\n```\n\n### F.worker.is\n\nType: `property`\n\ntrue cuando el script se ejecuta como worker.\n\nReturns: `Boolean`\n\n`true` en un hilo de `NEWTHREAD()`, en un fork de `NEWFORK()` y en los workers de `NEWTHREADPOOL()`: todos reciben el argumento `--worker` en `process.argv`.\n\nExample: Ejecutar como worker o por separado\n```js\nvar worker = NEWTHREAD();\nif (!worker.is)\n\tconsole.log('Started directly with node, not as a worker');\n```\n\n### F.worker.isfork\n\nType: `property`\n\ntrue en un proceso forkeado, false en un hilo worker.\n\nReturns: `Boolean`\n\n`true` cuando el worker es un proceso de `NEWFORK()` (los mensajes pasan por `process.send()`), `false` en un hilo worker.\n\nExample: Hilo o proceso\n```js\nvar worker = NEWTHREAD();\nconsole.log(worker.isfork ? 'process ' + process.pid : 'thread');\n```\n\n### F.worker.message = function(msg) {}\n\nType: `delegate`\n\nRecibe los mensajes del padre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | El mensaje del padre |\n\nAsigna una función. Se llama con cada mensaje que el padre envía con `postMessage()`. Por defecto no hace nada.\n\nExample: Responder mensajes\n```js\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tif (msg.type === 'ping')\n\t\tworker.send({ type: 'pong' });\n};\n```\n\n### F.worker.send(msg)\n\nType: `method`\n\nEnvía un mensaje al padre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | El mensaje; se copia, no se permiten funciones |\n\nEnvía el mensaje al proceso o hilo que inició el worker. `F.worker.postMessage()` es el mismo método. El padre lo recibe en `on('message')`.\n\nExample: Enviar un resultado\n```js\nworker.send({ id: msg.id, result: result });\n```\n\n### F.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)`. Dentro de un hilo termina el hilo; el padre recibe el evento `exit` con el código. `F.worker.kill()` y `F.worker.close()` son el mismo método.\n\nExample: Terminar tras el trabajo\n```js\nworker.message = function(msg) {\n\twork(msg);\n\tworker.exit();\n};\n```\n\n### F.worker.setTimeout(timeout)\n\nType: `method`\n\nTermina el worker con el código 1 tras un timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Milisegundos |\n\nInicia una cuenta atrás. Cuando se agota, el worker termina con el código de salida `1`. Una nueva llamada borra la cuenta atrás anterior e inicia una nueva, así que llámalo al comienzo de cada trabajo.\n\nExample: Watchdog\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\tjob(msg, function(response) {\n\t\tworker.send(response);\n\t});\n};\n```\n\n### thread.kill()\n\nType: `method`\n\nDetiene un hilo iniciado con NEWTHREAD().\n\nLlama a `terminate()` del `Worker` de Node.js. `thread.exit()` es el mismo método.\n\nExample: Detener un hilo\n```js\nvar thread = NEWTHREAD('calc');\nsetTimeout(() => thread.kill(), 5000);\n```\n\n### NEWFORK(name)\n\nType: `method` · Since: `0.0.16`\n\nEjecuta un script de la carpeta workers/ en un nuevo proceso de Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del archivo en `workers/` sin `.js`, o `~` y una ruta absoluta |\n\nReturns: `ChildProcess` El proceso bifurcado\n\nInicia `workers/{name}.js` con `child_process.fork()`. Un nombre que empieza por `~` es una ruta absoluta. El resultado es el `ChildProcess` de Node.js; el framework añade `postMessage()` (lo mismo que `send()`) y `terminate()`. Los mensajes se serializan como JSON.\n\nEl directorio de trabajo del fork es la carpeta de su script. El framework en el fork envía el string `total:init` al padre tras iniciarse, así que omite los mensajes de tipo string en el padre. Llamado sin nombre dentro del fork, `NEWFORK()` devuelve `F.worker`, como hace `NEWTHREAD()` en un hilo; `F.worker.data` es entonces un objeto vacío.\n\nExample: Aplicación principal\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn;\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nExample: workers/report.js\n```js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n### fork.terminate()\n\nType: `method` · Since: `0.0.16`\n\nMata un proceso iniciado con NEWFORK().\n\nEnvía `SIGKILL` al proceso. El proceso termina de inmediato, sin ejecutar sus handlers de salida.\n\nExample: Matar un fork\n```js\nvar fork = NEWFORK('report');\nsetTimeout(() => fork.terminate(), 60000);\n```\n\n### fork.postMessage(msg)\n\nType: `method` · Since: `0.0.16`\n\nEnvía un mensaje a un proceso iniciado con NEWFORK().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | El mensaje; se serializa como JSON |\n\nEl mismo método que `fork.send()` de Node.js, así el código para hilos y forks puede ser igual. El fork recibe el mensaje en `F.worker.message`.\n\nExample: Enviar un trabajo\n```js\nfork.postMessage({ id: 100, type: 'pdf' });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nInicia un pool de hilos worker o forks 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 |  | El número de workers |\n| `isfork` | `Boolean` | no | `false` | Inicia los workers con `NEWFORK()` en lugar de hilos |\n\nReturns: `Object` El pool\n\nInicia `count` workers de `workers/{name}.js` a la vez y devuelve un pool: hilos worker, o procesos de `NEWFORK()` cuando `isfork` es `true`. Los trabajos obtienen los workers con `pool.exec()`; un worker pasa al siguiente trabajo solo después de que el trabajo actual llame a `release()`. Los trabajos que llegan mientras todos los workers están ocupados esperan en `pool.pending`. Un worker que termina se sustituye por uno nuevo, que se entrega al siguiente trabajo en espera. Los workers no reciben datos (`F.worker.data` es `{}`). El pool también se guarda en `F.workers[name]`.\n\nExample: Pool de cuatro hilos\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\nExample: Pool de forks\n```js\nvar pool = NEWTHREADPOOL('report', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nEjecuta un trabajo en el siguiente worker libre del pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Solo sin `fn`: se resuelve con el worker\n\nAñade el trabajo a la cola y lo inicia en cuanto hay un worker libre. La función recibe `(worker, release)`; llama a `release()` cuando termine el trabajo. Sin función, el método devuelve una promesa que se resuelve con el worker; libéralo con `worker.release()`.\n\nAntes de que un worker empiece un trabajo, el pool elimina todos sus listeners de `message`, así que cada trabajo añade los suyos.\n\nExample: Con un callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 1, b: 2 });\n});\n```\n\nExample: Con una promesa\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 2 });\n```\n\n### worker.release()\n\nType: `method`\n\nDevuelve un worker de un pool al pool.\n\nTodo worker de un pool tiene este método. Marca el worker como libre y lo da al siguiente trabajo en espera. Es la misma función que el argumento `release` de `pool.exec(fn)`.\n\nExample: Liberar\n```js\nvar worker = await pool.exec();\nworker.on('message', () => worker.release());\nworker.postMessage({});\n```\n\n### pool.workers\n\nType: `property`\n\nLos workers del pool.\n\nReturns: `Array`\n\nUn array de los objetos `Worker` que inició el pool.\n\nExample: Enviar a todos\n```js\npool.workers.forEach(w => w.postMessage({ type: 'reload' }));\n```\n\n### pool.pending\n\nType: `property`\n\nLos trabajos que esperan un worker libre.\n\nReturns: `Array`\n\nUn array de las funciones pasadas a `pool.exec()` que aún no han empezado. Su longitud indica lo ocupado que está el pool.\n\nExample: Longitud de la cola\n```js\nconsole.log('Waiting jobs:', pool.pending.length);\n```\n\n### pool.count\n\nType: `property`\n\nEl número de workers del pool.\n\nReturns: `Number`\n\nEl `count` indicado a `NEWTHREADPOOL()`. El pool mantiene este número de workers: un worker que termina se sustituye.\n\nExample: Tamaño\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\nconsole.log(pool.count); // 4\n```\n\n### F.workers\n\nType: `property`\n\nLos pools de hilos de la aplicación por nombre.\n\nReturns: `Object`\n\n`NEWTHREADPOOL(name, count)` guarda aquí el pool bajo su nombre.\n\nExample: Obtener un pool\n```js\nvar pool = F.workers.calc;\n```\n\n### options.cluster = 4\n\nType: `config`\n\nOpción de inicio: ejecuta la aplicación en un clúster de procesos.\n\nUn número de procesos, o `'auto'`. Defínelo en las opciones de `Total.run()`. El primer proceso se convierte en el master: inicia los procesos uno tras otro, y cada uno carga la aplicación y escucha en el mismo puerto. Un proceso que termina se vuelve a iniciar tras un segundo. Los procesos se ejecutan en modo release con `options.release = true` u `options.watcher = false`; si no, se ejecutan en modo debug y el master los reinicia todos cuando cambia un archivo fuente.\n\nCon `'auto'` el master inicia un proceso, hace ping a todos los procesos cada 5 segundos y añade uno cuando la respuesta media tarda más de 70 ms (hasta `limit`). Cuando vuelven a responder rápido, elimina el último proceso si tiene menos de dos peticiones pendientes.\n\nExample: Script de inicio\n```js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n\nTotal.run(options);\n```\n\n### options.limit = 10\n\nType: `config`\n\nOpción de inicio: el número máximo de procesos de un clúster 'auto'.\n\nSolo se usa con `cluster: 'auto'`. Sin ella, el master puede añadir procesos sin límite.\n\nExample: Clúster automático\n```js\nrequire('total5');\n\nTotal.run({ release: true, port: 8000, cluster: 'auto', limit: 8 });\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nOpción de inicio de un clúster: la zona horaria de los procesos.\n\nEn modo clúster, el framework define `process.env.TZ` con este valor antes de iniciar los procesos. El valor por defecto es `'utc'`.\n\nExample: Zona horaria\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 4, tz: 'Europe/Madrid' });\n```\n\n### options.logs = 'isolated'\n\nType: `config`\n\nOpción de inicio de un clúster: imprimir siempre la cabecera del clúster.\n\nEl master imprime la cabecera `CLUSTER` (PID, versiones, número de hilos, modo) cuando se ejecuta por sí solo. Cuando se ejecuta bajo otro proceso de Node.js (con un canal IPC) la cabecera se omite, salvo que `logs` sea `'isolated'`.\n\nExample: Cabecera\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 2, logs: 'isolated' });\n```\n\n### options.callback = function(forks) {}\n\nType: `delegate`\n\nOpción de inicio de un clúster: se llama cuando todos los procesos han arrancado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forks` | `Array` | yes |  | Los workers del clúster |\n\nSe ejecuta en el master cuando cada proceso del clúster ha arrancado. `forks` es el array de los objetos `cluster.Worker`.\n\nExample: Tras el inicio\n```js\nrequire('total5');\n\nTotal.run({\n\trelease: true,\n\tcluster: 2,\n\tcallback: function(forks) {\n\t\tconsole.log('Started', forks.length, 'processes');\n\t}\n});\n```\n\n### F.isCluster\n\nType: `property`\n\ntrue en un proceso de un clúster.\n\nReturns: `Boolean`\n\nEl framework lo define cuando el master envía las opciones de inicio al proceso. En otros casos es `undefined`.\n\nExample: Comprobar\n```js\nif (F.isCluster)\n\tprocess.send({ type: 'clearcache' });\n```\n\n### F.isWorker\n\nType: `property`\n\ntrue cuando el proceso es un worker del clúster de Node.js.\n\nReturns: `Boolean`\n\nEl valor de `cluster.isWorker` de Node.js, así que es `true` en los procesos de un clúster de Total.js. Es `false` cuando está definida la variable de entorno `PASSENGER_APP_ENV`. Los procesos con `F.isWorker` envían sus estadísticas al master.\n\nExample: Comprobar\n```js\nconsole.log(F.isWorker);\n```\n\n### F.clusterid\n\nType: `property`\n\nEl identificador del proceso en un clúster.\n\nReturns: `String`\n\nUna cadena como `'1'` o `'2'`, el mismo valor que `F.id`. Fuera de un clúster es una cadena vacía. El framework lo añade a los nombres de los archivos temporales y a las estadísticas.\n\nExample: Archivo por proceso\n```js\nvar filename = PATH.tmp('export' + F.clusterid + '.csv');\n```\n\n### F.id\n\nType: `property`\n\nEl identificador del proceso en un clúster.\n\nReturns: `String`\n\nEl mismo valor que `F.clusterid`: una cadena con el número del proceso, o una cadena vacía fuera de un clúster.\n\nExample: Log\n```js\nconsole.log('Process', F.id);\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nCada mensaje que el proceso recibe por su canal 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 por cada mensaje del proceso padre. En un clúster, un objeto que un proceso envía con `process.send()` lo pasa el master a todos los procesos listos, incluido el emisor, y cada uno lo recibe aquí. No uses la propiedad `TYPE` ni cadenas que empiecen por `total:` en tus mensajes: el framework las usa.\n\nExample: Sincronizar cachés\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// in any process\nprocess.send({ type: 'clearcache' });\n```\n\n### restart (file)\n\nType: `command`\n\nUn archivo que reinicia todos los procesos de un clúster.\n\nEl master de un clúster comprueba cada 5 segundos si existe un archivo llamado `restart` en el directorio de la aplicación. Si existe, el master lo borra y reinicia los procesos uno a uno, con dos segundos de separación. Un segundo reinicio en menos de 30 segundos se ignora.\n\nExample: Reiniciar desde la shell\n```bash\n$ touch restart\n```\n\n### SHELL(cmd, [callback], [cwd])\n\nType: `method`\n\nEjecuta un comando de shell.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cmd` | `String` | yes |  | El comando |\n| `callback` | `Function` | no |  | `function(err, stdout)`; o el directorio de trabajo como cadena |\n| `cwd` | `String` | no | `the application root` | El directorio de trabajo |\n\nReturns: `Promise` Solo sin callback: se resuelve con la salida estándar\n\nEjecuta el comando con `child_process.exec()` en la shell del sistema. Con un callback llama a `callback(err, stdout)`; sin él devuelve una promesa que se resuelve con la salida estándar o se rechaza con el error. Un string como segundo argumento es el directorio de trabajo. El directorio por defecto es la raíz de la aplicación. La clave de configuración `$shell` establece la shell que se usa. La salida puede tener hasta 100 MB (`maxBuffer`); una salida mayor termina con un error.\n\nExample: Callback\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n```\n\nExample: Promesa y directorio\n```js\nvar list = await SHELL('ls -1', PATH.public());\n```\n\n### $shell : /bin/bash\n\nType: `config`\n\nLa shell que usa SHELL().\n\nLa ruta de la shell para `SHELL()`. No está definida por defecto, lo que usa la shell por defecto de Node.js (`/bin/sh`, o `cmd.exe` en Windows).\n\nExample: config\n```text\n$shell : /bin/bash\n```\n\n### F.python(filename, [callback])\n\nType: `method`\n\nEjecuta un script de Python y devuelve su salida.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | La ruta absoluta al archivo `.py`. |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)`. |\n\nReturns: `Promise` Solo sin callback: se resuelve con la salida estándar.\n\nEjecuta `$python <filename>` con `child_process.exec()` en la carpeta del script. Con un callback llama a `callback(err, stdout, stderr)`; sin él devuelve una promesa que se resuelve con la salida estándar. Un script que termina con un código de salida distinto de `0` da un error (`err.code` es el código de salida) y la promesa se rechaza. `$python` es la clave de configuración con el comando de Python (`python3` por defecto).\n\nExample: Promesa\n```js\nvar output = await F.python(PATH.root('scripts/report.py'));\n```\n\nExample: Callback\n```js\nF.python(PATH.root('scripts/report.py'), function(err, stdout, stderr) {\n\tif (err)\n\t\tconsole.log(stderr);\n\telse\n\t\tconsole.log(stdout);\n});\n```\n\n### PYPELINE(name, [options])\n\nType: `method`\n\nInicia un script de Python e intercambia mensajes con él.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del archivo en `pypelines/` sin `.py`, `~` y una ruta absoluta, o código inline |\n| `options` | `Object` | no |  | `{ autorestart, type, socket }` |\n\nReturns: `Pypeline` Un objeto con eventos y los métodos de abajo\n\nEjecuta `python3` con `pypelines/{name}.py` (o una ruta absoluta que empieza por `~`) en la carpeta del script. Un `name` que contiene un salto de línea, `;` o una comilla es código inline, ejecutado con `python3 -c` en la raíz de la aplicación.\n\nEl framework escucha en un socket Unix en `tmp/` y pasa su ruta al script como `sys.argv[1]`. Cada mensaje, en ambas direcciones, es una longitud de 4 bytes big-endian seguida del payload. La salida estándar y la de error del script van a la consola de la aplicación. Cuando la aplicación termina, se matan todos los procesos Python.\n\nLas opciones son `autorestart` (por defecto `true`: volver a iniciar el script cuando termina), `type` (`'json'` por defecto, `'text'` para cadenas, o cualquier otro valor para buffers en bruto) y `socket` (`false` ejecuta el script sin socket, para scripts que solo se ejecutan).\n\nExample: Iniciar un pipeline\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text);\n});\n\npy.send({ text: 'hello' });\n```\n\nExample: Mensajes de texto\n```js\nvar py = PYPELINE('tokenizer', { type: 'text' });\n```\n\n### F.pipinstall(name, [callback])\n\nType: `method`\n\nInstala un paquete de Python con pip.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El paquete, opcionalmente con una versión (`requests==2.32.3`). |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Solo sin callback.\n\nEjecuta `$python -m pip install <name>` en el directorio de la aplicación. Con un callback llama a `callback(err)`; sin él devuelve una promesa. Cuando pip falla, el error es la salida de error de pip (un string), o el error del proceso.\n\nExample: Instalar antes de usar\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/download.py'));\n```\n\n### pypeline.send(data)\n\nType: `method`\n\nEnvía un mensaje al script de Python.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|Buffer|String` | yes |  | El mensaje |\n\nReturns: `Pypeline` El pipeline (solo cuando el script está conectado)\n\nUn objeto se envía como JSON, un `Buffer` tal cual y otros valores como texto, cada uno precedido de una longitud de 4 bytes. Los mensajes enviados antes de que el script se conecte esperan y se envían cuando se conecta.\n\nExample: Enviar\n```js\npy.send({ text: 'hello' });\n```\n\n### pypeline.close()\n\nType: `method`\n\nDetiene el script de Python definitivamente.\n\nReturns: `Pypeline`\n\nDesactiva `autorestart`, cierra el servidor del socket y mata el proceso Python.\n\nExample: Detener\n```js\npy.close();\n```\n\n### pypeline.restart()\n\nType: `method`\n\nMata el proceso Python y lo vuelve a iniciar.\n\nMata el proceso actual y vuelve a iniciar el script. `pypeline.run()` es el mismo método.\n\nExample: Recargar\n```js\npy.restart();\n```\n\n### pypeline.on('data', function(msg) {})\n\nType: `event`\n\nUn mensaje del script de Python.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object|String|Buffer` | yes |  | El mensaje |\n\nSe emite por cada mensaje completo. Con `type: 'json'` el mensaje se parsea, con `'text'` es una cadena, y en otro caso un `Buffer`.\n\nExample: Leer\n```js\npy.on('data', function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### pypeline.on('open', function() {})\n\nType: `event`\n\nEl script de Python se conectó al socket.\n\nSe emite cada vez que el script se conecta, después de enviar los mensajes en espera.\n\nExample: Conectado\n```js\npy.on('open', function() {\n\tconsole.log('Python is ready');\n});\n```\n\n### pypeline.on('restart', function() {})\n\nType: `event`\n\nEl script de Python terminó y se volvió a iniciar.\n\nSe emite con `autorestart: true` después de que el framework haya vuelto a iniciar el script.\n\nExample: Registrar reinicios\n```js\npy.on('restart', function() {\n\tconsole.log('Python restarted');\n});\n```\n\n### pypeline.name\n\nType: `property`\n\nEl nombre del pipeline.\n\nReturns: `String`\n\nEl `name` pasado a `PYPELINE()`, o `Inline Python Code` para código inline.\n\nExample: Log\n```js\nconsole.log(py.name);\n```\n","entries":[{"type":"method","name":"NEWTHREAD(name, [data])","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD()","since":"","deprecated":false},{"type":"property","name":"F.worker","signature":"F.worker","since":"","deprecated":false},{"type":"property","name":"F.worker.data","signature":"F.worker.data","since":"","deprecated":false},{"type":"property","name":"F.worker.is","signature":"F.worker.is","since":"","deprecated":false},{"type":"property","name":"F.worker.isfork","signature":"F.worker.isfork","since":"","deprecated":false},{"type":"delegate","name":"F.worker.message","signature":"F.worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"F.worker.send(msg)","signature":"F.worker.send(msg)","since":"","deprecated":false},{"type":"method","name":"F.worker.exit([code])","signature":"F.worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"F.worker.setTimeout(timeout)","signature":"F.worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"thread.kill()","signature":"thread.kill()","since":"","deprecated":false},{"type":"method","name":"NEWFORK(name)","signature":"NEWFORK(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.terminate()","signature":"fork.terminate()","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.postMessage(msg)","signature":"fork.postMessage(msg)","since":"0.0.16","deprecated":false},{"type":"method","name":"NEWTHREADPOOL(name, count)","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec([fn])","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"method","name":"worker.release()","signature":"worker.release()","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"pool.pending","signature":"pool.pending","since":"","deprecated":false},{"type":"property","name":"pool.count","signature":"pool.count","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"config","name":"cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"limit","signature":"options.limit = 10","since":"","deprecated":false},{"type":"config","name":"tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"delegate","name":"callback","signature":"options.callback = function(forks) {}","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.isWorker","signature":"F.isWorker","since":"","deprecated":false},{"type":"property","name":"F.clusterid","signature":"F.clusterid","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart (file)","since":"","deprecated":false},{"type":"method","name":"SHELL(cmd, [callback], [cwd])","signature":"SHELL(cmd, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : /bin/bash","since":"","deprecated":false},{"type":"method","name":"F.python()","signature":"F.python(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"PYPELINE(name, [options])","signature":"PYPELINE(name, [options])","since":"","deprecated":false},{"type":"method","name":"F.pipinstall()","signature":"F.pipinstall(name, [callback])","since":"","deprecated":false},{"type":"method","name":"pypeline.send(data)","signature":"pypeline.send(data)","since":"","deprecated":false},{"type":"method","name":"pypeline.close()","signature":"pypeline.close()","since":"","deprecated":false},{"type":"method","name":"pypeline.restart()","signature":"pypeline.restart()","since":"","deprecated":false},{"type":"event","name":"pypeline.on('data')","signature":"pypeline.on('data', function(msg) {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('open')","signature":"pypeline.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('restart')","signature":"pypeline.on('restart', function() {})","since":"","deprecated":false},{"type":"property","name":"pypeline.name","signature":"pypeline.name","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvT9Ex61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Workers, threads et cluster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, les options du cluster, SHELL(), F.python(), F.pipinstall() et PYPELINE().","markdown":"---\ntitle: Workers, threads et cluster\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/workers-and-threads/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Workers, threads et cluster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, les options du cluster, SHELL(), F.python(), F.pipinstall() et PYPELINE().\n\nMéthodes, propriétés, options de démarrage et événements des worker threads, des processus forkés, des pools de threads, du cluster, de `SHELL()` et de `PYPELINE()`. Pour une introduction avec des exemples, lis le guide [Workers, threads et cluster](../../guides/workers-and-threads/).\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nDémarre un worker thread depuis le dossier workers/.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du fichier dans `workers/` sans `.js`, ou `~` et un chemin absolu |\n| `data` | `Object` | no |  | Les données copiées dans le thread sous `F.worker.data` |\n\nReturns: `Worker` Le worker thread Node.js\n\nExécute `workers/{name}.js` dans un nouveau worker thread Node.js. Un nom qui commence par `~` est un chemin absolu vers le script. `data` est copié dans le thread et y est disponible sous `F.worker.data`. Le thread reçoit `--worker` dans son `process.argv`.\n\nLe résultat est l'objet `Worker` de Node.js : utilise `postMessage()` pour envoyer un message et `on('message')`, `on('error')` et `on('exit')` pour écouter. Le framework ajoute `kill()` et `exit()`, qui appellent `terminate()`.\n\nExample: Démarrer un thread\n```js\nvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\nthread.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tthread.kill();\n});\n\nthread.postMessage({ a: 1, b: 2 });\n```\n\n### NEWTHREAD()\n\nType: `method`\n\nDans un script de worker : renvoie l'objet worker F.worker.\n\nReturns: `Object` F.worker\n\nAppelée sans nom dans un script qui s'exécute comme worker, `NEWTHREAD()` crée `F.worker` (ou le renvoie s'il existe), définit le répertoire de l'application sur le répertoire de travail courant et commence à transmettre les messages du parent à `F.worker.message`. Charge le framework avec `require('total5')` avant de l'appeler.\n\nExample: workers/calc.js\n```js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tworker.send({ sum: msg.a + msg.b });\n};\n```\n\n### F.worker\n\nType: `property`\n\nL'objet worker d'un script qui s'exécute comme worker.\n\nReturns: `Object`\n\nCréé par `NEWTHREAD()` (ou `NEWFORK()`) sans nom. Il contient les données du parent et les méthodes pour recevoir et envoyer des messages et pour terminer le worker. Dans l'application principale, il vaut `undefined`.\n\nExample: Vérifier les données\n```js\nvar worker = NEWTHREAD();\nconsole.log(F.worker === worker); // true\nconsole.log(worker.data);\n```\n\n### F.worker.data\n\nType: `property`\n\nLes données passées à NEWTHREAD(name, data).\n\nReturns: `Object`\n\nUne copie du deuxième argument de `NEWTHREAD()` dans le thread principal. C'est un objet vide `{}` quand aucune donnée n'a été passée, dans un fork et dans les threads d'un pool.\n\nExample: Lire les données\n```js\nvar worker = NEWTHREAD();\nvar user = worker.data.user;\n```\n\n### F.worker.is\n\nType: `property`\n\ntrue quand le script s'exécute comme worker.\n\nReturns: `Boolean`\n\n`true` dans un thread de `NEWTHREAD()`, dans un fork de `NEWFORK()` et dans les workers de `NEWTHREADPOOL()` : ils reçoivent tous l'argument `--worker` dans `process.argv`.\n\nExample: Exécuter comme worker ou seul\n```js\nvar worker = NEWTHREAD();\nif (!worker.is)\n\tconsole.log('Started directly with node, not as a worker');\n```\n\n### F.worker.isfork\n\nType: `property`\n\ntrue dans un processus forké, false dans un worker thread.\n\nReturns: `Boolean`\n\n`true` quand le worker est un processus de `NEWFORK()` (les messages passent par `process.send()`), `false` dans un worker thread.\n\nExample: Thread ou processus\n```js\nvar worker = NEWTHREAD();\nconsole.log(worker.isfork ? 'process ' + process.pid : 'thread');\n```\n\n### F.worker.message = function(msg) {}\n\nType: `delegate`\n\nReçoit les messages du parent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Le message du parent |\n\nAssigne une fonction. Elle est appelée avec chaque message que le parent envoie avec `postMessage()`. Par défaut, elle ne fait rien.\n\nExample: Répondre aux messages\n```js\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tif (msg.type === 'ping')\n\t\tworker.send({ type: 'pong' });\n};\n```\n\n### F.worker.send(msg)\n\nType: `method`\n\nEnvoie un message au parent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Le message ; il est copié, les fonctions ne sont pas autorisées |\n\nEnvoie le message au processus ou au thread qui a démarré le worker. `F.worker.postMessage()` est la même méthode. Le parent le reçoit dans `on('message')`.\n\nExample: Envoyer un résultat\n```js\nworker.send({ id: msg.id, result: result });\n```\n\n### F.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)`. Dans un thread, elle termine le thread ; le parent reçoit l'événement `exit` avec le code. `F.worker.kill()` et `F.worker.close()` sont la même méthode.\n\nExample: Terminer après la tâche\n```js\nworker.message = function(msg) {\n\twork(msg);\n\tworker.exit();\n};\n```\n\n### F.worker.setTimeout(timeout)\n\nType: `method`\n\nTermine le worker avec le code 1 après un délai.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Millisecondes |\n\nDémarre un compte à rebours. Quand il arrive à zéro, le worker se termine avec le code de sortie `1`. Un nouvel appel annule le compte à rebours précédent et en démarre un nouveau ; appelle-la donc au début de chaque tâche.\n\nExample: Watchdog\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\tjob(msg, function(response) {\n\t\tworker.send(response);\n\t});\n};\n```\n\n### thread.kill()\n\nType: `method`\n\nArrête un thread démarré avec NEWTHREAD().\n\nAppelle `terminate()` du `Worker` de Node.js. `thread.exit()` est la même méthode.\n\nExample: Arrêter un thread\n```js\nvar thread = NEWTHREAD('calc');\nsetTimeout(() => thread.kill(), 5000);\n```\n\n### NEWFORK(name)\n\nType: `method` · Since: `0.0.16`\n\nExécute un script du dossier workers/ dans un nouveau processus Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du fichier dans `workers/` sans `.js`, ou `~` suivi d'un chemin absolu |\n\nReturns: `ChildProcess` Le processus forké\n\nDémarre `workers/{name}.js` avec `child_process.fork()`. Un nom qui commence par `~` est un chemin absolu. Le résultat est le `ChildProcess` de Node.js ; le framework ajoute `postMessage()` (identique à `send()`) et `terminate()`. Les messages sont sérialisés en JSON.\n\nLe répertoire de travail du fork est le dossier de son script. Le framework du fork envoie la chaîne `total:init` au parent après son démarrage : ignore donc les messages de type chaîne dans le parent. Appelée sans nom à l'intérieur du fork, `NEWFORK()` renvoie `F.worker`, comme `NEWTHREAD()` le fait dans un thread ; `F.worker.data` est alors un objet vide.\n\nExample: Application principale\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn;\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nExample: workers/report.js\n```js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n### fork.terminate()\n\nType: `method` · Since: `0.0.16`\n\nTue un processus démarré avec NEWFORK().\n\nEnvoie `SIGKILL` au processus. Le processus se termine immédiatement, sans exécuter ses handlers de sortie.\n\nExample: Tuer un fork\n```js\nvar fork = NEWFORK('report');\nsetTimeout(() => fork.terminate(), 60000);\n```\n\n### fork.postMessage(msg)\n\nType: `method` · Since: `0.0.16`\n\nEnvoie un message à un processus démarré avec NEWFORK().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Le message ; il est sérialisé en JSON |\n\nLa même méthode que `fork.send()` de Node.js, afin que le code des threads et des forks puisse se ressembler. Le fork reçoit le message dans `F.worker.message`.\n\nExample: Envoyer une tâche\n```js\nfork.postMessage({ id: 100, type: 'pdf' });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nDémarre un pool de worker threads ou de forks 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 |  | Le nombre de workers |\n| `isfork` | `Boolean` | no | `false` | Démarrer les workers avec `NEWFORK()` au lieu de threads |\n\nReturns: `Object` Le pool\n\nDémarre d'un coup `count` workers de `workers/{name}.js` et renvoie un pool : des worker threads, ou des processus de `NEWFORK()` quand `isfork` vaut `true`. Les tâches obtiennent les workers via `pool.exec()` ; un worker ne passe à la tâche suivante qu'après que la tâche en cours a appelé `release()`. Les tâches qui arrivent pendant que tous les workers sont occupés attendent dans `pool.pending`. Un worker qui se termine est remplacé par un nouveau, qui est donné à la prochaine tâche en attente. Les workers ne reçoivent aucune donnée (`F.worker.data` vaut `{}`). Le pool est aussi stocké dans `F.workers[name]`.\n\nExample: Pool de quatre threads\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\nExample: Pool de forks\n```js\nvar pool = NEWTHREADPOOL('report', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nExécute une tâche sur le prochain worker libre du pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Seulement sans `fn` : résolue avec le worker\n\nAjoute la tâche à la file et la démarre dès qu'un worker est libre. La fonction reçoit `(worker, release)` ; appelle `release()` quand la tâche est terminée. Sans fonction, la méthode renvoie une promesse résolue avec le worker ; libère-le avec `worker.release()`.\n\nAvant qu'un worker commence une tâche, le pool supprime tous ses écouteurs `message`, donc chaque tâche attache les siens.\n\nExample: Avec un callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 1, b: 2 });\n});\n```\n\nExample: Avec une promesse\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 2 });\n```\n\n### worker.release()\n\nType: `method`\n\nRend un worker d'un pool au pool.\n\nChaque worker d'un pool a cette méthode. Elle marque le worker comme libre et le donne à la prochaine tâche en attente. C'est la même fonction que l'argument `release` de `pool.exec(fn)`.\n\nExample: Libérer\n```js\nvar worker = await pool.exec();\nworker.on('message', () => worker.release());\nworker.postMessage({});\n```\n\n### pool.workers\n\nType: `property`\n\nLes workers du pool.\n\nReturns: `Array`\n\nUn tableau des objets `Worker` que le pool a démarrés.\n\nExample: Envoyer à tous\n```js\npool.workers.forEach(w => w.postMessage({ type: 'reload' }));\n```\n\n### pool.pending\n\nType: `property`\n\nLes tâches qui attendent un worker libre.\n\nReturns: `Array`\n\nUn tableau des fonctions passées à `pool.exec()` qui n'ont pas encore démarré. Sa longueur indique la charge du pool.\n\nExample: Longueur de la file\n```js\nconsole.log('Waiting jobs:', pool.pending.length);\n```\n\n### pool.count\n\nType: `property`\n\nLe nombre de workers du pool.\n\nReturns: `Number`\n\nLe `count` donné à `NEWTHREADPOOL()`. Le pool garde ce nombre de workers : un worker qui se termine est remplacé.\n\nExample: Taille\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\nconsole.log(pool.count); // 4\n```\n\n### F.workers\n\nType: `property`\n\nLes pools de threads de l'application, par nom.\n\nReturns: `Object`\n\n`NEWTHREADPOOL(name, count)` stocke ici le pool sous son nom.\n\nExample: Obtenir un pool\n```js\nvar pool = F.workers.calc;\n```\n\n### options.cluster = 4\n\nType: `config`\n\nOption de démarrage : exécute l'application dans un cluster de processus.\n\nUn nombre de processus, ou `'auto'`. Définis-la dans les options de `Total.run()`. Le premier processus devient le master : il démarre les processus l'un après l'autre, chacun charge l'application et écoute sur le même port. Un processus qui se termine est redémarré après une seconde. Les processus s'exécutent en mode release avec `options.release = true` ou `options.watcher = false` ; sinon, ils s'exécutent en mode debug et le master les redémarre tous quand un fichier source change.\n\nAvec `'auto'`, le master démarre un processus, envoie un ping à tous les processus toutes les 5 secondes et en ajoute un quand la réponse moyenne prend plus de 70 ms (jusqu'à `limit`). Quand ils répondent de nouveau rapidement, il supprime le dernier processus s'il a moins de deux requêtes en attente.\n\nExample: Script de démarrage\n```js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n\nTotal.run(options);\n```\n\n### options.limit = 10\n\nType: `config`\n\nOption de démarrage : le nombre maximal de processus d'un cluster 'auto'.\n\nUtilisée seulement avec `cluster: 'auto'`. Sans elle, le master peut ajouter des processus sans limite.\n\nExample: Cluster auto\n```js\nrequire('total5');\n\nTotal.run({ release: true, port: 8000, cluster: 'auto', limit: 8 });\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nOption de démarrage d'un cluster : le fuseau horaire des processus.\n\nEn mode cluster, le framework définit `process.env.TZ` sur cette valeur avant de démarrer les processus. La valeur par défaut est `'utc'`.\n\nExample: Fuseau horaire\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 4, tz: 'Europe/Madrid' });\n```\n\n### options.logs = 'isolated'\n\nType: `config`\n\nOption de démarrage d'un cluster : toujours afficher l'en-tête du cluster.\n\nLe master affiche l'en-tête `CLUSTER` (PID, versions, nombre de threads, mode) quand il s'exécute seul. Quand il s'exécute sous un autre processus Node.js (avec un canal IPC), l'en-tête est omis, sauf si `logs` vaut `'isolated'`.\n\nExample: En-tête\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 2, logs: 'isolated' });\n```\n\n### options.callback = function(forks) {}\n\nType: `delegate`\n\nOption de démarrage d'un cluster : appelée une fois tous les processus démarrés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forks` | `Array` | yes |  | Les workers du cluster |\n\nS'exécute dans le master une fois que chaque processus du cluster a démarré. `forks` est le tableau des objets `cluster.Worker`.\n\nExample: Après le démarrage\n```js\nrequire('total5');\n\nTotal.run({\n\trelease: true,\n\tcluster: 2,\n\tcallback: function(forks) {\n\t\tconsole.log('Started', forks.length, 'processes');\n\t}\n});\n```\n\n### F.isCluster\n\nType: `property`\n\ntrue dans un processus d'un cluster.\n\nReturns: `Boolean`\n\nLe framework la définit quand le master envoie les options de démarrage au processus. Dans les autres cas, elle vaut `undefined`.\n\nExample: Vérifier\n```js\nif (F.isCluster)\n\tprocess.send({ type: 'clearcache' });\n```\n\n### F.isWorker\n\nType: `property`\n\ntrue quand le processus est un worker du cluster Node.js.\n\nReturns: `Boolean`\n\nLa valeur de `cluster.isWorker` de Node.js, donc elle vaut `true` dans les processus d'un cluster Total.js. Elle vaut `false` quand la variable d'environnement `PASSENGER_APP_ENV` est définie. Les processus avec `F.isWorker` envoient leurs statistiques au master.\n\nExample: Vérifier\n```js\nconsole.log(F.isWorker);\n```\n\n### F.clusterid\n\nType: `property`\n\nL'identifiant du processus dans un cluster.\n\nReturns: `String`\n\nUne chaîne comme `'1'` ou `'2'`, la même valeur que `F.id`. Hors d'un cluster, c'est une chaîne vide. Le framework l'ajoute aux noms des fichiers temporaires et aux statistiques.\n\nExample: Fichier par processus\n```js\nvar filename = PATH.tmp('export' + F.clusterid + '.csv');\n```\n\n### F.id\n\nType: `property`\n\nL'identifiant du processus dans un cluster.\n\nReturns: `String`\n\nLa même valeur que `F.clusterid` : une chaîne avec le numéro du processus, ou une chaîne vide hors d'un cluster.\n\nExample: Journal\n```js\nconsole.log('Process', F.id);\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nChaque message que le processus reçoit via son canal 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, s'il y en a un |\n\nÉmis pour chaque message du processus parent. Dans un cluster, un objet qu'un processus envoie avec `process.send()` est transmis par le master à tous les processus prêts, y compris l'expéditeur, et chacun le reçoit ici. N'utilise pas la propriété `TYPE` ni des chaînes qui commencent par `total:` dans tes messages : le framework les utilise.\n\nExample: Synchroniser les caches\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// in any process\nprocess.send({ type: 'clearcache' });\n```\n\n### restart (file)\n\nType: `command`\n\nUn fichier qui redémarre tous les processus d'un cluster.\n\nLe master d'un cluster vérifie toutes les 5 secondes si un fichier nommé `restart` existe dans le répertoire de l'application. Si c'est le cas, le master le supprime et redémarre les processus un par un, à deux secondes d'intervalle. Un deuxième redémarrage dans les 30 secondes est ignoré.\n\nExample: Redémarrer depuis le shell\n```bash\n$ touch restart\n```\n\n### SHELL(cmd, [callback], [cwd])\n\nType: `method`\n\nExécute une commande shell.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cmd` | `String` | yes |  | La commande |\n| `callback` | `Function` | no |  | `function(err, stdout)` ; ou le répertoire de travail sous forme de chaîne |\n| `cwd` | `String` | no | `the application root` | Le répertoire de travail |\n\nReturns: `Promise` Seulement sans callback : résolue avec la sortie standard\n\nExécute la commande avec `child_process.exec()` dans le shell du système. Avec un callback, elle appelle `callback(err, stdout)` ; sans callback, elle renvoie une promesse résolue avec la sortie standard ou rejetée avec l'erreur. Une chaîne comme second argument est le répertoire de travail. Le répertoire par défaut est la racine de l'application. La clé de configuration `$shell` définit le shell à utiliser. La sortie peut atteindre 100 Mo (`maxBuffer`) ; une sortie plus grande se termine par une erreur.\n\nExample: Callback\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n```\n\nExample: Promesse et répertoire\n```js\nvar list = await SHELL('ls -1', PATH.public());\n```\n\n### $shell : /bin/bash\n\nType: `config`\n\nLe shell qu'utilise SHELL().\n\nLe chemin du shell pour `SHELL()`. Non défini par défaut, ce qui utilise le shell par défaut de Node.js (`/bin/sh`, ou `cmd.exe` sous Windows).\n\nExample: config\n```text\n$shell : /bin/bash\n```\n\n### F.python(filename, [callback])\n\nType: `method`\n\nExécute un script Python et renvoie sa sortie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le chemin absolu du fichier `.py`. |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)`. |\n\nReturns: `Promise` Seulement sans callback : résolue avec la sortie standard.\n\nExécute `$python <filename>` avec `child_process.exec()` dans le dossier du script. Avec un callback, elle appelle `callback(err, stdout, stderr)` ; sans callback, elle renvoie une promesse résolue avec la sortie standard. Un script qui se termine avec un code de sortie autre que `0` donne une erreur (`err.code` est le code de sortie) et la promesse est rejetée. `$python` est la clé de configuration avec la commande Python (`python3` par défaut).\n\nExample: Promesse\n```js\nvar output = await F.python(PATH.root('scripts/report.py'));\n```\n\nExample: Callback\n```js\nF.python(PATH.root('scripts/report.py'), function(err, stdout, stderr) {\n\tif (err)\n\t\tconsole.log(stderr);\n\telse\n\t\tconsole.log(stdout);\n});\n```\n\n### PYPELINE(name, [options])\n\nType: `method`\n\nDémarre un script Python et échange des messages avec lui.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du fichier dans `pypelines/` sans `.py`, `~` et un chemin absolu, ou du code en ligne |\n| `options` | `Object` | no |  | `{ autorestart, type, socket }` |\n\nReturns: `Pypeline` Un objet avec des événements et les méthodes ci-dessous\n\nExécute `python3` avec `pypelines/{name}.py` (ou un chemin absolu qui commence par `~`) dans le dossier du script. Un `name` qui contient un saut de ligne, `;` ou un guillemet est du code en ligne, exécuté avec `python3 -c` à la racine de l'application.\n\nLe framework écoute sur un socket Unix dans `tmp/` et passe son chemin au script sous `sys.argv[1]`. Chaque message, dans les deux sens, est une longueur de 4 octets en big-endian suivie des données. La sortie standard et la sortie d'erreur du script vont dans la console de l'application. Quand l'application se termine, tous les processus Python sont tués.\n\nLes options sont `autorestart` (par défaut `true` : redémarrer le script quand il se termine), `type` (`'json'` par défaut, `'text'` pour des chaînes, ou toute autre valeur pour des buffers bruts) et `socket` (`false` exécute le script sans socket, pour les scripts qui se contentent de s'exécuter).\n\nExample: Démarrer un pipeline\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text);\n});\n\npy.send({ text: 'hello' });\n```\n\nExample: Messages texte\n```js\nvar py = PYPELINE('tokenizer', { type: 'text' });\n```\n\n### F.pipinstall(name, [callback])\n\nType: `method`\n\nInstalle un paquet Python avec pip.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le paquet, éventuellement avec une version (`requests==2.32.3`). |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Uniquement sans callback.\n\nExécute `$python -m pip install <name>` dans le répertoire de l'application. Avec un callback, elle appelle `callback(err)` ; sans callback, elle renvoie une promesse. Quand pip échoue, l'erreur est la sortie d'erreur de pip (une chaîne), ou l'erreur du processus.\n\nExample: Installer avant l'utilisation\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/download.py'));\n```\n\n### pypeline.send(data)\n\nType: `method`\n\nEnvoie un message au script Python.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|Buffer|String` | yes |  | Le message |\n\nReturns: `Pypeline` Le pipeline (seulement quand le script est connecté)\n\nUn objet est envoyé en JSON, un `Buffer` tel quel et les autres valeurs en texte, chacun précédé d'une longueur de 4 octets. Les messages envoyés avant que le script se connecte attendent et sont envoyés à sa connexion.\n\nExample: Envoyer\n```js\npy.send({ text: 'hello' });\n```\n\n### pypeline.close()\n\nType: `method`\n\nArrête définitivement le script Python.\n\nReturns: `Pypeline`\n\nDésactive `autorestart`, ferme le serveur de socket et tue le processus Python.\n\nExample: Arrêter\n```js\npy.close();\n```\n\n### pypeline.restart()\n\nType: `method`\n\nTue le processus Python et le redémarre.\n\nTue le processus en cours et redémarre le script. `pypeline.run()` est la même méthode.\n\nExample: Recharger\n```js\npy.restart();\n```\n\n### pypeline.on('data', function(msg) {})\n\nType: `event`\n\nUn message du script Python.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object|String|Buffer` | yes |  | Le message |\n\nÉmis pour chaque message complet. Avec `type: 'json'`, le message est analysé ; avec `'text'`, c'est une chaîne ; sinon, un `Buffer`.\n\nExample: Lire\n```js\npy.on('data', function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### pypeline.on('open', function() {})\n\nType: `event`\n\nLe script Python s'est connecté au socket.\n\nÉmis chaque fois que le script se connecte, après l'envoi des messages en attente.\n\nExample: Connecté\n```js\npy.on('open', function() {\n\tconsole.log('Python is ready');\n});\n```\n\n### pypeline.on('restart', function() {})\n\nType: `event`\n\nLe script Python s'est terminé et a été redémarré.\n\nÉmis avec `autorestart: true` après que le framework a redémarré le script.\n\nExample: Journaliser les redémarrages\n```js\npy.on('restart', function() {\n\tconsole.log('Python restarted');\n});\n```\n\n### pypeline.name\n\nType: `property`\n\nLe nom du pipeline.\n\nReturns: `String`\n\nLe `name` passé à `PYPELINE()`, ou `Inline Python Code` pour du code en ligne.\n\nExample: Journal\n```js\nconsole.log(py.name);\n```\n","entries":[{"type":"method","name":"NEWTHREAD(name, [data])","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD()","since":"","deprecated":false},{"type":"property","name":"F.worker","signature":"F.worker","since":"","deprecated":false},{"type":"property","name":"F.worker.data","signature":"F.worker.data","since":"","deprecated":false},{"type":"property","name":"F.worker.is","signature":"F.worker.is","since":"","deprecated":false},{"type":"property","name":"F.worker.isfork","signature":"F.worker.isfork","since":"","deprecated":false},{"type":"delegate","name":"F.worker.message","signature":"F.worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"F.worker.send(msg)","signature":"F.worker.send(msg)","since":"","deprecated":false},{"type":"method","name":"F.worker.exit([code])","signature":"F.worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"F.worker.setTimeout(timeout)","signature":"F.worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"thread.kill()","signature":"thread.kill()","since":"","deprecated":false},{"type":"method","name":"NEWFORK(name)","signature":"NEWFORK(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.terminate()","signature":"fork.terminate()","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.postMessage(msg)","signature":"fork.postMessage(msg)","since":"0.0.16","deprecated":false},{"type":"method","name":"NEWTHREADPOOL(name, count)","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec([fn])","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"method","name":"worker.release()","signature":"worker.release()","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"pool.pending","signature":"pool.pending","since":"","deprecated":false},{"type":"property","name":"pool.count","signature":"pool.count","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"config","name":"cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"limit","signature":"options.limit = 10","since":"","deprecated":false},{"type":"config","name":"tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"delegate","name":"callback","signature":"options.callback = function(forks) {}","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.isWorker","signature":"F.isWorker","since":"","deprecated":false},{"type":"property","name":"F.clusterid","signature":"F.clusterid","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart (file)","since":"","deprecated":false},{"type":"method","name":"SHELL(cmd, [callback], [cwd])","signature":"SHELL(cmd, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : /bin/bash","since":"","deprecated":false},{"type":"method","name":"F.python()","signature":"F.python(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"PYPELINE(name, [options])","signature":"PYPELINE(name, [options])","since":"","deprecated":false},{"type":"method","name":"F.pipinstall()","signature":"F.pipinstall(name, [callback])","since":"","deprecated":false},{"type":"method","name":"pypeline.send(data)","signature":"pypeline.send(data)","since":"","deprecated":false},{"type":"method","name":"pypeline.close()","signature":"pypeline.close()","since":"","deprecated":false},{"type":"method","name":"pypeline.restart()","signature":"pypeline.restart()","since":"","deprecated":false},{"type":"event","name":"pypeline.on('data')","signature":"pypeline.on('data', function(msg) {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('open')","signature":"pypeline.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('restart')","signature":"pypeline.on('restart', function() {})","since":"","deprecated":false},{"type":"property","name":"pypeline.name","signature":"pypeline.name","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvT9Ex61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Worker, thread e cluster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, le opzioni del cluster, SHELL(), F.python(), F.pipinstall() e PYPELINE().","markdown":"---\ntitle: Worker, thread e cluster\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/workers-and-threads/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Worker, thread e cluster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, le opzioni del cluster, SHELL(), F.python(), F.pipinstall() e PYPELINE().\n\nMetodi, proprietà, opzioni di avvio ed eventi per worker thread, processi forkati, pool di thread, il cluster, `SHELL()` e `PYPELINE()`. Per un'introduzione con esempi leggi la guida [Worker, thread e cluster](../../guides/workers-and-threads/).\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nAvvia un worker thread dalla cartella workers/.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del file in `workers/` senza `.js`, oppure `~` e un percorso assoluto |\n| `data` | `Object` | no |  | Dati copiati nel thread come `F.worker.data` |\n\nReturns: `Worker` Il worker thread di Node.js\n\nEsegue `workers/{name}.js` in un nuovo worker thread di Node.js. Un nome che inizia con `~` è un percorso assoluto allo script. `data` viene copiato nel thread ed è disponibile lì come `F.worker.data`. Il thread riceve `--worker` nel suo `process.argv`.\n\nIl risultato è l'oggetto `Worker` di Node.js: usa `postMessage()` per inviare un messaggio e `on('message')`, `on('error')` e `on('exit')` per ascoltare. Il framework aggiunge `kill()` ed `exit()`, che chiamano `terminate()`.\n\nExample: Avviare un thread\n```js\nvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\nthread.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tthread.kill();\n});\n\nthread.postMessage({ a: 1, b: 2 });\n```\n\n### NEWTHREAD()\n\nType: `method`\n\nDentro uno script worker: restituisce l'oggetto worker F.worker.\n\nReturns: `Object` F.worker\n\nChiamato senza nome in uno script che viene eseguito come worker, `NEWTHREAD()` crea `F.worker` (o lo restituisce se esiste), imposta la directory dell'applicazione sulla directory di lavoro corrente e inizia a passare i messaggi del genitore a `F.worker.message`. Carica il framework con `require('total5')` prima di chiamarlo.\n\nExample: workers/calc.js\n```js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tworker.send({ sum: msg.a + msg.b });\n};\n```\n\n### F.worker\n\nType: `property`\n\nL'oggetto worker di uno script eseguito come worker.\n\nReturns: `Object`\n\nCreato da `NEWTHREAD()` (o `NEWFORK()`) senza nome. Contiene i dati del genitore e i metodi per ricevere e inviare messaggi e per terminare il worker. Nell'applicazione principale è `undefined`.\n\nExample: Verificare i dati\n```js\nvar worker = NEWTHREAD();\nconsole.log(F.worker === worker); // true\nconsole.log(worker.data);\n```\n\n### F.worker.data\n\nType: `property`\n\nI dati passati a NEWTHREAD(name, data).\n\nReturns: `Object`\n\nUna copia del secondo argomento di `NEWTHREAD()` nel thread principale. È un oggetto vuoto `{}` quando non sono stati passati dati, in un fork e nei thread di un pool.\n\nExample: Leggere i dati\n```js\nvar worker = NEWTHREAD();\nvar user = worker.data.user;\n```\n\n### F.worker.is\n\nType: `property`\n\ntrue quando lo script gira come worker.\n\nReturns: `Boolean`\n\n`true` in un thread di `NEWTHREAD()`, in un fork di `NEWFORK()` e nei worker di `NEWTHREADPOOL()`: tutti ricevono l'argomento `--worker` in `process.argv`.\n\nExample: Eseguire come worker o da solo\n```js\nvar worker = NEWTHREAD();\nif (!worker.is)\n\tconsole.log('Started directly with node, not as a worker');\n```\n\n### F.worker.isfork\n\nType: `property`\n\ntrue in un processo forkato, false in un worker thread.\n\nReturns: `Boolean`\n\n`true` quando il worker è un processo di `NEWFORK()` (i messaggi passano da `process.send()`), `false` in un worker thread.\n\nExample: Thread o processo\n```js\nvar worker = NEWTHREAD();\nconsole.log(worker.isfork ? 'process ' + process.pid : 'thread');\n```\n\n### F.worker.message = function(msg) {}\n\nType: `delegate`\n\nRiceve i messaggi dal genitore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Il messaggio del processo padre |\n\nAssegna una funzione. Viene chiamata con ogni messaggio che il genitore invia con `postMessage()`. Il valore predefinito non fa nulla.\n\nExample: Rispondere ai messaggi\n```js\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tif (msg.type === 'ping')\n\t\tworker.send({ type: 'pong' });\n};\n```\n\n### F.worker.send(msg)\n\nType: `method`\n\nInvia un messaggio al genitore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Il messaggio; viene copiato, le funzioni non sono ammesse |\n\nInvia il messaggio al processo o al thread che ha avviato il worker. `F.worker.postMessage()` è lo stesso metodo. Il genitore lo riceve in `on('message')`.\n\nExample: Inviare un risultato\n```js\nworker.send({ id: msg.id, result: result });\n```\n\n### F.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)`. Dentro un thread termina il thread; il genitore riceve l'evento `exit` con il codice. `F.worker.kill()` e `F.worker.close()` sono lo stesso metodo.\n\nExample: Terminare dopo il lavoro\n```js\nworker.message = function(msg) {\n\twork(msg);\n\tworker.exit();\n};\n```\n\n### F.worker.setTimeout(timeout)\n\nType: `method`\n\nTermina il worker con codice 1 dopo un timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Millisecondi |\n\nAvvia un conto alla rovescia. Quando scade, il worker termina con codice di uscita `1`. Una nuova chiamata cancella il conto alla rovescia precedente e ne avvia uno nuovo, quindi chiamalo all'inizio di ogni lavoro.\n\nExample: Watchdog\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\tjob(msg, function(response) {\n\t\tworker.send(response);\n\t});\n};\n```\n\n### thread.kill()\n\nType: `method`\n\nFerma un thread avviato con NEWTHREAD().\n\nChiama `terminate()` del `Worker` di Node.js. `thread.exit()` è lo stesso metodo.\n\nExample: Fermare un thread\n```js\nvar thread = NEWTHREAD('calc');\nsetTimeout(() => thread.kill(), 5000);\n```\n\n### NEWFORK(name)\n\nType: `method` · Since: `0.0.16`\n\nEsegue uno script della cartella workers/ in un nuovo processo Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del file in `workers/` senza `.js`, oppure `~` e un percorso assoluto |\n\nReturns: `ChildProcess` Il processo creato con fork\n\nAvvia `workers/{name}.js` con `child_process.fork()`. Un nome che inizia con `~` è un percorso assoluto. Il risultato è il `ChildProcess` di Node.js; il framework aggiunge `postMessage()` (lo stesso di `send()`) e `terminate()`. I messaggi vengono serializzati in JSON.\n\nLa directory di lavoro del fork è la cartella del suo script. Il framework nel fork invia la stringa `total:init` al processo padre dopo l'avvio, quindi nel padre ignora i messaggi di tipo stringa. Chiamato senza nome dentro il fork, `NEWFORK()` restituisce `F.worker`, come fa `NEWTHREAD()` in un thread; `F.worker.data` è allora un oggetto vuoto.\n\nExample: Applicazione principale\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn;\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nExample: workers/report.js\n```js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n### fork.terminate()\n\nType: `method` · Since: `0.0.16`\n\nTermina un processo avviato con NEWFORK().\n\nInvia `SIGKILL` al processo. Il processo termina subito, senza eseguire i suoi handler di uscita.\n\nExample: Terminare un fork\n```js\nvar fork = NEWFORK('report');\nsetTimeout(() => fork.terminate(), 60000);\n```\n\n### fork.postMessage(msg)\n\nType: `method` · Since: `0.0.16`\n\nInvia un messaggio a un processo avviato con NEWFORK().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Il messaggio; viene serializzato in JSON |\n\nLo stesso metodo di `fork.send()` di Node.js, così il codice per thread e fork può essere uguale. Il fork riceve il messaggio in `F.worker.message`.\n\nExample: Inviare un job\n```js\nfork.postMessage({ id: 100, type: 'pdf' });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nAvvia un pool di worker thread o di fork 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 |  | Il numero di worker |\n| `isfork` | `Boolean` | no | `false` | Avvia i worker con `NEWFORK()` invece che come thread |\n\nReturns: `Object` Il pool\n\nAvvia subito `count` worker di `workers/{name}.js` e restituisce un pool: worker thread, o processi di `NEWFORK()` quando `isfork` è `true`. I job ricevono i worker tramite `pool.exec()`; un worker passa al job successivo solo dopo che il job attuale chiama `release()`. I job che arrivano mentre tutti i worker sono occupati aspettano in `pool.pending`. Un worker che termina viene sostituito da uno nuovo, che viene dato al prossimo job in attesa. I worker non ricevono dati (`F.worker.data` è `{}`). Il pool viene anche salvato in `F.workers[name]`.\n\nExample: Pool di quattro thread\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\nExample: Pool di fork\n```js\nvar pool = NEWTHREADPOOL('report', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nEsegue un lavoro sul prossimo worker libero del pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Solo senza `fn`: si risolve con il worker\n\nAggiunge il lavoro alla coda e lo avvia appena un worker è libero. La funzione riceve `(worker, release)`; chiama `release()` quando il lavoro è finito. Senza funzione il metodo restituisce una promise che si risolve con il worker; rilascialo con `worker.release()`.\n\nPrima che un worker inizi un lavoro, il pool rimuove tutti i suoi listener `message`, così ogni lavoro collega i propri.\n\nExample: Con una callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 1, b: 2 });\n});\n```\n\nExample: Con una promise\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 2 });\n```\n\n### worker.release()\n\nType: `method`\n\nRestituisce un worker di un pool al pool.\n\nOgni worker di un pool ha questo metodo. Segna il worker come libero e lo dà al prossimo lavoro in attesa. È la stessa funzione dell'argomento `release` di `pool.exec(fn)`.\n\nExample: Rilasciare\n```js\nvar worker = await pool.exec();\nworker.on('message', () => worker.release());\nworker.postMessage({});\n```\n\n### pool.workers\n\nType: `property`\n\nI worker del pool.\n\nReturns: `Array`\n\nUn array degli oggetti `Worker` avviati dal pool.\n\nExample: Inviare a tutti\n```js\npool.workers.forEach(w => w.postMessage({ type: 'reload' }));\n```\n\n### pool.pending\n\nType: `property`\n\nI lavori che attendono un worker libero.\n\nReturns: `Array`\n\nUn array delle funzioni passate a `pool.exec()` che non sono ancora partite. La sua lunghezza indica quanto è occupato il pool.\n\nExample: Lunghezza della coda\n```js\nconsole.log('Waiting jobs:', pool.pending.length);\n```\n\n### pool.count\n\nType: `property`\n\nIl numero di worker del pool.\n\nReturns: `Number`\n\nIl `count` passato a `NEWTHREADPOOL()`. Il pool mantiene questo numero di worker: un worker che termina viene sostituito.\n\nExample: Dimensione\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\nconsole.log(pool.count); // 4\n```\n\n### F.workers\n\nType: `property`\n\nI pool di thread dell'applicazione per nome.\n\nReturns: `Object`\n\n`NEWTHREADPOOL(name, count)` memorizza qui il pool sotto il suo nome.\n\nExample: Ottenere un pool\n```js\nvar pool = F.workers.calc;\n```\n\n### options.cluster = 4\n\nType: `config`\n\nOpzione di avvio: esegue l'applicazione in un cluster di processi.\n\nUn numero di processi, oppure `'auto'`. Impostala nelle opzioni di `Total.run()`. Il primo processo diventa il master: avvia i processi uno dopo l'altro, ognuno carica l'applicazione e ascolta sulla stessa porta. Un processo che termina viene riavviato dopo un secondo. I processi vengono eseguiti in modalità release con `options.release = true` o `options.watcher = false`; altrimenti vengono eseguiti in modalità debug e il master li riavvia tutti quando cambia un file sorgente.\n\nCon `'auto'` il master avvia un processo, interroga tutti i processi ogni 5 secondi e ne aggiunge uno quando la risposta media impiega più di 70 ms (fino a `limit`). Quando rispondono di nuovo velocemente, rimuove l'ultimo processo se ha meno di due richieste in sospeso.\n\nExample: Script di avvio\n```js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n\nTotal.run(options);\n```\n\n### options.limit = 10\n\nType: `config`\n\nOpzione di avvio: il numero massimo di processi di un cluster 'auto'.\n\nUsata solo con `cluster: 'auto'`. Senza di essa il master può aggiungere processi senza limite.\n\nExample: Cluster automatico\n```js\nrequire('total5');\n\nTotal.run({ release: true, port: 8000, cluster: 'auto', limit: 8 });\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nOpzione di avvio di un cluster: il fuso orario dei processi.\n\nIn modalità cluster il framework imposta `process.env.TZ` su questo valore prima di avviare i processi. Il valore predefinito è `'utc'`.\n\nExample: Fuso orario\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 4, tz: 'Europe/Madrid' });\n```\n\n### options.logs = 'isolated'\n\nType: `config`\n\nOpzione di avvio di un cluster: stampa sempre l'intestazione del cluster.\n\nIl master stampa l'intestazione `CLUSTER` (PID, versioni, numero di thread, modalità) quando è eseguito da solo. Quando è eseguito sotto un altro processo Node.js (con un canale IPC) l'intestazione viene saltata, a meno che `logs` sia `'isolated'`.\n\nExample: Intestazione\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 2, logs: 'isolated' });\n```\n\n### options.callback = function(forks) {}\n\nType: `delegate`\n\nOpzione di avvio di un cluster: chiamata dopo l'avvio di tutti i processi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forks` | `Array` | yes |  | I worker del cluster |\n\nViene eseguita nel master una volta avviati tutti i processi del cluster. `forks` è l'array degli oggetti `cluster.Worker`.\n\nExample: Dopo l'avvio\n```js\nrequire('total5');\n\nTotal.run({\n\trelease: true,\n\tcluster: 2,\n\tcallback: function(forks) {\n\t\tconsole.log('Started', forks.length, 'processes');\n\t}\n});\n```\n\n### F.isCluster\n\nType: `property`\n\ntrue in un processo di un cluster.\n\nReturns: `Boolean`\n\nIl framework la imposta quando il master invia le opzioni di avvio al processo. Negli altri casi è `undefined`.\n\nExample: Verificare\n```js\nif (F.isCluster)\n\tprocess.send({ type: 'clearcache' });\n```\n\n### F.isWorker\n\nType: `property`\n\ntrue quando il processo è un worker del cluster di Node.js.\n\nReturns: `Boolean`\n\nIl valore di `cluster.isWorker` di Node.js, quindi è `true` nei processi di un cluster Total.js. È `false` quando è impostata la variabile d'ambiente `PASSENGER_APP_ENV`. I processi con `F.isWorker` inviano le loro statistiche al master.\n\nExample: Verificare\n```js\nconsole.log(F.isWorker);\n```\n\n### F.clusterid\n\nType: `property`\n\nL'identificatore del processo in un cluster.\n\nReturns: `String`\n\nUna stringa come `'1'` o `'2'`, lo stesso valore di `F.id`. Fuori da un cluster è una stringa vuota. Il framework lo aggiunge ai nomi dei file temporanei e alle statistiche.\n\nExample: File per processo\n```js\nvar filename = PATH.tmp('export' + F.clusterid + '.csv');\n```\n\n### F.id\n\nType: `property`\n\nL'identificatore del processo in un cluster.\n\nReturns: `String`\n\nLo stesso valore di `F.clusterid`: una stringa con il numero del processo, oppure una stringa vuota fuori da un cluster.\n\nExample: Log\n```js\nconsole.log('Process', F.id);\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nOgni messaggio che il processo riceve tramite il suo canale 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 dal processo genitore. In un cluster un oggetto che un processo invia con `process.send()` viene passato dal master a tutti i processi pronti, compreso il mittente, e ciascuno lo riceve qui. Non usare la proprietà `TYPE` né stringhe che iniziano con `total:` nei tuoi messaggi: le usa il framework.\n\nExample: Sincronizzare le cache\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// in any process\nprocess.send({ type: 'clearcache' });\n```\n\n### restart (file)\n\nType: `command`\n\nUn file che riavvia tutti i processi di un cluster.\n\nIl master di un cluster controlla ogni 5 secondi se esiste un file chiamato `restart` nella directory dell'applicazione. Se esiste, il master lo elimina e riavvia i processi uno alla volta, a due secondi di distanza. Un secondo riavvio entro 30 secondi viene ignorato.\n\nExample: Riavviare dalla shell\n```bash\n$ touch restart\n```\n\n### SHELL(cmd, [callback], [cwd])\n\nType: `method`\n\nEsegue un comando shell.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cmd` | `String` | yes |  | Il comando |\n| `callback` | `Function` | no |  | `function(err, stdout)`; oppure la directory di lavoro come stringa |\n| `cwd` | `String` | no | `the application root` | La directory di lavoro |\n\nReturns: `Promise` Solo senza callback: si risolve con lo standard output\n\nEsegue il comando con `child_process.exec()` nella shell di sistema. Con una callback chiama `callback(err, stdout)`; senza, restituisce una promise che si risolve con lo standard output o viene rifiutata con l'errore. Una stringa come secondo argomento è la directory di lavoro. La directory predefinita è la radice dell'applicazione. La chiave di configurazione `$shell` imposta la shell da usare. L'output può arrivare fino a 100 MB (`maxBuffer`); un output più grande termina con un errore.\n\nExample: Callback\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n```\n\nExample: Promise e directory\n```js\nvar list = await SHELL('ls -1', PATH.public());\n```\n\n### $shell : /bin/bash\n\nType: `config`\n\nLa shell usata da SHELL().\n\nIl percorso della shell per `SHELL()`. Non impostato per impostazione predefinita, il che usa la shell predefinita di Node.js (`/bin/sh`, o `cmd.exe` su Windows).\n\nExample: config\n```text\n$shell : /bin/bash\n```\n\n### F.python(filename, [callback])\n\nType: `method`\n\nEsegue uno script Python e restituisce il suo output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il percorso assoluto del file `.py`. |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)`. |\n\nReturns: `Promise` Solo senza callback: si risolve con l'output standard.\n\nEsegue `$python <filename>` con `child_process.exec()` nella cartella dello script. Con una callback chiama `callback(err, stdout, stderr)`; senza restituisce una promise che si risolve con l'output standard. Uno script che termina con un exit code diverso da `0` dà un errore (`err.code` è l'exit code) e la promise viene rifiutata. `$python` è la chiave di configurazione con il comando Python (`python3` per impostazione predefinita).\n\nExample: Promise\n```js\nvar output = await F.python(PATH.root('scripts/report.py'));\n```\n\nExample: Callback\n```js\nF.python(PATH.root('scripts/report.py'), function(err, stdout, stderr) {\n\tif (err)\n\t\tconsole.log(stderr);\n\telse\n\t\tconsole.log(stdout);\n});\n```\n\n### PYPELINE(name, [options])\n\nType: `method`\n\nAvvia uno script Python e scambia messaggi con esso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del file in `pypelines/` senza `.py`, `~` e un percorso assoluto, oppure codice inline |\n| `options` | `Object` | no |  | `{ autorestart, type, socket }` |\n\nReturns: `Pypeline` Un oggetto con eventi e i metodi descritti sotto\n\nEsegue `python3` con `pypelines/{name}.py` (o un percorso assoluto che inizia con `~`) nella cartella dello script. Un `name` che contiene un a capo, `;` o un apice è codice inline, eseguito con `python3 -c` nella radice dell'applicazione.\n\nIl framework ascolta su un socket Unix in `tmp/` e passa il suo percorso allo script come `sys.argv[1]`. Ogni messaggio in entrambe le direzioni è una lunghezza di 4 byte big-endian seguita dal payload. Lo standard output e lo standard error dello script vanno nella console dell'applicazione. Quando l'applicazione termina, tutti i processi Python vengono uccisi.\n\nLe opzioni sono `autorestart` (predefinito `true`: riavvia lo script quando termina), `type` (`'json'` per impostazione predefinita, `'text'` per le stringhe, o qualsiasi altro valore per buffer grezzi) e `socket` (`false` esegue lo script senza socket, per script che devono solo essere eseguiti).\n\nExample: Avviare una pipeline\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text);\n});\n\npy.send({ text: 'hello' });\n```\n\nExample: Messaggi di testo\n```js\nvar py = PYPELINE('tokenizer', { type: 'text' });\n```\n\n### F.pipinstall(name, [callback])\n\nType: `method`\n\nInstalla un pacchetto Python con pip.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il pacchetto, eventualmente con una versione (`requests==2.32.3`). |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Solo senza callback.\n\nEsegue `$python -m pip install <name>` nella directory dell'applicazione. Con una callback chiama `callback(err)`; senza restituisce una promise. Quando pip fallisce, l'errore è l'output di errore di pip (una stringa), oppure l'errore del processo.\n\nExample: Installare prima dell'uso\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/download.py'));\n```\n\n### pypeline.send(data)\n\nType: `method`\n\nInvia un messaggio allo script Python.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|Buffer|String` | yes |  | Il messaggio |\n\nReturns: `Pypeline` La pipeline (solo quando lo script è connesso)\n\nUn oggetto viene inviato come JSON, un `Buffer` così com'è e gli altri valori come testo, ciascuno preceduto da una lunghezza di 4 byte. I messaggi inviati prima che lo script si connetta restano in attesa e vengono inviati quando si connette.\n\nExample: Inviare\n```js\npy.send({ text: 'hello' });\n```\n\n### pypeline.close()\n\nType: `method`\n\nFerma definitivamente lo script Python.\n\nReturns: `Pypeline`\n\nDisattiva `autorestart`, chiude il server socket e uccide il processo Python.\n\nExample: Fermare\n```js\npy.close();\n```\n\n### pypeline.restart()\n\nType: `method`\n\nUccide il processo Python e lo avvia di nuovo.\n\nUccide il processo corrente e avvia di nuovo lo script. `pypeline.run()` è lo stesso metodo.\n\nExample: Ricaricare\n```js\npy.restart();\n```\n\n### pypeline.on('data', function(msg) {})\n\nType: `event`\n\nUn messaggio dallo script Python.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object|String|Buffer` | yes |  | Il messaggio |\n\nEmesso per ogni messaggio completo. Con `type: 'json'` il messaggio viene analizzato, con `'text'` è una stringa, altrimenti un `Buffer`.\n\nExample: Leggere\n```js\npy.on('data', function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### pypeline.on('open', function() {})\n\nType: `event`\n\nLo script Python si è connesso al socket.\n\nEmesso ogni volta che lo script si connette, dopo l'invio dei messaggi in attesa.\n\nExample: Connesso\n```js\npy.on('open', function() {\n\tconsole.log('Python is ready');\n});\n```\n\n### pypeline.on('restart', function() {})\n\nType: `event`\n\nLo script Python è terminato ed è stato riavviato.\n\nEmesso con `autorestart: true` dopo che il framework ha riavviato lo script.\n\nExample: Registrare i riavvii\n```js\npy.on('restart', function() {\n\tconsole.log('Python restarted');\n});\n```\n\n### pypeline.name\n\nType: `property`\n\nIl nome della pipeline.\n\nReturns: `String`\n\nIl `name` passato a `PYPELINE()`, oppure `Inline Python Code` per il codice inline.\n\nExample: Log\n```js\nconsole.log(py.name);\n```\n","entries":[{"type":"method","name":"NEWTHREAD(name, [data])","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD()","since":"","deprecated":false},{"type":"property","name":"F.worker","signature":"F.worker","since":"","deprecated":false},{"type":"property","name":"F.worker.data","signature":"F.worker.data","since":"","deprecated":false},{"type":"property","name":"F.worker.is","signature":"F.worker.is","since":"","deprecated":false},{"type":"property","name":"F.worker.isfork","signature":"F.worker.isfork","since":"","deprecated":false},{"type":"delegate","name":"F.worker.message","signature":"F.worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"F.worker.send(msg)","signature":"F.worker.send(msg)","since":"","deprecated":false},{"type":"method","name":"F.worker.exit([code])","signature":"F.worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"F.worker.setTimeout(timeout)","signature":"F.worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"thread.kill()","signature":"thread.kill()","since":"","deprecated":false},{"type":"method","name":"NEWFORK(name)","signature":"NEWFORK(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.terminate()","signature":"fork.terminate()","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.postMessage(msg)","signature":"fork.postMessage(msg)","since":"0.0.16","deprecated":false},{"type":"method","name":"NEWTHREADPOOL(name, count)","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec([fn])","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"method","name":"worker.release()","signature":"worker.release()","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"pool.pending","signature":"pool.pending","since":"","deprecated":false},{"type":"property","name":"pool.count","signature":"pool.count","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"config","name":"cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"limit","signature":"options.limit = 10","since":"","deprecated":false},{"type":"config","name":"tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"delegate","name":"callback","signature":"options.callback = function(forks) {}","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.isWorker","signature":"F.isWorker","since":"","deprecated":false},{"type":"property","name":"F.clusterid","signature":"F.clusterid","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart (file)","since":"","deprecated":false},{"type":"method","name":"SHELL(cmd, [callback], [cwd])","signature":"SHELL(cmd, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : /bin/bash","since":"","deprecated":false},{"type":"method","name":"F.python()","signature":"F.python(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"PYPELINE(name, [options])","signature":"PYPELINE(name, [options])","since":"","deprecated":false},{"type":"method","name":"F.pipinstall()","signature":"F.pipinstall(name, [callback])","since":"","deprecated":false},{"type":"method","name":"pypeline.send(data)","signature":"pypeline.send(data)","since":"","deprecated":false},{"type":"method","name":"pypeline.close()","signature":"pypeline.close()","since":"","deprecated":false},{"type":"method","name":"pypeline.restart()","signature":"pypeline.restart()","since":"","deprecated":false},{"type":"event","name":"pypeline.on('data')","signature":"pypeline.on('data', function(msg) {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('open')","signature":"pypeline.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('restart')","signature":"pypeline.on('restart', function() {})","since":"","deprecated":false},{"type":"property","name":"pypeline.name","signature":"pypeline.name","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwvT9Ex61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/workers-and-threads/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Workery, vlákna a klaster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, voľby clustera, SHELL(), F.python(), F.pipinstall() a PYPELINE().","markdown":"---\ntitle: \"Workery, vlákna a klaster\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/workers-and-threads/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Workery, vlákna a klaster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, voľby clustera, SHELL(), F.python(), F.pipinstall() a PYPELINE().\n\nMetódy, vlastnosti, štartovacie voľby a udalosti pre worker vlákna, forknuté procesy, pooly vlákien, cluster, `SHELL()` a `PYPELINE()`. Úvod s príkladmi nájdeš v návode [Workery, vlákna a cluster](../../guides/workers-and-threads/).\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nSpustí worker vlákno z priečinka workers/.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru vo `workers/` bez `.js` alebo `~` a absolútna cesta |\n| `data` | `Object` | no |  | Dáta skopírované do vlákna ako `F.worker.data` |\n\nReturns: `Worker` Worker vlákno Node.js\n\nSpustí `workers/{name}.js` v novom worker vlákne Node.js. Názov, ktorý začína `~`, je absolútna cesta ku skriptu. `data` sa skopírujú do vlákna a sú tam dostupné ako `F.worker.data`. Vlákno dostane v `process.argv` hodnotu `--worker`.\n\nVýsledkom je objekt Node.js `Worker`: na odoslanie správy použi `postMessage()` a na počúvanie `on('message')`, `on('error')` a `on('exit')`. Framework pridáva `kill()` a `exit()`, ktoré volajú `terminate()`.\n\nExample: Spustenie vlákna\n```js\nvar thread = NEWTHREAD('calc', { user: 'Peter' });\n\nthread.on('message', function(msg) {\n\tconsole.log(msg.sum);\n\tthread.kill();\n});\n\nthread.postMessage({ a: 1, b: 2 });\n```\n\n### NEWTHREAD()\n\nType: `method`\n\nV skripte workera: vráti objekt workera F.worker.\n\nReturns: `Object` F.worker\n\nKeď sa `NEWTHREAD()` zavolá bez názvu v skripte, ktorý beží ako worker, vytvorí `F.worker` (alebo ho vráti, ak existuje), nastaví adresár aplikácie na aktuálny pracovný adresár a začne odovzdávať správy od rodiča do `F.worker.message`. Pred volaním načítaj framework cez `require('total5')`.\n\nExample: workers/calc.js\n```js\nrequire('total5');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tworker.send({ sum: msg.a + msg.b });\n};\n```\n\n### F.worker\n\nType: `property`\n\nObjekt workera v skripte, ktorý beží ako worker.\n\nReturns: `Object`\n\nVytvorí ho `NEWTHREAD()` (alebo `NEWFORK()`) bez názvu. Obsahuje dáta od rodiča a metódy na prijímanie a odosielanie správ a na ukončenie workera. V hlavnej aplikácii je `undefined`.\n\nExample: Kontrola dát\n```js\nvar worker = NEWTHREAD();\nconsole.log(F.worker === worker); // true\nconsole.log(worker.data);\n```\n\n### F.worker.data\n\nType: `property`\n\nDáta odovzdané do NEWTHREAD(name, data).\n\nReturns: `Object`\n\nKópia druhého argumentu `NEWTHREAD()` z hlavného vlákna. Je to prázdny objekt `{}`, keď sa neodovzdali žiadne dáta, vo forku a vo vláknach poolu.\n\nExample: Čítanie dát\n```js\nvar worker = NEWTHREAD();\nvar user = worker.data.user;\n```\n\n### F.worker.is\n\nType: `property`\n\ntrue, keď skript beží ako worker.\n\nReturns: `Boolean`\n\n`true` vo vlákne z `NEWTHREAD()`, vo forku z `NEWFORK()` a vo workeroch z `NEWTHREADPOOL()`: všetky dostanú argument `--worker` v `process.argv`.\n\nExample: Spustenie ako worker alebo samostatne\n```js\nvar worker = NEWTHREAD();\nif (!worker.is)\n\tconsole.log('Started directly with node, not as a worker');\n```\n\n### F.worker.isfork\n\nType: `property`\n\ntrue vo forknutom procese, false vo worker vlákne.\n\nReturns: `Boolean`\n\n`true`, keď je worker procesom z `NEWFORK()` (správy idú cez `process.send()`), `false` vo worker vlákne.\n\nExample: Vlákno alebo proces\n```js\nvar worker = NEWTHREAD();\nconsole.log(worker.isfork ? 'process ' + process.pid : 'thread');\n```\n\n### F.worker.message = function(msg) {}\n\nType: `delegate`\n\nPrijíma správy od rodiča.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Správa od rodiča |\n\nPriraď funkciu. Zavolá sa s každou správou, ktorú rodič pošle cez `postMessage()`. Predvolená nerobí nič.\n\nExample: Odpovedanie na správy\n```js\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\tif (msg.type === 'ping')\n\t\tworker.send({ type: 'pong' });\n};\n```\n\n### F.worker.send(msg)\n\nType: `method`\n\nPošle správu rodičovi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Správa; skopíruje sa, funkcie nie sú povolené |\n\nPošle správu procesu alebo vláknu, ktoré workera spustilo. `F.worker.postMessage()` je tá istá metóda. Rodič ju dostane v `on('message')`.\n\nExample: Odoslanie výsledku\n```js\nworker.send({ id: msg.id, result: result });\n```\n\n### F.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\nZavolá `process.exit(code)`. Vo vlákne ukončí vlákno; rodič dostane udalosť `exit` s kódom. `F.worker.kill()` a `F.worker.close()` sú tá istá metóda.\n\nExample: Ukončenie po úlohe\n```js\nworker.message = function(msg) {\n\twork(msg);\n\tworker.exit();\n};\n```\n\n### F.worker.setTimeout(timeout)\n\nType: `method`\n\nUkončí workera s kódom 1 po časovom limite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Milisekundy |\n\nSpustí odpočet. Keď vyprší, worker sa ukončí s výstupným kódom `1`. Nové volanie zruší predchádzajúci odpočet a spustí nový, preto ho volaj na začiatku každej úlohy.\n\nExample: Watchdog\n```js\nworker.message = function(msg) {\n\tworker.setTimeout(10000);\n\tjob(msg, function(response) {\n\t\tworker.send(response);\n\t});\n};\n```\n\n### thread.kill()\n\nType: `method`\n\nZastaví vlákno spustené cez NEWTHREAD().\n\nZavolá `terminate()` objektu Node.js `Worker`. `thread.exit()` je tá istá metóda.\n\nExample: Zastavenie vlákna\n```js\nvar thread = NEWTHREAD('calc');\nsetTimeout(() => thread.kill(), 5000);\n```\n\n### NEWFORK(name)\n\nType: `method` · Since: `0.0.16`\n\nSpustí skript z priečinka workers/ v novom procese Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru vo `workers/` bez `.js` alebo `~` a absolútna cesta |\n\nReturns: `ChildProcess` Forknutý proces\n\nSpustí `workers/{name}.js` cez `child_process.fork()`. Názov, ktorý začína `~`, je absolútna cesta. Výsledkom je Node.js `ChildProcess`; framework pridáva `postMessage()` (to isté ako `send()`) a `terminate()`. Správy sa serializujú ako JSON.\n\nPracovný adresár forku je priečinok jeho skriptu. Framework vo forku po štarte pošle rodičovi reťazec `total:init`, preto v rodičovi reťazcové správy preskakuj. Zavolané bez názvu vnútri forku vráti `NEWFORK()` objekt `F.worker`, rovnako ako `NEWTHREAD()` vo vlákne; `F.worker.data` je potom prázdny objekt.\n\nExample: Hlavná aplikácia\n```js\nvar fork = NEWFORK('report');\n\nfork.on('message', function(msg) {\n\tif (typeof(msg) === 'string')\n\t\treturn;\n\tconsole.log(msg);\n\tfork.terminate();\n});\n\nfork.postMessage({ id: 100 });\n```\n\nExample: workers/report.js\n```js\nrequire('total5');\n\nvar worker = NEWFORK();\n\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, done: true });\n};\n```\n\n### fork.terminate()\n\nType: `method` · Since: `0.0.16`\n\nZabije proces spustený cez NEWFORK().\n\nPošle procesu `SIGKILL`. Proces okamžite skončí bez spustenia svojich exit handlerov.\n\nExample: Zabitie forku\n```js\nvar fork = NEWFORK('report');\nsetTimeout(() => fork.terminate(), 60000);\n```\n\n### fork.postMessage(msg)\n\nType: `method` · Since: `0.0.16`\n\nPošle správu procesu spustenému cez NEWFORK().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Správa; serializuje sa ako JSON |\n\nTá istá metóda ako `fork.send()` z Node.js, takže kód pre vlákna a forky môže vyzerať rovnako. Fork dostane správu v `F.worker.message`.\n\nExample: Odoslanie úlohy\n```js\nfork.postMessage({ id: 100, type: 'pdf' });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nSpustí pool worker vlákien alebo forkov a požičiava ich úlohám.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru vo `workers/` bez `.js` |\n| `count` | `Number` | yes |  | Počet workerov |\n| `isfork` | `Boolean` | no | `false` | Spustiť workery cez `NEWFORK()` namiesto vlákien |\n\nReturns: `Object` Pool\n\nSpustí naraz `count` workerov z `workers/{name}.js` a vráti pool: worker vlákna, alebo procesy z `NEWFORK()`, keď je `isfork` `true`. Úlohy dostávajú workery cez `pool.exec()`; worker prejde na ďalšiu úlohu, až keď aktuálna úloha zavolá `release()`. Úlohy, ktoré prídu, kým sú všetky workery obsadené, čakajú v `pool.pending`. Worker, ktorý skončí, sa nahradí novým a ten dostane ďalšia čakajúca úloha. Workery nedostanú žiadne dáta (`F.worker.data` je `{}`). Pool sa uloží aj do `F.workers[name]`.\n\nExample: Pool štyroch vlákien\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\n\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\tconsole.log(msg.sum);\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 5, b: 5 });\n});\n```\n\nExample: Pool forkov\n```js\nvar pool = NEWTHREADPOOL('report', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nSpustí úlohu na najbližšom voľnom workeri poolu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Iba bez `fn`: vyrieši sa s workerom\n\nPridá úlohu do fronty a spustí ju, hneď ako je nejaký worker voľný. Funkcia dostane `(worker, release)`; po dokončení úlohy zavolaj `release()`. Bez funkcie metóda vráti promise, ktorý sa vyrieši s workerom; uvoľni ho cez `worker.release()`.\n\nPredtým ako worker začne úlohu, pool odstráni všetky jeho listenery `message`, takže každá úloha si pripojí vlastný.\n\nExample: S callbackom\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t});\n\tworker.postMessage({ a: 1, b: 2 });\n});\n```\n\nExample: S promise\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n});\nworker.postMessage({ a: 1, b: 2 });\n```\n\n### worker.release()\n\nType: `method`\n\nVráti workera poolu späť do poolu.\n\nTúto metódu má každý worker poolu. Označí workera ako voľného a pridelí ho ďalšej čakajúcej úlohe. Je to tá istá funkcia ako argument `release` v `pool.exec(fn)`.\n\nExample: Uvoľnenie\n```js\nvar worker = await pool.exec();\nworker.on('message', () => worker.release());\nworker.postMessage({});\n```\n\n### pool.workers\n\nType: `property`\n\nWorkeri poolu.\n\nReturns: `Array`\n\nPole objektov `Worker`, ktoré pool spustil.\n\nExample: Odoslanie všetkým\n```js\npool.workers.forEach(w => w.postMessage({ type: 'reload' }));\n```\n\n### pool.pending\n\nType: `property`\n\nÚlohy, ktoré čakajú na voľného workera.\n\nReturns: `Array`\n\nPole funkcií odovzdaných do `pool.exec()`, ktoré sa ešte nespustili. Jeho dĺžka ukazuje, ako je pool vyťažený.\n\nExample: Dĺžka fronty\n```js\nconsole.log('Waiting jobs:', pool.pending.length);\n```\n\n### pool.count\n\nType: `property`\n\nPočet workerov poolu.\n\nReturns: `Number`\n\n`count` zadaný do `NEWTHREADPOOL()`. Pool udržiava tento počet workerov: worker, ktorý skončí, sa nahradí.\n\nExample: Veľkosť\n```js\nvar pool = NEWTHREADPOOL('calc', 4);\nconsole.log(pool.count); // 4\n```\n\n### F.workers\n\nType: `property`\n\nPooly vlákien aplikácie podľa názvu.\n\nReturns: `Object`\n\n`NEWTHREADPOOL(name, count)` sem uloží pool pod jeho názvom.\n\nExample: Získanie poolu\n```js\nvar pool = F.workers.calc;\n```\n\n### options.cluster = 4\n\nType: `config`\n\nŠtartovacia voľba: spustí aplikáciu v clusteri procesov.\n\nPočet procesov alebo `'auto'`. Nastav ju vo voľbách `Total.run()`. Prvý proces sa stane masterom: spúšťa procesy jeden po druhom, každý z nich načíta aplikáciu a počúva na tom istom porte. Proces, ktorý sa ukončí, sa po jednej sekunde spustí znova. Procesy bežia v režime release s `options.release = true` alebo `options.watcher = false`; inak bežia v režime debug a master ich všetky reštartuje, keď sa zmení zdrojový súbor.\n\nPri `'auto'` master spustí jeden proces, každých 5 sekúnd pingne všetky procesy a pridá jeden, keď priemerná odpoveď trvá dlhšie ako 70 ms (až po `limit`). Keď opäť odpovedajú rýchlo, odstráni posledný proces, ak má menej ako dve čakajúce požiadavky.\n\nExample: Štartovací skript\n```js\nrequire('total5');\n\nconst options = {};\noptions.port = 8000;\noptions.release = true;\noptions.cluster = 4;\n\nTotal.run(options);\n```\n\n### options.limit = 10\n\nType: `config`\n\nŠtartovacia voľba: maximálny počet procesov clustera 'auto'.\n\nPoužíva sa iba s `cluster: 'auto'`. Bez nej môže master pridávať procesy bez obmedzenia.\n\nExample: Automatický cluster\n```js\nrequire('total5');\n\nTotal.run({ release: true, port: 8000, cluster: 'auto', limit: 8 });\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nŠtartovacia voľba clustera: časové pásmo procesov.\n\nV režime cluster framework nastaví `process.env.TZ` na túto hodnotu predtým, ako spustí procesy. Predvolená hodnota je `'utc'`.\n\nExample: Časové pásmo\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 4, tz: 'Europe/Madrid' });\n```\n\n### options.logs = 'isolated'\n\nType: `config`\n\nŠtartovacia voľba clustera: vždy vypísať hlavičku clustera.\n\nMaster vypíše hlavičku `CLUSTER` (PID, verzie, počet vlákien, režim), keď beží samostatne. Keď beží pod iným procesom Node.js (s IPC kanálom), hlavička sa vynechá, pokiaľ `logs` nie je `'isolated'`.\n\nExample: Hlavička\n```js\nrequire('total5');\n\nTotal.run({ release: true, cluster: 2, logs: 'isolated' });\n```\n\n### options.callback = function(forks) {}\n\nType: `delegate`\n\nŠtartovacia voľba clustera: volá sa po spustení všetkých procesov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forks` | `Array` | yes |  | Workeri clustera |\n\nSpustí sa v mastri, keď sa spustí každý proces clustera. `forks` je pole objektov `cluster.Worker`.\n\nExample: Po štarte\n```js\nrequire('total5');\n\nTotal.run({\n\trelease: true,\n\tcluster: 2,\n\tcallback: function(forks) {\n\t\tconsole.log('Started', forks.length, 'processes');\n\t}\n});\n```\n\n### F.isCluster\n\nType: `property`\n\ntrue v procese clustera.\n\nReturns: `Boolean`\n\nFramework ju nastaví, keď master pošle procesu štartovacie voľby. V ostatných prípadoch je `undefined`.\n\nExample: Kontrola\n```js\nif (F.isCluster)\n\tprocess.send({ type: 'clearcache' });\n```\n\n### F.isWorker\n\nType: `property`\n\ntrue, keď je proces workerom clustera Node.js.\n\nReturns: `Boolean`\n\nHodnota `cluster.isWorker` z Node.js, takže je `true` v procesoch Total.js clustera. Je `false`, keď je nastavená premenná prostredia `PASSENGER_APP_ENV`. Procesy s `F.isWorker` posielajú svoje štatistiky mastrovi.\n\nExample: Kontrola\n```js\nconsole.log(F.isWorker);\n```\n\n### F.clusterid\n\nType: `property`\n\nIdentifikátor procesu v clusteri.\n\nReturns: `String`\n\nReťazec ako `'1'` alebo `'2'`, rovnaká hodnota ako `F.id`. Mimo clustera je to prázdny reťazec. Framework ho pridáva do názvov dočasných súborov a do štatistík.\n\nExample: Súbor pre každý proces\n```js\nvar filename = PATH.tmp('export' + F.clusterid + '.csv');\n```\n\n### F.id\n\nType: `property`\n\nIdentifikátor procesu v clusteri.\n\nReturns: `String`\n\nRovnaká hodnota ako `F.clusterid`: reťazec s číslom procesu alebo prázdny reťazec mimo clustera.\n\nExample: Log\n```js\nconsole.log('Process', F.id);\n```\n\n### ON('$message', function(msg, handle) {})\n\nType: `event`\n\nKaždá správa, ktorú proces dostane cez svoj IPC kanál.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Správa |\n| `handle` | `Object` | yes |  | Handle odoslaný so správou, ak existuje |\n\nEmituje sa pre každú správu od rodičovského procesu. V clusteri objekt, ktorý jeden proces pošle cez `process.send()`, master odovzdá všetkým pripraveným procesom vrátane odosielateľa a každý z nich ho dostane tu. V správach nepoužívaj vlastnosť `TYPE` ani reťazce, ktoré začínajú `total:`: používa ich framework.\n\nExample: Synchronizácia cache\n```js\nON('$message', function(msg) {\n\tif (msg && msg.type === 'clearcache')\n\t\tMAIN.products = null;\n});\n\n// in any process\nprocess.send({ type: 'clearcache' });\n```\n\n### restart (file)\n\nType: `command`\n\nSúbor, ktorý reštartuje všetky procesy clustera.\n\nMaster clustera každých 5 sekúnd kontroluje, či v adresári aplikácie existuje súbor s názvom `restart`. Ak áno, master ho vymaže a reštartuje procesy jeden po druhom s odstupom dvoch sekúnd. Druhý reštart do 30 sekúnd sa ignoruje.\n\nExample: Reštart zo shellu\n```bash\n$ touch restart\n```\n\n### SHELL(cmd, [callback], [cwd])\n\nType: `method`\n\nSpustí príkaz shellu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cmd` | `String` | yes |  | Príkaz |\n| `callback` | `Function` | no |  | `function(err, stdout)`; alebo pracovný adresár ako reťazec |\n| `cwd` | `String` | no | `the application root` | Pracovný adresár |\n\nReturns: `Promise` Iba bez callbacku: vyrieši sa so štandardným výstupom\n\nSpustí príkaz cez `child_process.exec()` v systémovom shelli. S callbackom zavolá `callback(err, stdout)`; bez neho vráti promise, ktorý sa vyrieši so štandardným výstupom alebo sa zamietne s chybou. Reťazec ako druhý argument je pracovný adresár. Predvolený adresár je koreň aplikácie. Konfiguračný kľúč `$shell` nastaví shell, ktorý sa použije. Výstup môže mať až 100 MB (`maxBuffer`); väčší výstup skončí chybou.\n\nExample: Callback\n```js\nSHELL('git rev-parse HEAD', function(err, stdout) {\n\tconsole.log(stdout.trim());\n});\n```\n\nExample: Promise a adresár\n```js\nvar list = await SHELL('ls -1', PATH.public());\n```\n\n### $shell : /bin/bash\n\nType: `config`\n\nShell, ktorý používa SHELL().\n\nCesta k shellu pre `SHELL()`. Predvolene nie je nastavená, čo použije predvolený shell Node.js (`/bin/sh` alebo `cmd.exe` vo Windows).\n\nExample: config\n```text\n$shell : /bin/bash\n```\n\n### F.python(filename, [callback])\n\nType: `method`\n\nSpustí Python skript a vráti jeho výstup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Absolútna cesta k súboru `.py`. |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)`. |\n\nReturns: `Promise` Iba bez callbacku: vyrieši sa so štandardným výstupom.\n\nSpustí `$python <filename>` cez `child_process.exec()` v priečinku skriptu. S callbackom zavolá `callback(err, stdout, stderr)`; bez neho vráti promise, ktorý sa vyrieši so štandardným výstupom. Skript, ktorý skončí s exit kódom iným ako `0`, vráti chybu (`err.code` je exit kód) a promise sa zamietne. `$python` je konfiguračný kľúč s príkazom Pythonu (predvolene `python3`).\n\nExample: Promise\n```js\nvar output = await F.python(PATH.root('scripts/report.py'));\n```\n\nExample: Callback\n```js\nF.python(PATH.root('scripts/report.py'), function(err, stdout, stderr) {\n\tif (err)\n\t\tconsole.log(stderr);\n\telse\n\t\tconsole.log(stdout);\n});\n```\n\n### PYPELINE(name, [options])\n\nType: `method`\n\nSpustí Python skript a vymieňa si s ním správy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru v `pypelines/` bez `.py`, `~` a absolútna cesta alebo inline kód |\n| `options` | `Object` | no |  | `{ autorestart, type, socket }` |\n\nReturns: `Pypeline` Objekt s udalosťami a nižšie uvedenými metódami\n\nSpustí `python3` s `pypelines/{name}.py` (alebo s absolútnou cestou, ktorá začína `~`) v priečinku skriptu. `name`, ktorý obsahuje nový riadok, `;` alebo úvodzovky, je inline kód spustený cez `python3 -c` v koreni aplikácie.\n\nFramework počúva na Unix sockete v `tmp/` a jeho cestu odovzdá skriptu ako `sys.argv[1]`. Každá správa v oboch smeroch je 4-bajtová big-endian dĺžka, za ktorou nasleduje payload. Štandardný výstup a chybový výstup skriptu idú do konzoly aplikácie. Keď sa aplikácia ukončí, všetky Python procesy sa zabijú.\n\nVoľby sú `autorestart` (predvolene `true`: spustiť skript znova, keď skončí), `type` (predvolene `'json'`, `'text'` pre reťazce alebo akákoľvek iná hodnota pre surové buffery) a `socket` (`false` spustí skript bez socketu, pre skripty, ktoré sa iba spúšťajú).\n\nExample: Spustenie pipeline\n```js\nvar py = PYPELINE('upper');\n\npy.on('data', function(msg) {\n\tconsole.log(msg.text);\n});\n\npy.send({ text: 'hello' });\n```\n\nExample: Textové správy\n```js\nvar py = PYPELINE('tokenizer', { type: 'text' });\n```\n\n### F.pipinstall(name, [callback])\n\nType: `method`\n\nNainštaluje Python balík cez pip.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Balík, voliteľne s verziou (`requests==2.32.3`). |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Promise` Iba bez callbacku.\n\nSpustí `$python -m pip install <name>` v adresári aplikácie. S callbackom zavolá `callback(err)`; bez neho vráti promise. Keď pip zlyhá, chybou je chybový výstup pipu (reťazec) alebo chyba procesu.\n\nExample: Inštalácia pred použitím\n```js\nawait F.pipinstall('requests');\nvar output = await F.python(PATH.root('scripts/download.py'));\n```\n\n### pypeline.send(data)\n\nType: `method`\n\nPošle správu Python skriptu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|Buffer|String` | yes |  | Správa |\n\nReturns: `Pypeline` Pipeline (iba keď je skript pripojený)\n\nObjekt sa pošle ako JSON, `Buffer` bez zmeny a ostatné hodnoty ako text, každá so 4-bajtovou dĺžkou na začiatku. Správy odoslané pred pripojením skriptu čakajú a pošlú sa, keď sa pripojí.\n\nExample: Odoslanie\n```js\npy.send({ text: 'hello' });\n```\n\n### pypeline.close()\n\nType: `method`\n\nNatrvalo zastaví Python skript.\n\nReturns: `Pypeline`\n\nVypne `autorestart`, zatvorí socket server a zabije Python proces.\n\nExample: Zastavenie\n```js\npy.close();\n```\n\n### pypeline.restart()\n\nType: `method`\n\nZabije Python proces a spustí ho znova.\n\nZabije aktuálny proces a znova spustí skript. `pypeline.run()` je tá istá metóda.\n\nExample: Znovunačítanie\n```js\npy.restart();\n```\n\n### pypeline.on('data', function(msg) {})\n\nType: `event`\n\nSpráva od Python skriptu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object|String|Buffer` | yes |  | Správa |\n\nEmituje sa pre každú úplnú správu. S `type: 'json'` sa správa sparsuje, s `'text'` je to reťazec, inak `Buffer`.\n\nExample: Čítanie\n```js\npy.on('data', function(msg) {\n\tconsole.log(msg);\n});\n```\n\n### pypeline.on('open', function() {})\n\nType: `event`\n\nPython skript sa pripojil k socketu.\n\nEmituje sa pri každom pripojení skriptu, po odoslaní čakajúcich správ.\n\nExample: Pripojené\n```js\npy.on('open', function() {\n\tconsole.log('Python is ready');\n});\n```\n\n### pypeline.on('restart', function() {})\n\nType: `event`\n\nPython skript skončil a bol znova spustený.\n\nEmituje sa pri `autorestart: true` po tom, čo framework znova spustil skript.\n\nExample: Logovanie reštartov\n```js\npy.on('restart', function() {\n\tconsole.log('Python restarted');\n});\n```\n\n### pypeline.name\n\nType: `property`\n\nNázov pipeline.\n\nReturns: `String`\n\n`name` odovzdaný do `PYPELINE()` alebo `Inline Python Code` pre inline kód.\n\nExample: Log\n```js\nconsole.log(py.name);\n```\n","entries":[{"type":"method","name":"NEWTHREAD(name, [data])","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD()","since":"","deprecated":false},{"type":"property","name":"F.worker","signature":"F.worker","since":"","deprecated":false},{"type":"property","name":"F.worker.data","signature":"F.worker.data","since":"","deprecated":false},{"type":"property","name":"F.worker.is","signature":"F.worker.is","since":"","deprecated":false},{"type":"property","name":"F.worker.isfork","signature":"F.worker.isfork","since":"","deprecated":false},{"type":"delegate","name":"F.worker.message","signature":"F.worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"F.worker.send(msg)","signature":"F.worker.send(msg)","since":"","deprecated":false},{"type":"method","name":"F.worker.exit([code])","signature":"F.worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"F.worker.setTimeout(timeout)","signature":"F.worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"thread.kill()","signature":"thread.kill()","since":"","deprecated":false},{"type":"method","name":"NEWFORK(name)","signature":"NEWFORK(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.terminate()","signature":"fork.terminate()","since":"0.0.16","deprecated":false},{"type":"method","name":"fork.postMessage(msg)","signature":"fork.postMessage(msg)","since":"0.0.16","deprecated":false},{"type":"method","name":"NEWTHREADPOOL(name, count)","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec([fn])","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"method","name":"worker.release()","signature":"worker.release()","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"pool.pending","signature":"pool.pending","since":"","deprecated":false},{"type":"property","name":"pool.count","signature":"pool.count","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"config","name":"cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"limit","signature":"options.limit = 10","since":"","deprecated":false},{"type":"config","name":"tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"delegate","name":"callback","signature":"options.callback = function(forks) {}","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.isWorker","signature":"F.isWorker","since":"","deprecated":false},{"type":"property","name":"F.clusterid","signature":"F.clusterid","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"event","name":"ON('$message')","signature":"ON('$message', function(msg, handle) {})","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart (file)","since":"","deprecated":false},{"type":"method","name":"SHELL(cmd, [callback], [cwd])","signature":"SHELL(cmd, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"$shell","signature":"$shell : /bin/bash","since":"","deprecated":false},{"type":"method","name":"F.python()","signature":"F.python(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"PYPELINE(name, [options])","signature":"PYPELINE(name, [options])","since":"","deprecated":false},{"type":"method","name":"F.pipinstall()","signature":"F.pipinstall(name, [callback])","since":"","deprecated":false},{"type":"method","name":"pypeline.send(data)","signature":"pypeline.send(data)","since":"","deprecated":false},{"type":"method","name":"pypeline.close()","signature":"pypeline.close()","since":"","deprecated":false},{"type":"method","name":"pypeline.restart()","signature":"pypeline.restart()","since":"","deprecated":false},{"type":"event","name":"pypeline.on('data')","signature":"pypeline.on('data', function(msg) {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('open')","signature":"pypeline.on('open', function() {})","since":"","deprecated":false},{"type":"event","name":"pypeline.on('restart')","signature":"pypeline.on('restart', function() {})","since":"","deprecated":false},{"type":"property","name":"pypeline.name","signature":"pypeline.name","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwWWJIx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"MCP server","summary":"The $mcp key, the mcp option of actions, the JSON-RPC methods of POST /$mcp/, the client of GET /$mcp/client.js and Total.mcp.","markdown":"---\ntitle: MCP server\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/mcp-server/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# MCP server\n\n> The $mcp key, the mcp option of actions, the JSON-RPC methods of POST /$mcp/, the client of GET /$mcp/client.js and Total.mcp.\n\nThe `$mcp` key, the `mcp` option of actions, the JSON-RPC methods of `POST /$mcp/`, the JavaScript client of `GET /$mcp/client.js` (code mode) and the `Total.mcp` object. The guide [MCP server](../../guides/mcp-server/) explains how actions become tools and how to protect the endpoint.\n\n## API\n\n### $mcp : Boolean\n\nType: `config`\n\nTurns on the MCP server.\n\nReturns: `Boolean`\n\n`true` creates the routes `POST /$mcp/` and `GET /$mcp/client.js` when the application is ready. Set it in the `config` file or in code before the start.\n\nDefault: `false`.\n\nExample: In the config file\n```text\n$mcp : true\n```\n\n### mcp: Boolean\n\nType: `config`\n\nMakes an action a tool.\n\nReturns: `Boolean`\n\nAn action with `mcp: true` is listed by `tools/list` and runs with `tools/call`. The name of the tool is the name of the action with each character other than `A-Z`, `a-z`, `0-9`, `_` and `-` replaced by `_` (at most 64 characters). The description is the `summary` option, or the `name` option. The `input`, `query` and `params` schemas become the arguments and `output` the output schema.\n\nExample: A tool\n```js\nNEWACTION('Tasks|list', {\n\tsummary: 'Lists the tasks, 20 per page',\n\tmcp: true,\n\tquery: 'page:Number // The page number',\n\taction: function($) {\n\t\tNOSQL('tasks').find().paginate($.query.page || 1, 20).callback($);\n\t}\n});\n// the tool Tasks_list\n```\n\n### POST /$mcp/\n\nType: `type`\n\nThe endpoint of the MCP server.\n\nA JSON-RPC 2.0 endpoint: one message in the body, one JSON answer. The body can have up to 10 MB and the request can take up to 300 seconds. A message without `id` is a notification and gets status `202` without a body. A message without `\"jsonrpc\": \"2.0\"` or `method`, or an array, gets the error `-32600`; an unknown method gets `-32601`. When `Total.mcp.auth` refuses the request, the status is `401` and the error `-32001`.\n\nExample: A request\n```js\nawait fetch('http://localhost:8000/$mcp/', {\n\tmethod: 'POST',\n\theaders: { 'Content-Type': 'application/json', Authorization: 'Bearer 6f1d2c' },\n\tbody: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' })\n});\n```\n\n### GET /$mcp/client.js[?q=words]\n\nType: `type`\n\nThe tools as a JavaScript client, for code mode.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `q` | `String` | no |  | Words that the name or the description of a tool must contain. |\n\nReturns: `String` The JavaScript source.\n\nReturns a CommonJS module (`text/javascript`) made from the tools that the caller may use: one function per tool, with JSDoc for its arguments (`input`, `query`, `params` and their fields, with the `//` messages as descriptions) and for its result. `require('./client.js')(token, [url])` returns an object of these functions. Each function sends `tools/call` to `POST /$mcp/` with `Authorization: Bearer <token>`, resolves with the output of the tool (`structuredContent`, or the parsed text) and throws an `Error` with the message of a tool error. The default `url` is the address the file was downloaded from. It needs Node.js 18 or newer (`fetch`) and no packages.\n\n`?q=words` returns only the tools whose name or description contain all the words (not case-sensitive). The request goes through `Total.mcp.auth` (a refused one gets `401` and the text `Unauthorized`) and `Total.mcp.filter`, so the client has the same tools as `tools/list`. Nothing runs on the server: the script runs where the agent runs, and every call is a normal tool call.\n\nExample: Download and use\n```js\n// curl -H 'Authorization: Bearer TOKEN' 'https://app.example.com/$mcp/client.js?q=tasks' > client.js\nconst api = require('./client.js')('TOKEN');\n\nconst task = await api.Tasks_create({ input: { name: 'Call Peter' } });\nconsole.log(task.id);\n```\n\nExample: A function of the file\n```js\n/**\n * Creates a task and returns its ID\n * @param {Object} args\n * @param {Object} args.input Payload (request body) passed to this action.\n * @param {String} args.input.name The name of the task\n * @param {String} [args.input.due] When the task must be done (ISO date)\n * @returns {Promise<{ id: ?String }>}\n */\napi.Tasks_create = args => call(\"Tasks_create\", args);\n```\n\n### { method: 'initialize', params: { protocolVersion } }\n\nType: `method`\n\nStarts a session of the client.\n\nReturns: `Object` The result.\n\nReturns `protocolVersion` (the version of the client when it is in `Total.mcp.versions`, otherwise the first one), `capabilities: { tools: {} }` and `serverInfo: { name: CONF.name, version: CONF.version }`. The server keeps no state between requests.\n\nExample: Answer\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n### { method: 'ping' }\n\nType: `method`\n\nChecks the connection.\n\nReturns: `Object` An empty object.\n\nReturns an empty result `{}`.\n\n### { method: 'tools/list' }\n\nType: `method`\n\nLists the tools.\n\nReturns: `Object` The result.\n\nReturns `{ resultType: 'complete', tools: [...] }` with the definitions of all actions that have `mcp: true` (`Total.mcp.tools`) that `Total.mcp.filter` allows for the caller. Each definition has `name`, `description` (when the action has `summary` or `name`), `inputSchema` and, with an `output` schema, `outputSchema`.\n\n### { method: 'tools/call', params: { name, arguments: { input, query, params } } }\n\nType: `method`\n\nRuns a tool.\n\nReturns: `Object` The result.\n\nRuns the action of the tool with `ACTION()`. `arguments.input` (or `arguments.data`) is the payload, `arguments.query` and `arguments.params` are the query and the URL parameters. The action has no controller, its user is the user that `Total.mcp.auth` accepted the request with (`{ id: 'ai', name: 'AI', sa: true }` with the default function) and `$.config.id` is the `id` from the query string of the endpoint. The result has `content: [{ type: 'text', text }]` with the response (a string as it is, other values as JSON) and, for an object, `structuredContent`. Errors of the action are a result with `isError: true`, also when the action throws an exception (the text is `Tool execution failed`, or `500: Internal Server Error` for an `async` action, and the exception goes to the error log). An unknown tool, a tool that `Total.mcp.filter` hides from the caller, or arguments that are not an object give the error `-32602`.\n\nExample: Call\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_remove\", \"arguments\": { \"params\": { \"id\": \"JafvB11cV61f\" } } } }\n```\n\nExample: Answer\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"success\\\":true}\" }], \"structuredContent\": { \"success\": true } } }\n```\n\n### { method: 'server/discover' }\n\nType: `method`\n\nDescribes the server.\n\nReturns: `Object` The result.\n\nReturns `resultType: 'complete'`, `supportedVersions: ['2026-07-28']`, `capabilities: { tools: {} }` and the server info (`CONF.name`, `CONF.version`) in `_meta['io.modelcontextprotocol/serverInfo']`.\n\n### Total.mcp.auth = function($)\n\nType: `delegate`\n\nDecides who may use the endpoint.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | The request; call `$.success()` or `$.invalid()`. |\n\nRuns for every request to `POST /$mcp/` and `GET /$mcp/client.js`. `$.token` (and `$.auth`) is the `Authorization` header without `Bearer `, and `$` has `headers`, `query`, `ip`, `ua` and `url`. Call `$.success(user)` to accept the request or `$.invalid()` to refuse it with `401`. The tools run as `user` and `Total.mcp.filter` gets it as `$.user`; `$.success()` without a user gives an empty user `{}`. The default function accepts every request with the user `{ id: 'ai', name: 'AI', sa: true }`. Set it in a file in `definitions/`.\n\nExample: Tokens from the config\n```js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token && $.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader', permissions: ['tasks_read'] });\n\telse\n\t\t$.invalid();\n};\n```\n\n### Total.mcp.filter = function(tool, $)\n\nType: `delegate`\n\nDecides which tools a caller sees and may run.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tool` | `Object` | yes |  | The definition of the tool: `name`, `description`, `inputSchema`, `outputSchema`. |\n| `$` | `Options` | yes |  | The request; `$.user` is the caller. |\n\nReturns: `Boolean` `true` when the caller may use the tool.\n\nOptional, `null` by default (every caller has all tools). The function gets the definition of a tool (an item of `Total.mcp.tools`) and `$` with the user from `Total.mcp.auth` in `$.user`, and returns `true` to allow the tool. A tool that is not allowed is left out of `tools/list` and `GET /$mcp/client.js`, and `tools/call` answers it with `-32602` (`Unknown tool`), as if it did not exist.\n\nExample: Admin tools only for admins\n```js\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n### Total.mcp.tools\n\nType: `property`\n\nThe definitions of the tools.\n\nReturns: `Array`\n\nAn array with the definition of every action that has `mcp: true`, the same objects that `tools/list` returns. It is built again 200 ms after each `NEWACTION()`.\n\nExample: Names\n```js\nconsole.log(Total.mcp.tools.map(tool => tool.name));\n// ['Tasks_create', 'Tasks_list', 'Tasks_remove']\n```\n\n### Total.mcp.versions\n\nType: `property`\n\nThe supported protocol versions.\n\nReturns: `Array`\n\nAn array, newest first: `['2026-07-28', '2025-11-25', '2025-06-18', '2025-03-26']`. `initialize` answers with the version of the client when it is in the list, otherwise with the first one.\n\n### F.actions[name].toAITool()\n\nType: `method`\n\nReturns the tool definition of an action.\n\nReturns: `Object` The tool definition.\n\nReturns `{ name, description, inputSchema, [outputSchema] }` in the format of `tools/list`. It works for any action, also without `mcp: true`, so you can pass actions as tools to an AI model yourself.\n\nExample: One tool\n```js\nvar tool = F.actions['Tasks|remove'].toAITool();\n// { name: 'Tasks_remove', description: 'Removes a task', inputSchema: { type: 'object', properties: { params: {...} }, required: ['params'] } }\n```\n","entries":[{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"type","name":"POST /$mcp/","signature":"POST /$mcp/","since":"","deprecated":false},{"type":"type","name":"GET /$mcp/client.js","signature":"GET /$mcp/client.js[?q=words]","since":"","deprecated":false},{"type":"method","name":"initialize","signature":"{ method: 'initialize', params: { protocolVersion } }","since":"","deprecated":false},{"type":"method","name":"ping","signature":"{ method: 'ping' }","since":"","deprecated":false},{"type":"method","name":"tools/list","signature":"{ method: 'tools/list' }","since":"","deprecated":false},{"type":"method","name":"tools/call","signature":"{ method: 'tools/call', params: { name, arguments: { input, query, params } } }","since":"","deprecated":false},{"type":"method","name":"server/discover","signature":"{ method: 'server/discover' }","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.auth","signature":"Total.mcp.auth = function($)","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.filter","signature":"Total.mcp.filter = function(tool, $)","since":"","deprecated":false},{"type":"property","name":"Total.mcp.tools","signature":"Total.mcp.tools","since":"","deprecated":false},{"type":"property","name":"Total.mcp.versions","signature":"Total.mcp.versions","since":"","deprecated":false},{"type":"method","name":"action.toAITool()","signature":"F.actions[name].toAITool()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JafwWWJIx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"MCP-Server","summary":"Der Schlüssel $mcp, die Option mcp von Aktionen, die JSON-RPC-Methoden von POST /$mcp/, der Client von GET /$mcp/client.js und Total.mcp.","markdown":"---\ntitle: MCP-Server\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/mcp-server/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# MCP-Server\n\n> Der Schlüssel $mcp, die Option mcp von Aktionen, die JSON-RPC-Methoden von POST /$mcp/, der Client von GET /$mcp/client.js und Total.mcp.\n\nDer Schlüssel `$mcp`, die Option `mcp` von Aktionen, die JSON-RPC-Methoden von `POST /$mcp/`, der JavaScript-Client von `GET /$mcp/client.js` (Code-Modus) und das Objekt `Total.mcp`. Die Anleitung [MCP-Server](../../guides/mcp-server/) erklärt, wie Aktionen zu Tools werden und wie du den Endpunkt schützt.\n\n## API\n\n### $mcp : Boolean\n\nType: `config`\n\nSchaltet den MCP-Server ein.\n\nReturns: `Boolean`\n\n`true` erstellt die Routen `POST /$mcp/` und `GET /$mcp/client.js`, sobald die Anwendung bereit ist. Setze es in der Datei `config` oder im Code vor dem Start.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\n$mcp : true\n```\n\n### mcp: Boolean\n\nType: `config`\n\nMacht eine Aktion zu einem Tool.\n\nReturns: `Boolean`\n\nEine Aktion mit `mcp: true` wird von `tools/list` aufgelistet und läuft mit `tools/call`. Der Name des Tools ist der Name der Aktion, in dem jedes Zeichen außer `A-Z`, `a-z`, `0-9`, `_` und `-` durch `_` ersetzt wird (höchstens 64 Zeichen). Die Beschreibung ist die Option `summary` oder die Option `name`. Die Schemas `input`, `query` und `params` werden zu den Argumenten und `output` zum Ausgabeschema.\n\nExample: Ein Tool\n```js\nNEWACTION('Tasks|list', {\n\tsummary: 'Lists the tasks, 20 per page',\n\tmcp: true,\n\tquery: 'page:Number // The page number',\n\taction: function($) {\n\t\tNOSQL('tasks').find().paginate($.query.page || 1, 20).callback($);\n\t}\n});\n// the tool Tasks_list\n```\n\n### POST /$mcp/\n\nType: `type`\n\nDer Endpunkt des MCP-Servers.\n\nEin JSON-RPC-2.0-Endpunkt: eine Nachricht im Body, eine JSON-Antwort. Der Body darf bis zu 10 MB groß sein, und die Anfrage darf bis zu 300 Sekunden dauern. Eine Nachricht ohne `id` ist eine Notification und erhält den Status `202` ohne Body. Eine Nachricht ohne `\"jsonrpc\": \"2.0\"` oder `method` oder ein Array erhält den Fehler `-32600`; eine unbekannte Methode erhält `-32601`. Wenn `Total.mcp.auth` die Anfrage ablehnt, ist der Status `401` und der Fehler `-32001`.\n\nExample: Eine Anfrage\n```js\nawait fetch('http://localhost:8000/$mcp/', {\n\tmethod: 'POST',\n\theaders: { 'Content-Type': 'application/json', Authorization: 'Bearer 6f1d2c' },\n\tbody: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' })\n});\n```\n\n### GET /$mcp/client.js[?q=words]\n\nType: `type`\n\nDie Tools als JavaScript-Client, für den Code-Modus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `q` | `String` | no |  | Wörter, die der Name oder die Beschreibung eines Tools enthalten muss. |\n\nReturns: `String` Der JavaScript-Quellcode.\n\nGibt ein CommonJS-Modul (`text/javascript`) zurück, das aus den Tools erstellt wird, die der Aufrufer verwenden darf: eine Funktion pro Tool, mit JSDoc für ihre Argumente (`input`, `query`, `params` und ihre Felder, mit den `//`-Meldungen als Beschreibungen) und für ihr Ergebnis. `require('./client.js')(token, [url])` gibt ein Objekt mit diesen Funktionen zurück. Jede Funktion sendet `tools/call` an `POST /$mcp/` mit `Authorization: Bearer <token>`, wird mit der Ausgabe des Tools erfüllt (`structuredContent` oder der geparste Text) und wirft einen `Error` mit der Meldung eines Tool-Fehlers. Die Standard-`url` ist die Adresse, von der die Datei heruntergeladen wurde. Es braucht Node.js 18 oder neuer (`fetch`) und keine Pakete.\n\n`?q=words` gibt nur die Tools zurück, deren Name oder Beschreibung alle Wörter enthält (ohne Beachtung der Groß- und Kleinschreibung). Die Anfrage durchläuft `Total.mcp.auth` (eine abgelehnte erhält `401` und den Text `Unauthorized`) und `Total.mcp.filter`, sodass der Client dieselben Tools hat wie `tools/list`. Auf dem Server läuft nichts: Das Skript läuft dort, wo der Agent läuft, und jeder Aufruf ist ein normaler Tool-Aufruf.\n\nExample: Herunterladen und verwenden\n```js\n// curl -H 'Authorization: Bearer TOKEN' 'https://app.example.com/$mcp/client.js?q=tasks' > client.js\nconst api = require('./client.js')('TOKEN');\n\nconst task = await api.Tasks_create({ input: { name: 'Call Peter' } });\nconsole.log(task.id);\n```\n\nExample: Eine Funktion der Datei\n```js\n/**\n * Creates a task and returns its ID\n * @param {Object} args\n * @param {Object} args.input Payload (request body) passed to this action.\n * @param {String} args.input.name The name of the task\n * @param {String} [args.input.due] When the task must be done (ISO date)\n * @returns {Promise<{ id: ?String }>}\n */\napi.Tasks_create = args => call(\"Tasks_create\", args);\n```\n\n### { method: 'initialize', params: { protocolVersion } }\n\nType: `method`\n\nStartet eine Session des Clients.\n\nReturns: `Object` Das Ergebnis.\n\nGibt `protocolVersion` (die Version des Clients, wenn sie in `Total.mcp.versions` steht, sonst die erste), `capabilities: { tools: {} }` und `serverInfo: { name: CONF.name, version: CONF.version }` zurück. Der Server hält keinen Zustand zwischen Anfragen.\n\nExample: Antwort\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n### { method: 'ping' }\n\nType: `method`\n\nPrüft die Verbindung.\n\nReturns: `Object` Ein leeres Objekt.\n\nGibt ein leeres Ergebnis `{}` zurück.\n\n### { method: 'tools/list' }\n\nType: `method`\n\nListet die Tools auf.\n\nReturns: `Object` Das Ergebnis.\n\nGibt `{ resultType: 'complete', tools: [...] }` mit den Definitionen aller Aktionen zurück, die `mcp: true` haben (`Total.mcp.tools`) und die `Total.mcp.filter` für den Aufrufer erlaubt. Jede Definition hat `name`, `description` (wenn die Aktion `summary` oder `name` hat), `inputSchema` und, mit einem Schema `output`, `outputSchema`.\n\n### { method: 'tools/call', params: { name, arguments: { input, query, params } } }\n\nType: `method`\n\nFührt ein Tool aus.\n\nReturns: `Object` Das Ergebnis.\n\nFührt die Aktion des Tools mit `ACTION()` aus. `arguments.input` (oder `arguments.data`) ist der Payload, `arguments.query` und `arguments.params` sind die Query und die URL-Parameter. Die Aktion hat keinen Controller, ihr Benutzer ist der Benutzer, mit dem `Total.mcp.auth` die Anfrage angenommen hat (`{ id: 'ai', name: 'AI', sa: true }` mit der Standardfunktion), und `$.config.id` ist die `id` aus dem Query String des Endpunkts. Das Ergebnis hat `content: [{ type: 'text', text }]` mit der Antwort (ein String so, wie er ist, andere Werte als JSON) und, bei einem Objekt, `structuredContent`. Fehler der Aktion sind ein Ergebnis mit `isError: true`, auch wenn die Aktion eine Exception wirft (der Text ist `Tool execution failed` oder bei einer `async`-Aktion `500: Internal Server Error`, und die Exception geht ins Fehlerprotokoll). Ein unbekanntes Tool, ein Tool, das `Total.mcp.filter` vor dem Aufrufer verbirgt, oder Argumente, die kein Objekt sind, führen zum Fehler `-32602`.\n\nExample: Aufruf\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_remove\", \"arguments\": { \"params\": { \"id\": \"JafvB11cV61f\" } } } }\n```\n\nExample: Antwort\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"success\\\":true}\" }], \"structuredContent\": { \"success\": true } } }\n```\n\n### { method: 'server/discover' }\n\nType: `method`\n\nBeschreibt den Server.\n\nReturns: `Object` Das Ergebnis.\n\nGibt `resultType: 'complete'`, `supportedVersions: ['2026-07-28']`, `capabilities: { tools: {} }` und die Serverinformationen (`CONF.name`, `CONF.version`) in `_meta['io.modelcontextprotocol/serverInfo']` zurück.\n\n### Total.mcp.auth = function($)\n\nType: `delegate`\n\nEntscheidet, wer den Endpunkt verwenden darf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | Die Anfrage; rufe `$.success()` oder `$.invalid()` auf. |\n\nLäuft bei jeder Anfrage an `POST /$mcp/` und `GET /$mcp/client.js`. `$.token` (und `$.auth`) ist der Header `Authorization` ohne `Bearer `, und `$` hat `headers`, `query`, `ip`, `ua` und `url`. Rufe `$.success(user)` auf, um die Anfrage anzunehmen, oder `$.invalid()`, um sie mit `401` abzulehnen. Die Tools laufen als `user`, und `Total.mcp.filter` erhält ihn als `$.user`; `$.success()` ohne Benutzer ergibt einen leeren Benutzer `{}`. Die Standardfunktion nimmt jede Anfrage mit dem Benutzer `{ id: 'ai', name: 'AI', sa: true }` an. Setze sie in einer Datei in `definitions/`.\n\nExample: Token aus der Konfiguration\n```js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token && $.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader', permissions: ['tasks_read'] });\n\telse\n\t\t$.invalid();\n};\n```\n\n### Total.mcp.filter = function(tool, $)\n\nType: `delegate`\n\nEntscheidet, welche Tools ein Aufrufer sieht und ausführen darf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tool` | `Object` | yes |  | Die Definition des Tools: `name`, `description`, `inputSchema`, `outputSchema`. |\n| `$` | `Options` | yes |  | Die Anfrage; `$.user` ist der Aufrufer. |\n\nReturns: `Boolean` `true`, wenn der Aufrufer das Tool verwenden darf.\n\nOptional, standardmäßig `null` (jeder Aufrufer hat alle Tools). Die Funktion erhält die Definition eines Tools (ein Element von `Total.mcp.tools`) und `$` mit dem Benutzer aus `Total.mcp.auth` in `$.user` und gibt `true` zurück, um das Tool zu erlauben. Ein nicht erlaubtes Tool fehlt in `tools/list` und `GET /$mcp/client.js`, und `tools/call` beantwortet es mit `-32602` (`Unknown tool`), als gäbe es es nicht.\n\nExample: Admin-Tools nur für Admins\n```js\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n### Total.mcp.tools\n\nType: `property`\n\nDie Definitionen der Tools.\n\nReturns: `Array`\n\nEin Array mit der Definition jeder Aktion, die `mcp: true` hat, dieselben Objekte, die `tools/list` zurückgibt. Es wird 200 ms nach jedem `NEWACTION()` neu aufgebaut.\n\nExample: Namen\n```js\nconsole.log(Total.mcp.tools.map(tool => tool.name));\n// ['Tasks_create', 'Tasks_list', 'Tasks_remove']\n```\n\n### Total.mcp.versions\n\nType: `property`\n\nDie unterstützten Protokollversionen.\n\nReturns: `Array`\n\nEin Array, die neueste zuerst: `['2026-07-28', '2025-11-25', '2025-06-18', '2025-03-26']`. `initialize` antwortet mit der Version des Clients, wenn sie in der Liste steht, sonst mit der ersten.\n\n### F.actions[name].toAITool()\n\nType: `method`\n\nGibt die Tool-Definition einer Aktion zurück.\n\nReturns: `Object` Die Tool-Definition.\n\nGibt `{ name, description, inputSchema, [outputSchema] }` im Format von `tools/list` zurück. Es funktioniert für jede Aktion, auch ohne `mcp: true`, sodass du Aktionen selbst als Tools an ein KI-Modell übergeben kannst.\n\nExample: Ein Tool\n```js\nvar tool = F.actions['Tasks|remove'].toAITool();\n// { name: 'Tasks_remove', description: 'Removes a task', inputSchema: { type: 'object', properties: { params: {...} }, required: ['params'] } }\n```\n","entries":[{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"type","name":"POST /$mcp/","signature":"POST /$mcp/","since":"","deprecated":false},{"type":"type","name":"GET /$mcp/client.js","signature":"GET /$mcp/client.js[?q=words]","since":"","deprecated":false},{"type":"method","name":"initialize","signature":"{ method: 'initialize', params: { protocolVersion } }","since":"","deprecated":false},{"type":"method","name":"ping","signature":"{ method: 'ping' }","since":"","deprecated":false},{"type":"method","name":"tools/list","signature":"{ method: 'tools/list' }","since":"","deprecated":false},{"type":"method","name":"tools/call","signature":"{ method: 'tools/call', params: { name, arguments: { input, query, params } } }","since":"","deprecated":false},{"type":"method","name":"server/discover","signature":"{ method: 'server/discover' }","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.auth","signature":"Total.mcp.auth = function($)","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.filter","signature":"Total.mcp.filter = function(tool, $)","since":"","deprecated":false},{"type":"property","name":"Total.mcp.tools","signature":"Total.mcp.tools","since":"","deprecated":false},{"type":"property","name":"Total.mcp.versions","signature":"Total.mcp.versions","since":"","deprecated":false},{"type":"method","name":"action.toAITool()","signature":"F.actions[name].toAITool()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JafwWWJIx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Servidor MCP","summary":"La clave $mcp, la opción mcp de las acciones, los métodos JSON-RPC de POST /$mcp/, el cliente de GET /$mcp/client.js y Total.mcp.","markdown":"---\ntitle: Servidor MCP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/mcp-server/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# Servidor MCP\n\n> La clave $mcp, la opción mcp de las acciones, los métodos JSON-RPC de POST /$mcp/, el cliente de GET /$mcp/client.js y Total.mcp.\n\nLa clave `$mcp`, la opción `mcp` de las acciones, los métodos JSON-RPC de `POST /$mcp/`, el cliente JavaScript de `GET /$mcp/client.js` (modo código) y el objeto `Total.mcp`. La guía [Servidor MCP](../../guides/mcp-server/) explica cómo las acciones se convierten en herramientas y cómo proteger el endpoint.\n\n## API\n\n### $mcp : Boolean\n\nType: `config`\n\nActiva el servidor MCP.\n\nReturns: `Boolean`\n\n`true` crea las rutas `POST /$mcp/` y `GET /$mcp/client.js` cuando la aplicación está lista. Establécela en el archivo `config` o en el código antes del arranque.\n\nPor defecto: `false`.\n\nExample: En el archivo config\n```text\n$mcp : true\n```\n\n### mcp: Boolean\n\nType: `config`\n\nConvierte una acción en una herramienta.\n\nReturns: `Boolean`\n\nUna acción con `mcp: true` aparece en `tools/list` y se ejecuta con `tools/call`. El nombre de la herramienta es el nombre de la acción con cada carácter que no sea `A-Z`, `a-z`, `0-9`, `_` o `-` sustituido por `_` (como máximo 64 caracteres). La descripción es la opción `summary`, o la opción `name`. Los esquemas `input`, `query` y `params` se convierten en los argumentos y `output` en el esquema de salida.\n\nExample: Una herramienta\n```js\nNEWACTION('Tasks|list', {\n\tsummary: 'Lists the tasks, 20 per page',\n\tmcp: true,\n\tquery: 'page:Number // The page number',\n\taction: function($) {\n\t\tNOSQL('tasks').find().paginate($.query.page || 1, 20).callback($);\n\t}\n});\n// the tool Tasks_list\n```\n\n### POST /$mcp/\n\nType: `type`\n\nEl endpoint del servidor MCP.\n\nUn endpoint JSON-RPC 2.0: un mensaje en el cuerpo, una respuesta JSON. El cuerpo puede tener hasta 10 MB y la petición puede durar hasta 300 segundos. Un mensaje sin `id` es una notificación y recibe el estado `202` sin cuerpo. Un mensaje sin `\"jsonrpc\": \"2.0\"` o sin `method`, o un array, recibe el error `-32600`; un método desconocido recibe `-32601`. Cuando `Total.mcp.auth` rechaza la petición, el estado es `401` y el error `-32001`.\n\nExample: Una petición\n```js\nawait fetch('http://localhost:8000/$mcp/', {\n\tmethod: 'POST',\n\theaders: { 'Content-Type': 'application/json', Authorization: 'Bearer 6f1d2c' },\n\tbody: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' })\n});\n```\n\n### GET /$mcp/client.js[?q=words]\n\nType: `type`\n\nLas herramientas como cliente JavaScript, para el modo código.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `q` | `String` | no |  | Palabras que tiene que contener el nombre o la descripción de una herramienta. |\n\nReturns: `String` El código fuente JavaScript.\n\nDevuelve un módulo CommonJS (`text/javascript`) creado a partir de las herramientas que puede usar quien llama: una función por herramienta, con JSDoc para sus argumentos (`input`, `query`, `params` y sus campos, con los mensajes `//` como descripciones) y para su resultado. `require('./client.js')(token, [url])` devuelve un objeto con estas funciones. Cada función envía `tools/call` a `POST /$mcp/` con `Authorization: Bearer <token>`, se resuelve con la salida de la herramienta (`structuredContent`, o el texto parseado) y lanza un `Error` con el mensaje de un error de la herramienta. La `url` por defecto es la dirección desde la que se descargó el archivo. Necesita Node.js 18 o posterior (`fetch`) y ningún paquete.\n\n`?q=words` devuelve solo las herramientas cuyo nombre o descripción contienen todas las palabras (sin distinguir mayúsculas y minúsculas). La petición pasa por `Total.mcp.auth` (una rechazada recibe `401` y el texto `Unauthorized`) y por `Total.mcp.filter`, así que el cliente tiene las mismas herramientas que `tools/list`. En el servidor no se ejecuta nada: el script se ejecuta donde se ejecuta el agente, y cada llamada es una llamada normal a una herramienta.\n\nExample: Descargar y usar\n```js\n// curl -H 'Authorization: Bearer TOKEN' 'https://app.example.com/$mcp/client.js?q=tasks' > client.js\nconst api = require('./client.js')('TOKEN');\n\nconst task = await api.Tasks_create({ input: { name: 'Call Peter' } });\nconsole.log(task.id);\n```\n\nExample: Una función del archivo\n```js\n/**\n * Creates a task and returns its ID\n * @param {Object} args\n * @param {Object} args.input Payload (request body) passed to this action.\n * @param {String} args.input.name The name of the task\n * @param {String} [args.input.due] When the task must be done (ISO date)\n * @returns {Promise<{ id: ?String }>}\n */\napi.Tasks_create = args => call(\"Tasks_create\", args);\n```\n\n### { method: 'initialize', params: { protocolVersion } }\n\nType: `method`\n\nInicia una sesión del cliente.\n\nReturns: `Object` El resultado.\n\nDevuelve `protocolVersion` (la versión del cliente cuando está en `Total.mcp.versions`; si no, la primera), `capabilities: { tools: {} }` y `serverInfo: { name: CONF.name, version: CONF.version }`. El servidor no guarda estado entre peticiones.\n\nExample: Respuesta\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n### { method: 'ping' }\n\nType: `method`\n\nComprueba la conexión.\n\nReturns: `Object` Un objeto vacío.\n\nDevuelve un resultado vacío `{}`.\n\n### { method: 'tools/list' }\n\nType: `method`\n\nLista las herramientas.\n\nReturns: `Object` El resultado.\n\nDevuelve `{ resultType: 'complete', tools: [...] }` con las definiciones de todas las acciones que tienen `mcp: true` (`Total.mcp.tools`) que `Total.mcp.filter` permite a quien llama. Cada definición tiene `name`, `description` (cuando la acción tiene `summary` o `name`), `inputSchema` y, con un esquema `output`, `outputSchema`.\n\n### { method: 'tools/call', params: { name, arguments: { input, query, params } } }\n\nType: `method`\n\nEjecuta una herramienta.\n\nReturns: `Object` El resultado.\n\nEjecuta la acción de la herramienta con `ACTION()`. `arguments.input` (o `arguments.data`) es la carga útil, `arguments.query` y `arguments.params` son el query string y los parámetros de la URL. La acción no tiene controlador, su usuario es el usuario con el que `Total.mcp.auth` aceptó la petición (`{ id: 'ai', name: 'AI', sa: true }` con la función por defecto) y `$.config.id` es el `id` del query string del endpoint. El resultado tiene `content: [{ type: 'text', text }]` con la respuesta (un string tal cual, los demás valores como JSON) y, para un objeto, `structuredContent`. Los errores de la acción son un resultado con `isError: true`, también cuando la acción lanza una excepción (el texto es `Tool execution failed`, o `500: Internal Server Error` para una acción `async`, y la excepción va al registro de errores). Una herramienta desconocida, una herramienta que `Total.mcp.filter` oculta a quien llama o unos argumentos que no son un objeto dan el error `-32602`.\n\nExample: Llamada\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_remove\", \"arguments\": { \"params\": { \"id\": \"JafvB11cV61f\" } } } }\n```\n\nExample: Respuesta\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"success\\\":true}\" }], \"structuredContent\": { \"success\": true } } }\n```\n\n### { method: 'server/discover' }\n\nType: `method`\n\nDescribe el servidor.\n\nReturns: `Object` El resultado.\n\nDevuelve `resultType: 'complete'`, `supportedVersions: ['2026-07-28']`, `capabilities: { tools: {} }` y la información del servidor (`CONF.name`, `CONF.version`) en `_meta['io.modelcontextprotocol/serverInfo']`.\n\n### Total.mcp.auth = function($)\n\nType: `delegate`\n\nDecide quién puede usar el endpoint.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | La petición; llama a `$.success()` o a `$.invalid()`. |\n\nReturns: `undefined` Nada\n\nSe ejecuta para cada petición a `POST /$mcp/` y `GET /$mcp/client.js`. `$.token` (y `$.auth`) es la cabecera `Authorization` sin `Bearer `, y `$` tiene `headers`, `query`, `ip`, `ua` y `url`. Llama a `$.success(user)` para aceptar la petición o a `$.invalid()` para rechazarla con `401`. Las herramientas se ejecutan como `user` y `Total.mcp.filter` lo recibe como `$.user`; `$.success()` sin usuario da un usuario vacío `{}`. La función por defecto acepta cualquier petición con el usuario `{ id: 'ai', name: 'AI', sa: true }`. Establécela en un archivo de `definitions/`.\n\nExample: Tokens de la configuración\n```js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token && $.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader', permissions: ['tasks_read'] });\n\telse\n\t\t$.invalid();\n};\n```\n\n### Total.mcp.filter = function(tool, $)\n\nType: `delegate`\n\nDecide qué herramientas ve y puede ejecutar quien llama.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tool` | `Object` | yes |  | La definición de la herramienta: `name`, `description`, `inputSchema`, `outputSchema`. |\n| `$` | `Options` | yes |  | La petición; `$.user` es quien llama. |\n\nReturns: `Boolean` `true` cuando quien llama puede usar la herramienta.\n\nOpcional, `null` por defecto (todos tienen todas las herramientas). La función recibe la definición de una herramienta (un elemento de `Total.mcp.tools`) y `$` con el usuario de `Total.mcp.auth` en `$.user`, y devuelve `true` para permitir la herramienta. Una herramienta no permitida se deja fuera de `tools/list` y de `GET /$mcp/client.js`, y `tools/call` la responde con `-32602` (`Unknown tool`), como si no existiera.\n\nExample: Herramientas de administración solo para administradores\n```js\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n### Total.mcp.tools\n\nType: `property`\n\nLas definiciones de las herramientas.\n\nReturns: `Array`\n\nUn array con la definición de cada acción que tiene `mcp: true`, los mismos objetos que devuelve `tools/list`. Se vuelve a construir 200 ms después de cada `NEWACTION()`.\n\nExample: Nombres\n```js\nconsole.log(Total.mcp.tools.map(tool => tool.name));\n// ['Tasks_create', 'Tasks_list', 'Tasks_remove']\n```\n\n### Total.mcp.versions\n\nType: `property`\n\nLas versiones del protocolo admitidas.\n\nReturns: `Array`\n\nUn array, de la más nueva a la más antigua: `['2026-07-28', '2025-11-25', '2025-06-18', '2025-03-26']`. `initialize` responde con la versión del cliente cuando está en la lista; si no, con la primera.\n\n### F.actions[name].toAITool()\n\nType: `method`\n\nDevuelve la definición de herramienta de una acción.\n\nReturns: `Object` La definición de la herramienta.\n\nDevuelve `{ name, description, inputSchema, [outputSchema] }` en el formato de `tools/list`. Funciona con cualquier acción, también sin `mcp: true`, así puedes pasar tú mismo acciones como herramientas a un modelo de IA.\n\nExample: Una herramienta\n```js\nvar tool = F.actions['Tasks|remove'].toAITool();\n// { name: 'Tasks_remove', description: 'Removes a task', inputSchema: { type: 'object', properties: { params: {...} }, required: ['params'] } }\n```\n","entries":[{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"type","name":"POST /$mcp/","signature":"POST /$mcp/","since":"","deprecated":false},{"type":"type","name":"GET /$mcp/client.js","signature":"GET /$mcp/client.js[?q=words]","since":"","deprecated":false},{"type":"method","name":"initialize","signature":"{ method: 'initialize', params: { protocolVersion } }","since":"","deprecated":false},{"type":"method","name":"ping","signature":"{ method: 'ping' }","since":"","deprecated":false},{"type":"method","name":"tools/list","signature":"{ method: 'tools/list' }","since":"","deprecated":false},{"type":"method","name":"tools/call","signature":"{ method: 'tools/call', params: { name, arguments: { input, query, params } } }","since":"","deprecated":false},{"type":"method","name":"server/discover","signature":"{ method: 'server/discover' }","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.auth","signature":"Total.mcp.auth = function($)","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.filter","signature":"Total.mcp.filter = function(tool, $)","since":"","deprecated":false},{"type":"property","name":"Total.mcp.tools","signature":"Total.mcp.tools","since":"","deprecated":false},{"type":"property","name":"Total.mcp.versions","signature":"Total.mcp.versions","since":"","deprecated":false},{"type":"method","name":"action.toAITool()","signature":"F.actions[name].toAITool()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JafwWWJIx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Serveur MCP","summary":"La clé $mcp, l'option mcp des actions, les méthodes JSON-RPC de POST /$mcp/, le client de GET /$mcp/client.js et Total.mcp.","markdown":"---\ntitle: Serveur MCP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/mcp-server/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# Serveur MCP\n\n> La clé $mcp, l'option mcp des actions, les méthodes JSON-RPC de POST /$mcp/, le client de GET /$mcp/client.js et Total.mcp.\n\nLa clé `$mcp`, l'option `mcp` des actions, les méthodes JSON-RPC de `POST /$mcp/`, le client JavaScript de `GET /$mcp/client.js` (mode code) et l'objet `Total.mcp`. Le guide [Serveur MCP](../../guides/mcp-server/) explique comment les actions deviennent des outils et comment protéger l'endpoint.\n\n## API\n\n### $mcp : Boolean\n\nType: `config`\n\nActive le serveur MCP.\n\nReturns: `Boolean`\n\n`true` crée les routes `POST /$mcp/` et `GET /$mcp/client.js` quand l'application est prête. Définis-la dans le fichier `config` ou dans le code avant le démarrage.\n\nPar défaut : `false`.\n\nExample: Dans le fichier config\n```text\n$mcp : true\n```\n\n### mcp: Boolean\n\nType: `config`\n\nFait d'une action un outil.\n\nReturns: `Boolean`\n\nUne action avec `mcp: true` est listée par `tools/list` et s'exécute avec `tools/call`. Le nom de l'outil est le nom de l'action où chaque caractère autre que `A-Z`, `a-z`, `0-9`, `_` et `-` est remplacé par `_` (64 caractères au maximum). La description est l'option `summary`, ou l'option `name`. Les schémas `input`, `query` et `params` deviennent les arguments et `output` le schéma de sortie.\n\nExample: Un outil\n```js\nNEWACTION('Tasks|list', {\n\tsummary: 'Lists the tasks, 20 per page',\n\tmcp: true,\n\tquery: 'page:Number // The page number',\n\taction: function($) {\n\t\tNOSQL('tasks').find().paginate($.query.page || 1, 20).callback($);\n\t}\n});\n// the tool Tasks_list\n```\n\n### POST /$mcp/\n\nType: `type`\n\nL'endpoint du serveur MCP.\n\nUn endpoint JSON-RPC 2.0 : un message dans le corps, une réponse JSON. Le corps peut faire jusqu'à 10 Mo et la requête peut durer jusqu'à 300 secondes. Un message sans `id` est une notification et reçoit le statut `202` sans corps. Un message sans `\"jsonrpc\": \"2.0\"` ou `method`, ou un tableau, reçoit l'erreur `-32600` ; une méthode inconnue reçoit `-32601`. Quand `Total.mcp.auth` refuse la requête, le statut est `401` et l'erreur `-32001`.\n\nExample: Une requête\n```js\nawait fetch('http://localhost:8000/$mcp/', {\n\tmethod: 'POST',\n\theaders: { 'Content-Type': 'application/json', Authorization: 'Bearer 6f1d2c' },\n\tbody: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' })\n});\n```\n\n### GET /$mcp/client.js[?q=words]\n\nType: `type`\n\nLes outils sous forme de client JavaScript, pour le mode code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `q` | `String` | no |  | Les mots que le nom ou la description d'un outil doivent contenir. |\n\nReturns: `String` Le code source JavaScript.\n\nRenvoie un module CommonJS (`text/javascript`) construit à partir des outils que l'appelant peut utiliser : une fonction par outil, avec du JSDoc pour ses arguments (`input`, `query`, `params` et leurs champs, avec les messages `//` comme descriptions) et pour son résultat. `require('./client.js')(token, [url])` renvoie un objet avec ces fonctions. Chaque fonction envoie `tools/call` à `POST /$mcp/` avec `Authorization: Bearer <token>`, se résout avec la sortie de l'outil (`structuredContent`, ou le texte analysé) et lève une `Error` avec le message d'une erreur de l'outil. L'`url` par défaut est l'adresse depuis laquelle le fichier a été téléchargé. Il faut Node.js 18 ou plus récent (`fetch`) et aucun paquet.\n\n`?q=words` ne renvoie que les outils dont le nom ou la description contiennent tous les mots (sans tenir compte de la casse). La requête passe par `Total.mcp.auth` (une requête refusée reçoit `401` et le texte `Unauthorized`) et `Total.mcp.filter`, donc le client a les mêmes outils que `tools/list`. Rien ne s'exécute sur le serveur : le script s'exécute là où l'agent s'exécute, et chaque appel est un appel d'outil normal.\n\nExample: Télécharger et utiliser\n```js\n// curl -H 'Authorization: Bearer TOKEN' 'https://app.example.com/$mcp/client.js?q=tasks' > client.js\nconst api = require('./client.js')('TOKEN');\n\nconst task = await api.Tasks_create({ input: { name: 'Call Peter' } });\nconsole.log(task.id);\n```\n\nExample: Une fonction du fichier\n```js\n/**\n * Creates a task and returns its ID\n * @param {Object} args\n * @param {Object} args.input Payload (request body) passed to this action.\n * @param {String} args.input.name The name of the task\n * @param {String} [args.input.due] When the task must be done (ISO date)\n * @returns {Promise<{ id: ?String }>}\n */\napi.Tasks_create = args => call(\"Tasks_create\", args);\n```\n\n### { method: 'initialize', params: { protocolVersion } }\n\nType: `method`\n\nDémarre une session du client.\n\nReturns: `Object` Le résultat.\n\nRenvoie `protocolVersion` (la version du client quand elle se trouve dans `Total.mcp.versions`, sinon la première), `capabilities: { tools: {} }` et `serverInfo: { name: CONF.name, version: CONF.version }`. Le serveur ne garde aucun état entre les requêtes.\n\nExample: Réponse\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n### { method: 'ping' }\n\nType: `method`\n\nVérifie la connexion.\n\nReturns: `Object` Un objet vide.\n\nRenvoie un résultat vide `{}`.\n\n### { method: 'tools/list' }\n\nType: `method`\n\nListe les outils.\n\nReturns: `Object` Le résultat.\n\nRenvoie `{ resultType: 'complete', tools: [...] }` avec les définitions de toutes les actions qui ont `mcp: true` (`Total.mcp.tools`) que `Total.mcp.filter` autorise pour l'appelant. Chaque définition a `name`, `description` (quand l'action a `summary` ou `name`), `inputSchema` et, avec un schéma `output`, `outputSchema`.\n\n### { method: 'tools/call', params: { name, arguments: { input, query, params } } }\n\nType: `method`\n\nExécute un outil.\n\nReturns: `Object` Le résultat.\n\nExécute l'action de l'outil avec `ACTION()`. `arguments.input` (ou `arguments.data`) correspond aux données envoyées, `arguments.query` et `arguments.params` sont la query et les paramètres d'URL. L'action n'a pas de contrôleur, son utilisateur est celui avec lequel `Total.mcp.auth` a accepté la requête (`{ id: 'ai', name: 'AI', sa: true }` avec la fonction par défaut) et `$.config.id` est l'`id` de la query string de l'endpoint. Le résultat a `content: [{ type: 'text', text }]` avec la réponse (une chaîne telle quelle, les autres valeurs en JSON) et, pour un objet, `structuredContent`. Les erreurs de l'action sont un résultat avec `isError: true`, aussi quand l'action lève une exception (le texte est `Tool execution failed`, ou `500: Internal Server Error` pour une action `async`, et l'exception va dans le journal des erreurs). Un outil inconnu, un outil que `Total.mcp.filter` cache à l'appelant, ou des arguments qui ne sont pas un objet donnent l'erreur `-32602`.\n\nExample: Appel\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_remove\", \"arguments\": { \"params\": { \"id\": \"JafvB11cV61f\" } } } }\n```\n\nExample: Réponse\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"success\\\":true}\" }], \"structuredContent\": { \"success\": true } } }\n```\n\n### { method: 'server/discover' }\n\nType: `method`\n\nDécrit le serveur.\n\nReturns: `Object` Le résultat.\n\nRenvoie `resultType: 'complete'`, `supportedVersions: ['2026-07-28']`, `capabilities: { tools: {} }` et les informations du serveur (`CONF.name`, `CONF.version`) dans `_meta['io.modelcontextprotocol/serverInfo']`.\n\n### Total.mcp.auth = function($)\n\nType: `delegate`\n\nDécide qui peut utiliser l'endpoint.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | La requête ; appelle `$.success()` ou `$.invalid()`. |\n\nS'exécute pour chaque requête vers `POST /$mcp/` et `GET /$mcp/client.js`. `$.token` (et `$.auth`) est l'en-tête `Authorization` sans `Bearer `, et `$` a `headers`, `query`, `ip`, `ua` et `url`. Appelle `$.success(user)` pour accepter la requête ou `$.invalid()` pour la refuser avec `401`. Les outils s'exécutent avec `user` et `Total.mcp.filter` le reçoit comme `$.user` ; `$.success()` sans utilisateur donne un utilisateur vide `{}`. La fonction par défaut accepte chaque requête avec l'utilisateur `{ id: 'ai', name: 'AI', sa: true }`. Définis-la dans un fichier de `definitions/`.\n\nExample: Tokens depuis la configuration\n```js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token && $.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader', permissions: ['tasks_read'] });\n\telse\n\t\t$.invalid();\n};\n```\n\n### Total.mcp.filter = function(tool, $)\n\nType: `delegate`\n\nDécide quels outils un appelant voit et peut exécuter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tool` | `Object` | yes |  | La définition de l'outil : `name`, `description`, `inputSchema`, `outputSchema`. |\n| `$` | `Options` | yes |  | La requête ; `$.user` est l'appelant. |\n\nReturns: `Boolean` `true` quand l'appelant peut utiliser l'outil.\n\nFacultative, `null` par défaut (chaque appelant a tous les outils). La fonction reçoit la définition d'un outil (un élément de `Total.mcp.tools`) et `$` avec l'utilisateur de `Total.mcp.auth` dans `$.user`, et renvoie `true` pour autoriser l'outil. Un outil non autorisé est omis de `tools/list` et de `GET /$mcp/client.js`, et `tools/call` y répond avec `-32602` (`Unknown tool`), comme s'il n'existait pas.\n\nExample: Outils d'administration réservés aux admins\n```js\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n### Total.mcp.tools\n\nType: `property`\n\nLes définitions des outils.\n\nReturns: `Array`\n\nUn tableau avec la définition de chaque action qui a `mcp: true`, les mêmes objets que ceux que renvoie `tools/list`. Il est reconstruit 200 ms après chaque `NEWACTION()`.\n\nExample: Noms\n```js\nconsole.log(Total.mcp.tools.map(tool => tool.name));\n// ['Tasks_create', 'Tasks_list', 'Tasks_remove']\n```\n\n### Total.mcp.versions\n\nType: `property`\n\nLes versions du protocole prises en charge.\n\nReturns: `Array`\n\nUn tableau, la plus récente en premier : `['2026-07-28', '2025-11-25', '2025-06-18', '2025-03-26']`. `initialize` répond avec la version du client quand elle se trouve dans la liste, sinon avec la première.\n\n### F.actions[name].toAITool()\n\nType: `method`\n\nRenvoie la définition d'outil d'une action.\n\nReturns: `Object` La définition de l'outil.\n\nRenvoie `{ name, description, inputSchema, [outputSchema] }` au format de `tools/list`. Elle fonctionne pour n'importe quelle action, même sans `mcp: true`, pour que tu puisses toi-même passer des actions comme outils à un modèle d'IA.\n\nExample: Un outil\n```js\nvar tool = F.actions['Tasks|remove'].toAITool();\n// { name: 'Tasks_remove', description: 'Removes a task', inputSchema: { type: 'object', properties: { params: {...} }, required: ['params'] } }\n```\n","entries":[{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"type","name":"POST /$mcp/","signature":"POST /$mcp/","since":"","deprecated":false},{"type":"type","name":"GET /$mcp/client.js","signature":"GET /$mcp/client.js[?q=words]","since":"","deprecated":false},{"type":"method","name":"initialize","signature":"{ method: 'initialize', params: { protocolVersion } }","since":"","deprecated":false},{"type":"method","name":"ping","signature":"{ method: 'ping' }","since":"","deprecated":false},{"type":"method","name":"tools/list","signature":"{ method: 'tools/list' }","since":"","deprecated":false},{"type":"method","name":"tools/call","signature":"{ method: 'tools/call', params: { name, arguments: { input, query, params } } }","since":"","deprecated":false},{"type":"method","name":"server/discover","signature":"{ method: 'server/discover' }","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.auth","signature":"Total.mcp.auth = function($)","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.filter","signature":"Total.mcp.filter = function(tool, $)","since":"","deprecated":false},{"type":"property","name":"Total.mcp.tools","signature":"Total.mcp.tools","since":"","deprecated":false},{"type":"property","name":"Total.mcp.versions","signature":"Total.mcp.versions","since":"","deprecated":false},{"type":"method","name":"action.toAITool()","signature":"F.actions[name].toAITool()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JafwWWJIx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Server MCP","summary":"La chiave $mcp, l'opzione mcp delle azioni, i metodi JSON-RPC di POST /$mcp/, il client di GET /$mcp/client.js e Total.mcp.","markdown":"---\ntitle: Server MCP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/mcp-server/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# Server MCP\n\n> La chiave $mcp, l'opzione mcp delle azioni, i metodi JSON-RPC di POST /$mcp/, il client di GET /$mcp/client.js e Total.mcp.\n\nLa chiave `$mcp`, l'opzione `mcp` delle azioni, i metodi JSON-RPC di `POST /$mcp/`, il client JavaScript di `GET /$mcp/client.js` (modalità codice) e l'oggetto `Total.mcp`. La guida [Server MCP](../../guides/mcp-server/) spiega come le azioni diventano tool e come proteggere l'endpoint.\n\n## API\n\n### $mcp : Boolean\n\nType: `config`\n\nAttiva il server MCP.\n\nReturns: `Boolean`\n\n`true` crea le route `POST /$mcp/` e `GET /$mcp/client.js` quando l'applicazione è pronta. Impostala nel file `config` o nel codice prima dell'avvio.\n\nPredefinito: `false`.\n\nExample: Nel file config\n```text\n$mcp : true\n```\n\n### mcp: Boolean\n\nType: `config`\n\nRende un'azione un tool.\n\nReturns: `Boolean`\n\nUn'azione con `mcp: true` viene elencata da `tools/list` ed eseguita con `tools/call`. Il nome del tool è il nome dell'azione con ogni carattere diverso da `A-Z`, `a-z`, `0-9`, `_` e `-` sostituito da `_` (al massimo 64 caratteri). La descrizione è l'opzione `summary`, oppure l'opzione `name`. Gli schemi `input`, `query` e `params` diventano gli argomenti e `output` lo schema di output.\n\nExample: Un tool\n```js\nNEWACTION('Tasks|list', {\n\tsummary: 'Lists the tasks, 20 per page',\n\tmcp: true,\n\tquery: 'page:Number // The page number',\n\taction: function($) {\n\t\tNOSQL('tasks').find().paginate($.query.page || 1, 20).callback($);\n\t}\n});\n// the tool Tasks_list\n```\n\n### POST /$mcp/\n\nType: `type`\n\nL'endpoint del server MCP.\n\nUn endpoint JSON-RPC 2.0: un messaggio nel body, una risposta JSON. Il body può essere grande fino a 10 MB e la richiesta può durare fino a 300 secondi. Un messaggio senza `id` è una notifica e riceve lo stato `202` senza body. Un messaggio senza `\"jsonrpc\": \"2.0\"` o `method`, oppure un array, riceve l'errore `-32600`; un metodo sconosciuto riceve `-32601`. Quando `Total.mcp.auth` rifiuta la richiesta, lo stato è `401` e l'errore `-32001`.\n\nExample: Una richiesta\n```js\nawait fetch('http://localhost:8000/$mcp/', {\n\tmethod: 'POST',\n\theaders: { 'Content-Type': 'application/json', Authorization: 'Bearer 6f1d2c' },\n\tbody: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' })\n});\n```\n\n### GET /$mcp/client.js[?q=words]\n\nType: `type`\n\nI tool come client JavaScript, per la modalità codice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `q` | `String` | no |  | Parole che il nome o la descrizione di un tool devono contenere. |\n\nReturns: `String` Il sorgente JavaScript.\n\nRestituisce un modulo CommonJS (`text/javascript`) creato dai tool che il chiamante può usare: una funzione per tool, con JSDoc per i suoi argomenti (`input`, `query`, `params` e i loro campi, con i messaggi `//` come descrizioni) e per il suo risultato. `require('./client.js')(token, [url])` restituisce un oggetto con queste funzioni. Ogni funzione invia `tools/call` a `POST /$mcp/` con `Authorization: Bearer <token>`, si risolve con l'output del tool (`structuredContent`, o il testo interpretato) e lancia un `Error` con il messaggio di un errore del tool. L'`url` predefinito è l'indirizzo da cui è stato scaricato il file. Richiede Node.js 18 o successivo (`fetch`) e nessun pacchetto.\n\n`?q=words` restituisce solo i tool il cui nome o la cui descrizione contengono tutte le parole (senza distinzione tra maiuscole e minuscole). La richiesta passa da `Total.mcp.auth` (una rifiutata riceve `401` e il testo `Unauthorized`) e da `Total.mcp.filter`, così il client ha gli stessi tool di `tools/list`. Sul server non viene eseguito nulla: lo script gira dove gira l'agente, e ogni chiamata è una normale chiamata di tool.\n\nExample: Scaricare e usare\n```js\n// curl -H 'Authorization: Bearer TOKEN' 'https://app.example.com/$mcp/client.js?q=tasks' > client.js\nconst api = require('./client.js')('TOKEN');\n\nconst task = await api.Tasks_create({ input: { name: 'Call Peter' } });\nconsole.log(task.id);\n```\n\nExample: Una funzione del file\n```js\n/**\n * Creates a task and returns its ID\n * @param {Object} args\n * @param {Object} args.input Payload (request body) passed to this action.\n * @param {String} args.input.name The name of the task\n * @param {String} [args.input.due] When the task must be done (ISO date)\n * @returns {Promise<{ id: ?String }>}\n */\napi.Tasks_create = args => call(\"Tasks_create\", args);\n```\n\n### { method: 'initialize', params: { protocolVersion } }\n\nType: `method`\n\nAvvia una sessione del client.\n\nReturns: `Object` Il risultato.\n\nRestituisce `protocolVersion` (la versione del client quando è in `Total.mcp.versions`, altrimenti la prima), `capabilities: { tools: {} }` e `serverInfo: { name: CONF.name, version: CONF.version }`. Il server non mantiene alcuno stato tra le richieste.\n\nExample: Risposta\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n### { method: 'ping' }\n\nType: `method`\n\nControlla la connessione.\n\nReturns: `Object` Un oggetto vuoto.\n\nRestituisce un risultato vuoto `{}`.\n\n### { method: 'tools/list' }\n\nType: `method`\n\nElenca i tool.\n\nReturns: `Object` Il risultato.\n\nRestituisce `{ resultType: 'complete', tools: [...] }` con le definizioni di tutte le azioni che hanno `mcp: true` (`Total.mcp.tools`) e che `Total.mcp.filter` consente al chiamante. Ogni definizione ha `name`, `description` (quando l'azione ha `summary` o `name`), `inputSchema` e, con uno schema `output`, `outputSchema`.\n\n### { method: 'tools/call', params: { name, arguments: { input, query, params } } }\n\nType: `method`\n\nEsegue un tool.\n\nReturns: `Object` Il risultato.\n\nEsegue l'azione del tool con `ACTION()`. `arguments.input` (o `arguments.data`) è il payload, `arguments.query` e `arguments.params` sono la query e i parametri URL. L'azione non ha controller, il suo utente è l'utente con cui `Total.mcp.auth` ha accettato la richiesta (`{ id: 'ai', name: 'AI', sa: true }` con la funzione predefinita) e `$.config.id` è l'`id` dalla query string dell'endpoint. Il risultato ha `content: [{ type: 'text', text }]` con la risposta (una stringa così com'è, gli altri valori come JSON) e, per un oggetto, `structuredContent`. Gli errori dell'azione sono un risultato con `isError: true`, anche quando l'azione lancia un'eccezione (il testo è `Tool execution failed`, o `500: Internal Server Error` per un'azione `async`, e l'eccezione va nel log degli errori). Un tool sconosciuto, un tool che `Total.mcp.filter` nasconde al chiamante, o argomenti che non sono un oggetto danno l'errore `-32602`.\n\nExample: Chiamata\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_remove\", \"arguments\": { \"params\": { \"id\": \"JafvB11cV61f\" } } } }\n```\n\nExample: Risposta\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"success\\\":true}\" }], \"structuredContent\": { \"success\": true } } }\n```\n\n### { method: 'server/discover' }\n\nType: `method`\n\nDescrive il server.\n\nReturns: `Object` Il risultato.\n\nRestituisce `resultType: 'complete'`, `supportedVersions: ['2026-07-28']`, `capabilities: { tools: {} }` e le informazioni del server (`CONF.name`, `CONF.version`) in `_meta['io.modelcontextprotocol/serverInfo']`.\n\n### Total.mcp.auth = function($)\n\nType: `delegate`\n\nDecide chi può usare l'endpoint.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | La richiesta; chiama `$.success()` o `$.invalid()`. |\n\nViene eseguita per ogni richiesta a `POST /$mcp/` e `GET /$mcp/client.js`. `$.token` (e `$.auth`) è l'header `Authorization` senza `Bearer `, e `$` ha `headers`, `query`, `ip`, `ua` e `url`. Chiama `$.success(user)` per accettare la richiesta o `$.invalid()` per rifiutarla con `401`. I tool vengono eseguiti come `user` e `Total.mcp.filter` lo riceve come `$.user`; `$.success()` senza utente dà un utente vuoto `{}`. La funzione predefinita accetta ogni richiesta con l'utente `{ id: 'ai', name: 'AI', sa: true }`. Impostala in un file in `definitions/`.\n\nExample: Token dalla configurazione\n```js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token && $.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader', permissions: ['tasks_read'] });\n\telse\n\t\t$.invalid();\n};\n```\n\n### Total.mcp.filter = function(tool, $)\n\nType: `delegate`\n\nDecide quali tool un chiamante vede e può eseguire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tool` | `Object` | yes |  | La definizione del tool: `name`, `description`, `inputSchema`, `outputSchema`. |\n| `$` | `Options` | yes |  | La richiesta; `$.user` è il chiamante. |\n\nReturns: `Boolean` `true` quando il chiamante può usare il tool.\n\nFacoltativa, `null` per impostazione predefinita (ogni chiamante ha tutti i tool). La funzione riceve la definizione di un tool (un elemento di `Total.mcp.tools`) e `$` con l'utente di `Total.mcp.auth` in `$.user`, e restituisce `true` per consentire il tool. Un tool non consentito viene escluso da `tools/list` e da `GET /$mcp/client.js`, e `tools/call` gli risponde con `-32602` (`Unknown tool`), come se non esistesse.\n\nExample: Tool di amministrazione solo per gli amministratori\n```js\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n### Total.mcp.tools\n\nType: `property`\n\nLe definizioni dei tool.\n\nReturns: `Array`\n\nUn array con la definizione di ogni azione che ha `mcp: true`, gli stessi oggetti che restituisce `tools/list`. Viene ricostruito 200 ms dopo ogni `NEWACTION()`.\n\nExample: Nomi\n```js\nconsole.log(Total.mcp.tools.map(tool => tool.name));\n// ['Tasks_create', 'Tasks_list', 'Tasks_remove']\n```\n\n### Total.mcp.versions\n\nType: `property`\n\nLe versioni del protocollo supportate.\n\nReturns: `Array`\n\nUn array, dalla più recente: `['2026-07-28', '2025-11-25', '2025-06-18', '2025-03-26']`. `initialize` risponde con la versione del client quando è nell'elenco, altrimenti con la prima.\n\n### F.actions[name].toAITool()\n\nType: `method`\n\nRestituisce la definizione di tool di un'azione.\n\nReturns: `Object` La definizione del tool.\n\nRestituisce `{ name, description, inputSchema, [outputSchema] }` nel formato di `tools/list`. Funziona per qualsiasi azione, anche senza `mcp: true`, così puoi passare tu stesso le azioni come tool a un modello AI.\n\nExample: Un tool\n```js\nvar tool = F.actions['Tasks|remove'].toAITool();\n// { name: 'Tasks_remove', description: 'Removes a task', inputSchema: { type: 'object', properties: { params: {...} }, required: ['params'] } }\n```\n","entries":[{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"type","name":"POST /$mcp/","signature":"POST /$mcp/","since":"","deprecated":false},{"type":"type","name":"GET /$mcp/client.js","signature":"GET /$mcp/client.js[?q=words]","since":"","deprecated":false},{"type":"method","name":"initialize","signature":"{ method: 'initialize', params: { protocolVersion } }","since":"","deprecated":false},{"type":"method","name":"ping","signature":"{ method: 'ping' }","since":"","deprecated":false},{"type":"method","name":"tools/list","signature":"{ method: 'tools/list' }","since":"","deprecated":false},{"type":"method","name":"tools/call","signature":"{ method: 'tools/call', params: { name, arguments: { input, query, params } } }","since":"","deprecated":false},{"type":"method","name":"server/discover","signature":"{ method: 'server/discover' }","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.auth","signature":"Total.mcp.auth = function($)","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.filter","signature":"Total.mcp.filter = function(tool, $)","since":"","deprecated":false},{"type":"property","name":"Total.mcp.tools","signature":"Total.mcp.tools","since":"","deprecated":false},{"type":"property","name":"Total.mcp.versions","signature":"Total.mcp.versions","since":"","deprecated":false},{"type":"method","name":"action.toAITool()","signature":"F.actions[name].toAITool()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JafwWWJIx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/mcp-server/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"MCP server","summary":"Kľúč $mcp, možnosť mcp akcií, JSON-RPC metódy POST /$mcp/, klient z GET /$mcp/client.js a Total.mcp.","markdown":"---\ntitle: MCP server\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/mcp-server/\nupdated: 2026-11-19T16:17:07.153Z\n---\n\n# MCP server\n\n> Kľúč $mcp, možnosť mcp akcií, JSON-RPC metódy POST /$mcp/, klient z GET /$mcp/client.js a Total.mcp.\n\nKľúč `$mcp`, možnosť `mcp` akcií, JSON-RPC metódy `POST /$mcp/`, JavaScript klient z `GET /$mcp/client.js` (code mode) a objekt `Total.mcp`. Návod [MCP server](../../guides/mcp-server/) vysvetľuje, ako sa z akcií stanú nástroje a ako chrániť endpoint.\n\n## API\n\n### $mcp : Boolean\n\nType: `config`\n\nZapne MCP server.\n\nReturns: `Boolean`\n\n`true` vytvorí routy `POST /$mcp/` a `GET /$mcp/client.js`, keď je aplikácia pripravená. Nastav ho v súbore `config` alebo v kóde pred štartom.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\n$mcp : true\n```\n\n### mcp: Boolean\n\nType: `config`\n\nUrobí z akcie nástroj.\n\nReturns: `Boolean`\n\nAkciu s `mcp: true` vypíše `tools/list` a spúšťa sa cez `tools/call`. Názov nástroja je názov akcie, v ktorom je každý znak okrem `A-Z`, `a-z`, `0-9`, `_` a `-` nahradený znakom `_` (najviac 64 znakov). Popis je možnosť `summary` alebo možnosť `name`. Schémy `input`, `query` a `params` sa stanú argumentmi a `output` výstupnou schémou.\n\nExample: Nástroj\n```js\nNEWACTION('Tasks|list', {\n\tsummary: 'Lists the tasks, 20 per page',\n\tmcp: true,\n\tquery: 'page:Number // The page number',\n\taction: function($) {\n\t\tNOSQL('tasks').find().paginate($.query.page || 1, 20).callback($);\n\t}\n});\n// the tool Tasks_list\n```\n\n### POST /$mcp/\n\nType: `type`\n\nEndpoint MCP servera.\n\nEndpoint JSON-RPC 2.0: jedna správa v tele, jedna JSON odpoveď. Telo môže mať až 10 MB a požiadavka môže trvať až 300 sekúnd. Správa bez `id` je notifikácia a dostane stav `202` bez tela. Správa bez `\"jsonrpc\": \"2.0\"` alebo `method`, alebo pole, dostane chybu `-32600`; neznáma metóda dostane `-32601`. Keď `Total.mcp.auth` požiadavku odmietne, stav je `401` a chyba `-32001`.\n\nExample: Požiadavka\n```js\nawait fetch('http://localhost:8000/$mcp/', {\n\tmethod: 'POST',\n\theaders: { 'Content-Type': 'application/json', Authorization: 'Bearer 6f1d2c' },\n\tbody: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' })\n});\n```\n\n### GET /$mcp/client.js[?q=words]\n\nType: `type`\n\nNástroje ako JavaScript klient, pre code mode.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `q` | `String` | no |  | Slová, ktoré musí obsahovať názov alebo popis nástroja. |\n\nReturns: `String` Zdrojový kód JavaScriptu.\n\nVráti CommonJS modul (`text/javascript`) vytvorený z nástrojov, ktoré volajúci smie používať: jednu funkciu pre každý nástroj, s JSDoc pre jej argumenty (`input`, `query`, `params` a ich polia, so správami `//` ako popismi) a pre jej výsledok. `require('./client.js')(token, [url])` vráti objekt s týmito funkciami. Každá funkcia pošle `tools/call` na `POST /$mcp/` s `Authorization: Bearer <token>`, vyrieši sa s výstupom nástroja (`structuredContent` alebo sparsovaný text) a pri chybe nástroja vyhodí `Error` so správou chyby. Predvolená `url` je adresa, z ktorej sa súbor stiahol. Potrebuje Node.js 18 alebo novší (`fetch`) a žiadne balíky.\n\n`?q=words` vráti iba nástroje, ktorých názov alebo popis obsahuje všetky slová (bez ohľadu na veľkosť písmen). Požiadavka prejde cez `Total.mcp.auth` (odmietnutá dostane `401` a text `Unauthorized`) a `Total.mcp.filter`, takže klient má tie isté nástroje ako `tools/list`. Na serveri sa nič nespúšťa: skript beží tam, kde beží agent, a každé volanie je bežné volanie nástroja.\n\nExample: Stiahnutie a použitie\n```js\n// curl -H 'Authorization: Bearer TOKEN' 'https://app.example.com/$mcp/client.js?q=tasks' > client.js\nconst api = require('./client.js')('TOKEN');\n\nconst task = await api.Tasks_create({ input: { name: 'Call Peter' } });\nconsole.log(task.id);\n```\n\nExample: Funkcia zo súboru\n```js\n/**\n * Creates a task and returns its ID\n * @param {Object} args\n * @param {Object} args.input Payload (request body) passed to this action.\n * @param {String} args.input.name The name of the task\n * @param {String} [args.input.due] When the task must be done (ISO date)\n * @returns {Promise<{ id: ?String }>}\n */\napi.Tasks_create = args => call(\"Tasks_create\", args);\n```\n\n### { method: 'initialize', params: { protocolVersion } }\n\nType: `method`\n\nZačne session klienta.\n\nReturns: `Object` Výsledok.\n\nVráti `protocolVersion` (verziu klienta, keď je v `Total.mcp.versions`, inak prvú z nich), `capabilities: { tools: {} }` a `serverInfo: { name: CONF.name, version: CONF.version }`. Server medzi požiadavkami nedrží žiadny stav.\n\nExample: Odpoveď\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": { \"protocolVersion\": \"2025-06-18\", \"capabilities\": { \"tools\": {} }, \"serverInfo\": { \"name\": \"Tasks\", \"version\": \"1.0\" } } }\n```\n\n### { method: 'ping' }\n\nType: `method`\n\nSkontroluje pripojenie.\n\nReturns: `Object` Prázdny objekt.\n\nVráti prázdny výsledok `{}`.\n\n### { method: 'tools/list' }\n\nType: `method`\n\nVypíše nástroje.\n\nReturns: `Object` Výsledok.\n\nVráti `{ resultType: 'complete', tools: [...] }` s definíciami všetkých akcií, ktoré majú `mcp: true` (`Total.mcp.tools`) a ktoré `Total.mcp.filter` volajúcemu povolí. Každá definícia má `name`, `description` (keď má akcia `summary` alebo `name`), `inputSchema` a so schémou `output` aj `outputSchema`.\n\n### { method: 'tools/call', params: { name, arguments: { input, query, params } } }\n\nType: `method`\n\nSpustí nástroj.\n\nReturns: `Object` Výsledok.\n\nSpustí akciu nástroja cez `ACTION()`. `arguments.input` (alebo `arguments.data`) je payload, `arguments.query` a `arguments.params` sú query a URL parametre. Akcia nemá controller, jej používateľ je ten, s ktorým `Total.mcp.auth` požiadavku prijal (`{ id: 'ai', name: 'AI', sa: true }` s predvolenou funkciou), a `$.config.id` je `id` z query stringu endpointu. Výsledok má `content: [{ type: 'text', text }]` s odpoveďou (reťazec tak, ako je, ostatné hodnoty ako JSON) a pre objekt aj `structuredContent`. Chyby akcie sú výsledok s `isError: true`, aj keď akcia vyhodí výnimku (text je `Tool execution failed`, alebo `500: Internal Server Error` pri akcii `async`, a výnimka ide do logu chýb). Neznámy nástroj, nástroj, ktorý `Total.mcp.filter` pred volajúcim skryje, alebo argumenty, ktoré nie sú objekt, vrátia chybu `-32602`.\n\nExample: Volanie\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"method\": \"tools/call\", \"params\": { \"name\": \"Tasks_remove\", \"arguments\": { \"params\": { \"id\": \"JafvB11cV61f\" } } } }\n```\n\nExample: Odpoveď\n```json\n{ \"jsonrpc\": \"2.0\", \"id\": 5, \"result\": { \"resultType\": \"complete\", \"content\": [{ \"type\": \"text\", \"text\": \"{\\\"success\\\":true}\" }], \"structuredContent\": { \"success\": true } } }\n```\n\n### { method: 'server/discover' }\n\nType: `method`\n\nOpíše server.\n\nReturns: `Object` Výsledok.\n\nVráti `resultType: 'complete'`, `supportedVersions: ['2026-07-28']`, `capabilities: { tools: {} }` a informácie o serveri (`CONF.name`, `CONF.version`) v `_meta['io.modelcontextprotocol/serverInfo']`.\n\n### Total.mcp.auth = function($)\n\nType: `delegate`\n\nRozhoduje, kto smie používať endpoint.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Options` | yes |  | Požiadavka; zavolaj `$.success()` alebo `$.invalid()`. |\n\nSpustí sa pre každú požiadavku na `POST /$mcp/` a `GET /$mcp/client.js`. `$.token` (a `$.auth`) je hlavička `Authorization` bez `Bearer ` a `$` má `headers`, `query`, `ip`, `ua` a `url`. Zavolaj `$.success(user)`, aby si požiadavku prijal, alebo `$.invalid()`, aby si ju odmietol s `401`. Nástroje bežia ako `user` a `Total.mcp.filter` ho dostane ako `$.user`; `$.success()` bez používateľa dá prázdneho používateľa `{}`. Predvolená funkcia prijme každú požiadavku s používateľom `{ id: 'ai', name: 'AI', sa: true }`. Nastav ju v súbore v `definitions/`.\n\nExample: Tokeny z konfigurácie\n```js\nTotal.mcp.auth = function($) {\n\tif ($.token && $.token === CONF.mcp_admin)\n\t\t$.success({ id: 'admin', name: 'Admin', sa: true });\n\telse if ($.token && $.token === CONF.mcp_reader)\n\t\t$.success({ id: 'reader', name: 'Reader', permissions: ['tasks_read'] });\n\telse\n\t\t$.invalid();\n};\n```\n\n### Total.mcp.filter = function(tool, $)\n\nType: `delegate`\n\nRozhoduje, ktoré nástroje volajúci vidí a smie spustiť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tool` | `Object` | yes |  | Definícia nástroja: `name`, `description`, `inputSchema`, `outputSchema`. |\n| `$` | `Options` | yes |  | Požiadavka; `$.user` je volajúci. |\n\nReturns: `Boolean` `true`, keď volajúci smie nástroj používať.\n\nVoliteľné, predvolene `null` (každý volajúci má všetky nástroje). Funkcia dostane definíciu nástroja (položku `Total.mcp.tools`) a `$` s používateľom z `Total.mcp.auth` v `$.user` a vráti `true`, aby nástroj povolila. Nepovolený nástroj sa vynechá z `tools/list` aj z `GET /$mcp/client.js` a `tools/call` naň odpovie chybou `-32602` (`Unknown tool`), ako keby neexistoval.\n\nExample: Administrátorské nástroje iba pre administrátorov\n```js\nTotal.mcp.filter = function(tool, $) {\n\treturn !tool.name.startsWith('Admin_') || $.user.sa;\n};\n```\n\n### Total.mcp.tools\n\nType: `property`\n\nDefinície nástrojov.\n\nReturns: `Array`\n\nPole s definíciou každej akcie, ktorá má `mcp: true`, tie isté objekty, ktoré vracia `tools/list`. Zostaví sa znova 200 ms po každom `NEWACTION()`.\n\nExample: Názvy\n```js\nconsole.log(Total.mcp.tools.map(tool => tool.name));\n// ['Tasks_create', 'Tasks_list', 'Tasks_remove']\n```\n\n### Total.mcp.versions\n\nType: `property`\n\nPodporované verzie protokolu.\n\nReturns: `Array`\n\nPole, najnovšia prvá: `['2026-07-28', '2025-11-25', '2025-06-18', '2025-03-26']`. `initialize` odpovie verziou klienta, keď je v zozname, inak prvou z nich.\n\n### F.actions[name].toAITool()\n\nType: `method`\n\nVráti definíciu nástroja akcie.\n\nReturns: `Object` Definícia nástroja.\n\nVráti `{ name, description, inputSchema, [outputSchema] }` vo formáte `tools/list`. Funguje pre akúkoľvek akciu, aj bez `mcp: true`, takže môžeš akcie odovzdať AI modelu ako nástroje sám.\n\nExample: Jeden nástroj\n```js\nvar tool = F.actions['Tasks|remove'].toAITool();\n// { name: 'Tasks_remove', description: 'Removes a task', inputSchema: { type: 'object', properties: { params: {...} }, required: ['params'] } }\n```\n","entries":[{"type":"config","name":"$mcp","signature":"$mcp : Boolean","since":"","deprecated":false},{"type":"config","name":"NEWACTION.mcp","signature":"mcp: Boolean","since":"","deprecated":false},{"type":"type","name":"POST /$mcp/","signature":"POST /$mcp/","since":"","deprecated":false},{"type":"type","name":"GET /$mcp/client.js","signature":"GET /$mcp/client.js[?q=words]","since":"","deprecated":false},{"type":"method","name":"initialize","signature":"{ method: 'initialize', params: { protocolVersion } }","since":"","deprecated":false},{"type":"method","name":"ping","signature":"{ method: 'ping' }","since":"","deprecated":false},{"type":"method","name":"tools/list","signature":"{ method: 'tools/list' }","since":"","deprecated":false},{"type":"method","name":"tools/call","signature":"{ method: 'tools/call', params: { name, arguments: { input, query, params } } }","since":"","deprecated":false},{"type":"method","name":"server/discover","signature":"{ method: 'server/discover' }","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.auth","signature":"Total.mcp.auth = function($)","since":"","deprecated":false},{"type":"delegate","name":"Total.mcp.filter","signature":"Total.mcp.filter = function(tool, $)","since":"","deprecated":false},{"type":"property","name":"Total.mcp.tools","signature":"Total.mcp.tools","since":"","deprecated":false},{"type":"property","name":"Total.mcp.versions","signature":"Total.mcp.versions","since":"","deprecated":false},{"type":"method","name":"action.toAITool()","signature":"F.actions[name].toAITool()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:07.153Z"}
{"id":"JafwwLBgx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/utilities/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Utilities","summary":"U/Utils functions, global helpers (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), shared objects, CACHE, MEMORIZE, BACKUP, RESTORE and PATH.","markdown":"---\ntitle: Utilities\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/utilities/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Utilities\n\n> U/Utils functions, global helpers (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), shared objects, CACHE, MEMORIZE, BACKUP, RESTORE and PATH.\n\nThis page lists the global helpers, the shared global objects, the in-memory `CACHE`, the `PATH` functions and the functions of the `U` (`Utils`) module that applications use. The guide [Utilities](../../guides/utilities/) explains how they fit together, with examples. The methods added to `String`, `Number`, `Date` and `Array` are in [Prototypes](../prototypes/).\n\n## API\n\n### U\n\nType: `property`\n\nThe Utils module as a global object.\n\nReturns: `Object` The Utils module.\n\nAll functions of `utils.js` are available through `U` and its alias `Utils` (both point to the same object). This page documents the functions that applications use; the others are used by the framework itself.\n\nExample: Use a helper\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\nvar same = Utils === U;           // true\n```\n\n### UID()\n\nType: `method`\n\nReturns a new unique identifier.\n\nReturns: `String` For example `JacVuE1cn61f`.\n\nThe identifier is a short string of letters and digits: a base-62 time stamp (in tenths of a second), an internal counter, a random character chosen at start-up (changed every minute), the length of the time part, a parity digit and the letter `f`. Identifiers created later sort after earlier ones in most cases. The `uid` validator of the framework (`DEF.validators.uid`) accepts them.\n\nExample: A new record\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\nNOSQL('products').insert(model);\n```\n\n### GUID([length])\n\nType: `method`\n\nReturns a UUID-like string, or a random string of a given length.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | The number of characters. Omit it for the UUID-like format. |\n\nReturns: `String`\n\nWithout `length`, it returns a string in the shape `xxxxxxxx-xxxx-Nxxx-Yxxx-xxxxxxxxxxxx` (36 characters) built from the current time and random hexadecimal digits. With `length`, it returns that many random characters from `0-9` and `a-z`.\n\nExample: Tokens\n```js\nvar guid = GUID();       // '1a1e0561-0561-4c86-8eaf-d9a327a65943'\nvar token = GUID(30);    // 30 random characters\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nHashes a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The text to hash. |\n| `type` | `String` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32` or `crc32unsigned`. |\n\nReturns: `Number|String` A number without a type, a hexadecimal string for md5/sha types.\n\nWithout `type`, it returns an unsigned 32-bit number computed from the string (fast, not cryptographic). With a type it returns the hash as a hexadecimal string (`md5`, `sha1`, `sha256`, `sha512`) or a CRC32 number (`crc32`, `crc32unsigned`). `value` must be a string; convert numbers with `+ ''` first.\n\nExample: Hashes\n```js\nHASH('abc');            // 96354\nHASH('abc', 'md5');     // '900150983cd24fb0d6963f7d28e17f72'\nHASH(email, 'sha256');\n```\n\n### CLONE(obj, [skip], [nofunctions])\n\nType: `method`\n\nMakes a deep copy of an object or an array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array` | yes |  | The value to copy. Other values are returned unchanged. |\n| `skip` | `Object` | no |  | Keys to leave out, e.g. `{ password: 1 }`. |\n| `nofunctions` | `Boolean` | no | `false` | `true` leaves out functions. |\n\nReturns: `Object|Array` The copy.\n\nNested objects and arrays are copied, buffers in object properties are duplicated, and dates, errors and other non-object values are kept as they are. `skip` is an object whose keys are left out of the copy at every level. With `nofunctions`, properties that contain functions are left out too.\n\nExample: Copy without a key\n```js\nvar user = { id: 'abc', name: 'Peter', password: 'secret', address: { city: 'Bratislava' } };\nvar safe = CLONE(user, { password: 1 });\nsafe.address.city = 'Prague';  // user.address.city is still 'Bratislava'\n```\n\n### COPY(source, [target], [all])\n\nType: `method`\n\nCopies the keys of one object into another.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | The object to read. |\n| `target` | `Object` | no |  | The object to write into. |\n| `all` | `Boolean` | no | `true` | `false` writes only the keys that `target` already has. |\n\nReturns: `Object` The target (or the new copy).\n\nEach value of `source` is cloned and written into `target`. With `all` set to `false`, only keys that are already defined in `target` are written, so `target` works as a list of allowed fields. Without `target`, it returns a deep copy of `source`.\n\nExample: Allowed fields\n```js\nvar allowed = { name: '', email: '' };\nCOPY(this.body, allowed, false);\n// allowed contains only name and email from the body\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nCompares two arrays of objects by one property.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | The key that identifies an item, e.g. `id`. |\n| `db` | `Array` | yes |  | The current items (for example from the database). |\n| `form` | `Array` | yes |  | The new items (for example from a form). |\n\nReturns: `Object` `{ add: Array, upd: Array, rem: Array }`.\n\nItems are matched when their `prop` values are equal (`==`). The result has three arrays: `add` holds the items of `form` that are not in `db`, `upd` holds pairs `{ db, form }` of matched items, and `rem` holds the `prop` values of the `db` items that are not in `form`.\n\nExample: Synchronize items\n```js\nvar diff = DIFFARR('id', current, model.items);\n\nfor (var item of diff.add)\n\tNOSQL('items').insert(item);\n\nfor (var pair of diff.upd)\n\tNOSQL('items').modify(pair.form).where('id', pair.db.id);\n\nfor (var id of diff.rem)\n\tNOSQL('items').remove().where('id', id);\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nBuilds a query string from an object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | A URL, optionally with a method in front. |\n| `obj` | `Object` | yes |  | The values. |\n\nReturns: `String`\n\nKeys and values are URL-encoded. `null`, `undefined` and empty values are skipped, dates are written as ISO strings and arrays are joined with commas. Without `url`, the result starts with `?` (or is an empty string when nothing is left). With `url`, the query string is appended with `?` or `&`; the URL may start with an HTTP method (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `API`) followed by a space, as `REQUEST()` and `AJAX()` take it. The function is also `U.querify()`.\n\nExample: Query strings\n```js\nQUERIFY({ q: 'red shoes', page: 2 });           // '?q=red%20shoes&page=2'\nQUERIFY('/api/?lang=en', { page: 2 });         // '/api/?lang=en&page=2'\nQUERIFY('GET https://example.com/', { id: 5 }); // 'GET https://example.com/?id=5'\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method`\n\nCalls a callback-style function and returns a promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | A function whose last argument is a callback. |\n| `a` | `Object` | no |  | The first argument. |\n| `b` | `Object` | no |  | The second argument. |\n| `c` | `Object` | no |  | The third argument. |\n\nReturns: `Promise`\n\n`fn` is called with the arguments you pass (up to three) and a callback `function(err, response)`. The promise rejects with `err` or resolves with `response`. Pass only the arguments you need: an argument that is `undefined` ends the list.\n\nExample: Read a file\n```js\nvar Fs = require('fs');\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n\n### ERROR([name])\n\nType: `method`\n\nReturns a callback that logs errors.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The name shown with the error, e.g. the function that failed. |\n\nReturns: `Function` `function(err)`.\n\nThe returned function takes `err` as its first argument and, when it is set, passes it to the error handler of the framework (`DEF.onError`, which prints it and keeps it in the stats) with `name` as the source. Use it for callbacks whose result you do not need but whose errors you want to see.\n\nExample: Log a failed write\n```js\nFs.writeFile(PATH.databases('cache.json'), JSON.stringify(data), ERROR('cache.save'));\n```\n\n### print(...values)\n\nType: `method`\n\nWrites values to the console.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `values` | `Object` | yes |  | The values to print. |\n\n`print` is `console.log`. The framework uses it for its start-up information.\n\nExample: Print\n```js\nprint('Imported', count, 'products');\n```\n\n### NOW\n\nType: `property`\n\nA Date with the current time, refreshed every 5 seconds.\n\nReturns: `Date`\n\nThe framework assigns `new Date()` to `NOW` every 5 seconds once it is loaded, and also when it writes an error, an audit log or a cache item. Use it where a precision of a few seconds is enough: expirations, log lines, `dtcreated` fields. Do not change the object; assign a new date instead.\n\nExample: Expiration\n```js\nvar expire = NOW.add('1 hour');\nif (session.expire < NOW)\n\tdelete sessions[session.id];\n```\n\n### NOOP\n\nType: `property`\n\nAn empty function.\n\nReturns: `Function`\n\nUse it where a callback is required but you do not need the result. It is the same function as `U.noop`.\n\nExample: Ignore the result\n```js\nFs.unlink(filename, NOOP);\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nA frozen empty object; EMPTYARRAY is a frozen empty array.\n\nReturns: `Object`\n\n`EMPTYOBJECT` (`{}`) and `EMPTYARRAY` (`[]`) are created once and frozen with `Object.freeze()`, so they cannot be changed. Use them as default values instead of creating new objects, for example `var opt = options || EMPTYOBJECT;`. Never write into them: in strict mode a write throws.\n\nExample: Defaults\n```js\nfunction find(filter) {\n\tvar opt = filter || EMPTYOBJECT;\n\tvar tags = opt.tags || EMPTYARRAY;\n\treturn tags.length;\n}\n```\n\n### MAIN\n\nType: `property`\n\nA global object for the shared state of the application.\n\nReturns: `Object`\n\nThe framework creates `MAIN` as an empty object and does not use it. Store there what several files of your application share: settings loaded at start, open connections, counters. It is readable in views as `MAIN`.\n\nExample: Shared settings\n```js\n// definitions/settings.js\nMAIN.settings = MEMORIZE('settings');\n\n// a controller or an action\nvar title = MAIN.settings.title;\n```\n\n### REPO\n\nType: `property`\n\nA global object for shared data, also available in views.\n\nReturns: `Object`\n\nAn empty object that the framework creates at start (it is also `F.repo`). Views can read it as `REPO`, which makes it a good place for data that layouts need, for example a menu or the contact information.\n\nExample: Data for the layout\n```js\nREPO.menu = [{ name: 'Home', url: '/' }, { name: 'Contact', url: '/contact/' }];\n\n// views/layout.html\n// @{foreach m in REPO.menu}<a href=\"@{m.url}\">@{m.name}</a>@{end}\n```\n\n### FUNC\n\nType: `property`\n\nA global object for your shared functions.\n\nReturns: `Object`\n\nAn empty object for functions that several parts of the application use. Define them in `/definitions/` so they exist before the first request. Views can read `FUNC` too.\n\nExample: A shared function\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// anywhere\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nA global object for short-lived data, cleared every 5 minutes.\n\nReturns: `Object`\n\nEvery 5 minutes the framework replaces `TEMP` with a new empty object. Use it for small temporary data that may disappear at any time, such as one-time tokens or throttling counters. Always read it through the global (`TEMP.key`), not through a saved reference, because the object changes.\n\nExample: A short-lived token\n```js\nvar token = GUID(20);\nTEMP[token] = { userid: user.id };\n\n// later\nvar data = TEMP[token];\nif (!data)\n\t$.invalid('The token has expired');\n```\n\n### MODS\n\nType: `property`\n\nThe loaded modules by their id.\n\nReturns: `Object`\n\nEach `.js` file in `/modules/` is loaded at start and stored in `MODS` under its `exports.id`, or under the file name when it does not set one. Its `install()` function, if any, is called after loading. `MODS` is the same object as `F.modules` and can be read in views.\n\nExample: A module\n```js\n// modules/pricing.js\nexports.id = 'pricing';\nexports.vat = function(price) {\n\treturn price * 1.2;\n};\n\n// anywhere\nvar total = MODS.pricing.vat(100);\n```\n\n### CACHE.set(key, value, [expire])\n\nType: `method`\n\nStores a value in the in-memory cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key. |\n| `value` | `Object` | yes |  | Any value. |\n| `expire` | `String` | no | `'5 minutes'` | How long the value is valid. |\n\nThe value is kept in the memory of the process until it expires. `expire` is a duration in the form that `Date.add()` accepts (`'30 seconds'`, `'5 minutes'`, `'1 hour'`, `'2 days'`). The value is stored as it is, not copied: change it and the cached value changes too. Expired items are removed every minute.\n\nExample: Cache a result\n```js\nCACHE.set('products', items, '2 minutes');\n```\n\n### CACHE.get(key, [def])\n\nType: `method`\n\nReads a value from the in-memory cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key. |\n| `def` | `Object` | no |  | The value returned when the key is missing or expired. |\n\nReturns: `Object`\n\nReturns the value when it exists and has not expired; otherwise `def`. `CACHE.read()` is an alias.\n\nExample: Read or load\n```js\nvar items = CACHE.get('products');\nif (!items) {\n\titems = await DATA.find('nosql/products').promise($);\n\tCACHE.set('products', items, '2 minutes');\n}\n```\n\n### CACHE.remove(key)\n\nType: `method`\n\nRemoves one value from the in-memory cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key. |\n\nCall it when the cached data changes, so the next read loads fresh data.\n\nExample: Invalidate\n```js\nNOSQL('products').insert(model).callback(function() {\n\tCACHE.remove('products');\n});\n```\n\n### CACHE.reset([search])\n\nType: `method`\n\nRemoves many values, or all of them.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | no |  | A part of the keys, or a pattern. |\n\nReturns: `Number` The number of removed keys.\n\nWithout `search`, the whole cache is cleared. With a string, every key that contains it is removed; with a regular expression, every key that matches it. Returns the number of removed keys (0 when the whole cache is cleared).\n\nExample: Remove a group\n```js\nCACHE.set('products_1', a);\nCACHE.set('products_2', b);\nCACHE.reset('products_');  // 2\nCACHE.reset(/^user_/);\nCACHE.reset();             // everything\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method`\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 the last change and the write. |\n| `skip` | `String|Array` | no |  | Keys not written to the file, as an array or a comma-separated string. |\n\nReturns: `Object` The data with `save()` and `set(key, value)`.\n\nReads `databases/memorize_{name}.json` (or `databases/memorize.json` without a name) and returns its content as an object (an empty object when the file does not exist). The object gets two functions: `save()` schedules a write of the whole object, and `set(key, value)` assigns a value and calls `save()`. The write happens `delay` milliseconds after the last call, so many changes produce one write. `skip` lists keys that are not written. The arguments `delay` and `skip` may be swapped. Call `MEMORIZE()` once per name and keep the object; every call reads the file again.\n\nExample: Settings that survive restarts\n```js\nvar settings = MEMORIZE('settings', 'cache');\n\nsettings.set('title', 'My shop');\n\nsettings.counter = (settings.counter || 0) + 1;\nsettings.cache = {};      // not written\nsettings.save();\n```\n\n### BACKUP(filename, files, [callback], [filter])\n\nType: `method`\n\nPacks files and directories into one archive file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | The archive file to create (an existing file is replaced). |\n| `files` | `String|Array` | yes |  | A directory, or paths relative to the root. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`; return `true` to pack the path. |\n\nReturns: `Promise` When `callback` is omitted.\n\nWrites a text archive: one line per directory and one line per file, with the path and the gzip-compressed content in base64. `files` is a directory (everything in it is packed with paths relative to it) or an array of paths relative to the application root (files and whole directories). Names that contain `.git`, `.gitignore`, `.npmignore` or `.ds_store` are skipped. `filter(path, isdirectory)` gets each path (starting with `/`) and leaves it out when it returns a falsy value. `filename` can also be a writable stream. The callback gets `{ filename, files, size }`; without a callback, the function returns a promise.\n\nExample: Back up the uploads\n```js\nvar meta = await BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), null, function(path, isdir) {\n\treturn isdir || !path.endsWith('.tmp');\n});\nprint(meta.files, 'files', meta.size, 'bytes');\n```\n\nExample: Selected paths\n```js\nawait BACKUP(PATH.temp('app.backup'), ['config', 'databases', 'public/uploads']);\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nUnpacks an archive made by BACKUP().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | The archive. |\n| `target` | `String` | yes |  | The directory to unpack into. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nReturns: `Promise` When `callback` is omitted.\n\nCreates the directories and files of the archive inside `target`. `filename` can also be a readable stream. `filter(path, isdirectory)` is called for each item: for a directory, `false` skips creating it; for a file, return `false` to skip it, a string to write it under that path (relative to `target`), or nothing to keep its path. The callback gets `{ files, size, path }`; without a callback, the function returns a promise.\n\nExample: Restore\n```js\nvar meta = await RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'));\nprint('Restored', meta.files, 'files');\n```\n\nExample: Skip files on the way\n```js\nRESTORE(PATH.temp('app.backup'), PATH.root(), function(err) {\n\terr && print(err);\n}, function(path, isdir) {\n\tif (!isdir && path.startsWith('/config'))\n\t\treturn false;\n});\n```\n\n### PATH.root([path])\n\nType: `method`\n\nReturns the root directory of the application, or a path inside it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | A relative path. |\n\nReturns: `String` An absolute path.\n\nThe root is the directory of the application (where the start script runs). With `path`, it returns the root joined with it. Like the other directory functions of `PATH`, it creates the directory the first time it is called with a path. `PATH.public()`, `PATH.private()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()`, `PATH.templates()`, `PATH.flowstreams()` and `PATH.scripts()` work the same for their directories.\n\nExample: Paths\n```js\nPATH.root();                 // '/www/app'\nPATH.root('config');         // '/www/app/config'\nPATH.private('report.pdf');  // '/www/app/private/report.pdf'\n```\n\n### PATH.databases([path])\n\nType: `method`\n\nReturns the databases directory, or a path inside it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | A relative path. |\n\nReturns: `String` An absolute path.\n\nThe directory `/databases/` holds the files of NoSQL databases, `MEMORIZE()` files and other data of the application. It is created when you first ask for a path inside it.\n\nExample: A data file\n```js\nvar filename = PATH.databases('import.json');\nFs.writeFile(filename, JSON.stringify(data), NOOP);\n```\n\n### PATH.temp([path])\n\nType: `method`\n\nReturns the temporary directory, or a path inside it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | A relative path. |\n\nReturns: `String` An absolute path.\n\nThe directory `/tmp/` holds uploads, cached files and compiled assets. `PATH.tmp()` is an alias. When the application starts, the framework deletes its own temporary files there (`.js`, `.css`, `.html`, `.htm`, `.tmp` and `.upload` files). Keep data that must last in `/databases/`.\n\nExample: A temporary file\n```js\nvar filename = PATH.temp(UID() + '.csv');\n```\n\n### PATH.exists(path, [callback])\n\nType: `method`\n\nChecks whether a file or a directory exists.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | An absolute path. |\n| `callback` | `Function` | no |  | `function(exists, size, isfile)`. |\n\nReturns: `Promise<Boolean>` When `callback` is omitted.\n\nThe callback gets three arguments: `exists`, the size in bytes and `isfile` (`true` for a file, `false` for a directory). Without a callback, the function returns a promise that resolves with `exists`.\n\nExample: Check a file\n```js\nif (await PATH.exists(PATH.databases('settings.json')))\n\tprint('Settings found');\n\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isfile) {\n\tprint(exists, size, isfile);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nDeletes one or more files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|Array` | yes |  | An absolute path, or an array of paths. |\n| `callback` | `Function` | no |  | `function()`. |\n\nDeletes the files one after another and then calls the callback. Errors (for example a missing file) are ignored.\n\nExample: Delete files\n```js\nPATH.unlink([PATH.temp('a.csv'), PATH.temp('b.csv')], function() {\n\tprint('Removed');\n});\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nDeletes directories with everything in them.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|Array` | yes |  | An absolute path, or an array of paths. |\n| `callback` | `Function` | no |  | `function()`. |\n\nFor each directory, all files are deleted, then the subdirectories from the deepest one, then the directory itself. Then the callback is called.\n\nExample: Delete a directory\n```js\nPATH.rmdir(PATH.temp('export'), function() {\n\tprint('Directory removed');\n});\n```\n\n### Total.FsPromises\n\nType: `property`\n\nThe Node.js module `node:fs/promises`.\n\nReturns: `Object` The module `node:fs/promises`.\n\nThe promise version of the file system functions of Node.js, loaded by the framework. `F.FsPromises` is the same object, and `Total.Fs` (`F.Fs`) is the module `node:fs`.\n\nExample: Read and list\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\nvar files = await Total.FsPromises.readdir(PATH.public());\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nConverts any value to a number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value to convert. |\n| `def` | `Number` | no | `0` | The result for empty or invalid values. |\n\nReturns: `Number`\n\nA number is returned as it is. A string is trimmed and converted with the unary `+`; other values are converted to a string first. `null`, `undefined`, an empty string and a value that is not a number return `def` (0 by default). The result is not rounded (`'1.5'` gives `1.5`). `U.parseFloat(value, [def])` works the same and also accepts a comma as the decimal separator (`'12,50'` gives `12.5`).\n\nExample: Query values\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\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 |  | The value to convert. |\n| `def` | `Boolean` | no | `false` | The result for `null` or `undefined`. |\n\nReturns: `Boolean`\n\nA boolean is returned as it is; a number is `true` when it is greater than 0; the strings `true`, `1` and `on` (in any case) are `true` and every other string is `false`. `null` and `undefined` return `def` (`false` by default).\n\nExample: A checkbox\n```js\nvar newsletter = U.parseBoolean(this.body.newsletter); // 'on' -> true\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nReads a nested value by a path.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The object to read. |\n| `path` | `String` | yes |  | The path. |\n\nReturns: `Object` The value, or `undefined`.\n\nThe path uses dots and brackets: `a.b.c`, `items[0].name`. When a part of the path is missing, it returns `undefined` instead of throwing. Paths with spaces, parentheses or keywords such as `__proto__` and `constructor` are refused (`undefined`). Compiled readers are cached per path.\n\nExample: Nested values\n```js\nvar data = { user: { address: { city: 'Bratislava' } }, items: [{ name: 'A' }] };\nU.get(data, 'user.address.city');  // 'Bratislava'\nU.get(data, 'items[0].name');      // 'A'\nU.get(data, 'user.phone.number');  // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nWrites a nested value by a path.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The object to write into. |\n| `path` | `String` | yes |  | The path. |\n| `value` | `Object` | yes |  | The value. |\n\nReturns: `Object` The written value.\n\nMissing objects on the path are created. A path that ends with `[]` pushes the value into the array, and an index creates an array with objects in it (`items[0].name`). Paths with spaces, parentheses or keywords such as `__proto__` and `constructor` are refused: nothing is written. Returns the value.\n\nExample: Build an object\n```js\nvar model = {};\nU.set(model, 'address.city', 'Bratislava');\nU.set(model, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\nExample: Path with an index\n```js\nvar model = {};\nU.set(model, 'items[0].name', 'Pen');\n// { items: [{ name: 'Pen' }] }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nCopies the keys of source into target.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | The object to write into. |\n| `source` | `Object` | yes |  | The object to read. |\n| `rewrite` | `Boolean` | no | `true` | `false` keeps existing values. |\n\nReturns: `Object` The target.\n\nEvery key of `source` is cloned into `target`. With `rewrite` set to `false`, keys that already exist in `target` are not changed, which is how you fill defaults. Returns `target`.\n\nExample: Defaults\n```js\nvar options = { limit: 50 };\nU.extend(options, { limit: 10, sort: 'name' }, false);\n// { limit: 50, sort: 'name' }\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nReturns a compare function for Array.sort().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | For example `name` or `price_desc,name`. |\n\nReturns: `Function` `function(a, b)` for `Array.prototype.sort()`.\n\n`sort` is a comma-separated list of keys; add `_desc` for descending order (`_asc` is the default). Nested keys use dots (`address.city`). The type of each key is read from the first value that is not empty the first time the expression is used, and is kept for later uses of the same expression: strings are compared with diacritics in mind, numbers, booleans and dates by value.\n\nExample: Sort products\n```js\nproducts.sort(U.sortcomparer('price_desc,name'));\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nReturns a random integer in a range.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | The largest value. |\n| `min` | `Number` | no | `0` | The smallest value. |\n\nReturns: `Number`\n\nReturns an integer between `min` and `max`, both included.\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 |  | The number of characters. |\n\nReturns: `String`\n\nThe characters are `0-9`, `A-Z` and `a-z`. `U.random_string(length)` uses only letters, and `U.random_number(length)` only digits (returned as a string that does not start with 0). These values come from `Math.random()`: do not use them as passwords or security tokens.\n\nExample: Random strings\n```js\nU.random_text(8);    // 'yb7JVb2a'\nU.random_string(6);  // 'HNXkTk'\nU.random_number(6);  // '825174'\n```\n\n### U.convert62(number)\n\nType: `method`\n\nConverts a number to a base-62 string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | A non-negative number. |\n\nReturns: `String`\n\nThe digits are `0-9`, `A-Z` and `a-z`, in this order. The number is rounded down first. `U.from62(value)` converts the string back to the number. Use it for short codes made from numeric ids.\n\nExample: Short codes\n```js\nvar code = U.convert62(123456);  // 'W7E'\nvar id = U.from62(code);         // 123456\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nReturns the extension of a file name.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | A file name, a path or a URL. |\n| `raw` | `Boolean` | no | `false` | `true` keeps the original case. |\n\nReturns: `String`\n\nReturns the part after the last dot, without the dot and in lower case (with `raw`, in the original case). A query string after `?` is ignored. Returns an empty string when the name has no extension.\n\nExample: Extensions\n```js\nU.getExtension('/img/Photo.JPG');      // 'jpg'\nU.getExtension('/files/a.pdf?v=1');    // 'pdf'\nU.getExtension('README');              // ''\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 |  | A path or a URL. |\n\nReturns: `String`\n\nReturns the file name (or the last directory) of a path with `/` or `\\\\` separators. A trailing separator is ignored.\n\nExample: File names\n```js\nU.getName('/www/app/public/logo.png');  // 'logo.png'\nU.getName('/www/app/public/');          // 'public'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nReturns the MIME type for an extension.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | An extension, e.g. `png` or `.png`. |\n\nReturns: `String`\n\nThe extension may start with a dot. Unknown extensions return `application/octet-stream`. `U.getExtensionFromContentType(type)` does the reverse and returns the first extension with that type (or `undefined`). The whole table is `U.contentTypes`.\n\nExample: Content types\n```js\nU.getContentType('png');                     // 'image/png'\nU.getContentType('.json');                   // 'application/json'\nU.getExtensionFromContentType('image/png');  // 'png'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nEncodes text or a buffer to base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | The data to encode. |\n\nReturns: `String`\n\nA buffer is encoded directly; other values are converted to a string and encoded as UTF-8. `U.atob(value)` decodes base64 back to a UTF-8 string.\n\nExample: Base64\n```js\nvar encoded = U.btoa('Hello');   // 'SGVsbG8='\nvar text = U.atob(encoded);      // 'Hello'\n```\n\n### U.validhost(host)\n\nType: `method`\n\nChecks that a host name is plain ASCII and that an IP address is in its canonical form.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | The host name or IP address. |\n\nReturns: `Boolean` `true` for a valid host.\n\nReturns `false` for a value that is not a string, is empty, or contains a character outside the visible ASCII range (spaces, NUL bytes, letters with accents). A value made only of numbers and dots (or hex numbers) must be a canonical IPv4 address: `127.0.0.1` is valid, `127.1`, `0127.0.0.1`, `0x7f.0.0.1` and `2130706433` are not. Other ASCII values, including IPv6 addresses, return `true`; the function does not check the full syntax of a host name. Convert an international name with `U.tohost()` first.\n\nExample: Check hosts\n```js\nU.validhost('example.com');     // true\nU.validhost('127.0.0.1');       // true\nU.validhost('127.1');           // false\nU.validhost('0x7f.0.0.1');      // false\nU.validhost('münchen.de');      // false\nU.validhost('evil.example\\0.trusted.example'); // false\n```\n\n### U.tohost(host)\n\nType: `method`\n\nConverts a host name to its canonical ASCII form.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | The host name or IP address. |\n\nReturns: `String` The canonical host, or an empty string.\n\nConverts the host with the URL parser of Node.js: letters become lower case, an international name becomes punycode, and an IPv4 address in another notation becomes the dotted form (a leading `0` means an octal number, `0x` a hex number). The result is then checked with `U.validhost()`. A value that contains `:` (an IPv6 address) is only checked. Returns an empty string when the host is not valid, so test the result before you use it.\n\nExample: Convert hosts\n```js\nU.tohost('münchen.de');      // 'xn--mnchen-3ya.de'\nU.tohost('EXAMPLE.com');     // 'example.com'\nU.tohost('127.1');           // '127.0.0.1'\nU.tohost('0x7f.0.0.1');      // '127.0.0.1'\nU.tohost('evil.example\\0.trusted.example'); // ''\n```\n\nExample: Validate input\n```js\nfunction host(value) {\n\tvar host = U.tohost(value);\n\tif (!host)\n\t\tthrow new Error('Invalid hostname');\n\treturn host;\n}\n```\n\n### U.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` | no |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Milliseconds before the wait fails. |\n| `interval` | `Number` | no | `500` | Milliseconds between checks. |\n\nReturns: `Promise` When `callback` is omitted.\n\n`validator` is called right away and then every `interval` milliseconds until it returns `true`; then the callback gets `(null, true)`. When `timeout` passes first, the callback gets an `Error('Timeout')`. Without a callback, the function returns a promise that resolves or rejects the same way.\n\nExample: Wait for a connection\n```js\nawait U.wait(() => MAIN.db != null, null, 10000, 200);\nprint('Database ready');\n```\n\n### U.resolve(url, callback, [param])\n\nType: `method`\n\nResolves the host of a URL to IPv4 addresses, with a cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | An absolute URL. |\n| `callback` | `Function` | yes |  | `function(err, uri, param, addresses)`. |\n| `param` | `Any` | no |  | A value passed to the callback. |\n\nParses `url`, checks its host name with `U.validhost()` and asks the DNS servers for its IPv4 addresses (`dns.resolve4()`, so the hosts file is not used). The callback gets `(err, uri, param, addresses)`: `uri` is the parsed URL with `host` set to the first address, `param` is the third argument and `addresses` the whole list. The addresses are cached for the life of the process; a failed lookup is tried once more before `err` is passed.\n\nA string that is not a URL gives `TypeError: Invalid URL`, and a host name that is not valid gives the error `Invalid hostname` without a DNS query. For `http` and `https` URLs the URL parser already converts the host; for other schemes a non-canonical address such as `tcp://127.1/` gives `Invalid hostname`. `REQUEST()` uses this function with the option `resolve: true`, and `RESTBuilder` by default.\n\nExample: Resolve a host\n```js\nU.resolve('https://example.com/api/', function(err, uri, param, addresses) {\n\tif (err)\n\t\tconsole.log(err.message || err.code);\n\telse\n\t\tconsole.log(uri.hostname, addresses);\n});\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nSplits a stream of data into parts by delimiters.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | The start of a part, or the separator. |\n| `end` | `String|Buffer` | no |  | The end of a part. |\n| `callback` | `Function` | yes |  | `function(value, index)`; return `false` to stop. |\n| `skip` | `Number` | no | `0` | The number of first parts to ignore. |\n| `stream` | `Stream` | no |  | A stream whose `end` event flushes the rest. |\n\nReturns: `Function` `function(chunk)`.\n\nReturns a function that you call with each chunk (a buffer), for example as the `data` handler of a stream. With `beg` and `end`, the callback gets each part that starts with `beg` and ends with `end`, both included (for example one `<item>...</item>` of a large XML file). With `beg` only, `beg` is a separator and the callback gets each part up to and including it (for example lines with `\\n`). The callback gets `(value, index)` with the value as a string; returning `false` stops the parsing. `skip` ignores that many first parts. With `stream`, the remaining data is processed when the stream ends. `U.streamer2()` takes the same arguments and passes buffers instead of strings.\n\nExample: Read a large XML file\n```js\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\nstream.on('data', U.streamer('<product>', '</product>', function(value, index) {\n\tvar product = value.parseXML();\n\tprint(index, product);\n}));\n```\n\nExample: Lines of a CSV file\n```js\nvar stream = Fs.createReadStream(filename);\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tvar cols = line.trim().split(';');\n}, 1, stream));  // skips the header line\n```\n\n### U.connect(options, [callback])\n\nType: `method`\n\nOpens a TCP or TLS connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | `{ host, port, secure, tls, timeout }` and, with `secure`, other options of `tls.connect()`. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nConnects to `options.host` and `options.port` and calls `callback(err, meta)` when the connection is open. The host is converted with `U.tohost()` first, so an international name is sent as punycode and `127.1` as `127.0.0.1`; a host that is not valid gives the error `Invalid hostname` and no connection is made. With `secure: true` the connection uses TLS from the start and the other options (`servername`, `rejectUnauthorized`, `ca` ...) go to `tls.connect()`. With `tls` the connection starts as plain TCP and is upgraded to TLS as soon as it is open: `tls: true` uses the default options of `tls.connect()`, an object passes its options (`servername`, `rejectUnauthorized`, `ca` ...). With `timeout` (in milliseconds) a connection that is not open in time gives the error `Timeout`.\n\n`meta` has `socket` (the Node.js socket), `opt` (the options with the converted host), `write(data)`, `ondata(fn)` for the received chunks, and `close()` (also `destroy()`). `LDAP()` connects with this function.\n\nExample: Read the greeting of a server\n```js\nU.connect({ host: 'mail.example.com', port: 25, timeout: 5000 }, function(err, meta) {\n\tif (err) {\n\t\tconsole.log(err.message);\n\t\treturn;\n\t}\n\tmeta.ondata(function(chunk) {\n\t\tconsole.log(chunk.toString());\n\t\tmeta.close();\n\t});\n});\n```\n\nExample: Upgrade to TLS\n```js\nU.connect({ host: 'mail.example.com', port: 465, tls: { servername: 'mail.example.com' } }, function(err, meta) {\n\tif (!err)\n\t\tconsole.log(meta.socket.encrypted); // true\n});\n```\n\n### U.ls(path, [callback], [filter])\n\nType: `method`\n\nLists the files and directories of a directory recursively.\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 |  | The filter. |\n\nReturns: `Promise` `{ files, directories }` when `callback` is omitted.\n\nThe callback gets two arrays of absolute paths: `files` and `directories` (directories end with the path separator). `filter` can be a string (paths that contain it, case-insensitive), a regular expression, or a function `(path, isdirectory)` that returns `true` to keep the item; string and regular expression filters apply to files only. A directory that the filter drops is not searched. Without a callback, the function returns a promise with `{ files, directories }`. `U.ls2()` takes the same arguments and returns files as `{ filename, stats }` objects with the `fs.Stats` of each file.\n\nExample: Find JSON files\n```js\nU.ls(PATH.databases(), function(files, directories) {\n\tprint(files);\n}, /\\.json$/);\n```\n\nExample: Sizes with ls2\n```js\nvar result = await U.ls2(PATH.public('uploads'));\nvar size = 0;\nfor (var file of result.files)\n\tsize += file.stats.size;\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nStores a large list in temporary files, in pages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A unique name, used for the file names. |\n| `max` | `Number` | no | `50` | Items per page. |\n\nReturns: `Chunker`\n\nA chunker collects items with `write(item)` (alias `append()`); every `max` items are written to a file `tmp/{name}-{index}.chunker` (compressed with deflate when `compress` is `true`, the default) so the memory stays small. Call `end()` to write the rest. Then `each(onitem, [ondone])` reads the pages in order: `onitem(items, next, index)` gets one page and calls `next()` to continue, and `percentage` tells how far the reading is. `read(index, callback)` reads one page. With `autoremove` (`true` by default), each file is deleted after it is read; `clear()` deletes all files and `destroy()` also releases the chunker. The properties `count` and `pages` hold the number of items and pages.\n\nExample: Process a large export\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var row of rows)\n\tchunker.write(row);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tprint('Page', index, chunker.percentage + '%');\n\tsend(items, next);\n}, function() {\n\tprint('Done', chunker.count, 'items');\n});\n```\n\n### chunker.load([callback])\n\nType: `method` · Since: `0.0.16`\n\nFinds the pages that an earlier chunker with the same name left on disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `Promise` When `callback` is omitted.\n\nCounts the files of the chunker in the temporary directory and sets the internal page index, so `each()` and `read()` can read the pages that an earlier instance wrote and did not read (for example before a restart). Create the chunker with the same `name`. The callback gets `(null, count)`; without a callback, the function returns a promise that resolves when the counting is done.\n\nExample: Continue a chunker\n```js\nvar chunker = U.chunker('export');\nawait chunker.load();\nchunker.each(function(items, next) {\n\tsend(items, next);\n});\n```\n\n### new U.EventEmitter2() / U.EventEmitter2(obj)\n\nType: `class`\n\nA small event emitter.\n\nReturns: `EventEmitter2`\n\nAn object with `on(name, fn)`, `once(name, fn)`, `off(name, [fn])` and `emit(name, ...args)` (up to seven arguments). `off(name)` without a function removes all handlers of the event. Handlers run with the emitter as `this`. Called with an object (`U.EventEmitter2(obj)`), it adds these methods to that object, unless it already has `emit`, and returns it.\n\nExample: Events on your object\n```js\nvar Cart = {};\nU.EventEmitter2(Cart);\n\nCart.on('add', function(item) {\n\tprint('Added', item.name);\n});\n\nCart.emit('add', { name: 'Shoes' });\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nObfuscates a string with a key.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The text. |\n| `key` | `String` | yes |  | The key. |\n| `encode` | `String` | no | `'base64'` | The output encoding, or `buffer`. |\n\nReturns: `String|Buffer`\n\nEncodes the string with the key and a random 4-byte mask and returns it in base64 (or in the encoding you set; `buffer` returns a buffer). The same input gives a different output each time. `U.decrypt_data(value, key, [encode])` returns the original string, or `null` for invalid input. This is a light obfuscation, not strong encryption; for sensitive data use `ENCRYPT()` (see [Encryption](../../guides/encryption/)).\n\nExample: Round trip\n```js\nvar data = U.encrypt_data('hello', 'mykey');\nvar text = U.decrypt_data(data, 'mykey');  // 'hello'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nSigns an identifier so that it cannot be changed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | The identifier. |\n| `key` | `String` | no | `CONF.secret` | The key. |\n\nReturns: `String`\n\nReturns the identifier with a checksum in front, made from the value, the key and `CONF.secret_uid`. `U.decrypt_uid(value, [key])` checks it and returns the original identifier (a number when the original was a number) or `null` when the value was changed. The identifier itself stays readable. Without `key`, `CONF.secret` is used.\n\nExample: Signed id in a link\n```js\nvar signed = U.encrypt_uid(123, 'mykey');   // 'n...x123', the checksum depends on CONF.secret_uid\nU.decrypt_uid(signed, 'mykey');             // 123\nU.decrypt_uid('n2v55u4jx124', 'mykey');     // null\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifies JavaScript; U.minify_css() and U.minify_html() do the same for CSS and HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The source code. |\n\nReturns: `String`\n\nThese are the minifiers that the framework uses for static files and views. They take a string and return the minified string.\n\nExample: Minify\n```js\nU.minify_js('var a = 1 ;  // note\\n');  // 'var a=1;'\nU.minify_css('a { color : red ; }');     // 'a{color:red}'\nU.minify_html(html);\n```\n\n### U.aistreamer(online, [onmessage])\n\nType: `method` · Since: `0.0.16`\n\nParses a streamed response of an AI chat API into lines of text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `online` | `Function` | yes |  | `function(line)`, called for each complete line of text. |\n| `onmessage` | `Function` | no |  | `function(message)`, called for each parsed JSON message. |\n\nReturns: `Function` `function(chunk)`.\n\nReturns a function that you call with each chunk (a buffer) of a streamed response. It reads JSON messages line by line in two formats: server-sent events with `data: {...}` (OpenAI completions, where the text is in `choices[0].delta.content` and `data: [DONE]` ends it) and plain JSON lines (Ollama, where the text is in `message.content` and `done` ends it). The text is collected and `online(line)` is called for every complete line. `onmessage(obj)`, when you set it, gets every parsed message; JSON dates are then parsed as dates.\n\nExample: Print an answer line by line\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nCaches the result of a task in a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Identifier of the cached item. |\n| `expire` | `String` | yes |  | How long the file is valid, for example `'5 minutes'`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `maker` | `Function` | yes |  | `function(next, id)` that creates the value. |\n| `encoding` | `String` | no | `json` | `json` or a file encoding such as `utf8`. |\n\nLooks for the file of `id` in `tmp/`. When it exists and is newer than `expire`, its content goes to `callback(err, response)`. Otherwise `maker(next, id)` runs; `next(err, response, [load])` writes the response to the file and calls `callback`, unless `load` is `false`. With the `json` encoding the value is stored as JSON and parsed back; any other encoding stores and reads the raw content.\n\nExample: Cache a remote list\n```js\nFILECACHE('currencies', '1 day', function(err, response) {\n\tMAIN.currencies = response;\n}, function(next) {\n\tREQUEST({ url: 'https://example.com/rates.json', callback: function(err, response) {\n\t\tnext(err, err ? null : response.body.parseJSON());\n\t}});\n});\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID()","since":"","deprecated":false},{"type":"method","name":"GUID([length])","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"HASH(value, [type])","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"CLONE(obj, [skip], [nofunctions])","signature":"CLONE(obj, [skip], [nofunctions])","since":"","deprecated":false},{"type":"method","name":"COPY(source, [target], [all])","signature":"COPY(source, [target], [all])","since":"","deprecated":false},{"type":"method","name":"DIFFARR(prop, db, form)","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"QUERIFY([url], obj)","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"PROMISIFY(fn, [a], [b], [c])","signature":"PROMISIFY(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"ERROR([name])","signature":"ERROR([name])","since":"","deprecated":false},{"type":"method","name":"print()","signature":"print(...values)","since":"","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"NOOP","signature":"NOOP","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","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":"CACHE.set(key, value, [expire])","signature":"CACHE.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"CACHE.get(key, [def])","signature":"CACHE.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"CACHE.remove(key)","signature":"CACHE.remove(key)","since":"","deprecated":false},{"type":"method","name":"CACHE.reset([search])","signature":"CACHE.reset([search])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE([name], [delay], [skip])","signature":"MEMORIZE([name], [delay], [skip])","since":"","deprecated":false},{"type":"method","name":"BACKUP(filename, files, [callback], [filter])","signature":"BACKUP(filename, files, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE(filename, target, [callback], [filter])","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"PATH.root([path])","signature":"PATH.root([path])","since":"","deprecated":false},{"type":"method","name":"PATH.databases([path])","signature":"PATH.databases([path])","since":"","deprecated":false},{"type":"method","name":"PATH.temp([path])","signature":"PATH.temp([path])","since":"","deprecated":false},{"type":"method","name":"PATH.exists(path, [callback])","signature":"PATH.exists(path, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink(files, [callback])","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir(directories, [callback])","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"property","name":"Total.FsPromises","signature":"Total.FsPromises","since":"","deprecated":false},{"type":"method","name":"U.parseInt(value, [def])","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseBoolean(value, [def])","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.get(obj, path)","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set(obj, path, value)","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.extend(target, source, [rewrite])","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer(sort)","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.random([max], [min])","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text(length)","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.convert62(number)","signature":"U.convert62(number)","since":"","deprecated":false},{"type":"method","name":"U.getExtension(filename, [raw])","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName(path)","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType(ext)","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.btoa(value)","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.validhost(host)","signature":"U.validhost(host)","since":"","deprecated":false},{"type":"method","name":"U.tohost(host)","signature":"U.tohost(host)","since":"","deprecated":false},{"type":"method","name":"U.wait(validator, [callback], [timeout], [interval])","signature":"U.wait(validator, [callback], [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"U.resolve(url, callback, [param])","signature":"U.resolve(url, callback, [param])","since":"","deprecated":false},{"type":"method","name":"U.streamer(beg, [end], callback, [skip], [stream])","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.connect(options, [callback])","signature":"U.connect(options, [callback])","since":"","deprecated":false},{"type":"method","name":"U.ls(path, [callback], [filter])","signature":"U.ls(path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"U.chunker(name, [max])","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.load([callback])","signature":"chunker.load([callback])","since":"0.0.16","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2() / U.EventEmitter2(obj)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_data(value, key, [encode])","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid(value, [key])","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.minify_js(value)","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.aistreamer(online, [onmessage])","signature":"U.aistreamer(online, [onmessage])","since":"0.0.16","deprecated":false},{"type":"method","name":"FILECACHE(id, expire, callback, maker, [encoding])","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwwLBgx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/utilities/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Hilfsmittel","summary":"U/Utils-Funktionen, globale Hilfsfunktionen (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), gemeinsame Objekte, CACHE, MEMORIZE, BACKUP, RESTORE und PATH.","markdown":"---\ntitle: Hilfsmittel\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/utilities/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Hilfsmittel\n\n> U/Utils-Funktionen, globale Hilfsfunktionen (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), gemeinsame Objekte, CACHE, MEMORIZE, BACKUP, RESTORE und PATH.\n\nDiese Seite listet die globalen Hilfsfunktionen, die gemeinsamen globalen Objekte, den In-Memory-`CACHE`, die `PATH`-Funktionen und die Funktionen des Moduls `U` (`Utils`) auf, die Anwendungen verwenden. Die Anleitung [Hilfsfunktionen](../../guides/utilities/) erklärt mit Beispielen, wie sie zusammenspielen. Die Methoden, die `String`, `Number`, `Date` und `Array` hinzugefügt werden, findest du unter [Prototypen](../prototypes/).\n\n## API\n\n### U\n\nType: `property`\n\nDas Utils-Modul als globales Objekt.\n\nReturns: `Object` Das Utils-Modul.\n\nAlle Funktionen von `utils.js` sind über `U` und seinen Alias `Utils` verfügbar (beide verweisen auf dasselbe Objekt). Diese Seite dokumentiert die Funktionen, die Anwendungen verwenden; die übrigen nutzt das Framework selbst.\n\nExample: Eine Hilfsfunktion verwenden\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\nvar same = Utils === U;           // true\n```\n\n### UID()\n\nType: `method`\n\nGibt einen neuen eindeutigen Bezeichner zurück.\n\nReturns: `String` Zum Beispiel `JacVuE1cn61f`.\n\nDer Bezeichner ist ein kurzer String aus Buchstaben und Ziffern: ein Zeitstempel zur Basis 62 (in Zehntelsekunden), ein interner Zähler, ein beim Start zufällig gewähltes Zeichen (wird jede Minute gewechselt), die Länge des Zeitanteils, eine Paritätsziffer und der Buchstabe `f`. Später erzeugte Bezeichner werden in den meisten Fällen nach früheren sortiert. Der `uid`-Validator des Frameworks (`DEF.validators.uid`) akzeptiert sie.\n\nExample: Ein neuer Datensatz\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\nNOSQL('products').insert(model);\n```\n\n### GUID([length])\n\nType: `method`\n\nGibt einen UUID-ähnlichen String oder einen zufälligen String der angegebenen Länge zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Die Anzahl der Zeichen. Lass ihn für das UUID-ähnliche Format weg. |\n\nReturns: `String`\n\nOhne `length` gibt sie einen String in der Form `xxxxxxxx-xxxx-Nxxx-Yxxx-xxxxxxxxxxxx` (36 Zeichen) zurück, der aus der aktuellen Zeit und zufälligen Hexadezimalziffern gebildet wird. Mit `length` gibt sie so viele zufällige Zeichen aus `0-9` und `a-z` zurück.\n\nExample: Tokens\n```js\nvar guid = GUID();       // '1a1e0561-0561-4c86-8eaf-d9a327a65943'\nvar token = GUID(30);    // 30 random characters\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nBerechnet den Hash eines Strings.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der zu hashende Text. |\n| `type` | `String` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32` oder `crc32unsigned`. |\n\nReturns: `Number|String` Ohne Typ eine Zahl, für md5/sha-Typen ein hexadezimaler String.\n\nOhne `type` gibt sie eine vorzeichenlose 32-Bit-Zahl zurück, die aus dem String berechnet wird (schnell, nicht kryptografisch). Mit einem Typ gibt sie den Hash als hexadezimalen String (`md5`, `sha1`, `sha256`, `sha512`) oder als CRC32-Zahl (`crc32`, `crc32unsigned`) zurück. `value` muss ein String sein; wandle Zahlen vorher mit `+ ''` um.\n\nExample: Hashes\n```js\nHASH('abc');            // 96354\nHASH('abc', 'md5');     // '900150983cd24fb0d6963f7d28e17f72'\nHASH(email, 'sha256');\n```\n\n### CLONE(obj, [skip], [nofunctions])\n\nType: `method`\n\nErstellt eine tiefe Kopie eines Objekts oder Arrays.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array` | yes |  | Der zu kopierende Wert. Andere Werte werden unverändert zurückgegeben. |\n| `skip` | `Object` | no |  | Wegzulassende Schlüssel, z. B. `{ password: 1 }`. |\n| `nofunctions` | `Boolean` | no | `false` | `true` lässt Funktionen weg. |\n\nReturns: `Object|Array` Die Kopie.\n\nVerschachtelte Objekte und Arrays werden kopiert, Buffer in Objekteigenschaften werden dupliziert, und Datumswerte, Fehler und andere Nicht-Objekt-Werte bleiben, wie sie sind. `skip` ist ein Objekt, dessen Schlüssel auf jeder Ebene aus der Kopie weggelassen werden. Mit `nofunctions` werden auch Eigenschaften weggelassen, die Funktionen enthalten.\n\nExample: Kopie ohne einen Schlüssel\n```js\nvar user = { id: 'abc', name: 'Peter', password: 'secret', address: { city: 'Bratislava' } };\nvar safe = CLONE(user, { password: 1 });\nsafe.address.city = 'Prague';  // user.address.city is still 'Bratislava'\n```\n\n### COPY(source, [target], [all])\n\nType: `method`\n\nKopiert die Schlüssel eines Objekts in ein anderes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Das zu lesende Objekt. |\n| `target` | `Object` | no |  | Das Objekt, in das geschrieben wird. |\n| `all` | `Boolean` | no | `true` | `false` schreibt nur die Schlüssel, die `target` bereits hat. |\n\nReturns: `Object` Das Ziel (oder die neue Kopie).\n\nJeder Wert von `source` wird geklont und in `target` geschrieben. Ist `all` auf `false` gesetzt, werden nur Schlüssel geschrieben, die in `target` bereits definiert sind, sodass `target` als Liste erlaubter Felder dient. Ohne `target` gibt sie eine tiefe Kopie von `source` zurück.\n\nExample: Erlaubte Felder\n```js\nvar allowed = { name: '', email: '' };\nCOPY(this.body, allowed, false);\n// allowed contains only name and email from the body\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nVergleicht zwei Arrays von Objekten anhand einer Eigenschaft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | Der Schlüssel, der ein Element identifiziert, z. B. `id`. |\n| `db` | `Array` | yes |  | Die aktuellen Elemente (zum Beispiel aus der Datenbank). |\n| `form` | `Array` | yes |  | Die neuen Elemente (zum Beispiel aus einem Formular). |\n\nReturns: `Object` `{ add: Array, upd: Array, rem: Array }`.\n\nElemente werden zugeordnet, wenn ihre `prop`-Werte gleich sind (`==`). Das Ergebnis hat drei Arrays: `add` enthält die Elemente von `form`, die nicht in `db` sind, `upd` enthält Paare `{ db, form }` zugeordneter Elemente, und `rem` enthält die `prop`-Werte der `db`-Elemente, die nicht in `form` sind.\n\nExample: Elemente synchronisieren\n```js\nvar diff = DIFFARR('id', current, model.items);\n\nfor (var item of diff.add)\n\tNOSQL('items').insert(item);\n\nfor (var pair of diff.upd)\n\tNOSQL('items').modify(pair.form).where('id', pair.db.id);\n\nfor (var id of diff.rem)\n\tNOSQL('items').remove().where('id', id);\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nErstellt einen Query String aus einem Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Eine URL, optional mit einer Methode davor. |\n| `obj` | `Object` | yes |  | Die Werte. |\n\nReturns: `String`\n\nSchlüssel und Werte werden URL-kodiert. `null`, `undefined` und leere Werte werden übersprungen, Datumswerte als ISO-Strings geschrieben und Arrays mit Kommas verbunden. Ohne `url` beginnt das Ergebnis mit `?` (oder ist ein leerer String, wenn nichts übrig bleibt). Mit `url` wird der Query String mit `?` oder `&` angehängt; die URL darf mit einer HTTP-Methode (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `API`) gefolgt von einem Leerzeichen beginnen, so wie `REQUEST()` und `AJAX()` sie entgegennehmen. Die Funktion ist auch als `U.querify()` verfügbar.\n\nExample: Query Strings\n```js\nQUERIFY({ q: 'red shoes', page: 2 });           // '?q=red%20shoes&page=2'\nQUERIFY('/api/?lang=en', { page: 2 });         // '/api/?lang=en&page=2'\nQUERIFY('GET https://example.com/', { id: 5 }); // 'GET https://example.com/?id=5'\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method`\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, deren letztes Argument ein Callback ist. |\n| `a` | `Object` | no |  | Das erste Argument. |\n| `b` | `Object` | no |  | Das zweite Argument. |\n| `c` | `Object` | no |  | Das dritte Argument. |\n\nReturns: `Promise`\n\n`fn` wird mit den übergebenen Argumenten (bis zu drei) und einem Callback `function(err, response)` aufgerufen. Die Promise wird mit `err` abgelehnt oder mit `response` erfüllt. Übergib nur die Argumente, die du brauchst: Ein Argument, das `undefined` ist, beendet die Liste.\n\nExample: Eine Datei lesen\n```js\nvar Fs = require('fs');\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n\n### ERROR([name])\n\nType: `method`\n\nGibt einen Callback zurück, der Fehler protokolliert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Der Name, der mit dem Fehler angezeigt wird, z. B. die fehlgeschlagene Funktion. |\n\nReturns: `Function` `function(err)`.\n\nDie zurückgegebene Funktion nimmt `err` als erstes Argument und übergibt es, wenn es gesetzt ist, mit `name` als Quelle an den Fehler-Handler des Frameworks (`DEF.onError`, der den Fehler ausgibt und in den Statistiken speichert). Verwende sie für Callbacks, deren Ergebnis du nicht brauchst, deren Fehler du aber sehen willst.\n\nExample: Einen fehlgeschlagenen Schreibvorgang protokollieren\n```js\nFs.writeFile(PATH.databases('cache.json'), JSON.stringify(data), ERROR('cache.save'));\n```\n\n### print(...values)\n\nType: `method`\n\nSchreibt Werte in die Konsole.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `values` | `Object` | yes |  | Die auszugebenden Werte. |\n\n`print` ist `console.log`. Das Framework verwendet es für seine Startinformationen.\n\nExample: Ausgeben\n```js\nprint('Imported', count, 'products');\n```\n\n### NOW\n\nType: `property`\n\nEin Date mit der aktuellen Zeit, alle 5 Sekunden aktualisiert.\n\nReturns: `Date`\n\nDas Framework weist `NOW` nach dem Laden alle 5 Sekunden `new Date()` zu, außerdem wenn es einen Fehler, ein Audit-Log oder einen Cache-Eintrag schreibt. Verwende es dort, wo eine Genauigkeit von einigen Sekunden genügt: Ablaufzeiten, Log-Zeilen, `dtcreated`-Felder. Ändere das Objekt nicht; weise stattdessen ein neues Datum zu.\n\nExample: Ablaufzeit\n```js\nvar expire = NOW.add('1 hour');\nif (session.expire < NOW)\n\tdelete sessions[session.id];\n```\n\n### NOOP\n\nType: `property`\n\nEine leere Funktion.\n\nReturns: `Function`\n\nVerwende es dort, wo ein Callback erforderlich ist, du das Ergebnis aber nicht brauchst. Es ist dieselbe Funktion wie `U.noop`.\n\nExample: Das Ergebnis ignorieren\n```js\nFs.unlink(filename, NOOP);\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nEin eingefrorenes leeres Objekt; EMPTYARRAY ist ein eingefrorenes leeres Array.\n\nReturns: `Object`\n\n`EMPTYOBJECT` (`{}`) und `EMPTYARRAY` (`[]`) werden einmal erstellt und mit `Object.freeze()` eingefroren, sodass sie nicht geändert werden können. Verwende sie als Standardwerte, statt neue Objekte zu erstellen, zum Beispiel `var opt = options || EMPTYOBJECT;`. Schreibe nie in sie hinein: Im Strict Mode löst ein Schreibvorgang einen Fehler aus.\n\nExample: Standardwerte\n```js\nfunction find(filter) {\n\tvar opt = filter || EMPTYOBJECT;\n\tvar tags = opt.tags || EMPTYARRAY;\n\treturn tags.length;\n}\n```\n\n### MAIN\n\nType: `property`\n\nEin globales Objekt für den gemeinsamen Zustand der Anwendung.\n\nReturns: `Object`\n\nDas Framework erstellt `MAIN` als leeres Objekt und verwendet es nicht. Lege dort ab, was mehrere Dateien deiner Anwendung gemeinsam nutzen: beim Start geladene Einstellungen, offene Verbindungen, Zähler. In Views ist es als `MAIN` lesbar.\n\nExample: Gemeinsame Einstellungen\n```js\n// definitions/settings.js\nMAIN.settings = MEMORIZE('settings');\n\n// a controller or an action\nvar title = MAIN.settings.title;\n```\n\n### REPO\n\nType: `property`\n\nEin globales Objekt für gemeinsame Daten, auch in Views verfügbar.\n\nReturns: `Object`\n\nEin leeres Objekt, das das Framework beim Start erstellt (es ist auch `F.repo`). Views können es als `REPO` lesen, was es zu einem guten Ort für Daten macht, die Layouts brauchen, zum Beispiel ein Menü oder die Kontaktdaten.\n\nExample: Daten für das Layout\n```js\nREPO.menu = [{ name: 'Home', url: '/' }, { name: 'Contact', url: '/contact/' }];\n\n// views/layout.html\n// @{foreach m in REPO.menu}<a href=\"@{m.url}\">@{m.name}</a>@{end}\n```\n\n### FUNC\n\nType: `property`\n\nEin globales Objekt für deine gemeinsamen Funktionen.\n\nReturns: `Object`\n\nEin leeres Objekt für Funktionen, die mehrere Teile der Anwendung verwenden. Definiere sie in `/definitions/`, damit sie vor der ersten Anfrage existieren. Auch Views können `FUNC` lesen.\n\nExample: Eine gemeinsame Funktion\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// anywhere\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nEin globales Objekt für kurzlebige Daten, alle 5 Minuten geleert.\n\nReturns: `Object`\n\nAlle 5 Minuten ersetzt das Framework `TEMP` durch ein neues leeres Objekt. Verwende es für kleine temporäre Daten, die jederzeit verschwinden dürfen, etwa Einmal-Tokens oder Zähler für die Drosselung. Lies es immer über die globale Variable (`TEMP.key`), nicht über eine gespeicherte Referenz, denn das Objekt ändert sich.\n\nExample: Ein kurzlebiges Token\n```js\nvar token = GUID(20);\nTEMP[token] = { userid: user.id };\n\n// later\nvar data = TEMP[token];\nif (!data)\n\t$.invalid('The token has expired');\n```\n\n### MODS\n\nType: `property`\n\nDie geladenen Module nach ihrer ID.\n\nReturns: `Object`\n\nJede `.js`-Datei in `/modules/` wird beim Start geladen und in `MODS` unter ihrer `exports.id` gespeichert, oder unter dem Dateinamen, wenn sie keine setzt. Ihre `install()`-Funktion wird, falls vorhanden, nach dem Laden aufgerufen. `MODS` ist dasselbe Objekt wie `F.modules` und kann in Views gelesen werden.\n\nExample: Ein Modul\n```js\n// modules/pricing.js\nexports.id = 'pricing';\nexports.vat = function(price) {\n\treturn price * 1.2;\n};\n\n// anywhere\nvar total = MODS.pricing.vat(100);\n```\n\n### CACHE.set(key, value, [expire])\n\nType: `method`\n\nSpeichert einen Wert im In-Memory-Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `value` | `Object` | yes |  | Ein beliebiger Wert. |\n| `expire` | `String` | no | `'5 minutes'` | Wie lange der Wert gültig ist. |\n\nDer Wert wird im Speicher des Prozesses gehalten, bis er abläuft. `expire` ist eine Dauer in der Form, die `Date.add()` akzeptiert (`'30 seconds'`, `'5 minutes'`, `'1 hour'`, `'2 days'`). Der Wert wird so gespeichert, wie er ist, nicht kopiert: Änderst du ihn, ändert sich auch der zwischengespeicherte Wert. Abgelaufene Einträge werden jede Minute entfernt.\n\nExample: Ein Ergebnis zwischenspeichern\n```js\nCACHE.set('products', items, '2 minutes');\n```\n\n### CACHE.get(key, [def])\n\nType: `method`\n\nLiest einen Wert aus dem In-Memory-Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `def` | `Object` | no |  | Der Wert, der zurückgegeben wird, wenn der Schlüssel fehlt oder abgelaufen ist. |\n\nReturns: `Object`\n\nGibt den Wert zurück, wenn er existiert und nicht abgelaufen ist; andernfalls `def`. `CACHE.read()` ist ein Alias.\n\nExample: Lesen oder laden\n```js\nvar items = CACHE.get('products');\nif (!items) {\n\titems = await DATA.find('nosql/products').promise($);\n\tCACHE.set('products', items, '2 minutes');\n}\n```\n\n### CACHE.remove(key)\n\nType: `method`\n\nEntfernt einen Wert aus dem In-Memory-Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel. |\n\nRufe sie auf, wenn sich die zwischengespeicherten Daten ändern, damit der nächste Lesevorgang frische Daten lädt.\n\nExample: Invalidieren\n```js\nNOSQL('products').insert(model).callback(function() {\n\tCACHE.remove('products');\n});\n```\n\n### CACHE.reset([search])\n\nType: `method`\n\nEntfernt viele Werte oder alle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | no |  | Ein Teil der Schlüssel oder ein Muster. |\n\nReturns: `Number` Die Anzahl der entfernten Schlüssel.\n\nOhne `search` wird der ganze Cache geleert. Mit einem String wird jeder Schlüssel entfernt, der ihn enthält; mit einem regulären Ausdruck jeder Schlüssel, der darauf passt. Gibt die Anzahl der entfernten Schlüssel zurück (0, wenn der ganze Cache geleert wird).\n\nExample: Eine Gruppe entfernen\n```js\nCACHE.set('products_1', a);\nCACHE.set('products_2', b);\nCACHE.reset('products_');  // 2\nCACHE.reset(/^user_/);\nCACHE.reset();             // everything\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method`\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 der letzten Änderung und dem Schreiben. |\n| `skip` | `String|Array` | no |  | Schlüssel, die nicht in die Datei geschrieben werden, als Array oder als kommagetrennter String. |\n\nReturns: `Object` Die Daten mit `save()` und `set(key, value)`.\n\nLiest `databases/memorize_{name}.json` (oder ohne Namen `databases/memorize.json`) und gibt den Inhalt als Objekt zurück (ein leeres Objekt, wenn die Datei nicht existiert). Das Objekt erhält zwei Funktionen: `save()` plant das Schreiben des ganzen Objekts, und `set(key, value)` weist einen Wert zu und ruft `save()` auf. Das Schreiben erfolgt `delay` Millisekunden nach dem letzten Aufruf, sodass viele Änderungen einen einzigen Schreibvorgang ergeben. `skip` listet Schlüssel auf, die nicht geschrieben werden. Die Argumente `delay` und `skip` dürfen vertauscht werden. Rufe `MEMORIZE()` einmal pro Name auf und behalte das Objekt; jeder Aufruf liest die Datei erneut.\n\nExample: Einstellungen, die Neustarts überstehen\n```js\nvar settings = MEMORIZE('settings', 'cache');\n\nsettings.set('title', 'My shop');\n\nsettings.counter = (settings.counter || 0) + 1;\nsettings.cache = {};      // not written\nsettings.save();\n```\n\n### BACKUP(filename, files, [callback], [filter])\n\nType: `method`\n\nPackt Dateien und Verzeichnisse in eine Archivdatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Die zu erstellende Archivdatei (eine vorhandene Datei wird ersetzt). |\n| `files` | `String|Array` | yes |  | Ein Verzeichnis oder Pfade relativ zum Stammverzeichnis. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`; gib `true` zurück, um den Pfad zu packen. |\n\nReturns: `Promise` Wenn `callback` weggelassen wird.\n\nSchreibt ein Textarchiv: eine Zeile pro Verzeichnis und eine Zeile pro Datei, mit dem Pfad und dem gzip-komprimierten Inhalt in Base64. `files` ist ein Verzeichnis (alles darin wird mit Pfaden relativ dazu gepackt) oder ein Array von Pfaden relativ zum Stammverzeichnis der Anwendung (Dateien und ganze Verzeichnisse). Namen, die `.git`, `.gitignore`, `.npmignore` oder `.ds_store` enthalten, werden übersprungen. `filter(path, isdirectory)` erhält jeden Pfad (beginnend mit `/`) und lässt ihn weg, wenn sie einen falsy Wert zurückgibt. `filename` kann auch ein beschreibbarer Stream sein. Der Callback erhält `{ filename, files, size }`; ohne Callback gibt die Funktion eine Promise zurück.\n\nExample: Die Uploads sichern\n```js\nvar meta = await BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), null, function(path, isdir) {\n\treturn isdir || !path.endsWith('.tmp');\n});\nprint(meta.files, 'files', meta.size, 'bytes');\n```\n\nExample: Ausgewählte Pfade\n```js\nawait BACKUP(PATH.temp('app.backup'), ['config', 'databases', 'public/uploads']);\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nEntpackt ein mit BACKUP() erstelltes Archiv.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Das Archiv. |\n| `target` | `String` | yes |  | Das Verzeichnis, in das entpackt wird. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nReturns: `Promise` Wenn `callback` weggelassen wird.\n\nErstellt die Verzeichnisse und Dateien des Archivs innerhalb von `target`. `filename` kann auch ein lesbarer Stream sein. `filter(path, isdirectory)` wird für jedes Element aufgerufen: Bei einem Verzeichnis überspringt `false` das Anlegen; bei einer Datei gibst du `false` zurück, um sie zu überspringen, einen String, um sie unter diesem Pfad (relativ zu `target`) zu schreiben, oder nichts, um ihren Pfad beizubehalten. Der Callback erhält `{ files, size, path }`; ohne Callback gibt die Funktion eine Promise zurück.\n\nExample: Wiederherstellen\n```js\nvar meta = await RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'));\nprint('Restored', meta.files, 'files');\n```\n\nExample: Dateien unterwegs überspringen\n```js\nRESTORE(PATH.temp('app.backup'), PATH.root(), function(err) {\n\terr && print(err);\n}, function(path, isdir) {\n\tif (!isdir && path.startsWith('/config'))\n\t\treturn false;\n});\n```\n\n### PATH.root([path])\n\nType: `method`\n\nGibt das Stammverzeichnis der Anwendung oder einen Pfad darin zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ein relativer Pfad. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Stammverzeichnis ist das Verzeichnis der Anwendung (in dem das Startskript läuft). Mit `path` gibt sie das Stammverzeichnis verbunden mit diesem Pfad zurück. Wie die anderen Verzeichnisfunktionen von `PATH` erstellt sie das Verzeichnis beim ersten Aufruf mit einem Pfad. `PATH.public()`, `PATH.private()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()`, `PATH.templates()`, `PATH.flowstreams()` und `PATH.scripts()` funktionieren für ihre Verzeichnisse genauso.\n\nExample: Pfade\n```js\nPATH.root();                 // '/www/app'\nPATH.root('config');         // '/www/app/config'\nPATH.private('report.pdf');  // '/www/app/private/report.pdf'\n```\n\n### PATH.databases([path])\n\nType: `method`\n\nGibt das Datenbankverzeichnis oder einen Pfad darin zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ein relativer Pfad. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis `/databases/` enthält die Dateien der NoSQL-Datenbanken, `MEMORIZE()`-Dateien und andere Daten der Anwendung. Es wird erstellt, wenn du zum ersten Mal einen Pfad darin anforderst.\n\nExample: Eine Datendatei\n```js\nvar filename = PATH.databases('import.json');\nFs.writeFile(filename, JSON.stringify(data), NOOP);\n```\n\n### PATH.temp([path])\n\nType: `method`\n\nGibt das temporäre Verzeichnis oder einen Pfad darin zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ein relativer Pfad. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis `/tmp/` enthält Uploads, zwischengespeicherte Dateien und kompilierte Assets. `PATH.tmp()` ist ein Alias. Beim Start der Anwendung löscht das Framework dort seine eigenen temporären Dateien (`.js`-, `.css`-, `.html`-, `.htm`-, `.tmp`- und `.upload`-Dateien). Bewahre Daten, die bleiben müssen, in `/databases/` auf.\n\nExample: Eine temporäre Datei\n```js\nvar filename = PATH.temp(UID() + '.csv');\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 absoluter Pfad. |\n| `callback` | `Function` | no |  | `function(exists, size, isfile)`. |\n\nReturns: `Promise<Boolean>` Wenn `callback` weggelassen wird.\n\nDer Callback erhält drei Argumente: `exists`, die Größe in Bytes und `isfile` (`true` für eine Datei, `false` für ein Verzeichnis). Ohne Callback gibt die Funktion eine Promise zurück, die mit `exists` erfüllt wird.\n\nExample: Eine Datei prüfen\n```js\nif (await PATH.exists(PATH.databases('settings.json')))\n\tprint('Settings found');\n\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isfile) {\n\tprint(exists, size, isfile);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nLöscht eine oder mehrere Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|Array` | yes |  | Ein absoluter Pfad oder ein Array von Pfaden. |\n| `callback` | `Function` | no |  | `function()`. |\n\nLöscht die Dateien nacheinander und ruft dann den Callback auf. Fehler (zum Beispiel eine fehlende Datei) werden ignoriert.\n\nExample: Dateien löschen\n```js\nPATH.unlink([PATH.temp('a.csv'), PATH.temp('b.csv')], function() {\n\tprint('Removed');\n});\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nLöscht Verzeichnisse mit ihrem gesamten Inhalt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|Array` | yes |  | Ein absoluter Pfad oder ein Array von Pfaden. |\n| `callback` | `Function` | no |  | `function()`. |\n\nFür jedes Verzeichnis werden alle Dateien gelöscht, dann die Unterverzeichnisse, beginnend mit dem tiefsten, und dann das Verzeichnis selbst. Danach wird der Callback aufgerufen.\n\nExample: Ein Verzeichnis löschen\n```js\nPATH.rmdir(PATH.temp('export'), function() {\n\tprint('Directory removed');\n});\n```\n\n### Total.FsPromises\n\nType: `property`\n\nDas Node.js-Modul `node:fs/promises`.\n\nReturns: `Object` Das Modul `node:fs/promises`.\n\nDie Promise-Version der Dateisystemfunktionen von Node.js, vom Framework geladen. `F.FsPromises` ist dasselbe Objekt, und `Total.Fs` (`F.Fs`) ist das Modul `node:fs`.\n\nExample: Lesen und auflisten\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\nvar files = await Total.FsPromises.readdir(PATH.public());\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nWandelt einen beliebigen Wert in eine Zahl um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der umzuwandelnde Wert. |\n| `def` | `Number` | no | `0` | Das Ergebnis für leere oder ungültige Werte. |\n\nReturns: `Number`\n\nEine Zahl wird unverändert zurückgegeben. Ein String wird getrimmt und mit dem unären `+` umgewandelt; andere Werte werden zuerst in einen String umgewandelt. `null`, `undefined`, ein leerer String und ein Wert, der keine Zahl ist, ergeben `def` (standardmäßig 0). Das Ergebnis wird nicht gerundet (`'1.5'` ergibt `1.5`). `U.parseFloat(value, [def])` funktioniert genauso und akzeptiert zusätzlich ein Komma als Dezimaltrennzeichen (`'12,50'` ergibt `12.5`).\n\nExample: Query-Werte\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\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 |  | Der umzuwandelnde Wert. |\n| `def` | `Boolean` | no | `false` | Das Ergebnis für `null` oder `undefined`. |\n\nReturns: `Boolean`\n\nEin Boolean wird unverändert zurückgegeben; eine Zahl ist `true`, wenn sie größer als 0 ist; die Strings `true`, `1` und `on` (in beliebiger Schreibweise) sind `true` und jeder andere String ist `false`. `null` und `undefined` ergeben `def` (standardmäßig `false`).\n\nExample: Eine Checkbox\n```js\nvar newsletter = U.parseBoolean(this.body.newsletter); // 'on' -> true\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nLiest einen verschachtelten Wert über einen Pfad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Das zu lesende Objekt. |\n| `path` | `String` | yes |  | Der Pfad. |\n\nReturns: `Object` Der Wert oder `undefined`.\n\nDer Pfad verwendet Punkte und eckige Klammern: `a.b.c`, `items[0].name`. Fehlt ein Teil des Pfads, gibt sie `undefined` zurück, statt einen Fehler auszulösen. Pfade mit Leerzeichen, runden Klammern oder Schlüsselwörtern wie `__proto__` und `constructor` werden abgelehnt (`undefined`). Kompilierte Lesefunktionen werden pro Pfad zwischengespeichert.\n\nExample: Verschachtelte Werte\n```js\nvar data = { user: { address: { city: 'Bratislava' } }, items: [{ name: 'A' }] };\nU.get(data, 'user.address.city');  // 'Bratislava'\nU.get(data, 'items[0].name');      // 'A'\nU.get(data, 'user.phone.number');  // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nSchreibt einen verschachtelten Wert über einen Pfad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Das Objekt, in das geschrieben wird. |\n| `path` | `String` | yes |  | Der Pfad. |\n| `value` | `Object` | yes |  | Der Wert. |\n\nReturns: `Object` Der geschriebene Wert.\n\nFehlende Objekte auf dem Pfad werden erstellt. Ein Pfad, der mit `[]` endet, hängt den Wert an das Array an, und ein Index erstellt ein Array mit Objekten darin (`items[0].name`). Pfade mit Leerzeichen, Klammern oder Schlüsselwörtern wie `__proto__` und `constructor` werden abgelehnt: Es wird nichts geschrieben. Gibt den Wert zurück.\n\nExample: Ein Objekt aufbauen\n```js\nvar model = {};\nU.set(model, 'address.city', 'Bratislava');\nU.set(model, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\nExample: Pfad mit einem Index\n```js\nvar model = {};\nU.set(model, 'items[0].name', 'Pen');\n// { items: [{ name: 'Pen' }] }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nKopiert die Schlüssel von source in target.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | Das Objekt, in das geschrieben wird. |\n| `source` | `Object` | yes |  | Das zu lesende Objekt. |\n| `rewrite` | `Boolean` | no | `true` | `false` behält vorhandene Werte. |\n\nReturns: `Object` Das Ziel.\n\nJeder Schlüssel von `source` wird in `target` geklont. Ist `rewrite` auf `false` gesetzt, werden Schlüssel, die in `target` bereits existieren, nicht geändert – so füllst du Standardwerte. Gibt `target` zurück.\n\nExample: Standardwerte\n```js\nvar options = { limit: 50 };\nU.extend(options, { limit: 10, sort: 'name' }, false);\n// { limit: 50, sort: 'name' }\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nGibt eine Vergleichsfunktion für Array.sort() zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Zum Beispiel `name` oder `price_desc,name`. |\n\nReturns: `Function` `function(a, b)` für `Array.prototype.sort()`.\n\n`sort` ist eine kommagetrennte Liste von Schlüsseln; füge `_desc` für absteigende Reihenfolge hinzu (`_asc` ist der Standard). Verschachtelte Schlüssel verwenden Punkte (`address.city`). Der Typ jedes Schlüssels wird beim ersten Verwenden des Ausdrucks aus dem ersten nicht leeren Wert ermittelt und für spätere Verwendungen desselben Ausdrucks beibehalten: Strings werden unter Berücksichtigung diakritischer Zeichen verglichen, Zahlen, Booleans und Datumswerte nach ihrem Wert.\n\nExample: Produkte sortieren\n```js\nproducts.sort(U.sortcomparer('price_desc,name'));\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nGibt eine zufällige Ganzzahl in einem Bereich zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | Der größte Wert. |\n| `min` | `Number` | no | `0` | Der kleinste Wert. |\n\nReturns: `Number`\n\nGibt eine Ganzzahl zwischen `min` und `max` zurück, beide eingeschlossen.\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 |  | Die Anzahl der Zeichen. |\n\nReturns: `String`\n\nDie Zeichen sind `0-9`, `A-Z` und `a-z`. `U.random_string(length)` verwendet nur Buchstaben und `U.random_number(length)` nur Ziffern (als String zurückgegeben, der nicht mit 0 beginnt). Diese Werte stammen aus `Math.random()`: Verwende sie nicht als Passwörter oder Sicherheits-Tokens.\n\nExample: Zufällige Strings\n```js\nU.random_text(8);    // 'yb7JVb2a'\nU.random_string(6);  // 'HNXkTk'\nU.random_number(6);  // '825174'\n```\n\n### U.convert62(number)\n\nType: `method`\n\nKonvertiert eine Zahl in einen Base-62-String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | Eine nicht negative Zahl. |\n\nReturns: `String`\n\nDie Ziffern sind `0-9`, `A-Z` und `a-z`, in dieser Reihenfolge. Die Zahl wird zuerst abgerundet. `U.from62(value)` wandelt den String zurück in die Zahl. Verwende sie für kurze Codes, die aus numerischen IDs gebildet werden.\n\nExample: Kurze Codes\n```js\nvar code = U.convert62(123456);  // 'W7E'\nvar id = U.from62(code);         // 123456\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nGibt die Erweiterung eines Dateinamens zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Ein Dateiname, ein Pfad oder eine URL. |\n| `raw` | `Boolean` | no | `false` | `true` behält die ursprüngliche Schreibweise. |\n\nReturns: `String`\n\nGibt den Teil nach dem letzten Punkt zurück, ohne den Punkt und in Kleinbuchstaben (mit `raw` in der ursprünglichen Schreibweise). Ein Query String nach `?` wird ignoriert. Gibt einen leeren String zurück, wenn der Name keine Erweiterung hat.\n\nExample: Erweiterungen\n```js\nU.getExtension('/img/Photo.JPG');      // 'jpg'\nU.getExtension('/files/a.pdf?v=1');    // 'pdf'\nU.getExtension('README');              // ''\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 |  | Ein Pfad oder eine URL. |\n\nReturns: `String`\n\nGibt den Dateinamen (oder das letzte Verzeichnis) eines Pfads mit `/`- oder `\\\\`-Trennzeichen zurück. Ein abschließendes Trennzeichen wird ignoriert.\n\nExample: Dateinamen\n```js\nU.getName('/www/app/public/logo.png');  // 'logo.png'\nU.getName('/www/app/public/');          // 'public'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nGibt den MIME-Typ für eine Erweiterung zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Eine Erweiterung, z. B. `png` oder `.png`. |\n\nReturns: `String`\n\nDie Erweiterung darf mit einem Punkt beginnen. Unbekannte Erweiterungen ergeben `application/octet-stream`. `U.getExtensionFromContentType(type)` macht das Umgekehrte und gibt die erste Erweiterung mit diesem Typ zurück (oder `undefined`). Die ganze Tabelle ist `U.contentTypes`.\n\nExample: Content-Types\n```js\nU.getContentType('png');                     // 'image/png'\nU.getContentType('.json');                   // 'application/json'\nU.getExtensionFromContentType('image/png');  // 'png'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nKodiert Text oder einen Buffer in Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Die zu kodierenden Daten. |\n\nReturns: `String`\n\nEin Buffer wird direkt kodiert; andere Werte werden in einen String umgewandelt und als UTF-8 kodiert. `U.atob(value)` dekodiert Base64 zurück in einen UTF-8-String.\n\nExample: Base64\n```js\nvar encoded = U.btoa('Hello');   // 'SGVsbG8='\nvar text = U.atob(encoded);      // 'Hello'\n```\n\n### U.validhost(host)\n\nType: `method`\n\nPrüft, ob ein Hostname reines ASCII ist und eine IP-Adresse in ihrer kanonischen Form vorliegt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | Der Hostname oder die IP-Adresse. |\n\nReturns: `Boolean` `true` für einen gültigen Host.\n\nGibt `false` für einen Wert zurück, der kein String ist, leer ist oder ein Zeichen außerhalb des sichtbaren ASCII-Bereichs enthält (Leerzeichen, NUL-Bytes, Buchstaben mit Akzenten). Ein Wert, der nur aus Zahlen und Punkten (oder Hex-Zahlen) besteht, muss eine kanonische IPv4-Adresse sein: `127.0.0.1` ist gültig, `127.1`, `0127.0.0.1`, `0x7f.0.0.1` und `2130706433` sind es nicht. Andere ASCII-Werte, einschließlich IPv6-Adressen, geben `true` zurück; die Funktion prüft nicht die vollständige Syntax eines Hostnamens. Wandle einen internationalen Namen zuerst mit `U.tohost()` um.\n\nExample: Hosts prüfen\n```js\nU.validhost('example.com');     // true\nU.validhost('127.0.0.1');       // true\nU.validhost('127.1');           // false\nU.validhost('0x7f.0.0.1');      // false\nU.validhost('münchen.de');      // false\nU.validhost('evil.example\\0.trusted.example'); // false\n```\n\n### U.tohost(host)\n\nType: `method`\n\nWandelt einen Hostnamen in seine kanonische ASCII-Form um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | Der Hostname oder die IP-Adresse. |\n\nReturns: `String` Der kanonische Host oder ein leerer String.\n\nWandelt den Host mit dem URL-Parser von Node.js um: Buchstaben werden kleingeschrieben, ein internationaler Name wird zu Punycode, und eine IPv4-Adresse in einer anderen Schreibweise wird zur Punktschreibweise (eine führende `0` bedeutet eine Oktalzahl, `0x` eine Hex-Zahl). Das Ergebnis wird dann mit `U.validhost()` geprüft. Ein Wert, der `:` enthält (eine IPv6-Adresse), wird nur geprüft. Gibt einen leeren String zurück, wenn der Host nicht gültig ist, also prüfe das Ergebnis, bevor du es verwendest.\n\nExample: Hosts umwandeln\n```js\nU.tohost('münchen.de');      // 'xn--mnchen-3ya.de'\nU.tohost('EXAMPLE.com');     // 'example.com'\nU.tohost('127.1');           // '127.0.0.1'\nU.tohost('0x7f.0.0.1');      // '127.0.0.1'\nU.tohost('evil.example\\0.trusted.example'); // ''\n```\n\nExample: Eingaben validieren\n```js\nfunction host(value) {\n\tvar host = U.tohost(value);\n\tif (!host)\n\t\tthrow new Error('Invalid hostname');\n\treturn host;\n}\n```\n\n### U.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` | no |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Millisekunden, bevor das Warten fehlschlägt. |\n| `interval` | `Number` | no | `500` | Millisekunden zwischen den Prüfungen. |\n\nReturns: `Promise` Wenn `callback` weggelassen wird.\n\n`validator` wird sofort und danach alle `interval` Millisekunden aufgerufen, bis er `true` zurückgibt; dann erhält der Callback `(null, true)`. Läuft zuerst `timeout` ab, erhält der Callback einen `Error('Timeout')`. Ohne Callback gibt die Funktion eine Promise zurück, die auf dieselbe Weise erfüllt oder abgelehnt wird.\n\nExample: Auf eine Verbindung warten\n```js\nawait U.wait(() => MAIN.db != null, null, 10000, 200);\nprint('Database ready');\n```\n\n### U.resolve(url, callback, [param])\n\nType: `method`\n\nLöst den Host einer URL in IPv4-Adressen auf, mit einem Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Eine absolute URL. |\n| `callback` | `Function` | yes |  | `function(err, uri, param, addresses)`. |\n| `param` | `Any` | no |  | Ein Wert, der an den Callback übergeben wird. |\n\nParst `url`, prüft seinen Hostnamen mit `U.validhost()` und fragt die DNS-Server nach seinen IPv4-Adressen (`dns.resolve4()`, daher wird die hosts-Datei nicht verwendet). Der Callback erhält `(err, uri, param, addresses)`: `uri` ist die geparste URL, deren `host` auf die erste Adresse gesetzt ist, `param` ist das dritte Argument und `addresses` die ganze Liste. Die Adressen werden für die Lebensdauer des Prozesses gecacht; eine fehlgeschlagene Abfrage wird noch einmal versucht, bevor `err` übergeben wird.\n\nEin String, der keine URL ist, führt zu `TypeError: Invalid URL`, und ein ungültiger Hostname führt ohne DNS-Abfrage zum Fehler `Invalid hostname`. Bei `http`- und `https`-URLs wandelt der URL-Parser den Host bereits um; bei anderen Schemata führt eine nicht kanonische Adresse wie `tcp://127.1/` zu `Invalid hostname`. `REQUEST()` verwendet diese Funktion mit der Option `resolve: true`, und `RESTBuilder` standardmäßig.\n\nExample: Einen Host auflösen\n```js\nU.resolve('https://example.com/api/', function(err, uri, param, addresses) {\n\tif (err)\n\t\tconsole.log(err.message || err.code);\n\telse\n\t\tconsole.log(uri.hostname, addresses);\n});\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nTeilt einen Datenstrom anhand von Trennzeichen in Teile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Der Anfang eines Teils oder das Trennzeichen. |\n| `end` | `String|Buffer` | no |  | Das Ende eines Teils. |\n| `callback` | `Function` | yes |  | `function(value, index)`; gib `false` zurück, um abzubrechen. |\n| `skip` | `Number` | no | `0` | Die Anzahl der zu ignorierenden ersten Teile. |\n| `stream` | `Stream` | no |  | Ein Stream, dessen `end`-Event den Rest verarbeitet. |\n\nReturns: `Function` `function(chunk)`.\n\nGibt eine Funktion zurück, die du mit jedem Chunk (einem Buffer) aufrufst, zum Beispiel als `data`-Handler eines Streams. Mit `beg` und `end` erhält der Callback jeden Teil, der mit `beg` beginnt und mit `end` endet, beide eingeschlossen (zum Beispiel ein `<item>...</item>` einer großen XML-Datei). Nur mit `beg` ist `beg` ein Trennzeichen, und der Callback erhält jeden Teil bis einschließlich dieses Zeichens (zum Beispiel Zeilen mit `\\n`). Der Callback erhält `(value, index)` mit dem Wert als String; die Rückgabe von `false` beendet das Parsen. `skip` ignoriert die entsprechende Anzahl erster Teile. Mit `stream` werden die verbleibenden Daten verarbeitet, wenn der Stream endet. `U.streamer2()` nimmt dieselben Argumente und übergibt Buffer statt Strings.\n\nExample: Eine große XML-Datei lesen\n```js\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\nstream.on('data', U.streamer('<product>', '</product>', function(value, index) {\n\tvar product = value.parseXML();\n\tprint(index, product);\n}));\n```\n\nExample: Zeilen einer CSV-Datei\n```js\nvar stream = Fs.createReadStream(filename);\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tvar cols = line.trim().split(';');\n}, 1, stream));  // skips the header line\n```\n\n### U.connect(options, [callback])\n\nType: `method`\n\nÖffnet eine TCP- oder TLS-Verbindung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | `{ host, port, secure, tls, timeout }` und, mit `secure`, weitere Optionen von `tls.connect()`. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nVerbindet sich mit `options.host` und `options.port` und ruft `callback(err, meta)` auf, sobald die Verbindung offen ist. Der Host wird zuerst mit `U.tohost()` umgewandelt, daher wird ein internationaler Name als Punycode gesendet und `127.1` als `127.0.0.1`; ein ungültiger Host führt zum Fehler `Invalid hostname`, und es wird keine Verbindung hergestellt. Mit `secure: true` verwendet die Verbindung von Anfang an TLS, und die anderen Optionen (`servername`, `rejectUnauthorized`, `ca` ...) gehen an `tls.connect()`. Mit `tls` beginnt die Verbindung als normales TCP und wird auf TLS umgestellt, sobald sie offen ist: `tls: true` verwendet die Standardoptionen von `tls.connect()`, ein Objekt übergibt seine Optionen (`servername`, `rejectUnauthorized`, `ca` ...). Mit `timeout` (in Millisekunden) führt eine Verbindung, die nicht rechtzeitig offen ist, zum Fehler `Timeout`.\n\n`meta` hat `socket` (den Node.js-Socket), `opt` (die Optionen mit dem umgewandelten Host), `write(data)`, `ondata(fn)` für die empfangenen Chunks und `close()` (auch `destroy()`). `LDAP()` verbindet sich mit dieser Funktion.\n\nExample: Die Begrüßung eines Servers lesen\n```js\nU.connect({ host: 'mail.example.com', port: 25, timeout: 5000 }, function(err, meta) {\n\tif (err) {\n\t\tconsole.log(err.message);\n\t\treturn;\n\t}\n\tmeta.ondata(function(chunk) {\n\t\tconsole.log(chunk.toString());\n\t\tmeta.close();\n\t});\n});\n```\n\nExample: Auf TLS umstellen\n```js\nU.connect({ host: 'mail.example.com', port: 465, tls: { servername: 'mail.example.com' } }, function(err, meta) {\n\tif (!err)\n\t\tconsole.log(meta.socket.encrypted); // true\n});\n```\n\n### U.ls(path, [callback], [filter])\n\nType: `method`\n\nListet die Dateien und Verzeichnisse eines Verzeichnisses rekursiv 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 |  | Der Filter. |\n\nReturns: `Promise` `{ files, directories }`, wenn `callback` weggelassen wird.\n\nDer Callback erhält zwei Arrays mit absoluten Pfaden: `files` und `directories` (Verzeichnisse enden mit dem Pfadtrennzeichen). `filter` kann ein String sein (Pfade, die ihn enthalten, ohne Beachtung der Groß-/Kleinschreibung), ein regulärer Ausdruck oder eine Funktion `(path, isdirectory)`, die `true` zurückgibt, um das Element zu behalten; String- und Regex-Filter gelten nur für Dateien. Ein Verzeichnis, das der Filter verwirft, wird nicht durchsucht. Ohne Callback gibt die Funktion eine Promise mit `{ files, directories }` zurück. `U.ls2()` nimmt dieselben Argumente und gibt Dateien als `{ filename, stats }`-Objekte mit den `fs.Stats` jeder Datei zurück.\n\nExample: JSON-Dateien finden\n```js\nU.ls(PATH.databases(), function(files, directories) {\n\tprint(files);\n}, /\\.json$/);\n```\n\nExample: Größen mit ls2\n```js\nvar result = await U.ls2(PATH.public('uploads'));\nvar size = 0;\nfor (var file of result.files)\n\tsize += file.stats.size;\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nSpeichert eine große Liste seitenweise in temporären Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein eindeutiger Name, der für die Dateinamen verwendet wird. |\n| `max` | `Number` | no | `50` | Elemente pro Seite. |\n\nReturns: `Chunker`\n\nEin Chunker sammelt Elemente mit `write(item)` (Alias `append()`); alle `max` Elemente werden in eine Datei `tmp/{name}-{index}.chunker` geschrieben (mit deflate komprimiert, wenn `compress` `true` ist, der Standard), damit der Speicherbedarf klein bleibt. Rufe `end()` auf, um den Rest zu schreiben. Danach liest `each(onitem, [ondone])` die Seiten der Reihe nach: `onitem(items, next, index)` erhält eine Seite und ruft `next()` auf, um fortzufahren, und `percentage` gibt an, wie weit das Lesen fortgeschritten ist. `read(index, callback)` liest eine Seite. Mit `autoremove` (standardmäßig `true`) wird jede Datei nach dem Lesen gelöscht; `clear()` löscht alle Dateien und `destroy()` gibt zusätzlich den Chunker frei. Die Eigenschaften `count` und `pages` enthalten die Anzahl der Elemente und Seiten.\n\nExample: Einen großen Export verarbeiten\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var row of rows)\n\tchunker.write(row);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tprint('Page', index, chunker.percentage + '%');\n\tsend(items, next);\n}, function() {\n\tprint('Done', chunker.count, 'items');\n});\n```\n\n### chunker.load([callback])\n\nType: `method` · Since: `0.0.16`\n\nFindet die Seiten, die ein früherer Chunker mit demselben Namen auf der Festplatte hinterlassen hat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `Promise` Wenn `callback` weggelassen wird.\n\nZählt die Dateien des Chunkers im temporären Verzeichnis und setzt den internen Seitenindex, sodass `each()` und `read()` die Seiten lesen können, die eine frühere Instanz geschrieben und nicht gelesen hat (zum Beispiel vor einem Neustart). Erstelle den Chunker mit demselben `name`. Der Callback erhält `(null, count)`; ohne Callback gibt die Funktion eine Promise zurück, die erfüllt wird, wenn das Zählen abgeschlossen ist.\n\nExample: Einen Chunker fortsetzen\n```js\nvar chunker = U.chunker('export');\nawait chunker.load();\nchunker.each(function(items, next) {\n\tsend(items, next);\n});\n```\n\n### new U.EventEmitter2() / U.EventEmitter2(obj)\n\nType: `class`\n\nEin kleiner Event-Emitter.\n\nReturns: `EventEmitter2`\n\nEin Objekt mit `on(name, fn)`, `once(name, fn)`, `off(name, [fn])` und `emit(name, ...args)` (bis zu sieben Argumente). `off(name)` ohne Funktion entfernt alle Handler des Events. Handler laufen mit dem Emitter als `this`. Mit einem Objekt aufgerufen (`U.EventEmitter2(obj)`), fügt sie diese Methoden dem Objekt hinzu, sofern es nicht bereits `emit` hat, und gibt es zurück.\n\nExample: Events auf deinem Objekt\n```js\nvar Cart = {};\nU.EventEmitter2(Cart);\n\nCart.on('add', function(item) {\n\tprint('Added', item.name);\n});\n\nCart.emit('add', { name: 'Shoes' });\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nVerschleiert einen String mit einem Schlüssel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der Text. |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `encode` | `String` | no | `'base64'` | Die Ausgabekodierung oder `buffer`. |\n\nReturns: `String|Buffer`\n\nKodiert den String mit dem Schlüssel und einer zufälligen 4-Byte-Maske und gibt ihn in Base64 zurück (oder in der Kodierung, die du festlegst; `buffer` gibt einen Buffer zurück). Dieselbe Eingabe ergibt jedes Mal eine andere Ausgabe. `U.decrypt_data(value, key, [encode])` gibt den ursprünglichen String zurück, oder `null` bei ungültiger Eingabe. Das ist eine leichte Verschleierung, keine starke Verschlüsselung; für sensible Daten verwende `ENCRYPT()` (siehe [Verschlüsselung](../../guides/encryption/)).\n\nExample: Hin und zurück\n```js\nvar data = U.encrypt_data('hello', 'mykey');\nvar text = U.decrypt_data(data, 'mykey');  // 'hello'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nSigniert einen Bezeichner, sodass er nicht verändert werden kann.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | Der Bezeichner. |\n| `key` | `String` | no | `CONF.secret` | Der Schlüssel. |\n\nReturns: `String`\n\nGibt den Bezeichner mit einer vorangestellten Prüfsumme zurück, die aus dem Wert, dem Schlüssel und `CONF.secret_uid` gebildet wird. `U.decrypt_uid(value, [key])` prüft ihn und gibt den ursprünglichen Bezeichner zurück (eine Zahl, wenn das Original eine Zahl war), oder `null`, wenn der Wert verändert wurde. Der Bezeichner selbst bleibt lesbar. Ohne `key` wird `CONF.secret` verwendet.\n\nExample: Signierte ID in einem Link\n```js\nvar signed = U.encrypt_uid(123, 'mykey');   // 'n...x123', the checksum depends on CONF.secret_uid\nU.decrypt_uid(signed, 'mykey');             // 123\nU.decrypt_uid('n2v55u4jx124', 'mykey');     // null\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifiziert JavaScript; U.minify_css() und U.minify_html() machen dasselbe für CSS und HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der Quellcode. |\n\nReturns: `String`\n\nDas sind die Minifier, die das Framework für statische Dateien und Views verwendet. Sie nehmen einen String entgegen und geben den minifizierten String zurück.\n\nExample: Minifizieren\n```js\nU.minify_js('var a = 1 ;  // note\\n');  // 'var a=1;'\nU.minify_css('a { color : red ; }');     // 'a{color:red}'\nU.minify_html(html);\n```\n\n### U.aistreamer(online, [onmessage])\n\nType: `method` · Since: `0.0.16`\n\nParst eine gestreamte Antwort einer KI-Chat-API in Textzeilen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `online` | `Function` | yes |  | `function(line)`, wird für jede vollständige Textzeile aufgerufen. |\n| `onmessage` | `Function` | no |  | `function(message)`, wird für jede geparste JSON-Nachricht aufgerufen. |\n\nReturns: `Function` `function(chunk)`.\n\nGibt eine Funktion zurück, die du mit jedem Chunk (einem Buffer) einer gestreamten Antwort aufrufst. Sie liest JSON-Nachrichten Zeile für Zeile in zwei Formaten: Server-Sent Events mit `data: {...}` (OpenAI Completions, wo der Text in `choices[0].delta.content` steht und `data: [DONE]` sie beendet) und einfache JSON-Zeilen (Ollama, wo der Text in `message.content` steht und `done` sie beendet). Der Text wird gesammelt, und `online(line)` wird für jede vollständige Zeile aufgerufen. `onmessage(obj)` erhält, wenn du es setzt, jede geparste Nachricht; JSON-Datumswerte werden dann als Datum geparst.\n\nExample: Eine Antwort Zeile für Zeile ausgeben\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nCacht das Ergebnis einer Aufgabe in einer Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Kennung des gecachten Elements. |\n| `expire` | `String` | yes |  | Wie lange die Datei gültig ist, zum Beispiel `'5 minutes'`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `maker` | `Function` | yes |  | `function(next, id)`, die den Wert erstellt. |\n| `encoding` | `String` | no | `json` | `json` oder eine Dateikodierung wie `utf8`. |\n\nSucht die Datei von `id` in `tmp/`. Wenn sie existiert und neuer als `expire` ist, geht ihr Inhalt an `callback(err, response)`. Andernfalls läuft `maker(next, id)`; `next(err, response, [load])` schreibt die Antwort in die Datei und ruft `callback` auf, es sei denn, `load` ist `false`. Mit der Kodierung `json` wird der Wert als JSON gespeichert und zurück geparst; jede andere Kodierung speichert und liest den Rohinhalt.\n\nExample: Eine entfernte Liste cachen\n```js\nFILECACHE('currencies', '1 day', function(err, response) {\n\tMAIN.currencies = response;\n}, function(next) {\n\tREQUEST({ url: 'https://example.com/rates.json', callback: function(err, response) {\n\t\tnext(err, err ? null : response.body.parseJSON());\n\t}});\n});\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID()","since":"","deprecated":false},{"type":"method","name":"GUID([length])","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"HASH(value, [type])","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"CLONE(obj, [skip], [nofunctions])","signature":"CLONE(obj, [skip], [nofunctions])","since":"","deprecated":false},{"type":"method","name":"COPY(source, [target], [all])","signature":"COPY(source, [target], [all])","since":"","deprecated":false},{"type":"method","name":"DIFFARR(prop, db, form)","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"QUERIFY([url], obj)","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"PROMISIFY(fn, [a], [b], [c])","signature":"PROMISIFY(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"ERROR([name])","signature":"ERROR([name])","since":"","deprecated":false},{"type":"method","name":"print()","signature":"print(...values)","since":"","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"NOOP","signature":"NOOP","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","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":"CACHE.set(key, value, [expire])","signature":"CACHE.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"CACHE.get(key, [def])","signature":"CACHE.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"CACHE.remove(key)","signature":"CACHE.remove(key)","since":"","deprecated":false},{"type":"method","name":"CACHE.reset([search])","signature":"CACHE.reset([search])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE([name], [delay], [skip])","signature":"MEMORIZE([name], [delay], [skip])","since":"","deprecated":false},{"type":"method","name":"BACKUP(filename, files, [callback], [filter])","signature":"BACKUP(filename, files, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE(filename, target, [callback], [filter])","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"PATH.root([path])","signature":"PATH.root([path])","since":"","deprecated":false},{"type":"method","name":"PATH.databases([path])","signature":"PATH.databases([path])","since":"","deprecated":false},{"type":"method","name":"PATH.temp([path])","signature":"PATH.temp([path])","since":"","deprecated":false},{"type":"method","name":"PATH.exists(path, [callback])","signature":"PATH.exists(path, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink(files, [callback])","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir(directories, [callback])","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"property","name":"Total.FsPromises","signature":"Total.FsPromises","since":"","deprecated":false},{"type":"method","name":"U.parseInt(value, [def])","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseBoolean(value, [def])","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.get(obj, path)","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set(obj, path, value)","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.extend(target, source, [rewrite])","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer(sort)","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.random([max], [min])","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text(length)","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.convert62(number)","signature":"U.convert62(number)","since":"","deprecated":false},{"type":"method","name":"U.getExtension(filename, [raw])","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName(path)","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType(ext)","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.btoa(value)","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.validhost(host)","signature":"U.validhost(host)","since":"","deprecated":false},{"type":"method","name":"U.tohost(host)","signature":"U.tohost(host)","since":"","deprecated":false},{"type":"method","name":"U.wait(validator, [callback], [timeout], [interval])","signature":"U.wait(validator, [callback], [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"U.resolve(url, callback, [param])","signature":"U.resolve(url, callback, [param])","since":"","deprecated":false},{"type":"method","name":"U.streamer(beg, [end], callback, [skip], [stream])","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.connect(options, [callback])","signature":"U.connect(options, [callback])","since":"","deprecated":false},{"type":"method","name":"U.ls(path, [callback], [filter])","signature":"U.ls(path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"U.chunker(name, [max])","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.load([callback])","signature":"chunker.load([callback])","since":"0.0.16","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2() / U.EventEmitter2(obj)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_data(value, key, [encode])","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid(value, [key])","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.minify_js(value)","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.aistreamer(online, [onmessage])","signature":"U.aistreamer(online, [onmessage])","since":"0.0.16","deprecated":false},{"type":"method","name":"FILECACHE(id, expire, callback, maker, [encoding])","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwwLBgx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/utilities/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Utilidades","summary":"Funciones de U/Utils, helpers globales (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), objetos compartidos, CACHE, MEMORIZE, BACKUP, RESTORE y PATH.","markdown":"---\ntitle: Utilidades\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/utilities/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Utilidades\n\n> Funciones de U/Utils, helpers globales (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), objetos compartidos, CACHE, MEMORIZE, BACKUP, RESTORE y PATH.\n\nEsta página lista los helpers globales, los objetos globales compartidos, la `CACHE` en memoria, las funciones de `PATH` y las funciones del módulo `U` (`Utils`) que usan las aplicaciones. La guía [Utilidades](../../guides/utilities/) explica cómo encajan entre sí, con ejemplos. Los métodos añadidos a `String`, `Number`, `Date` y `Array` están en [Prototipos](../prototypes/).\n\n## API\n\n### U\n\nType: `property`\n\nEl módulo Utils como objeto global.\n\nReturns: `Object` El módulo Utils.\n\nTodas las funciones de `utils.js` están disponibles a través de `U` y su alias `Utils` (ambos apuntan al mismo objeto). Esta página documenta las funciones que usan las aplicaciones; las demás las usa el propio framework.\n\nExample: Usar un helper\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\nvar same = Utils === U;           // true\n```\n\n### UID()\n\nType: `method`\n\nDevuelve un nuevo identificador único.\n\nReturns: `String` Por ejemplo `JacVuE1cn61f`.\n\nEl identificador es una cadena corta de letras y dígitos: una marca de tiempo en base 62 (en décimas de segundo), un contador interno, un carácter aleatorio elegido al arrancar (cambia cada minuto), la longitud de la parte de tiempo, un dígito de paridad y la letra `f`. Los identificadores creados más tarde se ordenan después de los anteriores en la mayoría de los casos. El validador `uid` del framework (`DEF.validators.uid`) los acepta.\n\nExample: Un nuevo registro\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\nNOSQL('products').insert(model);\n```\n\n### GUID([length])\n\nType: `method`\n\nDevuelve una cadena con forma de UUID, o una cadena aleatoria de una longitud dada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | El número de caracteres. Omítelo para el formato con forma de UUID. |\n\nReturns: `String`\n\nSin `length`, devuelve una cadena con la forma `xxxxxxxx-xxxx-Nxxx-Yxxx-xxxxxxxxxxxx` (36 caracteres) construida a partir de la hora actual y dígitos hexadecimales aleatorios. Con `length`, devuelve ese número de caracteres aleatorios de `0-9` y `a-z`.\n\nExample: Tokens\n```js\nvar guid = GUID();       // '1a1e0561-0561-4c86-8eaf-d9a327a65943'\nvar token = GUID(30);    // 30 random characters\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nCalcula el hash de una cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El texto del que calcular el hash. |\n| `type` | `String` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32` o `crc32unsigned`. |\n\nReturns: `Number|String` Un número sin tipo, una cadena hexadecimal para los tipos md5/sha.\n\nSin `type`, devuelve un número de 32 bits sin signo calculado a partir de la cadena (rápido, no criptográfico). Con un tipo devuelve el hash como cadena hexadecimal (`md5`, `sha1`, `sha256`, `sha512`) o un número CRC32 (`crc32`, `crc32unsigned`). `value` debe ser una cadena; convierte antes los números con `+ ''`.\n\nExample: Hashes\n```js\nHASH('abc');            // 96354\nHASH('abc', 'md5');     // '900150983cd24fb0d6963f7d28e17f72'\nHASH(email, 'sha256');\n```\n\n### CLONE(obj, [skip], [nofunctions])\n\nType: `method`\n\nHace una copia profunda de un objeto o un array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array` | yes |  | El valor a copiar. Los demás valores se devuelven sin cambios. |\n| `skip` | `Object` | no |  | Claves que se dejan fuera, p. ej. `{ password: 1 }`. |\n| `nofunctions` | `Boolean` | no | `false` | `true` deja fuera las funciones. |\n\nReturns: `Object|Array` La copia.\n\nLos objetos y arrays anidados se copian, los buffers en propiedades de objetos se duplican, y las fechas, los errores y los demás valores que no son objetos se mantienen tal cual. `skip` es un objeto cuyas claves se dejan fuera de la copia en todos los niveles. Con `nofunctions`, también se dejan fuera las propiedades que contienen funciones.\n\nExample: Copiar sin una clave\n```js\nvar user = { id: 'abc', name: 'Peter', password: 'secret', address: { city: 'Bratislava' } };\nvar safe = CLONE(user, { password: 1 });\nsafe.address.city = 'Prague';  // user.address.city is still 'Bratislava'\n```\n\n### COPY(source, [target], [all])\n\nType: `method`\n\nCopia las claves de un objeto en otro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | El objeto a leer. |\n| `target` | `Object` | no |  | El objeto en el que escribir. |\n| `all` | `Boolean` | no | `true` | `false` escribe solo las claves que ya tiene `target`. |\n\nReturns: `Object` El destino (o la nueva copia).\n\nCada valor de `source` se clona y se escribe en `target`. Con `all` en `false`, solo se escriben las claves que ya están definidas en `target`, de modo que `target` funciona como una lista de campos permitidos. Sin `target`, devuelve una copia profunda de `source`.\n\nExample: Campos permitidos\n```js\nvar allowed = { name: '', email: '' };\nCOPY(this.body, allowed, false);\n// allowed contains only name and email from the body\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nCompara dos arrays de objetos por una propiedad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | La clave que identifica un elemento, p. ej. `id`. |\n| `db` | `Array` | yes |  | Los elementos actuales (por ejemplo, de la base de datos). |\n| `form` | `Array` | yes |  | Los elementos nuevos (por ejemplo, de un formulario). |\n\nReturns: `Object` `{ add: Array, upd: Array, rem: Array }`.\n\nLos elementos coinciden cuando sus valores de `prop` son iguales (`==`). El resultado tiene tres arrays: `add` contiene los elementos de `form` que no están en `db`, `upd` contiene pares `{ db, form }` de elementos coincidentes, y `rem` contiene los valores de `prop` de los elementos de `db` que no están en `form`.\n\nExample: Sincronizar elementos\n```js\nvar diff = DIFFARR('id', current, model.items);\n\nfor (var item of diff.add)\n\tNOSQL('items').insert(item);\n\nfor (var pair of diff.upd)\n\tNOSQL('items').modify(pair.form).where('id', pair.db.id);\n\nfor (var id of diff.rem)\n\tNOSQL('items').remove().where('id', id);\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nConstruye un query string a partir de un objeto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Una URL, opcionalmente con un método delante. |\n| `obj` | `Object` | yes |  | Los valores. |\n\nReturns: `String`\n\nLas claves y los valores se codifican para URL. Los valores `null`, `undefined` y vacíos se omiten, las fechas se escriben como cadenas ISO y los arrays se unen con comas. Sin `url`, el resultado empieza con `?` (o es una cadena vacía cuando no queda nada). Con `url`, el query string se añade con `?` o `&`; la URL puede empezar con un método HTTP (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `API`) seguido de un espacio, tal como lo aceptan `REQUEST()` y `AJAX()`. La función también es `U.querify()`.\n\nExample: Query strings\n```js\nQUERIFY({ q: 'red shoes', page: 2 });           // '?q=red%20shoes&page=2'\nQUERIFY('/api/?lang=en', { page: 2 });         // '/api/?lang=en&page=2'\nQUERIFY('GET https://example.com/', { id: 5 }); // 'GET https://example.com/?id=5'\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method`\n\nLlama a una función de estilo callback y devuelve una promesa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Una función cuyo último argumento es un callback. |\n| `a` | `Object` | no |  | El primer argumento. |\n| `b` | `Object` | no |  | El segundo argumento. |\n| `c` | `Object` | no |  | El tercer argumento. |\n\nReturns: `Promise`\n\n`fn` se llama con los argumentos que pases (hasta tres) y un callback `function(err, response)`. La promesa se rechaza con `err` o se resuelve con `response`. Pasa solo los argumentos que necesites: un argumento `undefined` termina la lista.\n\nExample: Leer un archivo\n```js\nvar Fs = require('fs');\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n\n### ERROR([name])\n\nType: `method`\n\nDevuelve un callback que registra los errores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | El nombre que se muestra con el error, p. ej. la función que falló. |\n\nReturns: `Function` `function(err)`.\n\nLa función devuelta recibe `err` como primer argumento y, cuando tiene valor, lo pasa al manejador de errores del framework (`DEF.onError`, que lo imprime y lo guarda en las estadísticas) con `name` como origen. Úsala para callbacks cuyo resultado no necesitas pero cuyos errores quieres ver.\n\nExample: Registrar una escritura fallida\n```js\nFs.writeFile(PATH.databases('cache.json'), JSON.stringify(data), ERROR('cache.save'));\n```\n\n### print(...values)\n\nType: `method`\n\nEscribe valores en la consola.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `values` | `Object` | yes |  | Los valores a imprimir. |\n\n`print` es `console.log`. El framework lo usa para su información de arranque.\n\nExample: Imprimir\n```js\nprint('Imported', count, 'products');\n```\n\n### NOW\n\nType: `property`\n\nUn Date con la hora actual, actualizado cada 5 segundos.\n\nReturns: `Date`\n\nEl framework asigna `new Date()` a `NOW` cada 5 segundos una vez cargado, y también cuando escribe un error, un registro de auditoría o un elemento de caché. Úsalo donde basta una precisión de unos segundos: expiraciones, líneas de log, campos `dtcreated`. No modifiques el objeto; asigna una nueva fecha en su lugar.\n\nExample: Expiración\n```js\nvar expire = NOW.add('1 hour');\nif (session.expire < NOW)\n\tdelete sessions[session.id];\n```\n\n### NOOP\n\nType: `property`\n\nUna función vacía.\n\nReturns: `Function`\n\nÚsala donde se requiere un callback pero no necesitas el resultado. Es la misma función que `U.noop`.\n\nExample: Ignorar el resultado\n```js\nFs.unlink(filename, NOOP);\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nUn objeto vacío congelado; EMPTYARRAY es un array vacío congelado.\n\nReturns: `Object`\n\n`EMPTYOBJECT` (`{}`) y `EMPTYARRAY` (`[]`) se crean una vez y se congelan con `Object.freeze()`, así que no se pueden modificar. Úsalos como valores por defecto en lugar de crear objetos nuevos, por ejemplo `var opt = options || EMPTYOBJECT;`. Nunca escribas en ellos: en modo estricto una escritura lanza una excepción.\n\nExample: Valores por defecto\n```js\nfunction find(filter) {\n\tvar opt = filter || EMPTYOBJECT;\n\tvar tags = opt.tags || EMPTYARRAY;\n\treturn tags.length;\n}\n```\n\n### MAIN\n\nType: `property`\n\nUn objeto global para el estado compartido de la aplicación.\n\nReturns: `Object`\n\nEl framework crea `MAIN` como un objeto vacío y no lo usa. Guarda ahí lo que comparten varios archivos de tu aplicación: ajustes cargados al arrancar, conexiones abiertas, contadores. Se puede leer en las vistas como `MAIN`.\n\nExample: Ajustes compartidos\n```js\n// definitions/settings.js\nMAIN.settings = MEMORIZE('settings');\n\n// a controller or an action\nvar title = MAIN.settings.title;\n```\n\n### REPO\n\nType: `property`\n\nUn objeto global para datos compartidos, disponible también en las vistas.\n\nReturns: `Object`\n\nUn objeto vacío que el framework crea al arrancar (también es `F.repo`). Las vistas pueden leerlo como `REPO`, lo que lo convierte en un buen lugar para los datos que necesitan las plantillas (layouts), por ejemplo un menú o la información de contacto.\n\nExample: Datos para la plantilla (layout)\n```js\nREPO.menu = [{ name: 'Home', url: '/' }, { name: 'Contact', url: '/contact/' }];\n\n// views/layout.html\n// @{foreach m in REPO.menu}<a href=\"@{m.url}\">@{m.name}</a>@{end}\n```\n\n### FUNC\n\nType: `property`\n\nUn objeto global para tus funciones compartidas.\n\nReturns: `Object`\n\nUn objeto vacío para las funciones que usan varias partes de la aplicación. Defínelas en `/definitions/` para que existan antes de la primera petición. Las vistas también pueden leer `FUNC`.\n\nExample: Una función compartida\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// anywhere\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nUn objeto global para datos de corta duración, que se vacía cada 5 minutos.\n\nReturns: `Object`\n\nCada 5 minutos el framework sustituye `TEMP` por un nuevo objeto vacío. Úsalo para datos temporales pequeños que pueden desaparecer en cualquier momento, como tokens de un solo uso o contadores de limitación. Léelo siempre a través de la global (`TEMP.key`), no de una referencia guardada, porque el objeto cambia.\n\nExample: Un token de corta duración\n```js\nvar token = GUID(20);\nTEMP[token] = { userid: user.id };\n\n// later\nvar data = TEMP[token];\nif (!data)\n\t$.invalid('The token has expired');\n```\n\n### MODS\n\nType: `property`\n\nLos módulos cargados, por su id.\n\nReturns: `Object`\n\nCada archivo `.js` de `/modules/` se carga al arrancar y se guarda en `MODS` bajo su `exports.id`, o bajo el nombre del archivo cuando no lo define. Su función `install()`, si existe, se llama después de cargarlo. `MODS` es el mismo objeto que `F.modules` y se puede leer en las vistas.\n\nExample: Un módulo\n```js\n// modules/pricing.js\nexports.id = 'pricing';\nexports.vat = function(price) {\n\treturn price * 1.2;\n};\n\n// anywhere\nvar total = MODS.pricing.vat(100);\n```\n\n### CACHE.set(key, value, [expire])\n\nType: `method`\n\nGuarda un valor en la caché en memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave. |\n| `value` | `Object` | yes |  | Cualquier valor. |\n| `expire` | `String` | no | `'5 minutes'` | Cuánto tiempo es válido el valor. |\n\nEl valor se mantiene en la memoria del proceso hasta que expira. `expire` es una duración en la forma que acepta `Date.add()` (`'30 seconds'`, `'5 minutes'`, `'1 hour'`, `'2 days'`). El valor se guarda tal cual, no se copia: si lo modificas, el valor en caché también cambia. Los elementos expirados se eliminan cada minuto.\n\nExample: Guardar un resultado en caché\n```js\nCACHE.set('products', items, '2 minutes');\n```\n\n### CACHE.get(key, [def])\n\nType: `method`\n\nLee un valor de la caché en memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave. |\n| `def` | `Object` | no |  | El valor devuelto cuando la clave no existe o ha expirado. |\n\nReturns: `Object`\n\nDevuelve el valor cuando existe y no ha expirado; si no, `def`. `CACHE.read()` es un alias.\n\nExample: Leer o cargar\n```js\nvar items = CACHE.get('products');\nif (!items) {\n\titems = await DATA.find('nosql/products').promise($);\n\tCACHE.set('products', items, '2 minutes');\n}\n```\n\n### CACHE.remove(key)\n\nType: `method`\n\nElimina un valor de la caché en memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave. |\n\nLlámala cuando cambien los datos en caché, para que la siguiente lectura cargue datos nuevos.\n\nExample: Invalidar\n```js\nNOSQL('products').insert(model).callback(function() {\n\tCACHE.remove('products');\n});\n```\n\n### CACHE.reset([search])\n\nType: `method`\n\nElimina muchos valores, o todos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | no |  | Una parte de las claves, o un patrón. |\n\nReturns: `Number` El número de claves eliminadas.\n\nSin `search`, se vacía toda la caché. Con una cadena, se elimina cada clave que la contiene; con una expresión regular, cada clave que coincide con ella. Devuelve el número de claves eliminadas (0 cuando se vacía toda la caché).\n\nExample: Eliminar un grupo\n```js\nCACHE.set('products_1', a);\nCACHE.set('products_2', b);\nCACHE.reset('products_');  // 2\nCACHE.reset(/^user_/);\nCACHE.reset();             // everything\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method`\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 el último cambio y la escritura. |\n| `skip` | `String|Array` | no |  | Claves que no se escriben en el archivo, como array o como cadena separada por comas. |\n\nReturns: `Object` Los datos con `save()` y `set(key, value)`.\n\nLee `databases/memorize_{name}.json` (o `databases/memorize.json` sin nombre) y devuelve su contenido como objeto (un objeto vacío cuando el archivo no existe). El objeto recibe dos funciones: `save()` programa una escritura de todo el objeto, y `set(key, value)` asigna un valor y llama a `save()`. La escritura ocurre `delay` milisegundos después de la última llamada, así que muchos cambios producen una sola escritura. `skip` lista las claves que no se escriben. Los argumentos `delay` y `skip` se pueden intercambiar. Llama a `MEMORIZE()` una vez por nombre y conserva el objeto; cada llamada vuelve a leer el archivo.\n\nExample: Ajustes que sobreviven a los reinicios\n```js\nvar settings = MEMORIZE('settings', 'cache');\n\nsettings.set('title', 'My shop');\n\nsettings.counter = (settings.counter || 0) + 1;\nsettings.cache = {};      // not written\nsettings.save();\n```\n\n### BACKUP(filename, files, [callback], [filter])\n\nType: `method`\n\nEmpaqueta archivos y directorios en un único archivo comprimido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | El archivo comprimido a crear (un archivo existente se sustituye). |\n| `files` | `String|Array` | yes |  | Un directorio, o rutas relativas a la raíz. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`; devuelve `true` para empaquetar la ruta. |\n\nReturns: `Promise` Cuando se omite `callback`.\n\nEscribe un archivo de texto: una línea por directorio y una línea por archivo, con la ruta y el contenido comprimido con gzip en base64. `files` es un directorio (todo lo que contiene se empaqueta con rutas relativas a él) o un array de rutas relativas a la raíz de la aplicación (archivos y directorios completos). Los nombres que contienen `.git`, `.gitignore`, `.npmignore` o `.ds_store` se omiten. `filter(path, isdirectory)` recibe cada ruta (que empieza por `/`) y la deja fuera cuando devuelve un valor falso. `filename` también puede ser un stream de escritura. El callback recibe `{ filename, files, size }`; sin callback, la función devuelve una promesa.\n\nExample: Copia de seguridad de las subidas\n```js\nvar meta = await BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), null, function(path, isdir) {\n\treturn isdir || !path.endsWith('.tmp');\n});\nprint(meta.files, 'files', meta.size, 'bytes');\n```\n\nExample: Rutas seleccionadas\n```js\nawait BACKUP(PATH.temp('app.backup'), ['config', 'databases', 'public/uploads']);\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nDesempaqueta un archivo creado por BACKUP().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | El archivo comprimido. |\n| `target` | `String` | yes |  | El directorio en el que desempaquetar. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nReturns: `Promise` Cuando se omite `callback`.\n\nCrea los directorios y archivos del archivo comprimido dentro de `target`. `filename` también puede ser un stream de lectura. `filter(path, isdirectory)` se llama para cada elemento: para un directorio, `false` evita crearlo; para un archivo, devuelve `false` para omitirlo, una cadena para escribirlo bajo esa ruta (relativa a `target`), o nada para mantener su ruta. El callback recibe `{ files, size, path }`; sin callback, la función devuelve una promesa.\n\nExample: Restaurar\n```js\nvar meta = await RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'));\nprint('Restored', meta.files, 'files');\n```\n\nExample: Omitir archivos por el camino\n```js\nRESTORE(PATH.temp('app.backup'), PATH.root(), function(err) {\n\terr && print(err);\n}, function(path, isdir) {\n\tif (!isdir && path.startsWith('/config'))\n\t\treturn false;\n});\n```\n\n### PATH.root([path])\n\nType: `method`\n\nDevuelve el directorio raíz de la aplicación, o una ruta dentro de él.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Una ruta relativa. |\n\nReturns: `String` Una ruta absoluta.\n\nLa raíz es el directorio de la aplicación (donde se ejecuta el script de arranque). Con `path`, devuelve la raíz unida a esa ruta. Como las demás funciones de directorio de `PATH`, crea el directorio la primera vez que se llama con una ruta. `PATH.public()`, `PATH.private()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()`, `PATH.templates()`, `PATH.flowstreams()` y `PATH.scripts()` funcionan igual para sus directorios.\n\nExample: Rutas\n```js\nPATH.root();                 // '/www/app'\nPATH.root('config');         // '/www/app/config'\nPATH.private('report.pdf');  // '/www/app/private/report.pdf'\n```\n\n### PATH.databases([path])\n\nType: `method`\n\nDevuelve el directorio de bases de datos, o una ruta dentro de él.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Una ruta relativa. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio `/databases/` contiene los archivos de las bases de datos NoSQL, los archivos de `MEMORIZE()` y otros datos de la aplicación. Se crea la primera vez que pides una ruta dentro de él.\n\nExample: Un archivo de datos\n```js\nvar filename = PATH.databases('import.json');\nFs.writeFile(filename, JSON.stringify(data), NOOP);\n```\n\n### PATH.temp([path])\n\nType: `method`\n\nDevuelve el directorio temporal, o una ruta dentro de él.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Una ruta relativa. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio `/tmp/` contiene las subidas, los archivos en caché y los recursos compilados. `PATH.tmp()` es un alias. Cuando arranca la aplicación, el framework borra allí sus propios archivos temporales (archivos `.js`, `.css`, `.html`, `.htm`, `.tmp` y `.upload`). Guarda los datos que deban perdurar en `/databases/`.\n\nExample: Un archivo temporal\n```js\nvar filename = PATH.temp(UID() + '.csv');\n```\n\n### PATH.exists(path, [callback])\n\nType: `method`\n\nComprueba si existe un archivo o un directorio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una ruta absoluta. |\n| `callback` | `Function` | no |  | `function(exists, size, isfile)`. |\n\nReturns: `Promise<Boolean>` Cuando se omite `callback`.\n\nEl callback recibe tres argumentos: `exists`, el tamaño en bytes e `isfile` (`true` para un archivo, `false` para un directorio). Sin callback, la función devuelve una promesa que se resuelve con `exists`.\n\nExample: Comprobar un archivo\n```js\nif (await PATH.exists(PATH.databases('settings.json')))\n\tprint('Settings found');\n\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isfile) {\n\tprint(exists, size, isfile);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nBorra uno o más archivos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|Array` | yes |  | Una ruta absoluta, o un array de rutas. |\n| `callback` | `Function` | no |  | `function()`. |\n\nBorra los archivos uno tras otro y luego llama al callback. Los errores (por ejemplo, un archivo que no existe) se ignoran.\n\nExample: Borrar archivos\n```js\nPATH.unlink([PATH.temp('a.csv'), PATH.temp('b.csv')], function() {\n\tprint('Removed');\n});\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nBorra directorios con todo lo que contienen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|Array` | yes |  | Una ruta absoluta, o un array de rutas. |\n| `callback` | `Function` | no |  | `function()`. |\n\nPara cada directorio, se borran todos los archivos, luego los subdirectorios empezando por el más profundo y luego el propio directorio. Después se llama al callback.\n\nExample: Borrar un directorio\n```js\nPATH.rmdir(PATH.temp('export'), function() {\n\tprint('Directory removed');\n});\n```\n\n### Total.FsPromises\n\nType: `property`\n\nEl módulo de Node.js `node:fs/promises`.\n\nReturns: `Object` El módulo `node:fs/promises`.\n\nLa versión con promesas de las funciones del sistema de archivos de Node.js, cargada por el framework. `F.FsPromises` es el mismo objeto, y `Total.Fs` (`F.Fs`) es el módulo `node:fs`.\n\nExample: Leer y listar\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\nvar files = await Total.FsPromises.readdir(PATH.public());\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nConvierte cualquier valor en un número.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor a convertir. |\n| `def` | `Number` | no | `0` | El resultado para valores vacíos o no válidos. |\n\nReturns: `Number`\n\nUn número se devuelve tal cual. Una cadena se recorta y se convierte con el `+` unario; los demás valores se convierten antes en cadena. `null`, `undefined`, una cadena vacía y un valor que no es un número devuelven `def` (0 por defecto). El resultado no se redondea (`'1.5'` da `1.5`). `U.parseFloat(value, [def])` funciona igual y además acepta una coma como separador decimal (`'12,50'` da `12.5`).\n\nExample: Valores del query string\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\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 |  | El valor a convertir. |\n| `def` | `Boolean` | no | `false` | El resultado para `null` o `undefined`. |\n\nReturns: `Boolean`\n\nUn booleano se devuelve tal cual; un número es `true` cuando es mayor que 0; las cadenas `true`, `1` y `on` (en mayúsculas o minúsculas) son `true` y cualquier otra cadena es `false`. `null` y `undefined` devuelven `def` (`false` por defecto).\n\nExample: Una casilla de verificación\n```js\nvar newsletter = U.parseBoolean(this.body.newsletter); // 'on' -> true\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nLee un valor anidado mediante una ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | El objeto a leer. |\n| `path` | `String` | yes |  | La ruta. |\n\nReturns: `Object` El valor, o `undefined`.\n\nLa ruta usa puntos y corchetes: `a.b.c`, `items[0].name`. Cuando falta una parte de la ruta, devuelve `undefined` en lugar de lanzar una excepción. Las rutas con espacios, paréntesis o palabras clave como `__proto__` y `constructor` se rechazan (`undefined`). Los lectores compilados se guardan en caché por ruta.\n\nExample: Valores anidados\n```js\nvar data = { user: { address: { city: 'Bratislava' } }, items: [{ name: 'A' }] };\nU.get(data, 'user.address.city');  // 'Bratislava'\nU.get(data, 'items[0].name');      // 'A'\nU.get(data, 'user.phone.number');  // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nEscribe un valor anidado mediante una ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | El objeto en el que escribir. |\n| `path` | `String` | yes |  | La ruta. |\n| `value` | `Object` | yes |  | El valor. |\n\nReturns: `Object` El valor escrito.\n\nLos objetos que faltan en la ruta se crean. Una ruta que termina en `[]` añade el valor al array, y un índice crea un array con objetos dentro (`items[0].name`). Las rutas con espacios, paréntesis o palabras clave como `__proto__` y `constructor` se rechazan: no se escribe nada. Devuelve el valor.\n\nExample: Construir un objeto\n```js\nvar model = {};\nU.set(model, 'address.city', 'Bratislava');\nU.set(model, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\nExample: Ruta con un índice\n```js\nvar model = {};\nU.set(model, 'items[0].name', 'Pen');\n// { items: [{ name: 'Pen' }] }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nCopia las claves de source en target.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | El objeto en el que escribir. |\n| `source` | `Object` | yes |  | El objeto a leer. |\n| `rewrite` | `Boolean` | no | `true` | `false` mantiene los valores existentes. |\n\nReturns: `Object` El destino.\n\nCada clave de `source` se clona en `target`. Con `rewrite` en `false`, las claves que ya existen en `target` no se modifican, que es la forma de rellenar valores por defecto. Devuelve `target`.\n\nExample: Valores por defecto\n```js\nvar options = { limit: 50 };\nU.extend(options, { limit: 10, sort: 'name' }, false);\n// { limit: 50, sort: 'name' }\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nDevuelve una función de comparación para Array.sort().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Por ejemplo `name` o `price_desc,name`. |\n\nReturns: `Function` `function(a, b)` para `Array.prototype.sort()`.\n\n`sort` es una lista de claves separadas por comas; añade `_desc` para orden descendente (`_asc` es el valor por defecto). Las claves anidadas usan puntos (`address.city`). El tipo de cada clave se lee del primer valor que no está vacío la primera vez que se usa la expresión, y se conserva para los usos posteriores de la misma expresión: las cadenas se comparan teniendo en cuenta los diacríticos; los números, booleanos y fechas, por valor.\n\nExample: Ordenar productos\n```js\nproducts.sort(U.sortcomparer('price_desc,name'));\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nDevuelve un entero aleatorio dentro de un rango.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | El valor más grande. |\n| `min` | `Number` | no | `0` | El valor más pequeño. |\n\nReturns: `Number`\n\nDevuelve un entero entre `min` y `max`, ambos incluidos.\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 |  | El número de caracteres. |\n\nReturns: `String`\n\nLos caracteres son `0-9`, `A-Z` y `a-z`. `U.random_string(length)` usa solo letras, y `U.random_number(length)` solo dígitos (devueltos como una cadena que no empieza por 0). Estos valores provienen de `Math.random()`: no los uses como contraseñas ni como tokens de seguridad.\n\nExample: Cadenas aleatorias\n```js\nU.random_text(8);    // 'yb7JVb2a'\nU.random_string(6);  // 'HNXkTk'\nU.random_number(6);  // '825174'\n```\n\n### U.convert62(number)\n\nType: `method`\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 no negativo. |\n\nReturns: `String`\n\nLos dígitos son `0-9`, `A-Z` y `a-z`, en este orden. Primero el número se redondea hacia abajo. `U.from62(value)` convierte la cadena de vuelta en el número. Úsala para códigos cortos hechos a partir de ids numéricos.\n\nExample: Códigos cortos\n```js\nvar code = U.convert62(123456);  // 'W7E'\nvar id = U.from62(code);         // 123456\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nDevuelve la extensión de un nombre de archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un nombre de archivo, una ruta o una URL. |\n| `raw` | `Boolean` | no | `false` | `true` mantiene las mayúsculas y minúsculas originales. |\n\nReturns: `String`\n\nDevuelve la parte que hay después del último punto, sin el punto y en minúsculas (con `raw`, en las mayúsculas y minúsculas originales). Un query string después de `?` se ignora. Devuelve una cadena vacía cuando el nombre no tiene extensión.\n\nExample: Extensiones\n```js\nU.getExtension('/img/Photo.JPG');      // 'jpg'\nU.getExtension('/files/a.pdf?v=1');    // 'pdf'\nU.getExtension('README');              // ''\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 |  | Una ruta o una URL. |\n\nReturns: `String`\n\nDevuelve el nombre del archivo (o el último directorio) de una ruta con separadores `/` o `\\\\`. Un separador final se ignora.\n\nExample: Nombres de archivo\n```js\nU.getName('/www/app/public/logo.png');  // 'logo.png'\nU.getName('/www/app/public/');          // 'public'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nDevuelve el tipo MIME de una extensión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Una extensión, p. ej. `png` o `.png`. |\n\nReturns: `String`\n\nLa extensión puede empezar por un punto. Las extensiones desconocidas devuelven `application/octet-stream`. `U.getExtensionFromContentType(type)` hace lo contrario y devuelve la primera extensión con ese tipo (o `undefined`). La tabla completa es `U.contentTypes`.\n\nExample: Tipos de contenido\n```js\nU.getContentType('png');                     // 'image/png'\nU.getContentType('.json');                   // 'application/json'\nU.getExtensionFromContentType('image/png');  // 'png'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nCodifica texto o un buffer en base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Los datos a codificar. |\n\nReturns: `String`\n\nUn buffer se codifica directamente; los demás valores se convierten en cadena y se codifican como UTF-8. `U.atob(value)` decodifica base64 de vuelta a una cadena UTF-8.\n\nExample: Base64\n```js\nvar encoded = U.btoa('Hello');   // 'SGVsbG8='\nvar text = U.atob(encoded);      // 'Hello'\n```\n\n### U.validhost(host)\n\nType: `method`\n\nComprueba que un nombre de host es ASCII simple y que una dirección IP está en su forma canónica.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | El nombre de host o la dirección IP. |\n\nReturns: `Boolean` `true` para un host válido.\n\nDevuelve `false` para un valor que no es un string, está vacío o contiene un carácter fuera del rango ASCII visible (espacios, bytes NUL, letras con acentos). Un valor formado solo por números y puntos (o números hexadecimales) debe ser una dirección IPv4 canónica: `127.0.0.1` es válida; `127.1`, `0127.0.0.1`, `0x7f.0.0.1` y `2130706433` no. Los demás valores ASCII, incluidas las direcciones IPv6, devuelven `true`; la función no comprueba la sintaxis completa de un nombre de host. Convierte primero un nombre internacional con `U.tohost()`.\n\nExample: Comprobar hosts\n```js\nU.validhost('example.com');     // true\nU.validhost('127.0.0.1');       // true\nU.validhost('127.1');           // false\nU.validhost('0x7f.0.0.1');      // false\nU.validhost('münchen.de');      // false\nU.validhost('evil.example\\0.trusted.example'); // false\n```\n\n### U.tohost(host)\n\nType: `method`\n\nConvierte un nombre de host a su forma ASCII canónica.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | El nombre de host o la dirección IP. |\n\nReturns: `String` El host canónico, o un string vacío.\n\nConvierte el host con el parser de URL de Node.js: las letras pasan a minúsculas, un nombre internacional se convierte en punycode y una dirección IPv4 en otra notación se convierte en la forma con puntos (un `0` inicial indica un número octal, `0x` un número hexadecimal). Después el resultado se comprueba con `U.validhost()`. Un valor que contiene `:` (una dirección IPv6) solo se comprueba. Devuelve un string vacío cuando el host no es válido, así que comprueba el resultado antes de usarlo.\n\nExample: Convertir hosts\n```js\nU.tohost('münchen.de');      // 'xn--mnchen-3ya.de'\nU.tohost('EXAMPLE.com');     // 'example.com'\nU.tohost('127.1');           // '127.0.0.1'\nU.tohost('0x7f.0.0.1');      // '127.0.0.1'\nU.tohost('evil.example\\0.trusted.example'); // ''\n```\n\nExample: Validar la entrada\n```js\nfunction host(value) {\n\tvar host = U.tohost(value);\n\tif (!host)\n\t\tthrow new Error('Invalid hostname');\n\treturn host;\n}\n```\n\n### U.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` | no |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Milisegundos antes de que la espera falle. |\n| `interval` | `Number` | no | `500` | Milisegundos entre comprobaciones. |\n\nReturns: `Promise` Cuando se omite `callback`.\n\n`validator` se llama inmediatamente y luego cada `interval` milisegundos hasta que devuelve `true`; entonces el callback recibe `(null, true)`. Cuando antes pasa `timeout`, el callback recibe un `Error('Timeout')`. Sin callback, la función devuelve una promesa que se resuelve o se rechaza de la misma forma.\n\nExample: Esperar a una conexión\n```js\nawait U.wait(() => MAIN.db != null, null, 10000, 200);\nprint('Database ready');\n```\n\n### U.resolve(url, callback, [param])\n\nType: `method`\n\nResuelve el host de una URL a direcciones IPv4, con caché.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Una URL absoluta. |\n| `callback` | `Function` | yes |  | `function(err, uri, param, addresses)`. |\n| `param` | `Any` | no |  | Un valor que se pasa al callback. |\n\nParsea `url`, comprueba su nombre de host con `U.validhost()` y pide a los servidores DNS sus direcciones IPv4 (`dns.resolve4()`, así que no se usa el archivo hosts). El callback recibe `(err, uri, param, addresses)`: `uri` es la URL parseada con `host` establecido a la primera dirección, `param` es el tercer argumento y `addresses` la lista completa. Las direcciones se guardan en caché durante la vida del proceso; una búsqueda fallida se intenta una vez más antes de pasar `err`.\n\nUn string que no es una URL da `TypeError: Invalid URL`, y un nombre de host que no es válido da el error `Invalid hostname` sin consulta DNS. Para las URL `http` y `https` el parser de URL ya convierte el host; para otros esquemas, una dirección no canónica como `tcp://127.1/` da `Invalid hostname`. `REQUEST()` usa esta función con la opción `resolve: true`, y `RESTBuilder` por defecto.\n\nExample: Resolver un host\n```js\nU.resolve('https://example.com/api/', function(err, uri, param, addresses) {\n\tif (err)\n\t\tconsole.log(err.message || err.code);\n\telse\n\t\tconsole.log(uri.hostname, addresses);\n});\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nDivide un flujo de datos en partes según unos delimitadores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | El inicio de una parte, o el separador. |\n| `end` | `String|Buffer` | no |  | El final de una parte. |\n| `callback` | `Function` | yes |  | `function(value, index)`; devuelve `false` para detener. |\n| `skip` | `Number` | no | `0` | El número de primeras partes que se ignoran. |\n| `stream` | `Stream` | no |  | Un stream cuyo evento `end` procesa el resto. |\n\nReturns: `Function` `function(chunk)`.\n\nDevuelve una función a la que llamas con cada fragmento (un buffer), por ejemplo como manejador `data` de un stream. Con `beg` y `end`, el callback recibe cada parte que empieza por `beg` y termina en `end`, ambos incluidos (por ejemplo, un `<item>...</item>` de un archivo XML grande). Solo con `beg`, `beg` es un separador y el callback recibe cada parte hasta él, incluido (por ejemplo, líneas con `\\n`). El callback recibe `(value, index)` con el valor como cadena; si devuelve `false`, se detiene el análisis. `skip` ignora ese número de primeras partes. Con `stream`, los datos que quedan se procesan cuando termina el stream. `U.streamer2()` recibe los mismos argumentos y pasa buffers en lugar de cadenas.\n\nExample: Leer un archivo XML grande\n```js\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\nstream.on('data', U.streamer('<product>', '</product>', function(value, index) {\n\tvar product = value.parseXML();\n\tprint(index, product);\n}));\n```\n\nExample: Líneas de un archivo CSV\n```js\nvar stream = Fs.createReadStream(filename);\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tvar cols = line.trim().split(';');\n}, 1, stream));  // skips the header line\n```\n\n### U.connect(options, [callback])\n\nType: `method`\n\nAbre una conexión TCP o TLS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | `{ host, port, secure, tls, timeout }` y, con `secure`, otras opciones de `tls.connect()`. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `undefined` Nada\n\nSe conecta a `options.host` y `options.port` y llama a `callback(err, meta)` cuando la conexión está abierta. Primero el host se convierte con `U.tohost()`, así que un nombre internacional se envía como punycode y `127.1` como `127.0.0.1`; un host que no es válido da el error `Invalid hostname` y no se establece ninguna conexión. Con `secure: true` la conexión usa TLS desde el principio y las demás opciones (`servername`, `rejectUnauthorized`, `ca` ...) van a `tls.connect()`. Con `tls` la conexión empieza como TCP sin cifrar y pasa a TLS en cuanto está abierta: `tls: true` usa las opciones por defecto de `tls.connect()`, y un objeto pasa sus opciones (`servername`, `rejectUnauthorized`, `ca` ...). Con `timeout` (en milisegundos), una conexión que no se abre a tiempo da el error `Timeout`.\n\n`meta` tiene `socket` (el socket de Node.js), `opt` (las opciones con el host convertido), `write(data)`, `ondata(fn)` para los fragmentos recibidos, y `close()` (también `destroy()`). `LDAP()` se conecta con esta función.\n\nExample: Leer el saludo de un servidor\n```js\nU.connect({ host: 'mail.example.com', port: 25, timeout: 5000 }, function(err, meta) {\n\tif (err) {\n\t\tconsole.log(err.message);\n\t\treturn;\n\t}\n\tmeta.ondata(function(chunk) {\n\t\tconsole.log(chunk.toString());\n\t\tmeta.close();\n\t});\n});\n```\n\nExample: Pasar a TLS\n```js\nU.connect({ host: 'mail.example.com', port: 465, tls: { servername: 'mail.example.com' } }, function(err, meta) {\n\tif (!err)\n\t\tconsole.log(meta.socket.encrypted); // true\n});\n```\n\n### U.ls(path, [callback], [filter])\n\nType: `method`\n\nLista los archivos y directorios de un directorio de forma recursiva.\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 |  | El filtro. |\n\nReturns: `Promise` `{ files, directories }` cuando se omite `callback`.\n\nEl callback recibe dos arrays de rutas absolutas: `files` y `directories` (los directorios terminan con el separador de ruta). `filter` puede ser una cadena (rutas que la contienen, sin distinguir mayúsculas y minúsculas), una expresión regular, o una función `(path, isdirectory)` que devuelve `true` para conservar el elemento; los filtros de cadena y de expresión regular se aplican solo a los archivos. Un directorio que el filtro descarta no se recorre. Sin callback, la función devuelve una promesa con `{ files, directories }`. `U.ls2()` acepta los mismos argumentos y devuelve los archivos como objetos `{ filename, stats }` con el `fs.Stats` de cada archivo.\n\nExample: Buscar archivos JSON\n```js\nU.ls(PATH.databases(), function(files, directories) {\n\tprint(files);\n}, /\\.json$/);\n```\n\nExample: Tamaños con ls2\n```js\nvar result = await U.ls2(PATH.public('uploads'));\nvar size = 0;\nfor (var file of result.files)\n\tsize += file.stats.size;\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nGuarda una lista grande en archivos temporales, por páginas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre único, usado para los nombres de archivo. |\n| `max` | `Number` | no | `50` | Elementos por página. |\n\nReturns: `Chunker`\n\nUn chunker recoge elementos con `write(item)` (alias `append()`); cada `max` elementos se escriben en un archivo `tmp/{name}-{index}.chunker` (comprimido con deflate cuando `compress` es `true`, el valor por defecto) para que la memoria se mantenga pequeña. Llama a `end()` para escribir el resto. Después, `each(onitem, [ondone])` lee las páginas en orden: `onitem(items, next, index)` recibe una página y llama a `next()` para continuar, y `percentage` indica cuánto se ha leído. `read(index, callback)` lee una página. Con `autoremove` (`true` por defecto), cada archivo se borra después de leerlo; `clear()` borra todos los archivos y `destroy()` además libera el chunker. Las propiedades `count` y `pages` contienen el número de elementos y de páginas.\n\nExample: Procesar una exportación grande\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var row of rows)\n\tchunker.write(row);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tprint('Page', index, chunker.percentage + '%');\n\tsend(items, next);\n}, function() {\n\tprint('Done', chunker.count, 'items');\n});\n```\n\n### chunker.load([callback])\n\nType: `method` · Since: `0.0.16`\n\nEncuentra las páginas que un chunker anterior con el mismo nombre dejó en disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `Promise` Cuando se omite `callback`.\n\nCuenta los archivos del chunker en el directorio temporal y establece el índice interno de páginas, así `each()` y `read()` pueden leer las páginas que una instancia anterior escribió y no leyó (por ejemplo antes de un reinicio). Crea el chunker con el mismo `name`. El callback recibe `(null, count)`; sin callback, la función devuelve una promesa que se resuelve cuando termina el recuento.\n\nExample: Continuar un chunker\n```js\nvar chunker = U.chunker('export');\nawait chunker.load();\nchunker.each(function(items, next) {\n\tsend(items, next);\n});\n```\n\n### new U.EventEmitter2() / U.EventEmitter2(obj)\n\nType: `class`\n\nUn pequeño emisor de eventos.\n\nReturns: `EventEmitter2`\n\nUn objeto con `on(name, fn)`, `once(name, fn)`, `off(name, [fn])` y `emit(name, ...args)` (hasta siete argumentos). `off(name)` sin función elimina todos los manejadores del evento. Los manejadores se ejecutan con el emisor como `this`. Si se llama con un objeto (`U.EventEmitter2(obj)`), añade estos métodos a ese objeto, salvo que ya tenga `emit`, y lo devuelve.\n\nExample: Eventos en tu objeto\n```js\nvar Cart = {};\nU.EventEmitter2(Cart);\n\nCart.on('add', function(item) {\n\tprint('Added', item.name);\n});\n\nCart.emit('add', { name: 'Shoes' });\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nOfusca una cadena con una clave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El texto. |\n| `key` | `String` | yes |  | La clave. |\n| `encode` | `String` | no | `'base64'` | La codificación de salida, o `buffer`. |\n\nReturns: `String|Buffer`\n\nCodifica la cadena con la clave y una máscara aleatoria de 4 bytes y la devuelve en base64 (o en la codificación que indiques; `buffer` devuelve un buffer). La misma entrada da una salida distinta cada vez. `U.decrypt_data(value, key, [encode])` devuelve la cadena original, o `null` para una entrada no válida. Es una ofuscación ligera, no un cifrado fuerte; para datos sensibles usa `ENCRYPT()` (consulta [Cifrado](../../guides/encryption/)).\n\nExample: Ida y vuelta\n```js\nvar data = U.encrypt_data('hello', 'mykey');\nvar text = U.decrypt_data(data, 'mykey');  // 'hello'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nFirma un identificador para que no se pueda modificar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | El identificador. |\n| `key` | `String` | no | `CONF.secret` | La clave. |\n\nReturns: `String`\n\nDevuelve el identificador con una suma de comprobación delante, calculada a partir del valor, la clave y `CONF.secret_uid`. `U.decrypt_uid(value, [key])` lo comprueba y devuelve el identificador original (un número cuando el original era un número) o `null` cuando el valor se ha modificado. El propio identificador sigue siendo legible. Sin `key`, se usa `CONF.secret`.\n\nExample: Id firmado en un enlace\n```js\nvar signed = U.encrypt_uid(123, 'mykey');   // 'n...x123', the checksum depends on CONF.secret_uid\nU.decrypt_uid(signed, 'mykey');             // 123\nU.decrypt_uid('n2v55u4jx124', 'mykey');     // null\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifica JavaScript; U.minify_css() y U.minify_html() hacen lo mismo con CSS y HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El código fuente. |\n\nReturns: `String`\n\nSon los minificadores que usa el framework para los archivos estáticos y las vistas. Reciben una cadena y devuelven la cadena minificada.\n\nExample: Minificar\n```js\nU.minify_js('var a = 1 ;  // note\\n');  // 'var a=1;'\nU.minify_css('a { color : red ; }');     // 'a{color:red}'\nU.minify_html(html);\n```\n\n### U.aistreamer(online, [onmessage])\n\nType: `method` · Since: `0.0.16`\n\nParsea la respuesta en streaming de una API de chat de IA en líneas de texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `online` | `Function` | yes |  | `function(line)`, llamada por cada línea de texto completa. |\n| `onmessage` | `Function` | no |  | `function(message)`, llamada por cada mensaje JSON parseado. |\n\nReturns: `Function` `function(chunk)`.\n\nDevuelve una función que llamas con cada fragmento (un buffer) de una respuesta en streaming. Lee mensajes JSON línea a línea en dos formatos: server-sent events con `data: {...}` (completions de OpenAI, donde el texto está en `choices[0].delta.content` y `data: [DONE]` lo termina) y líneas JSON simples (Ollama, donde el texto está en `message.content` y `done` lo termina). El texto se acumula y se llama a `online(line)` por cada línea completa. `onmessage(obj)`, cuando lo estableces, recibe cada mensaje parseado; las fechas JSON se parsean entonces como fechas.\n\nExample: Imprimir una respuesta línea a línea\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nGuarda en caché el resultado de una tarea en un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Identificador del elemento en caché. |\n| `expire` | `String` | yes |  | Cuánto tiempo es válido el archivo, por ejemplo `'5 minutes'`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `maker` | `Function` | yes |  | `function(next, id)` que crea el valor. |\n| `encoding` | `String` | no | `json` | `json` o una codificación de archivo como `utf8`. |\n\nBusca el archivo de `id` en `tmp/`. Cuando existe y es más reciente que `expire`, su contenido va a `callback(err, response)`. Si no, se ejecuta `maker(next, id)`; `next(err, response, [load])` escribe la respuesta en el archivo y llama a `callback`, salvo que `load` sea `false`. Con la codificación `json` el valor se guarda como JSON y se vuelve a parsear; cualquier otra codificación guarda y lee el contenido sin procesar.\n\nExample: Guardar en caché una lista remota\n```js\nFILECACHE('currencies', '1 day', function(err, response) {\n\tMAIN.currencies = response;\n}, function(next) {\n\tREQUEST({ url: 'https://example.com/rates.json', callback: function(err, response) {\n\t\tnext(err, err ? null : response.body.parseJSON());\n\t}});\n});\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID()","since":"","deprecated":false},{"type":"method","name":"GUID([length])","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"HASH(value, [type])","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"CLONE(obj, [skip], [nofunctions])","signature":"CLONE(obj, [skip], [nofunctions])","since":"","deprecated":false},{"type":"method","name":"COPY(source, [target], [all])","signature":"COPY(source, [target], [all])","since":"","deprecated":false},{"type":"method","name":"DIFFARR(prop, db, form)","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"QUERIFY([url], obj)","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"PROMISIFY(fn, [a], [b], [c])","signature":"PROMISIFY(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"ERROR([name])","signature":"ERROR([name])","since":"","deprecated":false},{"type":"method","name":"print()","signature":"print(...values)","since":"","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"NOOP","signature":"NOOP","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","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":"CACHE.set(key, value, [expire])","signature":"CACHE.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"CACHE.get(key, [def])","signature":"CACHE.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"CACHE.remove(key)","signature":"CACHE.remove(key)","since":"","deprecated":false},{"type":"method","name":"CACHE.reset([search])","signature":"CACHE.reset([search])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE([name], [delay], [skip])","signature":"MEMORIZE([name], [delay], [skip])","since":"","deprecated":false},{"type":"method","name":"BACKUP(filename, files, [callback], [filter])","signature":"BACKUP(filename, files, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE(filename, target, [callback], [filter])","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"PATH.root([path])","signature":"PATH.root([path])","since":"","deprecated":false},{"type":"method","name":"PATH.databases([path])","signature":"PATH.databases([path])","since":"","deprecated":false},{"type":"method","name":"PATH.temp([path])","signature":"PATH.temp([path])","since":"","deprecated":false},{"type":"method","name":"PATH.exists(path, [callback])","signature":"PATH.exists(path, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink(files, [callback])","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir(directories, [callback])","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"property","name":"Total.FsPromises","signature":"Total.FsPromises","since":"","deprecated":false},{"type":"method","name":"U.parseInt(value, [def])","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseBoolean(value, [def])","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.get(obj, path)","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set(obj, path, value)","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.extend(target, source, [rewrite])","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer(sort)","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.random([max], [min])","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text(length)","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.convert62(number)","signature":"U.convert62(number)","since":"","deprecated":false},{"type":"method","name":"U.getExtension(filename, [raw])","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName(path)","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType(ext)","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.btoa(value)","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.validhost(host)","signature":"U.validhost(host)","since":"","deprecated":false},{"type":"method","name":"U.tohost(host)","signature":"U.tohost(host)","since":"","deprecated":false},{"type":"method","name":"U.wait(validator, [callback], [timeout], [interval])","signature":"U.wait(validator, [callback], [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"U.resolve(url, callback, [param])","signature":"U.resolve(url, callback, [param])","since":"","deprecated":false},{"type":"method","name":"U.streamer(beg, [end], callback, [skip], [stream])","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.connect(options, [callback])","signature":"U.connect(options, [callback])","since":"","deprecated":false},{"type":"method","name":"U.ls(path, [callback], [filter])","signature":"U.ls(path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"U.chunker(name, [max])","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.load([callback])","signature":"chunker.load([callback])","since":"0.0.16","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2() / U.EventEmitter2(obj)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_data(value, key, [encode])","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid(value, [key])","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.minify_js(value)","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.aistreamer(online, [onmessage])","signature":"U.aistreamer(online, [onmessage])","since":"0.0.16","deprecated":false},{"type":"method","name":"FILECACHE(id, expire, callback, maker, [encoding])","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwwLBgx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/utilities/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Utilitaires","summary":"Fonctions U/Utils, helpers globaux (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), objets partagés, CACHE, MEMORIZE, BACKUP, RESTORE et PATH.","markdown":"---\ntitle: Utilitaires\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/utilities/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Utilitaires\n\n> Fonctions U/Utils, helpers globaux (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), objets partagés, CACHE, MEMORIZE, BACKUP, RESTORE et PATH.\n\nCette page liste les helpers globaux, les objets globaux partagés, le `CACHE` en mémoire, les fonctions `PATH` et les fonctions du module `U` (`Utils`) qu'utilisent les applications. Le guide [Utilitaires](../../guides/utilities/) explique, avec des exemples, comment ils s'articulent. Les méthodes ajoutées à `String`, `Number`, `Date` et `Array` se trouvent dans [Prototypes](../prototypes/).\n\n## API\n\n### U\n\nType: `property`\n\nLe module Utils sous forme d'objet global.\n\nReturns: `Object` Le module Utils.\n\nToutes les fonctions de `utils.js` sont disponibles via `U` et son alias `Utils` (les deux pointent vers le même objet). Cette page documente les fonctions qu'utilisent les applications ; les autres sont utilisées par le framework lui-même.\n\nExample: Utiliser un helper\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\nvar same = Utils === U;           // true\n```\n\n### UID()\n\nType: `method`\n\nRenvoie un nouvel identifiant unique.\n\nReturns: `String` Par exemple `JacVuE1cn61f`.\n\nL'identifiant est une courte chaîne de lettres et de chiffres : un horodatage en base 62 (en dixièmes de seconde), un compteur interne, un caractère aléatoire choisi au démarrage (changé chaque minute), la longueur de la partie temporelle, un chiffre de parité et la lettre `f`. Dans la plupart des cas, les identifiants créés plus tard sont triés après les précédents. Le validateur `uid` du framework (`DEF.validators.uid`) les accepte.\n\nExample: Un nouvel enregistrement\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\nNOSQL('products').insert(model);\n```\n\n### GUID([length])\n\nType: `method`\n\nRenvoie une chaîne de type UUID, ou une chaîne aléatoire d'une longueur donnée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Le nombre de caractères. Omets-le pour le format de type UUID. |\n\nReturns: `String`\n\nSans `length`, elle renvoie une chaîne de la forme `xxxxxxxx-xxxx-Nxxx-Yxxx-xxxxxxxxxxxx` (36 caractères) construite à partir de l'heure actuelle et de chiffres hexadécimaux aléatoires. Avec `length`, elle renvoie autant de caractères aléatoires parmi `0-9` et `a-z`.\n\nExample: Jetons\n```js\nvar guid = GUID();       // '1a1e0561-0561-4c86-8eaf-d9a327a65943'\nvar token = GUID(30);    // 30 random characters\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nCalcule le hachage d'une chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le texte à hacher. |\n| `type` | `String` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32` ou `crc32unsigned`. |\n\nReturns: `Number|String` Un nombre sans type, une chaîne hexadécimale pour les types md5/sha.\n\nSans `type`, elle renvoie un nombre non signé de 32 bits calculé à partir de la chaîne (rapide, non cryptographique). Avec un type, elle renvoie le hachage sous forme de chaîne hexadécimale (`md5`, `sha1`, `sha256`, `sha512`) ou d'un nombre CRC32 (`crc32`, `crc32unsigned`). `value` doit être une chaîne ; convertis d'abord les nombres avec `+ ''`.\n\nExample: Hachages\n```js\nHASH('abc');            // 96354\nHASH('abc', 'md5');     // '900150983cd24fb0d6963f7d28e17f72'\nHASH(email, 'sha256');\n```\n\n### CLONE(obj, [skip], [nofunctions])\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|Array` | yes |  | La valeur à copier. Les autres valeurs sont renvoyées sans modification. |\n| `skip` | `Object` | no |  | Les clés à exclure, par ex. `{ password: 1 }`. |\n| `nofunctions` | `Boolean` | no | `false` | `true` exclut les fonctions. |\n\nReturns: `Object|Array` La copie.\n\nLes objets et tableaux imbriqués sont copiés, les buffers des propriétés d'objet sont dupliqués, et les dates, les erreurs et les autres valeurs qui ne sont pas des objets sont conservées telles quelles. `skip` est un objet dont les clés sont exclues de la copie à tous les niveaux. Avec `nofunctions`, les propriétés qui contiennent des fonctions sont aussi exclues.\n\nExample: Copier sans une clé\n```js\nvar user = { id: 'abc', name: 'Peter', password: 'secret', address: { city: 'Bratislava' } };\nvar safe = CLONE(user, { password: 1 });\nsafe.address.city = 'Prague';  // user.address.city is still 'Bratislava'\n```\n\n### COPY(source, [target], [all])\n\nType: `method`\n\nCopie les clés d'un objet dans un autre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | L'objet à lire. |\n| `target` | `Object` | no |  | L'objet dans lequel écrire. |\n| `all` | `Boolean` | no | `true` | `false` n'écrit que les clés que `target` possède déjà. |\n\nReturns: `Object` La cible (ou la nouvelle copie).\n\nChaque valeur de `source` est clonée et écrite dans `target`. Avec `all` à `false`, seules les clés déjà définies dans `target` sont écrites, de sorte que `target` sert de liste des champs autorisés. Sans `target`, elle renvoie une copie profonde de `source`.\n\nExample: Champs autorisés\n```js\nvar allowed = { name: '', email: '' };\nCOPY(this.body, allowed, false);\n// allowed contains only name and email from the body\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nCompare deux tableaux d'objets selon une propriété.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | La clé qui identifie un élément, par ex. `id`. |\n| `db` | `Array` | yes |  | Les éléments actuels (par exemple issus de la base de données). |\n| `form` | `Array` | yes |  | Les nouveaux éléments (par exemple issus d'un formulaire). |\n\nReturns: `Object` `{ add: Array, upd: Array, rem: Array }`.\n\nLes éléments correspondent quand leurs valeurs `prop` sont égales (`==`). Le résultat contient trois tableaux : `add` contient les éléments de `form` absents de `db`, `upd` contient les paires `{ db, form }` des éléments correspondants, et `rem` contient les valeurs `prop` des éléments de `db` absents de `form`.\n\nExample: Synchroniser des éléments\n```js\nvar diff = DIFFARR('id', current, model.items);\n\nfor (var item of diff.add)\n\tNOSQL('items').insert(item);\n\nfor (var pair of diff.upd)\n\tNOSQL('items').modify(pair.form).where('id', pair.db.id);\n\nfor (var id of diff.rem)\n\tNOSQL('items').remove().where('id', id);\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nConstruit une query string à partir d'un objet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Une URL, éventuellement précédée d'une méthode. |\n| `obj` | `Object` | yes |  | Les valeurs. |\n\nReturns: `String`\n\nLes clés et les valeurs sont encodées pour l'URL. Les valeurs `null`, `undefined` et vides sont ignorées, les dates sont écrites en chaînes ISO et les tableaux sont joints par des virgules. Sans `url`, le résultat commence par `?` (ou est une chaîne vide quand il ne reste rien). Avec `url`, la query string est ajoutée avec `?` ou `&` ; l'URL peut commencer par une méthode HTTP (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `API`) suivie d'une espace, comme l'acceptent `REQUEST()` et `AJAX()`. La fonction existe aussi sous le nom `U.querify()`.\n\nExample: Query strings\n```js\nQUERIFY({ q: 'red shoes', page: 2 });           // '?q=red%20shoes&page=2'\nQUERIFY('/api/?lang=en', { page: 2 });         // '/api/?lang=en&page=2'\nQUERIFY('GET https://example.com/', { id: 5 }); // 'GET https://example.com/?id=5'\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method`\n\nAppelle une fonction de style callback et renvoie une promesse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Une fonction dont le dernier argument est un callback. |\n| `a` | `Object` | no |  | Le premier argument. |\n| `b` | `Object` | no |  | Le deuxième argument. |\n| `c` | `Object` | no |  | Le troisième argument. |\n\nReturns: `Promise`\n\n`fn` est appelée avec les arguments que tu passes (jusqu'à trois) et un callback `function(err, response)`. La promesse est rejetée avec `err` ou résolue avec `response`. Ne passe que les arguments nécessaires : un argument `undefined` termine la liste.\n\nExample: Lire un fichier\n```js\nvar Fs = require('fs');\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n\n### ERROR([name])\n\nType: `method`\n\nRenvoie un callback qui journalise les erreurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Le nom affiché avec l'erreur, par ex. la fonction qui a échoué. |\n\nReturns: `Function` `function(err)`.\n\nLa fonction renvoyée prend `err` comme premier argument et, lorsqu'il est défini, le transmet au gestionnaire d'erreurs du framework (`DEF.onError`, qui l'affiche et le conserve dans les statistiques) avec `name` comme source. Utilise-la pour les callbacks dont tu n'as pas besoin du résultat mais dont tu veux voir les erreurs.\n\nExample: Journaliser une écriture échouée\n```js\nFs.writeFile(PATH.databases('cache.json'), JSON.stringify(data), ERROR('cache.save'));\n```\n\n### print(...values)\n\nType: `method`\n\nÉcrit des valeurs dans la console.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `values` | `Object` | yes |  | Les valeurs à afficher. |\n\n`print` est `console.log`. Le framework l'utilise pour ses informations de démarrage.\n\nExample: Afficher\n```js\nprint('Imported', count, 'products');\n```\n\n### NOW\n\nType: `property`\n\nUne Date avec l'heure actuelle, rafraîchie toutes les 5 secondes.\n\nReturns: `Date`\n\nUne fois chargé, le framework affecte `new Date()` à `NOW` toutes les 5 secondes, ainsi que lorsqu'il écrit une erreur, un journal d'audit ou un élément de cache. Utilise-la quand une précision de quelques secondes suffit : expirations, lignes de journal, champs `dtcreated`. Ne modifie pas l'objet ; affecte plutôt une nouvelle date.\n\nExample: Expiration\n```js\nvar expire = NOW.add('1 hour');\nif (session.expire < NOW)\n\tdelete sessions[session.id];\n```\n\n### NOOP\n\nType: `property`\n\nUne fonction vide.\n\nReturns: `Function`\n\nUtilise-la là où un callback est requis mais où tu n'as pas besoin du résultat. C'est la même fonction que `U.noop`.\n\nExample: Ignorer le résultat\n```js\nFs.unlink(filename, NOOP);\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nUn objet vide gelé ; EMPTYARRAY est un tableau vide gelé.\n\nReturns: `Object`\n\n`EMPTYOBJECT` (`{}`) et `EMPTYARRAY` (`[]`) sont créés une seule fois et gelés avec `Object.freeze()`, ils ne peuvent donc pas être modifiés. Utilise-les comme valeurs par défaut au lieu de créer de nouveaux objets, par exemple `var opt = options || EMPTYOBJECT;`. N'écris jamais dedans : en mode strict, une écriture lève une exception.\n\nExample: Valeurs par défaut\n```js\nfunction find(filter) {\n\tvar opt = filter || EMPTYOBJECT;\n\tvar tags = opt.tags || EMPTYARRAY;\n\treturn tags.length;\n}\n```\n\n### MAIN\n\nType: `property`\n\nUn objet global pour l'état partagé de l'application.\n\nReturns: `Object`\n\nLe framework crée `MAIN` comme objet vide et ne l'utilise pas. Stockes-y ce que plusieurs fichiers de ton application partagent : paramètres chargés au démarrage, connexions ouvertes, compteurs. Il est accessible dans les vues sous le nom `MAIN`.\n\nExample: Paramètres partagés\n```js\n// definitions/settings.js\nMAIN.settings = MEMORIZE('settings');\n\n// a controller or an action\nvar title = MAIN.settings.title;\n```\n\n### REPO\n\nType: `property`\n\nUn objet global pour les données partagées, également disponible dans les vues.\n\nReturns: `Object`\n\nUn objet vide que le framework crée au démarrage (c'est aussi `F.repo`). Les vues peuvent le lire sous le nom `REPO`, ce qui en fait un bon endroit pour les données dont les layouts ont besoin, par exemple un menu ou les coordonnées de contact.\n\nExample: Données pour le layout\n```js\nREPO.menu = [{ name: 'Home', url: '/' }, { name: 'Contact', url: '/contact/' }];\n\n// views/layout.html\n// @{foreach m in REPO.menu}<a href=\"@{m.url}\">@{m.name}</a>@{end}\n```\n\n### FUNC\n\nType: `property`\n\nUn objet global pour tes fonctions partagées.\n\nReturns: `Object`\n\nUn objet vide pour les fonctions qu'utilisent plusieurs parties de l'application. Définis-les dans `/definitions/` pour qu'elles existent avant la première requête. Les vues peuvent aussi lire `FUNC`.\n\nExample: Une fonction partagée\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// anywhere\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nUn objet global pour les données éphémères, vidé toutes les 5 minutes.\n\nReturns: `Object`\n\nToutes les 5 minutes, le framework remplace `TEMP` par un nouvel objet vide. Utilise-le pour de petites données temporaires qui peuvent disparaître à tout moment, comme des jetons à usage unique ou des compteurs de limitation. Lis-le toujours via la variable globale (`TEMP.key`), pas via une référence enregistrée, car l'objet change.\n\nExample: Un jeton éphémère\n```js\nvar token = GUID(20);\nTEMP[token] = { userid: user.id };\n\n// later\nvar data = TEMP[token];\nif (!data)\n\t$.invalid('The token has expired');\n```\n\n### MODS\n\nType: `property`\n\nLes modules chargés, par leur id.\n\nReturns: `Object`\n\nChaque fichier `.js` de `/modules/` est chargé au démarrage et stocké dans `MODS` sous son `exports.id`, ou sous le nom du fichier s'il n'en définit pas. Sa fonction `install()`, si elle existe, est appelée après le chargement. `MODS` est le même objet que `F.modules` et peut être lu dans les vues.\n\nExample: Un module\n```js\n// modules/pricing.js\nexports.id = 'pricing';\nexports.vat = function(price) {\n\treturn price * 1.2;\n};\n\n// anywhere\nvar total = MODS.pricing.vat(100);\n```\n\n### CACHE.set(key, value, [expire])\n\nType: `method`\n\nStocke une valeur dans le cache en mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé. |\n| `value` | `Object` | yes |  | N'importe quelle valeur. |\n| `expire` | `String` | no | `'5 minutes'` | La durée de validité de la valeur. |\n\nLa valeur est conservée dans la mémoire du processus jusqu'à son expiration. `expire` est une durée sous la forme qu'accepte `Date.add()` (`'30 seconds'`, `'5 minutes'`, `'1 hour'`, `'2 days'`). La valeur est stockée telle quelle, sans copie : si tu la modifies, la valeur en cache change aussi. Les éléments expirés sont supprimés chaque minute.\n\nExample: Mettre un résultat en cache\n```js\nCACHE.set('products', items, '2 minutes');\n```\n\n### CACHE.get(key, [def])\n\nType: `method`\n\nLit une valeur du cache en mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé. |\n| `def` | `Object` | no |  | La valeur renvoyée quand la clé est absente ou expirée. |\n\nReturns: `Object`\n\nRenvoie la valeur si elle existe et n'a pas expiré ; sinon `def`. `CACHE.read()` est un alias.\n\nExample: Lire ou charger\n```js\nvar items = CACHE.get('products');\nif (!items) {\n\titems = await DATA.find('nosql/products').promise($);\n\tCACHE.set('products', items, '2 minutes');\n}\n```\n\n### CACHE.remove(key)\n\nType: `method`\n\nSupprime une valeur du cache en mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé. |\n\nAppelle-la quand les données en cache changent, pour que la lecture suivante charge des données fraîches.\n\nExample: Invalider\n```js\nNOSQL('products').insert(model).callback(function() {\n\tCACHE.remove('products');\n});\n```\n\n### CACHE.reset([search])\n\nType: `method`\n\nSupprime de nombreuses valeurs, ou toutes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | no |  | Une partie des clés, ou un motif. |\n\nReturns: `Number` Le nombre de clés supprimées.\n\nSans `search`, tout le cache est vidé. Avec une chaîne, chaque clé qui la contient est supprimée ; avec une expression régulière, chaque clé qui lui correspond. Renvoie le nombre de clés supprimées (0 quand tout le cache est vidé).\n\nExample: Supprimer un groupe\n```js\nCACHE.set('products_1', a);\nCACHE.set('products_2', b);\nCACHE.reset('products_');  // 2\nCACHE.reset(/^user_/);\nCACHE.reset();             // everything\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method`\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 la dernière modification et l'écriture. |\n| `skip` | `String|Array` | no |  | Les clés non écrites dans le fichier, sous forme de tableau ou de chaîne séparée par des virgules. |\n\nReturns: `Object` Les données avec `save()` et `set(key, value)`.\n\nLit `databases/memorize_{name}.json` (ou `databases/memorize.json` sans nom) et renvoie son contenu sous forme d'objet (un objet vide si le fichier n'existe pas). L'objet reçoit deux fonctions : `save()` planifie l'écriture de l'objet entier, et `set(key, value)` affecte une valeur et appelle `save()`. L'écriture a lieu `delay` millisecondes après le dernier appel, de sorte que de nombreuses modifications produisent une seule écriture. `skip` liste les clés qui ne sont pas écrites. Les arguments `delay` et `skip` peuvent être inversés. Appelle `MEMORIZE()` une seule fois par nom et conserve l'objet ; chaque appel relit le fichier.\n\nExample: Des paramètres qui survivent aux redémarrages\n```js\nvar settings = MEMORIZE('settings', 'cache');\n\nsettings.set('title', 'My shop');\n\nsettings.counter = (settings.counter || 0) + 1;\nsettings.cache = {};      // not written\nsettings.save();\n```\n\n### BACKUP(filename, files, [callback], [filter])\n\nType: `method`\n\nRegroupe des fichiers et des répertoires dans un seul fichier d'archive.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Le fichier d'archive à créer (un fichier existant est remplacé). |\n| `files` | `String|Array` | yes |  | Un répertoire, ou des chemins relatifs à la racine. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)` ; renvoie `true` pour archiver le chemin. |\n\nReturns: `Promise` Quand `callback` est omis.\n\nÉcrit une archive texte : une ligne par répertoire et une ligne par fichier, avec le chemin et le contenu compressé en gzip et encodé en base64. `files` est un répertoire (tout son contenu est archivé avec des chemins relatifs à celui-ci) ou un tableau de chemins relatifs à la racine de l'application (fichiers et répertoires entiers). Les noms qui contiennent `.git`, `.gitignore`, `.npmignore` ou `.ds_store` sont ignorés. `filter(path, isdirectory)` reçoit chaque chemin (commençant par `/`) et l'exclut quand il renvoie une valeur falsy. `filename` peut aussi être un flux en écriture. Le callback reçoit `{ filename, files, size }` ; sans callback, la fonction renvoie une promesse.\n\nExample: Sauvegarder les uploads\n```js\nvar meta = await BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), null, function(path, isdir) {\n\treturn isdir || !path.endsWith('.tmp');\n});\nprint(meta.files, 'files', meta.size, 'bytes');\n```\n\nExample: Chemins sélectionnés\n```js\nawait BACKUP(PATH.temp('app.backup'), ['config', 'databases', 'public/uploads']);\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nDécompresse une archive créée par BACKUP().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | L'archive. |\n| `target` | `String` | yes |  | Le répertoire dans lequel décompresser. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nReturns: `Promise` Quand `callback` est omis.\n\nCrée les répertoires et les fichiers de l'archive dans `target`. `filename` peut aussi être un flux en lecture. `filter(path, isdirectory)` est appelé pour chaque élément : pour un répertoire, `false` empêche sa création ; pour un fichier, renvoie `false` pour l'ignorer, une chaîne pour l'écrire sous ce chemin (relatif à `target`), ou rien pour conserver son chemin. Le callback reçoit `{ files, size, path }` ; sans callback, la fonction renvoie une promesse.\n\nExample: Restaurer\n```js\nvar meta = await RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'));\nprint('Restored', meta.files, 'files');\n```\n\nExample: Ignorer des fichiers au passage\n```js\nRESTORE(PATH.temp('app.backup'), PATH.root(), function(err) {\n\terr && print(err);\n}, function(path, isdir) {\n\tif (!isdir && path.startsWith('/config'))\n\t\treturn false;\n});\n```\n\n### PATH.root([path])\n\nType: `method`\n\nRenvoie le répertoire racine de l'application, ou un chemin à l'intérieur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un chemin relatif. |\n\nReturns: `String` Un chemin absolu.\n\nLa racine est le répertoire de l'application (là où s'exécute le script de démarrage). Avec `path`, elle renvoie la racine jointe à ce chemin. Comme les autres fonctions de répertoire de `PATH`, elle crée le répertoire la première fois qu'elle est appelée avec un chemin. `PATH.public()`, `PATH.private()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()`, `PATH.templates()`, `PATH.flowstreams()` et `PATH.scripts()` fonctionnent de la même façon pour leurs répertoires.\n\nExample: Chemins\n```js\nPATH.root();                 // '/www/app'\nPATH.root('config');         // '/www/app/config'\nPATH.private('report.pdf');  // '/www/app/private/report.pdf'\n```\n\n### PATH.databases([path])\n\nType: `method`\n\nRenvoie le répertoire des bases de données, ou un chemin à l'intérieur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un chemin relatif. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire `/databases/` contient les fichiers des bases NoSQL, les fichiers `MEMORIZE()` et d'autres données de l'application. Il est créé la première fois que tu demandes un chemin à l'intérieur.\n\nExample: Un fichier de données\n```js\nvar filename = PATH.databases('import.json');\nFs.writeFile(filename, JSON.stringify(data), NOOP);\n```\n\n### PATH.temp([path])\n\nType: `method`\n\nRenvoie le répertoire temporaire, ou un chemin à l'intérieur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un chemin relatif. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire `/tmp/` contient les uploads, les fichiers en cache et les ressources compilées. `PATH.tmp()` est un alias. Au démarrage de l'application, le framework y supprime ses propres fichiers temporaires (fichiers `.js`, `.css`, `.html`, `.htm`, `.tmp` et `.upload`). Conserve les données qui doivent durer dans `/databases/`.\n\nExample: Un fichier temporaire\n```js\nvar filename = PATH.temp(UID() + '.csv');\n```\n\n### PATH.exists(path, [callback])\n\nType: `method`\n\nVérifie si un fichier ou un répertoire existe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un chemin absolu. |\n| `callback` | `Function` | no |  | `function(exists, size, isfile)`. |\n\nReturns: `Promise<Boolean>` Quand `callback` est omis.\n\nLe callback reçoit trois arguments : `exists`, la taille en octets et `isfile` (`true` pour un fichier, `false` pour un répertoire). Sans callback, la fonction renvoie une promesse résolue avec `exists`.\n\nExample: Vérifier un fichier\n```js\nif (await PATH.exists(PATH.databases('settings.json')))\n\tprint('Settings found');\n\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isfile) {\n\tprint(exists, size, isfile);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nSupprime un ou plusieurs fichiers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|Array` | yes |  | Un chemin absolu, ou un tableau de chemins. |\n| `callback` | `Function` | no |  | `function()`. |\n\nSupprime les fichiers l'un après l'autre, puis appelle le callback. Les erreurs (par exemple un fichier manquant) sont ignorées.\n\nExample: Supprimer des fichiers\n```js\nPATH.unlink([PATH.temp('a.csv'), PATH.temp('b.csv')], function() {\n\tprint('Removed');\n});\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|Array` | yes |  | Un chemin absolu, ou un tableau de chemins. |\n| `callback` | `Function` | no |  | `function()`. |\n\nPour chaque répertoire, tous les fichiers sont supprimés, puis les sous-répertoires en partant du plus profond, puis le répertoire lui-même. Ensuite, le callback est appelé.\n\nExample: Supprimer un répertoire\n```js\nPATH.rmdir(PATH.temp('export'), function() {\n\tprint('Directory removed');\n});\n```\n\n### Total.FsPromises\n\nType: `property`\n\nLe module Node.js `node:fs/promises`.\n\nReturns: `Object` Le module `node:fs/promises`.\n\nLa version à promesses des fonctions du système de fichiers de Node.js, chargée par le framework. `F.FsPromises` est le même objet, et `Total.Fs` (`F.Fs`) est le module `node:fs`.\n\nExample: Lire et lister\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\nvar files = await Total.FsPromises.readdir(PATH.public());\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nConvertit n'importe quelle valeur en nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur à convertir. |\n| `def` | `Number` | no | `0` | Le résultat pour les valeurs vides ou invalides. |\n\nReturns: `Number`\n\nUn nombre est renvoyé tel quel. Une chaîne est débarrassée de ses espaces et convertie avec le `+` unaire ; les autres valeurs sont d'abord converties en chaîne. `null`, `undefined`, une chaîne vide et une valeur qui n'est pas un nombre renvoient `def` (0 par défaut). Le résultat n'est pas arrondi (`'1.5'` donne `1.5`). `U.parseFloat(value, [def])` fonctionne de la même façon et accepte aussi la virgule comme séparateur décimal (`'12,50'` donne `12.5`).\n\nExample: Valeurs de la query string\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\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 |  | La valeur à convertir. |\n| `def` | `Boolean` | no | `false` | Le résultat pour `null` ou `undefined`. |\n\nReturns: `Boolean`\n\nUn booléen est renvoyé tel quel ; un nombre vaut `true` s'il est supérieur à 0 ; les chaînes `true`, `1` et `on` (quelle que soit la casse) valent `true` et toute autre chaîne vaut `false`. `null` et `undefined` renvoient `def` (`false` par défaut).\n\nExample: Une case à cocher\n```js\nvar newsletter = U.parseBoolean(this.body.newsletter); // 'on' -> true\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nLit une valeur imbriquée par un chemin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'objet à lire. |\n| `path` | `String` | yes |  | Le chemin. |\n\nReturns: `Object` La valeur, ou `undefined`.\n\nLe chemin utilise des points et des crochets : `a.b.c`, `items[0].name`. Quand une partie du chemin manque, elle renvoie `undefined` au lieu de lever une exception. Les chemins contenant des espaces, des parenthèses ou des mots-clés comme `__proto__` et `constructor` sont refusés (`undefined`). Les lecteurs compilés sont mis en cache par chemin.\n\nExample: Valeurs imbriquées\n```js\nvar data = { user: { address: { city: 'Bratislava' } }, items: [{ name: 'A' }] };\nU.get(data, 'user.address.city');  // 'Bratislava'\nU.get(data, 'items[0].name');      // 'A'\nU.get(data, 'user.phone.number');  // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nÉcrit une valeur imbriquée par un chemin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'objet dans lequel écrire. |\n| `path` | `String` | yes |  | Le chemin. |\n| `value` | `Object` | yes |  | La valeur. |\n\nReturns: `Object` La valeur écrite.\n\nLes objets manquants sur le chemin sont créés. Un chemin qui se termine par `[]` ajoute la valeur au tableau, et un index crée un tableau contenant des objets (`items[0].name`). Les chemins avec des espaces, des parenthèses ou des mots-clés comme `__proto__` et `constructor` sont refusés : rien n'est écrit. Renvoie la valeur.\n\nExample: Construire un objet\n```js\nvar model = {};\nU.set(model, 'address.city', 'Bratislava');\nU.set(model, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\nExample: Chemin avec un index\n```js\nvar model = {};\nU.set(model, 'items[0].name', 'Pen');\n// { items: [{ name: 'Pen' }] }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nCopie les clés de source dans target.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | L'objet dans lequel écrire. |\n| `source` | `Object` | yes |  | L'objet à lire. |\n| `rewrite` | `Boolean` | no | `true` | `false` conserve les valeurs existantes. |\n\nReturns: `Object` La cible.\n\nChaque clé de `source` est clonée dans `target`. Avec `rewrite` à `false`, les clés qui existent déjà dans `target` ne sont pas modifiées, ce qui permet de remplir des valeurs par défaut. Renvoie `target`.\n\nExample: Valeurs par défaut\n```js\nvar options = { limit: 50 };\nU.extend(options, { limit: 10, sort: 'name' }, false);\n// { limit: 50, sort: 'name' }\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nRenvoie une fonction de comparaison pour Array.sort().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Par exemple `name` ou `price_desc,name`. |\n\nReturns: `Function` `function(a, b)` pour `Array.prototype.sort()`.\n\n`sort` est une liste de clés séparées par des virgules ; ajoute `_desc` pour l'ordre décroissant (`_asc` est la valeur par défaut). Les clés imbriquées utilisent des points (`address.city`). Le type de chaque clé est déduit de la première valeur non vide la première fois que l'expression est utilisée, et il est conservé pour les utilisations suivantes de la même expression : les chaînes sont comparées en tenant compte des signes diacritiques, les nombres, les booléens et les dates par valeur.\n\nExample: Trier des produits\n```js\nproducts.sort(U.sortcomparer('price_desc,name'));\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nRenvoie un entier aléatoire dans un intervalle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | La plus grande valeur. |\n| `min` | `Number` | no | `0` | La plus petite valeur. |\n\nReturns: `Number`\n\nRenvoie un entier entre `min` et `max`, tous deux inclus.\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 |  | Le nombre de caractères. |\n\nReturns: `String`\n\nLes caractères sont `0-9`, `A-Z` et `a-z`. `U.random_string(length)` n'utilise que des lettres, et `U.random_number(length)` que des chiffres (renvoyés sous forme de chaîne qui ne commence pas par 0). Ces valeurs proviennent de `Math.random()` : ne les utilise pas comme mots de passe ni comme jetons de sécurité.\n\nExample: Chaînes aléatoires\n```js\nU.random_text(8);    // 'yb7JVb2a'\nU.random_string(6);  // 'HNXkTk'\nU.random_number(6);  // '825174'\n```\n\n### U.convert62(number)\n\nType: `method`\n\nConvertit un nombre en chaîne en base 62.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | Un nombre non négatif. |\n\nReturns: `String`\n\nLes chiffres sont `0-9`, `A-Z` et `a-z`, dans cet ordre. Le nombre est d'abord arrondi à l'entier inférieur. `U.from62(value)` reconvertit la chaîne en nombre. Utilise-la pour des codes courts créés à partir d'identifiants numériques.\n\nExample: Codes courts\n```js\nvar code = U.convert62(123456);  // 'W7E'\nvar id = U.from62(code);         // 123456\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nRenvoie l'extension d'un nom de fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un nom de fichier, un chemin ou une URL. |\n| `raw` | `Boolean` | no | `false` | `true` conserve la casse d'origine. |\n\nReturns: `String`\n\nRenvoie la partie après le dernier point, sans le point et en minuscules (avec `raw`, dans la casse d'origine). Une query string après `?` est ignorée. Renvoie une chaîne vide quand le nom n'a pas d'extension.\n\nExample: Extensions\n```js\nU.getExtension('/img/Photo.JPG');      // 'jpg'\nU.getExtension('/files/a.pdf?v=1');    // 'pdf'\nU.getExtension('README');              // ''\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 |  | Un chemin ou une URL. |\n\nReturns: `String`\n\nRenvoie le nom du fichier (ou du dernier répertoire) d'un chemin avec des séparateurs `/` ou `\\\\`. Un séparateur final est ignoré.\n\nExample: Noms de fichiers\n```js\nU.getName('/www/app/public/logo.png');  // 'logo.png'\nU.getName('/www/app/public/');          // 'public'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nRenvoie le type MIME d'une extension.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Une extension, par ex. `png` ou `.png`. |\n\nReturns: `String`\n\nL'extension peut commencer par un point. Les extensions inconnues renvoient `application/octet-stream`. `U.getExtensionFromContentType(type)` fait l'inverse et renvoie la première extension de ce type (ou `undefined`). La table complète est `U.contentTypes`.\n\nExample: Types de contenu\n```js\nU.getContentType('png');                     // 'image/png'\nU.getContentType('.json');                   // 'application/json'\nU.getExtensionFromContentType('image/png');  // 'png'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nEncode un texte ou un buffer en base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Les données à encoder. |\n\nReturns: `String`\n\nUn buffer est encodé directement ; les autres valeurs sont converties en chaîne et encodées en UTF-8. `U.atob(value)` décode le base64 en chaîne UTF-8.\n\nExample: Base64\n```js\nvar encoded = U.btoa('Hello');   // 'SGVsbG8='\nvar text = U.atob(encoded);      // 'Hello'\n```\n\n### U.validhost(host)\n\nType: `method`\n\nVérifie qu'un nom d'hôte est en ASCII simple et qu'une adresse IP est dans sa forme canonique.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | Le nom d'hôte ou l'adresse IP. |\n\nReturns: `Boolean` `true` pour un hôte valide.\n\nRenvoie `false` pour une valeur qui n'est pas une chaîne, qui est vide ou qui contient un caractère en dehors de la plage ASCII visible (espaces, octets NUL, lettres accentuées). Une valeur composée uniquement de nombres et de points (ou de nombres hexadécimaux) doit être une adresse IPv4 canonique : `127.0.0.1` est valide, `127.1`, `0127.0.0.1`, `0x7f.0.0.1` et `2130706433` ne le sont pas. Les autres valeurs ASCII, y compris les adresses IPv6, renvoient `true` ; la fonction ne vérifie pas la syntaxe complète d'un nom d'hôte. Convertis d'abord un nom international avec `U.tohost()`.\n\nExample: Vérifier des hôtes\n```js\nU.validhost('example.com');     // true\nU.validhost('127.0.0.1');       // true\nU.validhost('127.1');           // false\nU.validhost('0x7f.0.0.1');      // false\nU.validhost('münchen.de');      // false\nU.validhost('evil.example\\0.trusted.example'); // false\n```\n\n### U.tohost(host)\n\nType: `method`\n\nConvertit un nom d'hôte dans sa forme ASCII canonique.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | Le nom d'hôte ou l'adresse IP. |\n\nReturns: `String` L'hôte canonique, ou une chaîne vide.\n\nConvertit l'hôte avec le parseur d'URL de Node.js : les lettres passent en minuscules, un nom international devient du punycode, et une adresse IPv4 dans une autre notation prend la forme à points (un `0` initial signifie un nombre octal, `0x` un nombre hexadécimal). Le résultat est ensuite vérifié avec `U.validhost()`. Une valeur qui contient `:` (une adresse IPv6) est seulement vérifiée. Renvoie une chaîne vide quand l'hôte n'est pas valide, donc teste le résultat avant de l'utiliser.\n\nExample: Convertir des hôtes\n```js\nU.tohost('münchen.de');      // 'xn--mnchen-3ya.de'\nU.tohost('EXAMPLE.com');     // 'example.com'\nU.tohost('127.1');           // '127.0.0.1'\nU.tohost('0x7f.0.0.1');      // '127.0.0.1'\nU.tohost('evil.example\\0.trusted.example'); // ''\n```\n\nExample: Valider une saisie\n```js\nfunction host(value) {\n\tvar host = U.tohost(value);\n\tif (!host)\n\t\tthrow new Error('Invalid hostname');\n\treturn host;\n}\n```\n\n### U.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` | no |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Millisecondes avant l'échec de l'attente. |\n| `interval` | `Number` | no | `500` | Millisecondes entre les vérifications. |\n\nReturns: `Promise` Quand `callback` est omis.\n\n`validator` est appelé immédiatement, puis toutes les `interval` millisecondes jusqu'à ce qu'il renvoie `true` ; le callback reçoit alors `(null, true)`. Si `timeout` est atteint avant, le callback reçoit une `Error('Timeout')`. Sans callback, la fonction renvoie une promesse résolue ou rejetée de la même façon.\n\nExample: Attendre une connexion\n```js\nawait U.wait(() => MAIN.db != null, null, 10000, 200);\nprint('Database ready');\n```\n\n### U.resolve(url, callback, [param])\n\nType: `method`\n\nRésout l'hôte d'une URL en adresses IPv4, avec un cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Une URL absolue. |\n| `callback` | `Function` | yes |  | `function(err, uri, param, addresses)`. |\n| `param` | `Any` | no |  | Une valeur passée au callback. |\n\nAnalyse `url`, vérifie son nom d'hôte avec `U.validhost()` et demande ses adresses IPv4 aux serveurs DNS (`dns.resolve4()`, donc le fichier hosts n'est pas utilisé). Le callback reçoit `(err, uri, param, addresses)` : `uri` est l'URL analysée avec `host` défini sur la première adresse, `param` est le troisième argument et `addresses` la liste complète. Les adresses sont mises en cache pendant toute la durée de vie du processus ; une résolution qui échoue est retentée une fois avant que `err` soit passé.\n\nUne chaîne qui n'est pas une URL donne `TypeError: Invalid URL`, et un nom d'hôte non valide donne l'erreur `Invalid hostname` sans requête DNS. Pour les URL `http` et `https`, le parseur d'URL convertit déjà l'hôte ; pour les autres schémas, une adresse non canonique comme `tcp://127.1/` donne `Invalid hostname`. `REQUEST()` utilise cette fonction avec l'option `resolve: true`, et `RESTBuilder` par défaut.\n\nExample: Résoudre un hôte\n```js\nU.resolve('https://example.com/api/', function(err, uri, param, addresses) {\n\tif (err)\n\t\tconsole.log(err.message || err.code);\n\telse\n\t\tconsole.log(uri.hostname, addresses);\n});\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nDécoupe un flux de données en parties selon des délimiteurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Le début d'une partie, ou le séparateur. |\n| `end` | `String|Buffer` | no |  | La fin d'une partie. |\n| `callback` | `Function` | yes |  | `function(value, index)` ; renvoie `false` pour arrêter. |\n| `skip` | `Number` | no | `0` | Le nombre de premières parties à ignorer. |\n| `stream` | `Stream` | no |  | Un flux dont l'événement `end` traite le reste. |\n\nReturns: `Function` `function(chunk)`.\n\nRenvoie une fonction que tu appelles avec chaque fragment (un buffer), par exemple comme gestionnaire `data` d'un flux. Avec `beg` et `end`, le callback reçoit chaque partie qui commence par `beg` et se termine par `end`, tous deux inclus (par exemple un `<item>...</item>` d'un gros fichier XML). Avec `beg` seul, `beg` est un séparateur et le callback reçoit chaque partie jusqu'à celui-ci inclus (par exemple des lignes avec `\\n`). Le callback reçoit `(value, index)` avec la valeur sous forme de chaîne ; renvoyer `false` arrête l'analyse. `skip` ignore ce nombre de premières parties. Avec `stream`, les données restantes sont traitées à la fin du flux. `U.streamer2()` prend les mêmes arguments et transmet des buffers au lieu de chaînes.\n\nExample: Lire un gros fichier XML\n```js\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\nstream.on('data', U.streamer('<product>', '</product>', function(value, index) {\n\tvar product = value.parseXML();\n\tprint(index, product);\n}));\n```\n\nExample: Lignes d'un fichier CSV\n```js\nvar stream = Fs.createReadStream(filename);\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tvar cols = line.trim().split(';');\n}, 1, stream));  // skips the header line\n```\n\n### U.connect(options, [callback])\n\nType: `method`\n\nOuvre une connexion TCP ou TLS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | `{ host, port, secure, tls, timeout }` et, avec `secure`, d'autres options de `tls.connect()`. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nSe connecte à `options.host` et `options.port` et appelle `callback(err, meta)` quand la connexion est ouverte. L'hôte est d'abord converti avec `U.tohost()`, donc un nom international est envoyé en punycode et `127.1` comme `127.0.0.1` ; un hôte non valide donne l'erreur `Invalid hostname` et aucune connexion n'est établie. Avec `secure: true`, la connexion utilise TLS dès le départ et les autres options (`servername`, `rejectUnauthorized`, `ca` ...) vont à `tls.connect()`. Avec `tls`, la connexion commence en TCP simple et passe en TLS dès qu'elle est ouverte : `tls: true` utilise les options par défaut de `tls.connect()`, un objet transmet ses options (`servername`, `rejectUnauthorized`, `ca` ...). Avec `timeout` (en millisecondes), une connexion qui n'est pas ouverte à temps donne l'erreur `Timeout`.\n\n`meta` a `socket` (le socket Node.js), `opt` (les options avec l'hôte converti), `write(data)`, `ondata(fn)` pour les morceaux reçus, et `close()` (aussi `destroy()`). `LDAP()` se connecte avec cette fonction.\n\nExample: Lire le message d'accueil d'un serveur\n```js\nU.connect({ host: 'mail.example.com', port: 25, timeout: 5000 }, function(err, meta) {\n\tif (err) {\n\t\tconsole.log(err.message);\n\t\treturn;\n\t}\n\tmeta.ondata(function(chunk) {\n\t\tconsole.log(chunk.toString());\n\t\tmeta.close();\n\t});\n});\n```\n\nExample: Passer en TLS\n```js\nU.connect({ host: 'mail.example.com', port: 465, tls: { servername: 'mail.example.com' } }, function(err, meta) {\n\tif (!err)\n\t\tconsole.log(meta.socket.encrypted); // true\n});\n```\n\n### U.ls(path, [callback], [filter])\n\nType: `method`\n\nListe récursivement les fichiers et les répertoires d'un répertoire.\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 |  | Le filtre. |\n\nReturns: `Promise` `{ files, directories }` quand `callback` est omis.\n\nLe callback reçoit deux tableaux de chemins absolus : `files` et `directories` (les répertoires se terminent par le séparateur de chemin). `filter` peut être une chaîne (les chemins qui la contiennent, sans tenir compte de la casse), une expression régulière, ou une fonction `(path, isdirectory)` qui renvoie `true` pour conserver l'élément ; les filtres de type chaîne et expression régulière ne s'appliquent qu'aux fichiers. Un répertoire écarté par le filtre n'est pas parcouru. Sans callback, la fonction renvoie une promesse avec `{ files, directories }`. `U.ls2()` prend les mêmes arguments et renvoie les fichiers sous forme d'objets `{ filename, stats }` avec les `fs.Stats` de chaque fichier.\n\nExample: Trouver les fichiers JSON\n```js\nU.ls(PATH.databases(), function(files, directories) {\n\tprint(files);\n}, /\\.json$/);\n```\n\nExample: Tailles avec ls2\n```js\nvar result = await U.ls2(PATH.public('uploads'));\nvar size = 0;\nfor (var file of result.files)\n\tsize += file.stats.size;\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nStocke une longue liste dans des fichiers temporaires, par pages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom unique, utilisé pour les noms de fichiers. |\n| `max` | `Number` | no | `50` | Éléments par page. |\n\nReturns: `Chunker`\n\nUn chunker collecte des éléments avec `write(item)` (alias `append()`) ; tous les `max` éléments, ils sont écrits dans un fichier `tmp/{name}-{index}.chunker` (compressé avec deflate quand `compress` vaut `true`, la valeur par défaut), de sorte que la mémoire reste faible. Appelle `end()` pour écrire le reste. Ensuite, `each(onitem, [ondone])` lit les pages dans l'ordre : `onitem(items, next, index)` reçoit une page et appelle `next()` pour continuer, et `percentage` indique l'avancement de la lecture. `read(index, callback)` lit une seule page. Avec `autoremove` (`true` par défaut), chaque fichier est supprimé après sa lecture ; `clear()` supprime tous les fichiers et `destroy()` libère aussi le chunker. Les propriétés `count` et `pages` contiennent le nombre d'éléments et de pages.\n\nExample: Traiter un gros export\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var row of rows)\n\tchunker.write(row);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tprint('Page', index, chunker.percentage + '%');\n\tsend(items, next);\n}, function() {\n\tprint('Done', chunker.count, 'items');\n});\n```\n\n### chunker.load([callback])\n\nType: `method` · Since: `0.0.16`\n\nRetrouve les pages qu'un chunker précédent du même nom a laissées sur le disque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `Promise` Quand `callback` est omis.\n\nCompte les fichiers du chunker dans le répertoire temporaire et définit l'index interne des pages, afin que `each()` et `read()` puissent lire les pages qu'une instance précédente a écrites et n'a pas lues (par exemple avant un redémarrage). Crée le chunker avec le même `name`. Le callback reçoit `(null, count)` ; sans callback, la fonction renvoie une promesse résolue une fois le comptage terminé.\n\nExample: Reprendre un chunker\n```js\nvar chunker = U.chunker('export');\nawait chunker.load();\nchunker.each(function(items, next) {\n\tsend(items, next);\n});\n```\n\n### new U.EventEmitter2() / U.EventEmitter2(obj)\n\nType: `class`\n\nUn petit émetteur d'événements.\n\nReturns: `EventEmitter2`\n\nUn objet avec `on(name, fn)`, `once(name, fn)`, `off(name, [fn])` et `emit(name, ...args)` (jusqu'à sept arguments). `off(name)` sans fonction supprime tous les gestionnaires de l'événement. Les gestionnaires s'exécutent avec l'émetteur comme `this`. Appelée avec un objet (`U.EventEmitter2(obj)`), elle ajoute ces méthodes à cet objet, sauf s'il possède déjà `emit`, et le renvoie.\n\nExample: Des événements sur ton objet\n```js\nvar Cart = {};\nU.EventEmitter2(Cart);\n\nCart.on('add', function(item) {\n\tprint('Added', item.name);\n});\n\nCart.emit('add', { name: 'Shoes' });\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nObfusque une chaîne avec une clé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le texte. |\n| `key` | `String` | yes |  | La clé. |\n| `encode` | `String` | no | `'base64'` | L'encodage de sortie, ou `buffer`. |\n\nReturns: `String|Buffer`\n\nEncode la chaîne avec la clé et un masque aléatoire de 4 octets, et la renvoie en base64 (ou dans l'encodage que tu définis ; `buffer` renvoie un buffer). La même entrée donne une sortie différente à chaque fois. `U.decrypt_data(value, key, [encode])` renvoie la chaîne d'origine, ou `null` pour une entrée invalide. Il s'agit d'une obfuscation légère, pas d'un chiffrement fort ; pour les données sensibles, utilise `ENCRYPT()` (voir [Chiffrement](../../guides/encryption/)).\n\nExample: Aller-retour\n```js\nvar data = U.encrypt_data('hello', 'mykey');\nvar text = U.decrypt_data(data, 'mykey');  // 'hello'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nSigne un identifiant pour qu'il ne puisse pas être modifié.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | L'identifiant. |\n| `key` | `String` | no | `CONF.secret` | La clé. |\n\nReturns: `String`\n\nRenvoie l'identifiant précédé d'une somme de contrôle, calculée à partir de la valeur, de la clé et de `CONF.secret_uid`. `U.decrypt_uid(value, [key])` la vérifie et renvoie l'identifiant d'origine (un nombre si l'original était un nombre) ou `null` si la valeur a été modifiée. L'identifiant lui-même reste lisible. Sans `key`, `CONF.secret` est utilisé.\n\nExample: Id signé dans un lien\n```js\nvar signed = U.encrypt_uid(123, 'mykey');   // 'n...x123', the checksum depends on CONF.secret_uid\nU.decrypt_uid(signed, 'mykey');             // 123\nU.decrypt_uid('n2v55u4jx124', 'mykey');     // null\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifie du JavaScript ; U.minify_css() et U.minify_html() font de même pour le CSS et le HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le code source. |\n\nReturns: `String`\n\nCe sont les minificateurs qu'utilise le framework pour les fichiers statiques et les vues. Ils prennent une chaîne et renvoient la chaîne minifiée.\n\nExample: Minifier\n```js\nU.minify_js('var a = 1 ;  // note\\n');  // 'var a=1;'\nU.minify_css('a { color : red ; }');     // 'a{color:red}'\nU.minify_html(html);\n```\n\n### U.aistreamer(online, [onmessage])\n\nType: `method` · Since: `0.0.16`\n\nAnalyse la réponse en stream d'une API de chat d'IA en lignes de texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `online` | `Function` | yes |  | `function(line)`, appelée pour chaque ligne de texte complète. |\n| `onmessage` | `Function` | no |  | `function(message)`, appelée pour chaque message JSON analysé. |\n\nReturns: `Function` `function(chunk)`.\n\nRenvoie une fonction que tu appelles avec chaque morceau (un buffer) d'une réponse en stream. Elle lit les messages JSON ligne par ligne dans deux formats : les server-sent events avec `data: {...}` (OpenAI completions, où le texte est dans `choices[0].delta.content` et `data: [DONE]` y met fin) et les lignes JSON simples (Ollama, où le texte est dans `message.content` et `done` y met fin). Le texte est collecté et `online(line)` est appelée pour chaque ligne complète. `onmessage(obj)`, si tu la définis, reçoit chaque message analysé ; les dates JSON sont alors analysées en tant que dates.\n\nExample: Afficher une réponse ligne par ligne\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nMet en cache le résultat d'une tâche dans un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Identifiant de l'élément en cache. |\n| `expire` | `String` | yes |  | Durée de validité du fichier, par exemple `'5 minutes'`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `maker` | `Function` | yes |  | `function(next, id)` qui crée la valeur. |\n| `encoding` | `String` | no | `json` | `json` ou un encodage de fichier comme `utf8`. |\n\nCherche le fichier de `id` dans `tmp/`. Quand il existe et qu'il est plus récent que `expire`, son contenu va à `callback(err, response)`. Sinon, `maker(next, id)` s'exécute ; `next(err, response, [load])` écrit la réponse dans le fichier et appelle `callback`, sauf si `load` vaut `false`. Avec l'encodage `json`, la valeur est stockée en JSON et analysée à la relecture ; tout autre encodage stocke et lit le contenu brut.\n\nExample: Mettre en cache une liste distante\n```js\nFILECACHE('currencies', '1 day', function(err, response) {\n\tMAIN.currencies = response;\n}, function(next) {\n\tREQUEST({ url: 'https://example.com/rates.json', callback: function(err, response) {\n\t\tnext(err, err ? null : response.body.parseJSON());\n\t}});\n});\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID()","since":"","deprecated":false},{"type":"method","name":"GUID([length])","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"HASH(value, [type])","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"CLONE(obj, [skip], [nofunctions])","signature":"CLONE(obj, [skip], [nofunctions])","since":"","deprecated":false},{"type":"method","name":"COPY(source, [target], [all])","signature":"COPY(source, [target], [all])","since":"","deprecated":false},{"type":"method","name":"DIFFARR(prop, db, form)","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"QUERIFY([url], obj)","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"PROMISIFY(fn, [a], [b], [c])","signature":"PROMISIFY(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"ERROR([name])","signature":"ERROR([name])","since":"","deprecated":false},{"type":"method","name":"print()","signature":"print(...values)","since":"","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"NOOP","signature":"NOOP","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","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":"CACHE.set(key, value, [expire])","signature":"CACHE.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"CACHE.get(key, [def])","signature":"CACHE.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"CACHE.remove(key)","signature":"CACHE.remove(key)","since":"","deprecated":false},{"type":"method","name":"CACHE.reset([search])","signature":"CACHE.reset([search])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE([name], [delay], [skip])","signature":"MEMORIZE([name], [delay], [skip])","since":"","deprecated":false},{"type":"method","name":"BACKUP(filename, files, [callback], [filter])","signature":"BACKUP(filename, files, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE(filename, target, [callback], [filter])","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"PATH.root([path])","signature":"PATH.root([path])","since":"","deprecated":false},{"type":"method","name":"PATH.databases([path])","signature":"PATH.databases([path])","since":"","deprecated":false},{"type":"method","name":"PATH.temp([path])","signature":"PATH.temp([path])","since":"","deprecated":false},{"type":"method","name":"PATH.exists(path, [callback])","signature":"PATH.exists(path, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink(files, [callback])","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir(directories, [callback])","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"property","name":"Total.FsPromises","signature":"Total.FsPromises","since":"","deprecated":false},{"type":"method","name":"U.parseInt(value, [def])","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseBoolean(value, [def])","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.get(obj, path)","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set(obj, path, value)","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.extend(target, source, [rewrite])","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer(sort)","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.random([max], [min])","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text(length)","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.convert62(number)","signature":"U.convert62(number)","since":"","deprecated":false},{"type":"method","name":"U.getExtension(filename, [raw])","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName(path)","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType(ext)","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.btoa(value)","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.validhost(host)","signature":"U.validhost(host)","since":"","deprecated":false},{"type":"method","name":"U.tohost(host)","signature":"U.tohost(host)","since":"","deprecated":false},{"type":"method","name":"U.wait(validator, [callback], [timeout], [interval])","signature":"U.wait(validator, [callback], [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"U.resolve(url, callback, [param])","signature":"U.resolve(url, callback, [param])","since":"","deprecated":false},{"type":"method","name":"U.streamer(beg, [end], callback, [skip], [stream])","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.connect(options, [callback])","signature":"U.connect(options, [callback])","since":"","deprecated":false},{"type":"method","name":"U.ls(path, [callback], [filter])","signature":"U.ls(path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"U.chunker(name, [max])","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.load([callback])","signature":"chunker.load([callback])","since":"0.0.16","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2() / U.EventEmitter2(obj)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_data(value, key, [encode])","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid(value, [key])","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.minify_js(value)","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.aistreamer(online, [onmessage])","signature":"U.aistreamer(online, [onmessage])","since":"0.0.16","deprecated":false},{"type":"method","name":"FILECACHE(id, expire, callback, maker, [encoding])","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwwLBgx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/utilities/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Utilità","summary":"Funzioni U/Utils, helper globali (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), oggetti condivisi, CACHE, MEMORIZE, BACKUP, RESTORE e PATH.","markdown":"---\ntitle: \"Utilità\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/utilities/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Utilità\n\n> Funzioni U/Utils, helper globali (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), oggetti condivisi, CACHE, MEMORIZE, BACKUP, RESTORE e PATH.\n\nQuesta pagina elenca gli helper globali, gli oggetti globali condivisi, la `CACHE` in memoria, le funzioni `PATH` e le funzioni del modulo `U` (`Utils`) che le applicazioni usano. La guida [Utilità](../../guides/utilities/) spiega come si combinano, con esempi. I metodi aggiunti a `String`, `Number`, `Date` e `Array` si trovano in [Prototipi](../prototypes/).\n\n## API\n\n### U\n\nType: `property`\n\nIl modulo Utils come oggetto globale.\n\nReturns: `Object` Il modulo Utils.\n\nTutte le funzioni di `utils.js` sono disponibili tramite `U` e il suo alias `Utils` (entrambi puntano allo stesso oggetto). Questa pagina documenta le funzioni che le applicazioni usano; le altre sono usate dal framework stesso.\n\nExample: Usare un helper\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\nvar same = Utils === U;           // true\n```\n\n### UID()\n\nType: `method`\n\nRestituisce un nuovo identificatore univoco.\n\nReturns: `String` Per esempio `JacVuE1cn61f`.\n\nL'identificatore è una breve stringa di lettere e cifre: un timestamp in base 62 (in decimi di secondo), un contatore interno, un carattere casuale scelto all'avvio (cambiato ogni minuto), la lunghezza della parte temporale, una cifra di parità e la lettera `f`. Gli identificatori creati più tardi vengono ordinati dopo quelli precedenti nella maggior parte dei casi. Il validatore `uid` del framework (`DEF.validators.uid`) li accetta.\n\nExample: Un nuovo record\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\nNOSQL('products').insert(model);\n```\n\n### GUID([length])\n\nType: `method`\n\nRestituisce una stringa simile a un UUID, o una stringa casuale di una data lunghezza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Il numero di caratteri. Omettilo per il formato simile a UUID. |\n\nReturns: `String`\n\nSenza `length`, restituisce una stringa nella forma `xxxxxxxx-xxxx-Nxxx-Yxxx-xxxxxxxxxxxx` (36 caratteri) costruita dall'ora corrente e da cifre esadecimali casuali. Con `length`, restituisce altrettanti caratteri casuali tra `0-9` e `a-z`.\n\nExample: Token\n```js\nvar guid = GUID();       // '1a1e0561-0561-4c86-8eaf-d9a327a65943'\nvar token = GUID(30);    // 30 random characters\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nCalcola l'hash di una stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il testo di cui calcolare l'hash. |\n| `type` | `String` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32` o `crc32unsigned`. |\n\nReturns: `Number|String` Un numero senza tipo, una stringa esadecimale per i tipi md5/sha.\n\nSenza `type`, restituisce un numero a 32 bit senza segno calcolato dalla stringa (veloce, non crittografico). Con un tipo restituisce l'hash come stringa esadecimale (`md5`, `sha1`, `sha256`, `sha512`) o un numero CRC32 (`crc32`, `crc32unsigned`). `value` deve essere una stringa; converti prima i numeri con `+ ''`.\n\nExample: Hash\n```js\nHASH('abc');            // 96354\nHASH('abc', 'md5');     // '900150983cd24fb0d6963f7d28e17f72'\nHASH(email, 'sha256');\n```\n\n### CLONE(obj, [skip], [nofunctions])\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|Array` | yes |  | Il valore da copiare. Gli altri valori vengono restituiti invariati. |\n| `skip` | `Object` | no |  | Chiavi da escludere, ad es. `{ password: 1 }`. |\n| `nofunctions` | `Boolean` | no | `false` | `true` esclude le funzioni. |\n\nReturns: `Object|Array` La copia.\n\nGli oggetti e gli array annidati vengono copiati, i buffer nelle proprietà degli oggetti vengono duplicati, e date, errori e altri valori non oggetto restano come sono. `skip` è un oggetto le cui chiavi vengono escluse dalla copia a ogni livello. Con `nofunctions` vengono escluse anche le proprietà che contengono funzioni.\n\nExample: Copia senza una chiave\n```js\nvar user = { id: 'abc', name: 'Peter', password: 'secret', address: { city: 'Bratislava' } };\nvar safe = CLONE(user, { password: 1 });\nsafe.address.city = 'Prague';  // user.address.city is still 'Bratislava'\n```\n\n### COPY(source, [target], [all])\n\nType: `method`\n\nCopia le chiavi di un oggetto in un altro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | L'oggetto da leggere. |\n| `target` | `Object` | no |  | L'oggetto in cui scrivere. |\n| `all` | `Boolean` | no | `true` | `false` scrive solo le chiavi che `target` ha già. |\n\nReturns: `Object` Il target (o la nuova copia).\n\nOgni valore di `source` viene clonato e scritto in `target`. Con `all` impostato a `false`, vengono scritte solo le chiavi già definite in `target`, quindi `target` funziona come elenco dei campi consentiti. Senza `target`, restituisce una copia profonda di `source`.\n\nExample: Campi consentiti\n```js\nvar allowed = { name: '', email: '' };\nCOPY(this.body, allowed, false);\n// allowed contains only name and email from the body\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nConfronta due array di oggetti in base a una proprietà.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | La chiave che identifica un elemento, ad es. `id`. |\n| `db` | `Array` | yes |  | Gli elementi attuali (per esempio dal database). |\n| `form` | `Array` | yes |  | I nuovi elementi (per esempio da un form). |\n\nReturns: `Object` `{ add: Array, upd: Array, rem: Array }`.\n\nGli elementi corrispondono quando i loro valori `prop` sono uguali (`==`). Il risultato contiene tre array: `add` contiene gli elementi di `form` che non sono in `db`, `upd` contiene coppie `{ db, form }` di elementi corrispondenti e `rem` contiene i valori `prop` degli elementi di `db` che non sono in `form`.\n\nExample: Sincronizzare gli elementi\n```js\nvar diff = DIFFARR('id', current, model.items);\n\nfor (var item of diff.add)\n\tNOSQL('items').insert(item);\n\nfor (var pair of diff.upd)\n\tNOSQL('items').modify(pair.form).where('id', pair.db.id);\n\nfor (var id of diff.rem)\n\tNOSQL('items').remove().where('id', id);\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nCostruisce una query string da un oggetto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Un URL, eventualmente preceduto da un metodo. |\n| `obj` | `Object` | yes |  | I valori. |\n\nReturns: `String`\n\nChiavi e valori vengono codificati per URL. I valori `null`, `undefined` e vuoti vengono saltati, le date vengono scritte come stringhe ISO e gli array vengono uniti con virgole. Senza `url`, il risultato inizia con `?` (o è una stringa vuota quando non resta nulla). Con `url`, la query string viene aggiunta con `?` o `&`; l'URL può iniziare con un metodo HTTP (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `API`) seguito da uno spazio, come lo accettano `REQUEST()` e `AJAX()`. La funzione è anche `U.querify()`.\n\nExample: Query string\n```js\nQUERIFY({ q: 'red shoes', page: 2 });           // '?q=red%20shoes&page=2'\nQUERIFY('/api/?lang=en', { page: 2 });         // '/api/?lang=en&page=2'\nQUERIFY('GET https://example.com/', { id: 5 }); // 'GET https://example.com/?id=5'\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method`\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 il cui ultimo argomento è una callback. |\n| `a` | `Object` | no |  | Il primo argomento. |\n| `b` | `Object` | no |  | Il secondo argomento. |\n| `c` | `Object` | no |  | Il terzo argomento. |\n\nReturns: `Promise`\n\n`fn` viene chiamata con gli argomenti che passi (fino a tre) e una callback `function(err, response)`. La promise viene rifiutata con `err` o risolta con `response`. Passa solo gli argomenti che ti servono: un argomento `undefined` termina l'elenco.\n\nExample: Leggere un file\n```js\nvar Fs = require('fs');\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n\n### ERROR([name])\n\nType: `method`\n\nRestituisce una callback che registra gli errori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Il nome mostrato con l'errore, ad es. la funzione che è fallita. |\n\nReturns: `Function` `function(err)`.\n\nLa funzione restituita accetta `err` come primo argomento e, quando è impostato, lo passa al gestore degli errori del framework (`DEF.onError`, che lo stampa e lo conserva nelle statistiche) con `name` come origine. Usala per le callback di cui non ti serve il risultato ma di cui vuoi vedere gli errori.\n\nExample: Registrare una scrittura fallita\n```js\nFs.writeFile(PATH.databases('cache.json'), JSON.stringify(data), ERROR('cache.save'));\n```\n\n### print(...values)\n\nType: `method`\n\nScrive valori nella console.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `values` | `Object` | yes |  | I valori da stampare. |\n\n`print` è `console.log`. Il framework la usa per le sue informazioni di avvio.\n\nExample: Stampare\n```js\nprint('Imported', count, 'products');\n```\n\n### NOW\n\nType: `property`\n\nUna Date con l'ora corrente, aggiornata ogni 5 secondi.\n\nReturns: `Date`\n\nUna volta caricato, il framework assegna `new Date()` a `NOW` ogni 5 secondi, e anche quando scrive un errore, un log di audit o un elemento della cache. Usala dove basta una precisione di pochi secondi: scadenze, righe di log, campi `dtcreated`. Non modificare l'oggetto; assegna invece una nuova data.\n\nExample: Scadenza\n```js\nvar expire = NOW.add('1 hour');\nif (session.expire < NOW)\n\tdelete sessions[session.id];\n```\n\n### NOOP\n\nType: `property`\n\nUna funzione vuota.\n\nReturns: `Function`\n\nUsala dove è richiesta una callback ma il risultato non ti serve. È la stessa funzione di `U.noop`.\n\nExample: Ignorare il risultato\n```js\nFs.unlink(filename, NOOP);\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nUn oggetto vuoto congelato; EMPTYARRAY è un array vuoto congelato.\n\nReturns: `Object`\n\n`EMPTYOBJECT` (`{}`) e `EMPTYARRAY` (`[]`) vengono creati una volta e congelati con `Object.freeze()`, quindi non possono essere modificati. Usali come valori predefiniti invece di creare nuovi oggetti, per esempio `var opt = options || EMPTYOBJECT;`. Non scriverci mai dentro: in strict mode una scrittura genera un'eccezione.\n\nExample: Valori predefiniti\n```js\nfunction find(filter) {\n\tvar opt = filter || EMPTYOBJECT;\n\tvar tags = opt.tags || EMPTYARRAY;\n\treturn tags.length;\n}\n```\n\n### MAIN\n\nType: `property`\n\nUn oggetto globale per lo stato condiviso dell'applicazione.\n\nReturns: `Object`\n\nIl framework crea `MAIN` come oggetto vuoto e non lo usa. Conserva lì ciò che più file della tua applicazione condividono: impostazioni caricate all'avvio, connessioni aperte, contatori. È leggibile nelle view come `MAIN`.\n\nExample: Impostazioni condivise\n```js\n// definitions/settings.js\nMAIN.settings = MEMORIZE('settings');\n\n// a controller or an action\nvar title = MAIN.settings.title;\n```\n\n### REPO\n\nType: `property`\n\nUn oggetto globale per i dati condivisi, disponibile anche nelle view.\n\nReturns: `Object`\n\nUn oggetto vuoto che il framework crea all'avvio (è anche `F.repo`). Le view possono leggerlo come `REPO`, il che lo rende un buon posto per i dati che servono ai layout, per esempio un menu o i dati di contatto.\n\nExample: Dati per il layout\n```js\nREPO.menu = [{ name: 'Home', url: '/' }, { name: 'Contact', url: '/contact/' }];\n\n// views/layout.html\n// @{foreach m in REPO.menu}<a href=\"@{m.url}\">@{m.name}</a>@{end}\n```\n\n### FUNC\n\nType: `property`\n\nUn oggetto globale per le tue funzioni condivise.\n\nReturns: `Object`\n\nUn oggetto vuoto per le funzioni che più parti dell'applicazione usano. Definiscile in `/definitions/` così esistono prima della prima richiesta. Anche le view possono leggere `FUNC`.\n\nExample: Una funzione condivisa\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// anywhere\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nUn oggetto globale per dati di breve durata, svuotato ogni 5 minuti.\n\nReturns: `Object`\n\nOgni 5 minuti il framework sostituisce `TEMP` con un nuovo oggetto vuoto. Usalo per piccoli dati temporanei che possono sparire in qualsiasi momento, come token monouso o contatori di throttling. Leggilo sempre tramite la variabile globale (`TEMP.key`), non tramite un riferimento salvato, perché l'oggetto cambia.\n\nExample: Un token di breve durata\n```js\nvar token = GUID(20);\nTEMP[token] = { userid: user.id };\n\n// later\nvar data = TEMP[token];\nif (!data)\n\t$.invalid('The token has expired');\n```\n\n### MODS\n\nType: `property`\n\nI moduli caricati, per id.\n\nReturns: `Object`\n\nOgni file `.js` in `/modules/` viene caricato all'avvio e salvato in `MODS` sotto il suo `exports.id`, o sotto il nome del file quando non ne imposta uno. La sua funzione `install()`, se presente, viene chiamata dopo il caricamento. `MODS` è lo stesso oggetto di `F.modules` e può essere letto nelle view.\n\nExample: Un modulo\n```js\n// modules/pricing.js\nexports.id = 'pricing';\nexports.vat = function(price) {\n\treturn price * 1.2;\n};\n\n// anywhere\nvar total = MODS.pricing.vat(100);\n```\n\n### CACHE.set(key, value, [expire])\n\nType: `method`\n\nSalva un valore nella cache in memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave. |\n| `value` | `Object` | yes |  | Qualsiasi valore. |\n| `expire` | `String` | no | `'5 minutes'` | Per quanto tempo il valore è valido. |\n\nIl valore viene mantenuto nella memoria del processo finché non scade. `expire` è una durata nella forma accettata da `Date.add()` (`'30 seconds'`, `'5 minutes'`, `'1 hour'`, `'2 days'`). Il valore viene salvato così com'è, non copiato: se lo modifichi, cambia anche il valore in cache. Gli elementi scaduti vengono rimossi ogni minuto.\n\nExample: Mettere in cache un risultato\n```js\nCACHE.set('products', items, '2 minutes');\n```\n\n### CACHE.get(key, [def])\n\nType: `method`\n\nLegge un valore dalla cache in memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave. |\n| `def` | `Object` | no |  | Il valore restituito quando la chiave manca o è scaduta. |\n\nReturns: `Object`\n\nRestituisce il valore quando esiste e non è scaduto; altrimenti `def`. `CACHE.read()` è un alias.\n\nExample: Leggere o caricare\n```js\nvar items = CACHE.get('products');\nif (!items) {\n\titems = await DATA.find('nosql/products').promise($);\n\tCACHE.set('products', items, '2 minutes');\n}\n```\n\n### CACHE.remove(key)\n\nType: `method`\n\nRimuove un valore dalla cache in memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave. |\n\nChiamala quando i dati in cache cambiano, così la lettura successiva carica dati aggiornati.\n\nExample: Invalidare\n```js\nNOSQL('products').insert(model).callback(function() {\n\tCACHE.remove('products');\n});\n```\n\n### CACHE.reset([search])\n\nType: `method`\n\nRimuove molti valori, o tutti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | no |  | Una parte delle chiavi, o un pattern. |\n\nReturns: `Number` Il numero di chiavi rimosse.\n\nSenza `search`, l'intera cache viene svuotata. Con una stringa, viene rimossa ogni chiave che la contiene; con un'espressione regolare, ogni chiave che corrisponde. Restituisce il numero di chiavi rimosse (0 quando viene svuotata l'intera cache).\n\nExample: Rimuovere un gruppo\n```js\nCACHE.set('products_1', a);\nCACHE.set('products_2', b);\nCACHE.reset('products_');  // 2\nCACHE.reset(/^user_/);\nCACHE.reset();             // everything\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method`\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 l'ultima modifica e la scrittura. |\n| `skip` | `String|Array` | no |  | Chiavi non scritte nel file, come array o stringa separata da virgole. |\n\nReturns: `Object` I dati con `save()` e `set(key, value)`.\n\nLegge `databases/memorize_{name}.json` (o `databases/memorize.json` senza nome) e restituisce il suo contenuto come oggetto (un oggetto vuoto quando il file non esiste). L'oggetto riceve due funzioni: `save()` pianifica la scrittura dell'intero oggetto e `set(key, value)` assegna un valore e chiama `save()`. La scrittura avviene `delay` millisecondi dopo l'ultima chiamata, quindi molte modifiche producono una sola scrittura. `skip` elenca le chiavi che non vengono scritte. Gli argomenti `delay` e `skip` possono essere scambiati. Chiama `MEMORIZE()` una volta per nome e conserva l'oggetto; ogni chiamata rilegge il file.\n\nExample: Impostazioni che sopravvivono ai riavvii\n```js\nvar settings = MEMORIZE('settings', 'cache');\n\nsettings.set('title', 'My shop');\n\nsettings.counter = (settings.counter || 0) + 1;\nsettings.cache = {};      // not written\nsettings.save();\n```\n\n### BACKUP(filename, files, [callback], [filter])\n\nType: `method`\n\nRaccoglie file e directory in un unico file di archivio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Il file di archivio da creare (un file esistente viene sostituito). |\n| `files` | `String|Array` | yes |  | Una directory, o percorsi relativi alla root. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`; restituisci `true` per archiviare il percorso. |\n\nReturns: `Promise` Quando `callback` viene omessa.\n\nScrive un archivio di testo: una riga per directory e una riga per file, con il percorso e il contenuto compresso con gzip in base64. `files` è una directory (tutto ciò che contiene viene archiviato con percorsi relativi a essa) o un array di percorsi relativi alla root dell'applicazione (file e intere directory). I nomi che contengono `.git`, `.gitignore`, `.npmignore` o `.ds_store` vengono saltati. `filter(path, isdirectory)` riceve ogni percorso (che inizia con `/`) e lo esclude quando restituisce un valore falsy. `filename` può anche essere uno stream scrivibile. La callback riceve `{ filename, files, size }`; senza callback, la funzione restituisce una promise.\n\nExample: Backup degli upload\n```js\nvar meta = await BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), null, function(path, isdir) {\n\treturn isdir || !path.endsWith('.tmp');\n});\nprint(meta.files, 'files', meta.size, 'bytes');\n```\n\nExample: Percorsi selezionati\n```js\nawait BACKUP(PATH.temp('app.backup'), ['config', 'databases', 'public/uploads']);\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nEstrae un archivio creato da BACKUP().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | L'archivio. |\n| `target` | `String` | yes |  | La directory in cui estrarre. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nReturns: `Promise` Quando `callback` viene omessa.\n\nCrea le directory e i file dell'archivio dentro `target`. `filename` può anche essere uno stream leggibile. `filter(path, isdirectory)` viene chiamata per ogni elemento: per una directory, `false` ne salta la creazione; per un file, restituisci `false` per saltarlo, una stringa per scriverlo con quel percorso (relativo a `target`), o niente per mantenere il suo percorso. La callback riceve `{ files, size, path }`; senza callback, la funzione restituisce una promise.\n\nExample: Ripristinare\n```js\nvar meta = await RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'));\nprint('Restored', meta.files, 'files');\n```\n\nExample: Saltare file durante il percorso\n```js\nRESTORE(PATH.temp('app.backup'), PATH.root(), function(err) {\n\terr && print(err);\n}, function(path, isdir) {\n\tif (!isdir && path.startsWith('/config'))\n\t\treturn false;\n});\n```\n\n### PATH.root([path])\n\nType: `method`\n\nRestituisce la directory root dell'applicazione, o un percorso al suo interno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un percorso relativo. |\n\nReturns: `String` Un percorso assoluto.\n\nLa root è la directory dell'applicazione (dove viene eseguito lo script di avvio). Con `path`, restituisce la root unita a esso. Come le altre funzioni di directory di `PATH`, crea la directory la prima volta che viene chiamata con un percorso. `PATH.public()`, `PATH.private()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()`, `PATH.templates()`, `PATH.flowstreams()` e `PATH.scripts()` funzionano allo stesso modo per le loro directory.\n\nExample: Percorsi\n```js\nPATH.root();                 // '/www/app'\nPATH.root('config');         // '/www/app/config'\nPATH.private('report.pdf');  // '/www/app/private/report.pdf'\n```\n\n### PATH.databases([path])\n\nType: `method`\n\nRestituisce la directory dei database, o un percorso al suo interno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un percorso relativo. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory `/databases/` contiene i file dei database NoSQL, i file di `MEMORIZE()` e altri dati dell'applicazione. Viene creata la prima volta che richiedi un percorso al suo interno.\n\nExample: Un file di dati\n```js\nvar filename = PATH.databases('import.json');\nFs.writeFile(filename, JSON.stringify(data), NOOP);\n```\n\n### PATH.temp([path])\n\nType: `method`\n\nRestituisce la directory temporanea, o un percorso al suo interno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un percorso relativo. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory `/tmp/` contiene upload, file in cache e asset compilati. `PATH.tmp()` è un alias. Quando l'applicazione si avvia, il framework elimina lì i propri file temporanei (file `.js`, `.css`, `.html`, `.htm`, `.tmp` e `.upload`). Conserva i dati che devono durare in `/databases/`.\n\nExample: Un file temporaneo\n```js\nvar filename = PATH.temp(UID() + '.csv');\n```\n\n### PATH.exists(path, [callback])\n\nType: `method`\n\nVerifica se un file o una directory esiste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un percorso assoluto. |\n| `callback` | `Function` | no |  | `function(exists, size, isfile)`. |\n\nReturns: `Promise<Boolean>` Quando `callback` viene omessa.\n\nLa callback riceve tre argomenti: `exists`, la dimensione in byte e `isfile` (`true` per un file, `false` per una directory). Senza callback, la funzione restituisce una promise che si risolve con `exists`.\n\nExample: Verificare un file\n```js\nif (await PATH.exists(PATH.databases('settings.json')))\n\tprint('Settings found');\n\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isfile) {\n\tprint(exists, size, isfile);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nElimina uno o più file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|Array` | yes |  | Un percorso assoluto, o un array di percorsi. |\n| `callback` | `Function` | no |  | `function()`. |\n\nElimina i file uno dopo l'altro e poi chiama la callback. Gli errori (per esempio un file mancante) vengono ignorati.\n\nExample: Eliminare file\n```js\nPATH.unlink([PATH.temp('a.csv'), PATH.temp('b.csv')], function() {\n\tprint('Removed');\n});\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nElimina le directory con tutto il loro contenuto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|Array` | yes |  | Un percorso assoluto, o un array di percorsi. |\n| `callback` | `Function` | no |  | `function()`. |\n\nPer ogni directory, vengono eliminati tutti i file, poi le sottodirectory a partire dalla più profonda, poi la directory stessa. Quindi viene chiamata la callback.\n\nExample: Eliminare una directory\n```js\nPATH.rmdir(PATH.temp('export'), function() {\n\tprint('Directory removed');\n});\n```\n\n### Total.FsPromises\n\nType: `property`\n\nIl modulo Node.js `node:fs/promises`.\n\nReturns: `Object` Il modulo `node:fs/promises`.\n\nLa versione con promise delle funzioni del file system di Node.js, caricata dal framework. `F.FsPromises` è lo stesso oggetto, e `Total.Fs` (`F.Fs`) è il modulo `node:fs`.\n\nExample: Leggere ed elencare\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\nvar files = await Total.FsPromises.readdir(PATH.public());\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nConverte qualsiasi valore in un numero.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore da convertire. |\n| `def` | `Number` | no | `0` | Il risultato per valori vuoti o non validi. |\n\nReturns: `Number`\n\nUn numero viene restituito così com'è. Una stringa viene ripulita dagli spazi e convertita con l'operatore unario `+`; gli altri valori vengono prima convertiti in stringa. `null`, `undefined`, una stringa vuota e un valore che non è un numero restituiscono `def` (0 per impostazione predefinita). Il risultato non viene arrotondato (`'1.5'` dà `1.5`). `U.parseFloat(value, [def])` funziona allo stesso modo e accetta anche la virgola come separatore decimale (`'12,50'` dà `12.5`).\n\nExample: Valori della query\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\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 |  | Il valore da convertire. |\n| `def` | `Boolean` | no | `false` | Il risultato per `null` o `undefined`. |\n\nReturns: `Boolean`\n\nUn booleano viene restituito così com'è; un numero è `true` quando è maggiore di 0; le stringhe `true`, `1` e `on` (maiuscole o minuscole) sono `true` e ogni altra stringa è `false`. `null` e `undefined` restituiscono `def` (`false` per impostazione predefinita).\n\nExample: Una checkbox\n```js\nvar newsletter = U.parseBoolean(this.body.newsletter); // 'on' -> true\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nLegge un valore annidato tramite un percorso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'oggetto da leggere. |\n| `path` | `String` | yes |  | Il percorso. |\n\nReturns: `Object` Il valore, oppure `undefined`.\n\nIl percorso usa punti e parentesi quadre: `a.b.c`, `items[0].name`. Quando manca una parte del percorso, restituisce `undefined` invece di generare un'eccezione. I percorsi con spazi, parentesi o parole chiave come `__proto__` e `constructor` vengono rifiutati (`undefined`). I lettori compilati vengono messi in cache per percorso.\n\nExample: Valori annidati\n```js\nvar data = { user: { address: { city: 'Bratislava' } }, items: [{ name: 'A' }] };\nU.get(data, 'user.address.city');  // 'Bratislava'\nU.get(data, 'items[0].name');      // 'A'\nU.get(data, 'user.phone.number');  // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nScrive un valore annidato tramite un percorso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'oggetto in cui scrivere. |\n| `path` | `String` | yes |  | Il percorso. |\n| `value` | `Object` | yes |  | Il valore. |\n\nReturns: `Object` Il valore scritto.\n\nGli oggetti mancanti lungo il percorso vengono creati. Un percorso che termina con `[]` aggiunge il valore all'array, e un indice crea un array con degli oggetti al suo interno (`items[0].name`). I percorsi con spazi, parentesi o parole chiave come `__proto__` e `constructor` vengono rifiutati: non viene scritto nulla. Restituisce il valore.\n\nExample: Costruire un oggetto\n```js\nvar model = {};\nU.set(model, 'address.city', 'Bratislava');\nU.set(model, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\nExample: Percorso con un indice\n```js\nvar model = {};\nU.set(model, 'items[0].name', 'Pen');\n// { items: [{ name: 'Pen' }] }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nCopia le chiavi di source in target.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | L'oggetto in cui scrivere. |\n| `source` | `Object` | yes |  | L'oggetto da leggere. |\n| `rewrite` | `Boolean` | no | `true` | `false` mantiene i valori esistenti. |\n\nReturns: `Object` L'oggetto di destinazione.\n\nOgni chiave di `source` viene clonata in `target`. Con `rewrite` impostato a `false`, le chiavi che esistono già in `target` non vengono modificate: è così che si impostano i valori predefiniti. Restituisce `target`.\n\nExample: Valori predefiniti\n```js\nvar options = { limit: 50 };\nU.extend(options, { limit: 10, sort: 'name' }, false);\n// { limit: 50, sort: 'name' }\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nRestituisce una funzione di confronto per Array.sort().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Per esempio `name` o `price_desc,name`. |\n\nReturns: `Function` `function(a, b)` per `Array.prototype.sort()`.\n\n`sort` è un elenco di chiavi separate da virgole; aggiungi `_desc` per l'ordine decrescente (`_asc` è il predefinito). Le chiavi annidate usano i punti (`address.city`). Il tipo di ogni chiave viene letto dal primo valore non vuoto la prima volta che l'espressione viene usata, e viene mantenuto per gli usi successivi della stessa espressione: le stringhe vengono confrontate tenendo conto dei segni diacritici, numeri, booleani e date per valore.\n\nExample: Ordinare i prodotti\n```js\nproducts.sort(U.sortcomparer('price_desc,name'));\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nRestituisce un intero casuale in un intervallo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | Il valore più grande. |\n| `min` | `Number` | no | `0` | Il valore più piccolo. |\n\nReturns: `Number`\n\nRestituisce un intero tra `min` e `max`, entrambi inclusi.\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 |  | Il numero di caratteri. |\n\nReturns: `String`\n\nI caratteri sono `0-9`, `A-Z` e `a-z`. `U.random_string(length)` usa solo lettere e `U.random_number(length)` solo cifre (restituite come stringa che non inizia con 0). Questi valori provengono da `Math.random()`: non usarli come password o token di sicurezza.\n\nExample: Stringhe casuali\n```js\nU.random_text(8);    // 'yb7JVb2a'\nU.random_string(6);  // 'HNXkTk'\nU.random_number(6);  // '825174'\n```\n\n### U.convert62(number)\n\nType: `method`\n\nConverte un numero in una stringa in base 62.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | Un numero non negativo. |\n\nReturns: `String`\n\nLe cifre sono `0-9`, `A-Z` e `a-z`, in questo ordine. Il numero viene prima arrotondato per difetto. `U.from62(value)` riconverte la stringa nel numero. Usala per codici brevi ricavati da id numerici.\n\nExample: Codici brevi\n```js\nvar code = U.convert62(123456);  // 'W7E'\nvar id = U.from62(code);         // 123456\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nRestituisce l'estensione di un nome di file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un nome di file, un percorso o un URL. |\n| `raw` | `Boolean` | no | `false` | `true` mantiene le maiuscole originali. |\n\nReturns: `String`\n\nRestituisce la parte dopo l'ultimo punto, senza il punto e in minuscolo (con `raw`, con le maiuscole originali). Una query string dopo `?` viene ignorata. Restituisce una stringa vuota quando il nome non ha estensione.\n\nExample: Estensioni\n```js\nU.getExtension('/img/Photo.JPG');      // 'jpg'\nU.getExtension('/files/a.pdf?v=1');    // 'pdf'\nU.getExtension('README');              // ''\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 |  | Un percorso o un URL. |\n\nReturns: `String`\n\nRestituisce il nome del file (o l'ultima directory) di un percorso con separatori `/` o `\\\\`. Un separatore finale viene ignorato.\n\nExample: Nomi di file\n```js\nU.getName('/www/app/public/logo.png');  // 'logo.png'\nU.getName('/www/app/public/');          // 'public'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nRestituisce il tipo MIME per un'estensione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Un'estensione, ad es. `png` o `.png`. |\n\nReturns: `String`\n\nL'estensione può iniziare con un punto. Le estensioni sconosciute restituiscono `application/octet-stream`. `U.getExtensionFromContentType(type)` fa l'inverso e restituisce la prima estensione con quel tipo (o `undefined`). L'intera tabella è `U.contentTypes`.\n\nExample: Content type\n```js\nU.getContentType('png');                     // 'image/png'\nU.getContentType('.json');                   // 'application/json'\nU.getExtensionFromContentType('image/png');  // 'png'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nCodifica testo o un buffer in base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | I dati da codificare. |\n\nReturns: `String`\n\nUn buffer viene codificato direttamente; gli altri valori vengono convertiti in stringa e codificati come UTF-8. `U.atob(value)` decodifica il base64 in una stringa UTF-8.\n\nExample: Base64\n```js\nvar encoded = U.btoa('Hello');   // 'SGVsbG8='\nvar text = U.atob(encoded);      // 'Hello'\n```\n\n### U.validhost(host)\n\nType: `method`\n\nVerifica che un nome host sia ASCII semplice e che un indirizzo IP sia nella sua forma canonica.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | Il nome host o l'indirizzo IP. |\n\nReturns: `Boolean` `true` per un host valido.\n\nRestituisce `false` per un valore che non è una stringa, è vuoto o contiene un carattere fuori dall'intervallo ASCII visibile (spazi, byte NUL, lettere accentate). Un valore fatto solo di numeri e punti (o di numeri esadecimali) deve essere un indirizzo IPv4 canonico: `127.0.0.1` è valido, `127.1`, `0127.0.0.1`, `0x7f.0.0.1` e `2130706433` non lo sono. Gli altri valori ASCII, compresi gli indirizzi IPv6, restituiscono `true`; la funzione non controlla la sintassi completa di un nome host. Converti prima un nome internazionale con `U.tohost()`.\n\nExample: Controllare gli host\n```js\nU.validhost('example.com');     // true\nU.validhost('127.0.0.1');       // true\nU.validhost('127.1');           // false\nU.validhost('0x7f.0.0.1');      // false\nU.validhost('münchen.de');      // false\nU.validhost('evil.example\\0.trusted.example'); // false\n```\n\n### U.tohost(host)\n\nType: `method`\n\nConverte un nome host nella sua forma ASCII canonica.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | Il nome host o l'indirizzo IP. |\n\nReturns: `String` L'host canonico, oppure una stringa vuota.\n\nConverte l'host con il parser di URL di Node.js: le lettere diventano minuscole, un nome internazionale diventa punycode e un indirizzo IPv4 in un'altra notazione diventa la forma puntata (uno `0` iniziale indica un numero ottale, `0x` un numero esadecimale). Il risultato viene poi controllato con `U.validhost()`. Un valore che contiene `:` (un indirizzo IPv6) viene solo controllato. Restituisce una stringa vuota quando l'host non è valido, quindi verifica il risultato prima di usarlo.\n\nExample: Convertire gli host\n```js\nU.tohost('münchen.de');      // 'xn--mnchen-3ya.de'\nU.tohost('EXAMPLE.com');     // 'example.com'\nU.tohost('127.1');           // '127.0.0.1'\nU.tohost('0x7f.0.0.1');      // '127.0.0.1'\nU.tohost('evil.example\\0.trusted.example'); // ''\n```\n\nExample: Validare l'input\n```js\nfunction host(value) {\n\tvar host = U.tohost(value);\n\tif (!host)\n\t\tthrow new Error('Invalid hostname');\n\treturn host;\n}\n```\n\n### U.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` | no |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Millisecondi prima che l'attesa fallisca. |\n| `interval` | `Number` | no | `500` | Millisecondi tra un controllo e l'altro. |\n\nReturns: `Promise` Quando `callback` viene omessa.\n\n`validator` viene chiamata subito e poi ogni `interval` millisecondi finché non restituisce `true`; a quel punto la callback riceve `(null, true)`. Quando scade prima `timeout`, la callback riceve un `Error('Timeout')`. Senza callback, la funzione restituisce una promise che si risolve o viene rifiutata allo stesso modo.\n\nExample: Attendere una connessione\n```js\nawait U.wait(() => MAIN.db != null, null, 10000, 200);\nprint('Database ready');\n```\n\n### U.resolve(url, callback, [param])\n\nType: `method`\n\nRisolve l'host di un URL in indirizzi IPv4, con una cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Un URL assoluto. |\n| `callback` | `Function` | yes |  | `function(err, uri, param, addresses)`. |\n| `param` | `Any` | no |  | Un valore passato alla callback. |\n\nInterpreta `url`, controlla il suo nome host con `U.validhost()` e chiede ai server DNS i suoi indirizzi IPv4 (`dns.resolve4()`, quindi il file hosts non viene usato). La callback riceve `(err, uri, param, addresses)`: `uri` è l'URL interpretato con `host` impostato al primo indirizzo, `param` è il terzo argomento e `addresses` l'intero elenco. Gli indirizzi restano in cache per tutta la vita del processo; una ricerca fallita viene ritentata una volta prima che venga passato `err`.\n\nUna stringa che non è un URL dà `TypeError: Invalid URL`, e un nome host non valido dà l'errore `Invalid hostname` senza una query DNS. Per gli URL `http` e `https` il parser di URL converte già l'host; per gli altri schemi un indirizzo non canonico come `tcp://127.1/` dà `Invalid hostname`. `REQUEST()` usa questa funzione con l'opzione `resolve: true`, e `RESTBuilder` per impostazione predefinita.\n\nExample: Risolvere un host\n```js\nU.resolve('https://example.com/api/', function(err, uri, param, addresses) {\n\tif (err)\n\t\tconsole.log(err.message || err.code);\n\telse\n\t\tconsole.log(uri.hostname, addresses);\n});\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nDivide un flusso di dati in parti tramite delimitatori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | L'inizio di una parte, o il separatore. |\n| `end` | `String|Buffer` | no |  | La fine di una parte. |\n| `callback` | `Function` | yes |  | `function(value, index)`; restituisci `false` per interrompere. |\n| `skip` | `Number` | no | `0` | Il numero di parti iniziali da ignorare. |\n| `stream` | `Stream` | no |  | Uno stream il cui evento `end` elabora il resto. |\n\nReturns: `Function` `function(chunk)`.\n\nRestituisce una funzione da chiamare con ogni chunk (un buffer), per esempio come handler `data` di uno stream. Con `beg` e `end`, la callback riceve ogni parte che inizia con `beg` e termina con `end`, entrambi inclusi (per esempio un `<item>...</item>` di un grande file XML). Con solo `beg`, `beg` è un separatore e la callback riceve ogni parte fino a esso incluso (per esempio righe con `\\n`). La callback riceve `(value, index)` con il valore come stringa; restituire `false` interrompe il parsing. `skip` ignora altrettante parti iniziali. Con `stream`, i dati rimanenti vengono elaborati quando lo stream termina. `U.streamer2()` accetta gli stessi argomenti e passa buffer invece di stringhe.\n\nExample: Leggere un grande file XML\n```js\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\nstream.on('data', U.streamer('<product>', '</product>', function(value, index) {\n\tvar product = value.parseXML();\n\tprint(index, product);\n}));\n```\n\nExample: Righe di un file CSV\n```js\nvar stream = Fs.createReadStream(filename);\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tvar cols = line.trim().split(';');\n}, 1, stream));  // skips the header line\n```\n\n### U.connect(options, [callback])\n\nType: `method`\n\nApre una connessione TCP o TLS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | `{ host, port, secure, tls, timeout }` e, con `secure`, altre opzioni di `tls.connect()`. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nSi connette a `options.host` e `options.port` e chiama `callback(err, meta)` quando la connessione è aperta. Prima l'host viene convertito con `U.tohost()`, quindi un nome internazionale viene inviato come punycode e `127.1` come `127.0.0.1`; un host non valido dà l'errore `Invalid hostname` e non viene aperta nessuna connessione. Con `secure: true` la connessione usa TLS fin dall'inizio e le altre opzioni (`servername`, `rejectUnauthorized`, `ca` ...) vanno a `tls.connect()`. Con `tls` la connessione inizia come TCP semplice e passa a TLS appena è aperta: `tls: true` usa le opzioni predefinite di `tls.connect()`, un oggetto passa le sue opzioni (`servername`, `rejectUnauthorized`, `ca` ...). Con `timeout` (in millisecondi) una connessione che non si apre in tempo dà l'errore `Timeout`.\n\n`meta` ha `socket` (il socket di Node.js), `opt` (le opzioni con l'host convertito), `write(data)`, `ondata(fn)` per i chunk ricevuti e `close()` (anche `destroy()`). `LDAP()` si connette con questa funzione.\n\nExample: Leggere il saluto di un server\n```js\nU.connect({ host: 'mail.example.com', port: 25, timeout: 5000 }, function(err, meta) {\n\tif (err) {\n\t\tconsole.log(err.message);\n\t\treturn;\n\t}\n\tmeta.ondata(function(chunk) {\n\t\tconsole.log(chunk.toString());\n\t\tmeta.close();\n\t});\n});\n```\n\nExample: Passare a TLS\n```js\nU.connect({ host: 'mail.example.com', port: 465, tls: { servername: 'mail.example.com' } }, function(err, meta) {\n\tif (!err)\n\t\tconsole.log(meta.socket.encrypted); // true\n});\n```\n\n### U.ls(path, [callback], [filter])\n\nType: `method`\n\nElenca ricorsivamente i file e le directory di una directory.\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 |  | Il filtro. |\n\nReturns: `Promise` `{ files, directories }` quando `callback` viene omessa.\n\nLa callback riceve due array di percorsi assoluti: `files` e `directories` (le directory terminano con il separatore di percorso). `filter` può essere una stringa (percorsi che la contengono, senza distinzione tra maiuscole e minuscole), un'espressione regolare o una funzione `(path, isdirectory)` che restituisce `true` per mantenere l'elemento; i filtri con stringa ed espressione regolare si applicano solo ai file. Una directory scartata dal filtro non viene esplorata. Senza callback, la funzione restituisce una promise con `{ files, directories }`. `U.ls2()` accetta gli stessi argomenti e restituisce i file come oggetti `{ filename, stats }` con le `fs.Stats` di ogni file.\n\nExample: Trovare file JSON\n```js\nU.ls(PATH.databases(), function(files, directories) {\n\tprint(files);\n}, /\\.json$/);\n```\n\nExample: Dimensioni con ls2\n```js\nvar result = await U.ls2(PATH.public('uploads'));\nvar size = 0;\nfor (var file of result.files)\n\tsize += file.stats.size;\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nSalva un elenco di grandi dimensioni in file temporanei, a pagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome univoco, usato per i nomi dei file. |\n| `max` | `Number` | no | `50` | Elementi per pagina. |\n\nReturns: `Chunker`\n\nUn chunker raccoglie gli elementi con `write(item)` (alias `append()`); ogni `max` elementi vengono scritti in un file `tmp/{name}-{index}.chunker` (compresso con deflate quando `compress` è `true`, il predefinito) così la memoria resta ridotta. Chiama `end()` per scrivere il resto. Poi `each(onitem, [ondone])` legge le pagine in ordine: `onitem(items, next, index)` riceve una pagina e chiama `next()` per continuare, e `percentage` indica a che punto è la lettura. `read(index, callback)` legge una pagina. Con `autoremove` (`true` per impostazione predefinita), ogni file viene eliminato dopo la lettura; `clear()` elimina tutti i file e `destroy()` rilascia anche il chunker. Le proprietà `count` e `pages` contengono il numero di elementi e di pagine.\n\nExample: Elaborare un grande export\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var row of rows)\n\tchunker.write(row);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tprint('Page', index, chunker.percentage + '%');\n\tsend(items, next);\n}, function() {\n\tprint('Done', chunker.count, 'items');\n});\n```\n\n### chunker.load([callback])\n\nType: `method` · Since: `0.0.16`\n\nTrova le pagine che un chunker precedente con lo stesso nome ha lasciato sul disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `Promise` Quando `callback` viene omessa.\n\nConta i file del chunker nella directory temporanea e imposta l'indice interno delle pagine, così `each()` e `read()` possono leggere le pagine che un'istanza precedente ha scritto e non letto (per esempio prima di un riavvio). Crea il chunker con lo stesso `name`. La callback riceve `(null, count)`; senza callback, la funzione restituisce una promise che si risolve quando il conteggio è terminato.\n\nExample: Continuare un chunker\n```js\nvar chunker = U.chunker('export');\nawait chunker.load();\nchunker.each(function(items, next) {\n\tsend(items, next);\n});\n```\n\n### new U.EventEmitter2() / U.EventEmitter2(obj)\n\nType: `class`\n\nUn piccolo emettitore di eventi.\n\nReturns: `EventEmitter2`\n\nUn oggetto con `on(name, fn)`, `once(name, fn)`, `off(name, [fn])` e `emit(name, ...args)` (fino a sette argomenti). `off(name)` senza funzione rimuove tutti gli handler dell'evento. Gli handler vengono eseguiti con l'emitter come `this`. Chiamata con un oggetto (`U.EventEmitter2(obj)`), aggiunge questi metodi a quell'oggetto, a meno che non abbia già `emit`, e lo restituisce.\n\nExample: Eventi sul tuo oggetto\n```js\nvar Cart = {};\nU.EventEmitter2(Cart);\n\nCart.on('add', function(item) {\n\tprint('Added', item.name);\n});\n\nCart.emit('add', { name: 'Shoes' });\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nOffusca una stringa con una chiave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il testo. |\n| `key` | `String` | yes |  | La chiave. |\n| `encode` | `String` | no | `'base64'` | La codifica di output, o `buffer`. |\n\nReturns: `String|Buffer`\n\nCodifica la stringa con la chiave e una maschera casuale di 4 byte e la restituisce in base64 (o nella codifica che imposti; `buffer` restituisce un buffer). Lo stesso input dà ogni volta un output diverso. `U.decrypt_data(value, key, [encode])` restituisce la stringa originale, o `null` per un input non valido. È un'offuscazione leggera, non una crittografia forte; per i dati sensibili usa `ENCRYPT()` (vedi [Cifratura](../../guides/encryption/)).\n\nExample: Andata e ritorno\n```js\nvar data = U.encrypt_data('hello', 'mykey');\nvar text = U.decrypt_data(data, 'mykey');  // 'hello'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nFirma un identificatore in modo che non possa essere modificato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | L'identificatore. |\n| `key` | `String` | no | `CONF.secret` | La chiave. |\n\nReturns: `String`\n\nRestituisce l'identificatore preceduto da un checksum, ricavato dal valore, dalla chiave e da `CONF.secret_uid`. `U.decrypt_uid(value, [key])` lo verifica e restituisce l'identificatore originale (un numero quando l'originale era un numero) o `null` quando il valore è stato modificato. L'identificatore stesso resta leggibile. Senza `key`, viene usato `CONF.secret`.\n\nExample: Id firmato in un link\n```js\nvar signed = U.encrypt_uid(123, 'mykey');   // 'n...x123', the checksum depends on CONF.secret_uid\nU.decrypt_uid(signed, 'mykey');             // 123\nU.decrypt_uid('n2v55u4jx124', 'mykey');     // null\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifica JavaScript; U.minify_css() e U.minify_html() fanno lo stesso per CSS e HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il codice sorgente. |\n\nReturns: `String`\n\nSono i minificatori che il framework usa per i file statici e le view. Accettano una stringa e restituiscono la stringa minificata.\n\nExample: Minificare\n```js\nU.minify_js('var a = 1 ;  // note\\n');  // 'var a=1;'\nU.minify_css('a { color : red ; }');     // 'a{color:red}'\nU.minify_html(html);\n```\n\n### U.aistreamer(online, [onmessage])\n\nType: `method` · Since: `0.0.16`\n\nInterpreta una risposta in streaming di un'API di chat AI in righe di testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `online` | `Function` | yes |  | `function(line)`, chiamata per ogni riga di testo completa. |\n| `onmessage` | `Function` | no |  | `function(message)`, chiamata per ogni messaggio JSON interpretato. |\n\nReturns: `Function` `function(chunk)`.\n\nRestituisce una funzione che chiami con ogni chunk (un buffer) di una risposta in streaming. Legge messaggi JSON riga per riga in due formati: server-sent event con `data: {...}` (completion di OpenAI, dove il testo è in `choices[0].delta.content` e `data: [DONE]` lo termina) e semplici righe JSON (Ollama, dove il testo è in `message.content` e `done` lo termina). Il testo viene raccolto e `online(line)` viene chiamata per ogni riga completa. `onmessage(obj)`, quando la imposti, riceve ogni messaggio interpretato; in questo caso le date JSON vengono interpretate come date.\n\nExample: Stampare una risposta riga per riga\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nMette in cache il risultato di un'operazione in un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Identificatore dell'elemento in cache. |\n| `expire` | `String` | yes |  | Per quanto tempo il file è valido, per esempio `'5 minutes'`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `maker` | `Function` | yes |  | `function(next, id)` che crea il valore. |\n| `encoding` | `String` | no | `json` | `json` o una codifica di file come `utf8`. |\n\nCerca il file di `id` in `tmp/`. Quando esiste ed è più recente di `expire`, il suo contenuto va a `callback(err, response)`. Altrimenti viene eseguito `maker(next, id)`; `next(err, response, [load])` scrive la risposta nel file e chiama `callback`, a meno che `load` sia `false`. Con la codifica `json` il valore viene salvato come JSON e riletto con il parsing; qualsiasi altra codifica salva e legge il contenuto grezzo.\n\nExample: Mettere in cache un elenco remoto\n```js\nFILECACHE('currencies', '1 day', function(err, response) {\n\tMAIN.currencies = response;\n}, function(next) {\n\tREQUEST({ url: 'https://example.com/rates.json', callback: function(err, response) {\n\t\tnext(err, err ? null : response.body.parseJSON());\n\t}});\n});\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID()","since":"","deprecated":false},{"type":"method","name":"GUID([length])","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"HASH(value, [type])","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"CLONE(obj, [skip], [nofunctions])","signature":"CLONE(obj, [skip], [nofunctions])","since":"","deprecated":false},{"type":"method","name":"COPY(source, [target], [all])","signature":"COPY(source, [target], [all])","since":"","deprecated":false},{"type":"method","name":"DIFFARR(prop, db, form)","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"QUERIFY([url], obj)","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"PROMISIFY(fn, [a], [b], [c])","signature":"PROMISIFY(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"ERROR([name])","signature":"ERROR([name])","since":"","deprecated":false},{"type":"method","name":"print()","signature":"print(...values)","since":"","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"NOOP","signature":"NOOP","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","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":"CACHE.set(key, value, [expire])","signature":"CACHE.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"CACHE.get(key, [def])","signature":"CACHE.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"CACHE.remove(key)","signature":"CACHE.remove(key)","since":"","deprecated":false},{"type":"method","name":"CACHE.reset([search])","signature":"CACHE.reset([search])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE([name], [delay], [skip])","signature":"MEMORIZE([name], [delay], [skip])","since":"","deprecated":false},{"type":"method","name":"BACKUP(filename, files, [callback], [filter])","signature":"BACKUP(filename, files, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE(filename, target, [callback], [filter])","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"PATH.root([path])","signature":"PATH.root([path])","since":"","deprecated":false},{"type":"method","name":"PATH.databases([path])","signature":"PATH.databases([path])","since":"","deprecated":false},{"type":"method","name":"PATH.temp([path])","signature":"PATH.temp([path])","since":"","deprecated":false},{"type":"method","name":"PATH.exists(path, [callback])","signature":"PATH.exists(path, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink(files, [callback])","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir(directories, [callback])","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"property","name":"Total.FsPromises","signature":"Total.FsPromises","since":"","deprecated":false},{"type":"method","name":"U.parseInt(value, [def])","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseBoolean(value, [def])","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.get(obj, path)","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set(obj, path, value)","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.extend(target, source, [rewrite])","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer(sort)","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.random([max], [min])","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text(length)","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.convert62(number)","signature":"U.convert62(number)","since":"","deprecated":false},{"type":"method","name":"U.getExtension(filename, [raw])","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName(path)","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType(ext)","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.btoa(value)","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.validhost(host)","signature":"U.validhost(host)","since":"","deprecated":false},{"type":"method","name":"U.tohost(host)","signature":"U.tohost(host)","since":"","deprecated":false},{"type":"method","name":"U.wait(validator, [callback], [timeout], [interval])","signature":"U.wait(validator, [callback], [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"U.resolve(url, callback, [param])","signature":"U.resolve(url, callback, [param])","since":"","deprecated":false},{"type":"method","name":"U.streamer(beg, [end], callback, [skip], [stream])","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.connect(options, [callback])","signature":"U.connect(options, [callback])","since":"","deprecated":false},{"type":"method","name":"U.ls(path, [callback], [filter])","signature":"U.ls(path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"U.chunker(name, [max])","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.load([callback])","signature":"chunker.load([callback])","since":"0.0.16","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2() / U.EventEmitter2(obj)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_data(value, key, [encode])","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid(value, [key])","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.minify_js(value)","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.aistreamer(online, [onmessage])","signature":"U.aistreamer(online, [onmessage])","since":"0.0.16","deprecated":false},{"type":"method","name":"FILECACHE(id, expire, callback, maker, [encoding])","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JafwwLBgx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/utilities/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Nástroje","summary":"Funkcie U/Utils, globálne pomocné funkcie (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), zdieľané objekty, CACHE, MEMORIZE, BACKUP, RESTORE a PATH.","markdown":"---\ntitle: \"Nástroje\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/utilities/\nupdated: 2026-11-18T16:57:29.576Z\n---\n\n# Nástroje\n\n> Funkcie U/Utils, globálne pomocné funkcie (UID, GUID, HASH, CLONE, COPY, DIFFARR, QUERIFY, PROMISIFY), zdieľané objekty, CACHE, MEMORIZE, BACKUP, RESTORE a PATH.\n\nTáto stránka uvádza globálne pomocné funkcie, zdieľané globálne objekty, pamäťovú `CACHE`, funkcie `PATH` a funkcie modulu `U` (`Utils`), ktoré aplikácie používajú. Návod [Pomocné funkcie](../../guides/utilities/) vysvetľuje, ako spolu súvisia, aj s príkladmi. Metódy pridané do `String`, `Number`, `Date` a `Array` nájdeš v [Prototypoch](../prototypes/).\n\n## API\n\n### U\n\nType: `property`\n\nModul Utils ako globálny objekt.\n\nReturns: `Object` Modul Utils.\n\nVšetky funkcie `utils.js` sú dostupné cez `U` a jeho alias `Utils` (oba ukazujú na ten istý objekt). Táto stránka dokumentuje funkcie, ktoré používajú aplikácie; ostatné používa samotný framework.\n\nExample: Použitie pomocnej funkcie\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\nvar same = Utils === U;           // true\n```\n\n### UID()\n\nType: `method`\n\nVráti nový jedinečný identifikátor.\n\nReturns: `String` Napríklad `JacVuE1cn61f`.\n\nIdentifikátor je krátky reťazec písmen a číslic: časová pečiatka v základe 62 (v desatinách sekundy), interné počítadlo, náhodný znak zvolený pri štarte (mení sa každú minútu), dĺžka časovej časti, paritná číslica a písmeno `f`. Neskôr vytvorené identifikátory sa vo väčšine prípadov zoradia za skoršie. Validátor `uid` frameworku (`DEF.validators.uid`) ich akceptuje.\n\nExample: Nový záznam\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\nNOSQL('products').insert(model);\n```\n\n### GUID([length])\n\nType: `method`\n\nVráti reťazec podobný UUID alebo náhodný reťazec zadanej dĺžky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Počet znakov. Vynechaj ho pre formát podobný UUID. |\n\nReturns: `String`\n\nBez `length` vráti reťazec v tvare `xxxxxxxx-xxxx-Nxxx-Yxxx-xxxxxxxxxxxx` (36 znakov) zostavený z aktuálneho času a náhodných šestnástkových číslic. S `length` vráti toľko náhodných znakov z `0-9` a `a-z`.\n\nExample: Tokeny\n```js\nvar guid = GUID();       // '1a1e0561-0561-4c86-8eaf-d9a327a65943'\nvar token = GUID(30);    // 30 random characters\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, z ktorého sa vytvorí hash. |\n| `type` | `String` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32` alebo `crc32unsigned`. |\n\nReturns: `Number|String` Číslo bez typu, šestnástkový reťazec pre typy md5/sha.\n\nBez `type` vráti 32-bitové číslo bez znamienka vypočítané z reťazca (rýchle, nie kryptografické). S typom vráti hash ako šestnástkový reťazec (`md5`, `sha1`, `sha256`, `sha512`) alebo číslo CRC32 (`crc32`, `crc32unsigned`). `value` musí byť reťazec; čísla najprv preveď pomocou `+ ''`.\n\nExample: Hashe\n```js\nHASH('abc');            // 96354\nHASH('abc', 'md5');     // '900150983cd24fb0d6963f7d28e17f72'\nHASH(email, 'sha256');\n```\n\n### CLONE(obj, [skip], [nofunctions])\n\nType: `method`\n\nVytvorí hlbokú kópiu objektu alebo poľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array` | yes |  | Hodnota na skopírovanie. Ostatné hodnoty sa vrátia nezmenené. |\n| `skip` | `Object` | no |  | Kľúče na vynechanie, napr. `{ password: 1 }`. |\n| `nofunctions` | `Boolean` | no | `false` | `true` vynechá funkcie. |\n\nReturns: `Object|Array` Kópia.\n\nVnorené objekty a polia sa skopírujú, buffery vo vlastnostiach objektov sa zduplikujú a dátumy, chyby a iné hodnoty, ktoré nie sú objektmi, zostanú tak, ako sú. `skip` je objekt, ktorého kľúče sa na každej úrovni vynechajú z kópie. S `nofunctions` sa vynechajú aj vlastnosti, ktoré obsahujú funkcie.\n\nExample: Kópia bez kľúča\n```js\nvar user = { id: 'abc', name: 'Peter', password: 'secret', address: { city: 'Bratislava' } };\nvar safe = CLONE(user, { password: 1 });\nsafe.address.city = 'Prague';  // user.address.city is still 'Bratislava'\n```\n\n### COPY(source, [target], [all])\n\nType: `method`\n\nSkopíruje kľúče jedného objektu do iného.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Objekt, z ktorého sa číta. |\n| `target` | `Object` | no |  | Objekt, do ktorého sa zapisuje. |\n| `all` | `Boolean` | no | `true` | `false` zapíše len kľúče, ktoré `target` už má. |\n\nReturns: `Object` Cieľ (alebo nová kópia).\n\nKaždá hodnota zo `source` sa naklonuje a zapíše do `target`. Keď je `all` nastavené na `false`, zapíšu sa len kľúče, ktoré sú v `target` už definované, takže `target` funguje ako zoznam povolených polí. Bez `target` vráti hlbokú kópiu `source`.\n\nExample: Povolené polia\n```js\nvar allowed = { name: '', email: '' };\nCOPY(this.body, allowed, false);\n// allowed contains only name and email from the body\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nPorovná dve polia objektov podľa jednej vlastnosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | Kľúč, ktorý identifikuje položku, napr. `id`. |\n| `db` | `Array` | yes |  | Aktuálne položky (napríklad z databázy). |\n| `form` | `Array` | yes |  | Nové položky (napríklad z formulára). |\n\nReturns: `Object` `{ add: Array, upd: Array, rem: Array }`.\n\nPoložky sa spárujú, keď sú ich hodnoty `prop` rovnaké (`==`). Výsledok má tri polia: `add` obsahuje položky z `form`, ktoré nie sú v `db`, `upd` obsahuje dvojice `{ db, form }` spárovaných položiek a `rem` obsahuje hodnoty `prop` položiek z `db`, ktoré nie sú vo `form`.\n\nExample: Synchronizácia položiek\n```js\nvar diff = DIFFARR('id', current, model.items);\n\nfor (var item of diff.add)\n\tNOSQL('items').insert(item);\n\nfor (var pair of diff.upd)\n\tNOSQL('items').modify(pair.form).where('id', pair.db.id);\n\nfor (var id of diff.rem)\n\tNOSQL('items').remove().where('id', id);\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nZostaví query string z objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | URL, voliteľne s metódou na začiatku. |\n| `obj` | `Object` | yes |  | Hodnoty. |\n\nReturns: `String`\n\nKľúče aj hodnoty sa zakódujú pre URL. Hodnoty `null`, `undefined` a prázdne hodnoty sa preskočia, dátumy sa zapíšu ako reťazce ISO a polia sa spoja čiarkami. Bez `url` výsledok začína znakom `?` (alebo je to prázdny reťazec, keď nič nezostane). S `url` sa query string pripojí pomocou `?` alebo `&`; URL môže začínať HTTP metódou (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `API`) a medzerou, tak ako ju prijímajú `REQUEST()` a `AJAX()`. Funkcia je dostupná aj ako `U.querify()`.\n\nExample: Query stringy\n```js\nQUERIFY({ q: 'red shoes', page: 2 });           // '?q=red%20shoes&page=2'\nQUERIFY('/api/?lang=en', { page: 2 });         // '/api/?lang=en&page=2'\nQUERIFY('GET https://example.com/', { id: 5 }); // 'GET https://example.com/?id=5'\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method`\n\nZavolá funkciu v štýle callbacku a vráti promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Funkcia, ktorej posledným argumentom je 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á s argumentmi, ktoré odovzdáš (najviac tri), a s callbackom `function(err, response)`. Promise sa zamietne s `err` alebo sa splní s `response`. Odovzdaj len argumenty, ktoré potrebuješ: argument s hodnotou `undefined` ukončí zoznam.\n\nExample: Čítanie súboru\n```js\nvar Fs = require('fs');\nvar buffer = await PROMISIFY(Fs.readFile, PATH.root('README.md'));\n```\n\n### ERROR([name])\n\nType: `method`\n\nVráti callback, ktorý zaznamenáva chyby.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Názov zobrazený s chybou, napr. funkcia, ktorá zlyhala. |\n\nReturns: `Function` `function(err)`.\n\nVrátená funkcia prijíma `err` ako prvý argument a keď je nastavený, odovzdá ho obsluhe chýb frameworku (`DEF.onError`, ktorá ho vypíše a uchová v štatistikách) s `name` ako zdrojom. Použi ju pre callbacky, ktorých výsledok nepotrebuješ, ale ich chyby chceš vidieť.\n\nExample: Zaznamenanie neúspešného zápisu\n```js\nFs.writeFile(PATH.databases('cache.json'), JSON.stringify(data), ERROR('cache.save'));\n```\n\n### print(...values)\n\nType: `method`\n\nVypíše hodnoty do konzoly.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `values` | `Object` | yes |  | Hodnoty na vypísanie. |\n\n`print` je `console.log`. Framework ju používa na informácie pri štarte.\n\nExample: Výpis\n```js\nprint('Imported', count, 'products');\n```\n\n### NOW\n\nType: `property`\n\nDate s aktuálnym časom, obnovovaný každých 5 sekúnd.\n\nReturns: `Date`\n\nFramework po načítaní priradí `new Date()` do `NOW` každých 5 sekúnd a tiež vtedy, keď zapisuje chybu, auditný záznam alebo položku cache. Použi ho tam, kde stačí presnosť niekoľkých sekúnd: expirácie, riadky logu, polia `dtcreated`. Objekt nemeň; namiesto toho priraď nový dátum.\n\nExample: Expirácia\n```js\nvar expire = NOW.add('1 hour');\nif (session.expire < NOW)\n\tdelete sessions[session.id];\n```\n\n### NOOP\n\nType: `property`\n\nPrázdna funkcia.\n\nReturns: `Function`\n\nPouži ju tam, kde je callback povinný, ale výsledok nepotrebuješ. Je to tá istá funkcia ako `U.noop`.\n\nExample: Ignorovanie výsledku\n```js\nFs.unlink(filename, NOOP);\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nZmrazený prázdny objekt; EMPTYARRAY je zmrazené prázdne pole.\n\nReturns: `Object`\n\n`EMPTYOBJECT` (`{}`) a `EMPTYARRAY` (`[]`) sa vytvoria raz a zmrazia pomocou `Object.freeze()`, takže sa nedajú zmeniť. Používaj ich ako predvolené hodnoty namiesto vytvárania nových objektov, napríklad `var opt = options || EMPTYOBJECT;`. Nikdy do nich nezapisuj: v strict mode zápis vyhodí chybu.\n\nExample: Predvolené hodnoty\n```js\nfunction find(filter) {\n\tvar opt = filter || EMPTYOBJECT;\n\tvar tags = opt.tags || EMPTYARRAY;\n\treturn tags.length;\n}\n```\n\n### MAIN\n\nType: `property`\n\nGlobálny objekt pre zdieľaný stav aplikácie.\n\nReturns: `Object`\n\nFramework vytvorí `MAIN` ako prázdny objekt a nepoužíva ho. Ulož doň to, čo zdieľa viacero súborov tvojej aplikácie: nastavenia načítané pri štarte, otvorené spojenia, počítadlá. Vo views je dostupný na čítanie ako `MAIN`.\n\nExample: Zdieľané nastavenia\n```js\n// definitions/settings.js\nMAIN.settings = MEMORIZE('settings');\n\n// a controller or an action\nvar title = MAIN.settings.title;\n```\n\n### REPO\n\nType: `property`\n\nGlobálny objekt pre zdieľané dáta, dostupný aj vo views.\n\nReturns: `Object`\n\nPrázdny objekt, ktorý framework vytvorí pri štarte (je to aj `F.repo`). Views ho môžu čítať ako `REPO`, preto je to dobré miesto pre dáta, ktoré potrebujú layouty, napríklad menu alebo kontaktné údaje.\n\nExample: Dáta pre layout\n```js\nREPO.menu = [{ name: 'Home', url: '/' }, { name: 'Contact', url: '/contact/' }];\n\n// views/layout.html\n// @{foreach m in REPO.menu}<a href=\"@{m.url}\">@{m.name}</a>@{end}\n```\n\n### FUNC\n\nType: `property`\n\nGlobálny objekt pre tvoje zdieľané funkcie.\n\nReturns: `Object`\n\nPrázdny objekt pre funkcie, ktoré používa viacero častí aplikácie. Definuj ich v `/definitions/`, aby existovali pred prvou požiadavkou. Aj `FUNC` môžu views čítať.\n\nExample: Zdieľaná funkcia\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// anywhere\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nGlobálny objekt pre krátkodobé dáta, vyprázdňovaný každých 5 minút.\n\nReturns: `Object`\n\nKaždých 5 minút framework nahradí `TEMP` novým prázdnym objektom. Používaj ho pre malé dočasné dáta, ktoré môžu kedykoľvek zmiznúť, napríklad jednorazové tokeny alebo počítadlá pre obmedzovanie. Vždy ho čítaj cez globálnu premennú (`TEMP.key`), nie cez uloženú referenciu, pretože sa objekt mení.\n\nExample: Krátkodobý token\n```js\nvar token = GUID(20);\nTEMP[token] = { userid: user.id };\n\n// later\nvar data = TEMP[token];\nif (!data)\n\t$.invalid('The token has expired');\n```\n\n### MODS\n\nType: `property`\n\nNačítané moduly podľa ich id.\n\nReturns: `Object`\n\nKaždý súbor `.js` v `/modules/` sa načíta pri štarte a uloží do `MODS` pod svojím `exports.id`, alebo pod názvom súboru, keď ho nenastaví. Jeho funkcia `install()`, ak existuje, sa zavolá po načítaní. `MODS` je ten istý objekt ako `F.modules` a dá sa čítať vo views.\n\nExample: Modul\n```js\n// modules/pricing.js\nexports.id = 'pricing';\nexports.vat = function(price) {\n\treturn price * 1.2;\n};\n\n// anywhere\nvar total = MODS.pricing.vat(100);\n```\n\n### CACHE.set(key, value, [expire])\n\nType: `method`\n\nUloží hodnotu do pamäťovej cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč. |\n| `value` | `Object` | yes |  | Ľubovoľná hodnota. |\n| `expire` | `String` | no | `'5 minutes'` | Ako dlho je hodnota platná. |\n\nHodnota sa drží v pamäti procesu, kým neexpiruje. `expire` je trvanie v tvare, ktorý prijíma `Date.add()` (`'30 seconds'`, `'5 minutes'`, `'1 hour'`, `'2 days'`). Hodnota sa uloží tak, ako je, neskopíruje sa: keď ju zmeníš, zmení sa aj hodnota v cache. Expirované položky sa odstraňujú každú minútu.\n\nExample: Uloženie výsledku do cache\n```js\nCACHE.set('products', items, '2 minutes');\n```\n\n### CACHE.get(key, [def])\n\nType: `method`\n\nPrečíta hodnotu z pamäťovej cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč. |\n| `def` | `Object` | no |  | Hodnota vrátená, keď kľúč chýba alebo expiroval. |\n\nReturns: `Object`\n\nVráti hodnotu, keď existuje a neexpirovala; inak `def`. `CACHE.read()` je alias.\n\nExample: Prečítanie alebo načítanie\n```js\nvar items = CACHE.get('products');\nif (!items) {\n\titems = await DATA.find('nosql/products').promise($);\n\tCACHE.set('products', items, '2 minutes');\n}\n```\n\n### CACHE.remove(key)\n\nType: `method`\n\nOdstráni jednu hodnotu z pamäťovej cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč. |\n\nZavolaj ju, keď sa dáta v cache zmenia, aby ďalšie čítanie načítalo čerstvé dáta.\n\nExample: Zneplatnenie\n```js\nNOSQL('products').insert(model).callback(function() {\n\tCACHE.remove('products');\n});\n```\n\n### CACHE.reset([search])\n\nType: `method`\n\nOdstráni viacero hodnôt alebo všetky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | no |  | Časť kľúčov alebo vzor. |\n\nReturns: `Number` Počet odstránených kľúčov.\n\nBez `search` sa vyprázdni celá cache. S reťazcom sa odstráni každý kľúč, ktorý ho obsahuje; s regulárnym výrazom každý kľúč, ktorý mu zodpovedá. Vráti počet odstránených kľúčov (0, keď sa vyprázdni celá cache).\n\nExample: Odstránenie skupiny\n```js\nCACHE.set('products_1', a);\nCACHE.set('products_2', b);\nCACHE.reset('products_');  // 2\nCACHE.reset(/^user_/);\nCACHE.reset();             // everything\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method`\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 poslednou zmenou a zápisom. |\n| `skip` | `String|Array` | no |  | Kľúče, ktoré sa nezapíšu do súboru, ako pole alebo reťazec oddelený čiarkami. |\n\nReturns: `Object` Dáta so `save()` a `set(key, value)`.\n\nPrečíta `databases/memorize_{name}.json` (alebo `databases/memorize.json` bez názvu) a vráti jeho obsah ako objekt (prázdny objekt, keď súbor neexistuje). Objekt dostane dve funkcie: `save()` naplánuje zápis celého objektu a `set(key, value)` priradí hodnotu a zavolá `save()`. Zápis prebehne `delay` milisekúnd po poslednom volaní, takže veľa zmien vytvorí jeden zápis. `skip` uvádza kľúče, ktoré sa nezapíšu. Argumenty `delay` a `skip` sa môžu vymeniť. `MEMORIZE()` zavolaj pre každý názov raz a objekt si uchovaj; každé volanie súbor prečíta znova.\n\nExample: Nastavenia, ktoré prežijú reštart\n```js\nvar settings = MEMORIZE('settings', 'cache');\n\nsettings.set('title', 'My shop');\n\nsettings.counter = (settings.counter || 0) + 1;\nsettings.cache = {};      // not written\nsettings.save();\n```\n\n### BACKUP(filename, files, [callback], [filter])\n\nType: `method`\n\nZabalí súbory a adresáre do jedného archívneho súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Archívny súbor, ktorý sa vytvorí (existujúci súbor sa nahradí). |\n| `files` | `String|Array` | yes |  | Adresár alebo cesty relatívne ku koreňu. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`; vráť `true`, aby sa cesta zabalila. |\n\nReturns: `Promise` Keď je `callback` vynechaný.\n\nZapíše textový archív: jeden riadok na adresár a jeden riadok na súbor, s cestou a obsahom skomprimovaným gzipom v base64. `files` je adresár (všetko v ňom sa zabalí s cestami relatívnymi k nemu) alebo pole ciest relatívnych ku koreňu aplikácie (súbory aj celé adresáre). Názvy obsahujúce `.git`, `.gitignore`, `.npmignore` alebo `.ds_store` sa preskočia. `filter(path, isdirectory)` dostane každú cestu (začínajúcu `/`) a vynechá ju, keď vráti nepravdivú hodnotu. `filename` môže byť aj zapisovateľný stream. Callback dostane `{ filename, files, size }`; bez callbacku funkcia vráti promise.\n\nExample: Záloha nahraných súborov\n```js\nvar meta = await BACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), null, function(path, isdir) {\n\treturn isdir || !path.endsWith('.tmp');\n});\nprint(meta.files, 'files', meta.size, 'bytes');\n```\n\nExample: Vybrané cesty\n```js\nawait BACKUP(PATH.temp('app.backup'), ['config', 'databases', 'public/uploads']);\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nRozbalí archív vytvorený pomocou BACKUP().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Archív. |\n| `target` | `String` | yes |  | Adresár, do ktorého sa rozbaľuje. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nReturns: `Promise` Keď je `callback` vynechaný.\n\nVytvorí adresáre a súbory archívu vnútri `target`. `filename` môže byť aj čitateľný stream. `filter(path, isdirectory)` sa zavolá pre každú položku: pre adresár `false` preskočí jeho vytvorenie; pre súbor vráť `false`, aby sa preskočil, reťazec, aby sa zapísal pod touto cestou (relatívnou k `target`), alebo nič, aby si ponechal svoju cestu. Callback dostane `{ files, size, path }`; bez callbacku funkcia vráti promise.\n\nExample: Obnovenie\n```js\nvar meta = await RESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'));\nprint('Restored', meta.files, 'files');\n```\n\nExample: Preskočenie súborov počas behu\n```js\nRESTORE(PATH.temp('app.backup'), PATH.root(), function(err) {\n\terr && print(err);\n}, function(path, isdir) {\n\tif (!isdir && path.startsWith('/config'))\n\t\treturn false;\n});\n```\n\n### PATH.root([path])\n\nType: `method`\n\nVráti koreňový adresár aplikácie alebo cestu v ňom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Relatívna cesta. |\n\nReturns: `String` Absolútna cesta.\n\nKoreň je adresár aplikácie (kde beží štartovací skript). S `path` vráti koreň spojený s ňou. Rovnako ako ostatné adresárové funkcie `PATH` vytvorí adresár, keď sa prvýkrát zavolá s cestou. `PATH.public()`, `PATH.private()`, `PATH.logs()`, `PATH.plugins()`, `PATH.modules()`, `PATH.templates()`, `PATH.flowstreams()` a `PATH.scripts()` fungujú rovnako pre svoje adresáre.\n\nExample: Cesty\n```js\nPATH.root();                 // '/www/app'\nPATH.root('config');         // '/www/app/config'\nPATH.private('report.pdf');  // '/www/app/private/report.pdf'\n```\n\n### PATH.databases([path])\n\nType: `method`\n\nVráti adresár databáz alebo cestu v ňom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Relatívna cesta. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár `/databases/` obsahuje súbory databáz NoSQL, súbory `MEMORIZE()` a ďalšie dáta aplikácie. Vytvorí sa, keď si prvýkrát požiadaš o cestu v ňom.\n\nExample: Dátový súbor\n```js\nvar filename = PATH.databases('import.json');\nFs.writeFile(filename, JSON.stringify(data), NOOP);\n```\n\n### PATH.temp([path])\n\nType: `method`\n\nVráti dočasný adresár alebo cestu v ňom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Relatívna cesta. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár `/tmp/` obsahuje nahrané súbory, súbory v cache a skompilované assety. `PATH.tmp()` je alias. Pri štarte aplikácie framework odstráni svoje vlastné dočasné súbory v ňom (súbory `.js`, `.css`, `.html`, `.htm`, `.tmp` a `.upload`). Dáta, ktoré musia vydržať, uchovávaj v `/databases/`.\n\nExample: Dočasný súbor\n```js\nvar filename = PATH.temp(UID() + '.csv');\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 |  | Absolútna cesta. |\n| `callback` | `Function` | no |  | `function(exists, size, isfile)`. |\n\nReturns: `Promise<Boolean>` Keď je `callback` vynechaný.\n\nCallback dostane tri argumenty: `exists`, veľkosť v bajtoch a `isfile` (`true` pre súbor, `false` pre adresár). Bez callbacku funkcia vráti promise, ktorý sa splní s `exists`.\n\nExample: Kontrola súboru\n```js\nif (await PATH.exists(PATH.databases('settings.json')))\n\tprint('Settings found');\n\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isfile) {\n\tprint(exists, size, isfile);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nOdstráni jeden alebo viac súborov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|Array` | yes |  | Absolútna cesta alebo pole ciest. |\n| `callback` | `Function` | no |  | `function()`. |\n\nOdstráni súbory jeden po druhom a potom zavolá callback. Chyby (napríklad chýbajúci súbor) sa ignorujú.\n\nExample: Odstránenie súborov\n```js\nPATH.unlink([PATH.temp('a.csv'), PATH.temp('b.csv')], function() {\n\tprint('Removed');\n});\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nOdstráni adresáre so všetkým, čo obsahujú.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|Array` | yes |  | Absolútna cesta alebo pole ciest. |\n| `callback` | `Function` | no |  | `function()`. |\n\nPre každý adresár sa odstránia všetky súbory, potom podadresáre od najhlbšieho, a nakoniec samotný adresár. Potom sa zavolá callback.\n\nExample: Odstránenie adresára\n```js\nPATH.rmdir(PATH.temp('export'), function() {\n\tprint('Directory removed');\n});\n```\n\n### Total.FsPromises\n\nType: `property`\n\nModul Node.js `node:fs/promises`.\n\nReturns: `Object` Modul `node:fs/promises`.\n\nPromise verzia funkcií súborového systému Node.js, ktorú načíta framework. `F.FsPromises` je ten istý objekt a `Total.Fs` (`F.Fs`) je modul `node:fs`.\n\nExample: Čítanie a výpis\n```js\nvar text = await Total.FsPromises.readFile(PATH.root('README.md'), 'utf8');\nvar files = await Total.FsPromises.readdir(PATH.public());\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nPrevedie ľubovoľnú hodnotu na číslo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota na prevod. |\n| `def` | `Number` | no | `0` | Výsledok pre prázdne alebo neplatné hodnoty. |\n\nReturns: `Number`\n\nČíslo sa vráti tak, ako je. Reťazec sa oreže a prevedie unárnym `+`; ostatné hodnoty sa najprv prevedú na reťazec. `null`, `undefined`, prázdny reťazec a hodnota, ktorá nie je číslom, vrátia `def` (predvolene 0). Výsledok sa nezaokrúhľuje (`'1.5'` dá `1.5`). `U.parseFloat(value, [def])` funguje rovnako a navyše akceptuje čiarku ako desatinný oddeľovač (`'12,50'` dá `12.5`).\n\nExample: Hodnoty z query\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\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 na prevod. |\n| `def` | `Boolean` | no | `false` | Výsledok pre `null` alebo `undefined`. |\n\nReturns: `Boolean`\n\nBoolean sa vráti tak, ako je; číslo je `true`, keď je väčšie ako 0; reťazce `true`, `1` a `on` (v ľubovoľnej veľkosti písmen) sú `true` a každý iný reťazec je `false`. `null` a `undefined` vrátia `def` (predvolene `false`).\n\nExample: Checkbox\n```js\nvar newsletter = U.parseBoolean(this.body.newsletter); // 'on' -> true\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nPrečíta vnorenú hodnotu podľa cesty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Objekt, z ktorého sa číta. |\n| `path` | `String` | yes |  | Cesta. |\n\nReturns: `Object` Hodnota alebo `undefined`.\n\nCesta používa bodky a hranaté zátvorky: `a.b.c`, `items[0].name`. Keď časť cesty chýba, vráti `undefined` namiesto vyhodenia chyby. Cesty s medzerami, zátvorkami alebo kľúčovými slovami ako `__proto__` a `constructor` sa odmietnu (`undefined`). Skompilované čítacie funkcie sa ukladajú do cache pre každú cestu.\n\nExample: Vnorené hodnoty\n```js\nvar data = { user: { address: { city: 'Bratislava' } }, items: [{ name: 'A' }] };\nU.get(data, 'user.address.city');  // 'Bratislava'\nU.get(data, 'items[0].name');      // 'A'\nU.get(data, 'user.phone.number');  // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nZapíše vnorenú hodnotu podľa cesty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Objekt, do ktorého sa zapisuje. |\n| `path` | `String` | yes |  | Cesta. |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `Object` Zapísaná hodnota.\n\nChýbajúce objekty na ceste sa vytvoria. Cesta, ktorá končí na `[]`, vloží hodnotu do poľa a index vytvorí pole s objektmi (`items[0].name`). Cesty s medzerami, zátvorkami alebo kľúčovými slovami ako `__proto__` a `constructor` sa odmietnu: nič sa nezapíše. Vráti hodnotu.\n\nExample: Zostavenie objektu\n```js\nvar model = {};\nU.set(model, 'address.city', 'Bratislava');\nU.set(model, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\nExample: Cesta s indexom\n```js\nvar model = {};\nU.set(model, 'items[0].name', 'Pen');\n// { items: [{ name: 'Pen' }] }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nSkopíruje kľúče zo source do target.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | Objekt, do ktorého sa zapisuje. |\n| `source` | `Object` | yes |  | Objekt, z ktorého sa číta. |\n| `rewrite` | `Boolean` | no | `true` | `false` ponechá existujúce hodnoty. |\n\nReturns: `Object` Cieľ.\n\nKaždý kľúč zo `source` sa naklonuje do `target`. Keď je `rewrite` nastavené na `false`, kľúče, ktoré už v `target` existujú, sa nezmenia, takto doplníš predvolené hodnoty. Vráti `target`.\n\nExample: Predvolené hodnoty\n```js\nvar options = { limit: 50 };\nU.extend(options, { limit: 10, sort: 'name' }, false);\n// { limit: 50, sort: 'name' }\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nVráti porovnávaciu funkciu pre Array.sort().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Napríklad `name` alebo `price_desc,name`. |\n\nReturns: `Function` `function(a, b)` pre `Array.prototype.sort()`.\n\n`sort` je zoznam kľúčov oddelených čiarkami; pridaj `_desc` pre zostupné poradie (`_asc` je predvolené). Vnorené kľúče používajú bodky (`address.city`). Typ každého kľúča sa určí z prvej neprázdnej hodnoty pri prvom použití výrazu a zachová sa pre ďalšie použitia rovnakého výrazu: reťazce sa porovnávajú s ohľadom na diakritiku, čísla, booleany a dátumy podľa hodnoty.\n\nExample: Zoradenie produktov\n```js\nproducts.sort(U.sortcomparer('price_desc,name'));\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nVráti náhodné celé číslo v rozsahu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | Najväčšia hodnota. |\n| `min` | `Number` | no | `0` | Najmenšia hodnota. |\n\nReturns: `Number`\n\nVráti celé číslo medzi `min` a `max`, vrátane oboch.\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`. `U.random_string(length)` používa len písmená a `U.random_number(length)` len číslice (vrátené ako reťazec, ktorý nezačína 0). Tieto hodnoty pochádzajú z `Math.random()`: nepoužívaj ich ako heslá ani bezpečnostné tokeny.\n\nExample: Náhodné reťazce\n```js\nU.random_text(8);    // 'yb7JVb2a'\nU.random_string(6);  // 'HNXkTk'\nU.random_number(6);  // '825174'\n```\n\n### U.convert62(number)\n\nType: `method`\n\nPrevedie číslo na reťazec v sústave 62.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | Nezáporné číslo. |\n\nReturns: `String`\n\nČíslice sú `0-9`, `A-Z` a `a-z`, v tomto poradí. Číslo sa najprv zaokrúhli nadol. `U.from62(value)` prevedie reťazec späť na číslo. Použi ju na krátke kódy vytvorené z číselných id.\n\nExample: Krátke kódy\n```js\nvar code = U.convert62(123456);  // 'W7E'\nvar id = U.from62(code);         // 123456\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nVráti príponu názvu súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Názov súboru, cesta alebo URL. |\n| `raw` | `Boolean` | no | `false` | `true` ponechá pôvodnú veľkosť písmen. |\n\nReturns: `String`\n\nVráti časť za poslednou bodkou, bez bodky a malými písmenami (s `raw` v pôvodnej veľkosti písmen). Query string za `?` sa ignoruje. Vráti prázdny reťazec, keď názov nemá príponu.\n\nExample: Prípony\n```js\nU.getExtension('/img/Photo.JPG');      // 'jpg'\nU.getExtension('/files/a.pdf?v=1');    // 'pdf'\nU.getExtension('README');              // ''\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 alebo URL. |\n\nReturns: `String`\n\nVráti názov súboru (alebo posledný adresár) z cesty s oddeľovačmi `/` alebo `\\\\`. Koncový oddeľovač sa ignoruje.\n\nExample: Názvy súborov\n```js\nU.getName('/www/app/public/logo.png');  // 'logo.png'\nU.getName('/www/app/public/');          // 'public'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nVráti MIME typ pre príponu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Prípona, napr. `png` alebo `.png`. |\n\nReturns: `String`\n\nPrípona môže začínať bodkou. Neznáme prípony vrátia `application/octet-stream`. `U.getExtensionFromContentType(type)` robí opak a vráti prvú príponu s týmto typom (alebo `undefined`). Celá tabuľka je `U.contentTypes`.\n\nExample: Content typy\n```js\nU.getContentType('png');                     // 'image/png'\nU.getContentType('.json');                   // 'application/json'\nU.getExtensionFromContentType('image/png');  // 'png'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nZakóduje text alebo buffer do base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Dáta na zakódovanie. |\n\nReturns: `String`\n\nBuffer sa zakóduje priamo; ostatné hodnoty sa prevedú na reťazec a zakódujú ako UTF-8. `U.atob(value)` dekóduje base64 späť na reťazec UTF-8.\n\nExample: Base64\n```js\nvar encoded = U.btoa('Hello');   // 'SGVsbG8='\nvar text = U.atob(encoded);      // 'Hello'\n```\n\n### U.validhost(host)\n\nType: `method`\n\nSkontroluje, že hostname je čisté ASCII a že IP adresa je v kanonickom tvare.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | Hostname alebo IP adresa. |\n\nReturns: `Boolean` `true` pre platného hosta.\n\nVráti `false` pre hodnotu, ktorá nie je reťazec, je prázdna alebo obsahuje znak mimo viditeľného rozsahu ASCII (medzery, NUL bajty, písmená s diakritikou). Hodnota zložená iba z čísel a bodiek (alebo hex čísel) musí byť kanonická IPv4 adresa: `127.0.0.1` je platná, `127.1`, `0127.0.0.1`, `0x7f.0.0.1` a `2130706433` nie sú. Ostatné ASCII hodnoty vrátane IPv6 adries vrátia `true`; funkcia nekontroluje úplnú syntax hostname. Medzinárodný názov najprv skonvertuj cez `U.tohost()`.\n\nExample: Kontrola hostov\n```js\nU.validhost('example.com');     // true\nU.validhost('127.0.0.1');       // true\nU.validhost('127.1');           // false\nU.validhost('0x7f.0.0.1');      // false\nU.validhost('münchen.de');      // false\nU.validhost('evil.example\\0.trusted.example'); // false\n```\n\n### U.tohost(host)\n\nType: `method`\n\nSkonvertuje hostname na jeho kanonický ASCII tvar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `String` | yes |  | Hostname alebo IP adresa. |\n\nReturns: `String` Kanonický host alebo prázdny reťazec.\n\nSkonvertuje hosta URL parserom Node.js: písmená sa zmenia na malé, medzinárodný názov na punycode a IPv4 adresa v inom zápise na tvar s bodkami (úvodná `0` znamená osmičkové číslo, `0x` hex číslo). Výsledok sa potom skontroluje cez `U.validhost()`. Hodnota, ktorá obsahuje `:` (IPv6 adresa), sa iba skontroluje. Vráti prázdny reťazec, keď host nie je platný, takže výsledok pred použitím otestuj.\n\nExample: Konverzia hostov\n```js\nU.tohost('münchen.de');      // 'xn--mnchen-3ya.de'\nU.tohost('EXAMPLE.com');     // 'example.com'\nU.tohost('127.1');           // '127.0.0.1'\nU.tohost('0x7f.0.0.1');      // '127.0.0.1'\nU.tohost('evil.example\\0.trusted.example'); // ''\n```\n\nExample: Validácia vstupu\n```js\nfunction host(value) {\n\tvar host = U.tohost(value);\n\tif (!host)\n\t\tthrow new Error('Invalid hostname');\n\treturn host;\n}\n```\n\n### U.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` | no |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Milisekundy, kým čakanie zlyhá. |\n| `interval` | `Number` | no | `500` | Milisekundy medzi kontrolami. |\n\nReturns: `Promise` Keď je `callback` vynechaný.\n\n`validator` sa zavolá hneď a potom každých `interval` milisekúnd, kým nevráti `true`; potom callback dostane `(null, true)`. Keď najprv uplynie `timeout`, callback dostane `Error('Timeout')`. Bez callbacku funkcia vráti promise, ktorý sa rovnakým spôsobom splní alebo zamietne.\n\nExample: Čakanie na spojenie\n```js\nawait U.wait(() => MAIN.db != null, null, 10000, 200);\nprint('Database ready');\n```\n\n### U.resolve(url, callback, [param])\n\nType: `method`\n\nPreloží hosta URL na IPv4 adresy, s cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Absolútna URL. |\n| `callback` | `Function` | yes |  | `function(err, uri, param, addresses)`. |\n| `param` | `Any` | no |  | Hodnota odovzdaná do callbacku. |\n\nSparsuje `url`, skontroluje jeho hostname cez `U.validhost()` a opýta sa DNS serverov na jeho IPv4 adresy (`dns.resolve4()`, takže súbor hosts sa nepoužije). Callback dostane `(err, uri, param, addresses)`: `uri` je sparsovaná URL s `host` nastaveným na prvú adresu, `param` je tretí argument a `addresses` celý zoznam. Adresy sa uložia do cache na celý život procesu; neúspešné vyhľadanie sa skúsi ešte raz, než sa odovzdá `err`.\n\nReťazec, ktorý nie je URL, vráti `TypeError: Invalid URL` a hostname, ktorý nie je platný, vráti chybu `Invalid hostname` bez DNS dopytu. Pre URL `http` a `https` hosta skonvertuje už URL parser; pre iné schémy vráti nekanonická adresa ako `tcp://127.1/` chybu `Invalid hostname`. `REQUEST()` používa túto funkciu s možnosťou `resolve: true` a `RESTBuilder` predvolene.\n\nExample: Preklad hosta\n```js\nU.resolve('https://example.com/api/', function(err, uri, param, addresses) {\n\tif (err)\n\t\tconsole.log(err.message || err.code);\n\telse\n\t\tconsole.log(uri.hostname, addresses);\n});\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nRozdelí prúd dát na časti podľa oddeľovačov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Začiatok časti alebo oddeľovač. |\n| `end` | `String|Buffer` | no |  | Koniec časti. |\n| `callback` | `Function` | yes |  | `function(value, index)`; vráť `false` na zastavenie. |\n| `skip` | `Number` | no | `0` | Počet prvých častí na ignorovanie. |\n| `stream` | `Stream` | no |  | Stream, ktorého udalosť `end` spracuje zvyšok. |\n\nReturns: `Function` `function(chunk)`.\n\nVráti funkciu, ktorú zavoláš s každým kúskom dát (bufferom), napríklad ako obsluhu `data` streamu. S `beg` a `end` dostane callback každú časť, ktorá začína `beg` a končí `end`, vrátane oboch (napríklad jeden `<item>...</item>` veľkého súboru XML). Len s `beg` je `beg` oddeľovač a callback dostane každú časť až po neho vrátane (napríklad riadky s `\\n`). Callback dostane `(value, index)` s hodnotou ako reťazcom; vrátenie `false` zastaví parsovanie. `skip` ignoruje daný počet prvých častí. So `stream` sa zvyšné dáta spracujú, keď stream skončí. `U.streamer2()` prijíma rovnaké argumenty a odovzdáva buffery namiesto reťazcov.\n\nExample: Čítanie veľkého súboru XML\n```js\nvar stream = Fs.createReadStream(PATH.databases('products.xml'));\nstream.on('data', U.streamer('<product>', '</product>', function(value, index) {\n\tvar product = value.parseXML();\n\tprint(index, product);\n}));\n```\n\nExample: Riadky súboru CSV\n```js\nvar stream = Fs.createReadStream(filename);\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tvar cols = line.trim().split(';');\n}, 1, stream));  // skips the header line\n```\n\n### U.connect(options, [callback])\n\nType: `method`\n\nOtvorí TCP alebo TLS spojenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | `{ host, port, secure, tls, timeout }` a so `secure` ďalšie možnosti `tls.connect()`. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nPripojí sa na `options.host` a `options.port` a zavolá `callback(err, meta)`, keď je spojenie otvorené. Host sa najprv skonvertuje cez `U.tohost()`, takže medzinárodný názov sa pošle ako punycode a `127.1` ako `127.0.0.1`; host, ktorý nie je platný, vráti chybu `Invalid hostname` a spojenie sa nevytvorí. So `secure: true` spojenie používa TLS od začiatku a ostatné možnosti (`servername`, `rejectUnauthorized`, `ca` ...) idú do `tls.connect()`. S `tls` sa spojenie začne ako čisté TCP a hneď po otvorení sa povýši na TLS: `tls: true` použije predvolené možnosti `tls.connect()`, objekt odovzdá svoje možnosti (`servername`, `rejectUnauthorized`, `ca` ...). S `timeout` (v milisekundách) vráti spojenie, ktoré sa neotvorí včas, chybu `Timeout`.\n\n`meta` má `socket` (socket Node.js), `opt` (možnosti so skonvertovaným hostom), `write(data)`, `ondata(fn)` pre prijaté časti a `close()` (aj `destroy()`). `LDAP()` sa pripája touto funkciou.\n\nExample: Prečítanie pozdravu servera\n```js\nU.connect({ host: 'mail.example.com', port: 25, timeout: 5000 }, function(err, meta) {\n\tif (err) {\n\t\tconsole.log(err.message);\n\t\treturn;\n\t}\n\tmeta.ondata(function(chunk) {\n\t\tconsole.log(chunk.toString());\n\t\tmeta.close();\n\t});\n});\n```\n\nExample: Povýšenie na TLS\n```js\nU.connect({ host: 'mail.example.com', port: 465, tls: { servername: 'mail.example.com' } }, function(err, meta) {\n\tif (!err)\n\t\tconsole.log(meta.socket.encrypted); // true\n});\n```\n\n### U.ls(path, [callback], [filter])\n\nType: `method`\n\nRekurzívne vypíše súbory a adresáre adresára.\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\nReturns: `Promise` `{ files, directories }`, keď je `callback` vynechaný.\n\nCallback dostane dve polia absolútnych ciest: `files` a `directories` (adresáre končia oddeľovačom ciest). `filter` môže byť reťazec (cesty, ktoré ho obsahujú, bez ohľadu na veľkosť písmen), regulárny výraz alebo funkcia `(path, isdirectory)`, ktorá vráti `true`, aby sa položka ponechala; filtre s reťazcom a regulárnym výrazom sa uplatňujú len na súbory. Adresár, ktorý filter vyradí, sa neprehľadáva. Bez callbacku funkcia vráti promise s `{ files, directories }`. `U.ls2()` prijíma rovnaké argumenty a vracia súbory ako objekty `{ filename, stats }` s `fs.Stats` každého súboru.\n\nExample: Nájdenie súborov JSON\n```js\nU.ls(PATH.databases(), function(files, directories) {\n\tprint(files);\n}, /\\.json$/);\n```\n\nExample: Veľkosti pomocou ls2\n```js\nvar result = await U.ls2(PATH.public('uploads'));\nvar size = 0;\nfor (var file of result.files)\n\tsize += file.stats.size;\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nUloží veľký zoznam do dočasných súborov po stránkach.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Jedinečný názov, použitý pre názvy súborov. |\n| `max` | `Number` | no | `50` | Položky na stránku. |\n\nReturns: `Chunker`\n\nChunker zbiera položky pomocou `write(item)` (alias `append()`); každých `max` položiek sa zapíše do súboru `tmp/{name}-{index}.chunker` (skomprimovaného deflate, keď je `compress` `true`, čo je predvolené), takže pamäť zostáva malá. Zavolaj `end()`, aby sa zapísal zvyšok. Potom `each(onitem, [ondone])` číta stránky v poradí: `onitem(items, next, index)` dostane jednu stránku a zavolá `next()`, aby sa pokračovalo, a `percentage` udáva, ako ďaleko je čítanie. `read(index, callback)` prečíta jednu stránku. S `autoremove` (predvolene `true`) sa každý súbor po prečítaní odstráni; `clear()` odstráni všetky súbory a `destroy()` navyše uvoľní chunker. Vlastnosti `count` a `pages` obsahujú počet položiek a stránok.\n\nExample: Spracovanie veľkého exportu\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var row of rows)\n\tchunker.write(row);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tprint('Page', index, chunker.percentage + '%');\n\tsend(items, next);\n}, function() {\n\tprint('Done', chunker.count, 'items');\n});\n```\n\n### chunker.load([callback])\n\nType: `method` · Since: `0.0.16`\n\nNájde stránky, ktoré na disku nechal skorší chunker s rovnakým názvom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `Promise` Keď je `callback` vynechaný.\n\nSpočíta súbory chunkera v dočasnom adresári a nastaví interný index stránok, takže `each()` a `read()` dokážu prečítať stránky, ktoré skoršia inštancia zapísala a neprečítala (napríklad pred reštartom). Vytvor chunker s rovnakým `name`. Callback dostane `(null, count)`; bez callbacku funkcia vráti promise, ktorý sa splní po dokončení počítania.\n\nExample: Pokračovanie chunkera\n```js\nvar chunker = U.chunker('export');\nawait chunker.load();\nchunker.each(function(items, next) {\n\tsend(items, next);\n});\n```\n\n### new U.EventEmitter2() / U.EventEmitter2(obj)\n\nType: `class`\n\nMalý emitor udalostí.\n\nReturns: `EventEmitter2`\n\nObjekt s `on(name, fn)`, `once(name, fn)`, `off(name, [fn])` a `emit(name, ...args)` (najviac sedem argumentov). `off(name)` bez funkcie odstráni všetky obsluhy udalosti. Obsluhy bežia s emitterom ako `this`. Keď sa zavolá s objektom (`U.EventEmitter2(obj)`), pridá tieto metódy do daného objektu, pokiaľ už nemá `emit`, a vráti ho.\n\nExample: Udalosti na tvojom objekte\n```js\nvar Cart = {};\nU.EventEmitter2(Cart);\n\nCart.on('add', function(item) {\n\tprint('Added', item.name);\n});\n\nCart.emit('add', { name: 'Shoes' });\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nZamaskuje reťazec pomocou kľúča.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Text. |\n| `key` | `String` | yes |  | Kľúč. |\n| `encode` | `String` | no | `'base64'` | Výstupné kódovanie alebo `buffer`. |\n\nReturns: `String|Buffer`\n\nZakóduje reťazec pomocou kľúča a náhodnej 4-bajtovej masky a vráti ho v base64 (alebo v kódovaní, ktoré nastavíš; `buffer` vráti buffer). Rovnaký vstup dá zakaždým iný výstup. `U.decrypt_data(value, key, [encode])` vráti pôvodný reťazec, alebo `null` pre neplatný vstup. Je to ľahké zamaskovanie, nie silné šifrovanie; pre citlivé dáta použi `ENCRYPT()` (pozri [Šifrovanie](../../guides/encryption/)).\n\nExample: Tam a späť\n```js\nvar data = U.encrypt_data('hello', 'mykey');\nvar text = U.decrypt_data(data, 'mykey');  // 'hello'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nPodpíše identifikátor, aby sa nedal zmeniť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | Identifikátor. |\n| `key` | `String` | no | `CONF.secret` | Kľúč. |\n\nReturns: `String`\n\nVráti identifikátor s kontrolným súčtom na začiatku, vytvoreným z hodnoty, kľúča a `CONF.secret_uid`. `U.decrypt_uid(value, [key])` ho overí a vráti pôvodný identifikátor (číslo, keď bol pôvodný číslom), alebo `null`, keď bola hodnota zmenená. Samotný identifikátor zostáva čitateľný. Bez `key` sa použije `CONF.secret`.\n\nExample: Podpísané id v odkaze\n```js\nvar signed = U.encrypt_uid(123, 'mykey');   // 'n...x123', the checksum depends on CONF.secret_uid\nU.decrypt_uid(signed, 'mykey');             // 123\nU.decrypt_uid('n2v55u4jx124', 'mykey');     // null\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifikuje JavaScript; U.minify_css() a U.minify_html() robia to isté pre CSS a HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Zdrojový kód. |\n\nReturns: `String`\n\nSú to minifikátory, ktoré framework používa pre statické súbory a views. Prijímajú reťazec a vracajú minifikovaný reťazec.\n\nExample: Minifikácia\n```js\nU.minify_js('var a = 1 ;  // note\\n');  // 'var a=1;'\nU.minify_css('a { color : red ; }');     // 'a{color:red}'\nU.minify_html(html);\n```\n\n### U.aistreamer(online, [onmessage])\n\nType: `method` · Since: `0.0.16`\n\nSpracuje streamovanú odpoveď AI chat API na riadky textu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `online` | `Function` | yes |  | `function(line)`, volaná pre každý celý riadok textu. |\n| `onmessage` | `Function` | no |  | `function(message)`, volaná pre každú spracovanú JSON správu. |\n\nReturns: `Function` `function(chunk)`.\n\nVráti funkciu, ktorú voláš s každým kúskom (bufferom) streamovanej odpovede. Číta JSON správy riadok po riadku v dvoch formátoch: server-sent events s `data: {...}` (OpenAI completions, kde je text v `choices[0].delta.content` a `data: [DONE]` ho ukončí) a obyčajné JSON riadky (Ollama, kde je text v `message.content` a `done` ho ukončí). Text sa zbiera a `online(line)` sa volá pre každý celý riadok. `onmessage(obj)`, keď ho nastavíš, dostane každú spracovanú správu; JSON dátumy sa potom spracujú ako dátumy.\n\nExample: Výpis odpovede riadok po riadku\n```js\nvar parser = U.aistreamer(function(line) {\n\tprint(line);\n});\n\nresponse.stream.on('data', parser);\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nUloží výsledok úlohy do súboru ako cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Identifikátor položky v cache. |\n| `expire` | `String` | yes |  | Ako dlho je súbor platný, napríklad `'5 minutes'`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `maker` | `Function` | yes |  | `function(next, id)`, ktorá vytvorí hodnotu. |\n| `encoding` | `String` | no | `json` | `json` alebo kódovanie súboru, napríklad `utf8`. |\n\nHľadá súbor pre `id` v `tmp/`. Keď existuje a je novší ako `expire`, jeho obsah ide do `callback(err, response)`. Inak sa spustí `maker(next, id)`; `next(err, response, [load])` zapíše odpoveď do súboru a zavolá `callback`, ak `load` nie je `false`. S kódovaním `json` sa hodnota uloží ako JSON a spätne sa spracuje; akékoľvek iné kódovanie ukladá a číta surový obsah.\n\nExample: Cache vzdialeného zoznamu\n```js\nFILECACHE('currencies', '1 day', function(err, response) {\n\tMAIN.currencies = response;\n}, function(next) {\n\tREQUEST({ url: 'https://example.com/rates.json', callback: function(err, response) {\n\t\tnext(err, err ? null : response.body.parseJSON());\n\t}});\n});\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID()","since":"","deprecated":false},{"type":"method","name":"GUID([length])","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"HASH(value, [type])","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"CLONE(obj, [skip], [nofunctions])","signature":"CLONE(obj, [skip], [nofunctions])","since":"","deprecated":false},{"type":"method","name":"COPY(source, [target], [all])","signature":"COPY(source, [target], [all])","since":"","deprecated":false},{"type":"method","name":"DIFFARR(prop, db, form)","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"QUERIFY([url], obj)","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"PROMISIFY(fn, [a], [b], [c])","signature":"PROMISIFY(fn, [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"ERROR([name])","signature":"ERROR([name])","since":"","deprecated":false},{"type":"method","name":"print()","signature":"print(...values)","since":"","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"NOOP","signature":"NOOP","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","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":"CACHE.set(key, value, [expire])","signature":"CACHE.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"CACHE.get(key, [def])","signature":"CACHE.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"CACHE.remove(key)","signature":"CACHE.remove(key)","since":"","deprecated":false},{"type":"method","name":"CACHE.reset([search])","signature":"CACHE.reset([search])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE([name], [delay], [skip])","signature":"MEMORIZE([name], [delay], [skip])","since":"","deprecated":false},{"type":"method","name":"BACKUP(filename, files, [callback], [filter])","signature":"BACKUP(filename, files, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE(filename, target, [callback], [filter])","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"PATH.root([path])","signature":"PATH.root([path])","since":"","deprecated":false},{"type":"method","name":"PATH.databases([path])","signature":"PATH.databases([path])","since":"","deprecated":false},{"type":"method","name":"PATH.temp([path])","signature":"PATH.temp([path])","since":"","deprecated":false},{"type":"method","name":"PATH.exists(path, [callback])","signature":"PATH.exists(path, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink(files, [callback])","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir(directories, [callback])","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"property","name":"Total.FsPromises","signature":"Total.FsPromises","since":"","deprecated":false},{"type":"method","name":"U.parseInt(value, [def])","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseBoolean(value, [def])","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.get(obj, path)","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set(obj, path, value)","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.extend(target, source, [rewrite])","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer(sort)","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.random([max], [min])","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text(length)","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.convert62(number)","signature":"U.convert62(number)","since":"","deprecated":false},{"type":"method","name":"U.getExtension(filename, [raw])","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName(path)","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType(ext)","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.btoa(value)","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.validhost(host)","signature":"U.validhost(host)","since":"","deprecated":false},{"type":"method","name":"U.tohost(host)","signature":"U.tohost(host)","since":"","deprecated":false},{"type":"method","name":"U.wait(validator, [callback], [timeout], [interval])","signature":"U.wait(validator, [callback], [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"U.resolve(url, callback, [param])","signature":"U.resolve(url, callback, [param])","since":"","deprecated":false},{"type":"method","name":"U.streamer(beg, [end], callback, [skip], [stream])","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.connect(options, [callback])","signature":"U.connect(options, [callback])","since":"","deprecated":false},{"type":"method","name":"U.ls(path, [callback], [filter])","signature":"U.ls(path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"U.chunker(name, [max])","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.load([callback])","signature":"chunker.load([callback])","since":"0.0.16","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2() / U.EventEmitter2(obj)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_data(value, key, [encode])","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid(value, [key])","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.minify_js(value)","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.aistreamer(online, [onmessage])","signature":"U.aistreamer(online, [onmessage])","since":"0.0.16","deprecated":false},{"type":"method","name":"FILECACHE(id, expire, callback, maker, [encoding])","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:29.576Z"}
{"id":"JacXWy2qt61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/prototypes/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Prototypes","summary":"Every method that Total.js adds to String, Number, Date and Array.prototype.","markdown":"---\ntitle: Prototypes\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/prototypes/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Prototypes\n\n> Every method that Total.js adds to String, Number, Date and Array.prototype.\n\nMethods that Total.js 5 adds to the built-in prototypes `String`, `Number`, `Date` and `Array`. They are available everywhere once the framework is loaded. The guide [Prototypes](../../guides/prototypes/) shows how to use them together with examples; this page is the exact reference.\n\n## API\n\n### str.format(arg0, [arg1], [...])\n\nType: `method`\n\nReplaces numbered placeholders {0}, {1}, ... with the arguments.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0...argN` | `Any` | yes |  | Values for `{0}`, `{1}` and so on. |\n\nReturns: `String` The new string.\n\nEach `{n}` is replaced with the argument at index `n`. A placeholder whose argument is `null` or `undefined` becomes an empty string. Only numbers are allowed inside the braces; use `String.args()` for named keys.\n\nExample: Numbered placeholders\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n// Hello Peter, you have 5 messages.\n```\n\n### str.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` | `String|Function` | no |  | `html`, `json`, a function `(value, key)` or any other string for URL encoding. |\n| `def` | `String` | no |  | The text for keys without a value. |\n\nReturns: `String` The new string.\n\n`String.arg()` is the same method. A placeholder is a key in single or double braces; spaces inside the braces are trimmed. Keys are read directly from `obj` (no nested paths).\n\n`encode` changes the output of each value: `'html'` encodes it with `String.encode()`, `'json'` writes `JSON.stringify(value)`, any other truthy string uses `encodeURIComponent()`, and a function `(value, key)` returns the text itself. When `encode` is a string it also replaces `def`: with `'html'` or a URL-encoding string, a key without a value becomes the text of `encode`; with `'json'` it becomes `undefined`. Without `encode`, a key without a value is left as it is, or replaced with `def` when you pass one.\n\nExample: Named placeholders\n```js\nvar tpl = 'Hello {name}, your order {{ id }} is ready.';\ntpl.args({ name: 'Peter', id: 'A100' });\n// Hello Peter, your order A100 is ready.\n\n'<b>{name}</b>'.args({ name: '<script>' }, 'html');\n// <b>&lt;script&gt;</b>\n```\n\n### str.slug([max])\n\nType: `method`\n\nMakes a URL-friendly slug from the text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | The maximum length of the slug. |\n\nReturns: `String` The slug.\n\nThe text is trimmed, lowercased and diacritics are removed (`toASCII()`). Letters, digits and `_` are kept; spaces and the characters `!\"#$%&'()*+,-./` become a single `-`; other characters are dropped. A trailing `-` is removed and the result has at most `max` characters.\n\nWhen the text contains a character without an ASCII form whose code is above 540 (for example Cyrillic letters, `€` or an emoji), the whole text is not slugged letter by letter: the method then returns a short hash-based identifier made from the text, so the result is still stable and URL-safe.\n\nExample: Slug a title\n```js\n' Hello World! Čaute 123 '.slug();\n// hello-world-caute-123\n\n'A very long article title'.slug(10);\n// a-very-lon\n```\n\n### str.max(length, [chars])\n\nType: `method`\n\nShortens 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 shortened string. |\n\nReturns: `String` The text, shortened when needed.\n\nWhen the text is longer than `length`, it is cut so that the result including `chars` has exactly `length` characters. Shorter text is returned unchanged.\n\nExample: Shorten\n```js\n'Hello world'.max(8);       // Hello...\n'Hello world'.max(8, '…');  // Hello w…\n```\n\n### str.capitalize([first])\n\nType: `method`\n\nCapitalizes the first letter of every word, or only of the text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Capitalize only the first character. |\n\nReturns: `String` The new string.\n\nThe text is lowercased first. Without arguments every letter after a space, tab or new line becomes uppercase. With `first` set to `true`, only the first character is uppercased and the rest stays lowercase.\n\nExample: Capitalize\n```js\n'hello WORLD'.capitalize();      // Hello World\n'hello WORLD'.capitalize(true);  // Hello world\n```\n\n### str.toName()\n\nType: `method`\n\nCleans a person name: removes digits and symbols, extra spaces and capitalizes words.\n\nReturns: `String` The cleaned name.\n\nOnly ASCII letters, characters above code 127 (letters with diacritics) and spaces are kept. Repeated spaces are reduced to one, trailing spaces are removed (leading spaces become one space) and the first letter of each word is uppercased. The rest of each word is kept as it is.\n\nExample: Clean a name\n```js\n'peter   sirka 12'.toName();\n// Peter Sirka\n```\n\n### str.encode()\n\nType: `method`\n\nEncodes HTML special characters.\n\nReturns: `String` The encoded text.\n\n`String.safehtml()` is the same method. The characters `<`, `>`, `\"`, `'` and `&` are replaced with `&lt;`, `&gt;`, `&quot;`, `&apos;` and `&amp;`. Use it before you put user text into HTML.\n\nExample: Encode user input\n```js\n'<a href=\"x\">Tom & Jerry</a>'.encode();\n// &lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/a&gt;\n```\n\n### str.decode()\n\nType: `method`\n\nDecodes HTML entities back to characters.\n\nReturns: `String` The decoded text.\n\nNamed entities (`&lt;`, `&amp;`, `&quot;`, ...) and numeric entities (`&#65;`, `&#x41;`) are replaced with their characters. Unknown named entities stay as they are.\n\nExample: Decode\n```js\n'&lt;b&gt;Tom &amp; Jerry&#33;&lt;/b&gt;'.decode();\n// <b>Tom & Jerry!</b>\n```\n\n### str.removeTags()\n\nType: `method`\n\nRemoves HTML tags from the text.\n\nReturns: `String` The text without tags.\n\nEvery `<...>` tag (opening or closing) is removed; the text between tags stays. The result is not HTML-encoded, so encode it with `String.encode()` when you write it back into HTML.\n\nExample: Strip tags\n```js\n'<p><b>Hi</b> there</p>'.removeTags();\n// Hi there\n```\n\n### str.padLeft(max, [c])\n\nType: `method`\n\nPads the text on the left to a length. String.padRight() pads on the right.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | The length of the result. |\n| `c` | `String` | no | `' '` | The padding character. |\n\nReturns: `String` The padded text.\n\nCharacters `c` are added until the text has `max` characters; longer text is returned unchanged. `str.padRight(max, [c])` works the same way on the right side. Both are defined only when the runtime does not already have them.\n\nExample: Pad\n```js\n'5'.padLeft(3, '0');   // 005\n'a'.padRight(3, '-');  // a--\n```\n\n### str.toASCII()\n\nType: `method`\n\nReplaces letters with diacritics by their ASCII form.\n\nReturns: `String` The text without diacritics.\n\nLetters such as `č`, `á` or `ü` are replaced with `c`, `a` and `u`. Characters without an ASCII form stay as they are.\n\nExample: Remove diacritics\n```js\n'Čučoriedka'.toASCII();\n// Cucoriedka\n```\n\n### str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtracts keywords from the text, the most frequent first.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forsearch` | `Boolean` | no | `true` | Normalize the words for search. |\n| `alternative` | `Boolean` | no | `false` | Shorten words to 80 % of their length. |\n| `max_count` | `Number` | no | `200` | The maximum number of words to read. |\n| `max_length` | `Number` | no | `20` | The maximum length of a keyword. |\n| `min_length` | `Number` | no | `2` | The minimum length of a keyword. |\n\nReturns: `Array` Unique keywords sorted by frequency.\n\nThe text is lowercased and split into words; characters that are not letters or digits are removed from each word. With `forsearch` (default) diacritics are removed and `y` becomes `i`, which makes matching tolerant. `alternative` keeps only the first 80 % of longer words (a simple stem). Words shorter than `min_length` or longer than `max_length` are skipped and at most `max_count` words are read. The unique words are returned sorted by how often they appear.\n\nFor a single normalized search string use `str.toSearch()`: it lowercases the text, removes diacritics and symbols, replaces `y` with `i` and drops repeated letters (`hello` becomes `helo`).\n\nExample: Keywords for a search index\n```js\n'Total.js is a great framework, great!'.toKeywords();\n// ['great', 'totaljs', 'is', 'framework']\n\n'Čaute Hello'.toSearch();\n// caute helo\n```\n\n### str.pluralize(zero, one, few, other)\n\nType: `method`\n\nConverts the text to a number and picks a plural form.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Text for 0, or all four forms separated by commas. |\n| `one` | `String` | no |  | Text for 1. |\n| `few` | `String` | no |  | Text for 2 to 4. |\n| `other` | `String` | no |  | Text for other numbers. |\n\nReturns: `String` The chosen form.\n\nThe text is converted with `parseInt()` and the result is passed to `Number.pluralize()`.\n\nExample: Pluralize a string\n```js\n'3'.pluralize('no items', '# item', '# items', '# items');\n// 3 items\n```\n\n### str.parseInt([def])\n\nType: `method`\n\nConverts the text to a number, with a default for invalid text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | The value for text that is not a number. |\n\nReturns: `Number` The number or the default.\n\nThe text is trimmed and converted with the unary `+`, so `'10'` is `10`, `'1.5'` is `1.5` and `'0x10'` is `16`. When the text is not a number, `def` is returned (`0` when you omit it).\n\n`str.parseInt2([def])` finds the first integer anywhere in the text instead (`'abc 123'` gives `123`); `str.parseFloat2([def])` does the same for a decimal number and accepts `,` as the decimal separator.\n\nExample: Read numbers\n```js\n'10'.parseInt();        // 10\n'abc'.parseInt(5);      // 5\n'Total: 123 EUR'.parseInt2(); // 123\n'x 1,5 y'.parseFloat2();      // 1.5\n```\n\n### str.parseFloat([def])\n\nType: `method`\n\nConverts the text to a decimal number; a comma is accepted as the decimal separator.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | The value for text that is not a number. |\n\nReturns: `Number` The number or the default.\n\nThe text is trimmed, the first `,` is replaced with `.` and the text is converted to a number. When the text is not a number, `def` is returned (`0` when you omit it).\n\nExample: Read decimals\n```js\n'1,5'.parseFloat();    // 1.5\n' 2.25 '.parseFloat(); // 2.25\n'n/a'.parseFloat(-1);  // -1\n```\n\n### str.parseBoolean()\n\nType: `method`\n\nConverts the text to a boolean.\n\nReturns: `Boolean`\n\nReturns `true` for `true`, `1` and `on` (case-insensitive) and `false` for everything else.\n\nExample: Read a flag\n```js\n'on'.parseBoolean();    // true\n'TRUE'.parseBoolean();  // true\n'no'.parseBoolean();    // false\n```\n\n### str.parseDate([format])\n\nType: `method`\n\nConverts the text to a Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | A format such as `dd/MM/yyyy HH:mm`. |\n\nReturns: `Date` The parsed date.\n\nWithout `format` the method understands:\n\n- JSON dates (`2024-05-01T12:30:00.000Z`),\n- `yyyy-MM-dd`, `yyyy-MM-dd HH:mm`, `yyyy-MM-dd HH:mm:ss` and `yyyy-MM-ddTHH:mm:ss.SSS`,\n- `d.M.yyyy` with an optional time (`1.5.2024 08:00`),\n- anything else that `new Date(text)` accepts.\n\nThe date and time of these forms are read as UTC. Missing parts of the date are taken from today.\n\nWith `format` the digits of the text are read by the positions of `yyyy`, `MM`, `dd`, `HH`, `mm` and `ss` in the format; the other characters of the format only separate the parts. The parts must be written with all their digits (`05`, not `5`). A two-digit year is in the 2000s, and `pm` in the text adds 12 hours.\n\nExample: Parse dates\n```js\n'2024-05-01 12:30'.parseDate();\n// 2024-05-01T12:30:00.000Z\n\n'1.5.2024'.parseDate();\n// 2024-05-01T00:00:00.000Z\n\n'01/05/2024'.parseDate('dd/MM/yyyy');\n// 1 May 2024\n```\n\n### str.parseDateExpiration()\n\nType: `method`\n\nConverts a relative time such as \"5 minutes\" to a Date in the future.\n\nReturns: `Date` The current time plus the given duration.\n\nThe text is a list of pairs `number unit` separated by spaces. Each pair is added to the current time with `Date.add()`, so all units of `Date.add()` work (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years` and their short forms). Use a negative number for a date in the past.\n\nExample: Expiration\n```js\nvar expire = '5 minutes'.parseDateExpiration();\nvar later = '1 day 2 hours'.parseDateExpiration();\n```\n\n### str.parseJSON([date])\n\nType: `method`\n\nParses JSON without throwing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | Convert JSON date strings to Date objects. |\n\nReturns: `Object` The parsed value or `undefined`.\n\nReturns the parsed value, or `undefined` when the text is not valid JSON. With `date` set to `true`, strings in the JSON date format (`2024-01-01T10:00:00.000Z`) become `Date` objects.\n\nExample: Safe parse\n```js\nvar obj = '{\"a\":1}'.parseJSON();          // { a: 1 }\nvar bad = '{a:1'.parseJSON();             // undefined\nvar doc = '{\"created\":\"2024-01-01T10:00:00.000Z\"}'.parseJSON(true);\ndoc.created instanceof Date;             // true\n```\n\n### str.parseCSV([delimiter])\n\nType: `method`\n\nParses CSV text into an array of objects with column keys a, b, c, ...\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | The column delimiter, one character. |\n\nReturns: `Array` An array of objects.\n\nEach line becomes an object. The keys are column letters: `a` for the first column, `b` for the second, ..., `z`, then `aa`, `ab` and so on. Values in double quotes may contain the delimiter and new lines; `\"\"` inside quotes is an escaped quote. Empty columns have no key in the object. Values are strings and are not trimmed. A header line is returned like any other line.\n\nExample: Parse CSV\n```js\nvar rows = 'name,age\\n\"Sirka, Peter\",40\\nAnna,'.parseCSV();\n// [{ a: 'name', b: 'age' }, { a: 'Sirka, Peter', b: '40' }, { a: 'Anna' }]\n\nvar header = rows.shift();\nfor (var row of rows)\n\tconsole.log(row.a, row.b || '-');\n```\n\n### str.parseContext()\n\nType: `method` · Since: `0.0.17`\n\nParses a text made of blocks with a header and a body.\n\nReturns: `Array` An array of objects, one per block.\n\nEach block starts with a line of at least 20 dashes, followed by header lines `key: value`, another line of at least 20 dashes and the body. The body ends where the next block starts. Every block becomes an object with the header keys (lowercased, values trimmed) and a `body` property with the trimmed body. Header lines without `:` are ignored.\n\nExample: Parse blocks\n```js\nvar text = [\n\t'--------------------',\n\t'Name: Hello',\n\t'Type: note',\n\t'--------------------',\n\t'Body one',\n\t'--------------------',\n\t'Name: Second',\n\t'--------------------',\n\t'Body two'\n].join('\\n');\n\ntext.parseContext();\n// [{ name: 'Hello', type: 'note', body: 'Body one' }, { name: 'Second', body: 'Body two' }]\n```\n\n### str.parseEncoded()\n\nType: `method`\n\nParses URL-encoded text (a query string or a form body) into an object.\n\nReturns: `Object` The parsed keys and values (strings).\n\nPairs `key=value` are separated by `&`; keys and values are URL-decoded. This is the parser that Total.js uses for query strings and `application/x-www-form-urlencoded` bodies.\n\nExample: Parse a query string\n```js\n'q=total.js&page=2&name=%20Peter'.parseEncoded();\n// { q: 'total.js', page: '2', name: ' Peter' }\n```\n\n### str.parseConfig([def], [onerr])\n\nType: `method`\n\nParses text in the Total.js configuration format 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)` for values that cannot be evaluated. |\n\nReturns: `Object` The parsed values.\n\nEach line is `key : value`. The separator is the first `:`, or the first `=` when the line has no `:`; the value starts at the second character after the separator, so keep one space there. Empty lines and lines that start with `#` or `//` are skipped. A value that starts with `base64 ` or `hex ` is decoded.\n\nA type in brackets after the key converts the value: `(string)`, `(number)` (also `float`, `double`, `currency`), `(boolean)` / `(bool)` (true when the value contains `true`, `on`, `1` or `enabled`, in any case), `(json)`, `(object)` / `(array)` / `(eval)` (evaluated as JavaScript), `(date)`, `(env)` (reads `process.env[value]`), `(config)` (reads another configuration key) and `(random)` (a random string of the given length). When an evaluated value fails, `onerr(err, line)` is called, or an error is thrown without it.\n\nExample: Parse settings\n```js\nvar text = 'name : Shop\\ncount (number) : 10\\nenabled (boolean) : true\\n# comment\\ntags (array) : [\\'a\\', \\'b\\']';\ntext.parseConfig();\n// { name: 'Shop', count: 10, enabled: true, tags: ['a', 'b'] }\n```\n\n### str.parseEnv()\n\nType: `method`\n\nParses text in the .env format into an object.\n\nReturns: `Object` The keys and values.\n\nEach line is `KEY=value`. Lines that are empty or start with `#` or `//` are skipped. A value in single or double quotes is unquoted (its inner spaces are kept); other values are trimmed. `\\n` in a value becomes a new line. All values are strings.\n\nExample: Parse .env\n```js\n'PORT=8000\\nNAME=\"My app\"\\n# comment'.parseEnv();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### str.parseUA([structured])\n\nType: `method`\n\nReads the operating system, browser and device type from a User-Agent header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Return an object instead of text. |\n\nReturns: `String|Object`\n\nWithout arguments the result is a short text such as `Windows Chrome`. With `structured` set to `true` the result is an object `{ os, browser, device }`, where `device` is `mobile` or `desktop`. Empty text returns an empty string.\n\nExample: Read the user agent\n```js\nvar ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Version/17.0 Mobile Safari/604.1';\nua.parseUA();      // iPhone Safari\nua.parseUA(true);  // { os: 'iPhone', browser: 'Safari', device: 'mobile' }\n```\n\n### str.isEmail()\n\nType: `method`\n\nChecks that the text is an e-mail address.\n\nReturns: `Boolean`\n\nThe test uses the `email` regular expression of `DEF.validators`: letters, digits and `-_.+` before `@`, a domain and a top-level domain of at least two letters. Text of four characters or less is never valid.\n\nExample: Validate\n```js\n'info@example.com'.isEmail();  // true\n'info@example'.isEmail();      // false\n```\n\n### str.isPhone()\n\nType: `method`\n\nChecks that the text is a phone number.\n\nReturns: `Boolean`\n\nThe test uses the `phone` regular expression of `DEF.validators`: an optional `+`, three digits (optionally in brackets), three digits and 4 to 8 digits, each group optionally separated by `-`, `.` or a space. Text shorter than six characters is never valid.\n\nExample: Validate\n```js\n'+421903123456'.isPhone();  // true\n'(123) 456-7890'.isPhone(); // true\n'12345'.isPhone();          // false\n```\n\n### str.isURL()\n\nType: `method`\n\nChecks that the text is an http or https URL.\n\nReturns: `Boolean`\n\nThe text must start with `http://` or `https://` and must not contain `,`, `{`, `}` or `\\`. Text of seven characters or less is never valid.\n\nExample: Validate\n```js\n'https://www.totaljs.com'.isURL();  // true\n'www.totaljs.com'.isURL();          // false\n```\n\n### str.isUID()\n\nType: `method`\n\nChecks that the text is a valid identifier made by UID().\n\nReturns: `Boolean`\n\nThe method checks the format and the checksum of identifiers created by `UID()`, so a random string of the same shape is rejected. To read the date and index stored in a UID use `str.parseUID()`, which returns `{ version, date, century, hash, index, valid }`. For standard GUIDs (`8-4-4-4-12` hex digits) use `str.isGUID()`.\n\nExample: Validate an id\n```js\nvar id = UID();\nid.isUID();       // true\n'abc'.isUID();    // false\nid.parseUID().date;  // the time the id was created\n'123e4567-e89b-12d3-a456-426614174000'.isGUID(); // true\n```\n\n### str.isNumber([isDecimal])\n\nType: `method`\n\nChecks that the text contains only digits.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `isDecimal` | `Boolean` | no | `false` | Allow one decimal separator. |\n\nReturns: `Boolean`\n\nEvery character must be a digit. With `isDecimal` set to `true`, one `.` or `,` is allowed as well. A sign (`-`, `+`) is not allowed and empty text is not a number.\n\nExample: Validate\n```js\n'0123'.isNumber();      // true\n'1.5'.isNumber();       // false\n'1,5'.isNumber(true);   // true\n```\n\n### str.isJSON()\n\nType: `method`\n\nQuickly checks that the text looks like a JSON object, array or string.\n\nReturns: `Boolean`\n\nLeading and trailing white space is skipped and the first and last characters are compared: `{` with `}`, `[` with `]` or `\"` with `\"`. It is also `true` when the text starts with a digit or a letter and ends with a character below `9`, for example `'123'` or `'abc1'`. The content is not parsed, so use `String.parseJSON()` when you need to be sure.\n\nExample: Check before parsing\n```js\nvar body = ' {\"a\":1} ';\nif (body.isJSON())\n\tvar obj = body.parseJSON();\n```\n\n### str.isXSS()\n\nType: `method`\n\nChecks that the text contains an HTML tag.\n\nReturns: `Boolean`\n\nReturns `true` when the text contains `<` followed later by `>`, which is how the `xss` regular expression of `DEF.validators` detects markup in user input. `str.isSQLInjection()` works the same way with the `sqlinjection` expression: it is `true` for quoted strings and for the SQL keywords `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` and `UNION` written in uppercase. Both are simple filters, not a replacement for encoding output and for query parameters.\n\nExample: Reject markup\n```js\n'<script>alert(1)</script>'.isXSS();  // true\n'Hello'.isXSS();                      // false\n'DROP TABLE users'.isSQLInjection();   // true\n```\n\n### str.hash([type], [salt])\n\nType: `method`\n\nReturns a hash of the text: a fast number hash or an md5, sha1, sha256, sha512 or crc32 digest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32`, `crc32unsigned`, or `true` for an unsigned number hash. |\n| `salt` | `String` | no |  | Text appended before hashing. |\n\nReturns: `Number|String` A number for the number hash and crc32, a hex string otherwise.\n\n`type` selects the algorithm: `md5`, `sha1`, `sha256`, `sha512` (hex strings), `crc32` (signed number) or `crc32unsigned` (unsigned number). Without `type` the method returns a fast 32-bit number hash of the text (signed); `hash(true)` returns it unsigned. `salt` is appended to the text before hashing. The number hash is not a cryptographic hash: use it for cache keys and similar purposes. `str.crc32([unsigned])` is also available directly.\n\nExample: Hashes\n```js\n'hello'.hash();          // a signed 32-bit number\n'hello'.hash(true);      // the same, unsigned\n'hello'.hash('sha256');  // hex digest\n'hello'.hash('crc32unsigned');\n```\n\n### str.md5([salt])\n\nType: `method`\n\nReturns the MD5 digest of the text as a hex string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text appended before hashing. |\n\nReturns: `String` 32 hex characters.\n\nThe text (with `salt` appended) is hashed as UTF-8 with Node.js `crypto`. MD5 is suitable for checksums and cache keys, not for passwords.\n\nExample: MD5\n```js\n'a'.md5();\n// 0cc175b9c0f1b6a831c399e269772661\n```\n\n### str.sha256([salt])\n\nType: `method`\n\nReturns the SHA-256 digest of the text as a hex string. sha1() and sha512() work the same.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text appended before hashing. |\n\nReturns: `String` 64 hex characters.\n\nThe text (with `salt` appended) is hashed as UTF-8 with Node.js `crypto`. `str.sha1([salt])` returns 40 hex characters and `str.sha512([salt])` 128 hex characters.\n\nExample: SHA digests\n```js\nvar digest = 'password'.sha256(CONF.secret);\nvar short = 'text'.sha1();\nvar long = 'text'.sha512();\n```\n\n### str.sign([key], [check])\n\nType: `method`\n\nSigns the text with a short checksum, or checks and removes the signature.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | The signing key. |\n| `check` | `Boolean` | no | `false` | Check the signature and return the original text. |\n\nReturns: `String` The signed text, the original text, or `null`.\n\n`str.sign(key)` returns `text-checksum`, where the checksum is made from the text and `key`. `signed.sign(key, true)` checks the checksum and returns the original text, or `null` when the signature does not match. Use it for values that travel through URLs and must not be changed, such as ids in links. It is not encryption: the text stays readable.\n\n`str.makeid()` returns only a short base-36 checksum of the text, handy as a compact key.\n\nExample: Sign an id\n```js\nvar token = '123'.sign('mykey');     // 123-155hlxd\ntoken.sign('mykey', true);           // 123\n(token + 'x').sign('mykey', true);   // null\n```\n\n### str.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nEncrypts the text with a key. String.decrypt() reverses it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The encryption key. |\n| `isUnique` | `Boolean` | no | `false` | Make a different result for each call. |\n| `secret` | `String` | no | `CONF.secret` | The secret used in the checksum. |\n\nReturns: `String` The encrypted text.\n\nThe result is a string of a checksum, `-` and hex data. With `isUnique` set to `true`, the same text gives a different result each time. The checksum uses `secret`, or the `secret` configuration key when you omit it.\n\n`str.decrypt(key, [secret])` returns the original text, or `null` when the key, the secret or the data do not match. Use the same `key` and `secret` for both.\n\nExample: Encrypt and decrypt\n```js\nvar value = 'user@example.com'.encrypt('mykey', true);\nvalue.decrypt('mykey');   // user@example.com\nvalue.decrypt('other');   // null\n```\n\n### str.encrypt_uid([key])\n\nType: `method`\n\nEncrypts an identifier into a short URL-safe token. String.decrypt_uid() reverses it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | The key. |\n\nReturns: `String` The token.\n\nUse it to hide numeric or text ids in public URLs. `key` defaults to the `secret` configuration key. `token.decrypt_uid([key])` returns the original id, or `null` when the token was changed or the key is different.\n\nExample: Hide an id\n```js\nvar token = '123'.encrypt_uid('mykey');\ntoken.decrypt_uid('mykey');  // 123\n```\n\n### str.base64ToBuffer()\n\nType: `method`\n\nConverts base64 text or a data URI to a Buffer.\n\nReturns: `Buffer` The decoded data.\n\nEverything up to and including the first `,` is skipped, so both plain base64 and `data:...;base64,...` work. Related methods: `str.base64ToFile(filename, [callback])` writes the decoded data to a file, `str.base64ContentType()` returns the content type of a data URI (`image/png`), and `str.parseDataURI()` returns `{ type, buffer }` (or `null` for text that is not a data URI).\n\nExample: Decode an upload\n```js\nvar uri = 'data:text/plain;base64,aGVsbG8=';\nuri.base64ToBuffer().toString();   // hello\nuri.base64ContentType();           // text/plain\nuri.parseDataURI().type;           // text/plain\nuri.base64ToFile(PATH.temp('hello.txt'));\n```\n\n### num.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormats a number with a thousands separator and a fixed number of 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 thousands separator is a space by default. The decimal separator is `.`, or `,` when the thousands separator is `.`. Extra decimals are cut, not rounded, so call `Number.round()` first when you need rounding. Missing decimals are filled with zeros. When the first argument is a string, the first two arguments are swapped: `format('.', 2)` is the same as `format(2, '.')`.\n\nExample: Format\n```js\n(1234567.891).format(2);           // 1 234 567.89\n(1234.5).format(2, ',', '.');      // 1,234.50\n(1234.5).format('.', 2);           // 1.234,50\n(1.999).round(2).format(2);        // 2.00\n```\n\n### num.pluralize(zero, one, few, other)\n\nType: `method`\n\nPicks a plural form by the number; # is replaced with the number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Text for 0, or all four forms separated by commas. |\n| `one` | `String` | no |  | Text for 1. |\n| `few` | `String` | no |  | Text for 2 to 4. |\n| `other` | `String` | no |  | Text for other numbers. |\n\nReturns: `String` The chosen form.\n\nThe form `zero` is used for 0, `one` for 1, `few` for 2 to 4 and `other` for the rest (the rule of Slavic languages; for English pass the same text as `few` and `other`). When you pass only one string, it is split by commas into the four forms. The first `#` in the chosen form is replaced with the number.\n\nExample: Plural forms\n```js\n(1).pluralize('no items', '# item', '# items', '# items');  // 1 item\n(7).pluralize('no items,# item,# items,# items');          // 7 items\n```\n\n### num.padLeft(max, [c])\n\nType: `method`\n\nPads the number on the left with zeros. Number.padRight() pads on the right.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | The length of the result. |\n| `c` | `String` | no | `'0'` | The padding character. |\n\nReturns: `String` The padded number.\n\nThe number is converted to a string and padded to `max` characters with `c` (`0` by default). `num.padRight(max, [c])` pads on the right.\n\nExample: Zero padding\n```js\n(5).padLeft(3);       // 005\n(7).padLeft(4, ' ');  // '   7'\n(5).padRight(3);      // 500\n```\n\n### num.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` | yes |  | The number of decimals. |\n\nReturns: `Number` The rounded number.\n\nRounding uses exponent notation, so values like `1.005` round correctly to `1.01`. `num.floor(decimals)` rounds down to a number of decimals instead (`(1.239).floor(2)` is `1.23`).\n\nExample: Round\n```js\n(1.005).round(2);  // 1.01\n(2.5).round(0);    // 3\n(1.239).floor(2);  // 1.23\n```\n\n### num.fixed(decimals)\n\nType: `method`\n\nRounds the number with toFixed() and returns a number, not a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | The number of decimals. |\n\nReturns: `Number`\n\nExample: Fixed\n```js\n(1.236).fixed(2);  // 1.24 (a number)\n```\n\n### num.between(condition, [otherwise])\n\nType: `method`\n\nReturns the value of the first range that contains the number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Ranges as keys, results as values. |\n| `otherwise` | `Any` | no |  | The result when no range matches. |\n\nReturns: `Any` The value of the matching range or `otherwise`.\n\n`condition` is an object whose keys are ranges: `'1-3'` (from 1 to 3, both included), `'7-'` (7 and more) or `'-5'` (5 and less). The keys are tested in order and the value of the first matching key is returned. When no range matches, `otherwise` is returned.\n\nExample: Grade a score\n```js\nvar score = 5;\nscore.between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }, 'unknown');\n// medium\n```\n\n### num.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAdds a tax to the number, or removes it from a price that includes it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | The tax rate in percent. |\n| `decimals` | `Number` | no | `2` | The number of decimals. |\n| `includedVAT` | `Boolean` | no | `false` | The number already includes the tax. |\n\nReturns: `Number`\n\n`Number.TAX()` is the same method. Without `includedVAT` the result is the number increased by `percentage`. With `includedVAT` set to `true` the number is a price that already includes the tax, and the result is the price without the tax. The result is rounded to `decimals` (2 by default). You can pass the boolean as the second argument: `VAT(20, true)`.\n\nExample: Prices with VAT\n```js\n(100).VAT(20);        // 120\n(120).VAT(20, true);  // 100\n(99.99).TAX(10, 0);   // 110\n```\n\n### num.discount(percentage, [decimals])\n\nType: `method`\n\nReduces the number by a percentage.\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`\n\nThe result is rounded down to `decimals` (2 by default).\n\nExample: Discount\n```js\n(100).discount(15);    // 85\n(19.99).discount(10);  // 17.99\n```\n\n### num.filesize([decimals], [type])\n\nType: `method`\n\nFormats a number of bytes as a human-readable size.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | The number of decimals. |\n| `type` | `String` | no |  | `bytes`, `KB`, `MB`, `GB` or `TB`. |\n\nReturns: `String` The size with its unit.\n\nWithout `type` the largest fitting unit is chosen: `bytes`, `KB`, `MB`, `GB` or `TB` (1 KB is 1024 bytes). With `type` the value is converted to that unit. Without `decimals` the value has up to two decimals and `.00` is removed; with `decimals` it is formatted with `Number.format(decimals)`. The arguments can be passed in either order.\n\nExample: File sizes\n```js\n(500).filesize();          // 500 bytes\n(1536000).filesize();      // 1.46 MB\n(5000000).filesize(1, 'MB'); // 4.7 MB\n```\n\n### num.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormats the number as an amount with a currency formatter registered in DEF.currencies.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | The key in `DEF.currencies`. |\n| `a, b, c` | `Any` | no |  | Extra arguments for the formatter. |\n\nReturns: `String` The formatted amount.\n\nThe formatter is the function `DEF.currencies[currency]` (or `DEF.currencies.default` without `currency`). It receives the number and the arguments `a`, `b` and `c` and returns the text. When no formatter exists for the currency, the result is `num.format(2)`. Register formatters at startup, for example in a definition file.\n\nExample: Register and use a currency\n```js\n// /definitions/currencies.js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2, ' ', ',') + ' €';\n};\n\n(1234.5).currency('eur');  // 1 234,50 €\n(10).currency('usd');      // 10.00 (no formatter)\n```\n\n### date.add(type, [value])\n\nType: `method`\n\nReturns a new date shifted by an amount of time.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | The unit, a string with value and unit, or milliseconds. |\n| `value` | `Number` | no |  | The amount, negative for the past. |\n\nReturns: `Date` A new date.\n\nThe original date is not changed. Pass the unit and the value (`add('minutes', 30)`), one string with both (`add('30 minutes')`, `add('-2 hours')`) or a number of milliseconds (`add(5000)`).\n\nUnits: `s`, `ss`, `sec`, `second`, `seconds`; `m`, `mm`, `min`, `minute`, `minutes`; `h`, `hh`, `hour`, `hours`; `d`, `dd`, `day`, `days`; `w`, `ww`, `week`, `weeks`; `M`, `MM`, `month`, `months`; `y`, `yyyy`, `year`, `years`. The units work on the UTC parts of the date. Adding months to the end of a month follows JavaScript: 31 January plus one month is 2 March in a leap year and 3 March otherwise.\n\nExample: Shift dates\n```js\nvar now = new Date();\nnow.add('1 day');\nnow.add('minutes', 30);\nnow.add('-2 hours');\nnow.add(5000);  // + 5 seconds\n```\n\n### date.diff([date], type)\n\nType: `method`\n\nReturns the difference between two dates in seconds, minutes, hours or days.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String|Number` | no | `now` | The date to compare with. |\n| `type` | `String` | yes |  | The unit of the result. |\n\nReturns: `Number` The difference in the unit.\n\nThe result is `this - date` in the given unit, rounded up, so it is positive when `this` is later. `date` can be a Date, a string that `Date.parse()` understands or a number of milliseconds. With one argument the date is compared with the current time. Units: `s` / `ss` / `second` / `seconds`, `m` / `mm` / `minute` / `minutes`, `h` / `hh` / `hour` / `hours`, `d` / `dd` / `day` / `days`. An unknown unit returns `NaN`.\n\nExample: Differences\n```js\nvar created = new Date('2024-01-30T00:00:00Z');\nvar end = new Date('2024-01-31T10:00:00Z');\nend.diff(created, 'hours');  // 34\nend.diff('2024-01-01T00:00:00Z', 'days'); // 31\ncreated.diff('seconds');     // negative: created is in the past\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormats the date by a pattern; without a pattern returns an ISO string in UTC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | The pattern. |\n| `resource` | `String` | no |  | The resource used for month and day names. |\n\nReturns: `String` The formatted date.\n\nWithout `format` the result is `yyyy-MM-ddTHH:mm:ss.SSSZ` in UTC. With `format` the parts are written in the server time zone (UTC unless the `$timezone` configuration key says otherwise):\n\n- `yyyy`, `yy` year; `MM`, `M` month number; `MMMM` month name, `MMM` its first three letters,\n- `dd`, `d` day; `dddd` day name, `ddd` its first two letters in uppercase,\n- `HH`, `H` hours (0-23); `mm`, `m` minutes; `ss`, `s` seconds,\n- `ww`, `w` ISO week number; `a` `AM` or `PM`.\n\nUppercase `YYYY`, `YY`, `DD`, `D`, `DDDD`, `DDD` and lowercase `hh`, `h` are accepted too. Month and day names are English; with `resource` they are translated with the resource file of that name. Compiled formats are cached, so formatting is fast.\n\nExample: Format dates\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.format();                      // 2024-01-31T10:00:00.000Z\nd.format('yyyy-MM-dd HH:mm');    // 2024-01-31 10:00\nd.format('dd.MM.yy');            // 31.01.24\nd.format('dddd, d. MMMM yyyy');  // Wednesday, 31. January 2024\nd.format('MMMM', 'sk');          // the month name from sk.resource\n```\n\n### date.extend(text)\n\nType: `method`\n\nReturns a new date with the date or time parts replaced from a text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | A date, a time, or both. |\n\nReturns: `Date` A new date.\n\nThe text can contain a date `yyyy-MM-dd` or `d.M.yyyy` and a time `HH:mm` or `HH:mm:ss`. Only the parts found in the text are replaced; the others are taken from the original date. The year, month and day are set one after another, so when the day of the original date does not exist in the new month the date moves to the next month (31 January extended with `2025-02-10` gives 10 March 2025). The values are UTC.\n\nExample: Change parts\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.extend('12:30');              // 2024-01-31T12:30:00.000Z\nd.extend('2025-03-04');         // 2025-03-04T10:00:00.000Z\nd.extend('1.3.2020 08:00');     // 2020-03-01T08:00:00.000Z\n```\n\n### date.toUTC([ticks])\n\nType: `method`\n\nShifts a local date by the time zone offset to UTC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Return milliseconds. |\n\nReturns: `Date|Number`\n\nThe result is the date plus the offset of the server time zone. With `ticks` set to `true` the result is the number of milliseconds instead of a Date. On a server running in UTC (the default) the date does not change.\n\nExample: To UTC\n```js\nvar utc = new Date().toUTC();\nvar ms = new Date().toUTC(true);\n```\n\n### date.setTimeZone(timezone)\n\nType: `method`\n\nReturns a new date that shows the same moment in another time zone.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | An IANA time zone name. |\n\nReturns: `Date` A new date.\n\nThe parts of the result (hours, day, ...) read in the server time zone are the wall-clock time of `timezone` at that moment, so `format()` prints the local time of that zone. `timezone` is an IANA name such as `Europe/Bratislava` or `America/New_York`.\n\nExample: Show local time\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.setTimeZone('Europe/Bratislava').format('HH:mm');  // 11:00\n```\n\n### arr.findItem(cb, [value])\n\nType: `method`\n\nReturns the first item that matches, or null.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | A test function, a property name or a value. |\n| `value` | `Any` | no |  | The value of the property. |\n\nReturns: `Object` The item or `null`.\n\nPass a function `(item, index)`, a property name and a value (`('id', 5)` compares `item.id === 5`), or a single value that is compared with `===`.\n\nExample: Find an item\n```js\nvar users = [{ id: 1, name: 'Peter' }, { id: 2, name: 'Anna' }];\nusers.findItem('id', 2);                  // { id: 2, name: 'Anna' }\nusers.findItem(u => u.name === 'Peter');  // { id: 1, name: 'Peter' }\nusers.findItem('id', 9);                  // null\n```\n\n### arr.findAll(cb, [value])\n\nType: `method`\n\nReturns all items that match.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | A test function, a property name or a value. |\n| `value` | `Any` | no |  | The value of the property. |\n\nReturns: `Array` The matching items.\n\nPass a function `(item, index)`, a property name and a value (`('id', 5)` compares `item.id === 5`), or a single value that is compared with `===`. The result is a new array; the original array is not changed.\n\nExample: Filter\n```js\nvar items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }];\nitems.findAll('type', 'a').length;  // 2\n```\n\n### arr.findIndex(cb, [value])\n\nType: `method`\n\nReturns the index of the first item that matches, or -1.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | A test function, a property name or a value. |\n| `value` | `Any` | no |  | The value of the property. |\n\nReturns: `Number` The index or `-1`.\n\nPass a function `(item, index)`, a property name and a value (`('id', 5)` compares `item.id === 5`), or a single value that is compared with `===`. Total.js replaces the native `findIndex()` with this version (with a function it behaves like the native one); `arr.TfindIndex()` is the same method.\n\nExample: Index of an item\n```js\nvar users = [{ id: 1 }, { id: 2 }];\nvar index = users.findIndex('id', 2);  // 1\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### arr.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 test function or a property name. |\n| `value` | `Any` | yes |  | The value of the property (pass `undefined` with a function). |\n| `path` | `String` | yes |  | The property to return. |\n| `def` | `Any` | no |  | The default value. |\n\nReturns: `Any`\n\nThe item is found like in `Array.findItem()`. The result is `item[path]`, or `def` when no item matches or the property is `null` / `undefined`.\n\nExample: Read a property\n```js\nvar users = [{ id: 1, name: 'Peter' }];\nusers.findValue('id', 1, 'name');          // Peter\nusers.findValue('id', 9, 'name', 'guest');  // guest\n```\n\n### arr.remove(cb, [value])\n\nType: `method`\n\nReturns a new array without the items that match.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | A test function, a property name or a value. |\n| `value` | `Any` | no |  | The value of the property. |\n\nReturns: `Array` A new array without the matching items.\n\nPass a function `(item, index)`, a property name and a value (`('id', 5)` compares `item.id === 5`), or a single value that is compared with `===`. The original array is not changed, so assign the result.\n\nExample: Remove items\n```js\nvar users = [{ id: 1 }, { id: 2 }, { id: 3 }];\nusers = users.remove('id', 1);       // [{ id: 2 }, { id: 3 }]\nvar nums = [1, 2, 3, 2].remove(2);   // [1, 3]\n```\n\n### arr.quicksort([sort], [desc])\n\nType: `method`\n\nSorts the array in place by one or more properties.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Properties to sort by, or `true` for descending plain values. |\n| `desc` | `Boolean` | no | `false` | Descending order for `sort`. |\n\nReturns: `Array` The same array, sorted.\n\n`sort` is a comma-separated list of property names, each optionally with `_asc` or `_desc` (`'name'`, `'price_desc'`, `'group,date_desc'`). Nested properties with dots are supported (`'user.name'`). The type of each column (string, number, boolean or Date) is detected from the first value that is not null the first time a sort expression is used, and is kept for later sorts with the same expression; strings are compared with diacritics in mind. Passing `true` (or `2`) as the second argument sorts a single property in descending order.\n\nWithout `sort` the array of plain values is sorted ascending; `quicksort(true)` sorts it descending. The method returns the same array.\n\nExample: Sort objects\n```js\nvar products = [{ name: 'B', price: 10 }, { name: 'A', price: 20 }];\nproducts.quicksort('name');        // A, B\nproducts.quicksort('price_desc');  // 20, 10\nproducts.quicksort('name', true);  // B, A\n[3, 1, 2].quicksort();             // [1, 2, 3]\n```\n\n### arr.take(count)\n\nType: `method`\n\nReturns the first count items as a new array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | The number of items. |\n\nReturns: `Array`\n\nExample: Take\n```js\n[1, 2, 3, 4].take(2);  // [1, 2]\n```\n\n### arr.skip(count)\n\nType: `method`\n\nReturns the items after the first count items as a new array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | The number of items to skip. |\n\nReturns: `Array`\n\nCombine with `take()` for paging.\n\nExample: Paging\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### arr.first([def])\n\nType: `method`\n\nReturns the first item, or a default for an empty array. Array.last() returns the last one.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Any` | no |  | The value for an empty array. |\n\nReturns: `Any`\n\n`arr.last([def])` returns the last item or `def`.\n\nExample: First and last\n```js\n[1, 2].first();     // 1\n[].first('none');   // none\n[1, 2].last();      // 2\n```\n\n### arr.group(name)\n\nType: `method`\n\nGroups the items by a property.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The property to group by. |\n\nReturns: `Array` Groups `{ name, items }`.\n\nReturns an array of `{ name, items }` sorted by `name`. The value of the property is converted to a string; items without the property are in a group with an empty name.\n\nExample: Group\n```js\nvar items = [{ type: 'x', id: 1 }, { type: 'y', id: 2 }, { type: 'x', id: 3 }];\nitems.group('type');\n// [{ name: 'x', items: [...2 items] }, { name: 'y', items: [...1 item] }]\n```\n\n### arr.trim()\n\nType: `method`\n\nTrims strings and returns a new array without empty values.\n\nReturns: `Array`\n\nStrings in the original array are trimmed in place. The result contains only truthy items, so empty strings, `null`, `undefined`, `0` and `false` are left out.\n\nExample: Clean a list\n```js\n' a , ,b'.split(',').trim();  // ['a', 'b']\n```\n\n### arr.random([item])\n\nType: `method`\n\nShuffles the array in place, or returns one random item.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Boolean` | no | `false` | Return one random item. |\n\nReturns: `Array|Any`\n\nWithout arguments the array is shuffled (Fisher-Yates) and returned. With `item` set to `true` one random item is returned and the array is not changed.\n\nExample: Random\n```js\nvar colors = ['red', 'green', 'blue'];\ncolors.random(true);  // one color\ncolors.random();      // the shuffled array\n```\n\n### arr.wait(onItem, [callback], [thread])\n\nType: `method`\n\nProcesses the items one by one with an asynchronous function.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | `function(item, next)`. |\n| `callback` | `Function` | no |  | Called when all items are processed. |\n| `thread` | `Number|Boolean` | no | `1` | Parallel items, or `true` to remove items as they are processed. |\n\nReturns: `Array` The array.\n\n`onItem(item, next)` is called for each item; call `next()` to continue with the next item. `callback()` is called when all items are done. `thread` sets how many items run at the same time (1 by default). With `thread` set to `true` the items are removed from the array with `shift()` as they are processed. Call `next('cancel')` to stop: `callback('cancel')` is then called.\n\nExample: Process in sequence\n```js\nvar ids = [1, 2, 3];\nids.wait(function(id, next) {\n\tFUNC.removeuser(id, next);\n}, function() {\n\tconsole.log('All removed');\n});\n```\n\nExample: Two at a time\n```js\nurls.wait(function(url, next) {\n\tREQUEST({ url: url, callback: () => next() });\n}, () => console.log('done'), 2);\n```\n\n### arr.async([thread], [callback])\n\nType: `method`\n\nRuns an array of functions one after another.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | How many functions run at the same time. |\n| `callback` | `Function` | no |  | Called at the end. |\n\nReturns: `Array` The array.\n\nEach item is a function `(next)`; call `next()` when it finishes. The functions are removed from the array as they run, so the array is empty at the end. `thread` sets how many functions start at the same time (1 by default). `callback()` is called when all functions are done, or `callback('cancel')` when one calls `next('cancel')`.\n\nExample: Run tasks\n```js\nvar tasks = [];\ntasks.push(function(next) {\n\tconsole.log('first');\n\tnext();\n});\ntasks.push(function(next) {\n\tsetTimeout(next, 100);\n});\ntasks.async(function() {\n\tconsole.log('done');\n});\n```\n\n### arr.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 |  | `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Called at the end. |\n\nReturns: `Array` The array.\n\n`fn(items, next, beg, end)` receives the next chunk and the start and end index; call `next()` to continue. `callback()` is called after the last chunk.\n\nExample: Insert in batches\n```js\nrows.limit(100, function(items, next) {\n\tFUNC.importrows(items, next);\n}, function() {\n\tconsole.log('Imported');\n});\n```\n","entries":[{"type":"method","name":"String.format()","signature":"str.format(arg0, [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"str.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"str.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"str.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"str.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"str.toName()","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"str.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"str.decode()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"str.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"str.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"str.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.toKeywords()","signature":"str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"str.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"str.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"str.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"str.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"str.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"str.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"str.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"str.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseContext()","signature":"str.parseContext()","since":"0.0.17","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"str.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"str.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseEnv()","signature":"str.parseEnv()","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"str.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"str.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"str.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"str.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"str.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"str.isNumber([isDecimal])","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"str.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"str.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"str.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"str.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"str.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"str.sign([key], [check])","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"str.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"str.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"str.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"num.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"num.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"num.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"num.round(precision)","since":"","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"num.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"num.between(condition, [otherwise])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"num.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"num.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"num.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"num.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"date.extend(text)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"arr.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"arr.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"arr.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"arr.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"arr.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"arr.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"arr.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"arr.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"arr.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.group()","signature":"arr.group(name)","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"arr.trim()","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"arr.random([item])","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"arr.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"arr.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"arr.limit(max, fn, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JacXWy2qt61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/prototypes/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Prototypen","summary":"Jede Methode, die Total.js zu String, Number, Date und Array.prototype hinzufügt.","markdown":"---\ntitle: Prototypen\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/prototypes/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Prototypen\n\n> Jede Methode, die Total.js zu String, Number, Date und Array.prototype hinzufügt.\n\nMethoden, die Total.js 5 zu den eingebauten Prototypen `String`, `Number`, `Date` und `Array` hinzufügt. Sie sind überall verfügbar, sobald das Framework geladen ist. Der Leitfaden [Prototypen](../../guides/prototypes/) zeigt mit Beispielen, wie du sie zusammen verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### str.format(arg0, [arg1], [...])\n\nType: `method`\n\nErsetzt nummerierte Platzhalter {0}, {1}, ... durch die Argumente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0...argN` | `Any` | yes |  | Werte für `{0}`, `{1}` und so weiter. |\n\nReturns: `String` Der neue String.\n\nJedes `{n}` wird durch das Argument mit dem Index `n` ersetzt. Ein Platzhalter, dessen Argument `null` oder `undefined` ist, wird zu einem leeren String. In den Klammern sind nur Zahlen erlaubt; verwende `String.args()` für benannte Schlüssel.\n\nExample: Nummerierte Platzhalter\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n// Hello Peter, you have 5 messages.\n```\n\n### str.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` | `String|Function` | no |  | `html`, `json`, eine Funktion `(value, key)` oder ein beliebiger anderer String für URL-Kodierung. |\n| `def` | `String` | no |  | Der Text für Schlüssel ohne Wert. |\n\nReturns: `String` Der neue String.\n\n`String.arg()` ist dieselbe Methode. Ein Platzhalter ist ein Schlüssel in einfachen oder doppelten geschweiften Klammern; Leerzeichen innerhalb der Klammern werden abgeschnitten. Schlüssel werden direkt aus `obj` gelesen (keine verschachtelten Pfade).\n\n`encode` ändert die Ausgabe jedes Werts: `'html'` codiert ihn mit `String.encode()`, `'json'` schreibt `JSON.stringify(value)`, jeder andere truthy String verwendet `encodeURIComponent()`, und eine Funktion `(value, key)` gibt den Text selbst zurück. Ist `encode` ein String, ersetzt er auch `def`: Mit `'html'` oder einem URL-Codierungs-String wird ein Schlüssel ohne Wert zum Text von `encode`; mit `'json'` wird er zu `undefined`. Ohne `encode` bleibt ein Schlüssel ohne Wert, wie er ist, oder wird durch `def` ersetzt, wenn du es übergibst.\n\nExample: Benannte Platzhalter\n```js\nvar tpl = 'Hello {name}, your order {{ id }} is ready.';\ntpl.args({ name: 'Peter', id: 'A100' });\n// Hello Peter, your order A100 is ready.\n\n'<b>{name}</b>'.args({ name: '<script>' }, 'html');\n// <b>&lt;script&gt;</b>\n```\n\n### str.slug([max])\n\nType: `method`\n\nErstellt aus dem Text einen URL-freundlichen Slug.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | Die maximale Länge des Slugs. |\n\nReturns: `String` Der Slug.\n\nDer Text wird getrimmt, in Kleinbuchstaben umgewandelt, und diakritische Zeichen werden entfernt (`toASCII()`). Buchstaben, Ziffern und `_` bleiben erhalten; Leerzeichen und die Zeichen `!\"#$%&'()*+,-./` werden zu einem einzelnen `-`; andere Zeichen werden verworfen. Ein `-` am Ende wird entfernt, und das Ergebnis hat höchstens `max` Zeichen.\n\nEnthält der Text ein Zeichen ohne ASCII-Form, dessen Code über 540 liegt (zum Beispiel kyrillische Buchstaben, `€` oder ein Emoji), wird nicht der ganze Text Buchstabe für Buchstabe umgewandelt: Die Methode gibt dann einen kurzen, aus dem Text gebildeten Hash-basierten Bezeichner zurück, sodass das Ergebnis trotzdem stabil und URL-sicher ist.\n\nExample: Einen Titel in einen Slug umwandeln\n```js\n' Hello World! Čaute 123 '.slug();\n// hello-world-caute-123\n\n'A very long article title'.slug(10);\n// a-very-lon\n```\n\n### str.max(length, [chars])\n\nType: `method`\n\nKürzt den Text auf eine maximale Länge und fügt Auslassungspunkte hinzu.\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 Text, bei Bedarf gekürzt.\n\nWenn der Text länger als `length` ist, wird er so gekürzt, dass das Ergebnis einschließlich `chars` genau `length` Zeichen hat. Kürzerer Text wird unverändert zurückgegeben.\n\nExample: Kürzen\n```js\n'Hello world'.max(8);       // Hello...\n'Hello world'.max(8, '…');  // Hello w…\n```\n\n### str.capitalize([first])\n\nType: `method`\n\nSchreibt den ersten Buchstaben jedes Wortes oder nur des Textes groß.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Nur das erste Zeichen großschreiben. |\n\nReturns: `String` Der neue String.\n\nDer Text wird zuerst in Kleinbuchstaben umgewandelt. Ohne Argumente wird jeder Buchstabe nach einem Leerzeichen, Tabulator oder Zeilenumbruch großgeschrieben. Mit `first` auf `true` wird nur das erste Zeichen großgeschrieben und der Rest bleibt klein.\n\nExample: Großschreiben\n```js\n'hello WORLD'.capitalize();      // Hello World\n'hello WORLD'.capitalize(true);  // Hello world\n```\n\n### str.toName()\n\nType: `method`\n\nBereinigt einen Personennamen: entfernt Ziffern und Symbole sowie überzählige Leerzeichen und schreibt Wörter groß.\n\nReturns: `String` Der bereinigte Name.\n\nNur ASCII-Buchstaben, Zeichen über Code 127 (Buchstaben mit diakritischen Zeichen) und Leerzeichen bleiben erhalten. Wiederholte Leerzeichen werden auf eines reduziert, Leerzeichen am Ende entfernt (führende Leerzeichen werden zu einem Leerzeichen), und der erste Buchstabe jedes Worts wird großgeschrieben. Der Rest jedes Worts bleibt, wie er ist.\n\nExample: Einen Namen bereinigen\n```js\n'peter   sirka 12'.toName();\n// Peter Sirka\n```\n\n### str.encode()\n\nType: `method`\n\nKodiert HTML-Sonderzeichen.\n\nReturns: `String` Der kodierte Text.\n\n`String.safehtml()` ist dieselbe Methode. Die Zeichen `<`, `>`, `\"`, `'` und `&` werden durch `&lt;`, `&gt;`, `&quot;`, `&apos;` und `&amp;` ersetzt. Verwende sie, bevor du Benutzertext in HTML einfügst.\n\nExample: Benutzereingaben kodieren\n```js\n'<a href=\"x\">Tom & Jerry</a>'.encode();\n// &lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/a&gt;\n```\n\n### str.decode()\n\nType: `method`\n\nDekodiert HTML-Entitäten zurück in Zeichen.\n\nReturns: `String` Der dekodierte Text.\n\nBenannte Entitäten (`&lt;`, `&amp;`, `&quot;`, ...) und numerische Entitäten (`&#65;`, `&#x41;`) werden durch ihre Zeichen ersetzt. Unbekannte benannte Entitäten bleiben unverändert.\n\nExample: Dekodieren\n```js\n'&lt;b&gt;Tom &amp; Jerry&#33;&lt;/b&gt;'.decode();\n// <b>Tom & Jerry!</b>\n```\n\n### str.removeTags()\n\nType: `method`\n\nEntfernt HTML-Tags aus dem Text.\n\nReturns: `String` Der Text ohne Tags.\n\nJedes Tag `<...>` (öffnend oder schließend) wird entfernt; der Text zwischen den Tags bleibt. Das Ergebnis ist nicht HTML-kodiert, also kodiere es mit `String.encode()`, wenn du es zurück in HTML schreibst.\n\nExample: Tags entfernen\n```js\n'<p><b>Hi</b> there</p>'.removeTags();\n// Hi there\n```\n\n### str.padLeft(max, [c])\n\nType: `method`\n\nFüllt den Text links bis zu einer Länge auf. String.padRight() füllt rechts auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Die Länge des Ergebnisses. |\n| `c` | `String` | no | `' '` | Das Füllzeichen. |\n\nReturns: `String` Der aufgefüllte Text.\n\nZeichen `c` werden hinzugefügt, bis der Text `max` Zeichen hat; längerer Text wird unverändert zurückgegeben. `str.padRight(max, [c])` funktioniert genauso auf der rechten Seite. Beide werden nur definiert, wenn die Laufzeitumgebung sie nicht bereits hat.\n\nExample: Auffüllen\n```js\n'5'.padLeft(3, '0');   // 005\n'a'.padRight(3, '-');  // a--\n```\n\n### str.toASCII()\n\nType: `method`\n\nErsetzt Buchstaben mit diakritischen Zeichen durch ihre ASCII-Form.\n\nReturns: `String` Der Text ohne diakritische Zeichen.\n\nBuchstaben wie `č`, `á` oder `ü` werden durch `c`, `a` und `u` ersetzt. Zeichen ohne ASCII-Form bleiben unverändert.\n\nExample: Diakritische Zeichen entfernen\n```js\n'Čučoriedka'.toASCII();\n// Cucoriedka\n```\n\n### str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrahiert Schlüsselwörter aus dem Text, die häufigsten zuerst.\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` | Wörter auf 80 % ihrer Länge kürzen. |\n| `max_count` | `Number` | no | `200` | Die maximale Anzahl zu lesender Wörter. |\n| `max_length` | `Number` | no | `20` | Die maximale Länge eines Schlüsselworts. |\n| `min_length` | `Number` | no | `2` | Die minimale Länge eines Schlüsselworts. |\n\nReturns: `Array` Eindeutige Schlüsselwörter, nach Häufigkeit sortiert.\n\nDer Text wird in Kleinbuchstaben umgewandelt und in Wörter zerlegt; Zeichen, die keine Buchstaben oder Ziffern sind, werden aus jedem Wort entfernt. Mit `forsearch` (Standard) werden diakritische Zeichen entfernt und `y` wird zu `i`, was den Abgleich tolerant macht. `alternative` behält nur die ersten 80 % längerer Wörter (ein einfacher Wortstamm). Wörter, die kürzer als `min_length` oder länger als `max_length` sind, werden übersprungen, und es werden höchstens `max_count` Wörter gelesen. Die eindeutigen Wörter werden nach ihrer Häufigkeit sortiert zurückgegeben.\n\nFür einen einzelnen normalisierten Suchstring verwende `str.toSearch()`: Es wandelt den Text in Kleinbuchstaben um, entfernt diakritische Zeichen und Symbole, ersetzt `y` durch `i` und entfernt wiederholte Buchstaben (`hello` wird zu `helo`).\n\nExample: Schlüsselwörter für einen Suchindex\n```js\n'Total.js is a great framework, great!'.toKeywords();\n// ['great', 'totaljs', 'is', 'framework']\n\n'Čaute Hello'.toSearch();\n// caute helo\n```\n\n### str.pluralize(zero, one, few, other)\n\nType: `method`\n\nWandelt den Text in eine Zahl um und wählt eine Pluralform.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Text für 0 oder alle vier Formen durch Kommas getrennt. |\n| `one` | `String` | no |  | Text für 1. |\n| `few` | `String` | no |  | Text für 2 bis 4. |\n| `other` | `String` | no |  | Text für andere Zahlen. |\n\nReturns: `String` Die gewählte Form.\n\nDer Text wird mit `parseInt()` umgewandelt und das Ergebnis an `Number.pluralize()` übergeben.\n\nExample: Einen String pluralisieren\n```js\n'3'.pluralize('no items', '# item', '# items', '# items');\n// 3 items\n```\n\n### str.parseInt([def])\n\nType: `method`\n\nWandelt den Text in eine Zahl um, mit einem Standardwert für ungültigen Text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Der Wert für Text, der keine Zahl ist. |\n\nReturns: `Number` Die Zahl oder der Standardwert.\n\nDer Text wird getrimmt und mit dem unären `+` umgewandelt, also ist `'10'` gleich `10`, `'1.5'` gleich `1.5` und `'0x10'` gleich `16`. Wenn der Text keine Zahl ist, wird `def` zurückgegeben (`0`, wenn du es weglässt).\n\n`str.parseInt2([def])` findet stattdessen die erste ganze Zahl irgendwo im Text (`'abc 123'` ergibt `123`); `str.parseFloat2([def])` macht dasselbe für eine Dezimalzahl und akzeptiert `,` als Dezimaltrennzeichen.\n\nExample: Zahlen lesen\n```js\n'10'.parseInt();        // 10\n'abc'.parseInt(5);      // 5\n'Total: 123 EUR'.parseInt2(); // 123\n'x 1,5 y'.parseFloat2();      // 1.5\n```\n\n### str.parseFloat([def])\n\nType: `method`\n\nWandelt den Text in eine Dezimalzahl um; ein Komma wird als Dezimaltrennzeichen akzeptiert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Der Wert für Text, der keine Zahl ist. |\n\nReturns: `Number` Die Zahl oder der Standardwert.\n\nDer Text wird getrimmt, das erste `,` wird durch `.` ersetzt und der Text wird in eine Zahl umgewandelt. Wenn der Text keine Zahl ist, wird `def` zurückgegeben (`0`, wenn du es weglässt).\n\nExample: Dezimalzahlen lesen\n```js\n'1,5'.parseFloat();    // 1.5\n' 2.25 '.parseFloat(); // 2.25\n'n/a'.parseFloat(-1);  // -1\n```\n\n### str.parseBoolean()\n\nType: `method`\n\nWandelt den Text in einen booleschen Wert um.\n\nReturns: `Boolean`\n\nGibt `true` für `true`, `1` und `on` zurück (ohne Berücksichtigung der Groß- und Kleinschreibung) und `false` für alles andere.\n\nExample: Ein Flag lesen\n```js\n'on'.parseBoolean();    // true\n'TRUE'.parseBoolean();  // true\n'no'.parseBoolean();    // false\n```\n\n### str.parseDate([format])\n\nType: `method`\n\nWandelt den Text in ein Date um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Ein Format wie `dd/MM/yyyy HH:mm`. |\n\nReturns: `Date` Das geparste Datum.\n\nOhne `format` versteht die Methode:\n\n- JSON-Datumswerte (`2024-05-01T12:30:00.000Z`),\n- `yyyy-MM-dd`, `yyyy-MM-dd HH:mm`, `yyyy-MM-dd HH:mm:ss` und `yyyy-MM-ddTHH:mm:ss.SSS`,\n- `d.M.yyyy` mit optionaler Uhrzeit (`1.5.2024 08:00`),\n- alles andere, was `new Date(text)` akzeptiert.\n\nDatum und Uhrzeit dieser Formen werden als UTC gelesen. Fehlende Teile des Datums werden vom heutigen Tag übernommen.\n\nMit `format` werden die Ziffern des Textes anhand der Positionen von `yyyy`, `MM`, `dd`, `HH`, `mm` und `ss` im Format gelesen; die anderen Zeichen des Formats trennen nur die Teile. Die Teile müssen mit allen Ziffern geschrieben werden (`05`, nicht `5`). Ein zweistelliges Jahr liegt in den 2000ern, und `pm` im Text addiert 12 Stunden.\n\nExample: Datumswerte parsen\n```js\n'2024-05-01 12:30'.parseDate();\n// 2024-05-01T12:30:00.000Z\n\n'1.5.2024'.parseDate();\n// 2024-05-01T00:00:00.000Z\n\n'01/05/2024'.parseDate('dd/MM/yyyy');\n// 1 May 2024\n```\n\n### str.parseDateExpiration()\n\nType: `method`\n\nWandelt eine relative Zeit wie \"5 minutes\" in ein Date in der Zukunft um.\n\nReturns: `Date` Die aktuelle Zeit plus die angegebene Dauer.\n\nDer Text ist eine Liste von Paaren `number unit`, getrennt durch Leerzeichen. Jedes Paar wird mit `Date.add()` zur aktuellen Zeit addiert, daher funktionieren alle Einheiten von `Date.add()` (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years` und ihre Kurzformen). Verwende eine negative Zahl für ein Datum in der Vergangenheit.\n\nExample: Ablauf\n```js\nvar expire = '5 minutes'.parseDateExpiration();\nvar later = '1 day 2 hours'.parseDateExpiration();\n```\n\n### str.parseJSON([date])\n\nType: `method`\n\nParst JSON, ohne einen Fehler zu werfen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | JSON-Datumsstrings in Date-Objekte umwandeln. |\n\nReturns: `Object` Der geparste Wert oder `undefined`.\n\nGibt den geparsten Wert zurück oder `undefined`, wenn der Text kein gültiges JSON ist. Mit `date` auf `true` werden Strings im JSON-Datumsformat (`2024-01-01T10:00:00.000Z`) zu `Date`-Objekten.\n\nExample: Sicheres Parsen\n```js\nvar obj = '{\"a\":1}'.parseJSON();          // { a: 1 }\nvar bad = '{a:1'.parseJSON();             // undefined\nvar doc = '{\"created\":\"2024-01-01T10:00:00.000Z\"}'.parseJSON(true);\ndoc.created instanceof Date;             // true\n```\n\n### str.parseCSV([delimiter])\n\nType: `method`\n\nParst CSV-Text in ein Array von Objekten mit den Spaltenschlüsseln a, b, c, ...\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | Das Spaltentrennzeichen, ein Zeichen. |\n\nReturns: `Array` Ein Array von Objekten.\n\nJede Zeile wird zu einem Objekt. Die Schlüssel sind Spaltenbuchstaben: `a` für die erste Spalte, `b` für die zweite, ..., `z`, dann `aa`, `ab` und so weiter. Werte in doppelten Anführungszeichen dürfen das Trennzeichen und Zeilenumbrüche enthalten; `\"\"` innerhalb von Anführungszeichen ist ein maskiertes Anführungszeichen. Leere Spalten haben keinen Schlüssel im Objekt. Werte sind Strings und werden nicht getrimmt. Eine Kopfzeile wird wie jede andere Zeile zurückgegeben.\n\nExample: CSV parsen\n```js\nvar rows = 'name,age\\n\"Sirka, Peter\",40\\nAnna,'.parseCSV();\n// [{ a: 'name', b: 'age' }, { a: 'Sirka, Peter', b: '40' }, { a: 'Anna' }]\n\nvar header = rows.shift();\nfor (var row of rows)\n\tconsole.log(row.a, row.b || '-');\n```\n\n### str.parseContext()\n\nType: `method` · Since: `0.0.17`\n\nParst einen Text aus Blöcken mit einem Header und einem Body.\n\nReturns: `Array` Ein Array von Objekten, eines pro Block.\n\nJeder Block beginnt mit einer Zeile aus mindestens 20 Bindestrichen, gefolgt von Header-Zeilen `key: value`, einer weiteren Zeile aus mindestens 20 Bindestrichen und dem Body. Der Body endet dort, wo der nächste Block beginnt. Jeder Block wird zu einem Objekt mit den Header-Schlüsseln (kleingeschrieben, Werte getrimmt) und einer Eigenschaft `body` mit dem getrimmten Body. Header-Zeilen ohne `:` werden ignoriert.\n\nExample: Blöcke parsen\n```js\nvar text = [\n\t'--------------------',\n\t'Name: Hello',\n\t'Type: note',\n\t'--------------------',\n\t'Body one',\n\t'--------------------',\n\t'Name: Second',\n\t'--------------------',\n\t'Body two'\n].join('\\n');\n\ntext.parseContext();\n// [{ name: 'Hello', type: 'note', body: 'Body one' }, { name: 'Second', body: 'Body two' }]\n```\n\n### str.parseEncoded()\n\nType: `method`\n\nParst URL-kodierten Text (einen Query String oder einen Formular-Body) in ein Objekt.\n\nReturns: `Object` Die geparsten Schlüssel und Werte (Strings).\n\nPaare `key=value` werden durch `&` getrennt; Schlüssel und Werte werden URL-dekodiert. Das ist der Parser, den Total.js für Query Strings und `application/x-www-form-urlencoded`-Bodys verwendet.\n\nExample: Einen Query String parsen\n```js\n'q=total.js&page=2&name=%20Peter'.parseEncoded();\n// { q: 'total.js', page: '2', name: ' Peter' }\n```\n\n### str.parseConfig([def], [onerr])\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 zuerst in das Ergebnis kopiert werden. |\n| `onerr` | `Function` | no |  | `function(err, line)` für Werte, die nicht ausgewertet werden können. |\n\nReturns: `Object` Die geparsten Werte.\n\nJede Zeile ist `key : value`. Das Trennzeichen ist das erste `:` oder das erste `=`, wenn die Zeile kein `:` hat; der Wert beginnt beim zweiten Zeichen nach dem Trennzeichen, lass dort also ein Leerzeichen. Leere Zeilen und Zeilen, die mit `#` oder `//` beginnen, werden übersprungen. Ein Wert, der mit `base64 ` oder `hex ` beginnt, wird decodiert.\n\nEin Typ in Klammern nach dem Schlüssel wandelt den Wert um: `(string)`, `(number)` (auch `float`, `double`, `currency`), `(boolean)` / `(bool)` (true, wenn der Wert `true`, `on`, `1` oder `enabled` enthält, in beliebiger Schreibweise), `(json)`, `(object)` / `(array)` / `(eval)` (als JavaScript ausgewertet), `(date)`, `(env)` (liest `process.env[value]`), `(config)` (liest einen anderen Konfigurationsschlüssel) und `(random)` (ein zufälliger String der angegebenen Länge). Schlägt ein ausgewerteter Wert fehl, wird `onerr(err, line)` aufgerufen, ohne ihn wird ein Fehler geworfen.\n\nExample: Einstellungen parsen\n```js\nvar text = 'name : Shop\\ncount (number) : 10\\nenabled (boolean) : true\\n# comment\\ntags (array) : [\\'a\\', \\'b\\']';\ntext.parseConfig();\n// { name: 'Shop', count: 10, enabled: true, tags: ['a', 'b'] }\n```\n\n### str.parseEnv()\n\nType: `method`\n\nParst Text im .env-Format in ein Objekt.\n\nReturns: `Object` Die Schlüssel und Werte.\n\nJede Zeile ist `KEY=value`. Zeilen, die leer sind oder mit `#` oder `//` beginnen, werden übersprungen. Bei einem Wert in einfachen oder doppelten Anführungszeichen werden die Anführungszeichen entfernt (seine inneren Leerzeichen bleiben erhalten); andere Werte werden getrimmt. `\\n` in einem Wert wird zu einem Zeilenumbruch. Alle Werte sind Strings.\n\nExample: .env parsen\n```js\n'PORT=8000\\nNAME=\"My app\"\\n# comment'.parseEnv();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### str.parseUA([structured])\n\nType: `method`\n\nLiest Betriebssystem, Browser und Gerätetyp aus einem User-Agent-Header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Ein Objekt statt Text zurückgeben. |\n\nReturns: `String|Object`\n\nOhne Argumente ist das Ergebnis ein kurzer Text wie `Windows Chrome`. Mit `structured` auf `true` ist das Ergebnis ein Objekt `{ os, browser, device }`, wobei `device` `mobile` oder `desktop` ist. Leerer Text gibt einen leeren String zurück.\n\nExample: Den User-Agent lesen\n```js\nvar ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Version/17.0 Mobile Safari/604.1';\nua.parseUA();      // iPhone Safari\nua.parseUA(true);  // { os: 'iPhone', browser: 'Safari', device: 'mobile' }\n```\n\n### str.isEmail()\n\nType: `method`\n\nPrüft, ob der Text eine E-Mail-Adresse ist.\n\nReturns: `Boolean`\n\nDer Test verwendet den regulären Ausdruck `email` aus `DEF.validators`: Buchstaben, Ziffern und `-_.+` vor `@`, eine Domain und eine Top-Level-Domain mit mindestens zwei Buchstaben. Text mit vier oder weniger Zeichen ist nie gültig.\n\nExample: Validieren\n```js\n'info@example.com'.isEmail();  // true\n'info@example'.isEmail();      // false\n```\n\n### str.isPhone()\n\nType: `method`\n\nPrüft, ob der Text eine Telefonnummer ist.\n\nReturns: `Boolean`\n\nDer Test verwendet den regulären Ausdruck `phone` aus `DEF.validators`: ein optionales `+`, drei Ziffern (optional in Klammern), drei Ziffern und 4 bis 8 Ziffern, jede Gruppe optional durch `-`, `.` oder ein Leerzeichen getrennt. Text mit weniger als sechs Zeichen ist nie gültig.\n\nExample: Validieren\n```js\n'+421903123456'.isPhone();  // true\n'(123) 456-7890'.isPhone(); // true\n'12345'.isPhone();          // false\n```\n\n### str.isURL()\n\nType: `method`\n\nPrüft, ob der Text eine http- oder https-URL ist.\n\nReturns: `Boolean`\n\nDer Text muss mit `http://` oder `https://` beginnen und darf `,`, `{`, `}` oder `\\` nicht enthalten. Text mit sieben oder weniger Zeichen ist nie gültig.\n\nExample: Validieren\n```js\n'https://www.totaljs.com'.isURL();  // true\n'www.totaljs.com'.isURL();          // false\n```\n\n### str.isUID()\n\nType: `method`\n\nPrüft, ob der Text eine gültige, von UID() erzeugte Kennung ist.\n\nReturns: `Boolean`\n\nDie Methode prüft das Format und die Prüfsumme von Kennungen, die mit `UID()` erstellt wurden, sodass ein zufälliger String derselben Form abgelehnt wird. Um das in einer UID gespeicherte Datum und den Index zu lesen, verwende `str.parseUID()`, das `{ version, date, century, hash, index, valid }` zurückgibt. Für Standard-GUIDs (`8-4-4-4-12` Hex-Ziffern) verwende `str.isGUID()`.\n\nExample: Eine ID validieren\n```js\nvar id = UID();\nid.isUID();       // true\n'abc'.isUID();    // false\nid.parseUID().date;  // the time the id was created\n'123e4567-e89b-12d3-a456-426614174000'.isGUID(); // true\n```\n\n### str.isNumber([isDecimal])\n\nType: `method`\n\nPrüft, ob der Text nur Ziffern enthält.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `isDecimal` | `Boolean` | no | `false` | Ein Dezimaltrennzeichen erlauben. |\n\nReturns: `Boolean`\n\nJedes Zeichen muss eine Ziffer sein. Mit `isDecimal` auf `true` ist zusätzlich ein `.` oder `,` erlaubt. Ein Vorzeichen (`-`, `+`) ist nicht erlaubt und leerer Text ist keine Zahl.\n\nExample: Validieren\n```js\n'0123'.isNumber();      // true\n'1.5'.isNumber();       // false\n'1,5'.isNumber(true);   // true\n```\n\n### str.isJSON()\n\nType: `method`\n\nPrüft schnell, ob der Text wie ein JSON-Objekt, -Array oder -String aussieht.\n\nReturns: `Boolean`\n\nLeerraum am Anfang und Ende wird übersprungen, und das erste und letzte Zeichen werden verglichen: `{` mit `}`, `[` mit `]` oder `\"` mit `\"`. Es ist auch `true`, wenn der Text mit einer Ziffer oder einem Buchstaben beginnt und mit einem Zeichen unter `9` endet, zum Beispiel `'123'` oder `'abc1'`. Der Inhalt wird nicht geparst; verwende also `String.parseJSON()`, wenn du sicher sein musst.\n\nExample: Vor dem Parsen prüfen\n```js\nvar body = ' {\"a\":1} ';\nif (body.isJSON())\n\tvar obj = body.parseJSON();\n```\n\n### str.isXSS()\n\nType: `method`\n\nPrüft, ob der Text ein HTML-Tag enthält.\n\nReturns: `Boolean`\n\nGibt `true` zurück, wenn der Text `<` gefolgt von einem späteren `>` enthält; so erkennt der reguläre Ausdruck `xss` aus `DEF.validators` Markup in Benutzereingaben. `str.isSQLInjection()` funktioniert genauso mit dem Ausdruck `sqlinjection`: Es ist `true` für Strings in Anführungszeichen und für die großgeschriebenen SQL-Schlüsselwörter `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` und `UNION`. Beide sind einfache Filter, kein Ersatz für das Kodieren der Ausgabe und für Abfrageparameter.\n\nExample: Markup ablehnen\n```js\n'<script>alert(1)</script>'.isXSS();  // true\n'Hello'.isXSS();                      // false\n'DROP TABLE users'.isSQLInjection();   // true\n```\n\n### str.hash([type], [salt])\n\nType: `method`\n\nGibt einen Hash des Textes zurück: einen schnellen Zahlen-Hash oder einen md5-, sha1-, sha256-, sha512- oder crc32-Digest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32`, `crc32unsigned` oder `true` für einen vorzeichenlosen Zahlen-Hash. |\n| `salt` | `String` | no |  | Text, der vor dem Hashen angehängt wird. |\n\nReturns: `Number|String` Eine Zahl beim Zahlen-Hash und crc32, sonst ein Hex-String.\n\n`type` wählt den Algorithmus: `md5`, `sha1`, `sha256`, `sha512` (Hex-Strings), `crc32` (vorzeichenbehaftete Zahl) oder `crc32unsigned` (vorzeichenlose Zahl). Ohne `type` gibt die Methode einen schnellen 32-Bit-Zahlen-Hash des Textes zurück (vorzeichenbehaftet); `hash(true)` gibt ihn vorzeichenlos zurück. `salt` wird vor dem Hashen an den Text angehängt. Der Zahlen-Hash ist kein kryptografischer Hash: Verwende ihn für Cache-Schlüssel und ähnliche Zwecke. `str.crc32([unsigned])` ist auch direkt verfügbar.\n\nExample: Hashes\n```js\n'hello'.hash();          // a signed 32-bit number\n'hello'.hash(true);      // the same, unsigned\n'hello'.hash('sha256');  // hex digest\n'hello'.hash('crc32unsigned');\n```\n\n### str.md5([salt])\n\nType: `method`\n\nGibt den MD5-Digest des Textes 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` 32 Hex-Zeichen.\n\nDer Text (mit angehängtem `salt`) wird als UTF-8 mit dem Node.js-Modul `crypto` gehasht. MD5 eignet sich für Prüfsummen und Cache-Schlüssel, nicht für Passwörter.\n\nExample: MD5\n```js\n'a'.md5();\n// 0cc175b9c0f1b6a831c399e269772661\n```\n\n### str.sha256([salt])\n\nType: `method`\n\nGibt den SHA-256-Digest des Textes als Hex-String zurück. sha1() und sha512() funktionieren genauso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text, der vor dem Hashen angehängt wird. |\n\nReturns: `String` 64 Hex-Zeichen.\n\nDer Text (mit angehängtem `salt`) wird als UTF-8 mit dem Node.js-Modul `crypto` gehasht. `str.sha1([salt])` gibt 40 Hex-Zeichen zurück und `str.sha512([salt])` 128 Hex-Zeichen.\n\nExample: SHA-Digests\n```js\nvar digest = 'password'.sha256(CONF.secret);\nvar short = 'text'.sha1();\nvar long = 'text'.sha512();\n```\n\n### str.sign([key], [check])\n\nType: `method`\n\nSigniert den Text mit einer kurzen Prüfsumme oder prüft und entfernt die Signatur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Der Signierschlüssel. |\n| `check` | `Boolean` | no | `false` | Die Signatur prüfen und den ursprünglichen Text zurückgeben. |\n\nReturns: `String` Der signierte Text, der ursprüngliche Text oder `null`.\n\n`str.sign(key)` gibt `text-checksum` zurück, wobei die Prüfsumme aus dem Text und `key` gebildet wird. `signed.sign(key, true)` prüft die Prüfsumme und gibt den ursprünglichen Text zurück oder `null`, wenn die Signatur nicht passt. Verwende es für Werte, die über URLs übertragen werden und nicht verändert werden dürfen, etwa IDs in Links. Es ist keine Verschlüsselung: Der Text bleibt lesbar.\n\n`str.makeid()` gibt nur eine kurze Base-36-Prüfsumme des Textes zurück, praktisch als kompakter Schlüssel.\n\nExample: Eine ID signieren\n```js\nvar token = '123'.sign('mykey');     // 123-155hlxd\ntoken.sign('mykey', true);           // 123\n(token + 'x').sign('mykey', true);   // null\n```\n\n### str.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nVerschlüsselt den Text mit einem Schlüssel. String.decrypt() kehrt das um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Verschlüsselungsschlüssel. |\n| `isUnique` | `Boolean` | no | `false` | Bei jedem Aufruf ein anderes Ergebnis erzeugen. |\n| `secret` | `String` | no | `CONF.secret` | Das in der Prüfsumme verwendete Secret. |\n\nReturns: `String` Der verschlüsselte Text.\n\nDas Ergebnis ist ein String aus einer Prüfsumme, `-` und Hex-Daten. Mit `isUnique` auf `true` ergibt derselbe Text jedes Mal ein anderes Ergebnis. Die Prüfsumme verwendet `secret` oder den Konfigurationsschlüssel `secret`, wenn du es weglässt.\n\n`str.decrypt(key, [secret])` gibt den ursprünglichen Text zurück oder `null`, wenn Schlüssel, Secret oder Daten nicht passen. Verwende für beides denselben `key` und dasselbe `secret`.\n\nExample: Verschlüsseln und entschlüsseln\n```js\nvar value = 'user@example.com'.encrypt('mykey', true);\nvalue.decrypt('mykey');   // user@example.com\nvalue.decrypt('other');   // null\n```\n\n### str.encrypt_uid([key])\n\nType: `method`\n\nVerschlüsselt eine Kennung in ein kurzes, URL-sicheres Token. String.decrypt_uid() kehrt das um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Der Schlüssel. |\n\nReturns: `String` Das Token.\n\nVerwende es, um numerische oder textuelle IDs in öffentlichen URLs zu verbergen. `key` ist standardmäßig der Konfigurationsschlüssel `secret`. `token.decrypt_uid([key])` gibt die ursprüngliche ID zurück oder `null`, wenn das Token verändert wurde oder der Schlüssel ein anderer ist.\n\nExample: Eine ID verbergen\n```js\nvar token = '123'.encrypt_uid('mykey');\ntoken.decrypt_uid('mykey');  // 123\n```\n\n### str.base64ToBuffer()\n\nType: `method`\n\nWandelt Base64-Text oder eine Data-URI in einen Buffer um.\n\nReturns: `Buffer` Die dekodierten Daten.\n\nAlles bis einschließlich zum ersten `,` wird übersprungen, daher funktionieren sowohl reines Base64 als auch `data:...;base64,...`. Verwandte Methoden: `str.base64ToFile(filename, [callback])` schreibt die dekodierten Daten in eine Datei, `str.base64ContentType()` gibt den Content-Type einer Data-URI zurück (`image/png`), und `str.parseDataURI()` gibt `{ type, buffer }` zurück (oder `null` für Text, der keine Data-URI ist).\n\nExample: Einen Upload dekodieren\n```js\nvar uri = 'data:text/plain;base64,aGVsbG8=';\nuri.base64ToBuffer().toString();   // hello\nuri.base64ContentType();           // text/plain\nuri.parseDataURI().type;           // text/plain\nuri.base64ToFile(PATH.temp('hello.txt'));\n```\n\n### num.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormatiert eine Zahl mit einem Tausendertrennzeichen und einer festen Anzahl von 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 Tausendertrennzeichen ist standardmäßig ein Leerzeichen. Das Dezimaltrennzeichen ist `.` oder `,`, wenn das Tausendertrennzeichen `.` ist. Überzählige Dezimalstellen werden abgeschnitten, nicht gerundet, also ruf zuerst `Number.round()` auf, wenn du runden musst. Fehlende Dezimalstellen werden mit Nullen aufgefüllt. Wenn das erste Argument ein String ist, werden die ersten beiden Argumente vertauscht: `format('.', 2)` ist dasselbe wie `format(2, '.')`.\n\nExample: Formatieren\n```js\n(1234567.891).format(2);           // 1 234 567.89\n(1234.5).format(2, ',', '.');      // 1,234.50\n(1234.5).format('.', 2);           // 1.234,50\n(1.999).round(2).format(2);        // 2.00\n```\n\n### num.pluralize(zero, one, few, other)\n\nType: `method`\n\nWählt eine Pluralform anhand der Zahl; # wird durch die Zahl ersetzt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Text für 0 oder alle vier Formen durch Kommas getrennt. |\n| `one` | `String` | no |  | Text für 1. |\n| `few` | `String` | no |  | Text für 2 bis 4. |\n| `other` | `String` | no |  | Text für andere Zahlen. |\n\nReturns: `String` Die gewählte Form.\n\nDie Form `zero` wird für 0 verwendet, `one` für 1, `few` für 2 bis 4 und `other` für den Rest (die Regel slawischer Sprachen; für Englisch übergib denselben Text als `few` und `other`). Wenn du nur einen String übergibst, wird er an Kommas in die vier Formen aufgeteilt. Das erste `#` in der gewählten Form wird durch die Zahl ersetzt.\n\nExample: Pluralformen\n```js\n(1).pluralize('no items', '# item', '# items', '# items');  // 1 item\n(7).pluralize('no items,# item,# items,# items');          // 7 items\n```\n\n### num.padLeft(max, [c])\n\nType: `method`\n\nFüllt die Zahl links mit Nullen auf. Number.padRight() füllt rechts auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Die Länge des Ergebnisses. |\n| `c` | `String` | no | `'0'` | Das Füllzeichen. |\n\nReturns: `String` Die aufgefüllte Zahl.\n\nDie Zahl wird in einen String umgewandelt und mit `c` (standardmäßig `0`) auf `max` Zeichen aufgefüllt. `num.padRight(max, [c])` füllt rechts auf.\n\nExample: Mit Nullen auffüllen\n```js\n(5).padLeft(3);       // 005\n(7).padLeft(4, ' ');  // '   7'\n(5).padRight(3);      // 500\n```\n\n### num.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` | yes |  | Die Anzahl der Dezimalstellen. |\n\nReturns: `Number` Die gerundete Zahl.\n\nDas Runden verwendet die Exponentialschreibweise, daher werden Werte wie `1.005` korrekt auf `1.01` gerundet. `num.floor(decimals)` rundet stattdessen auf eine Anzahl von Dezimalstellen ab (`(1.239).floor(2)` ist `1.23`).\n\nExample: Runden\n```js\n(1.005).round(2);  // 1.01\n(2.5).round(0);    // 3\n(1.239).floor(2);  // 1.23\n```\n\n### num.fixed(decimals)\n\nType: `method`\n\nRundet die Zahl mit toFixed() und gibt eine Zahl zurück, keinen String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Die Anzahl der Dezimalstellen. |\n\nReturns: `Number`\n\nExample: Fixed\n```js\n(1.236).fixed(2);  // 1.24 (a number)\n```\n\n### num.between(condition, [otherwise])\n\nType: `method`\n\nGibt den Wert des ersten Bereichs zurück, der die Zahl enthält.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Bereiche als Schlüssel, Ergebnisse als Werte. |\n| `otherwise` | `Any` | no |  | Das Ergebnis, wenn kein Bereich passt. |\n\nReturns: `Any` Der Wert des passenden Bereichs oder `otherwise`.\n\n`condition` ist ein Objekt, dessen Schlüssel Bereiche sind: `'1-3'` (von 1 bis 3, beide eingeschlossen), `'7-'` (7 und mehr) oder `'-5'` (5 und weniger). Die Schlüssel werden der Reihe nach geprüft und der Wert des ersten passenden Schlüssels wird zurückgegeben. Wenn kein Bereich passt, wird `otherwise` zurückgegeben.\n\nExample: Eine Punktzahl bewerten\n```js\nvar score = 5;\nscore.between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }, 'unknown');\n// medium\n```\n\n### num.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAddiert eine Steuer zur Zahl oder entfernt sie aus einem Preis, der sie enthält.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | Der Steuersatz in Prozent. |\n| `decimals` | `Number` | no | `2` | Die Anzahl der Dezimalstellen. |\n| `includedVAT` | `Boolean` | no | `false` | Die Zahl enthält die Steuer bereits. |\n\nReturns: `Number`\n\n`Number.TAX()` ist dieselbe Methode. Ohne `includedVAT` ist das Ergebnis die um `percentage` erhöhte Zahl. Mit `includedVAT` auf `true` ist die Zahl ein Preis, der die Steuer bereits enthält, und das Ergebnis ist der Preis ohne Steuer. Das Ergebnis wird auf `decimals` gerundet (standardmäßig 2). Du kannst den booleschen Wert als zweites Argument übergeben: `VAT(20, true)`.\n\nExample: Preise mit MwSt.\n```js\n(100).VAT(20);        // 120\n(120).VAT(20, true);  // 100\n(99.99).TAX(10, 0);   // 110\n```\n\n### num.discount(percentage, [decimals])\n\nType: `method`\n\nVerringert die Zahl um einen Prozentsatz.\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`\n\nDas Ergebnis wird auf `decimals` abgerundet (standardmäßig 2).\n\nExample: Rabatt\n```js\n(100).discount(15);    // 85\n(19.99).discount(10);  // 17.99\n```\n\n### num.filesize([decimals], [type])\n\nType: `method`\n\nFormatiert eine Anzahl von Bytes als menschenlesbare Größe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Die Anzahl der Dezimalstellen. |\n| `type` | `String` | no |  | `bytes`, `KB`, `MB`, `GB` oder `TB`. |\n\nReturns: `String` Die Größe mit ihrer Einheit.\n\nOhne `type` wird die größte passende Einheit gewählt: `bytes`, `KB`, `MB`, `GB` oder `TB` (1 KB sind 1024 Bytes). Mit `type` wird der Wert in diese Einheit umgerechnet. Ohne `decimals` hat der Wert bis zu zwei Dezimalstellen und `.00` wird entfernt; mit `decimals` wird er mit `Number.format(decimals)` formatiert. Die Argumente können in beliebiger Reihenfolge übergeben werden.\n\nExample: Dateigrößen\n```js\n(500).filesize();          // 500 bytes\n(1536000).filesize();      // 1.46 MB\n(5000000).filesize(1, 'MB'); // 4.7 MB\n```\n\n### num.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormatiert die Zahl als Betrag mit einem in DEF.currencies registrierten Währungsformatierer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | Der Schlüssel in `DEF.currencies`. |\n| `a, b, c` | `Any` | no |  | Zusätzliche Argumente für den Formatierer. |\n\nReturns: `String` Der formatierte Betrag.\n\nDer Formatierer ist die Funktion `DEF.currencies[currency]` (oder `DEF.currencies.default` ohne `currency`). Er erhält die Zahl und die Argumente `a`, `b` und `c` und gibt den Text zurück. Wenn für die Währung kein Formatierer existiert, ist das Ergebnis `num.format(2)`. Registriere Formatierer beim Start, zum Beispiel in einer Definitionsdatei.\n\nExample: Eine Währung registrieren und verwenden\n```js\n// /definitions/currencies.js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2, ' ', ',') + ' €';\n};\n\n(1234.5).currency('eur');  // 1 234,50 €\n(10).currency('usd');      // 10.00 (no formatter)\n```\n\n### date.add(type, [value])\n\nType: `method`\n\nGibt ein neues, um eine Zeitspanne verschobenes Datum zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | Die Einheit, ein String mit Wert und Einheit oder Millisekunden. |\n| `value` | `Number` | no |  | Der Betrag, negativ für die Vergangenheit. |\n\nReturns: `Date` Ein neues Datum.\n\nDas ursprüngliche Datum wird nicht verändert. Übergib die Einheit und den Wert (`add('minutes', 30)`), einen String mit beidem (`add('30 minutes')`, `add('-2 hours')`) oder eine Anzahl von Millisekunden (`add(5000)`).\n\nEinheiten: `s`, `ss`, `sec`, `second`, `seconds`; `m`, `mm`, `min`, `minute`, `minutes`; `h`, `hh`, `hour`, `hours`; `d`, `dd`, `day`, `days`; `w`, `ww`, `week`, `weeks`; `M`, `MM`, `month`, `months`; `y`, `yyyy`, `year`, `years`. Die Einheiten wirken auf die UTC-Teile des Datums. Das Addieren von Monaten zum Monatsende folgt JavaScript: 31. Januar plus ein Monat ist in einem Schaltjahr der 2. März und sonst der 3. März.\n\nExample: Datumswerte verschieben\n```js\nvar now = new Date();\nnow.add('1 day');\nnow.add('minutes', 30);\nnow.add('-2 hours');\nnow.add(5000);  // + 5 seconds\n```\n\n### date.diff([date], type)\n\nType: `method`\n\nGibt die Differenz zwischen zwei Datumswerten in Sekunden, Minuten, Stunden oder Tagen zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String|Number` | no | `now` | Das Datum, mit dem verglichen wird. |\n| `type` | `String` | yes |  | Die Einheit des Ergebnisses. |\n\nReturns: `Number` Die Differenz in der Einheit.\n\nDas Ergebnis ist `this - date` in der angegebenen Einheit, aufgerundet, also positiv, wenn `this` später ist. `date` kann ein Date sein, ein String, den `Date.parse()` versteht, oder eine Anzahl von Millisekunden. Mit einem Argument wird das Datum mit der aktuellen Zeit verglichen. Einheiten: `s` / `ss` / `second` / `seconds`, `m` / `mm` / `minute` / `minutes`, `h` / `hh` / `hour` / `hours`, `d` / `dd` / `day` / `days`. Eine unbekannte Einheit gibt `NaN` zurück.\n\nExample: Differenzen\n```js\nvar created = new Date('2024-01-30T00:00:00Z');\nvar end = new Date('2024-01-31T10:00:00Z');\nend.diff(created, 'hours');  // 34\nend.diff('2024-01-01T00:00:00Z', 'days'); // 31\ncreated.diff('seconds');     // negative: created is in the past\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormatiert das Datum nach einem Muster; ohne Muster wird ein ISO-String in UTC zurückgegeben.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Das Muster. |\n| `resource` | `String` | no |  | Die für Monats- und Tagesnamen verwendete Ressource. |\n\nReturns: `String` Das formatierte Datum.\n\nOhne `format` ist das Ergebnis `yyyy-MM-ddTHH:mm:ss.SSSZ` in UTC. Mit `format` werden die Teile in der Zeitzone des Servers geschrieben (UTC, sofern der Konfigurationsschlüssel `$timezone` nichts anderes angibt):\n\n- `yyyy`, `yy` Jahr; `MM`, `M` Monatsnummer; `MMMM` Monatsname, `MMM` seine ersten drei Buchstaben,\n- `dd`, `d` Tag; `dddd` Name des Tages, `ddd` seine ersten zwei Buchstaben in Großbuchstaben,\n- `HH`, `H` Stunden (0-23); `mm`, `m` Minuten; `ss`, `s` Sekunden,\n- `ww`, `w` ISO-Kalenderwoche; `a` `AM` oder `PM`.\n\nGroßgeschriebene `YYYY`, `YY`, `DD`, `D`, `DDDD`, `DDD` und kleingeschriebene `hh`, `h` werden ebenfalls akzeptiert. Monats- und Tagesnamen sind englisch; mit `resource` werden sie mit der Ressourcendatei dieses Namens übersetzt. Kompilierte Formate werden gecacht, daher ist das Formatieren schnell.\n\nExample: Datumswerte formatieren\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.format();                      // 2024-01-31T10:00:00.000Z\nd.format('yyyy-MM-dd HH:mm');    // 2024-01-31 10:00\nd.format('dd.MM.yy');            // 31.01.24\nd.format('dddd, d. MMMM yyyy');  // Wednesday, 31. January 2024\nd.format('MMMM', 'sk');          // the month name from sk.resource\n```\n\n### date.extend(text)\n\nType: `method`\n\nGibt ein neues Datum zurück, bei dem Datums- oder Zeitteile aus einem Text ersetzt sind.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Ein Datum, eine Uhrzeit oder beides. |\n\nReturns: `Date` Ein neues Datum.\n\nDer Text kann ein Datum `yyyy-MM-dd` oder `d.M.yyyy` und eine Uhrzeit `HH:mm` oder `HH:mm:ss` enthalten. Nur die im Text gefundenen Teile werden ersetzt; die anderen werden aus dem ursprünglichen Datum übernommen. Jahr, Monat und Tag werden nacheinander gesetzt; existiert der Tag des ursprünglichen Datums im neuen Monat nicht, rückt das Datum in den nächsten Monat (31. Januar, erweitert mit `2025-02-10`, ergibt den 10. März 2025). Die Werte sind UTC.\n\nExample: Teile ändern\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.extend('12:30');              // 2024-01-31T12:30:00.000Z\nd.extend('2025-03-04');         // 2025-03-04T10:00:00.000Z\nd.extend('1.3.2020 08:00');     // 2020-03-01T08:00:00.000Z\n```\n\n### date.toUTC([ticks])\n\nType: `method`\n\nVerschiebt ein lokales Datum um den Zeitzonen-Offset nach UTC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Millisekunden zurückgeben. |\n\nReturns: `Date|Number`\n\nDas Ergebnis ist das Datum plus der Offset der Zeitzone des Servers. Mit `ticks` auf `true` ist das Ergebnis die Anzahl der Millisekunden statt eines Date. Auf einem Server, der in UTC läuft (Standard), ändert sich das Datum nicht.\n\nExample: Nach UTC\n```js\nvar utc = new Date().toUTC();\nvar ms = new Date().toUTC(true);\n```\n\n### date.setTimeZone(timezone)\n\nType: `method`\n\nGibt ein neues Datum zurück, das denselben Zeitpunkt in einer anderen Zeitzone zeigt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | Ein IANA-Zeitzonenname. |\n\nReturns: `Date` Ein neues Datum.\n\nDie Teile des Ergebnisses (Stunden, Tag, ...), in der Zeitzone des Servers gelesen, sind die Ortszeit von `timezone` zu diesem Zeitpunkt, daher gibt `format()` die lokale Zeit dieser Zone aus. `timezone` ist ein IANA-Name wie `Europe/Bratislava` oder `America/New_York`.\n\nExample: Ortszeit anzeigen\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.setTimeZone('Europe/Bratislava').format('HH:mm');  // 11:00\n```\n\n### arr.findItem(cb, [value])\n\nType: `method`\n\nGibt das erste passende Element zurück oder null.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Eine Testfunktion, ein Eigenschaftsname oder ein Wert. |\n| `value` | `Any` | no |  | Der Wert der Eigenschaft. |\n\nReturns: `Object` Das Element oder `null`.\n\nÜbergib eine Funktion `(item, index)`, einen Eigenschaftsnamen und einen Wert (`('id', 5)` vergleicht `item.id === 5`) oder einen einzelnen Wert, der mit `===` verglichen wird.\n\nExample: Ein Element finden\n```js\nvar users = [{ id: 1, name: 'Peter' }, { id: 2, name: 'Anna' }];\nusers.findItem('id', 2);                  // { id: 2, name: 'Anna' }\nusers.findItem(u => u.name === 'Peter');  // { id: 1, name: 'Peter' }\nusers.findItem('id', 9);                  // null\n```\n\n### arr.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|Any` | yes |  | Eine Testfunktion, ein Eigenschaftsname oder ein Wert. |\n| `value` | `Any` | no |  | Der Wert der Eigenschaft. |\n\nReturns: `Array` Die passenden Elemente.\n\nÜbergib eine Funktion `(item, index)`, einen Eigenschaftsnamen und einen Wert (`('id', 5)` vergleicht `item.id === 5`) oder einen einzelnen Wert, der mit `===` verglichen wird. Das Ergebnis ist ein neues Array; das ursprüngliche Array wird nicht verändert.\n\nExample: Filtern\n```js\nvar items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }];\nitems.findAll('type', 'a').length;  // 2\n```\n\n### arr.findIndex(cb, [value])\n\nType: `method`\n\nGibt den Index des ersten passenden Elements zurück oder -1.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Eine Testfunktion, ein Eigenschaftsname oder ein Wert. |\n| `value` | `Any` | no |  | Der Wert der Eigenschaft. |\n\nReturns: `Number` Der Index oder `-1`.\n\nÜbergib eine Funktion `(item, index)`, einen Eigenschaftsnamen und einen Wert (`('id', 5)` vergleicht `item.id === 5`) oder einen einzelnen Wert, der mit `===` verglichen wird. Total.js ersetzt das native `findIndex()` durch diese Version (mit einer Funktion verhält sie sich wie die native); `arr.TfindIndex()` ist dieselbe Methode.\n\nExample: Index eines Elements\n```js\nvar users = [{ id: 1 }, { id: 2 }];\nvar index = users.findIndex('id', 2);  // 1\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### arr.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 Testfunktion oder ein Eigenschaftsname. |\n| `value` | `Any` | yes |  | Der Wert der Eigenschaft (übergib `undefined` bei einer Funktion). |\n| `path` | `String` | yes |  | Die zurückzugebende Eigenschaft. |\n| `def` | `Any` | no |  | Der Standardwert. |\n\nReturns: `Any`\n\nDas Element wird wie bei `Array.findItem()` gefunden. Das Ergebnis ist `item[path]` oder `def`, wenn kein Element passt oder die Eigenschaft `null` / `undefined` ist.\n\nExample: Eine Eigenschaft lesen\n```js\nvar users = [{ id: 1, name: 'Peter' }];\nusers.findValue('id', 1, 'name');          // Peter\nusers.findValue('id', 9, 'name', 'guest');  // guest\n```\n\n### arr.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|Any` | yes |  | Eine Testfunktion, ein Eigenschaftsname oder ein Wert. |\n| `value` | `Any` | no |  | Der Wert der Eigenschaft. |\n\nReturns: `Array` Ein neues Array ohne die passenden Elemente.\n\nÜbergib eine Funktion `(item, index)`, einen Eigenschaftsnamen und einen Wert (`('id', 5)` vergleicht `item.id === 5`) oder einen einzelnen Wert, der mit `===` verglichen wird. Das ursprüngliche Array wird nicht verändert, also weise das Ergebnis zu.\n\nExample: Elemente entfernen\n```js\nvar users = [{ id: 1 }, { id: 2 }, { id: 3 }];\nusers = users.remove('id', 1);       // [{ id: 2 }, { id: 3 }]\nvar nums = [1, 2, 3, 2].remove(2);   // [1, 3]\n```\n\n### arr.quicksort([sort], [desc])\n\nType: `method`\n\nSortiert das Array direkt nach einer oder mehreren Eigenschaften.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Eigenschaften, nach denen sortiert wird, oder `true` für absteigende einfache Werte. |\n| `desc` | `Boolean` | no | `false` | Absteigende Reihenfolge für `sort`. |\n\nReturns: `Array` Dasselbe Array, sortiert.\n\n`sort` ist eine kommagetrennte Liste von Eigenschaftsnamen, jeweils optional mit `_asc` oder `_desc` (`'name'`, `'price_desc'`, `'group,date_desc'`). Verschachtelte Eigenschaften mit Punkten werden unterstützt (`'user.name'`). Der Typ jeder Spalte (String, Zahl, Boolean oder Date) wird beim ersten Verwenden eines Sortierausdrucks aus dem ersten Wert ermittelt, der nicht null ist, und für spätere Sortierungen mit demselben Ausdruck beibehalten; Strings werden unter Berücksichtigung diakritischer Zeichen verglichen. Übergibst du `true` (oder `2`) als zweites Argument, wird eine einzelne Eigenschaft absteigend sortiert.\n\nOhne `sort` wird das Array einfacher Werte aufsteigend sortiert; `quicksort(true)` sortiert es absteigend. Die Methode gibt dasselbe Array zurück.\n\nExample: Objekte sortieren\n```js\nvar products = [{ name: 'B', price: 10 }, { name: 'A', price: 20 }];\nproducts.quicksort('name');        // A, B\nproducts.quicksort('price_desc');  // 20, 10\nproducts.quicksort('name', true);  // B, A\n[3, 1, 2].quicksort();             // [1, 2, 3]\n```\n\n### arr.take(count)\n\nType: `method`\n\nGibt die ersten count Elemente als neues Array zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Die Anzahl der Elemente. |\n\nReturns: `Array`\n\nExample: Take\n```js\n[1, 2, 3, 4].take(2);  // [1, 2]\n```\n\n### arr.skip(count)\n\nType: `method`\n\nGibt die Elemente nach den ersten count Elementen als neues Array zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Die Anzahl der zu überspringenden Elemente. |\n\nReturns: `Array`\n\nKombiniere es mit `take()` für die Seitenaufteilung.\n\nExample: Paginierung\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### arr.first([def])\n\nType: `method`\n\nGibt das erste Element zurück oder einen Standardwert bei einem leeren Array. Array.last() gibt das letzte zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Any` | no |  | Der Wert für ein leeres Array. |\n\nReturns: `Any`\n\n`arr.last([def])` gibt das letzte Element oder `def` zurück.\n\nExample: Erstes und letztes\n```js\n[1, 2].first();     // 1\n[].first('none');   // none\n[1, 2].last();      // 2\n```\n\n### arr.group(name)\n\nType: `method`\n\nGruppiert die Elemente nach einer Eigenschaft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Eigenschaft, nach der gruppiert wird. |\n\nReturns: `Array` Gruppen `{ name, items }`.\n\nGibt ein Array von `{ name, items }` zurück, sortiert nach `name`. Der Wert der Eigenschaft wird in einen String umgewandelt; Elemente ohne die Eigenschaft landen in einer Gruppe mit leerem Namen.\n\nExample: Gruppieren\n```js\nvar items = [{ type: 'x', id: 1 }, { type: 'y', id: 2 }, { type: 'x', id: 3 }];\nitems.group('type');\n// [{ name: 'x', items: [...2 items] }, { name: 'y', items: [...1 item] }]\n```\n\n### arr.trim()\n\nType: `method`\n\nTrimmt Strings und gibt ein neues Array ohne leere Werte zurück.\n\nReturns: `Array`\n\nStrings im ursprünglichen Array werden direkt getrimmt. Das Ergebnis enthält nur truthy Elemente, daher werden leere Strings, `null`, `undefined`, `0` und `false` weggelassen.\n\nExample: Eine Liste bereinigen\n```js\n' a , ,b'.split(',').trim();  // ['a', 'b']\n```\n\n### arr.random([item])\n\nType: `method`\n\nMischt das Array direkt 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|Any`\n\nOhne Argumente wird das Array gemischt (Fisher-Yates) und zurückgegeben. Mit `item` auf `true` wird ein zufälliges Element zurückgegeben und das Array nicht verändert.\n\nExample: Zufall\n```js\nvar colors = ['red', 'green', 'blue'];\ncolors.random(true);  // one color\ncolors.random();      // the shuffled array\n```\n\n### arr.wait(onItem, [callback], [thread])\n\nType: `method`\n\nVerarbeitet die Elemente nacheinander mit einer asynchronen Funktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | `function(item, next)`. |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn alle Elemente verarbeitet sind. |\n| `thread` | `Number|Boolean` | no | `1` | Parallele Elemente oder `true`, um Elemente bei der Verarbeitung zu entfernen. |\n\nReturns: `Array` Das Array.\n\n`onItem(item, next)` wird für jedes Element aufgerufen; ruf `next()` auf, um mit dem nächsten Element fortzufahren. `callback()` wird aufgerufen, wenn alle Elemente fertig sind. `thread` legt fest, wie viele Elemente gleichzeitig laufen (standardmäßig 1). Mit `thread` auf `true` werden die Elemente bei der Verarbeitung mit `shift()` aus dem Array entfernt. Ruf `next('cancel')` auf, um abzubrechen: Dann wird `callback('cancel')` aufgerufen.\n\nExample: Nacheinander verarbeiten\n```js\nvar ids = [1, 2, 3];\nids.wait(function(id, next) {\n\tFUNC.removeuser(id, next);\n}, function() {\n\tconsole.log('All removed');\n});\n```\n\nExample: Zwei gleichzeitig\n```js\nurls.wait(function(url, next) {\n\tREQUEST({ url: url, callback: () => next() });\n}, () => console.log('done'), 2);\n```\n\n### arr.async([thread], [callback])\n\nType: `method`\n\nFührt ein Array von Funktionen nacheinander aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | Wie viele Funktionen gleichzeitig laufen. |\n| `callback` | `Function` | no |  | Wird am Ende aufgerufen. |\n\nReturns: `Array` Das Array.\n\nJedes Element ist eine Funktion `(next)`; ruf `next()` auf, wenn sie fertig ist. Die Funktionen werden beim Ausführen aus dem Array entfernt, daher ist das Array am Ende leer. `thread` legt fest, wie viele Funktionen gleichzeitig starten (standardmäßig 1). `callback()` wird aufgerufen, wenn alle Funktionen fertig sind, oder `callback('cancel')`, wenn eine `next('cancel')` aufruft.\n\nExample: Aufgaben ausführen\n```js\nvar tasks = [];\ntasks.push(function(next) {\n\tconsole.log('first');\n\tnext();\n});\ntasks.push(function(next) {\n\tsetTimeout(next, 100);\n});\ntasks.async(function() {\n\tconsole.log('done');\n});\n```\n\n### arr.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 |  | `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Wird am Ende aufgerufen. |\n\nReturns: `Array` Das Array.\n\n`fn(items, next, beg, end)` erhält den nächsten Block sowie den Start- und Endindex; ruf `next()` auf, um fortzufahren. `callback()` wird nach dem letzten Block aufgerufen.\n\nExample: In Stapeln einfügen\n```js\nrows.limit(100, function(items, next) {\n\tFUNC.importrows(items, next);\n}, function() {\n\tconsole.log('Imported');\n});\n```\n","entries":[{"type":"method","name":"String.format()","signature":"str.format(arg0, [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"str.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"str.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"str.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"str.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"str.toName()","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"str.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"str.decode()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"str.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"str.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"str.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.toKeywords()","signature":"str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"str.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"str.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"str.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"str.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"str.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"str.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"str.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"str.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseContext()","signature":"str.parseContext()","since":"0.0.17","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"str.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"str.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseEnv()","signature":"str.parseEnv()","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"str.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"str.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"str.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"str.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"str.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"str.isNumber([isDecimal])","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"str.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"str.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"str.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"str.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"str.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"str.sign([key], [check])","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"str.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"str.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"str.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"num.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"num.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"num.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"num.round(precision)","since":"","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"num.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"num.between(condition, [otherwise])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"num.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"num.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"num.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"num.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"date.extend(text)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"arr.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"arr.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"arr.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"arr.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"arr.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"arr.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"arr.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"arr.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"arr.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.group()","signature":"arr.group(name)","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"arr.trim()","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"arr.random([item])","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"arr.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"arr.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"arr.limit(max, fn, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JacXWy2qt61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/prototypes/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Prototipos","summary":"Todos los métodos que Total.js añade a String, Number, Date y Array.prototype.","markdown":"---\ntitle: Prototipos\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/prototypes/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Prototipos\n\n> Todos los métodos que Total.js añade a String, Number, Date y Array.prototype.\n\nMétodos que Total.js 5 añade a los prototipos integrados `String`, `Number`, `Date` y `Array`. Están disponibles en todas partes una vez cargado el framework. La guía [Prototipos](../../guides/prototypes/) muestra cómo usarlos con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### str.format(arg0, [arg1], [...])\n\nType: `method`\n\nReemplaza los placeholders numerados {0}, {1}, ... por los argumentos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0...argN` | `Any` | yes |  | Valores para `{0}`, `{1}`, etc. |\n\nReturns: `String` La nueva cadena.\n\nCada `{n}` se reemplaza por el argumento del índice `n`. Un placeholder cuyo argumento es `null` o `undefined` se convierte en una cadena vacía. Solo se permiten números dentro de las llaves; usa `String.args()` para claves con nombre.\n\nExample: Placeholders numerados\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n// Hello Peter, you have 5 messages.\n```\n\n### str.args(obj, [encode], [def])\n\nType: `method`\n\nReemplaza los placeholders 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` | `String|Function` | no |  | `html`, `json`, una función `(value, key)` o cualquier otro string para la codificación URL. |\n| `def` | `String` | no |  | El texto para las claves sin valor. |\n\nReturns: `String` La nueva cadena.\n\n`String.arg()` es el mismo método. Un marcador es una clave entre llaves simples o dobles; los espacios dentro de las llaves se recortan. Las claves se leen directamente de `obj` (sin rutas anidadas).\n\n`encode` cambia la salida de cada valor: `'html'` lo codifica con `String.encode()`, `'json'` escribe `JSON.stringify(value)`, cualquier otro string truthy usa `encodeURIComponent()`, y una función `(value, key)` devuelve el propio texto. Cuando `encode` es un string también sustituye a `def`: con `'html'` o un string de codificación URL, una clave sin valor se convierte en el texto de `encode`; con `'json'` se convierte en `undefined`. Sin `encode`, una clave sin valor se deja tal cual, o se sustituye por `def` cuando lo pasas.\n\nExample: Marcadores con nombre\n```js\nvar tpl = 'Hello {name}, your order {{ id }} is ready.';\ntpl.args({ name: 'Peter', id: 'A100' });\n// Hello Peter, your order A100 is ready.\n\n'<b>{name}</b>'.args({ name: '<script>' }, 'html');\n// <b>&lt;script&gt;</b>\n```\n\n### str.slug([max])\n\nType: `method`\n\nCrea un slug apto para URLs a partir del texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | La longitud máxima del slug. |\n\nReturns: `String` El slug.\n\nEl texto se recorta, se pasa a minúsculas y se eliminan los diacríticos (`toASCII()`). Se conservan las letras, los dígitos y `_`; los espacios y los caracteres `!\"#$%&'()*+,-./` se convierten en un único `-`; los demás caracteres se descartan. Se elimina un `-` final y el resultado tiene como máximo `max` caracteres.\n\nCuando el texto contiene un carácter sin forma ASCII cuyo código es mayor que 540 (por ejemplo letras cirílicas, `€` o un emoji), el texto no se convierte en slug letra por letra: en ese caso el método devuelve un identificador corto basado en un hash del texto, así que el resultado sigue siendo estable y seguro para URL.\n\nExample: Slug de un título\n```js\n' Hello World! Čaute 123 '.slug();\n// hello-world-caute-123\n\n'A very long article title'.slug(10);\n// a-very-lon\n```\n\n### str.max(length, [chars])\n\nType: `method`\n\nAcorta 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 acortada. |\n\nReturns: `String` El texto, acortado cuando hace falta.\n\nCuando el texto es más largo que `length`, se corta para que el resultado, incluido `chars`, tenga exactamente `length` caracteres. Un texto más corto se devuelve sin cambios.\n\nExample: Acortar\n```js\n'Hello world'.max(8);       // Hello...\n'Hello world'.max(8, '…');  // Hello w…\n```\n\n### str.capitalize([first])\n\nType: `method`\n\nPone en mayúscula la primera letra de cada palabra, o solo la del texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Poner en mayúscula solo el primer carácter. |\n\nReturns: `String` La nueva cadena.\n\nPrimero el texto se pasa a minúsculas. Sin argumentos, cada letra tras un espacio, tabulador o salto de línea pasa a mayúscula. Con `first` a `true`, solo el primer carácter pasa a mayúscula y el resto queda en minúsculas.\n\nExample: Capitalizar\n```js\n'hello WORLD'.capitalize();      // Hello World\n'hello WORLD'.capitalize(true);  // Hello world\n```\n\n### str.toName()\n\nType: `method`\n\nLimpia un nombre de persona: elimina dígitos, símbolos y espacios sobrantes, y pone las palabras en mayúscula inicial.\n\nReturns: `String` El nombre limpio.\n\nSolo se conservan las letras ASCII, los caracteres por encima del código 127 (letras con diacríticos) y los espacios. Los espacios repetidos se reducen a uno, los espacios finales se eliminan (los iniciales se convierten en un espacio) y la primera letra de cada palabra se pasa a mayúscula. El resto de cada palabra se mantiene tal cual.\n\nExample: Limpiar un nombre\n```js\n'peter   sirka 12'.toName();\n// Peter Sirka\n```\n\n### str.encode()\n\nType: `method`\n\nCodifica los caracteres especiales de HTML.\n\nReturns: `String` El texto codificado.\n\n`String.safehtml()` es el mismo método. Los caracteres `<`, `>`, `\"`, `'` y `&` se reemplazan por `&lt;`, `&gt;`, `&quot;`, `&apos;` y `&amp;`. Úsalo antes de poner texto de usuario en HTML.\n\nExample: Codificar la entrada del usuario\n```js\n'<a href=\"x\">Tom & Jerry</a>'.encode();\n// &lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/a&gt;\n```\n\n### str.decode()\n\nType: `method`\n\nDecodifica entidades HTML y las convierte de nuevo en caracteres.\n\nReturns: `String` El texto decodificado.\n\nLas entidades con nombre (`&lt;`, `&amp;`, `&quot;`, ...) y las entidades numéricas (`&#65;`, `&#x41;`) se reemplazan por sus caracteres. Las entidades con nombre desconocidas quedan tal cual.\n\nExample: Decodificar\n```js\n'&lt;b&gt;Tom &amp; Jerry&#33;&lt;/b&gt;'.decode();\n// <b>Tom & Jerry!</b>\n```\n\n### str.removeTags()\n\nType: `method`\n\nElimina las etiquetas HTML del texto.\n\nReturns: `String` El texto sin etiquetas.\n\nSe elimina cada etiqueta `<...>` (de apertura o de cierre); el texto entre etiquetas se mantiene. El resultado no está codificado en HTML, así que codifícalo con `String.encode()` cuando lo vuelvas a escribir en HTML.\n\nExample: Quitar etiquetas\n```js\n'<p><b>Hi</b> there</p>'.removeTags();\n// Hi there\n```\n\n### str.padLeft(max, [c])\n\nType: `method`\n\nRellena el texto por la izquierda hasta una longitud. String.padRight() rellena por la derecha.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longitud del resultado. |\n| `c` | `String` | no | `' '` | El carácter de relleno. |\n\nReturns: `String` El texto rellenado.\n\nSe añaden caracteres `c` hasta que el texto tiene `max` caracteres; un texto más largo se devuelve sin cambios. `str.padRight(max, [c])` funciona igual por el lado derecho. Ambos solo se definen cuando el runtime no los tiene ya.\n\nExample: Rellenar\n```js\n'5'.padLeft(3, '0');   // 005\n'a'.padRight(3, '-');  // a--\n```\n\n### str.toASCII()\n\nType: `method`\n\nReemplaza las letras con diacríticos por su forma ASCII.\n\nReturns: `String` El texto sin diacríticos.\n\nLetras como `č`, `á` o `ü` se reemplazan por `c`, `a` y `u`. Los caracteres sin forma ASCII quedan tal cual.\n\nExample: Quitar diacríticos\n```js\n'Čučoriedka'.toASCII();\n// Cucoriedka\n```\n\n### str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrae palabras clave del texto, las más frecuentes primero.\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 las palabras al 80 % de su longitud. |\n| `max_count` | `Number` | no | `200` | El número máximo de palabras a leer. |\n| `max_length` | `Number` | no | `20` | La longitud máxima de una palabra clave. |\n| `min_length` | `Number` | no | `2` | La longitud mínima de una palabra clave. |\n\nReturns: `Array` Palabras clave únicas ordenadas por frecuencia.\n\nEl texto se pasa a minúsculas y se divide en palabras; de cada palabra se eliminan los caracteres que no son letras ni dígitos. Con `forsearch` (por defecto) se eliminan los diacríticos y `y` pasa a ser `i`, lo que hace la coincidencia tolerante. `alternative` mantiene solo el primer 80 % de las palabras más largas (una raíz simple). Las palabras más cortas que `min_length` o más largas que `max_length` se omiten y se leen como máximo `max_count` palabras. Las palabras únicas se devuelven ordenadas por la frecuencia con que aparecen.\n\nPara una única cadena de búsqueda normalizada usa `str.toSearch()`: pasa el texto a minúsculas, elimina diacríticos y símbolos, reemplaza `y` por `i` y elimina letras repetidas (`hello` pasa a ser `helo`).\n\nExample: Palabras clave para un índice de búsqueda\n```js\n'Total.js is a great framework, great!'.toKeywords();\n// ['great', 'totaljs', 'is', 'framework']\n\n'Čaute Hello'.toSearch();\n// caute helo\n```\n\n### str.pluralize(zero, one, few, other)\n\nType: `method`\n\nConvierte el texto en un número y elige una forma de plural.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Texto para 0, o las cuatro formas separadas por comas. |\n| `one` | `String` | no |  | Texto para 1. |\n| `few` | `String` | no |  | Texto para 2 a 4. |\n| `other` | `String` | no |  | Texto para los demás números. |\n\nReturns: `String` La forma elegida.\n\nEl texto se convierte con `parseInt()` y el resultado se pasa a `Number.pluralize()`.\n\nExample: Pluralizar una cadena\n```js\n'3'.pluralize('no items', '# item', '# items', '# items');\n// 3 items\n```\n\n### str.parseInt([def])\n\nType: `method`\n\nConvierte el texto en un número, con un valor por defecto para texto no válido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | El valor para un texto que no es un número. |\n\nReturns: `Number` El número o el valor por defecto.\n\nEl texto se recorta y se convierte con el `+` unario, así que `'10'` es `10`, `'1.5'` es `1.5` y `'0x10'` es `16`. Cuando el texto no es un número, se devuelve `def` (`0` si lo omites).\n\n`str.parseInt2([def])` busca en cambio el primer entero en cualquier parte del texto (`'abc 123'` da `123`); `str.parseFloat2([def])` hace lo mismo para un número decimal y acepta `,` como separador decimal.\n\nExample: Leer números\n```js\n'10'.parseInt();        // 10\n'abc'.parseInt(5);      // 5\n'Total: 123 EUR'.parseInt2(); // 123\n'x 1,5 y'.parseFloat2();      // 1.5\n```\n\n### str.parseFloat([def])\n\nType: `method`\n\nConvierte el texto en un número decimal; se acepta una coma como separador decimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | El valor para un texto que no es un número. |\n\nReturns: `Number` El número o el valor por defecto.\n\nEl texto se recorta, la primera `,` se reemplaza por `.` y el texto se convierte en un número. Cuando el texto no es un número, se devuelve `def` (`0` si lo omites).\n\nExample: Leer decimales\n```js\n'1,5'.parseFloat();    // 1.5\n' 2.25 '.parseFloat(); // 2.25\n'n/a'.parseFloat(-1);  // -1\n```\n\n### str.parseBoolean()\n\nType: `method`\n\nConvierte el texto en un booleano.\n\nReturns: `Boolean`\n\nDevuelve `true` para `true`, `1` y `on` (sin distinguir mayúsculas y minúsculas) y `false` para todo lo demás.\n\nExample: Leer un flag\n```js\n'on'.parseBoolean();    // true\n'TRUE'.parseBoolean();  // true\n'no'.parseBoolean();    // false\n```\n\n### str.parseDate([format])\n\nType: `method`\n\nConvierte el texto en un Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Un formato como `dd/MM/yyyy HH:mm`. |\n\nReturns: `Date` La fecha analizada.\n\nSin `format`, el método entiende:\n\n- fechas JSON (`2024-05-01T12:30:00.000Z`),\n- `yyyy-MM-dd`, `yyyy-MM-dd HH:mm`, `yyyy-MM-dd HH:mm:ss` y `yyyy-MM-ddTHH:mm:ss.SSS`,\n- `d.M.yyyy` con una hora opcional (`1.5.2024 08:00`),\n- cualquier otra cosa que acepte `new Date(text)`.\n\nLa fecha y la hora de estas formas se leen como UTC. Las partes que faltan de la fecha se toman de hoy.\n\nCon `format`, los dígitos del texto se leen según las posiciones de `yyyy`, `MM`, `dd`, `HH`, `mm` y `ss` en el formato; los demás caracteres del formato solo separan las partes. Las partes deben escribirse con todos sus dígitos (`05`, no `5`). Un año de dos dígitos está en los años 2000, y `pm` en el texto suma 12 horas.\n\nExample: Parsear fechas\n```js\n'2024-05-01 12:30'.parseDate();\n// 2024-05-01T12:30:00.000Z\n\n'1.5.2024'.parseDate();\n// 2024-05-01T00:00:00.000Z\n\n'01/05/2024'.parseDate('dd/MM/yyyy');\n// 1 May 2024\n```\n\n### str.parseDateExpiration()\n\nType: `method`\n\nConvierte un tiempo relativo como \"5 minutes\" en un Date futuro.\n\nReturns: `Date` La hora actual más la duración indicada.\n\nEl texto es una lista de pares `number unit` separados por espacios. Cada par se suma a la hora actual con `Date.add()`, así que funcionan todas las unidades de `Date.add()` (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years` y sus formas cortas). Usa un número negativo para una fecha en el pasado.\n\nExample: Expiración\n```js\nvar expire = '5 minutes'.parseDateExpiration();\nvar later = '1 day 2 hours'.parseDateExpiration();\n```\n\n### str.parseJSON([date])\n\nType: `method`\n\nParsea JSON sin lanzar excepciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | Convertir las cadenas de fecha JSON en objetos Date. |\n\nReturns: `Object` El valor parseado o `undefined`.\n\nDevuelve el valor parseado, o `undefined` cuando el texto no es JSON válido. Con `date` a `true`, las cadenas en el formato de fecha JSON (`2024-01-01T10:00:00.000Z`) se convierten en objetos `Date`.\n\nExample: Parseo seguro\n```js\nvar obj = '{\"a\":1}'.parseJSON();          // { a: 1 }\nvar bad = '{a:1'.parseJSON();             // undefined\nvar doc = '{\"created\":\"2024-01-01T10:00:00.000Z\"}'.parseJSON(true);\ndoc.created instanceof Date;             // true\n```\n\n### str.parseCSV([delimiter])\n\nType: `method`\n\nParsea texto CSV en un array de objetos con las claves de columna a, b, c, ...\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | El delimitador de columnas, un carácter. |\n\nReturns: `Array` Un array de objetos.\n\nCada línea se convierte en un objeto. Las claves son letras de columna: `a` para la primera columna, `b` para la segunda, ..., `z`, luego `aa`, `ab`, etc. Los valores entre comillas dobles pueden contener el delimitador y saltos de línea; `\"\"` dentro de comillas es una comilla escapada. Las columnas vacías no tienen clave en el objeto. Los valores son cadenas y no se recortan. Una línea de cabecera se devuelve como cualquier otra línea.\n\nExample: Parsear CSV\n```js\nvar rows = 'name,age\\n\"Sirka, Peter\",40\\nAnna,'.parseCSV();\n// [{ a: 'name', b: 'age' }, { a: 'Sirka, Peter', b: '40' }, { a: 'Anna' }]\n\nvar header = rows.shift();\nfor (var row of rows)\n\tconsole.log(row.a, row.b || '-');\n```\n\n### str.parseContext()\n\nType: `method` · Since: `0.0.17`\n\nParsea un texto formado por bloques con una cabecera y un cuerpo.\n\nReturns: `Array` Un array de objetos, uno por bloque.\n\nCada bloque empieza con una línea de al menos 20 guiones, seguida de líneas de cabecera `key: value`, otra línea de al menos 20 guiones y el cuerpo. El cuerpo termina donde empieza el siguiente bloque. Cada bloque se convierte en un objeto con las claves de la cabecera (en minúsculas, valores recortados) y una propiedad `body` con el cuerpo recortado. Las líneas de cabecera sin `:` se ignoran.\n\nExample: Parsear bloques\n```js\nvar text = [\n\t'--------------------',\n\t'Name: Hello',\n\t'Type: note',\n\t'--------------------',\n\t'Body one',\n\t'--------------------',\n\t'Name: Second',\n\t'--------------------',\n\t'Body two'\n].join('\\n');\n\ntext.parseContext();\n// [{ name: 'Hello', type: 'note', body: 'Body one' }, { name: 'Second', body: 'Body two' }]\n```\n\n### str.parseEncoded()\n\nType: `method`\n\nParsea texto codificado como URL (un query string o un cuerpo de formulario) en un objeto.\n\nReturns: `Object` Las claves y valores parseados (cadenas).\n\nLos pares `key=value` se separan con `&`; las claves y los valores se decodifican como URL. Es el parser que Total.js usa para los query strings y los cuerpos `application/x-www-form-urlencoded`.\n\nExample: Parsear un query string\n```js\n'q=total.js&page=2&name=%20Peter'.parseEncoded();\n// { q: 'total.js', page: '2', name: ' Peter' }\n```\n\n### str.parseConfig([def], [onerr])\n\nType: `method`\n\nParsea texto en el formato de configuración de Total.js en un objeto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Valores por defecto que se copian primero en el resultado. |\n| `onerr` | `Function` | no |  | `function(err, line)` para los valores que no se pueden evaluar. |\n\nReturns: `Object` Los valores parseados.\n\nCada línea es `key : value`. El separador es el primer `:`, o el primer `=` cuando la línea no tiene `:`; el valor empieza en el segundo carácter después del separador, así que deja un espacio ahí. Las líneas vacías y las que empiezan por `#` o `//` se omiten. Un valor que empieza por `base64 ` o `hex ` se decodifica.\n\nUn tipo entre paréntesis después de la clave convierte el valor: `(string)`, `(number)` (también `float`, `double`, `currency`), `(boolean)` / `(bool)` (true cuando el valor contiene `true`, `on`, `1` o `enabled`, en mayúsculas o minúsculas), `(json)`, `(object)` / `(array)` / `(eval)` (evaluado como JavaScript), `(date)`, `(env)` (lee `process.env[value]`), `(config)` (lee otra clave de configuración) y `(random)` (un string aleatorio de la longitud indicada). Cuando falla un valor evaluado, se llama a `onerr(err, line)`, o se lanza un error si no lo pasas.\n\nExample: Parsear ajustes\n```js\nvar text = 'name : Shop\\ncount (number) : 10\\nenabled (boolean) : true\\n# comment\\ntags (array) : [\\'a\\', \\'b\\']';\ntext.parseConfig();\n// { name: 'Shop', count: 10, enabled: true, tags: ['a', 'b'] }\n```\n\n### str.parseEnv()\n\nType: `method`\n\nParsea texto en el formato .env en un objeto.\n\nReturns: `Object` Las claves y los valores.\n\nCada línea es `KEY=value`. Las líneas vacías o que empiezan por `#` o `//` se omiten. A un valor entre comillas simples o dobles se le quitan las comillas (sus espacios internos se mantienen); los demás valores se recortan. `\\n` en un valor se convierte en un salto de línea. Todos los valores son cadenas.\n\nExample: Parsear .env\n```js\n'PORT=8000\\nNAME=\"My app\"\\n# comment'.parseEnv();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### str.parseUA([structured])\n\nType: `method`\n\nLee el sistema operativo, el navegador y el tipo de dispositivo de una cabecera User-Agent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Devolver un objeto en lugar de texto. |\n\nReturns: `String|Object`\n\nSin argumentos, el resultado es un texto corto como `Windows Chrome`. Con `structured` a `true`, el resultado es un objeto `{ os, browser, device }`, donde `device` es `mobile` o `desktop`. Un texto vacío devuelve una cadena vacía.\n\nExample: Leer el user agent\n```js\nvar ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Version/17.0 Mobile Safari/604.1';\nua.parseUA();      // iPhone Safari\nua.parseUA(true);  // { os: 'iPhone', browser: 'Safari', device: 'mobile' }\n```\n\n### str.isEmail()\n\nType: `method`\n\nComprueba que el texto es una dirección de e-mail.\n\nReturns: `Boolean`\n\nLa prueba usa la expresión regular `email` de `DEF.validators`: letras, dígitos y `-_.+` antes de `@`, un dominio y un dominio de primer nivel de al menos dos letras. Un texto de cuatro caracteres o menos nunca es válido.\n\nExample: Validar\n```js\n'info@example.com'.isEmail();  // true\n'info@example'.isEmail();      // false\n```\n\n### str.isPhone()\n\nType: `method`\n\nComprueba que el texto es un número de teléfono.\n\nReturns: `Boolean`\n\nLa prueba usa la expresión regular `phone` de `DEF.validators`: un `+` opcional, tres dígitos (opcionalmente entre paréntesis), tres dígitos y de 4 a 8 dígitos, cada grupo opcionalmente separado por `-`, `.` o un espacio. Un texto de menos de seis caracteres nunca es válido.\n\nExample: Validar\n```js\n'+421903123456'.isPhone();  // true\n'(123) 456-7890'.isPhone(); // true\n'12345'.isPhone();          // false\n```\n\n### str.isURL()\n\nType: `method`\n\nComprueba que el texto es una URL http o https.\n\nReturns: `Boolean`\n\nEl texto debe empezar por `http://` o `https://` y no debe contener `,`, `{`, `}` ni `\\`. Un texto de siete caracteres o menos nunca es válido.\n\nExample: Validar\n```js\n'https://www.totaljs.com'.isURL();  // true\n'www.totaljs.com'.isURL();          // false\n```\n\n### str.isUID()\n\nType: `method`\n\nComprueba que el texto es un identificador válido creado por UID().\n\nReturns: `Boolean`\n\nEl método comprueba el formato y el checksum de los identificadores creados por `UID()`, así que una cadena aleatoria con la misma forma se rechaza. Para leer la fecha y el índice guardados en un UID usa `str.parseUID()`, que devuelve `{ version, date, century, hash, index, valid }`. Para GUIDs estándar (`8-4-4-4-12` dígitos hexadecimales) usa `str.isGUID()`.\n\nExample: Validar un id\n```js\nvar id = UID();\nid.isUID();       // true\n'abc'.isUID();    // false\nid.parseUID().date;  // the time the id was created\n'123e4567-e89b-12d3-a456-426614174000'.isGUID(); // true\n```\n\n### str.isNumber([isDecimal])\n\nType: `method`\n\nComprueba que el texto contiene solo dígitos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `isDecimal` | `Boolean` | no | `false` | Permitir un separador decimal. |\n\nReturns: `Boolean`\n\nCada carácter debe ser un dígito. Con `isDecimal` a `true`, también se permite un `.` o una `,`. No se permite un signo (`-`, `+`) y un texto vacío no es un número.\n\nExample: Validar\n```js\n'0123'.isNumber();      // true\n'1.5'.isNumber();       // false\n'1,5'.isNumber(true);   // true\n```\n\n### str.isJSON()\n\nType: `method`\n\nComprueba rápidamente que el texto parece un objeto, array o cadena JSON.\n\nReturns: `Boolean`\n\nSe omiten los espacios en blanco iniciales y finales y se comparan el primer y el último carácter: `{` con `}`, `[` con `]` o `\"` con `\"`. También es `true` cuando el texto empieza por un dígito o una letra y termina con un carácter menor que `9`, por ejemplo `'123'` o `'abc1'`. El contenido no se parsea, así que usa `String.parseJSON()` cuando necesites estar seguro.\n\nExample: Comprobar antes de parsear\n```js\nvar body = ' {\"a\":1} ';\nif (body.isJSON())\n\tvar obj = body.parseJSON();\n```\n\n### str.isXSS()\n\nType: `method`\n\nComprueba que el texto contiene una etiqueta HTML.\n\nReturns: `Boolean`\n\nDevuelve `true` cuando el texto contiene `<` seguido más adelante de `>`, que es como la expresión regular `xss` de `DEF.validators` detecta marcado en la entrada del usuario. `str.isSQLInjection()` funciona igual con la expresión `sqlinjection`: es `true` para cadenas entre comillas y para las palabras clave SQL `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` y `UNION` escritas en mayúsculas. Ambos son filtros simples, no sustituyen la codificación de la salida ni los parámetros de las consultas.\n\nExample: Rechazar marcado\n```js\n'<script>alert(1)</script>'.isXSS();  // true\n'Hello'.isXSS();                      // false\n'DROP TABLE users'.isSQLInjection();   // true\n```\n\n### str.hash([type], [salt])\n\nType: `method`\n\nDevuelve un hash del texto: un hash numérico rápido o un digest md5, sha1, sha256, sha512 o crc32.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32`, `crc32unsigned`, o `true` para un hash numérico sin signo. |\n| `salt` | `String` | no |  | Texto que se añade antes del hash. |\n\nReturns: `Number|String` Un número para el hash numérico y crc32; una cadena hexadecimal en los demás casos.\n\n`type` selecciona el algoritmo: `md5`, `sha1`, `sha256`, `sha512` (cadenas hexadecimales), `crc32` (número con signo) o `crc32unsigned` (número sin signo). Sin `type`, el método devuelve un hash numérico rápido de 32 bits del texto (con signo); `hash(true)` lo devuelve sin signo. `salt` se añade al texto antes del hash. El hash numérico no es un hash criptográfico: úsalo para claves de caché y fines similares. `str.crc32([unsigned])` también está disponible directamente.\n\nExample: Hashes\n```js\n'hello'.hash();          // a signed 32-bit number\n'hello'.hash(true);      // the same, unsigned\n'hello'.hash('sha256');  // hex digest\n'hello'.hash('crc32unsigned');\n```\n\n### str.md5([salt])\n\nType: `method`\n\nDevuelve el digest MD5 del texto 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` 32 caracteres hexadecimales.\n\nEl texto (con `salt` añadido) se procesa como UTF-8 con `crypto` de Node.js. MD5 sirve para checksums y claves de caché, no para contraseñas.\n\nExample: MD5\n```js\n'a'.md5();\n// 0cc175b9c0f1b6a831c399e269772661\n```\n\n### str.sha256([salt])\n\nType: `method`\n\nDevuelve el digest SHA-256 del texto como cadena hexadecimal. sha1() y sha512() funcionan igual.\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` 64 caracteres hexadecimales.\n\nEl texto (con `salt` añadido) se procesa como UTF-8 con `crypto` de Node.js. `str.sha1([salt])` devuelve 40 caracteres hexadecimales y `str.sha512([salt])` 128 caracteres hexadecimales.\n\nExample: Digests SHA\n```js\nvar digest = 'password'.sha256(CONF.secret);\nvar short = 'text'.sha1();\nvar long = 'text'.sha512();\n```\n\n### str.sign([key], [check])\n\nType: `method`\n\nFirma el texto con un checksum corto, o comprueba y elimina la firma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | La clave de firma. |\n| `check` | `Boolean` | no | `false` | Comprueba la firma y devuelve el texto original. |\n\nReturns: `String` El texto firmado, el texto original o `null`.\n\n`str.sign(key)` devuelve `text-checksum`, donde el checksum se calcula a partir del texto y de `key`. `signed.sign(key, true)` comprueba el checksum y devuelve el texto original, o `null` cuando la firma no coincide. Úsalo para valores que viajan por URLs y no deben modificarse, como ids en enlaces. No es cifrado: el texto sigue siendo legible.\n\n`str.makeid()` devuelve solo un checksum corto en base 36 del texto, práctico como clave compacta.\n\nExample: Firmar un id\n```js\nvar token = '123'.sign('mykey');     // 123-155hlxd\ntoken.sign('mykey', true);           // 123\n(token + 'x').sign('mykey', true);   // null\n```\n\n### str.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nCifra el texto con una clave. String.decrypt() lo revierte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave de cifrado. |\n| `isUnique` | `Boolean` | no | `false` | Generar un resultado distinto en cada llamada. |\n| `secret` | `String` | no | `CONF.secret` | El secreto usado en el checksum. |\n\nReturns: `String` El texto cifrado.\n\nEl resultado es una cadena formada por un checksum, `-` y datos hexadecimales. Con `isUnique` a `true`, el mismo texto da un resultado distinto cada vez. El checksum usa `secret`, o la clave de configuración `secret` cuando lo omites.\n\n`str.decrypt(key, [secret])` devuelve el texto original, o `null` cuando la clave, el secreto o los datos no coinciden. Usa los mismos `key` y `secret` para ambos.\n\nExample: Cifrar y descifrar\n```js\nvar value = 'user@example.com'.encrypt('mykey', true);\nvalue.decrypt('mykey');   // user@example.com\nvalue.decrypt('other');   // null\n```\n\n### str.encrypt_uid([key])\n\nType: `method`\n\nCifra un identificador en un token corto y seguro para URLs. String.decrypt_uid() lo revierte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | La clave. |\n\nReturns: `String` El token.\n\nÚsalo para ocultar ids numéricos o de texto en URLs públicas. `key` toma por defecto la clave de configuración `secret`. `token.decrypt_uid([key])` devuelve el id original, o `null` cuando el token se modificó o la clave es distinta.\n\nExample: Ocultar un id\n```js\nvar token = '123'.encrypt_uid('mykey');\ntoken.decrypt_uid('mykey');  // 123\n```\n\n### str.base64ToBuffer()\n\nType: `method`\n\nConvierte texto base64 o un data URI en un Buffer.\n\nReturns: `Buffer` Los datos decodificados.\n\nSe omite todo hasta la primera `,` incluida, así que funcionan tanto el base64 simple como `data:...;base64,...`. Métodos relacionados: `str.base64ToFile(filename, [callback])` escribe los datos decodificados en un archivo, `str.base64ContentType()` devuelve el content type de un data URI (`image/png`), y `str.parseDataURI()` devuelve `{ type, buffer }` (o `null` para un texto que no es un data URI).\n\nExample: Decodificar una subida\n```js\nvar uri = 'data:text/plain;base64,aGVsbG8=';\nuri.base64ToBuffer().toString();   // hello\nuri.base64ContentType();           // text/plain\nuri.parseDataURI().type;           // text/plain\nuri.base64ToFile(PATH.temp('hello.txt'));\n```\n\n### num.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormatea un número con un separador de miles y un número fijo de 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 es un espacio por defecto. El separador decimal es `.`, o `,` cuando el separador de miles es `.`. Los decimales sobrantes se cortan, no se redondean, así que llama primero a `Number.round()` cuando necesites redondear. Los decimales que faltan se rellenan con ceros. Cuando el primer argumento es una cadena, los dos primeros argumentos se intercambian: `format('.', 2)` es lo mismo que `format(2, '.')`.\n\nExample: Formatear\n```js\n(1234567.891).format(2);           // 1 234 567.89\n(1234.5).format(2, ',', '.');      // 1,234.50\n(1234.5).format('.', 2);           // 1.234,50\n(1.999).round(2).format(2);        // 2.00\n```\n\n### num.pluralize(zero, one, few, other)\n\nType: `method`\n\nElige una forma de plural según el número; # se reemplaza por el número.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Texto para 0, o las cuatro formas separadas por comas. |\n| `one` | `String` | no |  | Texto para 1. |\n| `few` | `String` | no |  | Texto para 2 a 4. |\n| `other` | `String` | no |  | Texto para los demás números. |\n\nReturns: `String` La forma elegida.\n\nLa forma `zero` se usa para 0, `one` para 1, `few` de 2 a 4 y `other` para el resto (la regla de las lenguas eslavas; para inglés pasa el mismo texto como `few` y `other`). Cuando pasas una sola cadena, se divide por comas en las cuatro formas. El primer `#` de la forma elegida se reemplaza por el número.\n\nExample: Formas de plural\n```js\n(1).pluralize('no items', '# item', '# items', '# items');  // 1 item\n(7).pluralize('no items,# item,# items,# items');          // 7 items\n```\n\n### num.padLeft(max, [c])\n\nType: `method`\n\nRellena el número por la izquierda con ceros. Number.padRight() rellena por la derecha.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longitud del resultado. |\n| `c` | `String` | no | `'0'` | El carácter de relleno. |\n\nReturns: `String` El número rellenado.\n\nEl número se convierte en cadena y se rellena hasta `max` caracteres con `c` (`0` por defecto). `num.padRight(max, [c])` rellena por la derecha.\n\nExample: Relleno con ceros\n```js\n(5).padLeft(3);       // 005\n(7).padLeft(4, ' ');  // '   7'\n(5).padRight(3);      // 500\n```\n\n### num.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` | yes |  | El número de decimales. |\n\nReturns: `Number` El número redondeado.\n\nEl redondeo usa notación exponencial, así que valores como `1.005` se redondean correctamente a `1.01`. `num.floor(decimals)` redondea en cambio hacia abajo a un número de decimales (`(1.239).floor(2)` es `1.23`).\n\nExample: Redondear\n```js\n(1.005).round(2);  // 1.01\n(2.5).round(0);    // 3\n(1.239).floor(2);  // 1.23\n```\n\n### num.fixed(decimals)\n\nType: `method`\n\nRedondea el número con toFixed() y devuelve un número, no una cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | El número de decimales. |\n\nReturns: `Number`\n\nExample: Fixed\n```js\n(1.236).fixed(2);  // 1.24 (a number)\n```\n\n### num.between(condition, [otherwise])\n\nType: `method`\n\nDevuelve el valor del primer rango que contiene el número.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Rangos como claves, resultados como valores. |\n| `otherwise` | `Any` | no |  | El resultado cuando ningún rango coincide. |\n\nReturns: `Any` El valor del rango que coincide u `otherwise`.\n\n`condition` es un objeto cuyas claves son rangos: `'1-3'` (de 1 a 3, ambos incluidos), `'7-'` (7 o más) o `'-5'` (5 o menos). Las claves se prueban en orden y se devuelve el valor de la primera clave que coincide. Cuando ningún rango coincide, se devuelve `otherwise`.\n\nExample: Calificar una puntuación\n```js\nvar score = 5;\nscore.between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }, 'unknown');\n// medium\n```\n\n### num.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAñade un impuesto al número, o lo quita de un precio que lo incluye.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | El tipo impositivo en porcentaje. |\n| `decimals` | `Number` | no | `2` | El número de decimales. |\n| `includedVAT` | `Boolean` | no | `false` | El número ya incluye el impuesto. |\n\nReturns: `Number`\n\n`Number.TAX()` es el mismo método. Sin `includedVAT`, el resultado es el número incrementado en `percentage`. Con `includedVAT` a `true`, el número es un precio que ya incluye el impuesto, y el resultado es el precio sin el impuesto. El resultado se redondea a `decimals` (2 por defecto). Puedes pasar el booleano como segundo argumento: `VAT(20, true)`.\n\nExample: Precios con IVA\n```js\n(100).VAT(20);        // 120\n(120).VAT(20, true);  // 100\n(99.99).TAX(10, 0);   // 110\n```\n\n### num.discount(percentage, [decimals])\n\nType: `method`\n\nReduce el número en un porcentaje.\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`\n\nEl resultado se redondea hacia abajo a `decimals` (2 por defecto).\n\nExample: Descuento\n```js\n(100).discount(15);    // 85\n(19.99).discount(10);  // 17.99\n```\n\n### num.filesize([decimals], [type])\n\nType: `method`\n\nFormatea un número de bytes como un tamaño legible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | El número de decimales. |\n| `type` | `String` | no |  | `bytes`, `KB`, `MB`, `GB` o `TB`. |\n\nReturns: `String` El tamaño con su unidad.\n\nSin `type` se elige la mayor unidad que encaja: `bytes`, `KB`, `MB`, `GB` o `TB` (1 KB son 1024 bytes). Con `type` el valor se convierte a esa unidad. Sin `decimals` el valor tiene hasta dos decimales y se elimina `.00`; con `decimals` se formatea con `Number.format(decimals)`. Los argumentos se pueden pasar en cualquier orden.\n\nExample: Tamaños de archivo\n```js\n(500).filesize();          // 500 bytes\n(1536000).filesize();      // 1.46 MB\n(5000000).filesize(1, 'MB'); // 4.7 MB\n```\n\n### num.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormatea el número como un importe con un formateador de moneda registrado en DEF.currencies.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | La clave en `DEF.currencies`. |\n| `a, b, c` | `Any` | no |  | Argumentos adicionales para el formateador. |\n\nReturns: `String` El importe formateado.\n\nEl formateador es la función `DEF.currencies[currency]` (o `DEF.currencies.default` sin `currency`). Recibe el número y los argumentos `a`, `b` y `c` y devuelve el texto. Cuando no existe un formateador para la moneda, el resultado es `num.format(2)`. Registra los formateadores al arrancar, por ejemplo en un archivo de definiciones.\n\nExample: Registrar y usar una moneda\n```js\n// /definitions/currencies.js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2, ' ', ',') + ' €';\n};\n\n(1234.5).currency('eur');  // 1 234,50 €\n(10).currency('usd');      // 10.00 (no formatter)\n```\n\n### date.add(type, [value])\n\nType: `method`\n\nDevuelve una nueva fecha desplazada una cantidad de tiempo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | La unidad, una cadena con valor y unidad, o milisegundos. |\n| `value` | `Number` | no |  | La cantidad, negativa para el pasado. |\n\nReturns: `Date` Una nueva fecha.\n\nLa fecha original no se modifica. Pasa la unidad y el valor (`add('minutes', 30)`), una cadena con ambos (`add('30 minutes')`, `add('-2 hours')`) o un número de milisegundos (`add(5000)`).\n\nUnidades: `s`, `ss`, `sec`, `second`, `seconds`; `m`, `mm`, `min`, `minute`, `minutes`; `h`, `hh`, `hour`, `hours`; `d`, `dd`, `day`, `days`; `w`, `ww`, `week`, `weeks`; `M`, `MM`, `month`, `months`; `y`, `yyyy`, `year`, `years`. Las unidades trabajan sobre las partes UTC de la fecha. Sumar meses al final de un mes sigue a JavaScript: el 31 de enero más un mes es el 2 de marzo en un año bisiesto y el 3 de marzo en los demás.\n\nExample: Desplazar fechas\n```js\nvar now = new Date();\nnow.add('1 day');\nnow.add('minutes', 30);\nnow.add('-2 hours');\nnow.add(5000);  // + 5 seconds\n```\n\n### date.diff([date], type)\n\nType: `method`\n\nDevuelve la diferencia entre dos fechas en segundos, minutos, horas o días.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String|Number` | no | `now` | La fecha con la que comparar. |\n| `type` | `String` | yes |  | La unidad del resultado. |\n\nReturns: `Number` La diferencia en la unidad.\n\nEl resultado es `this - date` en la unidad indicada, redondeado hacia arriba, así que es positivo cuando `this` es posterior. `date` puede ser un Date, una cadena que entienda `Date.parse()` o un número de milisegundos. Con un solo argumento, la fecha se compara con la hora actual. Unidades: `s` / `ss` / `second` / `seconds`, `m` / `mm` / `minute` / `minutes`, `h` / `hh` / `hour` / `hours`, `d` / `dd` / `day` / `days`. Una unidad desconocida devuelve `NaN`.\n\nExample: Diferencias\n```js\nvar created = new Date('2024-01-30T00:00:00Z');\nvar end = new Date('2024-01-31T10:00:00Z');\nend.diff(created, 'hours');  // 34\nend.diff('2024-01-01T00:00:00Z', 'days'); // 31\ncreated.diff('seconds');     // negative: created is in the past\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormatea la fecha según un patrón; sin patrón devuelve una cadena ISO en UTC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | El patrón. |\n| `resource` | `String` | no |  | El recurso usado para los nombres de meses y días. |\n\nReturns: `String` La fecha formateada.\n\nSin `format`, el resultado es `yyyy-MM-ddTHH:mm:ss.SSSZ` en UTC. Con `format`, las partes se escriben en la zona horaria del servidor (UTC salvo que la clave de configuración `$timezone` diga otra cosa):\n\n- `yyyy`, `yy` año; `MM`, `M` número de mes; `MMMM` nombre del mes, `MMM` sus tres primeras letras,\n- `dd`, `d` día; `dddd` nombre del día, `ddd` sus dos primeras letras en mayúsculas,\n- `HH`, `H` horas (0-23); `mm`, `m` minutos; `ss`, `s` segundos,\n- `ww`, `w` número de semana ISO; `a` `AM` o `PM`.\n\nTambién se aceptan `YYYY`, `YY`, `DD`, `D`, `DDDD`, `DDD` en mayúsculas y `hh`, `h` en minúsculas. Los nombres de meses y días están en inglés; con `resource` se traducen con el archivo de recursos de ese nombre. Los formatos compilados se guardan en caché, así que el formateo es rápido.\n\nExample: Formatear fechas\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.format();                      // 2024-01-31T10:00:00.000Z\nd.format('yyyy-MM-dd HH:mm');    // 2024-01-31 10:00\nd.format('dd.MM.yy');            // 31.01.24\nd.format('dddd, d. MMMM yyyy');  // Wednesday, 31. January 2024\nd.format('MMMM', 'sk');          // the month name from sk.resource\n```\n\n### date.extend(text)\n\nType: `method`\n\nDevuelve una nueva fecha con las partes de fecha u hora reemplazadas a partir de un texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Una fecha, una hora o ambas. |\n\nReturns: `Date` Una nueva fecha.\n\nEl texto puede contener una fecha `yyyy-MM-dd` o `d.M.yyyy` y una hora `HH:mm` o `HH:mm:ss`. Solo se sustituyen las partes que aparecen en el texto; las demás se toman de la fecha original. El año, el mes y el día se establecen uno tras otro, así que cuando el día de la fecha original no existe en el nuevo mes, la fecha pasa al mes siguiente (el 31 de enero ampliado con `2025-02-10` da el 10 de marzo de 2025). Los valores están en UTC.\n\nExample: Cambiar partes\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.extend('12:30');              // 2024-01-31T12:30:00.000Z\nd.extend('2025-03-04');         // 2025-03-04T10:00:00.000Z\nd.extend('1.3.2020 08:00');     // 2020-03-01T08:00:00.000Z\n```\n\n### date.toUTC([ticks])\n\nType: `method`\n\nDesplaza una fecha local a UTC según el desfase de la zona horaria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Devolver milisegundos. |\n\nReturns: `Date|Number`\n\nEl resultado es la fecha más el desfase de la zona horaria del servidor. Con `ticks` a `true`, el resultado es el número de milisegundos en lugar de un Date. En un servidor que se ejecuta en UTC (por defecto) la fecha no cambia.\n\nExample: A UTC\n```js\nvar utc = new Date().toUTC();\nvar ms = new Date().toUTC(true);\n```\n\n### date.setTimeZone(timezone)\n\nType: `method`\n\nDevuelve una nueva fecha que muestra el mismo instante en otra zona horaria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | Un nombre de zona horaria IANA. |\n\nReturns: `Date` Una nueva fecha.\n\nLas partes del resultado (horas, día, ...) leídas en la zona horaria del servidor son la hora local de `timezone` en ese instante, así que `format()` imprime la hora local de esa zona. `timezone` es un nombre IANA como `Europe/Bratislava` o `America/New_York`.\n\nExample: Mostrar la hora local\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.setTimeZone('Europe/Bratislava').format('HH:mm');  // 11:00\n```\n\n### arr.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|Any` | yes |  | Una función de prueba, un nombre de propiedad o un valor. |\n| `value` | `Any` | no |  | El valor de la propiedad. |\n\nReturns: `Object` El elemento o `null`.\n\nPasa una función `(item, index)`, un nombre de propiedad y un valor (`('id', 5)` compara `item.id === 5`), o un único valor que se compara con `===`.\n\nExample: Buscar un elemento\n```js\nvar users = [{ id: 1, name: 'Peter' }, { id: 2, name: 'Anna' }];\nusers.findItem('id', 2);                  // { id: 2, name: 'Anna' }\nusers.findItem(u => u.name === 'Peter');  // { id: 1, name: 'Peter' }\nusers.findItem('id', 9);                  // null\n```\n\n### arr.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|Any` | yes |  | Una función de prueba, un nombre de propiedad o un valor. |\n| `value` | `Any` | no |  | El valor de la propiedad. |\n\nReturns: `Array` Los elementos que coinciden.\n\nPasa una función `(item, index)`, un nombre de propiedad y un valor (`('id', 5)` compara `item.id === 5`), o un único valor que se compara con `===`. El resultado es un array nuevo; el array original no se modifica.\n\nExample: Filtrar\n```js\nvar items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }];\nitems.findAll('type', 'a').length;  // 2\n```\n\n### arr.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|Any` | yes |  | Una función de prueba, un nombre de propiedad o un valor. |\n| `value` | `Any` | no |  | El valor de la propiedad. |\n\nReturns: `Number` El índice o `-1`.\n\nPasa una función `(item, index)`, un nombre de propiedad y un valor (`('id', 5)` compara `item.id === 5`), o un único valor que se compara con `===`. Total.js reemplaza el `findIndex()` nativo por esta versión (con una función se comporta como el nativo); `arr.TfindIndex()` es el mismo método.\n\nExample: Índice de un elemento\n```js\nvar users = [{ id: 1 }, { id: 2 }];\nvar index = users.findIndex('id', 2);  // 1\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### arr.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 de prueba o un nombre de propiedad. |\n| `value` | `Any` | yes |  | El valor de la propiedad (pasa `undefined` con una función). |\n| `path` | `String` | yes |  | La propiedad a devolver. |\n| `def` | `Any` | no |  | El valor por defecto. |\n\nReturns: `Any`\n\nEl elemento se busca como en `Array.findItem()`. El resultado es `item[path]`, o `def` cuando ningún elemento coincide o la propiedad es `null` / `undefined`.\n\nExample: Leer una propiedad\n```js\nvar users = [{ id: 1, name: 'Peter' }];\nusers.findValue('id', 1, 'name');          // Peter\nusers.findValue('id', 9, 'name', 'guest');  // guest\n```\n\n### arr.remove(cb, [value])\n\nType: `method`\n\nDevuelve un array nuevo sin los elementos que coinciden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Una función de prueba, un nombre de propiedad o un valor. |\n| `value` | `Any` | no |  | El valor de la propiedad. |\n\nReturns: `Array` Un array nuevo sin los elementos que coinciden.\n\nPasa una función `(item, index)`, un nombre de propiedad y un valor (`('id', 5)` compara `item.id === 5`), o un único valor que se compara con `===`. El array original no se modifica, así que asigna el resultado.\n\nExample: Eliminar elementos\n```js\nvar users = [{ id: 1 }, { id: 2 }, { id: 3 }];\nusers = users.remove('id', 1);       // [{ id: 2 }, { id: 3 }]\nvar nums = [1, 2, 3, 2].remove(2);   // [1, 3]\n```\n\n### arr.quicksort([sort], [desc])\n\nType: `method`\n\nOrdena el array in situ por una o más propiedades.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Propiedades por las que ordenar, o `true` para valores simples en orden descendente. |\n| `desc` | `Boolean` | no | `false` | Orden descendente para `sort`. |\n\nReturns: `Array` El mismo array, ordenado.\n\n`sort` es una lista de nombres de propiedades separados por comas, cada uno opcionalmente con `_asc` o `_desc` (`'name'`, `'price_desc'`, `'group,date_desc'`). Se admiten propiedades anidadas con puntos (`'user.name'`). El tipo de cada columna (string, number, boolean o Date) se detecta a partir del primer valor que no es null la primera vez que se usa una expresión de ordenación, y se conserva para las ordenaciones posteriores con la misma expresión; los strings se comparan teniendo en cuenta los diacríticos. Pasar `true` (o `2`) como segundo argumento ordena una sola propiedad en orden descendente.\n\nSin `sort` el array de valores simples se ordena de forma ascendente; `quicksort(true)` lo ordena de forma descendente. El método devuelve el mismo array.\n\nExample: Ordenar objetos\n```js\nvar products = [{ name: 'B', price: 10 }, { name: 'A', price: 20 }];\nproducts.quicksort('name');        // A, B\nproducts.quicksort('price_desc');  // 20, 10\nproducts.quicksort('name', true);  // B, A\n[3, 1, 2].quicksort();             // [1, 2, 3]\n```\n\n### arr.take(count)\n\nType: `method`\n\nDevuelve los primeros count elementos como un array nuevo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | El número de elementos. |\n\nReturns: `Array`\n\nExample: Take\n```js\n[1, 2, 3, 4].take(2);  // [1, 2]\n```\n\n### arr.skip(count)\n\nType: `method`\n\nDevuelve los elementos posteriores a los primeros count elementos como un array nuevo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | El número de elementos a omitir. |\n\nReturns: `Array`\n\nCombínalo con `take()` para paginar.\n\nExample: Paginación\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### arr.first([def])\n\nType: `method`\n\nDevuelve el primer elemento, o un valor por defecto para un array vacío. Array.last() devuelve el último.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Any` | no |  | El valor para un array vacío. |\n\nReturns: `Any`\n\n`arr.last([def])` devuelve el último elemento o `def`.\n\nExample: Primero y último\n```js\n[1, 2].first();     // 1\n[].first('none');   // none\n[1, 2].last();      // 2\n```\n\n### arr.group(name)\n\nType: `method`\n\nAgrupa los elementos por una propiedad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La propiedad por la que agrupar. |\n\nReturns: `Array` Grupos `{ name, items }`.\n\nDevuelve un array de `{ name, items }` ordenado por `name`. El valor de la propiedad se convierte en cadena; los elementos sin la propiedad están en un grupo con nombre vacío.\n\nExample: Agrupar\n```js\nvar items = [{ type: 'x', id: 1 }, { type: 'y', id: 2 }, { type: 'x', id: 3 }];\nitems.group('type');\n// [{ name: 'x', items: [...2 items] }, { name: 'y', items: [...1 item] }]\n```\n\n### arr.trim()\n\nType: `method`\n\nRecorta las cadenas y devuelve un array nuevo sin valores vacíos.\n\nReturns: `Array`\n\nLas cadenas del array original se recortan in situ. El resultado contiene solo elementos truthy, así que quedan fuera las cadenas vacías, `null`, `undefined`, `0` y `false`.\n\nExample: Limpiar una lista\n```js\n' a , ,b'.split(',').trim();  // ['a', 'b']\n```\n\n### arr.random([item])\n\nType: `method`\n\nMezcla el array in situ, 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|Any`\n\nSin argumentos, el array se mezcla (Fisher-Yates) y se devuelve. Con `item` a `true` se devuelve un elemento aleatorio y el array no se modifica.\n\nExample: Aleatorio\n```js\nvar colors = ['red', 'green', 'blue'];\ncolors.random(true);  // one color\ncolors.random();      // the shuffled array\n```\n\n### arr.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 |  | `function(item, next)`. |\n| `callback` | `Function` | no |  | Se llama cuando todos los elementos se han procesado. |\n| `thread` | `Number|Boolean` | no | `1` | Elementos en paralelo, o `true` para eliminar los elementos a medida que se procesan. |\n\nReturns: `Array` El array.\n\nSe llama a `onItem(item, next)` para cada elemento; llama a `next()` para continuar con el siguiente. Se llama a `callback()` cuando todos los elementos han terminado. `thread` define cuántos elementos se ejecutan a la vez (1 por defecto). Con `thread` a `true`, los elementos se eliminan del array con `shift()` a medida que se procesan. Llama a `next('cancel')` para detenerte: entonces se llama a `callback('cancel')`.\n\nExample: Procesar en secuencia\n```js\nvar ids = [1, 2, 3];\nids.wait(function(id, next) {\n\tFUNC.removeuser(id, next);\n}, function() {\n\tconsole.log('All removed');\n});\n```\n\nExample: De dos en dos\n```js\nurls.wait(function(url, next) {\n\tREQUEST({ url: url, callback: () => next() });\n}, () => console.log('done'), 2);\n```\n\n### arr.async([thread], [callback])\n\nType: `method`\n\nEjecuta un array de funciones una tras otra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | Cuántas funciones se ejecutan a la vez. |\n| `callback` | `Function` | no |  | Se llama al final. |\n\nReturns: `Array` El array.\n\nCada elemento es una función `(next)`; llama a `next()` cuando termine. Las funciones se eliminan del array a medida que se ejecutan, así que el array queda vacío al final. `thread` define cuántas funciones empiezan a la vez (1 por defecto). Se llama a `callback()` cuando todas las funciones han terminado, o a `callback('cancel')` cuando una llama a `next('cancel')`.\n\nExample: Ejecutar tareas\n```js\nvar tasks = [];\ntasks.push(function(next) {\n\tconsole.log('first');\n\tnext();\n});\ntasks.push(function(next) {\n\tsetTimeout(next, 100);\n});\ntasks.async(function() {\n\tconsole.log('done');\n});\n```\n\n### arr.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 |  | `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Se llama al final. |\n\nReturns: `Array` El array.\n\n`fn(items, next, beg, end)` recibe el siguiente bloque y los índices de inicio y fin; llama a `next()` para continuar. Se llama a `callback()` tras el último bloque.\n\nExample: Insertar por lotes\n```js\nrows.limit(100, function(items, next) {\n\tFUNC.importrows(items, next);\n}, function() {\n\tconsole.log('Imported');\n});\n```\n","entries":[{"type":"method","name":"String.format()","signature":"str.format(arg0, [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"str.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"str.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"str.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"str.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"str.toName()","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"str.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"str.decode()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"str.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"str.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"str.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.toKeywords()","signature":"str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"str.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"str.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"str.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"str.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"str.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"str.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"str.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"str.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseContext()","signature":"str.parseContext()","since":"0.0.17","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"str.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"str.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseEnv()","signature":"str.parseEnv()","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"str.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"str.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"str.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"str.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"str.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"str.isNumber([isDecimal])","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"str.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"str.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"str.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"str.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"str.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"str.sign([key], [check])","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"str.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"str.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"str.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"num.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"num.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"num.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"num.round(precision)","since":"","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"num.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"num.between(condition, [otherwise])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"num.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"num.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"num.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"num.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"date.extend(text)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"arr.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"arr.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"arr.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"arr.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"arr.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"arr.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"arr.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"arr.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"arr.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.group()","signature":"arr.group(name)","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"arr.trim()","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"arr.random([item])","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"arr.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"arr.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"arr.limit(max, fn, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JacXWy2qt61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/prototypes/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Prototypes","summary":"Toutes les méthodes que Total.js ajoute à String, Number, Date et Array.prototype.","markdown":"---\ntitle: Prototypes\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/prototypes/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Prototypes\n\n> Toutes les méthodes que Total.js ajoute à String, Number, Date et Array.prototype.\n\nLes méthodes que Total.js 5 ajoute aux prototypes intégrés `String`, `Number`, `Date` et `Array`. Elles sont disponibles partout une fois le framework chargé. Le guide [Prototypes](../../guides/prototypes/) montre comment les utiliser ensemble avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### str.format(arg0, [arg1], [...])\n\nType: `method`\n\nRemplace les placeholders numérotés {0}, {1}, ... par les arguments.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0...argN` | `Any` | yes |  | Les valeurs pour `{0}`, `{1}` et ainsi de suite. |\n\nReturns: `String` La nouvelle chaîne.\n\nChaque `{n}` est remplacé par l'argument d'indice `n`. Un placeholder dont l'argument vaut `null` ou `undefined` devient une chaîne vide. Seuls des nombres sont autorisés entre les accolades ; utilise `String.args()` pour des clés nommées.\n\nExample: Placeholders numérotés\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n// Hello Peter, you have 5 messages.\n```\n\n### str.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` | `String|Function` | no |  | `html`, `json`, une fonction `(value, key)` ou toute autre chaîne pour l'encodage URL. |\n| `def` | `String` | no |  | Le texte pour les clés sans valeur. |\n\nReturns: `String` La nouvelle chaîne.\n\n`String.arg()` est la même méthode. Un placeholder est une clé entre accolades simples ou doubles ; les espaces à l'intérieur des accolades sont supprimés. Les clés sont lues directement dans `obj` (pas de chemins imbriqués).\n\n`encode` change la sortie de chaque valeur : `'html'` l'encode avec `String.encode()`, `'json'` écrit `JSON.stringify(value)`, toute autre chaîne truthy utilise `encodeURIComponent()`, et une fonction `(value, key)` renvoie elle-même le texte. Lorsque `encode` est une chaîne, il remplace aussi `def` : avec `'html'` ou une chaîne d'encodage URL, une clé sans valeur devient le texte de `encode` ; avec `'json'`, elle devient `undefined`. Sans `encode`, une clé sans valeur est laissée telle quelle, ou remplacée par `def` si tu en passes un.\n\nExample: Placeholders nommés\n```js\nvar tpl = 'Hello {name}, your order {{ id }} is ready.';\ntpl.args({ name: 'Peter', id: 'A100' });\n// Hello Peter, your order A100 is ready.\n\n'<b>{name}</b>'.args({ name: '<script>' }, 'html');\n// <b>&lt;script&gt;</b>\n```\n\n### str.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 du slug. |\n\nReturns: `String` Le slug.\n\nLe texte est trimé, mis en minuscules et les diacritiques sont supprimés (`toASCII()`). Les lettres, les chiffres et `_` sont conservés ; les espaces et les caractères `!\"#$%&'()*+,-./` deviennent un seul `-` ; les autres caractères sont supprimés. Un `-` final est retiré et le résultat comporte au plus `max` caractères.\n\nLorsque le texte contient un caractère sans forme ASCII dont le code est supérieur à 540 (par exemple des lettres cyrilliques, `€` ou un emoji), le texte entier n'est pas transformé lettre par lettre : la méthode renvoie alors un court identifiant basé sur un hash du texte, de sorte que le résultat reste stable et sûr pour les URL.\n\nExample: Créer le slug d'un titre\n```js\n' Hello World! Čaute 123 '.slug();\n// hello-world-caute-123\n\n'A very long article title'.slug(10);\n// a-very-lon\n```\n\n### str.max(length, [chars])\n\nType: `method`\n\nRaccourcit 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 raccourcie. |\n\nReturns: `String` Le texte, raccourci si nécessaire.\n\nQuand le texte est plus long que `length`, il est coupé pour que le résultat, `chars` compris, fasse exactement `length` caractères. Un texte plus court est renvoyé inchangé.\n\nExample: Raccourcir\n```js\n'Hello world'.max(8);       // Hello...\n'Hello world'.max(8, '…');  // Hello w…\n```\n\n### str.capitalize([first])\n\nType: `method`\n\nMet en majuscule la première lettre de chaque mot, ou seulement celle du texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Ne mettre en majuscule que le premier caractère. |\n\nReturns: `String` La nouvelle chaîne.\n\nLe texte est d'abord mis en minuscules. Sans arguments, chaque lettre qui suit un espace, une tabulation ou un saut de ligne passe en majuscule. Avec `first` à `true`, seul le premier caractère passe en majuscule et le reste reste en minuscules.\n\nExample: Majuscules\n```js\n'hello WORLD'.capitalize();      // Hello World\n'hello WORLD'.capitalize(true);  // Hello world\n```\n\n### str.toName()\n\nType: `method`\n\nNettoie un nom de personne : supprime les chiffres et les symboles, les espaces en trop et met les mots en majuscule.\n\nReturns: `String` Le nom nettoyé.\n\nSeules les lettres ASCII, les caractères au-dessus du code 127 (lettres avec diacritiques) et les espaces sont conservés. Les espaces répétés sont réduits à un seul, les espaces finaux sont supprimés (les espaces initiaux deviennent un seul espace) et la première lettre de chaque mot est mise en majuscule. Le reste de chaque mot est conservé tel quel.\n\nExample: Nettoyer un nom\n```js\n'peter   sirka 12'.toName();\n// Peter Sirka\n```\n\n### str.encode()\n\nType: `method`\n\nEncode les caractères spéciaux HTML.\n\nReturns: `String` Le texte encodé.\n\n`String.safehtml()` est la même méthode. Les caractères `<`, `>`, `\"`, `'` et `&` sont remplacés par `&lt;`, `&gt;`, `&quot;`, `&apos;` et `&amp;`. Utilise-la avant de placer du texte d'utilisateur dans du HTML.\n\nExample: Encoder une saisie utilisateur\n```js\n'<a href=\"x\">Tom & Jerry</a>'.encode();\n// &lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/a&gt;\n```\n\n### str.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 (`&lt;`, `&amp;`, `&quot;`, ...) et les entités numériques (`&#65;`, `&#x41;`) sont remplacées par leurs caractères. Les entités nommées inconnues restent telles quelles.\n\nExample: Décoder\n```js\n'&lt;b&gt;Tom &amp; Jerry&#33;&lt;/b&gt;'.decode();\n// <b>Tom & Jerry!</b>\n```\n\n### str.removeTags()\n\nType: `method`\n\nSupprime les balises HTML du texte.\n\nReturns: `String` Le texte sans balises.\n\nChaque balise `<...>` (ouvrante ou fermante) est supprimée ; le texte entre les balises reste. Le résultat n'est pas encodé en HTML, donc encode-le avec `String.encode()` quand tu le réécris dans du HTML.\n\nExample: Supprimer les balises\n```js\n'<p><b>Hi</b> there</p>'.removeTags();\n// Hi there\n```\n\n### str.padLeft(max, [c])\n\nType: `method`\n\nComplète le texte à gauche jusqu'à une longueur. String.padRight() complète à droite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longueur du résultat. |\n| `c` | `String` | no | `' '` | Le caractère de remplissage. |\n\nReturns: `String` Le texte complété.\n\nDes caractères `c` sont ajoutés jusqu'à ce que le texte compte `max` caractères ; un texte plus long est renvoyé inchangé. `str.padRight(max, [c])` fonctionne de la même façon du côté droit. Les deux ne sont définies que si l'environnement d'exécution ne les a pas déjà.\n\nExample: Compléter\n```js\n'5'.padLeft(3, '0');   // 005\n'a'.padRight(3, '-');  // a--\n```\n\n### str.toASCII()\n\nType: `method`\n\nRemplace les lettres avec diacritiques par leur forme ASCII.\n\nReturns: `String` Le texte sans signes diacritiques.\n\nLes lettres comme `č`, `á` ou `ü` sont remplacées par `c`, `a` et `u`. Les caractères sans forme ASCII restent tels quels.\n\nExample: Supprimer les diacritiques\n```js\n'Čučoriedka'.toASCII();\n// Cucoriedka\n```\n\n### str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrait les mots-clés du texte, les plus fréquents en premier.\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 les mots à 80 % de leur longueur. |\n| `max_count` | `Number` | no | `200` | Le nombre maximal de mots à lire. |\n| `max_length` | `Number` | no | `20` | La longueur maximale d'un mot-clé. |\n| `min_length` | `Number` | no | `2` | La longueur minimale d'un mot-clé. |\n\nReturns: `Array` Les mots-clés uniques triés par fréquence.\n\nLe texte est mis en minuscules et découpé en mots ; les caractères qui ne sont ni des lettres ni des chiffres sont supprimés de chaque mot. Avec `forsearch` (par défaut), les diacritiques sont supprimés et `y` devient `i`, ce qui rend la correspondance tolérante. `alternative` ne garde que les premiers 80 % des mots longs (une racinisation simple). Les mots plus courts que `min_length` ou plus longs que `max_length` sont ignorés et au plus `max_count` mots sont lus. Les mots uniques sont renvoyés triés selon leur fréquence d'apparition.\n\nPour une seule chaîne de recherche normalisée, utilise `str.toSearch()` : elle met le texte en minuscules, supprime les diacritiques et les symboles, remplace `y` par `i` et supprime les lettres répétées (`hello` devient `helo`).\n\nExample: Mots-clés pour un index de recherche\n```js\n'Total.js is a great framework, great!'.toKeywords();\n// ['great', 'totaljs', 'is', 'framework']\n\n'Čaute Hello'.toSearch();\n// caute helo\n```\n\n### str.pluralize(zero, one, few, other)\n\nType: `method`\n\nConvertit le texte en nombre et choisit une forme du pluriel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Le texte pour 0, ou les quatre formes séparées par des virgules. |\n| `one` | `String` | no |  | Le texte pour 1. |\n| `few` | `String` | no |  | Le texte pour 2 à 4. |\n| `other` | `String` | no |  | Le texte pour les autres nombres. |\n\nReturns: `String` La forme choisie.\n\nLe texte est converti avec `parseInt()` et le résultat est passé à `Number.pluralize()`.\n\nExample: Pluraliser une chaîne\n```js\n'3'.pluralize('no items', '# item', '# items', '# items');\n// 3 items\n```\n\n### str.parseInt([def])\n\nType: `method`\n\nConvertit le texte en nombre, avec une valeur par défaut pour un texte invalide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | La valeur pour un texte qui n'est pas un nombre. |\n\nReturns: `Number` Le nombre ou la valeur par défaut.\n\nLe texte est nettoyé des espaces en début et en fin et converti avec le `+` unaire, donc `'10'` donne `10`, `'1.5'` donne `1.5` et `'0x10'` donne `16`. Quand le texte n'est pas un nombre, `def` est renvoyé (`0` si tu l'omets).\n\n`str.parseInt2([def])` trouve plutôt le premier entier n'importe où dans le texte (`'abc 123'` donne `123`) ; `str.parseFloat2([def])` fait de même pour un nombre décimal et accepte `,` comme séparateur décimal.\n\nExample: Lire des nombres\n```js\n'10'.parseInt();        // 10\n'abc'.parseInt(5);      // 5\n'Total: 123 EUR'.parseInt2(); // 123\n'x 1,5 y'.parseFloat2();      // 1.5\n```\n\n### str.parseFloat([def])\n\nType: `method`\n\nConvertit le texte en nombre décimal ; une virgule est acceptée comme séparateur décimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | La valeur pour un texte qui n'est pas un nombre. |\n\nReturns: `Number` Le nombre ou la valeur par défaut.\n\nLe texte est nettoyé des espaces en début et en fin, la première `,` est remplacée par `.` et le texte est converti en nombre. Quand le texte n'est pas un nombre, `def` est renvoyé (`0` si tu l'omets).\n\nExample: Lire des décimaux\n```js\n'1,5'.parseFloat();    // 1.5\n' 2.25 '.parseFloat(); // 2.25\n'n/a'.parseFloat(-1);  // -1\n```\n\n### str.parseBoolean()\n\nType: `method`\n\nConvertit le texte en booléen.\n\nReturns: `Boolean`\n\nRenvoie `true` pour `true`, `1` et `on` (sans tenir compte de la casse) et `false` pour tout le reste.\n\nExample: Lire un indicateur\n```js\n'on'.parseBoolean();    // true\n'TRUE'.parseBoolean();  // true\n'no'.parseBoolean();    // false\n```\n\n### str.parseDate([format])\n\nType: `method`\n\nConvertit le texte en Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Un format comme `dd/MM/yyyy HH:mm`. |\n\nReturns: `Date` La date analysée.\n\nSans `format`, la méthode comprend :\n\n- les dates JSON (`2024-05-01T12:30:00.000Z`),\n- `yyyy-MM-dd`, `yyyy-MM-dd HH:mm`, `yyyy-MM-dd HH:mm:ss` et `yyyy-MM-ddTHH:mm:ss.SSS`,\n- `d.M.yyyy` avec une heure facultative (`1.5.2024 08:00`),\n- tout ce que `new Date(text)` accepte.\n\nLa date et l'heure de ces formes sont lues en UTC. Les parties manquantes de la date sont prises dans la date du jour.\n\nAvec `format`, les chiffres du texte sont lus selon les positions de `yyyy`, `MM`, `dd`, `HH`, `mm` et `ss` dans le format ; les autres caractères du format ne font que séparer les parties. Les parties doivent être écrites avec tous leurs chiffres (`05`, pas `5`). Une année à deux chiffres est dans les années 2000, et `pm` dans le texte ajoute 12 heures.\n\nExample: Analyser des dates\n```js\n'2024-05-01 12:30'.parseDate();\n// 2024-05-01T12:30:00.000Z\n\n'1.5.2024'.parseDate();\n// 2024-05-01T00:00:00.000Z\n\n'01/05/2024'.parseDate('dd/MM/yyyy');\n// 1 May 2024\n```\n\n### str.parseDateExpiration()\n\nType: `method`\n\nConvertit un temps relatif comme « 5 minutes » en une Date future.\n\nReturns: `Date` L'heure actuelle plus la durée indiquée.\n\nLe texte est une liste de paires `number unit` séparées par des espaces. Chaque paire est ajoutée à l'heure actuelle avec `Date.add()`, donc toutes les unités de `Date.add()` fonctionnent (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years` et leurs formes courtes). Utilise un nombre négatif pour une date passée.\n\nExample: Expiration\n```js\nvar expire = '5 minutes'.parseDateExpiration();\nvar later = '1 day 2 hours'.parseDateExpiration();\n```\n\n### str.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 JSON en objets Date. |\n\nReturns: `Object` La valeur analysée ou `undefined`.\n\nRenvoie la valeur analysée, ou `undefined` quand le texte n'est pas du JSON valide. Avec `date` à `true`, les chaînes au format de date JSON (`2024-01-01T10:00:00.000Z`) deviennent des objets `Date`.\n\nExample: Analyse sûre\n```js\nvar obj = '{\"a\":1}'.parseJSON();          // { a: 1 }\nvar bad = '{a:1'.parseJSON();             // undefined\nvar doc = '{\"created\":\"2024-01-01T10:00:00.000Z\"}'.parseJSON(true);\ndoc.created instanceof Date;             // true\n```\n\n### str.parseCSV([delimiter])\n\nType: `method`\n\nAnalyse un texte CSV en un tableau d'objets avec les clés de colonne a, b, c, ...\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | Le délimiteur de colonnes, un seul caractère. |\n\nReturns: `Array` Un tableau d'objets.\n\nChaque ligne devient un objet. Les clés sont des lettres de colonne : `a` pour la première colonne, `b` pour la deuxième, ..., `z`, puis `aa`, `ab` et ainsi de suite. Les valeurs entre guillemets doubles peuvent contenir le délimiteur et des sauts de ligne ; `\"\"` entre guillemets est un guillemet échappé. Les colonnes vides n'ont pas de clé dans l'objet. Les valeurs sont des chaînes et ne sont pas nettoyées des espaces. Une ligne d'en-tête est renvoyée comme n'importe quelle autre ligne.\n\nExample: Analyser du CSV\n```js\nvar rows = 'name,age\\n\"Sirka, Peter\",40\\nAnna,'.parseCSV();\n// [{ a: 'name', b: 'age' }, { a: 'Sirka, Peter', b: '40' }, { a: 'Anna' }]\n\nvar header = rows.shift();\nfor (var row of rows)\n\tconsole.log(row.a, row.b || '-');\n```\n\n### str.parseContext()\n\nType: `method` · Since: `0.0.17`\n\nAnalyse un texte composé de blocs avec un en-tête et un corps.\n\nReturns: `Array` Un tableau d'objets, un par bloc.\n\nChaque bloc commence par une ligne d'au moins 20 tirets, suivie de lignes d'en-tête `key: value`, d'une autre ligne d'au moins 20 tirets et du corps. Le corps se termine là où commence le bloc suivant. Chaque bloc devient un objet avec les clés de l'en-tête (en minuscules, valeurs sans espaces superflus) et une propriété `body` contenant le corps sans espaces superflus. Les lignes d'en-tête sans `:` sont ignorées.\n\nExample: Analyser des blocs\n```js\nvar text = [\n\t'--------------------',\n\t'Name: Hello',\n\t'Type: note',\n\t'--------------------',\n\t'Body one',\n\t'--------------------',\n\t'Name: Second',\n\t'--------------------',\n\t'Body two'\n].join('\\n');\n\ntext.parseContext();\n// [{ name: 'Hello', type: 'note', body: 'Body one' }, { name: 'Second', body: 'Body two' }]\n```\n\n### str.parseEncoded()\n\nType: `method`\n\nAnalyse un texte encodé pour les URL (une query string ou un corps de formulaire) en un objet.\n\nReturns: `Object` Les clés et les valeurs analysées (des chaînes).\n\nLes paires `key=value` sont séparées par `&` ; les clés et les valeurs sont décodées. C'est l'analyseur que Total.js utilise pour les query strings et les corps `application/x-www-form-urlencoded`.\n\nExample: Analyser une query string\n```js\n'q=total.js&page=2&name=%20Peter'.parseEncoded();\n// { q: 'total.js', page: '2', name: ' Peter' }\n```\n\n### str.parseConfig([def], [onerr])\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 |  | Valeurs par défaut copiées d'abord dans le résultat. |\n| `onerr` | `Function` | no |  | `function(err, line)` pour les valeurs qui ne peuvent pas être évaluées. |\n\nReturns: `Object` Les valeurs analysées.\n\nChaque ligne est `key : value`. Le séparateur est le premier `:`, ou le premier `=` lorsque la ligne n'a pas de `:` ; la valeur commence au deuxième caractère après le séparateur, garde donc un espace à cet endroit. Les lignes vides et les lignes qui commencent par `#` ou `//` sont ignorées. Une valeur qui commence par `base64 ` ou `hex ` est décodée.\n\nUn type entre parenthèses après la clé convertit la valeur : `(string)`, `(number)` (aussi `float`, `double`, `currency`), `(boolean)` / `(bool)` (vrai lorsque la valeur contient `true`, `on`, `1` ou `enabled`, quelle que soit la casse), `(json)`, `(object)` / `(array)` / `(eval)` (évalué en JavaScript), `(date)`, `(env)` (lit `process.env[value]`), `(config)` (lit une autre clé de configuration) et `(random)` (une chaîne aléatoire de la longueur donnée). Lorsqu'une valeur évaluée échoue, `onerr(err, line)` est appelée, ou une erreur est levée sans elle.\n\nExample: Analyser des paramètres\n```js\nvar text = 'name : Shop\\ncount (number) : 10\\nenabled (boolean) : true\\n# comment\\ntags (array) : [\\'a\\', \\'b\\']';\ntext.parseConfig();\n// { name: 'Shop', count: 10, enabled: true, tags: ['a', 'b'] }\n```\n\n### str.parseEnv()\n\nType: `method`\n\nAnalyse un texte au format .env en un objet.\n\nReturns: `Object` Les clés et les valeurs.\n\nChaque ligne est `KEY=value`. Les lignes vides ou qui commencent par `#` ou `//` sont ignorées. Une valeur entre apostrophes ou guillemets doubles est extraite des guillemets (ses espaces intérieurs sont conservés) ; les autres valeurs sont nettoyées des espaces en début et en fin. `\\n` dans une valeur devient un saut de ligne. Toutes les valeurs sont des chaînes.\n\nExample: Analyser un .env\n```js\n'PORT=8000\\nNAME=\"My app\"\\n# comment'.parseEnv();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### str.parseUA([structured])\n\nType: `method`\n\nLit le système d'exploitation, le navigateur et le type d'appareil depuis un en-tête 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`\n\nSans arguments, le résultat est un texte court comme `Windows Chrome`. Avec `structured` à `true`, le résultat est un objet `{ os, browser, device }`, où `device` vaut `mobile` ou `desktop`. Un texte vide renvoie une chaîne vide.\n\nExample: Lire le user agent\n```js\nvar ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Version/17.0 Mobile Safari/604.1';\nua.parseUA();      // iPhone Safari\nua.parseUA(true);  // { os: 'iPhone', browser: 'Safari', device: 'mobile' }\n```\n\n### str.isEmail()\n\nType: `method`\n\nVérifie que le texte est une adresse e-mail.\n\nReturns: `Boolean`\n\nLe test utilise l'expression régulière `email` de `DEF.validators` : des lettres, des chiffres et `-_.+` avant `@`, un domaine et un domaine de premier niveau d'au moins deux lettres. Un texte de quatre caractères ou moins n'est jamais valide.\n\nExample: Valider\n```js\n'info@example.com'.isEmail();  // true\n'info@example'.isEmail();      // false\n```\n\n### str.isPhone()\n\nType: `method`\n\nVérifie que le texte est un numéro de téléphone.\n\nReturns: `Boolean`\n\nLe test utilise l'expression régulière `phone` de `DEF.validators` : un `+` facultatif, trois chiffres (éventuellement entre parenthèses), trois chiffres et 4 à 8 chiffres, chaque groupe étant éventuellement séparé par `-`, `.` ou un espace. Un texte de moins de six caractères n'est jamais valide.\n\nExample: Valider\n```js\n'+421903123456'.isPhone();  // true\n'(123) 456-7890'.isPhone(); // true\n'12345'.isPhone();          // false\n```\n\n### str.isURL()\n\nType: `method`\n\nVérifie que le texte est une URL http ou https.\n\nReturns: `Boolean`\n\nLe texte doit commencer par `http://` ou `https://` et ne doit pas contenir `,`, `{`, `}` ou `\\`. Un texte de sept caractères ou moins n'est jamais valide.\n\nExample: Valider\n```js\n'https://www.totaljs.com'.isURL();  // true\n'www.totaljs.com'.isURL();          // false\n```\n\n### str.isUID()\n\nType: `method`\n\nVérifie que le texte est un identifiant valide créé par UID().\n\nReturns: `Boolean`\n\nLa méthode vérifie le format et la somme de contrôle des identifiants créés par `UID()`, donc une chaîne aléatoire de même forme est rejetée. Pour lire la date et l'index stockés dans un UID, utilise `str.parseUID()`, qui renvoie `{ version, date, century, hash, index, valid }`. Pour les GUID standard (`8-4-4-4-12` chiffres hexadécimaux), utilise `str.isGUID()`.\n\nExample: Valider un identifiant\n```js\nvar id = UID();\nid.isUID();       // true\n'abc'.isUID();    // false\nid.parseUID().date;  // the time the id was created\n'123e4567-e89b-12d3-a456-426614174000'.isGUID(); // true\n```\n\n### str.isNumber([isDecimal])\n\nType: `method`\n\nVérifie que le texte ne contient que des chiffres.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `isDecimal` | `Boolean` | no | `false` | Autoriser un séparateur décimal. |\n\nReturns: `Boolean`\n\nChaque caractère doit être un chiffre. Avec `isDecimal` à `true`, un `.` ou une `,` est aussi autorisé. Un signe (`-`, `+`) n'est pas autorisé et un texte vide n'est pas un nombre.\n\nExample: Valider\n```js\n'0123'.isNumber();      // true\n'1.5'.isNumber();       // false\n'1,5'.isNumber(true);   // true\n```\n\n### str.isJSON()\n\nType: `method`\n\nVérifie rapidement que le texte ressemble à un objet, un tableau ou une chaîne JSON.\n\nReturns: `Boolean`\n\nLes espaces blancs initiaux et finaux sont ignorés et le premier et le dernier caractère sont comparés : `{` avec `}`, `[` avec `]` ou `\"` avec `\"`. Elle vaut aussi `true` lorsque le texte commence par un chiffre ou une lettre et se termine par un caractère inférieur à `9`, par exemple `'123'` ou `'abc1'`. Le contenu n'est pas analysé : utilise `String.parseJSON()` lorsque tu as besoin d'en être sûr.\n\nExample: Vérifier avant d'analyser\n```js\nvar body = ' {\"a\":1} ';\nif (body.isJSON())\n\tvar obj = body.parseJSON();\n```\n\n### str.isXSS()\n\nType: `method`\n\nVérifie que le texte contient une balise HTML.\n\nReturns: `Boolean`\n\nRenvoie `true` quand le texte contient `<` suivi plus loin de `>`, c'est ainsi que l'expression régulière `xss` de `DEF.validators` détecte du balisage dans une saisie utilisateur. `str.isSQLInjection()` fonctionne de la même façon avec l'expression `sqlinjection` : elle vaut `true` pour les chaînes entre guillemets et pour les mots-clés SQL `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` et `UNION` écrits en majuscules. Les deux sont de simples filtres, qui ne remplacent ni l'encodage de la sortie ni les paramètres de requête.\n\nExample: Rejeter le balisage\n```js\n'<script>alert(1)</script>'.isXSS();  // true\n'Hello'.isXSS();                      // false\n'DROP TABLE users'.isSQLInjection();   // true\n```\n\n### str.hash([type], [salt])\n\nType: `method`\n\nRenvoie un hash du texte : un hash numérique rapide ou une empreinte md5, sha1, sha256, sha512 ou crc32.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32`, `crc32unsigned`, ou `true` pour un hash numérique non signé. |\n| `salt` | `String` | no |  | Le texte ajouté avant le hachage. |\n\nReturns: `Number|String` Un nombre pour le hash numérique et crc32, une chaîne hexadécimale sinon.\n\n`type` sélectionne l'algorithme : `md5`, `sha1`, `sha256`, `sha512` (chaînes hexadécimales), `crc32` (nombre signé) ou `crc32unsigned` (nombre non signé). Sans `type`, la méthode renvoie un hash numérique rapide de 32 bits du texte (signé) ; `hash(true)` le renvoie non signé. `salt` est ajouté au texte avant le hachage. Le hash numérique n'est pas un hash cryptographique : utilise-le pour des clés de cache et des usages similaires. `str.crc32([unsigned])` est aussi disponible directement.\n\nExample: Hashes\n```js\n'hello'.hash();          // a signed 32-bit number\n'hello'.hash(true);      // the same, unsigned\n'hello'.hash('sha256');  // hex digest\n'hello'.hash('crc32unsigned');\n```\n\n### str.md5([salt])\n\nType: `method`\n\nRenvoie l'empreinte MD5 du texte 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` 32 caractères hexadécimaux.\n\nLe texte (avec `salt` ajouté) est haché en UTF-8 avec `crypto` de Node.js. MD5 convient aux sommes de contrôle et aux clés de cache, pas aux mots de passe.\n\nExample: MD5\n```js\n'a'.md5();\n// 0cc175b9c0f1b6a831c399e269772661\n```\n\n### str.sha256([salt])\n\nType: `method`\n\nRenvoie l'empreinte SHA-256 du texte sous forme de chaîne hexadécimale. sha1() et sha512() fonctionnent de la même façon.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Texte ajouté avant le hachage. |\n\nReturns: `String` 64 caractères hexadécimaux.\n\nLe texte (avec `salt` ajouté) est haché en UTF-8 avec `crypto` de Node.js. `str.sha1([salt])` renvoie 40 caractères hexadécimaux et `str.sha512([salt])` 128 caractères hexadécimaux.\n\nExample: Empreintes SHA\n```js\nvar digest = 'password'.sha256(CONF.secret);\nvar short = 'text'.sha1();\nvar long = 'text'.sha512();\n```\n\n### str.sign([key], [check])\n\nType: `method`\n\nSigne le texte avec une courte somme de contrôle, ou vérifie et supprime la signature.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | La clé de signature. |\n| `check` | `Boolean` | no | `false` | Vérifie la signature et renvoie le texte original. |\n\nReturns: `String` Le texte signé, le texte d'origine, ou `null`.\n\n`str.sign(key)` renvoie `text-checksum`, où la somme de contrôle est calculée à partir du texte et de `key`. `signed.sign(key, true)` vérifie la somme de contrôle et renvoie le texte d'origine, ou `null` quand la signature ne correspond pas. Utilise-la pour des valeurs qui passent par des URL et ne doivent pas être modifiées, comme des identifiants dans des liens. Ce n'est pas du chiffrement : le texte reste lisible.\n\n`str.makeid()` renvoie seulement une courte somme de contrôle du texte en base 36, pratique comme clé compacte.\n\nExample: Signer un id\n```js\nvar token = '123'.sign('mykey');     // 123-155hlxd\ntoken.sign('mykey', true);           // 123\n(token + 'x').sign('mykey', true);   // null\n```\n\n### str.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nChiffre le texte avec une clé. String.decrypt() fait l'inverse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de chiffrement. |\n| `isUnique` | `Boolean` | no | `false` | Produire un résultat différent à chaque appel. |\n| `secret` | `String` | no | `CONF.secret` | Le secret utilisé dans la somme de contrôle. |\n\nReturns: `String` Le texte chiffré.\n\nLe résultat est une chaîne composée d'une somme de contrôle, de `-` et de données hexadécimales. Avec `isUnique` à `true`, le même texte donne un résultat différent à chaque fois. La somme de contrôle utilise `secret`, ou la clé de configuration `secret` si tu l'omets.\n\n`str.decrypt(key, [secret])` renvoie le texte d'origine, ou `null` quand la clé, le secret ou les données ne correspondent pas. Utilise les mêmes `key` et `secret` pour les deux.\n\nExample: Chiffrer et déchiffrer\n```js\nvar value = 'user@example.com'.encrypt('mykey', true);\nvalue.decrypt('mykey');   // user@example.com\nvalue.decrypt('other');   // null\n```\n\n### str.encrypt_uid([key])\n\nType: `method`\n\nChiffre un identifiant en un jeton court sûr pour les URL. String.decrypt_uid() fait l'inverse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | La clé. |\n\nReturns: `String` Le jeton.\n\nUtilise-la pour masquer des identifiants numériques ou textuels dans des URL publiques. `key` vaut par défaut la clé de configuration `secret`. `token.decrypt_uid([key])` renvoie l'identifiant d'origine, ou `null` quand le jeton a été modifié ou que la clé est différente.\n\nExample: Masquer un identifiant\n```js\nvar token = '123'.encrypt_uid('mykey');\ntoken.decrypt_uid('mykey');  // 123\n```\n\n### str.base64ToBuffer()\n\nType: `method`\n\nConvertit un texte base64 ou une data URI en Buffer.\n\nReturns: `Buffer` Les données décodées.\n\nTout ce qui précède la première `,`, celle-ci comprise, est ignoré, donc le base64 simple comme `data:...;base64,...` fonctionnent. Méthodes associées : `str.base64ToFile(filename, [callback])` écrit les données décodées dans un fichier, `str.base64ContentType()` renvoie le type de contenu d'une data URI (`image/png`), et `str.parseDataURI()` renvoie `{ type, buffer }` (ou `null` pour un texte qui n'est pas une data URI).\n\nExample: Décoder un téléversement\n```js\nvar uri = 'data:text/plain;base64,aGVsbG8=';\nuri.base64ToBuffer().toString();   // hello\nuri.base64ContentType();           // text/plain\nuri.parseDataURI().type;           // text/plain\nuri.base64ToFile(PATH.temp('hello.txt'));\n```\n\n### num.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormate un nombre avec un séparateur de milliers et un nombre fixe de 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 est un espace par défaut. Le séparateur décimal est `.`, ou `,` quand le séparateur de milliers est `.`. Les décimales en trop sont coupées, pas arrondies ; appelle donc d'abord `Number.round()` quand tu as besoin d'arrondir. Les décimales manquantes sont complétées par des zéros. Quand le premier argument est une chaîne, les deux premiers arguments sont permutés : `format('.', 2)` équivaut à `format(2, '.')`.\n\nExample: Formater\n```js\n(1234567.891).format(2);           // 1 234 567.89\n(1234.5).format(2, ',', '.');      // 1,234.50\n(1234.5).format('.', 2);           // 1.234,50\n(1.999).round(2).format(2);        // 2.00\n```\n\n### num.pluralize(zero, one, few, other)\n\nType: `method`\n\nChoisit une forme du pluriel selon le nombre ; # est remplacé par le nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Le texte pour 0, ou les quatre formes séparées par des virgules. |\n| `one` | `String` | no |  | Le texte pour 1. |\n| `few` | `String` | no |  | Le texte pour 2 à 4. |\n| `other` | `String` | no |  | Le texte pour les autres nombres. |\n\nReturns: `String` La forme choisie.\n\nLa forme `zero` est utilisée pour 0, `one` pour 1, `few` pour 2 à 4 et `other` pour le reste (la règle des langues slaves ; pour l'anglais, passe le même texte pour `few` et `other`). Quand tu ne passes qu'une seule chaîne, elle est découpée par les virgules en quatre formes. Le premier `#` de la forme choisie est remplacé par le nombre.\n\nExample: Formes du pluriel\n```js\n(1).pluralize('no items', '# item', '# items', '# items');  // 1 item\n(7).pluralize('no items,# item,# items,# items');          // 7 items\n```\n\n### num.padLeft(max, [c])\n\nType: `method`\n\nComplète le nombre à gauche avec des zéros. Number.padRight() complète à droite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longueur du résultat. |\n| `c` | `String` | no | `'0'` | Le caractère de remplissage. |\n\nReturns: `String` Le nombre complété.\n\nLe nombre est converti en chaîne et complété jusqu'à `max` caractères avec `c` (`0` par défaut). `num.padRight(max, [c])` complète à droite.\n\nExample: Complétion par des zéros\n```js\n(5).padLeft(3);       // 005\n(7).padLeft(4, ' ');  // '   7'\n(5).padRight(3);      // 500\n```\n\n### num.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` | yes |  | Le nombre de décimales. |\n\nReturns: `Number` Le nombre arrondi.\n\nL'arrondi utilise la notation exponentielle, donc des valeurs comme `1.005` sont correctement arrondies à `1.01`. `num.floor(decimals)` arrondit plutôt vers le bas à un nombre de décimales (`(1.239).floor(2)` donne `1.23`).\n\nExample: Arrondir\n```js\n(1.005).round(2);  // 1.01\n(2.5).round(0);    // 3\n(1.239).floor(2);  // 1.23\n```\n\n### num.fixed(decimals)\n\nType: `method`\n\nArrondit le nombre avec toFixed() et renvoie un nombre, pas une chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Le nombre de décimales. |\n\nReturns: `Number`\n\nExample: Fixed\n```js\n(1.236).fixed(2);  // 1.24 (a number)\n```\n\n### num.between(condition, [otherwise])\n\nType: `method`\n\nRenvoie la valeur de la première plage qui contient le nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Les plages comme clés, les résultats comme valeurs. |\n| `otherwise` | `Any` | no |  | Le résultat quand aucune plage ne correspond. |\n\nReturns: `Any` La valeur de la plage correspondante ou `otherwise`.\n\n`condition` est un objet dont les clés sont des plages : `'1-3'` (de 1 à 3, bornes incluses), `'7-'` (7 et plus) ou `'-5'` (5 et moins). Les clés sont testées dans l'ordre et la valeur de la première clé correspondante est renvoyée. Quand aucune plage ne correspond, `otherwise` est renvoyé.\n\nExample: Noter un score\n```js\nvar score = 5;\nscore.between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }, 'unknown');\n// medium\n```\n\n### num.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAjoute une taxe au nombre, ou la retire d'un prix qui l'inclut.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | Le taux de taxe en pourcentage. |\n| `decimals` | `Number` | no | `2` | Le nombre de décimales. |\n| `includedVAT` | `Boolean` | no | `false` | Le nombre inclut déjà la taxe. |\n\nReturns: `Number`\n\n`Number.TAX()` est la même méthode. Sans `includedVAT`, le résultat est le nombre augmenté de `percentage`. Avec `includedVAT` à `true`, le nombre est un prix qui inclut déjà la taxe, et le résultat est le prix hors taxe. Le résultat est arrondi à `decimals` (2 par défaut). Tu peux passer le booléen comme deuxième argument : `VAT(20, true)`.\n\nExample: Prix avec TVA\n```js\n(100).VAT(20);        // 120\n(120).VAT(20, true);  // 100\n(99.99).TAX(10, 0);   // 110\n```\n\n### num.discount(percentage, [decimals])\n\nType: `method`\n\nRéduit le nombre d'un 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`\n\nLe résultat est arrondi vers le bas à `decimals` (2 par défaut).\n\nExample: Remise\n```js\n(100).discount(15);    // 85\n(19.99).discount(10);  // 17.99\n```\n\n### num.filesize([decimals], [type])\n\nType: `method`\n\nFormate un nombre d'octets en une taille lisible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Le nombre de décimales. |\n| `type` | `String` | no |  | `bytes`, `KB`, `MB`, `GB` ou `TB`. |\n\nReturns: `String` La taille avec son unité.\n\nSans `type`, la plus grande unité adaptée est choisie : `bytes`, `KB`, `MB`, `GB` ou `TB` (1 KB vaut 1024 octets). Avec `type`, la valeur est convertie dans cette unité. Sans `decimals`, la valeur a jusqu'à deux décimales et `.00` est supprimé ; avec `decimals`, elle est formatée avec `Number.format(decimals)`. Les arguments peuvent être passés dans n'importe quel ordre.\n\nExample: Tailles de fichiers\n```js\n(500).filesize();          // 500 bytes\n(1536000).filesize();      // 1.46 MB\n(5000000).filesize(1, 'MB'); // 4.7 MB\n```\n\n### num.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormate le nombre comme un montant avec un formateur de devise enregistré dans DEF.currencies.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | La clé dans `DEF.currencies`. |\n| `a, b, c` | `Any` | no |  | Des arguments supplémentaires pour le formateur. |\n\nReturns: `String` Le montant formaté.\n\nLe formateur est la fonction `DEF.currencies[currency]` (ou `DEF.currencies.default` sans `currency`). Il reçoit le nombre et les arguments `a`, `b` et `c` et renvoie le texte. Quand aucun formateur n'existe pour la devise, le résultat est `num.format(2)`. Enregistre les formateurs au démarrage, par exemple dans un fichier de définition.\n\nExample: Enregistrer et utiliser une devise\n```js\n// /definitions/currencies.js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2, ' ', ',') + ' €';\n};\n\n(1234.5).currency('eur');  // 1 234,50 €\n(10).currency('usd');      // 10.00 (no formatter)\n```\n\n### date.add(type, [value])\n\nType: `method`\n\nRenvoie une nouvelle date décalée d'une durée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | L'unité, une chaîne avec la valeur et l'unité, ou des millisecondes. |\n| `value` | `Number` | no |  | La quantité, négative pour le passé. |\n\nReturns: `Date` Une nouvelle date.\n\nLa date d'origine n'est pas modifiée. Passe l'unité et la valeur (`add('minutes', 30)`), une seule chaîne avec les deux (`add('30 minutes')`, `add('-2 hours')`) ou un nombre de millisecondes (`add(5000)`).\n\nUnités : `s`, `ss`, `sec`, `second`, `seconds` ; `m`, `mm`, `min`, `minute`, `minutes` ; `h`, `hh`, `hour`, `hours` ; `d`, `dd`, `day`, `days` ; `w`, `ww`, `week`, `weeks` ; `M`, `MM`, `month`, `months` ; `y`, `yyyy`, `year`, `years`. Les unités agissent sur les parties UTC de la date. Ajouter des mois à une fin de mois suit le comportement de JavaScript : le 31 janvier plus un mois donne le 2 mars dans une année bissextile et le 3 mars sinon.\n\nExample: Décaler des dates\n```js\nvar now = new Date();\nnow.add('1 day');\nnow.add('minutes', 30);\nnow.add('-2 hours');\nnow.add(5000);  // + 5 seconds\n```\n\n### date.diff([date], type)\n\nType: `method`\n\nRenvoie la différence entre deux dates en secondes, minutes, heures ou jours.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String|Number` | no | `now` | La date à comparer. |\n| `type` | `String` | yes |  | L'unité du résultat. |\n\nReturns: `Number` La différence dans l'unité.\n\nLe résultat est `this - date` dans l'unité indiquée, arrondi vers le haut, donc il est positif quand `this` est postérieure. `date` peut être une Date, une chaîne que `Date.parse()` comprend ou un nombre de millisecondes. Avec un seul argument, la date est comparée à l'heure actuelle. Unités : `s` / `ss` / `second` / `seconds`, `m` / `mm` / `minute` / `minutes`, `h` / `hh` / `hour` / `hours`, `d` / `dd` / `day` / `days`. Une unité inconnue renvoie `NaN`.\n\nExample: Différences\n```js\nvar created = new Date('2024-01-30T00:00:00Z');\nvar end = new Date('2024-01-31T10:00:00Z');\nend.diff(created, 'hours');  // 34\nend.diff('2024-01-01T00:00:00Z', 'days'); // 31\ncreated.diff('seconds');     // negative: created is in the past\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormate la date selon un motif ; sans motif, renvoie une chaîne ISO en UTC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Le motif. |\n| `resource` | `String` | no |  | La ressource utilisée pour les noms des mois et des jours. |\n\nReturns: `String` La date formatée.\n\nSans `format`, le résultat est `yyyy-MM-ddTHH:mm:ss.SSSZ` en UTC. Avec `format`, les parties sont écrites dans le fuseau horaire du serveur (UTC, sauf si la clé de configuration `$timezone` indique autre chose) :\n\n- `yyyy`, `yy` l'année ; `MM`, `M` le numéro du mois ; `MMMM` le nom du mois, `MMM` ses trois premières lettres,\n- `dd`, `d` le jour ; `dddd` le nom du jour, `ddd` ses deux premières lettres en majuscules,\n- `HH`, `H` les heures (0-23) ; `mm`, `m` les minutes ; `ss`, `s` les secondes,\n- `ww`, `w` le numéro de semaine ISO ; `a` `AM` ou `PM`.\n\nLes majuscules `YYYY`, `YY`, `DD`, `D`, `DDDD`, `DDD` et les minuscules `hh`, `h` sont aussi acceptées. Les noms des mois et des jours sont en anglais ; avec `resource`, ils sont traduits avec le fichier de ressources de ce nom. Les formats compilés sont mis en cache, donc le formatage est rapide.\n\nExample: Formater des dates\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.format();                      // 2024-01-31T10:00:00.000Z\nd.format('yyyy-MM-dd HH:mm');    // 2024-01-31 10:00\nd.format('dd.MM.yy');            // 31.01.24\nd.format('dddd, d. MMMM yyyy');  // Wednesday, 31. January 2024\nd.format('MMMM', 'sk');          // the month name from sk.resource\n```\n\n### date.extend(text)\n\nType: `method`\n\nRenvoie une nouvelle date dont les parties date ou heure sont remplacées à partir d'un texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Une date, une heure, ou les deux. |\n\nReturns: `Date` Une nouvelle date.\n\nLe texte peut contenir une date `yyyy-MM-dd` ou `d.M.yyyy` et une heure `HH:mm` ou `HH:mm:ss`. Seules les parties trouvées dans le texte sont remplacées ; les autres sont reprises de la date d'origine. L'année, le mois et le jour sont définis l'un après l'autre : lorsque le jour de la date d'origine n'existe pas dans le nouveau mois, la date passe au mois suivant (le 31 janvier étendu avec `2025-02-10` donne le 10 mars 2025). Les valeurs sont en UTC.\n\nExample: Changer des parties\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.extend('12:30');              // 2024-01-31T12:30:00.000Z\nd.extend('2025-03-04');         // 2025-03-04T10:00:00.000Z\nd.extend('1.3.2020 08:00');     // 2020-03-01T08:00:00.000Z\n```\n\n### date.toUTC([ticks])\n\nType: `method`\n\nDécale une date locale vers UTC selon le décalage du fuseau horaire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Renvoyer des millisecondes. |\n\nReturns: `Date|Number`\n\nLe résultat est la date plus le décalage du fuseau horaire du serveur. Avec `ticks` à `true`, le résultat est le nombre de millisecondes au lieu d'une Date. Sur un serveur qui fonctionne en UTC (par défaut), la date ne change pas.\n\nExample: Vers UTC\n```js\nvar utc = new Date().toUTC();\nvar ms = new Date().toUTC(true);\n```\n\n### date.setTimeZone(timezone)\n\nType: `method`\n\nRenvoie une nouvelle date qui affiche le même instant dans un autre fuseau horaire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | Un nom de fuseau horaire IANA. |\n\nReturns: `Date` Une nouvelle date.\n\nLes parties du résultat (heures, jour, ...) lues dans le fuseau horaire du serveur correspondent à l'heure locale de `timezone` à cet instant, donc `format()` affiche l'heure locale de ce fuseau. `timezone` est un nom IANA comme `Europe/Bratislava` ou `America/New_York`.\n\nExample: Afficher l'heure locale\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.setTimeZone('Europe/Bratislava').format('HH:mm');  // 11:00\n```\n\n### arr.findItem(cb, [value])\n\nType: `method`\n\nRenvoie le premier élément qui correspond, ou null.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Une fonction de test, un nom de propriété ou une valeur. |\n| `value` | `Any` | no |  | La valeur de la propriété. |\n\nReturns: `Object` L'élément ou `null`.\n\nPasse une fonction `(item, index)`, un nom de propriété et une valeur (`('id', 5)` compare `item.id === 5`), ou une valeur seule comparée avec `===`.\n\nExample: Trouver un élément\n```js\nvar users = [{ id: 1, name: 'Peter' }, { id: 2, name: 'Anna' }];\nusers.findItem('id', 2);                  // { id: 2, name: 'Anna' }\nusers.findItem(u => u.name === 'Peter');  // { id: 1, name: 'Peter' }\nusers.findItem('id', 9);                  // null\n```\n\n### arr.findAll(cb, [value])\n\nType: `method`\n\nRenvoie tous les éléments qui correspondent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Une fonction de test, un nom de propriété ou une valeur. |\n| `value` | `Any` | no |  | La valeur de la propriété. |\n\nReturns: `Array` Les éléments correspondants.\n\nPasse une fonction `(item, index)`, un nom de propriété et une valeur (`('id', 5)` compare `item.id === 5`), ou une valeur seule comparée avec `===`. Le résultat est un nouveau tableau ; le tableau d'origine n'est pas modifié.\n\nExample: Filtrer\n```js\nvar items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }];\nitems.findAll('type', 'a').length;  // 2\n```\n\n### arr.findIndex(cb, [value])\n\nType: `method`\n\nRenvoie l'indice du premier élément qui correspond, ou -1.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Une fonction de test, un nom de propriété ou une valeur. |\n| `value` | `Any` | no |  | La valeur de la propriété. |\n\nReturns: `Number` L'indice ou `-1`.\n\nPasse une fonction `(item, index)`, un nom de propriété et une valeur (`('id', 5)` compare `item.id === 5`), ou une valeur seule comparée avec `===`. Total.js remplace le `findIndex()` natif par cette version (avec une fonction, elle se comporte comme la version native) ; `arr.TfindIndex()` est la même méthode.\n\nExample: Indice d'un élément\n```js\nvar users = [{ id: 1 }, { id: 2 }];\nvar index = users.findIndex('id', 2);  // 1\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### arr.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 de test ou un nom de propriété. |\n| `value` | `Any` | yes |  | La valeur de la propriété (passe `undefined` avec une fonction). |\n| `path` | `String` | yes |  | La propriété à renvoyer. |\n| `def` | `Any` | no |  | La valeur par défaut. |\n\nReturns: `Any`\n\nL'élément est trouvé comme dans `Array.findItem()`. Le résultat est `item[path]`, ou `def` quand aucun élément ne correspond ou que la propriété vaut `null` / `undefined`.\n\nExample: Lire une propriété\n```js\nvar users = [{ id: 1, name: 'Peter' }];\nusers.findValue('id', 1, 'name');          // Peter\nusers.findValue('id', 9, 'name', 'guest');  // guest\n```\n\n### arr.remove(cb, [value])\n\nType: `method`\n\nRenvoie un nouveau tableau sans les éléments qui correspondent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Une fonction de test, un nom de propriété ou une valeur. |\n| `value` | `Any` | no |  | La valeur de la propriété. |\n\nReturns: `Array` Un nouveau tableau sans les éléments correspondants.\n\nPasse une fonction `(item, index)`, un nom de propriété et une valeur (`('id', 5)` compare `item.id === 5`), ou une valeur seule comparée avec `===`. Le tableau d'origine n'est pas modifié ; assigne donc le résultat.\n\nExample: Supprimer des éléments\n```js\nvar users = [{ id: 1 }, { id: 2 }, { id: 3 }];\nusers = users.remove('id', 1);       // [{ id: 2 }, { id: 3 }]\nvar nums = [1, 2, 3, 2].remove(2);   // [1, 3]\n```\n\n### arr.quicksort([sort], [desc])\n\nType: `method`\n\nTrie le tableau sur place selon une ou plusieurs propriétés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Propriétés de tri, ou `true` pour des valeurs simples en ordre décroissant. |\n| `desc` | `Boolean` | no | `false` | Ordre décroissant pour `sort`. |\n\nReturns: `Array` Le même tableau, trié.\n\n`sort` est une liste de noms de propriétés séparés par des virgules, chacun éventuellement avec `_asc` ou `_desc` (`'name'`, `'price_desc'`, `'group,date_desc'`). Les propriétés imbriquées avec des points sont prises en charge (`'user.name'`). Le type de chaque colonne (chaîne, nombre, booléen ou Date) est détecté à partir de la première valeur non nulle la première fois qu'une expression de tri est utilisée, et il est conservé pour les tris suivants avec la même expression ; les chaînes sont comparées en tenant compte des diacritiques. Passer `true` (ou `2`) comme deuxième argument trie une seule propriété par ordre décroissant.\n\nSans `sort`, le tableau de valeurs simples est trié par ordre croissant ; `quicksort(true)` le trie par ordre décroissant. La méthode renvoie le même tableau.\n\nExample: Trier des objets\n```js\nvar products = [{ name: 'B', price: 10 }, { name: 'A', price: 20 }];\nproducts.quicksort('name');        // A, B\nproducts.quicksort('price_desc');  // 20, 10\nproducts.quicksort('name', true);  // B, A\n[3, 1, 2].quicksort();             // [1, 2, 3]\n```\n\n### arr.take(count)\n\nType: `method`\n\nRenvoie les count premiers éléments dans un nouveau tableau.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre d'éléments. |\n\nReturns: `Array`\n\nExample: Take\n```js\n[1, 2, 3, 4].take(2);  // [1, 2]\n```\n\n### arr.skip(count)\n\nType: `method`\n\nRenvoie les éléments situés après les count premiers éléments dans un nouveau tableau.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre d'éléments à ignorer. |\n\nReturns: `Array`\n\nCombine-la avec `take()` pour la pagination.\n\nExample: Pagination\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### arr.first([def])\n\nType: `method`\n\nRenvoie le premier élément, ou une valeur par défaut pour un tableau vide. Array.last() renvoie le dernier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Any` | no |  | La valeur pour un tableau vide. |\n\nReturns: `Any`\n\n`arr.last([def])` renvoie le dernier élément ou `def`.\n\nExample: Premier et dernier\n```js\n[1, 2].first();     // 1\n[].first('none');   // none\n[1, 2].last();      // 2\n```\n\n### arr.group(name)\n\nType: `method`\n\nRegroupe les éléments selon une propriété.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La propriété de regroupement. |\n\nReturns: `Array` Des groupes `{ name, items }`.\n\nRenvoie un tableau de `{ name, items }` trié par `name`. La valeur de la propriété est convertie en chaîne ; les éléments sans la propriété sont dans un groupe au nom vide.\n\nExample: Regrouper\n```js\nvar items = [{ type: 'x', id: 1 }, { type: 'y', id: 2 }, { type: 'x', id: 3 }];\nitems.group('type');\n// [{ name: 'x', items: [...2 items] }, { name: 'y', items: [...1 item] }]\n```\n\n### arr.trim()\n\nType: `method`\n\nNettoie les chaînes des espaces et renvoie un nouveau tableau sans valeurs vides.\n\nReturns: `Array`\n\nLes chaînes du tableau d'origine sont nettoyées sur place. Le résultat ne contient que les éléments truthy, donc les chaînes vides, `null`, `undefined`, `0` et `false` sont exclus.\n\nExample: Nettoyer une liste\n```js\n' a , ,b'.split(',').trim();  // ['a', 'b']\n```\n\n### arr.random([item])\n\nType: `method`\n\nMélange le tableau sur place, 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|Any`\n\nSans arguments, le tableau est mélangé (Fisher-Yates) et renvoyé. Avec `item` à `true`, un élément aléatoire est renvoyé et le tableau n'est pas modifié.\n\nExample: Aléatoire\n```js\nvar colors = ['red', 'green', 'blue'];\ncolors.random(true);  // one color\ncolors.random();      // the shuffled array\n```\n\n### arr.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 |  | `function(item, next)`. |\n| `callback` | `Function` | no |  | Appelée quand tous les éléments sont traités. |\n| `thread` | `Number|Boolean` | no | `1` | Les éléments en parallèle, ou `true` pour retirer les éléments au fur et à mesure de leur traitement. |\n\nReturns: `Array` Le tableau.\n\n`onItem(item, next)` est appelée pour chaque élément ; appelle `next()` pour passer à l'élément suivant. `callback()` est appelée quand tous les éléments sont traités. `thread` définit combien d'éléments sont traités en même temps (1 par défaut). Avec `thread` à `true`, les éléments sont retirés du tableau avec `shift()` au fur et à mesure de leur traitement. Appelle `next('cancel')` pour arrêter : `callback('cancel')` est alors appelée.\n\nExample: Traiter en séquence\n```js\nvar ids = [1, 2, 3];\nids.wait(function(id, next) {\n\tFUNC.removeuser(id, next);\n}, function() {\n\tconsole.log('All removed');\n});\n```\n\nExample: Deux à la fois\n```js\nurls.wait(function(url, next) {\n\tREQUEST({ url: url, callback: () => next() });\n}, () => console.log('done'), 2);\n```\n\n### arr.async([thread], [callback])\n\nType: `method`\n\nExécute un tableau de fonctions l'une après l'autre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | Le nombre de fonctions exécutées en même temps. |\n| `callback` | `Function` | no |  | Appelée à la fin. |\n\nReturns: `Array` Le tableau.\n\nChaque élément est une fonction `(next)` ; appelle `next()` quand elle a terminé. Les fonctions sont retirées du tableau au fur et à mesure de leur exécution, donc le tableau est vide à la fin. `thread` définit combien de fonctions démarrent en même temps (1 par défaut). `callback()` est appelée quand toutes les fonctions sont terminées, ou `callback('cancel')` quand l'une d'elles appelle `next('cancel')`.\n\nExample: Exécuter des tâches\n```js\nvar tasks = [];\ntasks.push(function(next) {\n\tconsole.log('first');\n\tnext();\n});\ntasks.push(function(next) {\n\tsetTimeout(next, 100);\n});\ntasks.async(function() {\n\tconsole.log('done');\n});\n```\n\n### arr.limit(max, fn, [callback])\n\nType: `method`\n\nTraite le tableau par morceaux de max éléments.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La taille d'un morceau. |\n| `fn` | `Function` | yes |  | `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Appelée à la fin. |\n\nReturns: `Array` Le tableau.\n\n`fn(items, next, beg, end)` reçoit le morceau suivant et les indices de début et de fin ; appelle `next()` pour continuer. `callback()` est appelée après le dernier morceau.\n\nExample: Insérer par lots\n```js\nrows.limit(100, function(items, next) {\n\tFUNC.importrows(items, next);\n}, function() {\n\tconsole.log('Imported');\n});\n```\n","entries":[{"type":"method","name":"String.format()","signature":"str.format(arg0, [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"str.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"str.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"str.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"str.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"str.toName()","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"str.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"str.decode()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"str.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"str.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"str.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.toKeywords()","signature":"str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"str.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"str.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"str.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"str.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"str.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"str.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"str.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"str.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseContext()","signature":"str.parseContext()","since":"0.0.17","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"str.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"str.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseEnv()","signature":"str.parseEnv()","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"str.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"str.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"str.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"str.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"str.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"str.isNumber([isDecimal])","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"str.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"str.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"str.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"str.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"str.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"str.sign([key], [check])","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"str.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"str.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"str.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"num.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"num.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"num.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"num.round(precision)","since":"","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"num.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"num.between(condition, [otherwise])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"num.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"num.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"num.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"num.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"date.extend(text)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"arr.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"arr.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"arr.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"arr.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"arr.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"arr.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"arr.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"arr.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"arr.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.group()","signature":"arr.group(name)","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"arr.trim()","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"arr.random([item])","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"arr.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"arr.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"arr.limit(max, fn, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JacXWy2qt61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/prototypes/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Prototipi","summary":"Tutti i metodi che Total.js aggiunge a String, Number, Date e Array.prototype.","markdown":"---\ntitle: Prototipi\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/prototypes/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Prototipi\n\n> Tutti i metodi che Total.js aggiunge a String, Number, Date e Array.prototype.\n\nMetodi che Total.js 5 aggiunge ai prototipi integrati `String`, `Number`, `Date` e `Array`. Sono disponibili ovunque una volta caricato il framework. La guida [Prototipi](../../guides/prototypes/) mostra come usarli insieme con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### str.format(arg0, [arg1], [...])\n\nType: `method`\n\nSostituisce i segnaposto numerati {0}, {1}, ... con gli argomenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0...argN` | `Any` | yes |  | Valori per `{0}`, `{1}` e così via. |\n\nReturns: `String` La nuova stringa.\n\nOgni `{n}` viene sostituito con l'argomento all'indice `n`. Un segnaposto il cui argomento è `null` o `undefined` diventa una stringa vuota. Tra le parentesi graffe sono ammessi solo numeri; usa `String.args()` per le chiavi con nome.\n\nExample: Segnaposto numerati\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n// Hello Peter, you have 5 messages.\n```\n\n### str.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` | `String|Function` | no |  | `html`, `json`, una funzione `(value, key)` o qualsiasi altra stringa per la codifica URL. |\n| `def` | `String` | no |  | Il testo per le chiavi senza valore. |\n\nReturns: `String` La nuova stringa.\n\n`String.arg()` è lo stesso metodo. Un segnaposto è una chiave tra parentesi graffe singole o doppie; gli spazi all'interno delle parentesi vengono rimossi. Le chiavi vengono lette direttamente da `obj` (niente percorsi annidati).\n\n`encode` cambia l'output di ogni valore: `'html'` lo codifica con `String.encode()`, `'json'` scrive `JSON.stringify(value)`, qualsiasi altra stringa truthy usa `encodeURIComponent()`, e una funzione `(value, key)` restituisce il testo stesso. Quando `encode` è una stringa sostituisce anche `def`: con `'html'` o una stringa di codifica URL, una chiave senza valore diventa il testo di `encode`; con `'json'` diventa `undefined`. Senza `encode`, una chiave senza valore viene lasciata com'è, o sostituita con `def` quando lo passi.\n\nExample: Segnaposto con nome\n```js\nvar tpl = 'Hello {name}, your order {{ id }} is ready.';\ntpl.args({ name: 'Peter', id: 'A100' });\n// Hello Peter, your order A100 is ready.\n\n'<b>{name}</b>'.args({ name: '<script>' }, 'html');\n// <b>&lt;script&gt;</b>\n```\n\n### str.slug([max])\n\nType: `method`\n\nCrea uno slug adatto agli URL dal testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | La lunghezza massima dello slug. |\n\nReturns: `String` Lo slug.\n\nIl testo viene sottoposto a trim, convertito in minuscolo e privato dei segni diacritici (`toASCII()`). Lettere, cifre e `_` vengono mantenuti; gli spazi e i caratteri `!\"#$%&'()*+,-./` diventano un singolo `-`; gli altri caratteri vengono scartati. Un `-` finale viene rimosso e il risultato ha al massimo `max` caratteri.\n\nQuando il testo contiene un carattere senza forma ASCII il cui codice è superiore a 540 (ad esempio lettere cirilliche, `€` o un'emoji), l'intero testo non viene convertito in slug lettera per lettera: il metodo restituisce invece un breve identificatore basato su un hash del testo, quindi il risultato resta stabile e sicuro per gli URL.\n\nExample: Slug di un titolo\n```js\n' Hello World! Čaute 123 '.slug();\n// hello-world-caute-123\n\n'A very long article title'.slug(10);\n// a-very-lon\n```\n\n### str.max(length, [chars])\n\nType: `method`\n\nAccorcia il testo a una lunghezza massima e aggiunge dei 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 accorciata. |\n\nReturns: `String` Il testo, accorciato quando necessario.\n\nQuando il testo è più lungo di `length`, viene tagliato in modo che il risultato, compreso `chars`, abbia esattamente `length` caratteri. Il testo più corto viene restituito invariato.\n\nExample: Accorciare\n```js\n'Hello world'.max(8);       // Hello...\n'Hello world'.max(8, '…');  // Hello w…\n```\n\n### str.capitalize([first])\n\nType: `method`\n\nMette in maiuscolo la prima lettera di ogni parola, o solo del testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Mettere in maiuscolo solo il primo carattere. |\n\nReturns: `String` La nuova stringa.\n\nIl testo viene prima convertito in minuscolo. Senza argomenti ogni lettera dopo uno spazio, una tabulazione o un a capo diventa maiuscola. Con `first` impostato a `true`, solo il primo carattere diventa maiuscolo e il resto rimane minuscolo.\n\nExample: Maiuscole\n```js\n'hello WORLD'.capitalize();      // Hello World\n'hello WORLD'.capitalize(true);  // Hello world\n```\n\n### str.toName()\n\nType: `method`\n\nPulisce il nome di una persona: rimuove cifre e simboli, spazi superflui e mette in maiuscolo le parole.\n\nReturns: `String` Il nome pulito.\n\nVengono mantenuti solo le lettere ASCII, i caratteri con codice superiore a 127 (lettere con segni diacritici) e gli spazi. Gli spazi ripetuti vengono ridotti a uno, gli spazi finali vengono rimossi (gli spazi iniziali diventano uno spazio) e la prima lettera di ogni parola viene resa maiuscola. Il resto di ogni parola resta com'è.\n\nExample: Ripulire un nome\n```js\n'peter   sirka 12'.toName();\n// Peter Sirka\n```\n\n### str.encode()\n\nType: `method`\n\nCodifica i caratteri speciali HTML.\n\nReturns: `String` Il testo codificato.\n\n`String.safehtml()` è lo stesso metodo. I caratteri `<`, `>`, `\"`, `'` e `&` vengono sostituiti con `&lt;`, `&gt;`, `&quot;`, `&apos;` e `&amp;`. Usalo prima di inserire testo degli utenti in HTML.\n\nExample: Codificare l'input dell'utente\n```js\n'<a href=\"x\">Tom & Jerry</a>'.encode();\n// &lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/a&gt;\n```\n\n### str.decode()\n\nType: `method`\n\nDecodifica le entità HTML riportandole a caratteri.\n\nReturns: `String` Il testo decodificato.\n\nLe entità con nome (`&lt;`, `&amp;`, `&quot;`, ...) e le entità numeriche (`&#65;`, `&#x41;`) vengono sostituite con i loro caratteri. Le entità con nome sconosciute restano così come sono.\n\nExample: Decodificare\n```js\n'&lt;b&gt;Tom &amp; Jerry&#33;&lt;/b&gt;'.decode();\n// <b>Tom & Jerry!</b>\n```\n\n### str.removeTags()\n\nType: `method`\n\nRimuove i tag HTML dal testo.\n\nReturns: `String` Il testo senza tag.\n\nOgni tag `<...>` (di apertura o di chiusura) viene rimosso; il testo tra i tag rimane. Il risultato non è codificato in HTML, quindi codificalo con `String.encode()` quando lo riscrivi in HTML.\n\nExample: Rimuovere i tag\n```js\n'<p><b>Hi</b> there</p>'.removeTags();\n// Hi there\n```\n\n### str.padLeft(max, [c])\n\nType: `method`\n\nRiempie il testo a sinistra fino a una lunghezza. String.padRight() riempie a destra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La lunghezza del risultato. |\n| `c` | `String` | no | `' '` | Il carattere di riempimento. |\n\nReturns: `String` Il testo riempito.\n\nVengono aggiunti caratteri `c` finché il testo ha `max` caratteri; il testo più lungo viene restituito invariato. `str.padRight(max, [c])` funziona allo stesso modo sul lato destro. Entrambi sono definiti solo quando il runtime non li ha già.\n\nExample: Riempimento\n```js\n'5'.padLeft(3, '0');   // 005\n'a'.padRight(3, '-');  // a--\n```\n\n### str.toASCII()\n\nType: `method`\n\nSostituisce le lettere con diacritici con la loro forma ASCII.\n\nReturns: `String` Il testo senza segni diacritici.\n\nLettere come `č`, `á` o `ü` vengono sostituite con `c`, `a` e `u`. I caratteri senza forma ASCII restano così come sono.\n\nExample: Rimuovere i diacritici\n```js\n'Čučoriedka'.toASCII();\n// Cucoriedka\n```\n\n### str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nEstrae le parole chiave dal testo, prima le più frequenti.\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 le parole all'80 % della loro lunghezza. |\n| `max_count` | `Number` | no | `200` | Il numero massimo di parole da leggere. |\n| `max_length` | `Number` | no | `20` | La lunghezza massima di una parola chiave. |\n| `min_length` | `Number` | no | `2` | La lunghezza minima di una parola chiave. |\n\nReturns: `Array` Parole chiave uniche ordinate per frequenza.\n\nIl testo viene convertito in minuscolo e diviso in parole; i caratteri che non sono lettere o cifre vengono rimossi da ogni parola. Con `forsearch` (predefinito) i diacritici vengono rimossi e `y` diventa `i`, il che rende il confronto tollerante. `alternative` mantiene solo il primo 80 % delle parole più lunghe (una semplice radice). Le parole più corte di `min_length` o più lunghe di `max_length` vengono saltate e vengono lette al massimo `max_count` parole. Le parole uniche vengono restituite ordinate per frequenza.\n\nPer una singola stringa di ricerca normalizzata usa `str.toSearch()`: converte il testo in minuscolo, rimuove diacritici e simboli, sostituisce `y` con `i` ed elimina le lettere ripetute (`hello` diventa `helo`).\n\nExample: Parole chiave per un indice di ricerca\n```js\n'Total.js is a great framework, great!'.toKeywords();\n// ['great', 'totaljs', 'is', 'framework']\n\n'Čaute Hello'.toSearch();\n// caute helo\n```\n\n### str.pluralize(zero, one, few, other)\n\nType: `method`\n\nConverte il testo in un numero e sceglie una forma plurale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Testo per 0, oppure tutte e quattro le forme separate da virgole. |\n| `one` | `String` | no |  | Testo per 1. |\n| `few` | `String` | no |  | Testo per da 2 a 4. |\n| `other` | `String` | no |  | Testo per gli altri numeri. |\n\nReturns: `String` La forma scelta.\n\nIl testo viene convertito con `parseInt()` e il risultato viene passato a `Number.pluralize()`.\n\nExample: Plurale di una stringa\n```js\n'3'.pluralize('no items', '# item', '# items', '# items');\n// 3 items\n```\n\n### str.parseInt([def])\n\nType: `method`\n\nConverte il testo in un numero, con un valore predefinito per il testo non valido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Il valore per il testo che non è un numero. |\n\nReturns: `Number` Il numero o il valore predefinito.\n\nIl testo viene ripulito dagli spazi e convertito con il `+` unario, quindi `'10'` è `10`, `'1.5'` è `1.5` e `'0x10'` è `16`. Quando il testo non è un numero, viene restituito `def` (`0` quando lo ometti).\n\n`str.parseInt2([def])` trova invece il primo intero in qualsiasi punto del testo (`'abc 123'` dà `123`); `str.parseFloat2([def])` fa lo stesso per un numero decimale e accetta `,` come separatore decimale.\n\nExample: Leggere numeri\n```js\n'10'.parseInt();        // 10\n'abc'.parseInt(5);      // 5\n'Total: 123 EUR'.parseInt2(); // 123\n'x 1,5 y'.parseFloat2();      // 1.5\n```\n\n### str.parseFloat([def])\n\nType: `method`\n\nConverte il testo in un numero decimale; la virgola è accettata come separatore decimale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Il valore per il testo che non è un numero. |\n\nReturns: `Number` Il numero o il valore predefinito.\n\nIl testo viene ripulito dagli spazi, la prima `,` viene sostituita con `.` e il testo viene convertito in un numero. Quando il testo non è un numero, viene restituito `def` (`0` quando lo ometti).\n\nExample: Leggere decimali\n```js\n'1,5'.parseFloat();    // 1.5\n' 2.25 '.parseFloat(); // 2.25\n'n/a'.parseFloat(-1);  // -1\n```\n\n### str.parseBoolean()\n\nType: `method`\n\nConverte il testo in un booleano.\n\nReturns: `Boolean`\n\nRestituisce `true` per `true`, `1` e `on` (senza distinzione tra maiuscole e minuscole) e `false` per tutto il resto.\n\nExample: Leggere un flag\n```js\n'on'.parseBoolean();    // true\n'TRUE'.parseBoolean();  // true\n'no'.parseBoolean();    // false\n```\n\n### str.parseDate([format])\n\nType: `method`\n\nConverte il testo in una Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Un formato come `dd/MM/yyyy HH:mm`. |\n\nReturns: `Date` La data analizzata.\n\nSenza `format` il metodo comprende:\n\n- date JSON (`2024-05-01T12:30:00.000Z`),\n- `yyyy-MM-dd`, `yyyy-MM-dd HH:mm`, `yyyy-MM-dd HH:mm:ss` e `yyyy-MM-ddTHH:mm:ss.SSS`,\n- `d.M.yyyy` con un orario opzionale (`1.5.2024 08:00`),\n- qualsiasi altra cosa che `new Date(text)` accetti.\n\nLa data e l'ora di queste forme vengono lette come UTC. Le parti mancanti della data vengono prese dalla data odierna.\n\nCon `format` le cifre del testo vengono lette secondo le posizioni di `yyyy`, `MM`, `dd`, `HH`, `mm` e `ss` nel formato; gli altri caratteri del formato servono solo a separare le parti. Le parti devono essere scritte con tutte le loro cifre (`05`, non `5`). Un anno a due cifre è negli anni 2000, e `pm` nel testo aggiunge 12 ore.\n\nExample: Analizzare date\n```js\n'2024-05-01 12:30'.parseDate();\n// 2024-05-01T12:30:00.000Z\n\n'1.5.2024'.parseDate();\n// 2024-05-01T00:00:00.000Z\n\n'01/05/2024'.parseDate('dd/MM/yyyy');\n// 1 May 2024\n```\n\n### str.parseDateExpiration()\n\nType: `method`\n\nConverte un tempo relativo come \"5 minutes\" in una Date nel futuro.\n\nReturns: `Date` L'ora corrente più la durata indicata.\n\nIl testo è un elenco di coppie `number unit` separate da spazi. Ogni coppia viene aggiunta all'ora corrente con `Date.add()`, quindi funzionano tutte le unità di `Date.add()` (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years` e le loro forme brevi). Usa un numero negativo per una data nel passato.\n\nExample: Scadenza\n```js\nvar expire = '5 minutes'.parseDateExpiration();\nvar later = '1 day 2 hours'.parseDateExpiration();\n```\n\n### str.parseJSON([date])\n\nType: `method`\n\nAnalizza JSON senza lanciare eccezioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | Convertire le stringhe di data JSON in oggetti Date. |\n\nReturns: `Object` Il valore analizzato o `undefined`.\n\nRestituisce il valore analizzato, oppure `undefined` quando il testo non è JSON valido. Con `date` impostato a `true`, le stringhe nel formato data JSON (`2024-01-01T10:00:00.000Z`) diventano oggetti `Date`.\n\nExample: Parsing sicuro\n```js\nvar obj = '{\"a\":1}'.parseJSON();          // { a: 1 }\nvar bad = '{a:1'.parseJSON();             // undefined\nvar doc = '{\"created\":\"2024-01-01T10:00:00.000Z\"}'.parseJSON(true);\ndoc.created instanceof Date;             // true\n```\n\n### str.parseCSV([delimiter])\n\nType: `method`\n\nAnalizza testo CSV in un array di oggetti con chiavi di colonna a, b, c, ...\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | Il delimitatore di colonna, un carattere. |\n\nReturns: `Array` Un array di oggetti.\n\nOgni riga diventa un oggetto. Le chiavi sono lettere di colonna: `a` per la prima colonna, `b` per la seconda, ..., `z`, poi `aa`, `ab` e così via. I valori tra virgolette doppie possono contenere il delimitatore e degli a capo; `\"\"` tra virgolette è una virgoletta con escape. Le colonne vuote non hanno chiave nell'oggetto. I valori sono stringhe e non vengono ripuliti dagli spazi. Una riga di intestazione viene restituita come qualsiasi altra riga.\n\nExample: Analizzare CSV\n```js\nvar rows = 'name,age\\n\"Sirka, Peter\",40\\nAnna,'.parseCSV();\n// [{ a: 'name', b: 'age' }, { a: 'Sirka, Peter', b: '40' }, { a: 'Anna' }]\n\nvar header = rows.shift();\nfor (var row of rows)\n\tconsole.log(row.a, row.b || '-');\n```\n\n### str.parseContext()\n\nType: `method` · Since: `0.0.17`\n\nAnalizza un testo composto da blocchi con un'intestazione e un corpo.\n\nReturns: `Array` Un array di oggetti, uno per blocco.\n\nOgni blocco inizia con una riga di almeno 20 trattini, seguita da righe di intestazione `key: value`, un'altra riga di almeno 20 trattini e il corpo. Il corpo termina dove inizia il blocco successivo. Ogni blocco diventa un oggetto con le chiavi dell'intestazione (in minuscolo, valori senza spazi iniziali e finali) e una proprietà `body` con il corpo senza spazi iniziali e finali. Le righe di intestazione senza `:` vengono ignorate.\n\nExample: Analizzare i blocchi\n```js\nvar text = [\n\t'--------------------',\n\t'Name: Hello',\n\t'Type: note',\n\t'--------------------',\n\t'Body one',\n\t'--------------------',\n\t'Name: Second',\n\t'--------------------',\n\t'Body two'\n].join('\\n');\n\ntext.parseContext();\n// [{ name: 'Hello', type: 'note', body: 'Body one' }, { name: 'Second', body: 'Body two' }]\n```\n\n### str.parseEncoded()\n\nType: `method`\n\nAnalizza testo URL-encoded (una query string o il corpo di un form) in un oggetto.\n\nReturns: `Object` Le chiavi e i valori analizzati (stringhe).\n\nLe coppie `key=value` sono separate da `&`; chiavi e valori vengono decodificati dall'URL. È il parser che Total.js usa per le query string e i corpi `application/x-www-form-urlencoded`.\n\nExample: Analizzare una query string\n```js\n'q=total.js&page=2&name=%20Peter'.parseEncoded();\n// { q: 'total.js', page: '2', name: ' Peter' }\n```\n\n### str.parseConfig([def], [onerr])\n\nType: `method`\n\nAnalizza testo nel formato di configurazione di Total.js 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)` per i valori che non possono essere valutati. |\n\nReturns: `Object` I valori analizzati.\n\nOgni riga è `key : value`. Il separatore è il primo `:`, o il primo `=` quando la riga non ha `:`; il valore inizia dal secondo carattere dopo il separatore, quindi lascia uno spazio lì. Le righe vuote e quelle che iniziano con `#` o `//` vengono saltate. Un valore che inizia con `base64 ` o `hex ` viene decodificato.\n\nUn tipo tra parentesi dopo la chiave converte il valore: `(string)`, `(number)` (anche `float`, `double`, `currency`), `(boolean)` / `(bool)` (true quando il valore contiene `true`, `on`, `1` o `enabled`, maiuscolo o minuscolo), `(json)`, `(object)` / `(array)` / `(eval)` (valutato come JavaScript), `(date)`, `(env)` (legge `process.env[value]`), `(config)` (legge un'altra chiave di configurazione) e `(random)` (una stringa casuale della lunghezza indicata). Quando un valore valutato fallisce, viene chiamata `onerr(err, line)`, oppure senza di essa viene lanciato un errore.\n\nExample: Analizzare le impostazioni\n```js\nvar text = 'name : Shop\\ncount (number) : 10\\nenabled (boolean) : true\\n# comment\\ntags (array) : [\\'a\\', \\'b\\']';\ntext.parseConfig();\n// { name: 'Shop', count: 10, enabled: true, tags: ['a', 'b'] }\n```\n\n### str.parseEnv()\n\nType: `method`\n\nAnalizza testo nel formato .env in un oggetto.\n\nReturns: `Object` Le chiavi e i valori.\n\nOgni riga è `KEY=value`. Le righe vuote o che iniziano con `#` o `//` vengono saltate. Un valore tra apici singoli o doppi viene privato delle virgolette (i suoi spazi interni vengono mantenuti); gli altri valori vengono ripuliti dagli spazi. `\\n` in un valore diventa un a capo. Tutti i valori sono stringhe.\n\nExample: Analizzare .env\n```js\n'PORT=8000\\nNAME=\"My app\"\\n# comment'.parseEnv();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### str.parseUA([structured])\n\nType: `method`\n\nLegge il sistema operativo, il browser e il tipo di dispositivo da un header User-Agent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Restituire un oggetto invece del testo. |\n\nReturns: `String|Object`\n\nSenza argomenti il risultato è un breve testo come `Windows Chrome`. Con `structured` impostato a `true` il risultato è un oggetto `{ os, browser, device }`, dove `device` è `mobile` o `desktop`. Un testo vuoto restituisce una stringa vuota.\n\nExample: Leggere lo user agent\n```js\nvar ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Version/17.0 Mobile Safari/604.1';\nua.parseUA();      // iPhone Safari\nua.parseUA(true);  // { os: 'iPhone', browser: 'Safari', device: 'mobile' }\n```\n\n### str.isEmail()\n\nType: `method`\n\nVerifica che il testo sia un indirizzo e-mail.\n\nReturns: `Boolean`\n\nIl test usa l'espressione regolare `email` di `DEF.validators`: lettere, cifre e `-_.+` prima di `@`, un dominio e un dominio di primo livello di almeno due lettere. Un testo di quattro caratteri o meno non è mai valido.\n\nExample: Validare\n```js\n'info@example.com'.isEmail();  // true\n'info@example'.isEmail();      // false\n```\n\n### str.isPhone()\n\nType: `method`\n\nVerifica che il testo sia un numero di telefono.\n\nReturns: `Boolean`\n\nIl test usa l'espressione regolare `phone` di `DEF.validators`: un `+` opzionale, tre cifre (opzionalmente tra parentesi), tre cifre e da 4 a 8 cifre, ogni gruppo opzionalmente separato da `-`, `.` o uno spazio. Un testo più corto di sei caratteri non è mai valido.\n\nExample: Validare\n```js\n'+421903123456'.isPhone();  // true\n'(123) 456-7890'.isPhone(); // true\n'12345'.isPhone();          // false\n```\n\n### str.isURL()\n\nType: `method`\n\nVerifica che il testo sia un URL http o https.\n\nReturns: `Boolean`\n\nIl testo deve iniziare con `http://` o `https://` e non deve contenere `,`, `{`, `}` o `\\`. Un testo di sette caratteri o meno non è mai valido.\n\nExample: Validare\n```js\n'https://www.totaljs.com'.isURL();  // true\n'www.totaljs.com'.isURL();          // false\n```\n\n### str.isUID()\n\nType: `method`\n\nVerifica che il testo sia un identificatore valido creato da UID().\n\nReturns: `Boolean`\n\nIl metodo verifica il formato e il checksum degli identificatori creati da `UID()`, quindi una stringa casuale della stessa forma viene rifiutata. Per leggere la data e l'indice memorizzati in un UID usa `str.parseUID()`, che restituisce `{ version, date, century, hash, index, valid }`. Per i GUID standard (cifre esadecimali `8-4-4-4-12`) usa `str.isGUID()`.\n\nExample: Validare un id\n```js\nvar id = UID();\nid.isUID();       // true\n'abc'.isUID();    // false\nid.parseUID().date;  // the time the id was created\n'123e4567-e89b-12d3-a456-426614174000'.isGUID(); // true\n```\n\n### str.isNumber([isDecimal])\n\nType: `method`\n\nVerifica che il testo contenga solo cifre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `isDecimal` | `Boolean` | no | `false` | Ammettere un separatore decimale. |\n\nReturns: `Boolean`\n\nOgni carattere deve essere una cifra. Con `isDecimal` impostato a `true`, è ammesso anche un `.` o una `,`. Un segno (`-`, `+`) non è ammesso e un testo vuoto non è un numero.\n\nExample: Validare\n```js\n'0123'.isNumber();      // true\n'1.5'.isNumber();       // false\n'1,5'.isNumber(true);   // true\n```\n\n### str.isJSON()\n\nType: `method`\n\nVerifica rapidamente che il testo sembri un oggetto, un array o una stringa JSON.\n\nReturns: `Boolean`\n\nGli spazi iniziali e finali vengono ignorati e vengono confrontati il primo e l'ultimo carattere: `{` con `}`, `[` con `]` o `\"` con `\"`. È `true` anche quando il testo inizia con una cifra o una lettera e termina con un carattere inferiore a `9`, ad esempio `'123'` o `'abc1'`. Il contenuto non viene interpretato, quindi usa `String.parseJSON()` quando devi esserne sicuro.\n\nExample: Controllare prima di interpretare\n```js\nvar body = ' {\"a\":1} ';\nif (body.isJSON())\n\tvar obj = body.parseJSON();\n```\n\n### str.isXSS()\n\nType: `method`\n\nVerifica che il testo contenga un tag HTML.\n\nReturns: `Boolean`\n\nRestituisce `true` quando il testo contiene `<` seguito più avanti da `>`, che è il modo in cui l'espressione regolare `xss` di `DEF.validators` rileva il markup nell'input degli utenti. `str.isSQLInjection()` funziona allo stesso modo con l'espressione `sqlinjection`: è `true` per le stringhe tra virgolette e per le parole chiave SQL `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` e `UNION` scritte in maiuscolo. Entrambi sono filtri semplici, non un sostituto della codifica dell'output e dei parametri delle query.\n\nExample: Rifiutare il markup\n```js\n'<script>alert(1)</script>'.isXSS();  // true\n'Hello'.isXSS();                      // false\n'DROP TABLE users'.isSQLInjection();   // true\n```\n\n### str.hash([type], [salt])\n\nType: `method`\n\nRestituisce un hash del testo: un hash numerico veloce o un digest md5, sha1, sha256, sha512 o crc32.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32`, `crc32unsigned`, oppure `true` per un hash numerico senza segno. |\n| `salt` | `String` | no |  | Testo aggiunto prima dell'hashing. |\n\nReturns: `Number|String` Un numero per l'hash numerico e crc32, altrimenti una stringa esadecimale.\n\n`type` seleziona l'algoritmo: `md5`, `sha1`, `sha256`, `sha512` (stringhe esadecimali), `crc32` (numero con segno) o `crc32unsigned` (numero senza segno). Senza `type` il metodo restituisce un hash numerico veloce a 32 bit del testo (con segno); `hash(true)` lo restituisce senza segno. `salt` viene aggiunto al testo prima dell'hashing. L'hash numerico non è un hash crittografico: usalo per chiavi di cache e scopi simili. Anche `str.crc32([unsigned])` è disponibile direttamente.\n\nExample: Hash\n```js\n'hello'.hash();          // a signed 32-bit number\n'hello'.hash(true);      // the same, unsigned\n'hello'.hash('sha256');  // hex digest\n'hello'.hash('crc32unsigned');\n```\n\n### str.md5([salt])\n\nType: `method`\n\nRestituisce il digest MD5 del testo 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` 32 caratteri esadecimali.\n\nIl testo (con `salt` aggiunto) viene sottoposto a hash come UTF-8 con `crypto` di Node.js. MD5 è adatto per checksum e chiavi di cache, non per le password.\n\nExample: MD5\n```js\n'a'.md5();\n// 0cc175b9c0f1b6a831c399e269772661\n```\n\n### str.sha256([salt])\n\nType: `method`\n\nRestituisce il digest SHA-256 del testo come stringa esadecimale. sha1() e sha512() funzionano allo stesso modo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |\n\nReturns: `String` 64 caratteri esadecimali.\n\nIl testo (con `salt` aggiunto) viene sottoposto a hash come UTF-8 con `crypto` di Node.js. `str.sha1([salt])` restituisce 40 caratteri esadecimali e `str.sha512([salt])` 128 caratteri esadecimali.\n\nExample: Digest SHA\n```js\nvar digest = 'password'.sha256(CONF.secret);\nvar short = 'text'.sha1();\nvar long = 'text'.sha512();\n```\n\n### str.sign([key], [check])\n\nType: `method`\n\nFirma il testo con un breve checksum, oppure verifica e rimuove la firma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | La chiave di firma. |\n| `check` | `Boolean` | no | `false` | Controlla la firma e restituisci il testo originale. |\n\nReturns: `String` Il testo firmato, il testo originale, oppure `null`.\n\n`str.sign(key)` restituisce `text-checksum`, dove il checksum è ricavato dal testo e da `key`. `signed.sign(key, true)` verifica il checksum e restituisce il testo originale, oppure `null` quando la firma non corrisponde. Usalo per valori che viaggiano negli URL e non devono essere modificati, come gli id nei link. Non è crittografia: il testo resta leggibile.\n\n`str.makeid()` restituisce solo un breve checksum in base 36 del testo, comodo come chiave compatta.\n\nExample: Firmare un id\n```js\nvar token = '123'.sign('mykey');     // 123-155hlxd\ntoken.sign('mykey', true);           // 123\n(token + 'x').sign('mykey', true);   // null\n```\n\n### str.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nCifra il testo con una chiave. String.decrypt() fa l'operazione inversa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave di cifratura. |\n| `isUnique` | `Boolean` | no | `false` | Produrre un risultato diverso a ogni chiamata. |\n| `secret` | `String` | no | `CONF.secret` | Il segreto usato nel checksum. |\n\nReturns: `String` Il testo cifrato.\n\nIl risultato è una stringa composta da un checksum, `-` e dati esadecimali. Con `isUnique` impostato a `true`, lo stesso testo dà ogni volta un risultato diverso. Il checksum usa `secret`, oppure la chiave di configurazione `secret` quando lo ometti.\n\n`str.decrypt(key, [secret])` restituisce il testo originale, oppure `null` quando la chiave, il segreto o i dati non corrispondono. Usa la stessa `key` e lo stesso `secret` per entrambi.\n\nExample: Cifrare e decifrare\n```js\nvar value = 'user@example.com'.encrypt('mykey', true);\nvalue.decrypt('mykey');   // user@example.com\nvalue.decrypt('other');   // null\n```\n\n### str.encrypt_uid([key])\n\nType: `method`\n\nCifra un identificatore in un breve token sicuro per gli URL. String.decrypt_uid() fa l'operazione inversa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | La chiave. |\n\nReturns: `String` Il token.\n\nUsalo per nascondere id numerici o testuali negli URL pubblici. `key` ha come valore predefinito la chiave di configurazione `secret`. `token.decrypt_uid([key])` restituisce l'id originale, oppure `null` quando il token è stato modificato o la chiave è diversa.\n\nExample: Nascondere un id\n```js\nvar token = '123'.encrypt_uid('mykey');\ntoken.decrypt_uid('mykey');  // 123\n```\n\n### str.base64ToBuffer()\n\nType: `method`\n\nConverte testo base64 o un data URI in un Buffer.\n\nReturns: `Buffer` I dati decodificati.\n\nTutto fino alla prima `,` compresa viene saltato, quindi funzionano sia il base64 semplice sia `data:...;base64,...`. Metodi correlati: `str.base64ToFile(filename, [callback])` scrive i dati decodificati in un file, `str.base64ContentType()` restituisce il content type di un data URI (`image/png`), e `str.parseDataURI()` restituisce `{ type, buffer }` (oppure `null` per un testo che non è un data URI).\n\nExample: Decodificare un upload\n```js\nvar uri = 'data:text/plain;base64,aGVsbG8=';\nuri.base64ToBuffer().toString();   // hello\nuri.base64ContentType();           // text/plain\nuri.parseDataURI().type;           // text/plain\nuri.base64ToFile(PATH.temp('hello.txt'));\n```\n\n### num.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormatta un numero con un separatore delle migliaia e un numero fisso di 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 è uno spazio per impostazione predefinita. Il separatore decimale è `.`, oppure `,` quando il separatore delle migliaia è `.`. I decimali in eccesso vengono troncati, non arrotondati, quindi chiama prima `Number.round()` quando ti serve l'arrotondamento. I decimali mancanti vengono riempiti con zeri. Quando il primo argomento è una stringa, i primi due argomenti vengono scambiati: `format('.', 2)` equivale a `format(2, '.')`.\n\nExample: Formattare\n```js\n(1234567.891).format(2);           // 1 234 567.89\n(1234.5).format(2, ',', '.');      // 1,234.50\n(1234.5).format('.', 2);           // 1.234,50\n(1.999).round(2).format(2);        // 2.00\n```\n\n### num.pluralize(zero, one, few, other)\n\nType: `method`\n\nSceglie una forma plurale in base al numero; # viene sostituito con il numero.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Testo per 0, oppure tutte e quattro le forme separate da virgole. |\n| `one` | `String` | no |  | Testo per 1. |\n| `few` | `String` | no |  | Testo per da 2 a 4. |\n| `other` | `String` | no |  | Testo per gli altri numeri. |\n\nReturns: `String` La forma scelta.\n\nLa forma `zero` viene usata per 0, `one` per 1, `few` per da 2 a 4 e `other` per il resto (la regola delle lingue slave; per l'inglese passa lo stesso testo come `few` e `other`). Quando passi una sola stringa, viene divisa dalle virgole nelle quattro forme. Il primo `#` nella forma scelta viene sostituito con il numero.\n\nExample: Forme plurali\n```js\n(1).pluralize('no items', '# item', '# items', '# items');  // 1 item\n(7).pluralize('no items,# item,# items,# items');          // 7 items\n```\n\n### num.padLeft(max, [c])\n\nType: `method`\n\nRiempie il numero a sinistra con zeri. Number.padRight() riempie a destra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La lunghezza del risultato. |\n| `c` | `String` | no | `'0'` | Il carattere di riempimento. |\n\nReturns: `String` Il numero riempito.\n\nIl numero viene convertito in stringa e riempito fino a `max` caratteri con `c` (`0` per impostazione predefinita). `num.padRight(max, [c])` riempie a destra.\n\nExample: Riempimento con zeri\n```js\n(5).padLeft(3);       // 005\n(7).padLeft(4, ' ');  // '   7'\n(5).padRight(3);      // 500\n```\n\n### num.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` | yes |  | Il numero di decimali. |\n\nReturns: `Number` Il numero arrotondato.\n\nL'arrotondamento usa la notazione esponenziale, quindi valori come `1.005` vengono arrotondati correttamente a `1.01`. `num.floor(decimals)` arrotonda invece per difetto a un numero di decimali (`(1.239).floor(2)` è `1.23`).\n\nExample: Arrotondare\n```js\n(1.005).round(2);  // 1.01\n(2.5).round(0);    // 3\n(1.239).floor(2);  // 1.23\n```\n\n### num.fixed(decimals)\n\nType: `method`\n\nArrotonda il numero con toFixed() e restituisce un numero, non una stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Il numero di decimali. |\n\nReturns: `Number`\n\nExample: Fixed\n```js\n(1.236).fixed(2);  // 1.24 (a number)\n```\n\n### num.between(condition, [otherwise])\n\nType: `method`\n\nRestituisce il valore del primo intervallo che contiene il numero.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Intervalli come chiavi, risultati come valori. |\n| `otherwise` | `Any` | no |  | Il risultato quando nessun intervallo corrisponde. |\n\nReturns: `Any` Il valore dell'intervallo corrispondente o `otherwise`.\n\n`condition` è un oggetto le cui chiavi sono intervalli: `'1-3'` (da 1 a 3, entrambi inclusi), `'7-'` (7 e oltre) o `'-5'` (5 e meno). Le chiavi vengono verificate in ordine e viene restituito il valore della prima chiave corrispondente. Quando nessun intervallo corrisponde, viene restituito `otherwise`.\n\nExample: Valutare un punteggio\n```js\nvar score = 5;\nscore.between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }, 'unknown');\n// medium\n```\n\n### num.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAggiunge un'imposta al numero, o la rimuove da un prezzo che la include.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | L'aliquota in percentuale. |\n| `decimals` | `Number` | no | `2` | Il numero di decimali. |\n| `includedVAT` | `Boolean` | no | `false` | Il numero include già l'imposta. |\n\nReturns: `Number`\n\n`Number.TAX()` è lo stesso metodo. Senza `includedVAT` il risultato è il numero aumentato di `percentage`. Con `includedVAT` impostato a `true` il numero è un prezzo che include già l'imposta, e il risultato è il prezzo senza imposta. Il risultato viene arrotondato a `decimals` (2 per impostazione predefinita). Puoi passare il booleano come secondo argomento: `VAT(20, true)`.\n\nExample: Prezzi con IVA\n```js\n(100).VAT(20);        // 120\n(120).VAT(20, true);  // 100\n(99.99).TAX(10, 0);   // 110\n```\n\n### num.discount(percentage, [decimals])\n\nType: `method`\n\nRiduce il numero di una 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`\n\nIl risultato viene arrotondato per difetto a `decimals` (2 per impostazione predefinita).\n\nExample: Sconto\n```js\n(100).discount(15);    // 85\n(19.99).discount(10);  // 17.99\n```\n\n### num.filesize([decimals], [type])\n\nType: `method`\n\nFormatta un numero di byte come dimensione leggibile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Il numero di decimali. |\n| `type` | `String` | no |  | `bytes`, `KB`, `MB`, `GB` o `TB`. |\n\nReturns: `String` La dimensione con la sua unità.\n\nSenza `type` viene scelta l'unità più grande adatta: `bytes`, `KB`, `MB`, `GB` o `TB` (1 KB è 1024 byte). Con `type` il valore viene convertito in quell'unità. Senza `decimals` il valore ha fino a due decimali e `.00` viene rimosso; con `decimals` viene formattato con `Number.format(decimals)`. Gli argomenti possono essere passati in qualsiasi ordine.\n\nExample: Dimensioni dei file\n```js\n(500).filesize();          // 500 bytes\n(1536000).filesize();      // 1.46 MB\n(5000000).filesize(1, 'MB'); // 4.7 MB\n```\n\n### num.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormatta il numero come importo con un formattatore di valuta registrato in DEF.currencies.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | La chiave in `DEF.currencies`. |\n| `a, b, c` | `Any` | no |  | Argomenti aggiuntivi per il formattatore. |\n\nReturns: `String` L'importo formattato.\n\nIl formattatore è la funzione `DEF.currencies[currency]` (o `DEF.currencies.default` senza `currency`). Riceve il numero e gli argomenti `a`, `b` e `c` e restituisce il testo. Quando non esiste un formattatore per la valuta, il risultato è `num.format(2)`. Registra i formattatori all'avvio, per esempio in un file di definizione.\n\nExample: Registrare e usare una valuta\n```js\n// /definitions/currencies.js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2, ' ', ',') + ' €';\n};\n\n(1234.5).currency('eur');  // 1 234,50 €\n(10).currency('usd');      // 10.00 (no formatter)\n```\n\n### date.add(type, [value])\n\nType: `method`\n\nRestituisce una nuova data spostata di una quantità di tempo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | L'unità, una stringa con valore e unità, oppure millisecondi. |\n| `value` | `Number` | no |  | La quantità, negativa per il passato. |\n\nReturns: `Date` Una nuova data.\n\nLa data originale non viene modificata. Passa l'unità e il valore (`add('minutes', 30)`), una stringa con entrambi (`add('30 minutes')`, `add('-2 hours')`) oppure un numero di millisecondi (`add(5000)`).\n\nUnità: `s`, `ss`, `sec`, `second`, `seconds`; `m`, `mm`, `min`, `minute`, `minutes`; `h`, `hh`, `hour`, `hours`; `d`, `dd`, `day`, `days`; `w`, `ww`, `week`, `weeks`; `M`, `MM`, `month`, `months`; `y`, `yyyy`, `year`, `years`. Le unità operano sulle parti UTC della data. L'aggiunta di mesi alla fine di un mese segue JavaScript: 31 gennaio più un mese è il 2 marzo in un anno bisestile e il 3 marzo altrimenti.\n\nExample: Spostare date\n```js\nvar now = new Date();\nnow.add('1 day');\nnow.add('minutes', 30);\nnow.add('-2 hours');\nnow.add(5000);  // + 5 seconds\n```\n\n### date.diff([date], type)\n\nType: `method`\n\nRestituisce la differenza tra due date in secondi, minuti, ore o giorni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String|Number` | no | `now` | La data con cui confrontare. |\n| `type` | `String` | yes |  | L'unità del risultato. |\n\nReturns: `Number` La differenza nell'unità.\n\nIl risultato è `this - date` nell'unità indicata, arrotondato per eccesso, quindi è positivo quando `this` è successiva. `date` può essere una Date, una stringa che `Date.parse()` comprende oppure un numero di millisecondi. Con un solo argomento la data viene confrontata con l'ora corrente. Unità: `s` / `ss` / `second` / `seconds`, `m` / `mm` / `minute` / `minutes`, `h` / `hh` / `hour` / `hours`, `d` / `dd` / `day` / `days`. Un'unità sconosciuta restituisce `NaN`.\n\nExample: Differenze\n```js\nvar created = new Date('2024-01-30T00:00:00Z');\nvar end = new Date('2024-01-31T10:00:00Z');\nend.diff(created, 'hours');  // 34\nend.diff('2024-01-01T00:00:00Z', 'days'); // 31\ncreated.diff('seconds');     // negative: created is in the past\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormatta la data secondo un pattern; senza pattern restituisce una stringa ISO in UTC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Il pattern. |\n| `resource` | `String` | no |  | La risorsa usata per i nomi di mesi e giorni. |\n\nReturns: `String` La data formattata.\n\nSenza `format` il risultato è `yyyy-MM-ddTHH:mm:ss.SSSZ` in UTC. Con `format` le parti vengono scritte nel fuso orario del server (UTC a meno che la chiave di configurazione `$timezone` non dica altrimenti):\n\n- `yyyy`, `yy` anno; `MM`, `M` numero del mese; `MMMM` nome del mese, `MMM` le sue prime tre lettere,\n- `dd`, `d` giorno; `dddd` nome del giorno, `ddd` le sue prime due lettere in maiuscolo,\n- `HH`, `H` ore (0-23); `mm`, `m` minuti; `ss`, `s` secondi,\n- `ww`, `w` numero della settimana ISO; `a` `AM` o `PM`.\n\nSono accettati anche `YYYY`, `YY`, `DD`, `D`, `DDDD`, `DDD` in maiuscolo e `hh`, `h` in minuscolo. I nomi di mesi e giorni sono in inglese; con `resource` vengono tradotti con il file di risorse con quel nome. I formati compilati vengono messi in cache, quindi la formattazione è veloce.\n\nExample: Formattare date\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.format();                      // 2024-01-31T10:00:00.000Z\nd.format('yyyy-MM-dd HH:mm');    // 2024-01-31 10:00\nd.format('dd.MM.yy');            // 31.01.24\nd.format('dddd, d. MMMM yyyy');  // Wednesday, 31. January 2024\nd.format('MMMM', 'sk');          // the month name from sk.resource\n```\n\n### date.extend(text)\n\nType: `method`\n\nRestituisce una nuova data con le parti della data o dell'ora sostituite da un testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Una data, un orario o entrambi. |\n\nReturns: `Date` Una nuova data.\n\nIl testo può contenere una data `yyyy-MM-dd` o `d.M.yyyy` e un orario `HH:mm` o `HH:mm:ss`. Vengono sostituite solo le parti trovate nel testo; le altre vengono prese dalla data originale. Anno, mese e giorno vengono impostati uno dopo l'altro, quindi quando il giorno della data originale non esiste nel nuovo mese la data passa al mese successivo (31 gennaio esteso con `2025-02-10` dà 10 marzo 2025). I valori sono in UTC.\n\nExample: Cambiare parti\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.extend('12:30');              // 2024-01-31T12:30:00.000Z\nd.extend('2025-03-04');         // 2025-03-04T10:00:00.000Z\nd.extend('1.3.2020 08:00');     // 2020-03-01T08:00:00.000Z\n```\n\n### date.toUTC([ticks])\n\nType: `method`\n\nSposta una data locale in UTC tramite l'offset del fuso orario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Restituire millisecondi. |\n\nReturns: `Date|Number`\n\nIl risultato è la data più l'offset del fuso orario del server. Con `ticks` impostato a `true` il risultato è il numero di millisecondi invece di una Date. Su un server in UTC (il valore predefinito) la data non cambia.\n\nExample: In UTC\n```js\nvar utc = new Date().toUTC();\nvar ms = new Date().toUTC(true);\n```\n\n### date.setTimeZone(timezone)\n\nType: `method`\n\nRestituisce una nuova data che mostra lo stesso istante in un altro fuso orario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | Un nome di fuso orario IANA. |\n\nReturns: `Date` Una nuova data.\n\nLe parti del risultato (ore, giorno, ...) lette nel fuso orario del server corrispondono all'ora locale di `timezone` in quell'istante, quindi `format()` stampa l'ora locale di quel fuso. `timezone` è un nome IANA come `Europe/Bratislava` o `America/New_York`.\n\nExample: Mostrare l'ora locale\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.setTimeZone('Europe/Bratislava').format('HH:mm');  // 11:00\n```\n\n### arr.findItem(cb, [value])\n\nType: `method`\n\nRestituisce il primo elemento che corrisponde, oppure null.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Una funzione di test, un nome di proprietà o un valore. |\n| `value` | `Any` | no |  | Il valore della proprietà. |\n\nReturns: `Object` L'elemento o `null`.\n\nPassa una funzione `(item, index)`, un nome di proprietà e un valore (`('id', 5)` confronta `item.id === 5`), oppure un singolo valore che viene confrontato con `===`.\n\nExample: Trovare un elemento\n```js\nvar users = [{ id: 1, name: 'Peter' }, { id: 2, name: 'Anna' }];\nusers.findItem('id', 2);                  // { id: 2, name: 'Anna' }\nusers.findItem(u => u.name === 'Peter');  // { id: 1, name: 'Peter' }\nusers.findItem('id', 9);                  // null\n```\n\n### arr.findAll(cb, [value])\n\nType: `method`\n\nRestituisce tutti gli elementi che corrispondono.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Una funzione di test, un nome di proprietà o un valore. |\n| `value` | `Any` | no |  | Il valore della proprietà. |\n\nReturns: `Array` Gli elementi corrispondenti.\n\nPassa una funzione `(item, index)`, un nome di proprietà e un valore (`('id', 5)` confronta `item.id === 5`), oppure un singolo valore che viene confrontato con `===`. Il risultato è un nuovo array; l'array originale non viene modificato.\n\nExample: Filtrare\n```js\nvar items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }];\nitems.findAll('type', 'a').length;  // 2\n```\n\n### arr.findIndex(cb, [value])\n\nType: `method`\n\nRestituisce l'indice del primo elemento che corrisponde, oppure -1.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Una funzione di test, un nome di proprietà o un valore. |\n| `value` | `Any` | no |  | Il valore della proprietà. |\n\nReturns: `Number` L'indice o `-1`.\n\nPassa una funzione `(item, index)`, un nome di proprietà e un valore (`('id', 5)` confronta `item.id === 5`), oppure un singolo valore che viene confrontato con `===`. Total.js sostituisce il `findIndex()` nativo con questa versione (con una funzione si comporta come quello nativo); `arr.TfindIndex()` è lo stesso metodo.\n\nExample: Indice di un elemento\n```js\nvar users = [{ id: 1 }, { id: 2 }];\nvar index = users.findIndex('id', 2);  // 1\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### arr.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 di test o un nome di proprietà. |\n| `value` | `Any` | yes |  | Il valore della proprietà (passa `undefined` con una funzione). |\n| `path` | `String` | yes |  | La proprietà da restituire. |\n| `def` | `Any` | no |  | Il valore predefinito. |\n\nReturns: `Any`\n\nL'elemento viene trovato come in `Array.findItem()`. Il risultato è `item[path]`, oppure `def` quando nessun elemento corrisponde o la proprietà è `null` / `undefined`.\n\nExample: Leggere una proprietà\n```js\nvar users = [{ id: 1, name: 'Peter' }];\nusers.findValue('id', 1, 'name');          // Peter\nusers.findValue('id', 9, 'name', 'guest');  // guest\n```\n\n### arr.remove(cb, [value])\n\nType: `method`\n\nRestituisce un nuovo array senza gli elementi che corrispondono.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Any` | yes |  | Una funzione di test, un nome di proprietà o un valore. |\n| `value` | `Any` | no |  | Il valore della proprietà. |\n\nReturns: `Array` Un nuovo array senza gli elementi corrispondenti.\n\nPassa una funzione `(item, index)`, un nome di proprietà e un valore (`('id', 5)` confronta `item.id === 5`), oppure un singolo valore che viene confrontato con `===`. L'array originale non viene modificato, quindi assegna il risultato.\n\nExample: Rimuovere elementi\n```js\nvar users = [{ id: 1 }, { id: 2 }, { id: 3 }];\nusers = users.remove('id', 1);       // [{ id: 2 }, { id: 3 }]\nvar nums = [1, 2, 3, 2].remove(2);   // [1, 3]\n```\n\n### arr.quicksort([sort], [desc])\n\nType: `method`\n\nOrdina l'array sul posto in base a una o più proprietà.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Proprietà in base a cui ordinare, oppure `true` per valori semplici in ordine decrescente. |\n| `desc` | `Boolean` | no | `false` | Ordine decrescente per `sort`. |\n\nReturns: `Array` Lo stesso array, ordinato.\n\n`sort` è un elenco di nomi di proprietà separati da virgole, ognuno eventualmente con `_asc` o `_desc` (`'name'`, `'price_desc'`, `'group,date_desc'`). Sono supportate le proprietà annidate con i punti (`'user.name'`). Il tipo di ogni colonna (stringa, numero, booleano o Date) viene rilevato dal primo valore non null la prima volta che si usa un'espressione di ordinamento, e viene mantenuto per gli ordinamenti successivi con la stessa espressione; le stringhe vengono confrontate tenendo conto dei segni diacritici. Passare `true` (o `2`) come secondo argomento ordina una singola proprietà in ordine decrescente.\n\nSenza `sort` l'array di valori semplici viene ordinato in modo crescente; `quicksort(true)` lo ordina in modo decrescente. Il metodo restituisce lo stesso array.\n\nExample: Ordinare oggetti\n```js\nvar products = [{ name: 'B', price: 10 }, { name: 'A', price: 20 }];\nproducts.quicksort('name');        // A, B\nproducts.quicksort('price_desc');  // 20, 10\nproducts.quicksort('name', true);  // B, A\n[3, 1, 2].quicksort();             // [1, 2, 3]\n```\n\n### arr.take(count)\n\nType: `method`\n\nRestituisce i primi count elementi come nuovo array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Il numero di elementi. |\n\nReturns: `Array`\n\nExample: Take\n```js\n[1, 2, 3, 4].take(2);  // [1, 2]\n```\n\n### arr.skip(count)\n\nType: `method`\n\nRestituisce gli elementi dopo i primi count elementi come nuovo array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Il numero di elementi da saltare. |\n\nReturns: `Array`\n\nCombinalo con `take()` per la paginazione.\n\nExample: Paginazione\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### arr.first([def])\n\nType: `method`\n\nRestituisce il primo elemento, oppure un valore predefinito per un array vuoto. Array.last() restituisce l'ultimo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Any` | no |  | Il valore per un array vuoto. |\n\nReturns: `Any`\n\n`arr.last([def])` restituisce l'ultimo elemento o `def`.\n\nExample: Primo e ultimo\n```js\n[1, 2].first();     // 1\n[].first('none');   // none\n[1, 2].last();      // 2\n```\n\n### arr.group(name)\n\nType: `method`\n\nRaggruppa gli elementi in base a una proprietà.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La proprietà per cui raggruppare. |\n\nReturns: `Array` Gruppi `{ name, items }`.\n\nRestituisce un array di `{ name, items }` ordinato per `name`. Il valore della proprietà viene convertito in stringa; gli elementi senza la proprietà finiscono in un gruppo con nome vuoto.\n\nExample: Raggruppare\n```js\nvar items = [{ type: 'x', id: 1 }, { type: 'y', id: 2 }, { type: 'x', id: 3 }];\nitems.group('type');\n// [{ name: 'x', items: [...2 items] }, { name: 'y', items: [...1 item] }]\n```\n\n### arr.trim()\n\nType: `method`\n\nRipulisce le stringhe dagli spazi e restituisce un nuovo array senza valori vuoti.\n\nReturns: `Array`\n\nLe stringhe nell'array originale vengono ripulite sul posto. Il risultato contiene solo elementi truthy, quindi stringhe vuote, `null`, `undefined`, `0` e `false` vengono esclusi.\n\nExample: Pulire un elenco\n```js\n' a , ,b'.split(',').trim();  // ['a', 'b']\n```\n\n### arr.random([item])\n\nType: `method`\n\nMescola l'array sul posto, 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|Any`\n\nSenza argomenti l'array viene mescolato (Fisher-Yates) e restituito. Con `item` impostato a `true` viene restituito un elemento casuale e l'array non viene modificato.\n\nExample: Casuale\n```js\nvar colors = ['red', 'green', 'blue'];\ncolors.random(true);  // one color\ncolors.random();      // the shuffled array\n```\n\n### arr.wait(onItem, [callback], [thread])\n\nType: `method`\n\nElabora gli elementi uno per uno con una funzione asincrona.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | `function(item, next)`. |\n| `callback` | `Function` | no |  | Chiamata quando tutti gli elementi sono stati elaborati. |\n| `thread` | `Number|Boolean` | no | `1` | Elementi in parallelo, oppure `true` per rimuovere gli elementi man mano che vengono elaborati. |\n\nReturns: `Array` L'array.\n\n`onItem(item, next)` viene chiamata per ogni elemento; chiama `next()` per continuare con l'elemento successivo. `callback()` viene chiamata quando tutti gli elementi sono stati elaborati. `thread` imposta quanti elementi vengono elaborati contemporaneamente (1 per impostazione predefinita). Con `thread` impostato a `true` gli elementi vengono rimossi dall'array con `shift()` man mano che vengono elaborati. Chiama `next('cancel')` per fermarti: viene allora chiamata `callback('cancel')`.\n\nExample: Elaborare in sequenza\n```js\nvar ids = [1, 2, 3];\nids.wait(function(id, next) {\n\tFUNC.removeuser(id, next);\n}, function() {\n\tconsole.log('All removed');\n});\n```\n\nExample: Due alla volta\n```js\nurls.wait(function(url, next) {\n\tREQUEST({ url: url, callback: () => next() });\n}, () => console.log('done'), 2);\n```\n\n### arr.async([thread], [callback])\n\nType: `method`\n\nEsegue un array di funzioni una dopo l'altra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | Quante funzioni vengono eseguite contemporaneamente. |\n| `callback` | `Function` | no |  | Chiamata alla fine. |\n\nReturns: `Array` L'array.\n\nOgni elemento è una funzione `(next)`; chiama `next()` quando termina. Le funzioni vengono rimosse dall'array man mano che vengono eseguite, quindi alla fine l'array è vuoto. `thread` imposta quante funzioni partono contemporaneamente (1 per impostazione predefinita). `callback()` viene chiamata quando tutte le funzioni sono terminate, oppure `callback('cancel')` quando una chiama `next('cancel')`.\n\nExample: Eseguire attività\n```js\nvar tasks = [];\ntasks.push(function(next) {\n\tconsole.log('first');\n\tnext();\n});\ntasks.push(function(next) {\n\tsetTimeout(next, 100);\n});\ntasks.async(function() {\n\tconsole.log('done');\n});\n```\n\n### arr.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 |  | `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Chiamata alla fine. |\n\nReturns: `Array` L'array.\n\n`fn(items, next, beg, end)` riceve il blocco successivo e l'indice di inizio e di fine; chiama `next()` per continuare. `callback()` viene chiamata dopo l'ultimo blocco.\n\nExample: Inserire a lotti\n```js\nrows.limit(100, function(items, next) {\n\tFUNC.importrows(items, next);\n}, function() {\n\tconsole.log('Imported');\n});\n```\n","entries":[{"type":"method","name":"String.format()","signature":"str.format(arg0, [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"str.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"str.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"str.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"str.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"str.toName()","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"str.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"str.decode()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"str.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"str.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"str.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.toKeywords()","signature":"str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"str.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"str.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"str.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"str.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"str.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"str.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"str.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"str.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseContext()","signature":"str.parseContext()","since":"0.0.17","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"str.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"str.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseEnv()","signature":"str.parseEnv()","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"str.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"str.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"str.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"str.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"str.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"str.isNumber([isDecimal])","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"str.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"str.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"str.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"str.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"str.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"str.sign([key], [check])","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"str.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"str.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"str.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"num.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"num.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"num.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"num.round(precision)","since":"","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"num.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"num.between(condition, [otherwise])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"num.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"num.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"num.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"num.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"date.extend(text)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"arr.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"arr.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"arr.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"arr.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"arr.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"arr.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"arr.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"arr.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"arr.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.group()","signature":"arr.group(name)","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"arr.trim()","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"arr.random([item])","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"arr.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"arr.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"arr.limit(max, fn, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JacXWy2qt61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/prototypes/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Prototypy","summary":"Každá metóda, ktorú Total.js pridáva do String, Number, Date a Array.prototype.","markdown":"---\ntitle: Prototypy\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/prototypes/\nupdated: 2026-11-18T16:57:14.575Z\n---\n\n# Prototypy\n\n> Každá metóda, ktorú Total.js pridáva do String, Number, Date a Array.prototype.\n\nMetódy, ktoré Total.js 5 pridáva do vstavaných prototypov `String`, `Number`, `Date` a `Array`. Po načítaní frameworku sú dostupné všade. Návod [Prototypy](../../guides/prototypes/) ukazuje na príkladoch, ako ich spolu používať; táto stránka je presná referencia.\n\n## API\n\n### str.format(arg0, [arg1], [...])\n\nType: `method`\n\nNahradí číslované zástupné symboly {0}, {1}, ... argumentmi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0...argN` | `Any` | yes |  | Hodnoty pre `{0}`, `{1}` atď. |\n\nReturns: `String` Nový reťazec.\n\nKaždé `{n}` sa nahradí argumentom na indexe `n`. Zástupný symbol, ktorého argument je `null` alebo `undefined`, sa zmení na prázdny reťazec. V zátvorkách sú povolené iba čísla; pre pomenované kľúče použi `String.args()`.\n\nExample: Číslované zástupné symboly\n```js\n'Hello {0}, you have {1} messages.'.format('Peter', 5);\n// Hello Peter, you have 5 messages.\n```\n\n### str.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` | `String|Function` | no |  | `html`, `json`, funkcia `(value, key)` alebo akýkoľvek iný reťazec pre URL kódovanie. |\n| `def` | `String` | no |  | Text pre kľúče bez hodnoty. |\n\nReturns: `String` Nový reťazec.\n\n`String.arg()` je tá istá metóda. Zástupný symbol je kľúč v jednoduchých alebo dvojitých zložených zátvorkách; medzery vnútri zátvoriek sa orežú. Kľúče sa čítajú priamo z `obj` (bez vnorených ciest).\n\n`encode` mení výstup každej hodnoty: `'html'` ju zakóduje pomocou `String.encode()`, `'json'` zapíše `JSON.stringify(value)`, akýkoľvek iný pravdivý reťazec použije `encodeURIComponent()` a funkcia `(value, key)` vráti samotný text. Keď je `encode` reťazec, nahrádza aj `def`: s `'html'` alebo reťazcom pre URL kódovanie sa kľúč bez hodnoty zmení na text `encode`; s `'json'` sa zmení na `undefined`. Bez `encode` zostane kľúč bez hodnoty tak, ako je, alebo sa nahradí `def`, keď ho odovzdáš.\n\nExample: Pomenované zástupné symboly\n```js\nvar tpl = 'Hello {name}, your order {{ id }} is ready.';\ntpl.args({ name: 'Peter', id: 'A100' });\n// Hello Peter, your order A100 is ready.\n\n'<b>{name}</b>'.args({ name: '<script>' }, 'html');\n// <b>&lt;script&gt;</b>\n```\n\n### str.slug([max])\n\nType: `method`\n\nVytvorí z textu slug vhodný do URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | Maximálna dĺžka slugu. |\n\nReturns: `String` Slug.\n\nText sa oreže, prevedie na malé písmená a odstránia sa diakritické znamienka (`toASCII()`). Písmená, číslice a `_` sa zachovajú; medzery a znaky `!\"#$%&'()*+,-./` sa zmenia na jedno `-`; ostatné znaky sa zahodia. Koncové `-` sa odstráni a výsledok má najviac `max` znakov.\n\nKeď text obsahuje znak bez ASCII podoby, ktorého kód je vyšší ako 540 (napríklad písmená cyriliky, `€` alebo emoji), celý text sa nespracuje písmeno po písmene: metóda potom vráti krátky identifikátor založený na hashi textu, takže výsledok je stále stabilný a bezpečný pre URL.\n\nExample: Slug z nadpisu\n```js\n' Hello World! Čaute 123 '.slug();\n// hello-world-caute-123\n\n'A very long article title'.slug(10);\n// a-very-lon\n```\n\n### str.max(length, [chars])\n\nType: `method`\n\nSkráti text na maximálnu dĺžku a pridá výpustku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Maximálna dĺžka výsledku. |\n| `chars` | `String` | no | `'...'` | Text pripojený ku skrátenému reťazcu. |\n\nReturns: `String` Text, v prípade potreby skrátený.\n\nKeď je text dlhší ako `length`, oreže sa tak, aby mal výsledok vrátane `chars` presne `length` znakov. Kratší text sa vráti bez zmeny.\n\nExample: Skrátenie\n```js\n'Hello world'.max(8);       // Hello...\n'Hello world'.max(8, '…');  // Hello w…\n```\n\n### str.capitalize([first])\n\nType: `method`\n\nZmení prvé písmeno každého slova, alebo iba textu, na veľké.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Zmeniť na veľký iba prvý znak. |\n\nReturns: `String` Nový reťazec.\n\nText sa najprv prevedie na malé písmená. Bez argumentov sa každé písmeno po medzere, tabulátore alebo novom riadku zmení na veľké. Keď je `first` nastavené na `true`, na veľký sa zmení iba prvý znak a zvyšok zostane malými písmenami.\n\nExample: Veľké začiatočné písmená\n```js\n'hello WORLD'.capitalize();      // Hello World\n'hello WORLD'.capitalize(true);  // Hello world\n```\n\n### str.toName()\n\nType: `method`\n\nVyčistí meno osoby: odstráni číslice a symboly, nadbytočné medzery a zmení začiatočné písmená slov na veľké.\n\nReturns: `String` Vyčistené meno.\n\nZachovajú sa iba ASCII písmená, znaky s kódom nad 127 (písmená s diakritikou) a medzery. Opakované medzery sa zredukujú na jednu, koncové medzery sa odstránia (úvodné medzery sa zmenia na jednu medzeru) a prvé písmeno každého slova sa zmení na veľké. Zvyšok každého slova zostane tak, ako je.\n\nExample: Vyčistenie mena\n```js\n'peter   sirka 12'.toName();\n// Peter Sirka\n```\n\n### str.encode()\n\nType: `method`\n\nZakóduje špeciálne HTML znaky.\n\nReturns: `String` Zakódovaný text.\n\n`String.safehtml()` je tá istá metóda. Znaky `<`, `>`, `\"`, `'` a `&` sa nahradia za `&lt;`, `&gt;`, `&quot;`, `&apos;` a `&amp;`. Použi ju predtým, ako vložíš text od používateľa do HTML.\n\nExample: Zakódovanie vstupu používateľa\n```js\n'<a href=\"x\">Tom & Jerry</a>'.encode();\n// &lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;/a&gt;\n```\n\n### str.decode()\n\nType: `method`\n\nDekóduje HTML entity späť na znaky.\n\nReturns: `String` Dekódovaný text.\n\nPomenované entity (`&lt;`, `&amp;`, `&quot;`, ...) a číselné entity (`&#65;`, `&#x41;`) sa nahradia ich znakmi. Neznáme pomenované entity zostanú bez zmeny.\n\nExample: Dekódovanie\n```js\n'&lt;b&gt;Tom &amp; Jerry&#33;&lt;/b&gt;'.decode();\n// <b>Tom & Jerry!</b>\n```\n\n### str.removeTags()\n\nType: `method`\n\nOdstráni z textu HTML tagy.\n\nReturns: `String` Text bez tagov.\n\nKaždý tag `<...>` (otvárací aj zatvárací) sa odstráni; text medzi tagmi zostane. Výsledok nie je HTML-zakódovaný, takže ho zakóduj cez `String.encode()`, keď ho zapisuješ späť do HTML.\n\nExample: Odstránenie tagov\n```js\n'<p><b>Hi</b> there</p>'.removeTags();\n// Hi there\n```\n\n### str.padLeft(max, [c])\n\nType: `method`\n\nDoplní text zľava na danú dĺžku. String.padRight() dopĺňa sprava.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Dĺžka výsledku. |\n| `c` | `String` | no | `' '` | Znak na doplnenie. |\n\nReturns: `String` Doplnený text.\n\nZnaky `c` sa pridávajú, kým text nemá `max` znakov; dlhší text sa vráti bez zmeny. `str.padRight(max, [c])` funguje rovnako na pravej strane. Obe sú definované iba vtedy, keď ich runtime ešte nemá.\n\nExample: Doplnenie\n```js\n'5'.padLeft(3, '0');   // 005\n'a'.padRight(3, '-');  // a--\n```\n\n### str.toASCII()\n\nType: `method`\n\nNahradí písmená s diakritikou ich ASCII podobou.\n\nReturns: `String` Text bez diakritiky.\n\nPísmená ako `č`, `á` alebo `ü` sa nahradia za `c`, `a` a `u`. Znaky bez ASCII podoby zostanú bez zmeny.\n\nExample: Odstránenie diakritiky\n```js\n'Čučoriedka'.toASCII();\n// Cucoriedka\n```\n\n### str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nVyberie z textu kľúčové slová, najčastejšie ako prvé.\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ť slová na 80 % ich dĺžky. |\n| `max_count` | `Number` | no | `200` | Maximálny počet slov na prečítanie. |\n| `max_length` | `Number` | no | `20` | Maximálna dĺžka kľúčového slova. |\n| `min_length` | `Number` | no | `2` | Minimálna dĺžka kľúčového slova. |\n\nReturns: `Array` Jedinečné kľúčové slová zoradené podľa frekvencie.\n\nText sa prevedie na malé písmená a rozdelí na slová; z každého slova sa odstránia znaky, ktoré nie sú písmená ani číslice. S `forsearch` (predvolene) sa odstráni diakritika a `y` sa zmení na `i`, čo robí porovnávanie tolerantným. `alternative` ponechá z dlhších slov iba prvých 80 % (jednoduchý kmeň). Slová kratšie ako `min_length` alebo dlhšie ako `max_length` sa preskočia a prečíta sa najviac `max_count` slov. Jedinečné slová sa vrátia zoradené podľa toho, ako často sa vyskytujú.\n\nPre jeden normalizovaný vyhľadávací reťazec použi `str.toSearch()`: prevedie text na malé písmená, odstráni diakritiku a symboly, nahradí `y` za `i` a vynechá opakované písmená (`hello` sa zmení na `helo`).\n\nExample: Kľúčové slová pre vyhľadávací index\n```js\n'Total.js is a great framework, great!'.toKeywords();\n// ['great', 'totaljs', 'is', 'framework']\n\n'Čaute Hello'.toSearch();\n// caute helo\n```\n\n### str.pluralize(zero, one, few, other)\n\nType: `method`\n\nPrevedie text na číslo a vyberie tvar množného čísla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Text pre 0 alebo všetky štyri tvary oddelené čiarkami. |\n| `one` | `String` | no |  | Text pre 1. |\n| `few` | `String` | no |  | Text pre 2 až 4. |\n| `other` | `String` | no |  | Text pre ostatné čísla. |\n\nReturns: `String` Vybraný tvar.\n\nText sa prevedie cez `parseInt()` a výsledok sa odovzdá do `Number.pluralize()`.\n\nExample: Množné číslo z reťazca\n```js\n'3'.pluralize('no items', '# item', '# items', '# items');\n// 3 items\n```\n\n### str.parseInt([def])\n\nType: `method`\n\nPrevedie text na číslo, s predvolenou hodnotou pre neplatný text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Hodnota pre text, ktorý nie je číslo. |\n\nReturns: `Number` Číslo alebo predvolená hodnota.\n\nText sa oreže a prevedie unárnym `+`, takže `'10'` je `10`, `'1.5'` je `1.5` a `'0x10'` je `16`. Keď text nie je číslo, vráti sa `def` (`0`, keď ho vynecháš).\n\n`str.parseInt2([def])` namiesto toho nájde prvé celé číslo kdekoľvek v texte (`'abc 123'` dá `123`); `str.parseFloat2([def])` robí to isté pre desatinné číslo a prijíma `,` ako desatinný oddeľovač.\n\nExample: Čítanie čísel\n```js\n'10'.parseInt();        // 10\n'abc'.parseInt(5);      // 5\n'Total: 123 EUR'.parseInt2(); // 123\n'x 1,5 y'.parseFloat2();      // 1.5\n```\n\n### str.parseFloat([def])\n\nType: `method`\n\nPrevedie text na desatinné číslo; čiarka je prijatá ako desatinný oddeľovač.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Hodnota pre text, ktorý nie je číslo. |\n\nReturns: `Number` Číslo alebo predvolená hodnota.\n\nText sa oreže, prvá `,` sa nahradí za `.` a text sa prevedie na číslo. Keď text nie je číslo, vráti sa `def` (`0`, keď ho vynecháš).\n\nExample: Čítanie desatinných čísel\n```js\n'1,5'.parseFloat();    // 1.5\n' 2.25 '.parseFloat(); // 2.25\n'n/a'.parseFloat(-1);  // -1\n```\n\n### str.parseBoolean()\n\nType: `method`\n\nPrevedie text na boolean.\n\nReturns: `Boolean`\n\nVracia `true` pre `true`, `1` a `on` (bez ohľadu na veľkosť písmen) a `false` pre všetko ostatné.\n\nExample: Čítanie príznaku\n```js\n'on'.parseBoolean();    // true\n'TRUE'.parseBoolean();  // true\n'no'.parseBoolean();    // false\n```\n\n### str.parseDate([format])\n\nType: `method`\n\nPrevedie text na Date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Formát ako `dd/MM/yyyy HH:mm`. |\n\nReturns: `Date` Spracovaný dátum.\n\nBez `format` metóda rozumie:\n\n- JSON dátumom (`2024-05-01T12:30:00.000Z`),\n- `yyyy-MM-dd`, `yyyy-MM-dd HH:mm`, `yyyy-MM-dd HH:mm:ss` a `yyyy-MM-ddTHH:mm:ss.SSS`,\n- `d.M.yyyy` s voliteľným časom (`1.5.2024 08:00`),\n- čomukoľvek inému, čo prijme `new Date(text)`.\n\nDátum a čas týchto tvarov sa čítajú ako UTC. Chýbajúce časti dátumu sa vezmú z dnešného dňa.\n\nS `format` sa číslice textu čítajú podľa pozícií `yyyy`, `MM`, `dd`, `HH`, `mm` a `ss` vo formáte; ostatné znaky formátu iba oddeľujú časti. Časti musia byť zapísané so všetkými číslicami (`05`, nie `5`). Dvojciferný rok je v 2000-tych rokoch a `pm` v texte pridá 12 hodín.\n\nExample: Parsovanie dátumov\n```js\n'2024-05-01 12:30'.parseDate();\n// 2024-05-01T12:30:00.000Z\n\n'1.5.2024'.parseDate();\n// 2024-05-01T00:00:00.000Z\n\n'01/05/2024'.parseDate('dd/MM/yyyy');\n// 1 May 2024\n```\n\n### str.parseDateExpiration()\n\nType: `method`\n\nPrevedie relatívny čas ako \"5 minutes\" na Date v budúcnosti.\n\nReturns: `Date` Aktuálny čas plus zadané trvanie.\n\nText je zoznam dvojíc `number unit` oddelených medzerami. Každá dvojica sa pripočíta k aktuálnemu času cez `Date.add()`, takže fungujú všetky jednotky `Date.add()` (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years` a ich krátke tvary). Pre dátum v minulosti použi záporné číslo.\n\nExample: Expirácia\n```js\nvar expire = '5 minutes'.parseDateExpiration();\nvar later = '1 day 2 hours'.parseDateExpiration();\n```\n\n### str.parseJSON([date])\n\nType: `method`\n\nSparsuje JSON bez vyhodenia výnimky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | Previesť reťazce JSON dátumov na objekty Date. |\n\nReturns: `Object` Sparsovaná hodnota alebo `undefined`.\n\nVráti sparsovanú hodnotu alebo `undefined`, keď text nie je platný JSON. Keď je `date` nastavené na `true`, reťazce vo formáte JSON dátumu (`2024-01-01T10:00:00.000Z`) sa zmenia na objekty `Date`.\n\nExample: Bezpečné parsovanie\n```js\nvar obj = '{\"a\":1}'.parseJSON();          // { a: 1 }\nvar bad = '{a:1'.parseJSON();             // undefined\nvar doc = '{\"created\":\"2024-01-01T10:00:00.000Z\"}'.parseJSON(true);\ndoc.created instanceof Date;             // true\n```\n\n### str.parseCSV([delimiter])\n\nType: `method`\n\nSparsuje CSV text na pole objektov s kľúčmi stĺpcov a, b, c, ...\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | Oddeľovač stĺpcov, jeden znak. |\n\nReturns: `Array` Pole objektov.\n\nKaždý riadok sa stane objektom. Kľúče sú písmená stĺpcov: `a` pre prvý stĺpec, `b` pre druhý, ..., `z`, potom `aa`, `ab` atď. Hodnoty v dvojitých úvodzovkách môžu obsahovať oddeľovač a nové riadky; `\"\"` v úvodzovkách je escapovaná úvodzovka. Prázdne stĺpce nemajú v objekte kľúč. Hodnoty sú reťazce a neorezávajú sa. Riadok hlavičky sa vráti ako každý iný riadok.\n\nExample: Parsovanie CSV\n```js\nvar rows = 'name,age\\n\"Sirka, Peter\",40\\nAnna,'.parseCSV();\n// [{ a: 'name', b: 'age' }, { a: 'Sirka, Peter', b: '40' }, { a: 'Anna' }]\n\nvar header = rows.shift();\nfor (var row of rows)\n\tconsole.log(row.a, row.b || '-');\n```\n\n### str.parseContext()\n\nType: `method` · Since: `0.0.17`\n\nSparsuje text zložený z blokov s hlavičkou a telom.\n\nReturns: `Array` Pole objektov, jeden na blok.\n\nKaždý blok začína riadkom s aspoň 20 pomlčkami, za ním nasledujú riadky hlavičky `key: value`, ďalší riadok s aspoň 20 pomlčkami a telo. Telo končí tam, kde začína ďalší blok. Každý blok sa stane objektom s kľúčmi hlavičky (malými písmenami, hodnoty orezané) a vlastnosťou `body` s orezaným telom. Riadky hlavičky bez `:` sa ignorujú.\n\nExample: Parsovanie blokov\n```js\nvar text = [\n\t'--------------------',\n\t'Name: Hello',\n\t'Type: note',\n\t'--------------------',\n\t'Body one',\n\t'--------------------',\n\t'Name: Second',\n\t'--------------------',\n\t'Body two'\n].join('\\n');\n\ntext.parseContext();\n// [{ name: 'Hello', type: 'note', body: 'Body one' }, { name: 'Second', body: 'Body two' }]\n```\n\n### str.parseEncoded()\n\nType: `method`\n\nSparsuje URL-kódovaný text (query string alebo telo formulára) na objekt.\n\nReturns: `Object` Sparsované kľúče a hodnoty (reťazce).\n\nDvojice `key=value` sú oddelené `&`; kľúče a hodnoty sa URL-dekódujú. Toto je parser, ktorý Total.js používa pre query stringy a telá `application/x-www-form-urlencoded`.\n\nExample: Parsovanie query stringu\n```js\n'q=total.js&page=2&name=%20Peter'.parseEncoded();\n// { q: 'total.js', page: '2', name: ' Peter' }\n```\n\n### str.parseConfig([def], [onerr])\n\nType: `method`\n\nSparsuje text vo formáte konfigurácie Total.js na objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Predvolené hodnoty, ktoré sa do výsledku skopírujú ako prvé. |\n| `onerr` | `Function` | no |  | `function(err, line)` pre hodnoty, ktoré nemožno vyhodnotiť. |\n\nReturns: `Object` Sparsované hodnoty.\n\nKaždý riadok je `key : value`. Oddeľovač je prvá `:`, alebo prvé `=`, keď riadok nemá `:`; hodnota začína na druhom znaku za oddeľovačom, preto tam nechaj jednu medzeru. Prázdne riadky a riadky, ktoré začínajú `#` alebo `//`, sa preskočia. Hodnota, ktorá začína `base64 ` alebo `hex `, sa dekóduje.\n\nTyp v zátvorkách za kľúčom prevedie hodnotu: `(string)`, `(number)` (aj `float`, `double`, `currency`), `(boolean)` / `(bool)` (true, keď hodnota obsahuje `true`, `on`, `1` alebo `enabled`, bez ohľadu na veľkosť písmen), `(json)`, `(object)` / `(array)` / `(eval)` (vyhodnotí sa ako JavaScript), `(date)`, `(env)` (číta `process.env[value]`), `(config)` (číta iný konfiguračný kľúč) a `(random)` (náhodný reťazec zadanej dĺžky). Keď vyhodnotenie hodnoty zlyhá, zavolá sa `onerr(err, line)`, alebo sa bez neho vyhodí chyba.\n\nExample: Parsovanie nastavení\n```js\nvar text = 'name : Shop\\ncount (number) : 10\\nenabled (boolean) : true\\n# comment\\ntags (array) : [\\'a\\', \\'b\\']';\ntext.parseConfig();\n// { name: 'Shop', count: 10, enabled: true, tags: ['a', 'b'] }\n```\n\n### str.parseEnv()\n\nType: `method`\n\nSparsuje text vo formáte .env na objekt.\n\nReturns: `Object` Kľúče a hodnoty.\n\nKaždý riadok je `KEY=value`. Prázdne riadky a riadky, ktoré začínajú `#` alebo `//`, sa preskočia. Hodnote v jednoduchých alebo dvojitých úvodzovkách sa úvodzovky odstránia (vnútorné medzery sa zachovajú); ostatné hodnoty sa orežú. `\\n` v hodnote sa zmení na nový riadok. Všetky hodnoty sú reťazce.\n\nExample: Parsovanie .env\n```js\n'PORT=8000\\nNAME=\"My app\"\\n# comment'.parseEnv();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### str.parseUA([structured])\n\nType: `method`\n\nPrečíta operačný systém, prehliadač a typ zariadenia z hlavičky User-Agent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Vrátiť objekt namiesto textu. |\n\nReturns: `String|Object`\n\nBez argumentov je výsledkom krátky text ako `Windows Chrome`. Keď je `structured` nastavené na `true`, výsledkom je objekt `{ os, browser, device }`, kde `device` je `mobile` alebo `desktop`. Prázdny text vráti prázdny reťazec.\n\nExample: Čítanie user agenta\n```js\nvar ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Version/17.0 Mobile Safari/604.1';\nua.parseUA();      // iPhone Safari\nua.parseUA(true);  // { os: 'iPhone', browser: 'Safari', device: 'mobile' }\n```\n\n### str.isEmail()\n\nType: `method`\n\nOverí, že text je e-mailová adresa.\n\nReturns: `Boolean`\n\nTest používa regulárny výraz `email` z `DEF.validators`: písmená, číslice a `-_.+` pred `@`, doménu a doménu najvyššej úrovne s aspoň dvoma písmenami. Text so štyrmi alebo menej znakmi nie je nikdy platný.\n\nExample: Validácia\n```js\n'info@example.com'.isEmail();  // true\n'info@example'.isEmail();      // false\n```\n\n### str.isPhone()\n\nType: `method`\n\nOverí, že text je telefónne číslo.\n\nReturns: `Boolean`\n\nTest používa regulárny výraz `phone` z `DEF.validators`: voliteľné `+`, tri číslice (voliteľne v zátvorkách), tri číslice a 4 až 8 číslic, pričom každá skupina môže byť oddelená `-`, `.` alebo medzerou. Text kratší ako šesť znakov nie je nikdy platný.\n\nExample: Validácia\n```js\n'+421903123456'.isPhone();  // true\n'(123) 456-7890'.isPhone(); // true\n'12345'.isPhone();          // false\n```\n\n### str.isURL()\n\nType: `method`\n\nOverí, že text je http alebo https URL.\n\nReturns: `Boolean`\n\nText musí začínať `http://` alebo `https://` a nesmie obsahovať `,`, `{`, `}` ani `\\`. Text so siedmimi alebo menej znakmi nie je nikdy platný.\n\nExample: Validácia\n```js\n'https://www.totaljs.com'.isURL();  // true\n'www.totaljs.com'.isURL();          // false\n```\n\n### str.isUID()\n\nType: `method`\n\nOverí, že text je platný identifikátor vytvorený cez UID().\n\nReturns: `Boolean`\n\nMetóda kontroluje formát a kontrolný súčet identifikátorov vytvorených cez `UID()`, takže náhodný reťazec rovnakého tvaru sa odmietne. Na prečítanie dátumu a indexu uloženého v UID použi `str.parseUID()`, ktorá vráti `{ version, date, century, hash, index, valid }`. Pre štandardné GUID (`8-4-4-4-12` hex číslic) použi `str.isGUID()`.\n\nExample: Validácia id\n```js\nvar id = UID();\nid.isUID();       // true\n'abc'.isUID();    // false\nid.parseUID().date;  // the time the id was created\n'123e4567-e89b-12d3-a456-426614174000'.isGUID(); // true\n```\n\n### str.isNumber([isDecimal])\n\nType: `method`\n\nOverí, že text obsahuje iba číslice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `isDecimal` | `Boolean` | no | `false` | Povoliť jeden desatinný oddeľovač. |\n\nReturns: `Boolean`\n\nKaždý znak musí byť číslica. Keď je `isDecimal` nastavené na `true`, povolená je aj jedna `.` alebo `,`. Znamienko (`-`, `+`) nie je povolené a prázdny text nie je číslo.\n\nExample: Validácia\n```js\n'0123'.isNumber();      // true\n'1.5'.isNumber();       // false\n'1,5'.isNumber(true);   // true\n```\n\n### str.isJSON()\n\nType: `method`\n\nRýchlo overí, že text vyzerá ako JSON objekt, pole alebo reťazec.\n\nReturns: `Boolean`\n\nÚvodné a koncové biele znaky sa preskočia a porovná sa prvý a posledný znak: `{` s `}`, `[` s `]` alebo `\"` s `\"`. Je to `true` aj vtedy, keď text začína číslicou alebo písmenom a končí znakom menším ako `9`, napríklad `'123'` alebo `'abc1'`. Obsah sa neparsuje, preto použi `String.parseJSON()`, keď si potrebuješ byť istý.\n\nExample: Kontrola pred parsovaním\n```js\nvar body = ' {\"a\":1} ';\nif (body.isJSON())\n\tvar obj = body.parseJSON();\n```\n\n### str.isXSS()\n\nType: `method`\n\nOverí, že text obsahuje HTML tag.\n\nReturns: `Boolean`\n\nVracia `true`, keď text obsahuje `<`, za ktorým neskôr nasleduje `>`, čo je spôsob, akým regulárny výraz `xss` z `DEF.validators` rozpoznáva markup vo vstupe používateľa. `str.isSQLInjection()` funguje rovnako s výrazom `sqlinjection`: je `true` pre reťazce v úvodzovkách a pre SQL kľúčové slová `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` a `UNION` zapísané veľkými písmenami. Obe sú jednoduché filtre, nie náhrada za kódovanie výstupu a parametre dopytov.\n\nExample: Odmietnutie markupu\n```js\n'<script>alert(1)</script>'.isXSS();  // true\n'Hello'.isXSS();                      // false\n'DROP TABLE users'.isSQLInjection();   // true\n```\n\n### str.hash([type], [salt])\n\nType: `method`\n\nVráti hash textu: rýchly číselný hash alebo digest md5, sha1, sha256, sha512 či crc32.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | `md5`, `sha1`, `sha256`, `sha512`, `crc32`, `crc32unsigned` alebo `true` pre číselný hash bez znamienka. |\n| `salt` | `String` | no |  | Text pripojený pred hashovaním. |\n\nReturns: `Number|String` Číslo pre číselný hash a crc32, inak hex reťazec.\n\n`type` vyberá algoritmus: `md5`, `sha1`, `sha256`, `sha512` (hex reťazce), `crc32` (číslo so znamienkom) alebo `crc32unsigned` (číslo bez znamienka). Bez `type` metóda vráti rýchly 32-bitový číselný hash textu (so znamienkom); `hash(true)` ho vráti bez znamienka. `salt` sa pred hashovaním pripojí k textu. Číselný hash nie je kryptografický: používaj ho pre kľúče cache a podobné účely. `str.crc32([unsigned])` je dostupná aj priamo.\n\nExample: Hashe\n```js\n'hello'.hash();          // a signed 32-bit number\n'hello'.hash(true);      // the same, unsigned\n'hello'.hash('sha256');  // hex digest\n'hello'.hash('crc32unsigned');\n```\n\n### str.md5([salt])\n\nType: `method`\n\nVráti MD5 digest textu ako hex reťazec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text pripojený pred hashovaním. |\n\nReturns: `String` 32 hex znakov.\n\nText (s pripojeným `salt`) sa hashuje ako UTF-8 cez `crypto` z Node.js. MD5 je vhodné pre kontrolné súčty a kľúče cache, nie pre heslá.\n\nExample: MD5\n```js\n'a'.md5();\n// 0cc175b9c0f1b6a831c399e269772661\n```\n\n### str.sha256([salt])\n\nType: `method`\n\nVráti SHA-256 digest textu ako hex reťazec. sha1() a sha512() fungujú rovnako.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text pripojený pred hashovaním. |\n\nReturns: `String` 64 hex znakov.\n\nText (s pripojeným `salt`) sa hashuje ako UTF-8 cez `crypto` z Node.js. `str.sha1([salt])` vracia 40 hex znakov a `str.sha512([salt])` 128 hex znakov.\n\nExample: SHA digesty\n```js\nvar digest = 'password'.sha256(CONF.secret);\nvar short = 'text'.sha1();\nvar long = 'text'.sha512();\n```\n\n### str.sign([key], [check])\n\nType: `method`\n\nPodpíše text krátkym kontrolným súčtom, alebo podpis overí a odstráni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Podpisový kľúč. |\n| `check` | `Boolean` | no | `false` | Skontroluje podpis a vráti pôvodný text. |\n\nReturns: `String` Podpísaný text, pôvodný text alebo `null`.\n\n`str.sign(key)` vráti `text-checksum`, kde kontrolný súčet vznikne z textu a `key`. `signed.sign(key, true)` overí kontrolný súčet a vráti pôvodný text alebo `null`, keď podpis nesedí. Použi ho pre hodnoty, ktoré putujú cez URL a nesmú sa zmeniť, napríklad id v odkazoch. Nie je to šifrovanie: text zostáva čitateľný.\n\n`str.makeid()` vráti iba krátky kontrolný súčet textu v sústave so základom 36, praktický ako kompaktný kľúč.\n\nExample: Podpísanie id\n```js\nvar token = '123'.sign('mykey');     // 123-155hlxd\ntoken.sign('mykey', true);           // 123\n(token + 'x').sign('mykey', true);   // null\n```\n\n### str.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nZašifruje text kľúčom. String.decrypt() ho dešifruje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Šifrovací kľúč. |\n| `isUnique` | `Boolean` | no | `false` | Vytvoriť pri každom volaní iný výsledok. |\n| `secret` | `String` | no | `CONF.secret` | Tajomstvo použité v kontrolnom súčte. |\n\nReturns: `String` Zašifrovaný text.\n\nVýsledkom je reťazec z kontrolného súčtu, `-` a hex dát. Keď je `isUnique` nastavené na `true`, ten istý text dá zakaždým iný výsledok. Kontrolný súčet používa `secret` alebo konfiguračný kľúč `secret`, keď ho vynecháš.\n\n`str.decrypt(key, [secret])` vráti pôvodný text alebo `null`, keď kľúč, tajomstvo alebo dáta nesedia. Pre oba smery použi rovnaký `key` a `secret`.\n\nExample: Zašifrovanie a dešifrovanie\n```js\nvar value = 'user@example.com'.encrypt('mykey', true);\nvalue.decrypt('mykey');   // user@example.com\nvalue.decrypt('other');   // null\n```\n\n### str.encrypt_uid([key])\n\nType: `method`\n\nZašifruje identifikátor do krátkeho tokenu bezpečného pre URL. String.decrypt_uid() ho dešifruje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Kľúč. |\n\nReturns: `String` Token.\n\nPouži ho na skrytie číselných alebo textových id vo verejných URL. `key` je predvolene konfiguračný kľúč `secret`. `token.decrypt_uid([key])` vráti pôvodné id alebo `null`, keď bol token zmenený alebo je kľúč iný.\n\nExample: Skrytie id\n```js\nvar token = '123'.encrypt_uid('mykey');\ntoken.decrypt_uid('mykey');  // 123\n```\n\n### str.base64ToBuffer()\n\nType: `method`\n\nPrevedie base64 text alebo data URI na Buffer.\n\nReturns: `Buffer` Dekódované dáta.\n\nVšetko až po prvú `,` vrátane sa preskočí, takže funguje čisté base64 aj `data:...;base64,...`. Súvisiace metódy: `str.base64ToFile(filename, [callback])` zapíše dekódované dáta do súboru, `str.base64ContentType()` vráti content type data URI (`image/png`) a `str.parseDataURI()` vráti `{ type, buffer }` (alebo `null` pre text, ktorý nie je data URI).\n\nExample: Dekódovanie nahraného súboru\n```js\nvar uri = 'data:text/plain;base64,aGVsbG8=';\nuri.base64ToBuffer().toString();   // hello\nuri.base64ContentType();           // text/plain\nuri.parseDataURI().type;           // text/plain\nuri.base64ToFile(PATH.temp('hello.txt'));\n```\n\n### num.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nNaformátuje číslo s oddeľovačom tisícov a pevným počtom desatinných miest.\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\nOddeľovač tisícov je predvolene medzera. Desatinný oddeľovač je `.` alebo `,`, keď je oddeľovač tisícov `.`. Nadbytočné desatinné miesta sa odrežú, nie zaokrúhlia, takže keď potrebuješ zaokrúhľovanie, najprv zavolaj `Number.round()`. Chýbajúce desatinné miesta sa doplnia nulami. Keď je prvý argument reťazec, prvé dva argumenty sa vymenia: `format('.', 2)` je to isté ako `format(2, '.')`.\n\nExample: Formátovanie\n```js\n(1234567.891).format(2);           // 1 234 567.89\n(1234.5).format(2, ',', '.');      // 1,234.50\n(1234.5).format('.', 2);           // 1.234,50\n(1.999).round(2).format(2);        // 2.00\n```\n\n### num.pluralize(zero, one, few, other)\n\nType: `method`\n\nVyberie tvar množného čísla podľa čísla; # sa nahradí číslom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Text pre 0 alebo všetky štyri tvary oddelené čiarkami. |\n| `one` | `String` | no |  | Text pre 1. |\n| `few` | `String` | no |  | Text pre 2 až 4. |\n| `other` | `String` | no |  | Text pre ostatné čísla. |\n\nReturns: `String` Vybraný tvar.\n\nTvar `zero` sa použije pre 0, `one` pre 1, `few` pre 2 až 4 a `other` pre ostatné (pravidlo slovanských jazykov; pre angličtinu odovzdaj rovnaký text ako `few` a `other`). Keď odovzdáš iba jeden reťazec, rozdelí sa čiarkami na štyri tvary. Prvé `#` vo zvolenom tvare sa nahradí číslom.\n\nExample: Tvary množného čísla\n```js\n(1).pluralize('no items', '# item', '# items', '# items');  // 1 item\n(7).pluralize('no items,# item,# items,# items');          // 7 items\n```\n\n### num.padLeft(max, [c])\n\nType: `method`\n\nDoplní číslo zľava nulami. Number.padRight() dopĺňa sprava.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Dĺžka výsledku. |\n| `c` | `String` | no | `'0'` | Znak na doplnenie. |\n\nReturns: `String` Doplnené číslo.\n\nČíslo sa prevedie na reťazec a doplní na `max` znakov znakom `c` (predvolene `0`). `num.padRight(max, [c])` dopĺňa sprava.\n\nExample: Doplnenie nulami\n```js\n(5).padLeft(3);       // 005\n(7).padLeft(4, ' ');  // '   7'\n(5).padRight(3);      // 500\n```\n\n### num.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` | yes |  | Počet desatinných miest. |\n\nReturns: `Number` Zaokrúhlené číslo.\n\nZaokrúhľovanie používa exponenciálny zápis, takže hodnoty ako `1.005` sa správne zaokrúhlia na `1.01`. `num.floor(decimals)` namiesto toho zaokrúhli nadol na daný počet desatinných miest (`(1.239).floor(2)` je `1.23`).\n\nExample: Zaokrúhlenie\n```js\n(1.005).round(2);  // 1.01\n(2.5).round(0);    // 3\n(1.239).floor(2);  // 1.23\n```\n\n### num.fixed(decimals)\n\nType: `method`\n\nZaokrúhli číslo cez toFixed() a vráti číslo, nie reťazec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Počet desatinných miest. |\n\nReturns: `Number`\n\nExample: Fixed\n```js\n(1.236).fixed(2);  // 1.24 (a number)\n```\n\n### num.between(condition, [otherwise])\n\nType: `method`\n\nVráti hodnotu prvého rozsahu, ktorý obsahuje číslo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Rozsahy ako kľúče, výsledky ako hodnoty. |\n| `otherwise` | `Any` | no |  | Výsledok, keď nezodpovedá žiadny rozsah. |\n\nReturns: `Any` Hodnota zodpovedajúceho rozsahu alebo `otherwise`.\n\n`condition` je objekt, ktorého kľúče sú rozsahy: `'1-3'` (od 1 do 3, vrátane oboch), `'7-'` (7 a viac) alebo `'-5'` (5 a menej). Kľúče sa testujú postupne a vráti sa hodnota prvého zodpovedajúceho kľúča. Keď nezodpovedá žiadny rozsah, vráti sa `otherwise`.\n\nExample: Hodnotenie skóre\n```js\nvar score = 5;\nscore.between({ '0-3': 'low', '4-6': 'medium', '7-': 'high' }, 'unknown');\n// medium\n```\n\n### num.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nPripočíta k číslu daň alebo ju odpočíta z ceny, ktorá ju obsahuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | Sadzba dane v percentách. |\n| `decimals` | `Number` | no | `2` | Počet desatinných miest. |\n| `includedVAT` | `Boolean` | no | `false` | Číslo už obsahuje daň. |\n\nReturns: `Number`\n\n`Number.TAX()` je tá istá metóda. Bez `includedVAT` je výsledkom číslo zvýšené o `percentage`. Keď je `includedVAT` nastavené na `true`, číslo je cena, ktorá už daň obsahuje, a výsledkom je cena bez dane. Výsledok sa zaokrúhli na `decimals` (predvolene 2). Boolean môžeš odovzdať ako druhý argument: `VAT(20, true)`.\n\nExample: Ceny s DPH\n```js\n(100).VAT(20);        // 120\n(120).VAT(20, true);  // 100\n(99.99).TAX(10, 0);   // 110\n```\n\n### num.discount(percentage, [decimals])\n\nType: `method`\n\nZníži číslo o percento.\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`\n\nVýsledok sa zaokrúhli nadol na `decimals` (predvolene 2).\n\nExample: Zľava\n```js\n(100).discount(15);    // 85\n(19.99).discount(10);  // 17.99\n```\n\n### num.filesize([decimals], [type])\n\nType: `method`\n\nNaformátuje počet bajtov ako čitateľnú veľkosť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Počet desatinných miest. |\n| `type` | `String` | no |  | `bytes`, `KB`, `MB`, `GB` alebo `TB`. |\n\nReturns: `String` Veľkosť s jednotkou.\n\nBez `type` sa zvolí najväčšia vhodná jednotka: `bytes`, `KB`, `MB`, `GB` alebo `TB` (1 KB je 1024 bajtov). S `type` sa hodnota prevedie na túto jednotku. Bez `decimals` má hodnota najviac dve desatinné miesta a `.00` sa odstráni; s `decimals` sa naformátuje cez `Number.format(decimals)`. Argumenty možno odovzdať v ľubovoľnom poradí.\n\nExample: Veľkosti súborov\n```js\n(500).filesize();          // 500 bytes\n(1536000).filesize();      // 1.46 MB\n(5000000).filesize(1, 'MB'); // 4.7 MB\n```\n\n### num.currency([currency], [a], [b], [c])\n\nType: `method`\n\nNaformátuje číslo ako sumu formátovačom meny zaregistrovaným v DEF.currencies.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | Kľúč v `DEF.currencies`. |\n| `a, b, c` | `Any` | no |  | Ďalšie argumenty pre formátovač. |\n\nReturns: `String` Naformátovaná suma.\n\nFormátovač je funkcia `DEF.currencies[currency]` (alebo `DEF.currencies.default` bez `currency`). Dostane číslo a argumenty `a`, `b` a `c` a vráti text. Keď pre menu neexistuje formátovač, výsledkom je `num.format(2)`. Formátovače zaregistruj pri štarte, napríklad v súbore definícií.\n\nExample: Registrácia a použitie meny\n```js\n// /definitions/currencies.js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2, ' ', ',') + ' €';\n};\n\n(1234.5).currency('eur');  // 1 234,50 €\n(10).currency('usd');      // 10.00 (no formatter)\n```\n\n### date.add(type, [value])\n\nType: `method`\n\nVráti nový dátum posunutý o určitý čas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | Jednotka, reťazec s hodnotou a jednotkou alebo milisekundy. |\n| `value` | `Number` | no |  | Množstvo, záporné pre minulosť. |\n\nReturns: `Date` Nový dátum.\n\nPôvodný dátum sa nemení. Odovzdaj jednotku a hodnotu (`add('minutes', 30)`), jeden reťazec s oboma (`add('30 minutes')`, `add('-2 hours')`) alebo počet milisekúnd (`add(5000)`).\n\nJednotky: `s`, `ss`, `sec`, `second`, `seconds`; `m`, `mm`, `min`, `minute`, `minutes`; `h`, `hh`, `hour`, `hours`; `d`, `dd`, `day`, `days`; `w`, `ww`, `week`, `weeks`; `M`, `MM`, `month`, `months`; `y`, `yyyy`, `year`, `years`. Jednotky pracujú s UTC časťami dátumu. Pripočítanie mesiacov ku koncu mesiaca sa správa ako v JavaScripte: 31. január plus jeden mesiac je v priestupnom roku 2. marec a inak 3. marec.\n\nExample: Posúvanie dátumov\n```js\nvar now = new Date();\nnow.add('1 day');\nnow.add('minutes', 30);\nnow.add('-2 hours');\nnow.add(5000);  // + 5 seconds\n```\n\n### date.diff([date], type)\n\nType: `method`\n\nVráti rozdiel medzi dvoma dátumami v sekundách, minútach, hodinách alebo dňoch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|String|Number` | no | `now` | Dátum na porovnanie. |\n| `type` | `String` | yes |  | Jednotka výsledku. |\n\nReturns: `Number` Rozdiel v danej jednotke.\n\nVýsledok je `this - date` v zadanej jednotke, zaokrúhlený nahor, takže je kladný, keď je `this` neskôr. `date` môže byť Date, reťazec, ktorému rozumie `Date.parse()`, alebo počet milisekúnd. S jedným argumentom sa dátum porovná s aktuálnym časom. Jednotky: `s` / `ss` / `second` / `seconds`, `m` / `mm` / `minute` / `minutes`, `h` / `hh` / `hour` / `hours`, `d` / `dd` / `day` / `days`. Neznáma jednotka vráti `NaN`.\n\nExample: Rozdiely\n```js\nvar created = new Date('2024-01-30T00:00:00Z');\nvar end = new Date('2024-01-31T10:00:00Z');\nend.diff(created, 'hours');  // 34\nend.diff('2024-01-01T00:00:00Z', 'days'); // 31\ncreated.diff('seconds');     // negative: created is in the past\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nNaformátuje dátum podľa vzoru; bez vzoru vráti ISO reťazec v UTC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Vzor. |\n| `resource` | `String` | no |  | Resource použitý pre názvy mesiacov a dní. |\n\nReturns: `String` Naformátovaný dátum.\n\nBez `format` je výsledkom `yyyy-MM-ddTHH:mm:ss.SSSZ` v UTC. S `format` sa časti zapíšu v časovom pásme servera (UTC, pokiaľ konfiguračný kľúč `$timezone` neurčuje inak):\n\n- `yyyy`, `yy` rok; `MM`, `M` číslo mesiaca; `MMMM` názov mesiaca, `MMM` jeho prvé tri písmená,\n- `dd`, `d` deň; `dddd` názov dňa, `ddd` jeho prvé dve písmená veľkými písmenami,\n- `HH`, `H` hodiny (0-23); `mm`, `m` minúty; `ss`, `s` sekundy,\n- `ww`, `w` číslo týždňa podľa ISO; `a` `AM` alebo `PM`.\n\nPrijímajú sa aj veľké `YYYY`, `YY`, `DD`, `D`, `DDDD`, `DDD` a malé `hh`, `h`. Názvy mesiacov a dní sú anglické; s `resource` sa preložia resource súborom s týmto názvom. Skompilované formáty sa ukladajú do cache, takže formátovanie je rýchle.\n\nExample: Formátovanie dátumov\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.format();                      // 2024-01-31T10:00:00.000Z\nd.format('yyyy-MM-dd HH:mm');    // 2024-01-31 10:00\nd.format('dd.MM.yy');            // 31.01.24\nd.format('dddd, d. MMMM yyyy');  // Wednesday, 31. January 2024\nd.format('MMMM', 'sk');          // the month name from sk.resource\n```\n\n### date.extend(text)\n\nType: `method`\n\nVráti nový dátum s časťami dátumu alebo času nahradenými z textu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Dátum, čas alebo oboje. |\n\nReturns: `Date` Nový dátum.\n\nText môže obsahovať dátum `yyyy-MM-dd` alebo `d.M.yyyy` a čas `HH:mm` alebo `HH:mm:ss`. Nahradia sa iba časti nájdené v texte; ostatné sa vezmú z pôvodného dátumu. Rok, mesiac a deň sa nastavujú jeden po druhom, takže keď deň pôvodného dátumu v novom mesiaci neexistuje, dátum sa posunie do ďalšieho mesiaca (31. január rozšírený o `2025-02-10` dá 10. marec 2025). Hodnoty sú v UTC.\n\nExample: Zmena častí\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.extend('12:30');              // 2024-01-31T12:30:00.000Z\nd.extend('2025-03-04');         // 2025-03-04T10:00:00.000Z\nd.extend('1.3.2020 08:00');     // 2020-03-01T08:00:00.000Z\n```\n\n### date.toUTC([ticks])\n\nType: `method`\n\nPosunie lokálny dátum o posun časového pásma na UTC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Vrátiť milisekundy. |\n\nReturns: `Date|Number`\n\nVýsledkom je dátum plus posun časového pásma servera. Keď je `ticks` nastavené na `true`, výsledkom je namiesto Date počet milisekúnd. Na serveri, ktorý beží v UTC (predvolene), sa dátum nezmení.\n\nExample: Na UTC\n```js\nvar utc = new Date().toUTC();\nvar ms = new Date().toUTC(true);\n```\n\n### date.setTimeZone(timezone)\n\nType: `method`\n\nVráti nový dátum, ktorý zobrazuje ten istý okamih v inom časovom pásme.\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Časti výsledku (hodiny, deň, ...) čítané v časovom pásme servera sú miestnym časom `timezone` v danom okamihu, takže `format()` vypíše miestny čas tohto pásma. `timezone` je IANA názov ako `Europe/Bratislava` alebo `America/New_York`.\n\nExample: Zobrazenie miestneho času\n```js\nvar d = new Date('2024-01-31T10:00:00Z');\nd.setTimeZone('Europe/Bratislava').format('HH:mm');  // 11:00\n```\n\n### arr.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|Any` | yes |  | Testovacia funkcia, názov vlastnosti alebo hodnota. |\n| `value` | `Any` | no |  | Hodnota vlastnosti. |\n\nReturns: `Object` Položka alebo `null`.\n\nOdovzdaj funkciu `(item, index)`, názov vlastnosti a hodnotu (`('id', 5)` porovná `item.id === 5`) alebo jednu hodnotu, ktorá sa porovná cez `===`.\n\nExample: Nájdenie položky\n```js\nvar users = [{ id: 1, name: 'Peter' }, { id: 2, name: 'Anna' }];\nusers.findItem('id', 2);                  // { id: 2, name: 'Anna' }\nusers.findItem(u => u.name === 'Peter');  // { id: 1, name: 'Peter' }\nusers.findItem('id', 9);                  // null\n```\n\n### arr.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|Any` | yes |  | Testovacia funkcia, názov vlastnosti alebo hodnota. |\n| `value` | `Any` | no |  | Hodnota vlastnosti. |\n\nReturns: `Array` Zodpovedajúce položky.\n\nOdovzdaj funkciu `(item, index)`, názov vlastnosti a hodnotu (`('id', 5)` porovná `item.id === 5`) alebo jednu hodnotu, ktorá sa porovná cez `===`. Výsledkom je nové pole; pôvodné pole sa nemení.\n\nExample: Filtrovanie\n```js\nvar items = [{ type: 'a' }, { type: 'b' }, { type: 'a' }];\nitems.findAll('type', 'a').length;  // 2\n```\n\n### arr.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|Any` | yes |  | Testovacia funkcia, názov vlastnosti alebo hodnota. |\n| `value` | `Any` | no |  | Hodnota vlastnosti. |\n\nReturns: `Number` Index alebo `-1`.\n\nOdovzdaj funkciu `(item, index)`, názov vlastnosti a hodnotu (`('id', 5)` porovná `item.id === 5`) alebo jednu hodnotu, ktorá sa porovná cez `===`. Total.js nahrádza natívnu `findIndex()` touto verziou (s funkciou sa správa ako natívna); `arr.TfindIndex()` je tá istá metóda.\n\nExample: Index položky\n```js\nvar users = [{ id: 1 }, { id: 2 }];\nvar index = users.findIndex('id', 2);  // 1\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### arr.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 |  | Testovacia funkcia alebo názov vlastnosti. |\n| `value` | `Any` | yes |  | Hodnota vlastnosti (s funkciou odovzdaj `undefined`). |\n| `path` | `String` | yes |  | Vlastnosť, ktorá sa má vrátiť. |\n| `def` | `Any` | no |  | Predvolená hodnota. |\n\nReturns: `Any`\n\nPoložka sa nájde ako v `Array.findItem()`. Výsledkom je `item[path]` alebo `def`, keď nezodpovedá žiadna položka alebo je vlastnosť `null` / `undefined`.\n\nExample: Čítanie vlastnosti\n```js\nvar users = [{ id: 1, name: 'Peter' }];\nusers.findValue('id', 1, 'name');          // Peter\nusers.findValue('id', 9, 'name', 'guest');  // guest\n```\n\n### arr.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|Any` | yes |  | Testovacia funkcia, názov vlastnosti alebo hodnota. |\n| `value` | `Any` | no |  | Hodnota vlastnosti. |\n\nReturns: `Array` Nové pole bez zodpovedajúcich položiek.\n\nOdovzdaj funkciu `(item, index)`, názov vlastnosti a hodnotu (`('id', 5)` porovná `item.id === 5`) alebo jednu hodnotu, ktorá sa porovná cez `===`. Pôvodné pole sa nemení, takže výsledok priraď.\n\nExample: Odstránenie položiek\n```js\nvar users = [{ id: 1 }, { id: 2 }, { id: 3 }];\nusers = users.remove('id', 1);       // [{ id: 2 }, { id: 3 }]\nvar nums = [1, 2, 3, 2].remove(2);   // [1, 3]\n```\n\n### arr.quicksort([sort], [desc])\n\nType: `method`\n\nZoradí pole na mieste podľa jednej alebo viacerých vlastností.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Vlastnosti, podľa ktorých sa triedi, alebo `true` pre zostupné jednoduché hodnoty. |\n| `desc` | `Boolean` | no | `false` | Zostupné poradie pre `sort`. |\n\nReturns: `Array` To isté pole, zoradené.\n\n`sort` je zoznam názvov vlastností oddelených čiarkami, každý voliteľne s `_asc` alebo `_desc` (`'name'`, `'price_desc'`, `'group,date_desc'`). Podporované sú vnorené vlastnosti s bodkami (`'user.name'`). Typ každého stĺpca (reťazec, číslo, boolean alebo Date) sa zistí z prvej hodnoty, ktorá nie je null, pri prvom použití výrazu triedenia a zachová sa pre ďalšie triedenia s rovnakým výrazom; reťazce sa porovnávajú s ohľadom na diakritiku. Odovzdanie `true` (alebo `2`) ako druhého argumentu zoradí jednu vlastnosť zostupne.\n\nBez `sort` sa pole jednoduchých hodnôt zoradí vzostupne; `quicksort(true)` ho zoradí zostupne. Metóda vráti to isté pole.\n\nExample: Triedenie objektov\n```js\nvar products = [{ name: 'B', price: 10 }, { name: 'A', price: 20 }];\nproducts.quicksort('name');        // A, B\nproducts.quicksort('price_desc');  // 20, 10\nproducts.quicksort('name', true);  // B, A\n[3, 1, 2].quicksort();             // [1, 2, 3]\n```\n\n### arr.take(count)\n\nType: `method`\n\nVráti prvých count položiek ako nové pole.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Počet položiek. |\n\nReturns: `Array`\n\nExample: Take\n```js\n[1, 2, 3, 4].take(2);  // [1, 2]\n```\n\n### arr.skip(count)\n\nType: `method`\n\nVráti položky po prvých count položkách ako nové pole.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Počet položiek na preskočenie. |\n\nReturns: `Array`\n\nNa stránkovanie ju kombinuj s `take()`.\n\nExample: Stránkovanie\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### arr.first([def])\n\nType: `method`\n\nVráti prvú položku alebo predvolenú hodnotu pre prázdne pole. Array.last() vráti poslednú.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Any` | no |  | Hodnota pre prázdne pole. |\n\nReturns: `Any`\n\n`arr.last([def])` vráti poslednú položku alebo `def`.\n\nExample: Prvá a posledná\n```js\n[1, 2].first();     // 1\n[].first('none');   // none\n[1, 2].last();      // 2\n```\n\n### arr.group(name)\n\nType: `method`\n\nZoskupí položky podľa vlastnosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Vlastnosť, podľa ktorej sa zoskupuje. |\n\nReturns: `Array` Skupiny `{ name, items }`.\n\nVráti pole `{ name, items }` zoradené podľa `name`. Hodnota vlastnosti sa prevedie na reťazec; položky bez tejto vlastnosti sú v skupine s prázdnym názvom.\n\nExample: Zoskupenie\n```js\nvar items = [{ type: 'x', id: 1 }, { type: 'y', id: 2 }, { type: 'x', id: 3 }];\nitems.group('type');\n// [{ name: 'x', items: [...2 items] }, { name: 'y', items: [...1 item] }]\n```\n\n### arr.trim()\n\nType: `method`\n\nOreže reťazce a vráti nové pole bez prázdnych hodnôt.\n\nReturns: `Array`\n\nReťazce v pôvodnom poli sa orežú na mieste. Výsledok obsahuje iba pravdivé položky, takže prázdne reťazce, `null`, `undefined`, `0` a `false` sa vynechajú.\n\nExample: Vyčistenie zoznamu\n```js\n' a , ,b'.split(',').trim();  // ['a', 'b']\n```\n\n### arr.random([item])\n\nType: `method`\n\nZamieša pole na mieste alebo vráti jednu 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|Any`\n\nBez argumentov sa pole zamieša (Fisher-Yates) a vráti. Keď je `item` nastavené na `true`, vráti sa jedna náhodná položka a pole sa nezmení.\n\nExample: Náhodne\n```js\nvar colors = ['red', 'green', 'blue'];\ncolors.random(true);  // one color\ncolors.random();      // the shuffled array\n```\n\n### arr.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 |  | `function(item, next)`. |\n| `callback` | `Function` | no |  | Volá sa, keď sú všetky položky spracované. |\n| `thread` | `Number|Boolean` | no | `1` | Paralelné položky alebo `true` na odstraňovanie položiek počas spracovania. |\n\nReturns: `Array` Pole.\n\n`onItem(item, next)` sa zavolá pre každú položku; zavolaj `next()` na pokračovanie ďalšou položkou. `callback()` sa zavolá, keď sú všetky položky hotové. `thread` určuje, koľko položiek beží naraz (predvolene 1). Keď je `thread` nastavené na `true`, položky sa počas spracovania odstraňujú z poľa cez `shift()`. Na zastavenie zavolaj `next('cancel')`: potom sa zavolá `callback('cancel')`.\n\nExample: Postupné spracovanie\n```js\nvar ids = [1, 2, 3];\nids.wait(function(id, next) {\n\tFUNC.removeuser(id, next);\n}, function() {\n\tconsole.log('All removed');\n});\n```\n\nExample: Dve naraz\n```js\nurls.wait(function(url, next) {\n\tREQUEST({ url: url, callback: () => next() });\n}, () => console.log('done'), 2);\n```\n\n### arr.async([thread], [callback])\n\nType: `method`\n\nSpustí pole funkcií jednu po druhej.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | Koľko funkcií beží naraz. |\n| `callback` | `Function` | no |  | Volá sa na konci. |\n\nReturns: `Array` Pole.\n\nKaždá položka je funkcia `(next)`; keď skončí, zavolaj `next()`. Funkcie sa pri spúšťaní odstraňujú z poľa, takže na konci je pole prázdne. `thread` určuje, koľko funkcií sa spustí naraz (predvolene 1). `callback()` sa zavolá, keď sú všetky funkcie hotové, alebo `callback('cancel')`, keď niektorá zavolá `next('cancel')`.\n\nExample: Spustenie úloh\n```js\nvar tasks = [];\ntasks.push(function(next) {\n\tconsole.log('first');\n\tnext();\n});\ntasks.push(function(next) {\n\tsetTimeout(next, 100);\n});\ntasks.async(function() {\n\tconsole.log('done');\n});\n```\n\n### arr.limit(max, fn, [callback])\n\nType: `method`\n\nSpracuje pole po častiach s max položkami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Veľkosť časti. |\n| `fn` | `Function` | yes |  | `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Volá sa na konci. |\n\nReturns: `Array` Pole.\n\n`fn(items, next, beg, end)` dostane ďalšiu časť a počiatočný a koncový index; na pokračovanie zavolaj `next()`. `callback()` sa zavolá po poslednej časti.\n\nExample: Vkladanie v dávkach\n```js\nrows.limit(100, function(items, next) {\n\tFUNC.importrows(items, next);\n}, function() {\n\tconsole.log('Imported');\n});\n```\n","entries":[{"type":"method","name":"String.format()","signature":"str.format(arg0, [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"str.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"str.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"str.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"str.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"str.toName()","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"str.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"str.decode()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"str.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"str.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"str.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.toKeywords()","signature":"str.toKeywords([forsearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"str.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"str.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"str.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"str.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"str.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"str.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"str.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"str.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseContext()","signature":"str.parseContext()","since":"0.0.17","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"str.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"str.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseEnv()","signature":"str.parseEnv()","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"str.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"str.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"str.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"str.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"str.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"str.isNumber([isDecimal])","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"str.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"str.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"str.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"str.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"str.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"str.sign([key], [check])","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"str.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"str.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"str.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"num.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"num.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"num.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"num.round(precision)","since":"","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"num.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"num.between(condition, [otherwise])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"num.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"num.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"num.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"num.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"date.extend(text)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"arr.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"arr.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"arr.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"arr.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"arr.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"arr.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"arr.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"arr.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"arr.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.group()","signature":"arr.group(name)","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"arr.trim()","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"arr.random([item])","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"arr.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"arr.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"arr.limit(max, fn, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:14.575Z"}
{"id":"JafwTD5Lx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/images/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Images","summary":"The Image global and every method of image objects.","markdown":"---\ntitle: Images\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/images/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Images\n\n> The Image global and every method of image objects.\n\nThe `Image` global loads, changes, measures and saves images with GraphicsMagick or ImageMagick. The guide [Images](../../guides/images/) explains how to use it with examples; this page is the exact reference.\n\n## API\n\n### Image\n\nType: `class`\n\nThe global image module.\n\n`Image` is the image module of the framework. It has `Image.load()` to create image objects, the `Image.measure*()` functions that read the size from a file header, `Image.middleware()` and the constructor `Image.Image`. The operations run with the program set in `$imageconverter`.\n\nExample: Resize a photo\n```js\nImage.load(PATH.public('photo.jpg')).resize(800).save(PATH.public('photo-800.jpg'));\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nCreates an image object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | A file name, a Buffer or a readable stream. |\n| `converter` | `String` | no | `CONF.$imageconverter` | The program: `gm`, `im` or `magick`. |\n| `width` | `Number` | no |  | The known width, stored in `img.width`. |\n| `height` | `Number` | no |  | The known height, stored in `img.height`. |\n\nReturns: `Image` A new image object.\n\n`source` is a file name, a `Buffer` or a readable stream. With a file name, `img.type` is its extension; otherwise it is `jpg`. `converter` is `gm`, `im` or `magick` and overrides `$imageconverter` for this image. `width` and `height` are only stored in `img.width` and `img.height`; they are not read from the file.\n\nExample: Load from a file and a buffer\n```js\nvar a = Image.load(PATH.public('photo.jpg'));\nvar b = Image.load(buffer, 'magick');\n```\n\n### F.image(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|Buffer|Stream` | yes |  | A file name, a Buffer or a readable stream. |\n| `converter` | `String` | no | `CONF.$imageconverter` | The program: `gm`, `im` or `magick`. |\n| `width` | `Number` | no |  | The known width. |\n| `height` | `Number` | no |  | The known height. |\n\nReturns: `Image` A new image object.\n\nAn alias of `Image.load()` on the framework object.\n\nExample: Load an image\n```js\nF.image(filename).grayscale().save(target);\n```\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nThe constructor of image objects.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | A file name, a Buffer or a readable stream. |\n| `converter` | `String` | no | `CONF.$imageconverter` | The program: `gm`, `im` or `magick`. |\n| `width` | `Number` | no |  | The known width. |\n| `height` | `Number` | no |  | The known height. |\n\n`Image.load()` returns `new Image.Image(...)` with the same arguments. Use it when you want to test `img instanceof Image.Image` or add your own methods to `Image.Image.prototype`.\n\nExample: Add a method\n```js\nImage.Image.prototype.avatar = function() {\n\treturn this.resizecenter(128, 128).quality(90);\n};\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nReads the width and height from the header of an image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | An extension or a MIME type. |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`, `null` for a JPEG without the size marker, `undefined` for an unsupported type.\n\n`type` is an extension with or without the dot (`jpg`, `.png`) or a MIME type (`image/webp`). Supported types are JPEG, PNG, GIF, WebP, SVG, BMP and PSD. The buffer needs only the beginning of the file. For other types it returns `undefined`. For a JPEG buffer without the size marker it returns `null`.\n\nExample: Measure an uploaded buffer\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\t$.invalid('The image is too wide');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nReads the size of a JPEG image from a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }` or `null`.\n\nIt scans the markers until the frame header. Returns `null` when the buffer is not a JPEG or when the frame header is not in the buffer (a damaged file, a segment with an invalid length or too little data). Pass enough data: the framework reads 40 kB.\n\nExample: Measure\n```js\nvar size = Image.measureJPG(buffer);\nconsole.log(size.width, size.height);\n```\n\nExample: A JPEG without the size\n```js\nvar buffer = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00]);\nvar size = Image.measureJPG(buffer);\nconsole.log(size); // null: no frame header in the buffer\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nReads the size of a PNG image from a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`.\n\nIt reads the IHDR header, so 24 bytes are enough.\n\nExample: Measure\n```js\nvar size = Image.measurePNG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nReads the size of a GIF image from a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`.\n\nIt reads the logical screen size, so 10 bytes are enough.\n\nExample: Measure\n```js\nvar size = Image.measureGIF(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nReads the size of a WebP image from a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`.\n\nIt reads the `VP8 `, `VP8L` and `VP8X` headers. Returns `undefined` for other data.\n\nExample: Measure\n```js\nvar size = Image.measureWEBP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nReads the size of a SVG image from a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`.\n\nIt reads the first `width=\"...\"` and `height=\"...\"` attributes with whole numbers. Returns `undefined` when there is none.\n\nExample: Measure\n```js\nvar size = Image.measureSVG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nReads the size of a BMP image from a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`.\n\nIt reads the BITMAPINFOHEADER.\n\nExample: Measure\n```js\nvar size = Image.measureBMP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nReads the size of a Photoshop (PSD) image from a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`.\n\nIt reads the PSD file header.\n\nExample: Measure\n```js\nvar size = Image.measurePSD(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nRegisters a stream that post-processes results of one type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The image type, for example `png` or `.jpg`. |\n| `fn` | `Function` | yes |  | Returns a Transform stream. |\n\n`fn` must return a new Transform stream each time it is called. With `pipe()` and `writer()` the output of the program goes through it before it reaches you, and `type` is matched with the output format. With `save()` and a callback, the saved file is read through it and written again before the callback runs; there `type` is matched with `img.type` (the extension of the source or the value of `output()`). A leading dot in `type` is removed. One function per type; a new call replaces it.\n\nExample: Pass PNG results through a stream\n```js\nvar Transform = require('stream').Transform;\n\nImage.middleware('png', function() {\n\treturn new Transform({\n\t\ttransform: function(chunk, encoding, next) {\n\t\t\tnext(null, chunk);\n\t\t}\n\t});\n});\n```\n\n### img.width\n\nType: `property`\n\nThe width passed to `Image.load()`.\n\nReturns: `Number`\n\nThe third argument of `Image.load()`, or `undefined`. It is not read from the file; use `img.measure()` for that. `img.height` holds the fourth argument the same way.\n\nExample: Known size\n```js\nvar img = Image.load(file.path, null, file.width, file.height);\nif (img.width > 1000)\n\timg.resize(1000);\n```\n\n### img.filename\n\nType: `property`\n\nThe source file name.\n\nReturns: `String`\n\nThe file name given to `Image.load()`, or `null` when the source is a Buffer or a stream.\n\n### img.stream\n\nType: `property`\n\nThe source Buffer or stream.\n\nReturns: `Buffer|Stream`\n\nThe Buffer or readable stream given to `Image.load()`, or `null` when the source is a file name. It is written to the standard input of the program when the image is saved or piped.\n\n### img.type\n\nType: `property`\n\nThe image type.\n\nReturns: `String`\n\nThe extension of the source file in lower case without the dot (`jpg`, `png`…), or `jpg` for a Buffer or a stream. `output()` changes it. `pipe()` and `writer()` use it as the output format when you do not pass one, and `Image.middleware()` handlers are matched with it.\n\n### img.shell\n\nType: `property`\n\nThe program that processes the image.\n\nReturns: `String`\n\n`gm`, `im` or `magick`: the second argument of `Image.load()`, otherwise `CONF.$imageconverter`. `gm` runs `gm convert`, `im` runs `convert` and `magick` runs `magick`. You can change it before you save the image.\n\n### img.resize([w], [h], [options])\n\nType: `method`\n\nResizes the image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | The width in pixels, or a percentage like `'50%'`. Empty to keep the ratio. |\n| `h` | `Number|String` | no |  | The height in pixels, or a percentage. Empty to keep the ratio. |\n| `options` | `String` | no |  | A suffix of the size: `!` ignores the ratio, `^` fills the box, `>` only shrinks, `<` only enlarges. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-resize WxH`. The image fits into the box and keeps its aspect ratio unless `options` says otherwise. With only `w` the height follows the ratio, with only `h` the width does.\n\nExample: Resize\n```js\nimg.resize(800, 600);   // into 800x600\nimg.resize(800);        // width 800\nimg.resize(null, 600);  // height 600\nimg.resize(200, 200, '!'); // exactly 200x200\nimg.resize('50%');      // half size\n```\n\n### img.thumbnail([w], [h], [options])\n\nType: `method`\n\nResizes the image for a small preview.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | The width in pixels, or a percentage like `'50%'`. Empty to keep the ratio. |\n| `h` | `Number|String` | no |  | The height in pixels, or a percentage. Empty to keep the ratio. |\n| `options` | `String` | no |  | A suffix of the size: `!` ignores the ratio, `^` fills the box, `>` only shrinks, `<` only enlarges. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-thumbnail WxH`: a resize that also removes the profiles, so the file is smaller. The arguments are the same as in `resize()`.\n\nExample: Thumbnail\n```js\nImage.load(filename).thumbnail(150, 150).save(target);\n```\n\n### img.scale([w], [h], [options])\n\nType: `method`\n\nResizes the image quickly without filtering.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | The width in pixels, or a percentage like `'50%'`. Empty to keep the ratio. |\n| `h` | `Number|String` | no |  | The height in pixels, or a percentage. Empty to keep the ratio. |\n| `options` | `String` | no |  | A suffix of the size: `!` ignores the ratio, `^` fills the box, `>` only shrinks, `<` only enlarges. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-scale WxH`. Faster than `resize()` but with lower quality. The arguments are the same as in `resize()`.\n\nExample: Scale\n```js\nimg.scale(64, 64);\n```\n\n### img.geometry([w], [h], [options])\n\nType: `method`\n\nAdds the `-geometry` option.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | The width in pixels, or a percentage like `'50%'`. Empty to keep the ratio. |\n| `h` | `Number|String` | no |  | The height in pixels, or a percentage. Empty to keep the ratio. |\n| `options` | `String` | no |  | A suffix of the size: `!` ignores the ratio, `^` fills the box, `>` only shrinks, `<` only enlarges. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-geometry WxH` with the optional suffix. The program uses it as the preferred size and offset.\n\nExample: Geometry\n```js\nimg.geometry(300, 200, '!');\n```\n\n### img.crop(w, h, [x], [y])\n\nType: `method`\n\nCuts an area of the image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | The width of the area. |\n| `h` | `Number` | yes |  | The height of the area. |\n| `x` | `Number` | no | `0` | The horizontal offset. |\n| `y` | `Number` | no | `0` | The vertical offset. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-crop WxH+X+Y`. The offset is measured from the corner set by `align()` (top left by default).\n\nExample: Crop\n```js\nimg.crop(400, 300, 50, 20);\n\n// The centre\nimg.align('center').crop(400, 300);\n```\n\n### img.extent([w], [h], [x], [y])\n\nType: `method`\n\nSets the size of the canvas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | The width of the canvas. |\n| `h` | `Number` | no |  | The height of the canvas. |\n| `x` | `Number` | no |  | The horizontal offset, can be negative. |\n| `y` | `Number` | no |  | The vertical offset, can be negative. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-extent WxH` with an optional offset. A larger canvas is filled with the background color, a smaller one cuts the image. The position follows `align()`.\n\nExample: Square canvas\n```js\nimg.resize(500, 500).background('white').align('center').extent(500, 500);\n```\n\n### img.miniature(w, h, [color], [filter])\n\nType: `method`\n\nFits the image into a box and fills the rest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | The width. |\n| `h` | `Number` | yes |  | The height. |\n| `color` | `String` | no | `'white'` | The color of the free area. |\n| `filter` | `String` | no | `'Hamming'` | The resize filter. |\n\nReturns: `Image` The same image object, for chaining.\n\nA shortcut for `thumbnail(w, h).background(color).align('center').extent(w, h)`. The result is exactly `w`x`h` and shows the whole image. `filter` is the resize filter of `thumbnail()`.\n\nExample: Product photo\n```js\nImage.load(filename).miniature(300, 300, '#F0F0F0').save(target);\n```\n\n### img.resizecenter(w, h, [color])\n\nType: `method`\n\nFills a box and crops the centre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | The width. |\n| `h` | `Number` | yes |  | The height. |\n| `color` | `String` | no | `'white'` | The background color. |\n\nReturns: `Image` The same image object, for chaining.\n\nA shortcut for `resize(w, h, '^').background(color).align('center').crop(w, h)`. The result is `w`x`h` and the image covers it completely.\n\nExample: Cover\n```js\nImage.load(filename).resizecenter(1200, 630).save(target);\n```\n\n### img.resizealign(w, h, [align], [color])\n\nType: `method`\n\nFills a box and crops at a side.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | The width. |\n| `h` | `Number` | yes |  | The height. |\n| `align` | `String` | no | `'center'` | Where to crop: `top`, `bottom`, `left`, `center`… |\n| `color` | `String` | no | `'white'` | The background color. |\n\nReturns: `Image` The same image object, for chaining.\n\nA shortcut for `resize(w, h, '^').background(color).align(align).crop(w, h)`. `align` takes the values of `align()`.\n\nExample: Avatar\n```js\nImage.load(filename).resizealign(200, 200, 'top').save(target);\n```\n\n### img.align(type)\n\nType: `method`\n\nSets the gravity for crop and extent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The position. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-gravity`. Accepted values: `'top left'` (NorthWest), `'top'` (North), `'top right'` (NorthEast), `'left'` (West), `'center'` or `'middle'` (Center), `'right'` (East), `'bottom left'` (SouthWest), `'bottom'` (South), `'bottom right'` (SouthEast). Word order does not matter (`'left top'`), and `'center left'` means `left`. Other values are passed as they are, for example `'NorthEast'`.\n\nExample: Align\n```js\nimg.align('bottom right').crop(400, 300);\n```\n\n### img.gravity(type)\n\nType: `method`\n\nThe same method as `align()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The position. |\n\nReturns: `Image` The same image object, for chaining.\n\nAn alias of `align()`.\n\nExample: Gravity\n```js\nimg.gravity('NorthWest');\n```\n\n### img.quality([percentage])\n\nType: `method`\n\nSets the compression quality.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | The quality. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-quality`. For JPEG and WebP it is the quality from 1 to 100; an empty value means 80.\n\nExample: Quality\n```js\nimg.quality(70);\n```\n\n### img.rotate([deg])\n\nType: `method`\n\nRotates the image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | no | `0` | The angle in degrees. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-rotate`. The angle is in degrees clockwise. For angles other than multiples of 90 the corners are filled with the background color.\n\nExample: Rotate\n```js\nimg.background('white').rotate(45);\n```\n\n### img.flip()\n\nType: `method`\n\nMirrors the image vertically.\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-flip` (top to bottom).\n\nExample: Flip\n```js\nimg.flip();\n```\n\n### img.flop()\n\nType: `method`\n\nMirrors the image horizontally.\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-flop` (left to right).\n\nExample: Flop\n```js\nimg.flop();\n```\n\n### img.blur(radius)\n\nType: `method`\n\nBlurs the image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | The radius or `radiusxsigma`. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-blur`. The value is the radius, or `radiusxsigma` as a string (`'0x8'`).\n\nExample: Blur\n```js\nimg.blur(5);\nimg.blur('0x8');\n```\n\n### img.grayscale()\n\nType: `method`\n\nConverts the image to gray.\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-colorspace Gray`.\n\nExample: Gray\n```js\nimg.grayscale();\n```\n\n### img.sepia()\n\nType: `method`\n\nGives the image a sepia tone.\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-modulate 115,0,100 -colorize 7,21,50`.\n\nExample: Sepia\n```js\nimg.sepia();\n```\n\n### img.normalize()\n\nType: `method`\n\nStretches the contrast.\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-normalize`: the colors are spread over the full range.\n\nExample: Normalize\n```js\nimg.normalize();\n```\n\n### img.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 object, for chaining.\n\nAdds `-colors`.\n\nExample: Palette\n```js\nimg.output('png').colors(64);\n```\n\n### img.bitdepth(value)\n\nType: `method`\n\nSets the bit depth.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bits per channel, for example 8. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-depth`.\n\nExample: Depth\n```js\nimg.bitdepth(8);\n```\n\n### img.background(color)\n\nType: `method`\n\nSets the background color.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | The color. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-background color` and then `-extent 0x0`, so the color is set before the canvas is extended. The color fills new areas made by `extent()`, `rotate()` and the resize helpers. Any color of the program works: `white`, `#FF0000`, `none` for transparent.\n\nExample: Background\n```js\nimg.background('#FFFFFF').extent(800, 800);\n```\n\n### img.fill(color)\n\nType: `method`\n\nSets the fill color.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | The color. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-fill`. Used by operations that draw, for example `-colorize` or your own `command()` options.\n\nExample: Fill\n```js\nimg.fill('red').command('-colorize', '30');\n```\n\n### img.filter(type)\n\nType: `method`\n\nSets the resize filter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The filter name. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-filter`, for example `'Lanczos'`, `'Hamming'`, `'Box'` or `'Triangle'`. It is always placed before `-resize`, `-thumbnail` and `-scale`, so it applies to them whether you call it before or after `resize()`, `thumbnail()` or `scale()`.\n\nExample: Filter\n```js\nimg.resize(400).filter('Lanczos');\n```\n\nExample: The command\n```js\nImage.load('photo.jpg').filter('Lanczos').resize(200, 200).cmd('photo.jpg', 'small.jpg');\n// gm convert 'photo.jpg' -filter 'Lanczos' -resize '200x200' 'small.jpg'\n```\n\n### img.define(value)\n\nType: `method`\n\nPasses a coder option.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The definition `format:key=value`. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-define`, for example `'jpeg:extent=200kb'` or `'png:compression-level=9'`.\n\nExample: Define\n```js\nimg.define('jpeg:extent=200kb');\n```\n\n### img.minify()\n\nType: `method`\n\nRemoves the profiles and metadata.\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `+profile '*'`, which removes EXIF, ICC and other profiles. `save()`, `pipe()` and `writer()` call it when the image has no operations.\n\nExample: Strip metadata\n```js\nImage.load(filename).minify().save(target);\n```\n\n### img.limit(type, value)\n\nType: `method`\n\nLimits a resource of the program.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The resource. |\n| `value` | `Number|String` | yes |  | The limit, for example `256MB`. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-limit type value`, for example `limit('memory', '256MB')`. Types and units are those of the program (`memory`, `map`, `disk`…). A number without a unit is in bytes.\n\nExample: Limit memory\n```js\nimg.limit('memory', '256MB').limit('map', '512MB');\n```\n\n### img.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nDraws another image over the picture.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The file of the watermark. |\n| `x` | `Number` | no | `0` | The horizontal offset. |\n| `y` | `Number` | no | `0` | The vertical offset. |\n| `w` | `Number` | no | `0` | The width of the watermark. |\n| `h` | `Number` | no | `0` | The height of the watermark. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `-draw 'image over x,y w,h filename'`. The offset is measured from the top left corner. A width and height of 0 keep the size of the watermark. Single quotes are removed from the file name.\n\nExample: Logo in the corner\n```js\nImage.load(filename)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n### img.command(key, [value], [priority], [escape])\n\nType: `method`\n\nAdds any option of the program.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The option, for example `-sharpen`. |\n| `value` | `String|Number` | no |  | The value. |\n| `priority` | `Number|Boolean` | no | `10` | The position, or `true` to quote the value. |\n| `escape` | `Boolean` | no | `false` | Quote the value. |\n\nReturns: `Image` The same image object, for chaining.\n\nAdds `key value` to the command. `priority` decides the position (lower first, default 10; sizes have 1, gravity 3, crop 4, quality 5, rotate 8). `escape` puts the value in quotes; passing `true` as `priority` also turns on `escape` (with priority 10).\n\nExample: Custom options\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'My photo', true);\n```\n\n### img.make(fn)\n\nType: `method`\n\nApplies a function to the image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Gets the image. |\n\nReturns: `Image` The same image object, for chaining.\n\nCalls `fn(img)` with `this` set to the image. Use it to reuse a set of operations.\n\nExample: Preset\n```js\nfunction avatar(img) {\n\timg.resizecenter(128, 128).quality(90);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n### img.clear()\n\nType: `method`\n\nRemoves all operations.\n\nReturns: `Image` The same image object, for chaining.\n\nEmpties the list of operations. `save()` calls it after the program finishes.\n\nExample: Clear\n```js\nimg.clear().resize(100);\n```\n\n### img.output(type)\n\nType: `method`\n\nSets the image type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The type, for example `png` or `.webp`. |\n\nReturns: `Image` The same image object, for chaining.\n\nSets `img.type` (a leading dot is removed). `pipe()` and `writer()` produce this format when you do not pass one, and `Image.middleware()` is matched with it. `save()` takes the format from the extension of the target file.\n\nExample: Buffer to PNG\n```js\nImage.load(buffer).output('png').resize(100).pipe($.res);\n```\n\n### img.save([filename], [callback])\n\nType: `method`\n\nRuns the program and writes the result to a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `img.filename` | The target file. |\n| `callback` | `Function` | no |  | `function(err, success)`. |\n\nReturns: `Image` The same image object, for chaining.\n\nBuilds the command and runs it. The format comes from the extension of `filename`. Without `filename` the source file is overwritten. A Buffer or stream source is sent to the standard input. The callback gets `(err, success)`, where `success` is `true` or `false`. The operations are cleared afterwards.\n\nExample: Save\n```js\nImage.load(file.path).resize(1024).quality(80).save(PATH.public('photos/' + id + '.jpg'), function(err) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success();\n});\n```\n\n### img.pipe(stream, [type], [options])\n\nType: `method`\n\nRuns the program and sends the result to a stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | A writable stream, for example `$.res`. |\n| `type` | `String` | no | `img.type` | The output format. |\n| `options` | `Object` | no |  | Options of `stream.pipe()`. |\n\nReturns: `Image` The same image object, for chaining.\n\nWrites the output of the program to `stream`. `type` is the output format: `jpg`, `jpeg`, `png`, `gif`, `apng`, `webp`, `heif`, `heic` or `ico`; other values use `img.type`. `options` goes to `stream.pipe()` (for example `{ end: false }`); you can pass it as the second argument. Messages of the program on the standard error are emitted as `error` events on `stream`.\n\nExample: Send to the response\n```js\nfunction preview($) {\n\t$.res.writeHead(200, { 'content-type': 'image/png' });\n\tImage.load(PATH.public('photo.jpg')).resize(300).pipe($.res, 'png');\n}\n```\n\n### img.writer([type])\n\nType: `method`\n\nRuns the program and returns the output stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `img.type` | The output format. |\n\nReturns: `Stream` A readable stream with the result.\n\nStarts the program and returns its readable output (passed through the `Image.middleware()` of the type, when there is one). `type` takes the same values as in `pipe()`.\n\nExample: Collect into a Buffer\n```js\nvar chunks = [];\nvar stream = Image.load(buffer).resize(100, 100).writer('webp');\nstream.on('data', chunk => chunks.push(chunk));\nstream.on('end', function() {\n\tvar output = Buffer.concat(chunks);\n});\n```\n\n### img.measure(callback)\n\nType: `method`\n\nReads the size of the source file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, size)`. |\n\nReturns: `Image` The same image object, for chaining.\n\nReads the header of the source file and calls `callback(err, size)` with `{ width, height }`. For a `.jpg` file without the frame header in its first 40 kB, `size` is `null`. The source must be a file name with the extension `.jpg`, `.png`, `.gif` or `.webp`; other extensions give an error. It does not use the external program.\n\nExample: Measure a file\n```js\nImage.load(PATH.public('photo.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### img.cmd(from, to)\n\nType: `method`\n\nReturns the command line without running it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | The source file or `-`. |\n| `to` | `String` | yes |  | The target file or `-`. |\n\nReturns: `String` The command line.\n\nBuilds the command used by `save()`: the program, the quoted source, the sorted operations and the quoted target. Use `'-'` for the standard input or output. Useful for debugging.\n\nExample: Show the command\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n","entries":[{"type":"class","name":"Image","signature":"Image","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"F.image()","signature":"F.image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"class","name":"Image.Image","signature":"new Image.Image(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.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(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.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"property","name":"img.width","signature":"img.width","since":"","deprecated":false},{"type":"property","name":"img.filename","signature":"img.filename","since":"","deprecated":false},{"type":"property","name":"img.stream","signature":"img.stream","since":"","deprecated":false},{"type":"property","name":"img.type","signature":"img.type","since":"","deprecated":false},{"type":"property","name":"img.shell","signature":"img.shell","since":"","deprecated":false},{"type":"method","name":"img.resize()","signature":"img.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.thumbnail()","signature":"img.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.scale()","signature":"img.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.geometry()","signature":"img.geometry([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.crop()","signature":"img.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.extent()","signature":"img.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.miniature()","signature":"img.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"img.resizecenter()","signature":"img.resizecenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"img.resizealign()","signature":"img.resizealign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"img.align()","signature":"img.align(type)","since":"","deprecated":false},{"type":"method","name":"img.gravity()","signature":"img.gravity(type)","since":"","deprecated":false},{"type":"method","name":"img.quality()","signature":"img.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"img.rotate()","signature":"img.rotate([deg])","since":"","deprecated":false},{"type":"method","name":"img.flip()","signature":"img.flip()","since":"","deprecated":false},{"type":"method","name":"img.flop()","signature":"img.flop()","since":"","deprecated":false},{"type":"method","name":"img.blur()","signature":"img.blur(radius)","since":"","deprecated":false},{"type":"method","name":"img.grayscale()","signature":"img.grayscale()","since":"","deprecated":false},{"type":"method","name":"img.sepia()","signature":"img.sepia()","since":"","deprecated":false},{"type":"method","name":"img.normalize()","signature":"img.normalize()","since":"","deprecated":false},{"type":"method","name":"img.colors()","signature":"img.colors(value)","since":"","deprecated":false},{"type":"method","name":"img.bitdepth()","signature":"img.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"img.background()","signature":"img.background(color)","since":"","deprecated":false},{"type":"method","name":"img.fill()","signature":"img.fill(color)","since":"","deprecated":false},{"type":"method","name":"img.filter()","signature":"img.filter(type)","since":"","deprecated":false},{"type":"method","name":"img.define()","signature":"img.define(value)","since":"","deprecated":false},{"type":"method","name":"img.minify()","signature":"img.minify()","since":"","deprecated":false},{"type":"method","name":"img.limit()","signature":"img.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"img.watermark()","signature":"img.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"img.command()","signature":"img.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"img.make()","signature":"img.make(fn)","since":"","deprecated":false},{"type":"method","name":"img.clear()","signature":"img.clear()","since":"","deprecated":false},{"type":"method","name":"img.output()","signature":"img.output(type)","since":"","deprecated":false},{"type":"method","name":"img.save()","signature":"img.save([filename], [callback])","since":"","deprecated":false},{"type":"method","name":"img.pipe()","signature":"img.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"img.writer()","signature":"img.writer([type])","since":"","deprecated":false},{"type":"method","name":"img.measure()","signature":"img.measure(callback)","since":"","deprecated":false},{"type":"method","name":"img.cmd()","signature":"img.cmd(from, to)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwTD5Lx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/images/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Bilder","summary":"Das globale Objekt Image und alle Methoden von Bildobjekten.","markdown":"---\ntitle: Bilder\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/images/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Bilder\n\n> Das globale Objekt Image und alle Methoden von Bildobjekten.\n\nDas globale Objekt `Image` lädt, verändert, misst und speichert Bilder mit GraphicsMagick oder ImageMagick. Der Leitfaden [Bilder](../../guides/images/) erklärt die Verwendung mit Beispielen; diese Seite ist die genaue Referenz.\n\n## API\n\n### Image\n\nType: `class`\n\nDas globale Bildmodul.\n\n`Image` ist das Bildmodul des Frameworks. Es bietet `Image.load()` zum Erstellen von Bildobjekten, die Funktionen `Image.measure*()`, die die Größe aus dem Dateiheader lesen, `Image.middleware()` und den Konstruktor `Image.Image`. Die Operationen laufen mit dem Programm, das in `$imageconverter` eingestellt ist.\n\nExample: Ein Foto skalieren\n```js\nImage.load(PATH.public('photo.jpg')).resize(800).save(PATH.public('photo-800.jpg'));\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nErstellt ein Bildobjekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Ein Dateiname, ein Buffer oder ein lesbarer Stream. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Das Programm: `gm`, `im` oder `magick`. |\n| `width` | `Number` | no |  | Die bekannte Breite, gespeichert in `img.width`. |\n| `height` | `Number` | no |  | Die bekannte Höhe, gespeichert in `img.height`. |\n\nReturns: `Image` Ein neues Bildobjekt.\n\n`source` ist ein Dateiname, ein `Buffer` oder ein lesbarer Stream. Bei einem Dateinamen ist `img.type` dessen Endung; sonst ist es `jpg`. `converter` ist `gm`, `im` oder `magick` und überschreibt `$imageconverter` für dieses Bild. `width` und `height` werden nur in `img.width` und `img.height` gespeichert; sie werden nicht aus der Datei gelesen.\n\nExample: Aus einer Datei und einem Buffer laden\n```js\nvar a = Image.load(PATH.public('photo.jpg'));\nvar b = Image.load(buffer, 'magick');\n```\n\n### F.image(source, [converter], [width], [height])\n\nType: `method`\n\nDieselbe Funktion wie `Image.load()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Ein Dateiname, ein Buffer oder ein lesbarer Stream. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Das Programm: `gm`, `im` oder `magick`. |\n| `width` | `Number` | no |  | Die bekannte Breite. |\n| `height` | `Number` | no |  | Die bekannte Höhe. |\n\nReturns: `Image` Ein neues Bildobjekt.\n\nEin Alias von `Image.load()` auf dem Framework-Objekt.\n\nExample: Ein Bild laden\n```js\nF.image(filename).grayscale().save(target);\n```\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nDer Konstruktor von Bildobjekten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Ein Dateiname, ein Buffer oder ein lesbarer Stream. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Das Programm: `gm`, `im` oder `magick`. |\n| `width` | `Number` | no |  | Die bekannte Breite. |\n| `height` | `Number` | no |  | Die bekannte Höhe. |\n\n`Image.load()` gibt `new Image.Image(...)` mit denselben Argumenten zurück. Verwende ihn, wenn du `img instanceof Image.Image` prüfen oder eigene Methoden zu `Image.Image.prototype` hinzufügen willst.\n\nExample: Eine Methode hinzufügen\n```js\nImage.Image.prototype.avatar = function() {\n\treturn this.resizecenter(128, 128).quality(90);\n};\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nLiest Breite und Höhe aus dem Header eines Bildes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Eine Endung oder ein MIME-Typ. |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`, `null` für ein JPEG ohne Größenmarker, `undefined` für einen nicht unterstützten Typ.\n\n`type` ist eine Endung mit oder ohne Punkt (`jpg`, `.png`) oder ein MIME-Typ (`image/webp`). Unterstützte Typen sind JPEG, PNG, GIF, WebP, SVG, BMP und PSD. Der Buffer braucht nur den Anfang der Datei. Für andere Typen gibt sie `undefined` zurück. Für einen JPEG-Buffer ohne Größenmarker gibt sie `null` zurück.\n\nExample: Einen hochgeladenen Buffer messen\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\t$.invalid('The image is too wide');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nLiest die Größe eines JPEG-Bildes aus einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }` oder `null`.\n\nSie durchsucht die Marker bis zum Frame-Header. Gibt `null` zurück, wenn der Buffer kein JPEG ist oder der Frame-Header nicht im Buffer liegt (eine beschädigte Datei, ein Segment mit ungültiger Länge oder zu wenig Daten). Übergib genug Daten: Das Framework liest 40 kB.\n\nExample: Messen\n```js\nvar size = Image.measureJPG(buffer);\nconsole.log(size.width, size.height);\n```\n\nExample: Ein JPEG ohne Größe\n```js\nvar buffer = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00]);\nvar size = Image.measureJPG(buffer);\nconsole.log(size); // null: no frame header in the buffer\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nLiest die Größe eines PNG-Bildes aus einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`.\n\nSie liest den IHDR-Header, daher reichen 24 Bytes.\n\nExample: Messen\n```js\nvar size = Image.measurePNG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nLiest die Größe eines GIF-Bildes aus einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`.\n\nSie liest die logische Bildschirmgröße, daher reichen 10 Bytes.\n\nExample: Messen\n```js\nvar size = Image.measureGIF(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nLiest die Größe eines WebP-Bildes aus einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`.\n\nSie liest die Header `VP8 `, `VP8L` und `VP8X`. Gibt `undefined` für andere Daten zurück.\n\nExample: Messen\n```js\nvar size = Image.measureWEBP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nLiest die Größe eines SVG-Bildes aus einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`.\n\nSie liest die ersten Attribute `width=\"...\"` und `height=\"...\"` mit ganzen Zahlen. Gibt `undefined` zurück, wenn es keine gibt.\n\nExample: Messen\n```js\nvar size = Image.measureSVG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nLiest die Größe eines BMP-Bildes aus einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`.\n\nSie liest den BITMAPINFOHEADER.\n\nExample: Messen\n```js\nvar size = Image.measureBMP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nLiest die Größe eines Photoshop-Bildes (PSD) aus einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`.\n\nSie liest den Header der PSD-Datei.\n\nExample: Messen\n```js\nvar size = Image.measurePSD(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nRegistriert einen Stream, der Ergebnisse eines Typs nachbearbeitet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Der Bildtyp, zum Beispiel `png` oder `.jpg`. |\n| `fn` | `Function` | yes |  | Gibt einen Transform-Stream zurück. |\n\n`fn` muss bei jedem Aufruf einen neuen Transform-Stream zurückgeben. Bei `pipe()` und `writer()` läuft die Ausgabe des Programms durch ihn, bevor sie dich erreicht, und `type` wird mit dem Ausgabeformat verglichen. Bei `save()` mit einem Callback wird die gespeicherte Datei durch ihn gelesen und erneut geschrieben, bevor der Callback läuft; dort wird `type` mit `img.type` verglichen (der Endung der Quelle oder dem Wert von `output()`). Ein führender Punkt in `type` wird entfernt. Eine Funktion pro Typ; ein neuer Aufruf ersetzt sie.\n\nExample: PNG-Ergebnisse durch einen Stream leiten\n```js\nvar Transform = require('stream').Transform;\n\nImage.middleware('png', function() {\n\treturn new Transform({\n\t\ttransform: function(chunk, encoding, next) {\n\t\t\tnext(null, chunk);\n\t\t}\n\t});\n});\n```\n\n### img.width\n\nType: `property`\n\nDie an `Image.load()` übergebene Breite.\n\nReturns: `Number`\n\nDas dritte Argument von `Image.load()` oder `undefined`. Sie wird nicht aus der Datei gelesen; verwende dafür `img.measure()`. `img.height` enthält auf dieselbe Weise das vierte Argument.\n\nExample: Bekannte Größe\n```js\nvar img = Image.load(file.path, null, file.width, file.height);\nif (img.width > 1000)\n\timg.resize(1000);\n```\n\n### img.filename\n\nType: `property`\n\nDer Name der Quelldatei.\n\nReturns: `String`\n\nDer an `Image.load()` übergebene Dateiname oder `null`, wenn die Quelle ein Buffer oder ein Stream ist.\n\n### img.stream\n\nType: `property`\n\nDer Quell-Buffer oder -Stream.\n\nReturns: `Buffer|Stream`\n\nDer an `Image.load()` übergebene Buffer oder lesbare Stream oder `null`, wenn die Quelle ein Dateiname ist. Er wird in die Standardeingabe des Programms geschrieben, wenn das Bild gespeichert oder gepipet wird.\n\n### img.type\n\nType: `property`\n\nDer Bildtyp.\n\nReturns: `String`\n\nDie Endung der Quelldatei in Kleinbuchstaben ohne Punkt (`jpg`, `png`…) oder `jpg` bei einem Buffer oder Stream. `output()` ändert ihn. `pipe()` und `writer()` verwenden ihn als Ausgabeformat, wenn du keines übergibst, und Handler von `Image.middleware()` werden mit ihm verglichen.\n\n### img.shell\n\nType: `property`\n\nDas Programm, das das Bild verarbeitet.\n\nReturns: `String`\n\n`gm`, `im` oder `magick`: das zweite Argument von `Image.load()`, sonst `CONF.$imageconverter`. `gm` führt `gm convert` aus, `im` führt `convert` aus und `magick` führt `magick` aus. Du kannst es ändern, bevor du das Bild speicherst.\n\n### img.resize([w], [h], [options])\n\nType: `method`\n\nSkaliert das Bild.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | Die Breite in Pixeln oder ein Prozentwert wie `'50%'`. Leer, um das Seitenverhältnis beizubehalten. |\n| `h` | `Number|String` | no |  | Die Höhe in Pixeln oder ein Prozentwert. Leer, um das Seitenverhältnis beizubehalten. |\n| `options` | `String` | no |  | Ein Suffix der Größe: `!` ignoriert das Seitenverhältnis, `^` füllt den Rahmen, `>` verkleinert nur, `<` vergrößert nur. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-resize WxH` hinzu. Das Bild passt in den Rahmen und behält sein Seitenverhältnis, sofern `options` nichts anderes angibt. Nur mit `w` folgt die Höhe dem Verhältnis, nur mit `h` die Breite.\n\nExample: Skalieren\n```js\nimg.resize(800, 600);   // into 800x600\nimg.resize(800);        // width 800\nimg.resize(null, 600);  // height 600\nimg.resize(200, 200, '!'); // exactly 200x200\nimg.resize('50%');      // half size\n```\n\n### img.thumbnail([w], [h], [options])\n\nType: `method`\n\nSkaliert das Bild für eine kleine Vorschau.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | Die Breite in Pixeln oder ein Prozentwert wie `'50%'`. Leer, um das Seitenverhältnis beizubehalten. |\n| `h` | `Number|String` | no |  | Die Höhe in Pixeln oder ein Prozentwert. Leer, um das Seitenverhältnis beizubehalten. |\n| `options` | `String` | no |  | Ein Suffix der Größe: `!` ignoriert das Seitenverhältnis, `^` füllt den Rahmen, `>` verkleinert nur, `<` vergrößert nur. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-thumbnail WxH` hinzu: eine Skalierung, die auch die Profile entfernt, sodass die Datei kleiner wird. Die Argumente sind dieselben wie bei `resize()`.\n\nExample: Vorschaubild\n```js\nImage.load(filename).thumbnail(150, 150).save(target);\n```\n\n### img.scale([w], [h], [options])\n\nType: `method`\n\nSkaliert das Bild schnell ohne Filterung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | Die Breite in Pixeln oder ein Prozentwert wie `'50%'`. Leer, um das Seitenverhältnis beizubehalten. |\n| `h` | `Number|String` | no |  | Die Höhe in Pixeln oder ein Prozentwert. Leer, um das Seitenverhältnis beizubehalten. |\n| `options` | `String` | no |  | Ein Suffix der Größe: `!` ignoriert das Seitenverhältnis, `^` füllt den Rahmen, `>` verkleinert nur, `<` vergrößert nur. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-scale WxH` hinzu. Schneller als `resize()`, aber mit geringerer Qualität. Die Argumente sind dieselben wie bei `resize()`.\n\nExample: Skalieren\n```js\nimg.scale(64, 64);\n```\n\n### img.geometry([w], [h], [options])\n\nType: `method`\n\nFügt die Option `-geometry` hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | Die Breite in Pixeln oder ein Prozentwert wie `'50%'`. Leer, um das Seitenverhältnis beizubehalten. |\n| `h` | `Number|String` | no |  | Die Höhe in Pixeln oder ein Prozentwert. Leer, um das Seitenverhältnis beizubehalten. |\n| `options` | `String` | no |  | Ein Suffix der Größe: `!` ignoriert das Seitenverhältnis, `^` füllt den Rahmen, `>` verkleinert nur, `<` vergrößert nur. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-geometry WxH` mit dem optionalen Suffix hinzu. Das Programm verwendet es als bevorzugte Größe und Verschiebung.\n\nExample: Geometrie\n```js\nimg.geometry(300, 200, '!');\n```\n\n### img.crop(w, h, [x], [y])\n\nType: `method`\n\nSchneidet einen Bereich des Bildes aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Die Breite des Bereichs. |\n| `h` | `Number` | yes |  | Die Höhe des Bereichs. |\n| `x` | `Number` | no | `0` | Die horizontale Verschiebung. |\n| `y` | `Number` | no | `0` | Die vertikale Verschiebung. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-crop WxH+X+Y` hinzu. Die Verschiebung wird von der Ecke aus gemessen, die `align()` festlegt (standardmäßig oben links).\n\nExample: Zuschneiden\n```js\nimg.crop(400, 300, 50, 20);\n\n// The centre\nimg.align('center').crop(400, 300);\n```\n\n### img.extent([w], [h], [x], [y])\n\nType: `method`\n\nLegt die Größe der Leinwand fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Die Breite der Leinwand. |\n| `h` | `Number` | no |  | Die Höhe der Leinwand. |\n| `x` | `Number` | no |  | Die horizontale Verschiebung, kann negativ sein. |\n| `y` | `Number` | no |  | Die vertikale Verschiebung, kann negativ sein. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-extent WxH` mit einer optionalen Verschiebung hinzu. Eine größere Leinwand wird mit der Hintergrundfarbe gefüllt, eine kleinere schneidet das Bild ab. Die Position folgt `align()`.\n\nExample: Quadratische Leinwand\n```js\nimg.resize(500, 500).background('white').align('center').extent(500, 500);\n```\n\n### img.miniature(w, h, [color], [filter])\n\nType: `method`\n\nPasst das Bild in einen Rahmen ein und füllt den Rest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Die Breite. |\n| `h` | `Number` | yes |  | Die Höhe. |\n| `color` | `String` | no | `'white'` | Die Farbe des freien Bereichs. |\n| `filter` | `String` | no | `'Hamming'` | Der Skalierungsfilter. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nEine Abkürzung für `thumbnail(w, h).background(color).align('center').extent(w, h)`. Das Ergebnis ist genau `w`x`h` groß und zeigt das ganze Bild. `filter` ist der Skalierungsfilter von `thumbnail()`.\n\nExample: Produktfoto\n```js\nImage.load(filename).miniature(300, 300, '#F0F0F0').save(target);\n```\n\n### img.resizecenter(w, h, [color])\n\nType: `method`\n\nFüllt einen Rahmen und schneidet die Mitte aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Die Breite. |\n| `h` | `Number` | yes |  | Die Höhe. |\n| `color` | `String` | no | `'white'` | Die Hintergrundfarbe. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nEine Abkürzung für `resize(w, h, '^').background(color).align('center').crop(w, h)`. Das Ergebnis ist `w`x`h` groß und das Bild bedeckt es vollständig.\n\nExample: Abdecken\n```js\nImage.load(filename).resizecenter(1200, 630).save(target);\n```\n\n### img.resizealign(w, h, [align], [color])\n\nType: `method`\n\nFüllt einen Rahmen und schneidet an einer Seite zu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Die Breite. |\n| `h` | `Number` | yes |  | Die Höhe. |\n| `align` | `String` | no | `'center'` | Wo zugeschnitten wird: `top`, `bottom`, `left`, `center`… |\n| `color` | `String` | no | `'white'` | Die Hintergrundfarbe. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nEine Abkürzung für `resize(w, h, '^').background(color).align(align).crop(w, h)`. `align` nimmt die Werte von `align()` an.\n\nExample: Avatar\n```js\nImage.load(filename).resizealign(200, 200, 'top').save(target);\n```\n\n### img.align(type)\n\nType: `method`\n\nLegt die Ausrichtung (Gravity) für crop und extent fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Die Position. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-gravity` hinzu. Erlaubte Werte: `'top left'` (NorthWest), `'top'` (North), `'top right'` (NorthEast), `'left'` (West), `'center'` oder `'middle'` (Center), `'right'` (East), `'bottom left'` (SouthWest), `'bottom'` (South), `'bottom right'` (SouthEast). Die Reihenfolge der Wörter spielt keine Rolle (`'left top'`), und `'center left'` bedeutet `left`. Andere Werte werden unverändert übergeben, zum Beispiel `'NorthEast'`.\n\nExample: Ausrichten\n```js\nimg.align('bottom right').crop(400, 300);\n```\n\n### img.gravity(type)\n\nType: `method`\n\nDieselbe Methode wie `align()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Die Position. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nEin Alias von `align()`.\n\nExample: Gravity\n```js\nimg.gravity('NorthWest');\n```\n\n### img.quality([percentage])\n\nType: `method`\n\nSetzt die Kompressionsqualität.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | Die Qualität. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-quality` hinzu. Bei JPEG und WebP ist es die Qualität von 1 bis 100; ein leerer Wert bedeutet 80.\n\nExample: Qualität\n```js\nimg.quality(70);\n```\n\n### img.rotate([deg])\n\nType: `method`\n\nDreht das Bild.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | no | `0` | Der Winkel in Grad. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-rotate` hinzu. Der Winkel ist in Grad im Uhrzeigersinn. Bei Winkeln, die keine Vielfachen von 90 sind, werden die Ecken mit der Hintergrundfarbe gefüllt.\n\nExample: Drehen\n```js\nimg.background('white').rotate(45);\n```\n\n### img.flip()\n\nType: `method`\n\nSpiegelt das Bild vertikal.\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-flip` hinzu (von oben nach unten).\n\nExample: Flip\n```js\nimg.flip();\n```\n\n### img.flop()\n\nType: `method`\n\nSpiegelt das Bild horizontal.\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-flop` hinzu (von links nach rechts).\n\nExample: Flop\n```js\nimg.flop();\n```\n\n### img.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 oder `radiusxsigma`. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-blur` hinzu. Der Wert ist der Radius oder `radiusxsigma` als String (`'0x8'`).\n\nExample: Weichzeichnen\n```js\nimg.blur(5);\nimg.blur('0x8');\n```\n\n### img.grayscale()\n\nType: `method`\n\nWandelt das Bild in Graustufen um.\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-colorspace Gray` hinzu.\n\nExample: Grau\n```js\nimg.grayscale();\n```\n\n### img.sepia()\n\nType: `method`\n\nGibt dem Bild einen Sepiaton.\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-modulate 115,0,100 -colorize 7,21,50` hinzu.\n\nExample: Sepia\n```js\nimg.sepia();\n```\n\n### img.normalize()\n\nType: `method`\n\nStreckt den Kontrast.\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-normalize` hinzu: Die Farben werden über den gesamten Bereich verteilt.\n\nExample: Normalisieren\n```js\nimg.normalize();\n```\n\n### img.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 Bildobjekt, für Verkettung.\n\nFügt `-colors` hinzu.\n\nExample: Palette\n```js\nimg.output('png').colors(64);\n```\n\n### img.bitdepth(value)\n\nType: `method`\n\nLegt die Bittiefe fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bits pro Kanal, zum Beispiel 8. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-depth` hinzu.\n\nExample: Tiefe\n```js\nimg.bitdepth(8);\n```\n\n### img.background(color)\n\nType: `method`\n\nSetzt die Hintergrundfarbe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Die Farbe. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-background color` und danach `-extent 0x0` hinzu, sodass die Farbe gesetzt wird, bevor die Leinwand erweitert wird. Die Farbe füllt neue Bereiche, die durch `extent()`, `rotate()` und die Skalierungshelfer entstehen. Jede Farbe des Programms funktioniert: `white`, `#FF0000`, `none` für transparent.\n\nExample: Hintergrund\n```js\nimg.background('#FFFFFF').extent(800, 800);\n```\n\n### img.fill(color)\n\nType: `method`\n\nLegt die Füllfarbe fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Die Farbe. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-fill` hinzu. Wird von zeichnenden Operationen verwendet, zum Beispiel `-colorize` oder deinen eigenen Optionen über `command()`.\n\nExample: Füllung\n```js\nimg.fill('red').command('-colorize', '30');\n```\n\n### img.filter(type)\n\nType: `method`\n\nLegt den Skalierungsfilter fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Der Name des Filters. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-filter` hinzu, zum Beispiel `'Lanczos'`, `'Hamming'`, `'Box'` oder `'Triangle'`. Es wird immer vor `-resize`, `-thumbnail` und `-scale` gesetzt, gilt also für sie, egal ob du es vor oder nach `resize()`, `thumbnail()` oder `scale()` aufrufst.\n\nExample: Filter\n```js\nimg.resize(400).filter('Lanczos');\n```\n\nExample: Der Befehl\n```js\nImage.load('photo.jpg').filter('Lanczos').resize(200, 200).cmd('photo.jpg', 'small.jpg');\n// gm convert 'photo.jpg' -filter 'Lanczos' -resize '200x200' 'small.jpg'\n```\n\n### img.define(value)\n\nType: `method`\n\nÜbergibt eine Option des Coders.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Die Definition `format:key=value`. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-define` hinzu, zum Beispiel `'jpeg:extent=200kb'` oder `'png:compression-level=9'`.\n\nExample: Define\n```js\nimg.define('jpeg:extent=200kb');\n```\n\n### img.minify()\n\nType: `method`\n\nEntfernt die Profile und Metadaten.\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `+profile '*'` hinzu, was EXIF-, ICC- und andere Profile entfernt. `save()`, `pipe()` und `writer()` rufen es auf, wenn das Bild keine Operationen hat.\n\nExample: Metadaten entfernen\n```js\nImage.load(filename).minify().save(target);\n```\n\n### img.limit(type, value)\n\nType: `method`\n\nBegrenzt eine Ressource des Programms.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Die Ressource. |\n| `value` | `Number|String` | yes |  | Das Limit, zum Beispiel `256MB`. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-limit type value` hinzu, zum Beispiel `limit('memory', '256MB')`. Typen und Einheiten sind die des Programms (`memory`, `map`, `disk`…). Eine Zahl ohne Einheit ist in Bytes.\n\nExample: Speicher begrenzen\n```js\nimg.limit('memory', '256MB').limit('map', '512MB');\n```\n\n### img.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nZeichnet ein anderes Bild über das Bild.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Die Datei des Wasserzeichens. |\n| `x` | `Number` | no | `0` | Die horizontale Verschiebung. |\n| `y` | `Number` | no | `0` | Die vertikale Verschiebung. |\n| `w` | `Number` | no | `0` | Die Breite des Wasserzeichens. |\n| `h` | `Number` | no | `0` | Die Höhe des Wasserzeichens. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `-draw 'image over x,y w,h filename'` hinzu. Die Verschiebung wird von der oberen linken Ecke aus gemessen. Breite und Höhe 0 behalten die Größe des Wasserzeichens. Einfache Anführungszeichen werden aus dem Dateinamen entfernt.\n\nExample: Logo in der Ecke\n```js\nImage.load(filename)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n### img.command(key, [value], [priority], [escape])\n\nType: `method`\n\nFügt eine beliebige Option des Programms 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. |\n| `priority` | `Number|Boolean` | no | `10` | Die Position oder `true`, um den Wert in Anführungszeichen zu setzen. |\n| `escape` | `Boolean` | no | `false` | Den Wert in Anführungszeichen setzen. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nFügt `key value` zum Befehl hinzu. `priority` bestimmt die Position (niedrigere zuerst, Standard 10; Größen haben 1, Gravity 3, Crop 4, Qualität 5, Rotation 8). `escape` setzt den Wert in Anführungszeichen; `true` als `priority` schaltet ebenfalls `escape` ein (mit Priorität 10).\n\nExample: Eigene Optionen\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'My photo', true);\n```\n\n### img.make(fn)\n\nType: `method`\n\nWendet eine Funktion auf das Bild an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Erhält das Bild. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nRuft `fn(img)` auf, wobei `this` das Bild ist. Verwende es, um eine Reihe von Operationen wiederzuverwenden.\n\nExample: Voreinstellung\n```js\nfunction avatar(img) {\n\timg.resizecenter(128, 128).quality(90);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n### img.clear()\n\nType: `method`\n\nEntfernt alle Operationen.\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nLeert die Liste der Operationen. `save()` ruft es auf, nachdem das Programm fertig ist.\n\nExample: Leeren\n```js\nimg.clear().resize(100);\n```\n\n### img.output(type)\n\nType: `method`\n\nLegt den Bildtyp fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Der Typ, zum Beispiel `png` oder `.webp`. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nSetzt `img.type` (ein führender Punkt wird entfernt). `pipe()` und `writer()` erzeugen dieses Format, wenn du keines übergibst, und `Image.middleware()` wird damit verglichen. `save()` nimmt das Format aus der Endung der Zieldatei.\n\nExample: Buffer zu PNG\n```js\nImage.load(buffer).output('png').resize(100).pipe($.res);\n```\n\n### img.save([filename], [callback])\n\nType: `method`\n\nFührt das Programm aus und schreibt das Ergebnis in eine Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `img.filename` | Die Zieldatei. |\n| `callback` | `Function` | no |  | `function(err, success)`. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nBaut den Befehl und führt ihn aus. Das Format ergibt sich aus der Endung von `filename`. Ohne `filename` wird die Quelldatei überschrieben. Eine Buffer- oder Stream-Quelle wird an die Standardeingabe gesendet. Der Callback erhält `(err, success)`, wobei `success` `true` oder `false` ist. Die Operationen werden danach geleert.\n\nExample: Speichern\n```js\nImage.load(file.path).resize(1024).quality(80).save(PATH.public('photos/' + id + '.jpg'), function(err) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success();\n});\n```\n\n### img.pipe(stream, [type], [options])\n\nType: `method`\n\nFührt das Programm aus und sendet das Ergebnis an einen Stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Ein beschreibbarer Stream, zum Beispiel `$.res`. |\n| `type` | `String` | no | `img.type` | Das Ausgabeformat. |\n| `options` | `Object` | no |  | Optionen von `stream.pipe()`. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nSchreibt die Ausgabe des Programms in `stream`. `type` ist das Ausgabeformat: `jpg`, `jpeg`, `png`, `gif`, `apng`, `webp`, `heif`, `heic` oder `ico`; andere Werte verwenden `img.type`. `options` geht an `stream.pipe()` (zum Beispiel `{ end: false }`); du kannst es als zweites Argument übergeben. Meldungen des Programms auf der Standardfehlerausgabe werden als `error`-Ereignisse auf `stream` ausgelöst.\n\nExample: An die Antwort senden\n```js\nfunction preview($) {\n\t$.res.writeHead(200, { 'content-type': 'image/png' });\n\tImage.load(PATH.public('photo.jpg')).resize(300).pipe($.res, 'png');\n}\n```\n\n### img.writer([type])\n\nType: `method`\n\nFührt das Programm aus und gibt den Ausgabestream zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `img.type` | Das Ausgabeformat. |\n\nReturns: `Stream` Ein lesbarer Stream mit dem Ergebnis.\n\nStartet das Programm und gibt seine lesbare Ausgabe zurück (durch die `Image.middleware()` des Typs geleitet, falls vorhanden). `type` nimmt dieselben Werte an wie bei `pipe()`.\n\nExample: In einem Buffer sammeln\n```js\nvar chunks = [];\nvar stream = Image.load(buffer).resize(100, 100).writer('webp');\nstream.on('data', chunk => chunks.push(chunk));\nstream.on('end', function() {\n\tvar output = Buffer.concat(chunks);\n});\n```\n\n### img.measure(callback)\n\nType: `method`\n\nLiest die Größe der Quelldatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, size)`. |\n\nReturns: `Image` Dasselbe Bildobjekt, für Verkettung.\n\nLiest den Header der Quelldatei und ruft `callback(err, size)` mit `{ width, height }` auf. Bei einer `.jpg`-Datei ohne Frame-Header in ihren ersten 40 kB ist `size` gleich `null`. Die Quelle muss ein Dateiname mit der Endung `.jpg`, `.png`, `.gif` oder `.webp` sein; andere Endungen ergeben einen Fehler. Das externe Programm wird nicht verwendet.\n\nExample: Eine Datei messen\n```js\nImage.load(PATH.public('photo.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### img.cmd(from, to)\n\nType: `method`\n\nGibt die Befehlszeile zurück, ohne sie auszuführen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | Die Quelldatei oder `-`. |\n| `to` | `String` | yes |  | Die Zieldatei oder `-`. |\n\nReturns: `String` Die Befehlszeile.\n\nBaut den Befehl, den `save()` verwendet: das Programm, die Quelle in Anführungszeichen, die sortierten Operationen und das Ziel in Anführungszeichen. Verwende `'-'` für die Standardeingabe oder -ausgabe. Nützlich zum Debuggen.\n\nExample: Den Befehl anzeigen\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n","entries":[{"type":"class","name":"Image","signature":"Image","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"F.image()","signature":"F.image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"class","name":"Image.Image","signature":"new Image.Image(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.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(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.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"property","name":"img.width","signature":"img.width","since":"","deprecated":false},{"type":"property","name":"img.filename","signature":"img.filename","since":"","deprecated":false},{"type":"property","name":"img.stream","signature":"img.stream","since":"","deprecated":false},{"type":"property","name":"img.type","signature":"img.type","since":"","deprecated":false},{"type":"property","name":"img.shell","signature":"img.shell","since":"","deprecated":false},{"type":"method","name":"img.resize()","signature":"img.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.thumbnail()","signature":"img.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.scale()","signature":"img.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.geometry()","signature":"img.geometry([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.crop()","signature":"img.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.extent()","signature":"img.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.miniature()","signature":"img.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"img.resizecenter()","signature":"img.resizecenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"img.resizealign()","signature":"img.resizealign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"img.align()","signature":"img.align(type)","since":"","deprecated":false},{"type":"method","name":"img.gravity()","signature":"img.gravity(type)","since":"","deprecated":false},{"type":"method","name":"img.quality()","signature":"img.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"img.rotate()","signature":"img.rotate([deg])","since":"","deprecated":false},{"type":"method","name":"img.flip()","signature":"img.flip()","since":"","deprecated":false},{"type":"method","name":"img.flop()","signature":"img.flop()","since":"","deprecated":false},{"type":"method","name":"img.blur()","signature":"img.blur(radius)","since":"","deprecated":false},{"type":"method","name":"img.grayscale()","signature":"img.grayscale()","since":"","deprecated":false},{"type":"method","name":"img.sepia()","signature":"img.sepia()","since":"","deprecated":false},{"type":"method","name":"img.normalize()","signature":"img.normalize()","since":"","deprecated":false},{"type":"method","name":"img.colors()","signature":"img.colors(value)","since":"","deprecated":false},{"type":"method","name":"img.bitdepth()","signature":"img.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"img.background()","signature":"img.background(color)","since":"","deprecated":false},{"type":"method","name":"img.fill()","signature":"img.fill(color)","since":"","deprecated":false},{"type":"method","name":"img.filter()","signature":"img.filter(type)","since":"","deprecated":false},{"type":"method","name":"img.define()","signature":"img.define(value)","since":"","deprecated":false},{"type":"method","name":"img.minify()","signature":"img.minify()","since":"","deprecated":false},{"type":"method","name":"img.limit()","signature":"img.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"img.watermark()","signature":"img.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"img.command()","signature":"img.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"img.make()","signature":"img.make(fn)","since":"","deprecated":false},{"type":"method","name":"img.clear()","signature":"img.clear()","since":"","deprecated":false},{"type":"method","name":"img.output()","signature":"img.output(type)","since":"","deprecated":false},{"type":"method","name":"img.save()","signature":"img.save([filename], [callback])","since":"","deprecated":false},{"type":"method","name":"img.pipe()","signature":"img.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"img.writer()","signature":"img.writer([type])","since":"","deprecated":false},{"type":"method","name":"img.measure()","signature":"img.measure(callback)","since":"","deprecated":false},{"type":"method","name":"img.cmd()","signature":"img.cmd(from, to)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwTD5Lx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/images/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Imágenes","summary":"El global Image y todos los métodos de los objetos de imagen.","markdown":"---\ntitle: \"Imágenes\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/images/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Imágenes\n\n> El global Image y todos los métodos de los objetos de imagen.\n\nEl global `Image` carga, modifica, mide y guarda imágenes con GraphicsMagick o ImageMagick. La guía [Imágenes](../../guides/images/) explica cómo usarlo con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### Image\n\nType: `class`\n\nEl módulo global de imágenes.\n\n`Image` es el módulo de imágenes del framework. Tiene `Image.load()` para crear objetos de imagen, las funciones `Image.measure*()` que leen el tamaño de la cabecera de un archivo, `Image.middleware()` y el constructor `Image.Image`. Las operaciones se ejecutan con el programa definido en `$imageconverter`.\n\nExample: Redimensionar una foto\n```js\nImage.load(PATH.public('photo.jpg')).resize(800).save(PATH.public('photo-800.jpg'));\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nCrea un objeto de imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Un nombre de archivo, un Buffer o un stream de lectura. |\n| `converter` | `String` | no | `CONF.$imageconverter` | El programa: `gm`, `im` o `magick`. |\n| `width` | `Number` | no |  | El ancho conocido, guardado en `img.width`. |\n| `height` | `Number` | no |  | El alto conocido, guardado en `img.height`. |\n\nReturns: `Image` Un nuevo objeto de imagen.\n\n`source` es un nombre de archivo, un `Buffer` o un stream de lectura. Con un nombre de archivo, `img.type` es su extensión; en otro caso es `jpg`. `converter` es `gm`, `im` o `magick` y sobrescribe `$imageconverter` para esta imagen. `width` y `height` solo se guardan en `img.width` y `img.height`; no se leen del archivo.\n\nExample: Cargar desde un archivo y un buffer\n```js\nvar a = Image.load(PATH.public('photo.jpg'));\nvar b = Image.load(buffer, 'magick');\n```\n\n### F.image(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|Buffer|Stream` | yes |  | Un nombre de archivo, un Buffer o un stream de lectura. |\n| `converter` | `String` | no | `CONF.$imageconverter` | El programa: `gm`, `im` o `magick`. |\n| `width` | `Number` | no |  | El ancho conocido. |\n| `height` | `Number` | no |  | El alto conocido. |\n\nReturns: `Image` Un nuevo objeto de imagen.\n\nUn alias de `Image.load()` en el objeto del framework.\n\nExample: Cargar una imagen\n```js\nF.image(filename).grayscale().save(target);\n```\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nEl constructor de los objetos de imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Un nombre de archivo, un Buffer o un stream de lectura. |\n| `converter` | `String` | no | `CONF.$imageconverter` | El programa: `gm`, `im` o `magick`. |\n| `width` | `Number` | no |  | El ancho conocido. |\n| `height` | `Number` | no |  | El alto conocido. |\n\n`Image.load()` devuelve `new Image.Image(...)` con los mismos argumentos. Úsalo cuando quieras comprobar `img instanceof Image.Image` o añadir tus propios métodos a `Image.Image.prototype`.\n\nExample: Añadir un método\n```js\nImage.Image.prototype.avatar = function() {\n\treturn this.resizecenter(128, 128).quality(90);\n};\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nLee el ancho y el alto de la cabecera de una imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Una extensión o un tipo MIME. |\n| `buffer` | `Buffer` | yes |  | El comienzo del archivo. |\n\nReturns: `Object` `{ width, height }`, `null` para un JPEG sin marcador de tamaño, `undefined` para un tipo no soportado.\n\n`type` es una extensión con o sin punto (`jpg`, `.png`) o un tipo MIME (`image/webp`). Los tipos soportados son JPEG, PNG, GIF, WebP, SVG, BMP y PSD. El buffer solo necesita el comienzo del archivo. Para otros tipos devuelve `undefined`. Para un buffer JPEG sin marcador de tamaño devuelve `null`.\n\nExample: Medir un buffer subido\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\t$.invalid('The image is too wide');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nLee el tamaño de una imagen JPEG desde un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }` o `null`.\n\nRecorre los marcadores hasta la cabecera del frame. Devuelve `null` cuando el buffer no es un JPEG o cuando la cabecera del frame no está en el buffer (un archivo dañado, un segmento con una longitud no válida o demasiado pocos datos). Pasa suficientes datos: el framework lee 40 kB.\n\nExample: Medir\n```js\nvar size = Image.measureJPG(buffer);\nconsole.log(size.width, size.height);\n```\n\nExample: Un JPEG sin el tamaño\n```js\nvar buffer = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00]);\nvar size = Image.measureJPG(buffer);\nconsole.log(size); // null: no frame header in the buffer\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nLee el tamaño de una imagen PNG desde un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`.\n\nLee la cabecera IHDR, así que bastan 24 bytes.\n\nExample: Medir\n```js\nvar size = Image.measurePNG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nLee el tamaño de una imagen GIF desde un buffer.\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, así que bastan 10 bytes.\n\nExample: Medir\n```js\nvar size = Image.measureGIF(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nLee el tamaño de una imagen WebP desde un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`.\n\nLee las cabeceras `VP8 `, `VP8L` y `VP8X`. Devuelve `undefined` para otros datos.\n\nExample: Medir\n```js\nvar size = Image.measureWEBP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nLee el tamaño de una imagen SVG desde un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`.\n\nLee los primeros atributos `width=\"...\"` y `height=\"...\"` con números enteros. Devuelve `undefined` cuando no hay ninguno.\n\nExample: Medir\n```js\nvar size = Image.measureSVG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nLee el tamaño de una imagen BMP desde un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`.\n\nLee el BITMAPINFOHEADER.\n\nExample: Medir\n```js\nvar size = Image.measureBMP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nLee el tamaño de una imagen de Photoshop (PSD) desde un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`.\n\nLee la cabecera del archivo PSD.\n\nExample: Medir\n```js\nvar size = Image.measurePSD(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nRegistra un stream que posprocesa los resultados de un tipo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El tipo de imagen, por ejemplo `png` o `.jpg`. |\n| `fn` | `Function` | yes |  | Devuelve un stream Transform. |\n\n`fn` debe devolver un nuevo stream Transform cada vez que se llama. Con `pipe()` y `writer()` la salida del programa pasa por él antes de llegarte, y `type` se compara con el formato de salida. Con `save()` y un callback, el archivo guardado se lee a través de él y se vuelve a escribir antes de que se ejecute el callback; ahí `type` se compara con `img.type` (la extensión del origen o el valor de `output()`). Se elimina un punto inicial en `type`. Una función por tipo; una nueva llamada la reemplaza.\n\nExample: Pasar los resultados PNG por un stream\n```js\nvar Transform = require('stream').Transform;\n\nImage.middleware('png', function() {\n\treturn new Transform({\n\t\ttransform: function(chunk, encoding, next) {\n\t\t\tnext(null, chunk);\n\t\t}\n\t});\n});\n```\n\n### img.width\n\nType: `property`\n\nEl ancho pasado a `Image.load()`.\n\nReturns: `Number`\n\nEl tercer argumento de `Image.load()`, o `undefined`. No se lee del archivo; usa `img.measure()` para eso. `img.height` guarda el cuarto argumento de la misma forma.\n\nExample: Tamaño conocido\n```js\nvar img = Image.load(file.path, null, file.width, file.height);\nif (img.width > 1000)\n\timg.resize(1000);\n```\n\n### img.filename\n\nType: `property`\n\nEl nombre del archivo de origen.\n\nReturns: `String`\n\nEl nombre de archivo dado a `Image.load()`, o `null` cuando el origen es un Buffer o un stream.\n\n### img.stream\n\nType: `property`\n\nEl Buffer o stream de origen.\n\nReturns: `Buffer|Stream`\n\nEl Buffer o stream de lectura dado a `Image.load()`, o `null` cuando el origen es un nombre de archivo. Se escribe en la entrada estándar del programa cuando la imagen se guarda o se envía por pipe.\n\n### img.type\n\nType: `property`\n\nEl tipo de imagen.\n\nReturns: `String`\n\nLa extensión del archivo de origen en minúsculas y sin el punto (`jpg`, `png`…), o `jpg` para un Buffer o un stream. `output()` la cambia. `pipe()` y `writer()` la usan como formato de salida cuando no pasas uno, y los handlers de `Image.middleware()` se comparan con ella.\n\n### img.shell\n\nType: `property`\n\nEl programa que procesa la imagen.\n\nReturns: `String`\n\n`gm`, `im` o `magick`: el segundo argumento de `Image.load()`, si no `CONF.$imageconverter`. `gm` ejecuta `gm convert`, `im` ejecuta `convert` y `magick` ejecuta `magick`. Puedes cambiarlo antes de guardar la imagen.\n\n### img.resize([w], [h], [options])\n\nType: `method`\n\nRedimensiona la imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | El ancho en píxeles, o un porcentaje como `'50%'`. Vacío para mantener la proporción. |\n| `h` | `Number|String` | no |  | El alto en píxeles, o un porcentaje. Vacío para mantener la proporción. |\n| `options` | `String` | no |  | Un sufijo del tamaño: `!` ignora la proporción, `^` rellena la caja, `>` solo reduce, `<` solo amplía. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-resize WxH`. La imagen cabe en la caja y mantiene su relación de aspecto, salvo que `options` indique otra cosa. Con solo `w` el alto sigue la proporción; con solo `h`, el ancho.\n\nExample: Redimensionar\n```js\nimg.resize(800, 600);   // into 800x600\nimg.resize(800);        // width 800\nimg.resize(null, 600);  // height 600\nimg.resize(200, 200, '!'); // exactly 200x200\nimg.resize('50%');      // half size\n```\n\n### img.thumbnail([w], [h], [options])\n\nType: `method`\n\nRedimensiona la imagen para una vista previa pequeña.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | El ancho en píxeles, o un porcentaje como `'50%'`. Vacío para mantener la proporción. |\n| `h` | `Number|String` | no |  | El alto en píxeles, o un porcentaje. Vacío para mantener la proporción. |\n| `options` | `String` | no |  | Un sufijo del tamaño: `!` ignora la proporción, `^` rellena la caja, `>` solo reduce, `<` solo amplía. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-thumbnail WxH`: un redimensionado que además elimina los perfiles, así el archivo es más pequeño. Los argumentos son los mismos que en `resize()`.\n\nExample: Miniatura\n```js\nImage.load(filename).thumbnail(150, 150).save(target);\n```\n\n### img.scale([w], [h], [options])\n\nType: `method`\n\nRedimensiona la imagen rápidamente sin filtrado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | El ancho en píxeles, o un porcentaje como `'50%'`. Vacío para mantener la proporción. |\n| `h` | `Number|String` | no |  | El alto en píxeles, o un porcentaje. Vacío para mantener la proporción. |\n| `options` | `String` | no |  | Un sufijo del tamaño: `!` ignora la proporción, `^` rellena la caja, `>` solo reduce, `<` solo amplía. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-scale WxH`. Más rápido que `resize()` pero con menor calidad. Los argumentos son los mismos que en `resize()`.\n\nExample: Escalar\n```js\nimg.scale(64, 64);\n```\n\n### img.geometry([w], [h], [options])\n\nType: `method`\n\nAñade la opción `-geometry`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | El ancho en píxeles, o un porcentaje como `'50%'`. Vacío para mantener la proporción. |\n| `h` | `Number|String` | no |  | El alto en píxeles, o un porcentaje. Vacío para mantener la proporción. |\n| `options` | `String` | no |  | Un sufijo del tamaño: `!` ignora la proporción, `^` rellena la caja, `>` solo reduce, `<` solo amplía. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-geometry WxH` con el sufijo opcional. El programa lo usa como tamaño y desplazamiento preferidos.\n\nExample: Geometry\n```js\nimg.geometry(300, 200, '!');\n```\n\n### img.crop(w, h, [x], [y])\n\nType: `method`\n\nRecorta un área de la imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | El ancho del área. |\n| `h` | `Number` | yes |  | El alto del área. |\n| `x` | `Number` | no | `0` | El desplazamiento horizontal. |\n| `y` | `Number` | no | `0` | El desplazamiento vertical. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-crop WxH+X+Y`. El desplazamiento se mide desde la esquina definida por `align()` (arriba a la izquierda por defecto).\n\nExample: Recortar\n```js\nimg.crop(400, 300, 50, 20);\n\n// The centre\nimg.align('center').crop(400, 300);\n```\n\n### img.extent([w], [h], [x], [y])\n\nType: `method`\n\nDefine el tamaño del lienzo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | El ancho del lienzo. |\n| `h` | `Number` | no |  | El alto del lienzo. |\n| `x` | `Number` | no |  | El desplazamiento horizontal, puede ser negativo. |\n| `y` | `Number` | no |  | El desplazamiento vertical, puede ser negativo. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-extent WxH` con un desplazamiento opcional. Un lienzo más grande se rellena con el color de fondo; uno más pequeño recorta la imagen. La posición sigue a `align()`.\n\nExample: Lienzo cuadrado\n```js\nimg.resize(500, 500).background('white').align('center').extent(500, 500);\n```\n\n### img.miniature(w, h, [color], [filter])\n\nType: `method`\n\nEncaja la imagen en una caja y rellena el resto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | El ancho. |\n| `h` | `Number` | yes |  | El alto. |\n| `color` | `String` | no | `'white'` | El color del área libre. |\n| `filter` | `String` | no | `'Hamming'` | El filtro de redimensionado. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nUn atajo para `thumbnail(w, h).background(color).align('center').extent(w, h)`. El resultado mide exactamente `w`x`h` y muestra la imagen entera. `filter` es el filtro de redimensionado de `thumbnail()`.\n\nExample: Foto de producto\n```js\nImage.load(filename).miniature(300, 300, '#F0F0F0').save(target);\n```\n\n### img.resizecenter(w, h, [color])\n\nType: `method`\n\nRellena una caja y recorta el centro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | El ancho. |\n| `h` | `Number` | yes |  | El alto. |\n| `color` | `String` | no | `'white'` | El color de fondo. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nUn atajo para `resize(w, h, '^').background(color).align('center').crop(w, h)`. El resultado mide `w`x`h` y la imagen lo cubre por completo.\n\nExample: Cubrir\n```js\nImage.load(filename).resizecenter(1200, 630).save(target);\n```\n\n### img.resizealign(w, h, [align], [color])\n\nType: `method`\n\nRellena una caja y recorta por un lado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | El ancho. |\n| `h` | `Number` | yes |  | El alto. |\n| `align` | `String` | no | `'center'` | Dónde recortar: `top`, `bottom`, `left`, `center`… |\n| `color` | `String` | no | `'white'` | El color de fondo. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nUn atajo para `resize(w, h, '^').background(color).align(align).crop(w, h)`. `align` acepta los valores de `align()`.\n\nExample: Avatar\n```js\nImage.load(filename).resizealign(200, 200, 'top').save(target);\n```\n\n### img.align(type)\n\nType: `method`\n\nDefine la gravedad para crop y extent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La posición. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-gravity`. Valores aceptados: `'top left'` (NorthWest), `'top'` (North), `'top right'` (NorthEast), `'left'` (West), `'center'` o `'middle'` (Center), `'right'` (East), `'bottom left'` (SouthWest), `'bottom'` (South), `'bottom right'` (SouthEast). El orden de las palabras no importa (`'left top'`), y `'center left'` significa `left`. Otros valores se pasan tal cual, por ejemplo `'NorthEast'`.\n\nExample: Alinear\n```js\nimg.align('bottom right').crop(400, 300);\n```\n\n### img.gravity(type)\n\nType: `method`\n\nEl mismo método que `align()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La posición. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nUn alias de `align()`.\n\nExample: Gravedad\n```js\nimg.gravity('NorthWest');\n```\n\n### img.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` | La calidad. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-quality`. Para JPEG y WebP es la calidad de 1 a 100; un valor vacío significa 80.\n\nExample: Calidad\n```js\nimg.quality(70);\n```\n\n### img.rotate([deg])\n\nType: `method`\n\nRota la imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | no | `0` | El ángulo en grados. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-rotate`. El ángulo está en grados en sentido horario. Para ángulos que no son múltiplos de 90, las esquinas se rellenan con el color de fondo.\n\nExample: Rotar\n```js\nimg.background('white').rotate(45);\n```\n\n### img.flip()\n\nType: `method`\n\nRefleja la imagen verticalmente.\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-flip` (de arriba abajo).\n\nExample: Flip\n```js\nimg.flip();\n```\n\n### img.flop()\n\nType: `method`\n\nRefleja la imagen horizontalmente.\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-flop` (de izquierda a derecha).\n\nExample: Flop\n```js\nimg.flop();\n```\n\n### img.blur(radius)\n\nType: `method`\n\nDesenfoca la imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | El radio o `radiusxsigma`. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-blur`. El valor es el radio, o `radiusxsigma` como cadena (`'0x8'`).\n\nExample: Desenfocar\n```js\nimg.blur(5);\nimg.blur('0x8');\n```\n\n### img.grayscale()\n\nType: `method`\n\nConvierte la imagen a escala de grises.\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-colorspace Gray`.\n\nExample: Gris\n```js\nimg.grayscale();\n```\n\n### img.sepia()\n\nType: `method`\n\nDa a la imagen un tono sepia.\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-modulate 115,0,100 -colorize 7,21,50`.\n\nExample: Sepia\n```js\nimg.sepia();\n```\n\n### img.normalize()\n\nType: `method`\n\nEstira el contraste.\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-normalize`: los colores se reparten por todo el rango.\n\nExample: Normalizar\n```js\nimg.normalize();\n```\n\n### img.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` El mismo objeto de imagen, para encadenar.\n\nAñade `-colors`.\n\nExample: Paleta\n```js\nimg.output('png').colors(64);\n```\n\n### img.bitdepth(value)\n\nType: `method`\n\nDefine la profundidad de bits.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bits por canal, por ejemplo 8. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-depth`.\n\nExample: Profundidad\n```js\nimg.bitdepth(8);\n```\n\n### img.background(color)\n\nType: `method`\n\nEstablece el color de fondo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | El color. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-background color` y después `-extent 0x0`, de modo que el color se establece antes de ampliar el lienzo. El color rellena las áreas nuevas que crean `extent()`, `rotate()` y los ayudantes de redimensionado. Sirve cualquier color del programa: `white`, `#FF0000`, `none` para transparente.\n\nExample: Fondo\n```js\nimg.background('#FFFFFF').extent(800, 800);\n```\n\n### img.fill(color)\n\nType: `method`\n\nDefine el color de relleno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | El color. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-fill`. Lo usan las operaciones que dibujan, por ejemplo `-colorize` o tus propias opciones de `command()`.\n\nExample: Relleno\n```js\nimg.fill('red').command('-colorize', '30');\n```\n\n### img.filter(type)\n\nType: `method`\n\nDefine el filtro de redimensionado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El nombre del filtro. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-filter`, por ejemplo `'Lanczos'`, `'Hamming'`, `'Box'` o `'Triangle'`. Siempre se coloca antes de `-resize`, `-thumbnail` y `-scale`, así que se aplica a ellos tanto si lo llamas antes como después de `resize()`, `thumbnail()` o `scale()`.\n\nExample: Filtro\n```js\nimg.resize(400).filter('Lanczos');\n```\n\nExample: El comando\n```js\nImage.load('photo.jpg').filter('Lanczos').resize(200, 200).cmd('photo.jpg', 'small.jpg');\n// gm convert 'photo.jpg' -filter 'Lanczos' -resize '200x200' 'small.jpg'\n```\n\n### img.define(value)\n\nType: `method`\n\nPasa una opción del codificador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La definición `format:key=value`. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-define`, por ejemplo `'jpeg:extent=200kb'` o `'png:compression-level=9'`.\n\nExample: Define\n```js\nimg.define('jpeg:extent=200kb');\n```\n\n### img.minify()\n\nType: `method`\n\nElimina los perfiles y los metadatos.\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `+profile '*'`, que elimina EXIF, ICC y otros perfiles. `save()`, `pipe()` y `writer()` lo llaman cuando la imagen no tiene operaciones.\n\nExample: Eliminar metadatos\n```js\nImage.load(filename).minify().save(target);\n```\n\n### img.limit(type, value)\n\nType: `method`\n\nLimita un recurso del programa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El recurso. |\n| `value` | `Number|String` | yes |  | El límite, por ejemplo `256MB`. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-limit type value`, por ejemplo `limit('memory', '256MB')`. Los tipos y unidades son los del programa (`memory`, `map`, `disk`…). Un número sin unidad está en bytes.\n\nExample: Limitar la memoria\n```js\nimg.limit('memory', '256MB').limit('map', '512MB');\n```\n\n### img.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nDibuja otra imagen sobre la imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El archivo de la marca de agua. |\n| `x` | `Number` | no | `0` | El desplazamiento horizontal. |\n| `y` | `Number` | no | `0` | El desplazamiento vertical. |\n| `w` | `Number` | no | `0` | El ancho de la marca de agua. |\n| `h` | `Number` | no | `0` | El alto de la marca de agua. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `-draw 'image over x,y w,h filename'`. El desplazamiento se mide desde la esquina superior izquierda. Un ancho y un alto de 0 mantienen el tamaño de la marca de agua. Las comillas simples se eliminan del nombre de archivo.\n\nExample: Logo en la esquina\n```js\nImage.load(filename)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n### img.command(key, [value], [priority], [escape])\n\nType: `method`\n\nAñade cualquier opción del programa.\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. |\n| `priority` | `Number|Boolean` | no | `10` | La posición, o `true` para entrecomillar el valor. |\n| `escape` | `Boolean` | no | `false` | Entrecomillar el valor. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nAñade `key value` al comando. `priority` decide la posición (menor primero, por defecto 10; los tamaños tienen 1, gravity 3, crop 4, quality 5, rotate 8). `escape` pone el valor entre comillas; pasar `true` como `priority` también activa `escape` (con prioridad 10).\n\nExample: Opciones personalizadas\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'My photo', true);\n```\n\n### img.make(fn)\n\nType: `method`\n\nAplica una función a la imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Recibe la imagen. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nLlama a `fn(img)` con `this` apuntando a la imagen. Úsalo para reutilizar un conjunto de operaciones.\n\nExample: Preset\n```js\nfunction avatar(img) {\n\timg.resizecenter(128, 128).quality(90);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n### img.clear()\n\nType: `method`\n\nElimina todas las operaciones.\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nVacía la lista de operaciones. `save()` lo llama cuando el programa termina.\n\nExample: Limpiar\n```js\nimg.clear().resize(100);\n```\n\n### img.output(type)\n\nType: `method`\n\nDefine el tipo de imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El tipo, por ejemplo `png` o `.webp`. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nDefine `img.type` (se elimina un punto inicial). `pipe()` y `writer()` producen este formato cuando no pasas uno, y `Image.middleware()` se compara con él. `save()` toma el formato de la extensión del archivo de destino.\n\nExample: De Buffer a PNG\n```js\nImage.load(buffer).output('png').resize(100).pipe($.res);\n```\n\n### img.save([filename], [callback])\n\nType: `method`\n\nEjecuta el programa y escribe el resultado en un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `img.filename` | El archivo de destino. |\n| `callback` | `Function` | no |  | `function(err, success)`. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nConstruye el comando y lo ejecuta. El formato viene de la extensión de `filename`. Sin `filename` se sobrescribe el archivo de origen. Un origen Buffer o stream se envía a la entrada estándar. El callback recibe `(err, success)`, donde `success` es `true` o `false`. Después se limpian las operaciones.\n\nExample: Guardar\n```js\nImage.load(file.path).resize(1024).quality(80).save(PATH.public('photos/' + id + '.jpg'), function(err) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success();\n});\n```\n\n### img.pipe(stream, [type], [options])\n\nType: `method`\n\nEjecuta el programa y envía el resultado a un stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Un stream de escritura, por ejemplo `$.res`. |\n| `type` | `String` | no | `img.type` | El formato de salida. |\n| `options` | `Object` | no |  | Opciones de `stream.pipe()`. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nEscribe la salida del programa en `stream`. `type` es el formato de salida: `jpg`, `jpeg`, `png`, `gif`, `apng`, `webp`, `heif`, `heic` o `ico`; otros valores usan `img.type`. `options` va a `stream.pipe()` (por ejemplo `{ end: false }`); puedes pasarlo como segundo argumento. Los mensajes del programa en la salida de error estándar se emiten como eventos `error` en `stream`.\n\nExample: Enviar a la respuesta\n```js\nfunction preview($) {\n\t$.res.writeHead(200, { 'content-type': 'image/png' });\n\tImage.load(PATH.public('photo.jpg')).resize(300).pipe($.res, 'png');\n}\n```\n\n### img.writer([type])\n\nType: `method`\n\nEjecuta el programa y devuelve el stream de salida.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `img.type` | El formato de salida. |\n\nReturns: `Stream` Un stream de lectura con el resultado.\n\nInicia el programa y devuelve su salida de lectura (pasada por el `Image.middleware()` del tipo, cuando lo hay). `type` acepta los mismos valores que en `pipe()`.\n\nExample: Recoger en un Buffer\n```js\nvar chunks = [];\nvar stream = Image.load(buffer).resize(100, 100).writer('webp');\nstream.on('data', chunk => chunks.push(chunk));\nstream.on('end', function() {\n\tvar output = Buffer.concat(chunks);\n});\n```\n\n### img.measure(callback)\n\nType: `method`\n\nLee el tamaño del archivo de origen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, size)`. |\n\nReturns: `Image` El mismo objeto de imagen, para encadenar.\n\nLee la cabecera del archivo de origen y llama a `callback(err, size)` con `{ width, height }`. Para un archivo `.jpg` sin la cabecera del frame en sus primeros 40 kB, `size` es `null`. El origen debe ser un nombre de archivo con la extensión `.jpg`, `.png`, `.gif` o `.webp`; otras extensiones dan un error. No usa el programa externo.\n\nExample: Medir un archivo\n```js\nImage.load(PATH.public('photo.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### img.cmd(from, to)\n\nType: `method`\n\nDevuelve la línea de comandos sin ejecutarla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | El archivo de origen o `-`. |\n| `to` | `String` | yes |  | El archivo de destino o `-`. |\n\nReturns: `String` La línea de comandos.\n\nConstruye el comando que usa `save()`: el programa, el origen entrecomillado, las operaciones ordenadas y el destino entrecomillado. Usa `'-'` para la entrada o salida estándar. Útil para depurar.\n\nExample: Mostrar el comando\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n","entries":[{"type":"class","name":"Image","signature":"Image","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"F.image()","signature":"F.image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"class","name":"Image.Image","signature":"new Image.Image(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.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(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.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"property","name":"img.width","signature":"img.width","since":"","deprecated":false},{"type":"property","name":"img.filename","signature":"img.filename","since":"","deprecated":false},{"type":"property","name":"img.stream","signature":"img.stream","since":"","deprecated":false},{"type":"property","name":"img.type","signature":"img.type","since":"","deprecated":false},{"type":"property","name":"img.shell","signature":"img.shell","since":"","deprecated":false},{"type":"method","name":"img.resize()","signature":"img.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.thumbnail()","signature":"img.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.scale()","signature":"img.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.geometry()","signature":"img.geometry([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.crop()","signature":"img.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.extent()","signature":"img.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.miniature()","signature":"img.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"img.resizecenter()","signature":"img.resizecenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"img.resizealign()","signature":"img.resizealign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"img.align()","signature":"img.align(type)","since":"","deprecated":false},{"type":"method","name":"img.gravity()","signature":"img.gravity(type)","since":"","deprecated":false},{"type":"method","name":"img.quality()","signature":"img.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"img.rotate()","signature":"img.rotate([deg])","since":"","deprecated":false},{"type":"method","name":"img.flip()","signature":"img.flip()","since":"","deprecated":false},{"type":"method","name":"img.flop()","signature":"img.flop()","since":"","deprecated":false},{"type":"method","name":"img.blur()","signature":"img.blur(radius)","since":"","deprecated":false},{"type":"method","name":"img.grayscale()","signature":"img.grayscale()","since":"","deprecated":false},{"type":"method","name":"img.sepia()","signature":"img.sepia()","since":"","deprecated":false},{"type":"method","name":"img.normalize()","signature":"img.normalize()","since":"","deprecated":false},{"type":"method","name":"img.colors()","signature":"img.colors(value)","since":"","deprecated":false},{"type":"method","name":"img.bitdepth()","signature":"img.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"img.background()","signature":"img.background(color)","since":"","deprecated":false},{"type":"method","name":"img.fill()","signature":"img.fill(color)","since":"","deprecated":false},{"type":"method","name":"img.filter()","signature":"img.filter(type)","since":"","deprecated":false},{"type":"method","name":"img.define()","signature":"img.define(value)","since":"","deprecated":false},{"type":"method","name":"img.minify()","signature":"img.minify()","since":"","deprecated":false},{"type":"method","name":"img.limit()","signature":"img.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"img.watermark()","signature":"img.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"img.command()","signature":"img.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"img.make()","signature":"img.make(fn)","since":"","deprecated":false},{"type":"method","name":"img.clear()","signature":"img.clear()","since":"","deprecated":false},{"type":"method","name":"img.output()","signature":"img.output(type)","since":"","deprecated":false},{"type":"method","name":"img.save()","signature":"img.save([filename], [callback])","since":"","deprecated":false},{"type":"method","name":"img.pipe()","signature":"img.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"img.writer()","signature":"img.writer([type])","since":"","deprecated":false},{"type":"method","name":"img.measure()","signature":"img.measure(callback)","since":"","deprecated":false},{"type":"method","name":"img.cmd()","signature":"img.cmd(from, to)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwTD5Lx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/images/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Images","summary":"Le global Image et toutes les méthodes des objets image.","markdown":"---\ntitle: Images\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/images/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Images\n\n> Le global Image et toutes les méthodes des objets image.\n\nLe global `Image` charge, modifie, mesure et enregistre des images avec GraphicsMagick ou ImageMagick. Le guide [Images](../../guides/images/) explique comment l'utiliser avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### Image\n\nType: `class`\n\nLe module global des images.\n\n`Image` est le module des images du framework. Il fournit `Image.load()` pour créer des objets image, les fonctions `Image.measure*()` qui lisent la taille depuis l'en-tête d'un fichier, `Image.middleware()` et le constructeur `Image.Image`. Les opérations s'exécutent avec le programme défini dans `$imageconverter`.\n\nExample: Redimensionner une photo\n```js\nImage.load(PATH.public('photo.jpg')).resize(800).save(PATH.public('photo-800.jpg'));\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nCrée un objet image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Un nom de fichier, un Buffer ou un flux lisible. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Le programme : `gm`, `im` ou `magick`. |\n| `width` | `Number` | no |  | La largeur connue, stockée dans `img.width`. |\n| `height` | `Number` | no |  | La hauteur connue, stockée dans `img.height`. |\n\nReturns: `Image` Un nouvel objet image.\n\n`source` est un nom de fichier, un `Buffer` ou un flux lisible. Avec un nom de fichier, `img.type` est son extension ; sinon, c'est `jpg`. `converter` vaut `gm`, `im` ou `magick` et remplace `$imageconverter` pour cette image. `width` et `height` sont seulement stockés dans `img.width` et `img.height` ; ils ne sont pas lus depuis le fichier.\n\nExample: Charger depuis un fichier et un buffer\n```js\nvar a = Image.load(PATH.public('photo.jpg'));\nvar b = Image.load(buffer, 'magick');\n```\n\n### F.image(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|Buffer|Stream` | yes |  | Un nom de fichier, un Buffer ou un flux lisible. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Le programme : `gm`, `im` ou `magick`. |\n| `width` | `Number` | no |  | La largeur connue. |\n| `height` | `Number` | no |  | La hauteur connue. |\n\nReturns: `Image` Un nouvel objet image.\n\nUn alias de `Image.load()` sur l'objet du framework.\n\nExample: Charger une image\n```js\nF.image(filename).grayscale().save(target);\n```\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nLe constructeur des objets image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Un nom de fichier, un Buffer ou un flux lisible. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Le programme : `gm`, `im` ou `magick`. |\n| `width` | `Number` | no |  | La largeur connue. |\n| `height` | `Number` | no |  | La hauteur connue. |\n\n`Image.load()` renvoie `new Image.Image(...)` avec les mêmes arguments. Utilise-le quand tu veux tester `img instanceof Image.Image` ou ajouter tes propres méthodes à `Image.Image.prototype`.\n\nExample: Ajouter une méthode\n```js\nImage.Image.prototype.avatar = function() {\n\treturn this.resizecenter(128, 128).quality(90);\n};\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nLit la largeur et la hauteur depuis l'en-tête d'une image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Une extension ou un type MIME. |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`, `null` pour un JPEG sans marqueur de taille, `undefined` pour un type non pris en charge.\n\n`type` est une extension avec ou sans le point (`jpg`, `.png`) ou un type MIME (`image/webp`). Les types pris en charge sont JPEG, PNG, GIF, WebP, SVG, BMP et PSD. Le buffer n'a besoin que du début du fichier. Pour les autres types, elle renvoie `undefined`. Pour un buffer JPEG sans marqueur de taille, elle renvoie `null`.\n\nExample: Mesurer un buffer téléversé\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\t$.invalid('The image is too wide');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nLit la taille d'une image JPEG depuis un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }` ou `null`.\n\nElle parcourt les marqueurs jusqu'à l'en-tête de trame. Renvoie `null` quand le buffer n'est pas un JPEG ou que l'en-tête de trame n'est pas dans le buffer (un fichier endommagé, un segment avec une longueur non valide ou trop peu de données). Passe assez de données : le framework lit 40 kB.\n\nExample: Mesurer\n```js\nvar size = Image.measureJPG(buffer);\nconsole.log(size.width, size.height);\n```\n\nExample: Un JPEG sans la taille\n```js\nvar buffer = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00]);\nvar size = Image.measureJPG(buffer);\nconsole.log(size); // null: no frame header in the buffer\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nLit la taille d'une image PNG depuis un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`.\n\nElle lit l'en-tête IHDR, donc 24 octets suffisent.\n\nExample: Mesurer\n```js\nvar size = Image.measurePNG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nLit la taille d'une image GIF depuis un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`.\n\nElle lit la taille logique de l'écran, donc 10 octets suffisent.\n\nExample: Mesurer\n```js\nvar size = Image.measureGIF(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nLit la taille d'une image WebP depuis un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`.\n\nElle lit les en-têtes `VP8 `, `VP8L` et `VP8X`. Renvoie `undefined` pour d'autres données.\n\nExample: Mesurer\n```js\nvar size = Image.measureWEBP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nLit la taille d'une image SVG depuis un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`.\n\nElle lit les premiers attributs `width=\"...\"` et `height=\"...\"` avec des nombres entiers. Renvoie `undefined` quand il n'y en a pas.\n\nExample: Mesurer\n```js\nvar size = Image.measureSVG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nLit la taille d'une image BMP depuis un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`.\n\nElle lit le BITMAPINFOHEADER.\n\nExample: Mesurer\n```js\nvar size = Image.measureBMP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nLit la taille d'une image Photoshop (PSD) depuis un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`.\n\nElle lit l'en-tête du fichier PSD.\n\nExample: Mesurer\n```js\nvar size = Image.measurePSD(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nEnregistre un flux qui post-traite les résultats d'un type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le type d'image, par exemple `png` ou `.jpg`. |\n| `fn` | `Function` | yes |  | Renvoie un flux Transform. |\n\n`fn` doit renvoyer un nouveau flux Transform à chaque appel. Avec `pipe()` et `writer()`, la sortie du programme passe par ce flux avant de te parvenir, et `type` est comparé au format de sortie. Avec `save()` et un callback, le fichier enregistré est relu à travers ce flux et réécrit avant l'exécution du callback ; dans ce cas, `type` est comparé à `img.type` (l'extension de la source ou la valeur de `output()`). Un point initial dans `type` est supprimé. Une fonction par type ; un nouvel appel la remplace.\n\nExample: Faire passer les résultats PNG par un stream\n```js\nvar Transform = require('stream').Transform;\n\nImage.middleware('png', function() {\n\treturn new Transform({\n\t\ttransform: function(chunk, encoding, next) {\n\t\t\tnext(null, chunk);\n\t\t}\n\t});\n});\n```\n\n### img.width\n\nType: `property`\n\nLa largeur passée à `Image.load()`.\n\nReturns: `Number`\n\nLe troisième argument de `Image.load()`, ou `undefined`. Elle n'est pas lue depuis le fichier ; utilise `img.measure()` pour cela. `img.height` contient le quatrième argument de la même façon.\n\nExample: Taille connue\n```js\nvar img = Image.load(file.path, null, file.width, file.height);\nif (img.width > 1000)\n\timg.resize(1000);\n```\n\n### img.filename\n\nType: `property`\n\nLe nom du fichier source.\n\nReturns: `String`\n\nLe nom de fichier donné à `Image.load()`, ou `null` quand la source est un Buffer ou un flux.\n\n### img.stream\n\nType: `property`\n\nLe Buffer ou le flux source.\n\nReturns: `Buffer|Stream`\n\nLe Buffer ou le flux lisible donné à `Image.load()`, ou `null` quand la source est un nom de fichier. Il est écrit sur l'entrée standard du programme quand l'image est enregistrée ou envoyée dans un flux.\n\n### img.type\n\nType: `property`\n\nLe type de l'image.\n\nReturns: `String`\n\nL'extension du fichier source en minuscules sans le point (`jpg`, `png`…), ou `jpg` pour un Buffer ou un flux. `output()` la modifie. `pipe()` et `writer()` l'utilisent comme format de sortie quand tu n'en passes pas, et les gestionnaires `Image.middleware()` sont comparés à elle.\n\n### img.shell\n\nType: `property`\n\nLe programme qui traite l'image.\n\nReturns: `String`\n\n`gm`, `im` ou `magick` : le deuxième argument de `Image.load()`, sinon `CONF.$imageconverter`. `gm` exécute `gm convert`, `im` exécute `convert` et `magick` exécute `magick`. Tu peux le changer avant d'enregistrer l'image.\n\n### img.resize([w], [h], [options])\n\nType: `method`\n\nRedimensionne l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | La largeur en pixels, ou un pourcentage comme `'50%'`. Vide pour conserver le ratio. |\n| `h` | `Number|String` | no |  | La hauteur en pixels, ou un pourcentage. Vide pour conserver le ratio. |\n| `options` | `String` | no |  | Un suffixe de la taille : `!` ignore le ratio, `^` remplit la zone, `>` ne fait que réduire, `<` ne fait qu'agrandir. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-resize WxH`. L'image tient dans la zone et conserve ses proportions, sauf si `options` indique autre chose. Avec seulement `w`, la hauteur suit le ratio ; avec seulement `h`, c'est la largeur.\n\nExample: Redimensionner\n```js\nimg.resize(800, 600);   // into 800x600\nimg.resize(800);        // width 800\nimg.resize(null, 600);  // height 600\nimg.resize(200, 200, '!'); // exactly 200x200\nimg.resize('50%');      // half size\n```\n\n### img.thumbnail([w], [h], [options])\n\nType: `method`\n\nRedimensionne l'image pour un petit aperçu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | La largeur en pixels, ou un pourcentage comme `'50%'`. Vide pour conserver le ratio. |\n| `h` | `Number|String` | no |  | La hauteur en pixels, ou un pourcentage. Vide pour conserver le ratio. |\n| `options` | `String` | no |  | Un suffixe de la taille : `!` ignore le ratio, `^` remplit la zone, `>` ne fait que réduire, `<` ne fait qu'agrandir. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-thumbnail WxH` : un redimensionnement qui supprime aussi les profils, donc le fichier est plus petit. Les arguments sont les mêmes que pour `resize()`.\n\nExample: Miniature\n```js\nImage.load(filename).thumbnail(150, 150).save(target);\n```\n\n### img.scale([w], [h], [options])\n\nType: `method`\n\nRedimensionne l'image rapidement sans filtrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | La largeur en pixels, ou un pourcentage comme `'50%'`. Vide pour conserver le ratio. |\n| `h` | `Number|String` | no |  | La hauteur en pixels, ou un pourcentage. Vide pour conserver le ratio. |\n| `options` | `String` | no |  | Un suffixe de la taille : `!` ignore le ratio, `^` remplit la zone, `>` ne fait que réduire, `<` ne fait qu'agrandir. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-scale WxH`. Plus rapide que `resize()`, mais de moindre qualité. Les arguments sont les mêmes que pour `resize()`.\n\nExample: Mise à l'échelle\n```js\nimg.scale(64, 64);\n```\n\n### img.geometry([w], [h], [options])\n\nType: `method`\n\nAjoute l'option `-geometry`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | La largeur en pixels, ou un pourcentage comme `'50%'`. Vide pour conserver le ratio. |\n| `h` | `Number|String` | no |  | La hauteur en pixels, ou un pourcentage. Vide pour conserver le ratio. |\n| `options` | `String` | no |  | Un suffixe de la taille : `!` ignore le ratio, `^` remplit la zone, `>` ne fait que réduire, `<` ne fait qu'agrandir. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-geometry WxH` avec le suffixe facultatif. Le programme l'utilise comme taille et décalage préférés.\n\nExample: Géométrie\n```js\nimg.geometry(300, 200, '!');\n```\n\n### img.crop(w, h, [x], [y])\n\nType: `method`\n\nDécoupe une zone de l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | La largeur de la zone. |\n| `h` | `Number` | yes |  | La hauteur de la zone. |\n| `x` | `Number` | no | `0` | Le décalage horizontal. |\n| `y` | `Number` | no | `0` | Le décalage vertical. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-crop WxH+X+Y`. Le décalage est mesuré depuis le coin défini par `align()` (en haut à gauche par défaut).\n\nExample: Recadrer\n```js\nimg.crop(400, 300, 50, 20);\n\n// The centre\nimg.align('center').crop(400, 300);\n```\n\n### img.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 |  | La largeur du canevas. |\n| `h` | `Number` | no |  | La hauteur du canevas. |\n| `x` | `Number` | no |  | Le décalage horizontal, peut être négatif. |\n| `y` | `Number` | no |  | Le décalage vertical, peut être négatif. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-extent WxH` avec un décalage facultatif. Un canevas plus grand est rempli avec la couleur de fond, un plus petit coupe l'image. La position suit `align()`.\n\nExample: Canevas carré\n```js\nimg.resize(500, 500).background('white').align('center').extent(500, 500);\n```\n\n### img.miniature(w, h, [color], [filter])\n\nType: `method`\n\nFait tenir l'image dans une zone et remplit le reste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | La largeur. |\n| `h` | `Number` | yes |  | La hauteur. |\n| `color` | `String` | no | `'white'` | La couleur de la zone libre. |\n| `filter` | `String` | no | `'Hamming'` | Le filtre de redimensionnement. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nUn raccourci pour `thumbnail(w, h).background(color).align('center').extent(w, h)`. Le résultat fait exactement `w`x`h` et montre l'image entière. `filter` est le filtre de redimensionnement de `thumbnail()`.\n\nExample: Photo de produit\n```js\nImage.load(filename).miniature(300, 300, '#F0F0F0').save(target);\n```\n\n### img.resizecenter(w, h, [color])\n\nType: `method`\n\nRemplit une zone et recadre le centre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | La largeur. |\n| `h` | `Number` | yes |  | La hauteur. |\n| `color` | `String` | no | `'white'` | La couleur de fond. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nUn raccourci pour `resize(w, h, '^').background(color).align('center').crop(w, h)`. Le résultat fait `w`x`h` et l'image le couvre entièrement.\n\nExample: Couverture\n```js\nImage.load(filename).resizecenter(1200, 630).save(target);\n```\n\n### img.resizealign(w, h, [align], [color])\n\nType: `method`\n\nRemplit une zone et recadre sur un côté.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | La largeur. |\n| `h` | `Number` | yes |  | La hauteur. |\n| `align` | `String` | no | `'center'` | Où recadrer : `top`, `bottom`, `left`, `center`… |\n| `color` | `String` | no | `'white'` | La couleur de fond. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nUn raccourci pour `resize(w, h, '^').background(color).align(align).crop(w, h)`. `align` accepte les valeurs de `align()`.\n\nExample: Avatar\n```js\nImage.load(filename).resizealign(200, 200, 'top').save(target);\n```\n\n### img.align(type)\n\nType: `method`\n\nDéfinit la gravité pour le recadrage et l'extension du canevas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La position. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-gravity`. Valeurs acceptées : `'top left'` (NorthWest), `'top'` (North), `'top right'` (NorthEast), `'left'` (West), `'center'` ou `'middle'` (Center), `'right'` (East), `'bottom left'` (SouthWest), `'bottom'` (South), `'bottom right'` (SouthEast). L'ordre des mots n'a pas d'importance (`'left top'`), et `'center left'` signifie `left`. Les autres valeurs sont transmises telles quelles, par exemple `'NorthEast'`.\n\nExample: Aligner\n```js\nimg.align('bottom right').crop(400, 300);\n```\n\n### img.gravity(type)\n\nType: `method`\n\nLa même méthode que `align()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La position. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nUn alias de `align()`.\n\nExample: Gravité\n```js\nimg.gravity('NorthWest');\n```\n\n### img.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` | La qualité. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-quality`. Pour JPEG et WebP, c'est la qualité de 1 à 100 ; une valeur vide signifie 80.\n\nExample: Qualité\n```js\nimg.quality(70);\n```\n\n### img.rotate([deg])\n\nType: `method`\n\nFait pivoter l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | no | `0` | L'angle en degrés. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-rotate`. L'angle est en degrés dans le sens horaire. Pour les angles qui ne sont pas des multiples de 90, les coins sont remplis avec la couleur de fond.\n\nExample: Pivoter\n```js\nimg.background('white').rotate(45);\n```\n\n### img.flip()\n\nType: `method`\n\nRetourne l'image verticalement.\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-flip` (de haut en bas).\n\nExample: Flip\n```js\nimg.flip();\n```\n\n### img.flop()\n\nType: `method`\n\nRetourne l'image horizontalement.\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-flop` (de gauche à droite).\n\nExample: Flop\n```js\nimg.flop();\n```\n\n### img.blur(radius)\n\nType: `method`\n\nFloute l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | Le rayon ou `radiusxsigma`. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-blur`. La valeur est le rayon, ou `radiusxsigma` sous forme de chaîne (`'0x8'`).\n\nExample: Flou\n```js\nimg.blur(5);\nimg.blur('0x8');\n```\n\n### img.grayscale()\n\nType: `method`\n\nConvertit l'image en niveaux de gris.\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-colorspace Gray`.\n\nExample: Niveaux de gris\n```js\nimg.grayscale();\n```\n\n### img.sepia()\n\nType: `method`\n\nDonne à l'image un ton sépia.\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-modulate 115,0,100 -colorize 7,21,50`.\n\nExample: Sépia\n```js\nimg.sepia();\n```\n\n### img.normalize()\n\nType: `method`\n\nÉtire le contraste.\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-normalize` : les couleurs sont réparties sur toute la plage.\n\nExample: Normaliser\n```js\nimg.normalize();\n```\n\n### img.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` Le même objet image, pour le chaînage.\n\nAjoute `-colors`.\n\nExample: Palette\n```js\nimg.output('png').colors(64);\n```\n\n### img.bitdepth(value)\n\nType: `method`\n\nDéfinit la profondeur de bits.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bits par canal, par exemple 8. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-depth`.\n\nExample: Profondeur\n```js\nimg.bitdepth(8);\n```\n\n### img.background(color)\n\nType: `method`\n\nDéfinit la couleur de fond.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | La couleur. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-background color` puis `-extent 0x0`, donc la couleur est définie avant que le canevas soit agrandi. La couleur remplit les nouvelles zones créées par `extent()`, `rotate()` et les helpers de redimensionnement. Toute couleur du programme fonctionne : `white`, `#FF0000`, `none` pour la transparence.\n\nExample: Fond\n```js\nimg.background('#FFFFFF').extent(800, 800);\n```\n\n### img.fill(color)\n\nType: `method`\n\nDéfinit la couleur de remplissage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | La couleur. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-fill`. Utilisée par les opérations qui dessinent, par exemple `-colorize` ou tes propres options `command()`.\n\nExample: Remplissage\n```js\nimg.fill('red').command('-colorize', '30');\n```\n\n### img.filter(type)\n\nType: `method`\n\nDéfinit le filtre de redimensionnement.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le nom du filtre. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-filter`, par exemple `'Lanczos'`, `'Hamming'`, `'Box'` ou `'Triangle'`. Il est toujours placé avant `-resize`, `-thumbnail` et `-scale`, donc il s'applique à eux, que tu l'appelles avant ou après `resize()`, `thumbnail()` ou `scale()`.\n\nExample: Filtre\n```js\nimg.resize(400).filter('Lanczos');\n```\n\nExample: La commande\n```js\nImage.load('photo.jpg').filter('Lanczos').resize(200, 200).cmd('photo.jpg', 'small.jpg');\n// gm convert 'photo.jpg' -filter 'Lanczos' -resize '200x200' 'small.jpg'\n```\n\n### img.define(value)\n\nType: `method`\n\nTransmet une option du codeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La définition `format:key=value`. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-define`, par exemple `'jpeg:extent=200kb'` ou `'png:compression-level=9'`.\n\nExample: Define\n```js\nimg.define('jpeg:extent=200kb');\n```\n\n### img.minify()\n\nType: `method`\n\nSupprime les profils et les métadonnées.\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `+profile '*'`, qui supprime les profils EXIF, ICC et autres. `save()`, `pipe()` et `writer()` l'appellent quand l'image n'a aucune opération.\n\nExample: Supprimer les métadonnées\n```js\nImage.load(filename).minify().save(target);\n```\n\n### img.limit(type, value)\n\nType: `method`\n\nLimite une ressource du programme.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La ressource. |\n| `value` | `Number|String` | yes |  | La limite, par exemple `256MB`. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-limit type value`, par exemple `limit('memory', '256MB')`. Les types et les unités sont ceux du programme (`memory`, `map`, `disk`…). Un nombre sans unité est en octets.\n\nExample: Limiter la mémoire\n```js\nimg.limit('memory', '256MB').limit('map', '512MB');\n```\n\n### img.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nDessine une autre image par-dessus l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le fichier du filigrane. |\n| `x` | `Number` | no | `0` | Le décalage horizontal. |\n| `y` | `Number` | no | `0` | Le décalage vertical. |\n| `w` | `Number` | no | `0` | La largeur du filigrane. |\n| `h` | `Number` | no | `0` | La hauteur du filigrane. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `-draw 'image over x,y w,h filename'`. Le décalage est mesuré depuis le coin supérieur gauche. Une largeur et une hauteur de 0 conservent la taille du filigrane. Les apostrophes simples sont supprimées du nom de fichier.\n\nExample: Logo dans le coin\n```js\nImage.load(filename)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n### img.command(key, [value], [priority], [escape])\n\nType: `method`\n\nAjoute n'importe quelle option du programme.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | L'option, par exemple `-sharpen`. |\n| `value` | `String|Number` | no |  | La valeur. |\n| `priority` | `Number|Boolean` | no | `10` | La position, ou `true` pour mettre la valeur entre guillemets. |\n| `escape` | `Boolean` | no | `false` | Met la valeur entre guillemets. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAjoute `key value` à la commande. `priority` détermine la position (la plus basse en premier, 10 par défaut ; les tailles ont 1, la gravité 3, le recadrage 4, la qualité 5, la rotation 8). `escape` met la valeur entre guillemets ; passer `true` comme `priority` active aussi `escape` (avec la priorité 10).\n\nExample: Options personnalisées\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'My photo', true);\n```\n\n### img.make(fn)\n\nType: `method`\n\nApplique une fonction à l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Reçoit l'image. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nAppelle `fn(img)` avec `this` défini sur l'image. Utilise-la pour réutiliser un ensemble d'opérations.\n\nExample: Préréglage\n```js\nfunction avatar(img) {\n\timg.resizecenter(128, 128).quality(90);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n### img.clear()\n\nType: `method`\n\nSupprime toutes les opérations.\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nVide la liste des opérations. `save()` l'appelle quand le programme a terminé.\n\nExample: Vider\n```js\nimg.clear().resize(100);\n```\n\n### img.output(type)\n\nType: `method`\n\nDéfinit le type de l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le type, par exemple `png` ou `.webp`. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nDéfinit `img.type` (un point initial est supprimé). `pipe()` et `writer()` produisent ce format quand tu n'en passes pas, et `Image.middleware()` est comparé à lui. `save()` prend le format depuis l'extension du fichier cible.\n\nExample: Buffer vers PNG\n```js\nImage.load(buffer).output('png').resize(100).pipe($.res);\n```\n\n### img.save([filename], [callback])\n\nType: `method`\n\nExécute le programme et écrit le résultat dans un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `img.filename` | Le fichier cible. |\n| `callback` | `Function` | no |  | `function(err, success)`. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nConstruit la commande et l'exécute. Le format vient de l'extension de `filename`. Sans `filename`, le fichier source est écrasé. Une source Buffer ou flux est envoyée sur l'entrée standard. Le callback reçoit `(err, success)`, où `success` vaut `true` ou `false`. Les opérations sont vidées ensuite.\n\nExample: Enregistrer\n```js\nImage.load(file.path).resize(1024).quality(80).save(PATH.public('photos/' + id + '.jpg'), function(err) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success();\n});\n```\n\n### img.pipe(stream, [type], [options])\n\nType: `method`\n\nExécute le programme et envoie le résultat dans un flux.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Un flux inscriptible, par exemple `$.res`. |\n| `type` | `String` | no | `img.type` | Le format de sortie. |\n| `options` | `Object` | no |  | Les options de `stream.pipe()`. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nÉcrit la sortie du programme dans `stream`. `type` est le format de sortie : `jpg`, `jpeg`, `png`, `gif`, `apng`, `webp`, `heif`, `heic` ou `ico` ; les autres valeurs utilisent `img.type`. `options` est passé à `stream.pipe()` (par exemple `{ end: false }`) ; tu peux le passer comme deuxième argument. Les messages du programme sur la sortie d'erreur standard sont émis comme événements `error` sur `stream`.\n\nExample: Envoyer dans la réponse\n```js\nfunction preview($) {\n\t$.res.writeHead(200, { 'content-type': 'image/png' });\n\tImage.load(PATH.public('photo.jpg')).resize(300).pipe($.res, 'png');\n}\n```\n\n### img.writer([type])\n\nType: `method`\n\nExécute le programme et renvoie le flux de sortie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `img.type` | Le format de sortie. |\n\nReturns: `Stream` Un flux lisible avec le résultat.\n\nDémarre le programme et renvoie sa sortie lisible (passée par le `Image.middleware()` du type, s'il y en a un). `type` accepte les mêmes valeurs que dans `pipe()`.\n\nExample: Collecter dans un Buffer\n```js\nvar chunks = [];\nvar stream = Image.load(buffer).resize(100, 100).writer('webp');\nstream.on('data', chunk => chunks.push(chunk));\nstream.on('end', function() {\n\tvar output = Buffer.concat(chunks);\n});\n```\n\n### img.measure(callback)\n\nType: `method`\n\nLit la taille du fichier source.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, size)`. |\n\nReturns: `Image` Le même objet image, pour le chaînage.\n\nLit l'en-tête du fichier source et appelle `callback(err, size)` avec `{ width, height }`. Pour un fichier `.jpg` sans en-tête de trame dans ses 40 premiers kB, `size` vaut `null`. La source doit être un nom de fichier avec l'extension `.jpg`, `.png`, `.gif` ou `.webp` ; les autres extensions donnent une erreur. Elle n'utilise pas le programme externe.\n\nExample: Mesurer un fichier\n```js\nImage.load(PATH.public('photo.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### img.cmd(from, to)\n\nType: `method`\n\nRenvoie la ligne de commande sans l'exécuter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | Le fichier source ou `-`. |\n| `to` | `String` | yes |  | Le fichier cible ou `-`. |\n\nReturns: `String` La ligne de commande.\n\nConstruit la commande utilisée par `save()` : le programme, la source entre guillemets, les opérations triées et la cible entre guillemets. Utilise `'-'` pour l'entrée ou la sortie standard. Utile pour le débogage.\n\nExample: Afficher la commande\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n","entries":[{"type":"class","name":"Image","signature":"Image","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"F.image()","signature":"F.image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"class","name":"Image.Image","signature":"new Image.Image(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.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(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.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"property","name":"img.width","signature":"img.width","since":"","deprecated":false},{"type":"property","name":"img.filename","signature":"img.filename","since":"","deprecated":false},{"type":"property","name":"img.stream","signature":"img.stream","since":"","deprecated":false},{"type":"property","name":"img.type","signature":"img.type","since":"","deprecated":false},{"type":"property","name":"img.shell","signature":"img.shell","since":"","deprecated":false},{"type":"method","name":"img.resize()","signature":"img.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.thumbnail()","signature":"img.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.scale()","signature":"img.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.geometry()","signature":"img.geometry([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.crop()","signature":"img.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.extent()","signature":"img.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.miniature()","signature":"img.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"img.resizecenter()","signature":"img.resizecenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"img.resizealign()","signature":"img.resizealign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"img.align()","signature":"img.align(type)","since":"","deprecated":false},{"type":"method","name":"img.gravity()","signature":"img.gravity(type)","since":"","deprecated":false},{"type":"method","name":"img.quality()","signature":"img.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"img.rotate()","signature":"img.rotate([deg])","since":"","deprecated":false},{"type":"method","name":"img.flip()","signature":"img.flip()","since":"","deprecated":false},{"type":"method","name":"img.flop()","signature":"img.flop()","since":"","deprecated":false},{"type":"method","name":"img.blur()","signature":"img.blur(radius)","since":"","deprecated":false},{"type":"method","name":"img.grayscale()","signature":"img.grayscale()","since":"","deprecated":false},{"type":"method","name":"img.sepia()","signature":"img.sepia()","since":"","deprecated":false},{"type":"method","name":"img.normalize()","signature":"img.normalize()","since":"","deprecated":false},{"type":"method","name":"img.colors()","signature":"img.colors(value)","since":"","deprecated":false},{"type":"method","name":"img.bitdepth()","signature":"img.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"img.background()","signature":"img.background(color)","since":"","deprecated":false},{"type":"method","name":"img.fill()","signature":"img.fill(color)","since":"","deprecated":false},{"type":"method","name":"img.filter()","signature":"img.filter(type)","since":"","deprecated":false},{"type":"method","name":"img.define()","signature":"img.define(value)","since":"","deprecated":false},{"type":"method","name":"img.minify()","signature":"img.minify()","since":"","deprecated":false},{"type":"method","name":"img.limit()","signature":"img.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"img.watermark()","signature":"img.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"img.command()","signature":"img.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"img.make()","signature":"img.make(fn)","since":"","deprecated":false},{"type":"method","name":"img.clear()","signature":"img.clear()","since":"","deprecated":false},{"type":"method","name":"img.output()","signature":"img.output(type)","since":"","deprecated":false},{"type":"method","name":"img.save()","signature":"img.save([filename], [callback])","since":"","deprecated":false},{"type":"method","name":"img.pipe()","signature":"img.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"img.writer()","signature":"img.writer([type])","since":"","deprecated":false},{"type":"method","name":"img.measure()","signature":"img.measure(callback)","since":"","deprecated":false},{"type":"method","name":"img.cmd()","signature":"img.cmd(from, to)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwTD5Lx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/images/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Immagini","summary":"Il global Image e tutti i metodi degli oggetti immagine.","markdown":"---\ntitle: Immagini\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/images/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Immagini\n\n> Il global Image e tutti i metodi degli oggetti immagine.\n\nIl global `Image` carica, modifica, misura e salva immagini con GraphicsMagick o ImageMagick. La guida [Immagini](../../guides/images/) spiega come usarlo con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### Image\n\nType: `class`\n\nIl modulo globale delle immagini.\n\n`Image` è il modulo delle immagini del framework. Ha `Image.load()` per creare oggetti immagine, le funzioni `Image.measure*()` che leggono la dimensione dall'header di un file, `Image.middleware()` e il costruttore `Image.Image`. Le operazioni vengono eseguite con il programma impostato in `$imageconverter`.\n\nExample: Ridimensionare una foto\n```js\nImage.load(PATH.public('photo.jpg')).resize(800).save(PATH.public('photo-800.jpg'));\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nCrea un oggetto immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Un nome di file, un Buffer o uno stream leggibile. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Il programma: `gm`, `im` o `magick`. |\n| `width` | `Number` | no |  | La larghezza nota, memorizzata in `img.width`. |\n| `height` | `Number` | no |  | L'altezza nota, memorizzata in `img.height`. |\n\nReturns: `Image` Un nuovo oggetto immagine.\n\n`source` è un nome di file, un `Buffer` o uno stream leggibile. Con un nome di file, `img.type` è la sua estensione; altrimenti è `jpg`. `converter` è `gm`, `im` o `magick` e sostituisce `$imageconverter` per questa immagine. `width` e `height` vengono solo memorizzati in `img.width` e `img.height`; non vengono letti dal file.\n\nExample: Caricare da un file e da un buffer\n```js\nvar a = Image.load(PATH.public('photo.jpg'));\nvar b = Image.load(buffer, 'magick');\n```\n\n### F.image(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|Buffer|Stream` | yes |  | Un nome di file, un Buffer o uno stream leggibile. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Il programma: `gm`, `im` o `magick`. |\n| `width` | `Number` | no |  | La larghezza nota. |\n| `height` | `Number` | no |  | L'altezza nota. |\n\nReturns: `Image` Un nuovo oggetto immagine.\n\nUn alias di `Image.load()` sull'oggetto del framework.\n\nExample: Caricare un'immagine\n```js\nF.image(filename).grayscale().save(target);\n```\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nIl costruttore degli oggetti immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Un nome di file, un Buffer o uno stream leggibile. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Il programma: `gm`, `im` o `magick`. |\n| `width` | `Number` | no |  | La larghezza nota. |\n| `height` | `Number` | no |  | L'altezza nota. |\n\n`Image.load()` restituisce `new Image.Image(...)` con gli stessi argomenti. Usalo quando vuoi verificare `img instanceof Image.Image` o aggiungere metodi tuoi a `Image.Image.prototype`.\n\nExample: Aggiungere un metodo\n```js\nImage.Image.prototype.avatar = function() {\n\treturn this.resizecenter(128, 128).quality(90);\n};\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nLegge larghezza e altezza dall'header di un'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Un'estensione o un tipo MIME. |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`, `null` per un JPEG senza marker di dimensione, `undefined` per un tipo non supportato.\n\n`type` è un'estensione con o senza punto (`jpg`, `.png`) o un tipo MIME (`image/webp`). I tipi supportati sono JPEG, PNG, GIF, WebP, SVG, BMP e PSD. Il buffer deve contenere solo l'inizio del file. Per altri tipi restituisce `undefined`. Per un buffer JPEG senza marker di dimensione restituisce `null`.\n\nExample: Misurare un buffer caricato\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\t$.invalid('The image is too wide');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nLegge la dimensione di un'immagine JPEG da un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }` oppure `null`.\n\nScorre i marker fino all'header del frame. Restituisce `null` quando il buffer non è un JPEG o quando l'header del frame non è nel buffer (un file danneggiato, un segmento con una lunghezza non valida o troppo pochi dati). Passa dati sufficienti: il framework legge 40 kB.\n\nExample: Misurare\n```js\nvar size = Image.measureJPG(buffer);\nconsole.log(size.width, size.height);\n```\n\nExample: Un JPEG senza dimensioni\n```js\nvar buffer = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00]);\nvar size = Image.measureJPG(buffer);\nconsole.log(size); // null: no frame header in the buffer\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nLegge la dimensione di un'immagine PNG da un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`.\n\nLegge l'header IHDR, quindi bastano 24 byte.\n\nExample: Misurare\n```js\nvar size = Image.measurePNG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nLegge la dimensione di un'immagine GIF da un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`.\n\nLegge la dimensione logica dello schermo, quindi bastano 10 byte.\n\nExample: Misurare\n```js\nvar size = Image.measureGIF(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nLegge la dimensione di un'immagine WebP da un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`.\n\nLegge gli header `VP8 `, `VP8L` e `VP8X`. Restituisce `undefined` per altri dati.\n\nExample: Misurare\n```js\nvar size = Image.measureWEBP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nLegge la dimensione di un'immagine SVG da un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`.\n\nLegge i primi attributi `width=\"...\"` e `height=\"...\"` con numeri interi. Restituisce `undefined` quando non ce ne sono.\n\nExample: Misurare\n```js\nvar size = Image.measureSVG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nLegge la dimensione di un'immagine BMP da un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`.\n\nLegge il BITMAPINFOHEADER.\n\nExample: Misurare\n```js\nvar size = Image.measureBMP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nLegge la dimensione di un'immagine Photoshop (PSD) da un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`.\n\nLegge l'header del file PSD.\n\nExample: Misurare\n```js\nvar size = Image.measurePSD(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nRegistra uno stream che post-elabora i risultati di un tipo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il tipo di immagine, per esempio `png` o `.jpg`. |\n| `fn` | `Function` | yes |  | Restituisce uno stream Transform. |\n\n`fn` deve restituire un nuovo stream Transform ogni volta che viene chiamata. Con `pipe()` e `writer()` l'output del programma passa attraverso di esso prima di arrivare a te, e `type` viene confrontato con il formato di output. Con `save()` e una callback, il file salvato viene letto attraverso di esso e riscritto prima che venga eseguita la callback; in questo caso `type` viene confrontato con `img.type` (l'estensione della sorgente o il valore di `output()`). Un punto iniziale in `type` viene rimosso. Una funzione per tipo; una nuova chiamata la sostituisce.\n\nExample: Far passare i risultati PNG attraverso uno stream\n```js\nvar Transform = require('stream').Transform;\n\nImage.middleware('png', function() {\n\treturn new Transform({\n\t\ttransform: function(chunk, encoding, next) {\n\t\t\tnext(null, chunk);\n\t\t}\n\t});\n});\n```\n\n### img.width\n\nType: `property`\n\nLa larghezza passata a `Image.load()`.\n\nReturns: `Number`\n\nIl terzo argomento di `Image.load()`, oppure `undefined`. Non viene letta dal file; per questo usa `img.measure()`. `img.height` contiene il quarto argomento allo stesso modo.\n\nExample: Dimensione nota\n```js\nvar img = Image.load(file.path, null, file.width, file.height);\nif (img.width > 1000)\n\timg.resize(1000);\n```\n\n### img.filename\n\nType: `property`\n\nIl nome del file sorgente.\n\nReturns: `String`\n\nIl nome di file passato a `Image.load()`, oppure `null` quando la sorgente è un Buffer o uno stream.\n\n### img.stream\n\nType: `property`\n\nIl Buffer o lo stream sorgente.\n\nReturns: `Buffer|Stream`\n\nIl Buffer o lo stream leggibile passato a `Image.load()`, oppure `null` quando la sorgente è un nome di file. Viene scritto sullo standard input del programma quando l'immagine viene salvata o inviata in pipe.\n\n### img.type\n\nType: `property`\n\nIl tipo dell'immagine.\n\nReturns: `String`\n\nL'estensione del file sorgente in minuscolo senza punto (`jpg`, `png`…), oppure `jpg` per un Buffer o uno stream. `output()` la modifica. `pipe()` e `writer()` la usano come formato di output quando non ne passi uno, e gli handler di `Image.middleware()` vengono confrontati con essa.\n\n### img.shell\n\nType: `property`\n\nIl programma che elabora l'immagine.\n\nReturns: `String`\n\n`gm`, `im` o `magick`: il secondo argomento di `Image.load()`, altrimenti `CONF.$imageconverter`. `gm` esegue `gm convert`, `im` esegue `convert` e `magick` esegue `magick`. Puoi cambiarlo prima di salvare l'immagine.\n\n### img.resize([w], [h], [options])\n\nType: `method`\n\nRidimensiona l'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | La larghezza in pixel, o una percentuale come `'50%'`. Vuota per mantenere le proporzioni. |\n| `h` | `Number|String` | no |  | L'altezza in pixel, o una percentuale. Vuota per mantenere le proporzioni. |\n| `options` | `String` | no |  | Un suffisso della dimensione: `!` ignora le proporzioni, `^` riempie il riquadro, `>` solo riduce, `<` solo ingrandisce. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-resize WxH`. L'immagine entra nel riquadro e mantiene le proporzioni, salvo diversa indicazione di `options`. Con solo `w` l'altezza segue le proporzioni, con solo `h` lo fa la larghezza.\n\nExample: Ridimensionare\n```js\nimg.resize(800, 600);   // into 800x600\nimg.resize(800);        // width 800\nimg.resize(null, 600);  // height 600\nimg.resize(200, 200, '!'); // exactly 200x200\nimg.resize('50%');      // half size\n```\n\n### img.thumbnail([w], [h], [options])\n\nType: `method`\n\nRidimensiona l'immagine per una piccola anteprima.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | La larghezza in pixel, o una percentuale come `'50%'`. Vuota per mantenere le proporzioni. |\n| `h` | `Number|String` | no |  | L'altezza in pixel, o una percentuale. Vuota per mantenere le proporzioni. |\n| `options` | `String` | no |  | Un suffisso della dimensione: `!` ignora le proporzioni, `^` riempie il riquadro, `>` solo riduce, `<` solo ingrandisce. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-thumbnail WxH`: un ridimensionamento che rimuove anche i profili, così il file è più piccolo. Gli argomenti sono gli stessi di `resize()`.\n\nExample: Miniatura\n```js\nImage.load(filename).thumbnail(150, 150).save(target);\n```\n\n### img.scale([w], [h], [options])\n\nType: `method`\n\nRidimensiona l'immagine velocemente senza filtri.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | La larghezza in pixel, o una percentuale come `'50%'`. Vuota per mantenere le proporzioni. |\n| `h` | `Number|String` | no |  | L'altezza in pixel, o una percentuale. Vuota per mantenere le proporzioni. |\n| `options` | `String` | no |  | Un suffisso della dimensione: `!` ignora le proporzioni, `^` riempie il riquadro, `>` solo riduce, `<` solo ingrandisce. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-scale WxH`. Più veloce di `resize()` ma con qualità inferiore. Gli argomenti sono gli stessi di `resize()`.\n\nExample: Scalare\n```js\nimg.scale(64, 64);\n```\n\n### img.geometry([w], [h], [options])\n\nType: `method`\n\nAggiunge l'opzione `-geometry`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | La larghezza in pixel, o una percentuale come `'50%'`. Vuota per mantenere le proporzioni. |\n| `h` | `Number|String` | no |  | L'altezza in pixel, o una percentuale. Vuota per mantenere le proporzioni. |\n| `options` | `String` | no |  | Un suffisso della dimensione: `!` ignora le proporzioni, `^` riempie il riquadro, `>` solo riduce, `<` solo ingrandisce. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-geometry WxH` con il suffisso opzionale. Il programma lo usa come dimensione e offset preferiti.\n\nExample: Geometria\n```js\nimg.geometry(300, 200, '!');\n```\n\n### img.crop(w, h, [x], [y])\n\nType: `method`\n\nRitaglia un'area dell'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | La larghezza dell'area. |\n| `h` | `Number` | yes |  | L'altezza dell'area. |\n| `x` | `Number` | no | `0` | L'offset orizzontale. |\n| `y` | `Number` | no | `0` | L'offset verticale. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-crop WxH+X+Y`. L'offset è misurato dall'angolo impostato da `align()` (in alto a sinistra per impostazione predefinita).\n\nExample: Ritagliare\n```js\nimg.crop(400, 300, 50, 20);\n\n// The centre\nimg.align('center').crop(400, 300);\n```\n\n### img.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 |  | La larghezza della tela. |\n| `h` | `Number` | no |  | L'altezza della tela. |\n| `x` | `Number` | no |  | L'offset orizzontale, può essere negativo. |\n| `y` | `Number` | no |  | L'offset verticale, può essere negativo. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-extent WxH` con un offset opzionale. Una tela più grande viene riempita con il colore di sfondo, una più piccola taglia l'immagine. La posizione segue `align()`.\n\nExample: Tela quadrata\n```js\nimg.resize(500, 500).background('white').align('center').extent(500, 500);\n```\n\n### img.miniature(w, h, [color], [filter])\n\nType: `method`\n\nAdatta l'immagine in un riquadro e riempie il resto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | La larghezza. |\n| `h` | `Number` | yes |  | L'altezza. |\n| `color` | `String` | no | `'white'` | Il colore dell'area libera. |\n| `filter` | `String` | no | `'Hamming'` | Il filtro di ridimensionamento. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nUna scorciatoia per `thumbnail(w, h).background(color).align('center').extent(w, h)`. Il risultato è esattamente `w`x`h` e mostra l'immagine intera. `filter` è il filtro di ridimensionamento di `thumbnail()`.\n\nExample: Foto di un prodotto\n```js\nImage.load(filename).miniature(300, 300, '#F0F0F0').save(target);\n```\n\n### img.resizecenter(w, h, [color])\n\nType: `method`\n\nRiempie un riquadro e ritaglia il centro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | La larghezza. |\n| `h` | `Number` | yes |  | L'altezza. |\n| `color` | `String` | no | `'white'` | Il colore di sfondo. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nUna scorciatoia per `resize(w, h, '^').background(color).align('center').crop(w, h)`. Il risultato è `w`x`h` e l'immagine lo copre completamente.\n\nExample: Copertura\n```js\nImage.load(filename).resizecenter(1200, 630).save(target);\n```\n\n### img.resizealign(w, h, [align], [color])\n\nType: `method`\n\nRiempie un riquadro e ritaglia su un lato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | La larghezza. |\n| `h` | `Number` | yes |  | L'altezza. |\n| `align` | `String` | no | `'center'` | Dove ritagliare: `top`, `bottom`, `left`, `center`… |\n| `color` | `String` | no | `'white'` | Il colore di sfondo. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nUna scorciatoia per `resize(w, h, '^').background(color).align(align).crop(w, h)`. `align` accetta i valori di `align()`.\n\nExample: Avatar\n```js\nImage.load(filename).resizealign(200, 200, 'top').save(target);\n```\n\n### img.align(type)\n\nType: `method`\n\nImposta la gravità per crop ed extent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La posizione. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-gravity`. Valori accettati: `'top left'` (NorthWest), `'top'` (North), `'top right'` (NorthEast), `'left'` (West), `'center'` o `'middle'` (Center), `'right'` (East), `'bottom left'` (SouthWest), `'bottom'` (South), `'bottom right'` (SouthEast). L'ordine delle parole non conta (`'left top'`), e `'center left'` significa `left`. Gli altri valori vengono passati così come sono, per esempio `'NorthEast'`.\n\nExample: Allineare\n```js\nimg.align('bottom right').crop(400, 300);\n```\n\n### img.gravity(type)\n\nType: `method`\n\nLo stesso metodo di `align()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La posizione. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nUn alias di `align()`.\n\nExample: Gravità\n```js\nimg.gravity('NorthWest');\n```\n\n### img.quality([percentage])\n\nType: `method`\n\nImposta la qualità di compressione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | La qualità. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-quality`. Per JPEG e WebP è la qualità da 1 a 100; un valore vuoto significa 80.\n\nExample: Qualità\n```js\nimg.quality(70);\n```\n\n### img.rotate([deg])\n\nType: `method`\n\nRuota l'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | no | `0` | L'angolo in gradi. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-rotate`. L'angolo è in gradi in senso orario. Per angoli che non sono multipli di 90 gli angoli dell'immagine vengono riempiti con il colore di sfondo.\n\nExample: Ruotare\n```js\nimg.background('white').rotate(45);\n```\n\n### img.flip()\n\nType: `method`\n\nRispecchia l'immagine verticalmente.\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-flip` (dall'alto verso il basso).\n\nExample: Flip\n```js\nimg.flip();\n```\n\n### img.flop()\n\nType: `method`\n\nRispecchia l'immagine orizzontalmente.\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-flop` (da sinistra a destra).\n\nExample: Flop\n```js\nimg.flop();\n```\n\n### img.blur(radius)\n\nType: `method`\n\nSfoca l'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | Il raggio o `radiusxsigma`. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-blur`. Il valore è il raggio, oppure `radiusxsigma` come stringa (`'0x8'`).\n\nExample: Sfocatura\n```js\nimg.blur(5);\nimg.blur('0x8');\n```\n\n### img.grayscale()\n\nType: `method`\n\nConverte l'immagine in scala di grigi.\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-colorspace Gray`.\n\nExample: Scala di grigi\n```js\nimg.grayscale();\n```\n\n### img.sepia()\n\nType: `method`\n\nDà all'immagine un tono seppia.\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-modulate 115,0,100 -colorize 7,21,50`.\n\nExample: Seppia\n```js\nimg.sepia();\n```\n\n### img.normalize()\n\nType: `method`\n\nEstende il contrasto.\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-normalize`: i colori vengono distribuiti sull'intera gamma.\n\nExample: Normalizzare\n```js\nimg.normalize();\n```\n\n### img.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` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-colors`.\n\nExample: Palette\n```js\nimg.output('png').colors(64);\n```\n\n### img.bitdepth(value)\n\nType: `method`\n\nImposta la profondità di bit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bit per canale, per esempio 8. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-depth`.\n\nExample: Profondità\n```js\nimg.bitdepth(8);\n```\n\n### img.background(color)\n\nType: `method`\n\nImposta il colore di sfondo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Il colore. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-background color` e poi `-extent 0x0`, così il colore viene impostato prima che la tela venga estesa. Il colore riempie le nuove aree create da `extent()`, `rotate()` e dagli helper di ridimensionamento. Funziona qualsiasi colore del programma: `white`, `#FF0000`, `none` per il trasparente.\n\nExample: Sfondo\n```js\nimg.background('#FFFFFF').extent(800, 800);\n```\n\n### img.fill(color)\n\nType: `method`\n\nImposta il colore di riempimento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Il colore. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-fill`. Usato dalle operazioni che disegnano, per esempio `-colorize` o le tue opzioni di `command()`.\n\nExample: Riempimento\n```js\nimg.fill('red').command('-colorize', '30');\n```\n\n### img.filter(type)\n\nType: `method`\n\nImposta il filtro di ridimensionamento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il nome del filtro. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-filter`, per esempio `'Lanczos'`, `'Hamming'`, `'Box'` o `'Triangle'`. Viene sempre messo prima di `-resize`, `-thumbnail` e `-scale`, quindi si applica a essi sia che tu lo chiami prima sia dopo `resize()`, `thumbnail()` o `scale()`.\n\nExample: Filtro\n```js\nimg.resize(400).filter('Lanczos');\n```\n\nExample: Il comando\n```js\nImage.load('photo.jpg').filter('Lanczos').resize(200, 200).cmd('photo.jpg', 'small.jpg');\n// gm convert 'photo.jpg' -filter 'Lanczos' -resize '200x200' 'small.jpg'\n```\n\n### img.define(value)\n\nType: `method`\n\nPassa un'opzione del coder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La definizione `format:key=value`. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-define`, per esempio `'jpeg:extent=200kb'` o `'png:compression-level=9'`.\n\nExample: Define\n```js\nimg.define('jpeg:extent=200kb');\n```\n\n### img.minify()\n\nType: `method`\n\nRimuove i profili e i metadati.\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `+profile '*'`, che rimuove EXIF, ICC e altri profili. `save()`, `pipe()` e `writer()` lo chiamano quando l'immagine non ha operazioni.\n\nExample: Rimuovere i metadati\n```js\nImage.load(filename).minify().save(target);\n```\n\n### img.limit(type, value)\n\nType: `method`\n\nLimita una risorsa del programma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La risorsa. |\n| `value` | `Number|String` | yes |  | Il limite, per esempio `256MB`. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-limit type value`, per esempio `limit('memory', '256MB')`. Tipi e unità sono quelli del programma (`memory`, `map`, `disk`…). Un numero senza unità è in byte.\n\nExample: Limitare la memoria\n```js\nimg.limit('memory', '256MB').limit('map', '512MB');\n```\n\n### img.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nDisegna un'altra immagine sopra la foto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il file della filigrana. |\n| `x` | `Number` | no | `0` | L'offset orizzontale. |\n| `y` | `Number` | no | `0` | L'offset verticale. |\n| `w` | `Number` | no | `0` | La larghezza della filigrana. |\n| `h` | `Number` | no | `0` | L'altezza della filigrana. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `-draw 'image over x,y w,h filename'`. L'offset è misurato dall'angolo in alto a sinistra. Larghezza e altezza pari a 0 mantengono la dimensione della filigrana. Gli apici singoli vengono rimossi dal nome del file.\n\nExample: Logo nell'angolo\n```js\nImage.load(filename)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n### img.command(key, [value], [priority], [escape])\n\nType: `method`\n\nAggiunge qualsiasi opzione del programma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | L'opzione, per esempio `-sharpen`. |\n| `value` | `String|Number` | no |  | Il valore. |\n| `priority` | `Number|Boolean` | no | `10` | La posizione, oppure `true` per mettere il valore tra virgolette. |\n| `escape` | `Boolean` | no | `false` | Mettere il valore tra virgolette. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nAggiunge `key value` al comando. `priority` decide la posizione (prima i valori più bassi, predefinito 10; le dimensioni hanno 1, la gravità 3, il crop 4, la qualità 5, la rotazione 8). `escape` mette il valore tra virgolette; passare `true` come `priority` attiva anche `escape` (con priorità 10).\n\nExample: Opzioni personalizzate\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'My photo', true);\n```\n\n### img.make(fn)\n\nType: `method`\n\nApplica una funzione all'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Riceve l'immagine. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nChiama `fn(img)` con `this` impostato sull'immagine. Usalo per riutilizzare un insieme di operazioni.\n\nExample: Preset\n```js\nfunction avatar(img) {\n\timg.resizecenter(128, 128).quality(90);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n### img.clear()\n\nType: `method`\n\nRimuove tutte le operazioni.\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nSvuota l'elenco delle operazioni. `save()` lo chiama al termine del programma.\n\nExample: Svuotare\n```js\nimg.clear().resize(100);\n```\n\n### img.output(type)\n\nType: `method`\n\nImposta il tipo dell'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il tipo, per esempio `png` o `.webp`. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nImposta `img.type` (un punto iniziale viene rimosso). `pipe()` e `writer()` producono questo formato quando non ne passi uno, e `Image.middleware()` viene confrontato con esso. `save()` prende il formato dall'estensione del file di destinazione.\n\nExample: Da Buffer a PNG\n```js\nImage.load(buffer).output('png').resize(100).pipe($.res);\n```\n\n### img.save([filename], [callback])\n\nType: `method`\n\nEsegue il programma e scrive il risultato in un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `img.filename` | Il file di destinazione. |\n| `callback` | `Function` | no |  | `function(err, success)`. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nCostruisce il comando e lo esegue. Il formato deriva dall'estensione di `filename`. Senza `filename` il file sorgente viene sovrascritto. Una sorgente Buffer o stream viene inviata allo standard input. La callback riceve `(err, success)`, dove `success` è `true` o `false`. Le operazioni vengono poi svuotate.\n\nExample: Salvare\n```js\nImage.load(file.path).resize(1024).quality(80).save(PATH.public('photos/' + id + '.jpg'), function(err) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success();\n});\n```\n\n### img.pipe(stream, [type], [options])\n\nType: `method`\n\nEsegue il programma e invia il risultato a uno stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Uno stream scrivibile, per esempio `$.res`. |\n| `type` | `String` | no | `img.type` | Il formato di output. |\n| `options` | `Object` | no |  | Opzioni di `stream.pipe()`. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nScrive l'output del programma su `stream`. `type` è il formato di output: `jpg`, `jpeg`, `png`, `gif`, `apng`, `webp`, `heif`, `heic` o `ico`; altri valori usano `img.type`. `options` viene passato a `stream.pipe()` (per esempio `{ end: false }`); puoi passarlo come secondo argomento. I messaggi del programma sullo standard error vengono emessi come eventi `error` su `stream`.\n\nExample: Inviare alla risposta\n```js\nfunction preview($) {\n\t$.res.writeHead(200, { 'content-type': 'image/png' });\n\tImage.load(PATH.public('photo.jpg')).resize(300).pipe($.res, 'png');\n}\n```\n\n### img.writer([type])\n\nType: `method`\n\nEsegue il programma e restituisce lo stream di output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `img.type` | Il formato di output. |\n\nReturns: `Stream` Uno stream leggibile con il risultato.\n\nAvvia il programma e restituisce il suo output leggibile (passato attraverso l'`Image.middleware()` del tipo, se presente). `type` accetta gli stessi valori di `pipe()`.\n\nExample: Raccogliere in un Buffer\n```js\nvar chunks = [];\nvar stream = Image.load(buffer).resize(100, 100).writer('webp');\nstream.on('data', chunk => chunks.push(chunk));\nstream.on('end', function() {\n\tvar output = Buffer.concat(chunks);\n});\n```\n\n### img.measure(callback)\n\nType: `method`\n\nLegge la dimensione del file sorgente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, size)`. |\n\nReturns: `Image` Lo stesso oggetto immagine, per il concatenamento.\n\nLegge l'header del file sorgente e chiama `callback(err, size)` con `{ width, height }`. Per un file `.jpg` senza l'header del frame nei suoi primi 40 kB, `size` è `null`. La sorgente deve essere un nome di file con estensione `.jpg`, `.png`, `.gif` o `.webp`; altre estensioni danno un errore. Non usa il programma esterno.\n\nExample: Misurare un file\n```js\nImage.load(PATH.public('photo.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### img.cmd(from, to)\n\nType: `method`\n\nRestituisce la riga di comando senza eseguirla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | Il file sorgente o `-`. |\n| `to` | `String` | yes |  | Il file di destinazione o `-`. |\n\nReturns: `String` La riga di comando.\n\nCostruisce il comando usato da `save()`: il programma, la sorgente tra virgolette, le operazioni ordinate e la destinazione tra virgolette. Usa `'-'` per lo standard input o output. Utile per il debug.\n\nExample: Mostrare il comando\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n","entries":[{"type":"class","name":"Image","signature":"Image","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"F.image()","signature":"F.image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"class","name":"Image.Image","signature":"new Image.Image(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.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(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.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"property","name":"img.width","signature":"img.width","since":"","deprecated":false},{"type":"property","name":"img.filename","signature":"img.filename","since":"","deprecated":false},{"type":"property","name":"img.stream","signature":"img.stream","since":"","deprecated":false},{"type":"property","name":"img.type","signature":"img.type","since":"","deprecated":false},{"type":"property","name":"img.shell","signature":"img.shell","since":"","deprecated":false},{"type":"method","name":"img.resize()","signature":"img.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.thumbnail()","signature":"img.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.scale()","signature":"img.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.geometry()","signature":"img.geometry([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.crop()","signature":"img.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.extent()","signature":"img.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.miniature()","signature":"img.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"img.resizecenter()","signature":"img.resizecenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"img.resizealign()","signature":"img.resizealign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"img.align()","signature":"img.align(type)","since":"","deprecated":false},{"type":"method","name":"img.gravity()","signature":"img.gravity(type)","since":"","deprecated":false},{"type":"method","name":"img.quality()","signature":"img.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"img.rotate()","signature":"img.rotate([deg])","since":"","deprecated":false},{"type":"method","name":"img.flip()","signature":"img.flip()","since":"","deprecated":false},{"type":"method","name":"img.flop()","signature":"img.flop()","since":"","deprecated":false},{"type":"method","name":"img.blur()","signature":"img.blur(radius)","since":"","deprecated":false},{"type":"method","name":"img.grayscale()","signature":"img.grayscale()","since":"","deprecated":false},{"type":"method","name":"img.sepia()","signature":"img.sepia()","since":"","deprecated":false},{"type":"method","name":"img.normalize()","signature":"img.normalize()","since":"","deprecated":false},{"type":"method","name":"img.colors()","signature":"img.colors(value)","since":"","deprecated":false},{"type":"method","name":"img.bitdepth()","signature":"img.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"img.background()","signature":"img.background(color)","since":"","deprecated":false},{"type":"method","name":"img.fill()","signature":"img.fill(color)","since":"","deprecated":false},{"type":"method","name":"img.filter()","signature":"img.filter(type)","since":"","deprecated":false},{"type":"method","name":"img.define()","signature":"img.define(value)","since":"","deprecated":false},{"type":"method","name":"img.minify()","signature":"img.minify()","since":"","deprecated":false},{"type":"method","name":"img.limit()","signature":"img.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"img.watermark()","signature":"img.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"img.command()","signature":"img.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"img.make()","signature":"img.make(fn)","since":"","deprecated":false},{"type":"method","name":"img.clear()","signature":"img.clear()","since":"","deprecated":false},{"type":"method","name":"img.output()","signature":"img.output(type)","since":"","deprecated":false},{"type":"method","name":"img.save()","signature":"img.save([filename], [callback])","since":"","deprecated":false},{"type":"method","name":"img.pipe()","signature":"img.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"img.writer()","signature":"img.writer([type])","since":"","deprecated":false},{"type":"method","name":"img.measure()","signature":"img.measure(callback)","since":"","deprecated":false},{"type":"method","name":"img.cmd()","signature":"img.cmd(from, to)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwTD5Lx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/images/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Obrázky","summary":"Globálny objekt Image a všetky metódy objektov obrázkov.","markdown":"---\ntitle: \"Obrázky\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/images/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Obrázky\n\n> Globálny objekt Image a všetky metódy objektov obrázkov.\n\nGlobálny objekt `Image` načítava, upravuje, meria a ukladá obrázky pomocou GraphicsMagick alebo ImageMagick. Návod [Obrázky](../../guides/images/) vysvetľuje jeho použitie na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### Image\n\nType: `class`\n\nGlobálny modul pre obrázky.\n\n`Image` je modul frameworku pre obrázky. Obsahuje `Image.load()` na vytvorenie objektov obrázkov, funkcie `Image.measure*()`, ktoré čítajú veľkosť z hlavičky súboru, `Image.middleware()` a konštruktor `Image.Image`. Operácie sa spúšťajú programom nastaveným v `$imageconverter`.\n\nExample: Zmena veľkosti fotky\n```js\nImage.load(PATH.public('photo.jpg')).resize(800).save(PATH.public('photo-800.jpg'));\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nVytvorí objekt obrázka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Názov súboru, Buffer alebo čitateľný stream. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Program: `gm`, `im` alebo `magick`. |\n| `width` | `Number` | no |  | Známa šírka, uloží sa do `img.width`. |\n| `height` | `Number` | no |  | Známa výška, uloží sa do `img.height`. |\n\nReturns: `Image` Nový objekt obrázka.\n\n`source` je názov súboru, `Buffer` alebo čitateľný stream. Pri názve súboru je `img.type` jeho prípona; inak je to `jpg`. `converter` je `gm`, `im` alebo `magick` a pre tento obrázok prepíše `$imageconverter`. `width` a `height` sa iba uložia do `img.width` a `img.height`; zo súboru sa nečítajú.\n\nExample: Načítanie zo súboru a z buffera\n```js\nvar a = Image.load(PATH.public('photo.jpg'));\nvar b = Image.load(buffer, 'magick');\n```\n\n### F.image(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|Buffer|Stream` | yes |  | Názov súboru, Buffer alebo čitateľný stream. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Program: `gm`, `im` alebo `magick`. |\n| `width` | `Number` | no |  | Známa šírka. |\n| `height` | `Number` | no |  | Známa výška. |\n\nReturns: `Image` Nový objekt obrázka.\n\nAlias `Image.load()` na objekte frameworku.\n\nExample: Načítanie obrázka\n```js\nF.image(filename).grayscale().save(target);\n```\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nKonštruktor objektov obrázkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Buffer|Stream` | yes |  | Názov súboru, Buffer alebo čitateľný stream. |\n| `converter` | `String` | no | `CONF.$imageconverter` | Program: `gm`, `im` alebo `magick`. |\n| `width` | `Number` | no |  | Známa šírka. |\n| `height` | `Number` | no |  | Známa výška. |\n\n`Image.load()` vracia `new Image.Image(...)` s rovnakými argumentmi. Použi ho, keď chceš testovať `img instanceof Image.Image` alebo pridať vlastné metódy do `Image.Image.prototype`.\n\nExample: Pridanie metódy\n```js\nImage.Image.prototype.avatar = function() {\n\treturn this.resizecenter(128, 128).quality(90);\n};\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nPrečíta šírku a výšku z hlavičky obrázka.\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. |\n\nReturns: `Object` `{ width, height }`, `null` pre JPEG bez značky veľkosti, `undefined` pre nepodporovaný typ.\n\n`type` je prípona s bodkou alebo bez nej (`jpg`, `.png`) alebo MIME typ (`image/webp`). Podporované typy sú JPEG, PNG, GIF, WebP, SVG, BMP a PSD. Buffer potrebuje iba začiatok súboru. Pre iné typy vracia `undefined`. Pre JPEG buffer bez značky veľkosti vracia `null`.\n\nExample: Meranie nahraného buffera\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\t$.invalid('The image is too wide');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nPrečíta veľkosť obrázka JPEG z buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }` alebo `null`.\n\nPrechádza značky až po hlavičku snímky. Vracia `null`, keď buffer nie je JPEG alebo keď hlavička snímky nie je v bufferi (poškodený súbor, segment s neplatnou dĺžkou alebo príliš málo dát). Odovzdaj dosť dát: framework číta 40 kB.\n\nExample: Meranie\n```js\nvar size = Image.measureJPG(buffer);\nconsole.log(size.width, size.height);\n```\n\nExample: JPEG bez veľkosti\n```js\nvar buffer = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00]);\nvar size = Image.measureJPG(buffer);\nconsole.log(size); // null: no frame header in the buffer\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nPrečíta veľkosť obrázka PNG z buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`.\n\nČíta hlavičku IHDR, takže stačí 24 bajtov.\n\nExample: Meranie\n```js\nvar size = Image.measurePNG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nPrečíta veľkosť obrázka GIF z buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`.\n\nČíta logickú veľkosť obrazovky, takže stačí 10 bajtov.\n\nExample: Meranie\n```js\nvar size = Image.measureGIF(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nPrečíta veľkosť obrázka WebP z buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`.\n\nČíta hlavičky `VP8 `, `VP8L` a `VP8X`. Pre iné dáta vracia `undefined`.\n\nExample: Meranie\n```js\nvar size = Image.measureWEBP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nPrečíta veľkosť obrázka SVG z buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`.\n\nČíta prvé atribúty `width=\"...\"` a `height=\"...\"` s celými číslami. Keď žiadne nie sú, vracia `undefined`.\n\nExample: Meranie\n```js\nvar size = Image.measureSVG(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nPrečíta veľkosť obrázka BMP z buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`.\n\nČíta BITMAPINFOHEADER.\n\nExample: Meranie\n```js\nvar size = Image.measureBMP(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nPrečíta veľkosť obrázka Photoshop (PSD) z buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`.\n\nČíta hlavičku súboru PSD.\n\nExample: Meranie\n```js\nvar size = Image.measurePSD(buffer);\nconsole.log(size.width, size.height);\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nZaregistruje stream, ktorý dodatočne spracuje výsledky jedného typu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Typ obrázka, napríklad `png` alebo `.jpg`. |\n| `fn` | `Function` | yes |  | Vracia Transform stream. |\n\n`fn` musí pri každom volaní vrátiť nový Transform stream. Pri `pipe()` a `writer()` ním prejde výstup programu skôr, ako sa dostane k tebe, a `type` sa porovnáva s výstupným formátom. Pri `save()` s callbackom sa uložený súbor cez neho prečíta a znova zapíše pred spustením callbacku; tam sa `type` porovnáva s `img.type` (prípona zdroja alebo hodnota `output()`). Úvodná bodka v `type` sa odstráni. Jedna funkcia na typ; nové volanie ju nahradí.\n\nExample: Prechod výsledkov PNG cez stream\n```js\nvar Transform = require('stream').Transform;\n\nImage.middleware('png', function() {\n\treturn new Transform({\n\t\ttransform: function(chunk, encoding, next) {\n\t\t\tnext(null, chunk);\n\t\t}\n\t});\n});\n```\n\n### img.width\n\nType: `property`\n\nŠírka odovzdaná do `Image.load()`.\n\nReturns: `Number`\n\nTretí argument `Image.load()` alebo `undefined`. Zo súboru sa nečíta; na to použi `img.measure()`. `img.height` rovnako obsahuje štvrtý argument.\n\nExample: Známa veľkosť\n```js\nvar img = Image.load(file.path, null, file.width, file.height);\nif (img.width > 1000)\n\timg.resize(1000);\n```\n\n### img.filename\n\nType: `property`\n\nNázov zdrojového súboru.\n\nReturns: `String`\n\nNázov súboru odovzdaný do `Image.load()` alebo `null`, keď je zdrojom Buffer alebo stream.\n\n### img.stream\n\nType: `property`\n\nZdrojový Buffer alebo stream.\n\nReturns: `Buffer|Stream`\n\nBuffer alebo čitateľný stream odovzdaný do `Image.load()` alebo `null`, keď je zdrojom názov súboru. Pri uložení alebo presmerovaní obrázka sa zapíše na štandardný vstup programu.\n\n### img.type\n\nType: `property`\n\nTyp obrázka.\n\nReturns: `String`\n\nPrípona zdrojového súboru malými písmenami bez bodky (`jpg`, `png`…) alebo `jpg` pre Buffer či stream. Mení ho `output()`. `pipe()` a `writer()` ho použijú ako výstupný formát, keď žiadny neodovzdáš, a porovnávajú sa s ním handlery `Image.middleware()`.\n\n### img.shell\n\nType: `property`\n\nProgram, ktorý spracúva obrázok.\n\nReturns: `String`\n\n`gm`, `im` alebo `magick`: druhý argument `Image.load()`, inak `CONF.$imageconverter`. `gm` spúšťa `gm convert`, `im` spúšťa `convert` a `magick` spúšťa `magick`. Pred uložením obrázka ho môžeš zmeniť.\n\n### img.resize([w], [h], [options])\n\nType: `method`\n\nZmení veľkosť obrázka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | Šírka v pixeloch alebo percentá ako `'50%'`. Prázdne na zachovanie pomeru. |\n| `h` | `Number|String` | no |  | Výška v pixeloch alebo percentá. Prázdne na zachovanie pomeru. |\n| `options` | `String` | no |  | Prípona veľkosti: `!` ignoruje pomer, `^` vyplní rámček, `>` iba zmenšuje, `<` iba zväčšuje. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-resize WxH`. Obrázok sa zmestí do rámčeka a zachová si pomer strán, ak `options` neurčuje inak. Iba so `w` sa výška riadi pomerom, iba s `h` šírka.\n\nExample: Zmena veľkosti\n```js\nimg.resize(800, 600);   // into 800x600\nimg.resize(800);        // width 800\nimg.resize(null, 600);  // height 600\nimg.resize(200, 200, '!'); // exactly 200x200\nimg.resize('50%');      // half size\n```\n\n### img.thumbnail([w], [h], [options])\n\nType: `method`\n\nZmení veľkosť obrázka pre malý náhľad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | Šírka v pixeloch alebo percentá ako `'50%'`. Prázdne na zachovanie pomeru. |\n| `h` | `Number|String` | no |  | Výška v pixeloch alebo percentá. Prázdne na zachovanie pomeru. |\n| `options` | `String` | no |  | Prípona veľkosti: `!` ignoruje pomer, `^` vyplní rámček, `>` iba zmenšuje, `<` iba zväčšuje. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-thumbnail WxH`: zmenu veľkosti, ktorá zároveň odstráni profily, takže súbor je menší. Argumenty sú rovnaké ako v `resize()`.\n\nExample: Náhľad\n```js\nImage.load(filename).thumbnail(150, 150).save(target);\n```\n\n### img.scale([w], [h], [options])\n\nType: `method`\n\nRýchlo zmení veľkosť obrázka bez filtrovania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | Šírka v pixeloch alebo percentá ako `'50%'`. Prázdne na zachovanie pomeru. |\n| `h` | `Number|String` | no |  | Výška v pixeloch alebo percentá. Prázdne na zachovanie pomeru. |\n| `options` | `String` | no |  | Prípona veľkosti: `!` ignoruje pomer, `^` vyplní rámček, `>` iba zmenšuje, `<` iba zväčšuje. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-scale WxH`. Rýchlejšie ako `resize()`, ale s nižšou kvalitou. Argumenty sú rovnaké ako v `resize()`.\n\nExample: Škálovanie\n```js\nimg.scale(64, 64);\n```\n\n### img.geometry([w], [h], [options])\n\nType: `method`\n\nPridá voľbu `-geometry`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number|String` | no |  | Šírka v pixeloch alebo percentá ako `'50%'`. Prázdne na zachovanie pomeru. |\n| `h` | `Number|String` | no |  | Výška v pixeloch alebo percentá. Prázdne na zachovanie pomeru. |\n| `options` | `String` | no |  | Prípona veľkosti: `!` ignoruje pomer, `^` vyplní rámček, `>` iba zmenšuje, `<` iba zväčšuje. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-geometry WxH` s voliteľnou príponou. Program ju použije ako preferovanú veľkosť a posun.\n\nExample: Geometria\n```js\nimg.geometry(300, 200, '!');\n```\n\n### img.crop(w, h, [x], [y])\n\nType: `method`\n\nVyreže oblasť obrázka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Šírka oblasti. |\n| `h` | `Number` | yes |  | Výška oblasti. |\n| `x` | `Number` | no | `0` | Vodorovný posun. |\n| `y` | `Number` | no | `0` | Zvislý posun. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-crop WxH+X+Y`. Posun sa meria od rohu nastaveného cez `align()` (predvolene ľavý horný).\n\nExample: Orezanie\n```js\nimg.crop(400, 300, 50, 20);\n\n// The centre\nimg.align('center').crop(400, 300);\n```\n\n### img.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 plátna. |\n| `h` | `Number` | no |  | Výška plátna. |\n| `x` | `Number` | no |  | Vodorovný posun, môže byť záporný. |\n| `y` | `Number` | no |  | Zvislý posun, môže byť záporný. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-extent WxH` s voliteľným posunom. Väčšie plátno sa vyplní farbou pozadia, menšie obrázok oreže. Pozícia sa riadi podľa `align()`.\n\nExample: Štvorcové plátno\n```js\nimg.resize(500, 500).background('white').align('center').extent(500, 500);\n```\n\n### img.miniature(w, h, [color], [filter])\n\nType: `method`\n\nVloží obrázok do rámčeka a zvyšok vyplní.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Šírka. |\n| `h` | `Number` | yes |  | Výška. |\n| `color` | `String` | no | `'white'` | Farba voľnej plochy. |\n| `filter` | `String` | no | `'Hamming'` | Filter na zmenu veľkosti. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nSkratka pre `thumbnail(w, h).background(color).align('center').extent(w, h)`. Výsledok má presne `w`x`h` a ukazuje celý obrázok. `filter` je filter na zmenu veľkosti pre `thumbnail()`.\n\nExample: Fotka produktu\n```js\nImage.load(filename).miniature(300, 300, '#F0F0F0').save(target);\n```\n\n### img.resizecenter(w, h, [color])\n\nType: `method`\n\nVyplní rámček a oreže stred.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Šírka. |\n| `h` | `Number` | yes |  | Výška. |\n| `color` | `String` | no | `'white'` | Farba pozadia. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nSkratka pre `resize(w, h, '^').background(color).align('center').crop(w, h)`. Výsledok má `w`x`h` a obrázok ho úplne pokrýva.\n\nExample: Pokrytie\n```js\nImage.load(filename).resizecenter(1200, 630).save(target);\n```\n\n### img.resizealign(w, h, [align], [color])\n\nType: `method`\n\nVyplní rámček a oreže pri okraji.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Šírka. |\n| `h` | `Number` | yes |  | Výška. |\n| `align` | `String` | no | `'center'` | Kde orezať: `top`, `bottom`, `left`, `center`… |\n| `color` | `String` | no | `'white'` | Farba pozadia. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nSkratka pre `resize(w, h, '^').background(color).align(align).crop(w, h)`. `align` prijíma hodnoty `align()`.\n\nExample: Avatar\n```js\nImage.load(filename).resizealign(200, 200, 'top').save(target);\n```\n\n### img.align(type)\n\nType: `method`\n\nNastaví gravitáciu pre crop a extent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Pozícia. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-gravity`. Prijímané hodnoty: `'top left'` (NorthWest), `'top'` (North), `'top right'` (NorthEast), `'left'` (West), `'center'` alebo `'middle'` (Center), `'right'` (East), `'bottom left'` (SouthWest), `'bottom'` (South), `'bottom right'` (SouthEast). Na poradí slov nezáleží (`'left top'`) a `'center left'` znamená `left`. Iné hodnoty sa odovzdajú bez zmeny, napríklad `'NorthEast'`.\n\nExample: Zarovnanie\n```js\nimg.align('bottom right').crop(400, 300);\n```\n\n### img.gravity(type)\n\nType: `method`\n\nRovnaká metóda ako `align()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Pozícia. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nAlias `align()`.\n\nExample: Gravitácia\n```js\nimg.gravity('NorthWest');\n```\n\n### img.quality([percentage])\n\nType: `method`\n\nNastaví kvalitu kompresie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | Kvalita. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-quality`. Pre JPEG a WebP je to kvalita od 1 do 100; prázdna hodnota znamená 80.\n\nExample: Kvalita\n```js\nimg.quality(70);\n```\n\n### img.rotate([deg])\n\nType: `method`\n\nOtočí obrázok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | no | `0` | Uhol v stupňoch. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-rotate`. Uhol je v stupňoch v smere hodinových ručičiek. Pri uhloch, ktoré nie sú násobkami 90, sa rohy vyplnia farbou pozadia.\n\nExample: Otočenie\n```js\nimg.background('white').rotate(45);\n```\n\n### img.flip()\n\nType: `method`\n\nZrkadlovo prevráti obrázok zvisle.\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-flip` (zhora nadol).\n\nExample: Flip\n```js\nimg.flip();\n```\n\n### img.flop()\n\nType: `method`\n\nZrkadlovo prevráti obrázok vodorovne.\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-flop` (zľava doprava).\n\nExample: Flop\n```js\nimg.flop();\n```\n\n### img.blur(radius)\n\nType: `method`\n\nRozmaže obrázok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | Polomer alebo `radiusxsigma`. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-blur`. Hodnota je polomer alebo `radiusxsigma` ako reťazec (`'0x8'`).\n\nExample: Rozmazanie\n```js\nimg.blur(5);\nimg.blur('0x8');\n```\n\n### img.grayscale()\n\nType: `method`\n\nPrevedie obrázok do odtieňov sivej.\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-colorspace Gray`.\n\nExample: Odtiene sivej\n```js\nimg.grayscale();\n```\n\n### img.sepia()\n\nType: `method`\n\nDá obrázku tón sépie.\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-modulate 115,0,100 -colorize 7,21,50`.\n\nExample: Sépia\n```js\nimg.sepia();\n```\n\n### img.normalize()\n\nType: `method`\n\nRoztiahne kontrast.\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-normalize`: farby sa rozložia na celý rozsah.\n\nExample: Normalizácia\n```js\nimg.normalize();\n```\n\n### img.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ý objekt obrázka, na reťazenie.\n\nPridá `-colors`.\n\nExample: Paleta\n```js\nimg.output('png').colors(64);\n```\n\n### img.bitdepth(value)\n\nType: `method`\n\nNastaví bitovú hĺbku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bity na kanál, napríklad 8. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-depth`.\n\nExample: Hĺbka\n```js\nimg.bitdepth(8);\n```\n\n### img.background(color)\n\nType: `method`\n\nNastaví farbu pozadia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Farba. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-background color` a potom `-extent 0x0`, takže farba sa nastaví ešte pred rozšírením plátna. Farba vyplní nové plochy, ktoré vzniknú cez `extent()`, `rotate()` a pomocné funkcie na zmenu veľkosti. Funguje akákoľvek farba programu: `white`, `#FF0000`, `none` pre priehľadnú.\n\nExample: Pozadie\n```js\nimg.background('#FFFFFF').extent(800, 800);\n```\n\n### img.fill(color)\n\nType: `method`\n\nNastaví farbu výplne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Farba. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-fill`. Používajú ju operácie, ktoré kreslia, napríklad `-colorize` alebo tvoje vlastné voľby `command()`.\n\nExample: Výplň\n```js\nimg.fill('red').command('-colorize', '30');\n```\n\n### img.filter(type)\n\nType: `method`\n\nNastaví filter na zmenu veľkosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Názov filtra. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-filter`, napríklad `'Lanczos'`, `'Hamming'`, `'Box'` alebo `'Triangle'`. Vždy sa umiestni pred `-resize`, `-thumbnail` a `-scale`, takže sa na ne použije, či ho zavoláš pred alebo po `resize()`, `thumbnail()` alebo `scale()`.\n\nExample: Filter\n```js\nimg.resize(400).filter('Lanczos');\n```\n\nExample: Príkaz\n```js\nImage.load('photo.jpg').filter('Lanczos').resize(200, 200).cmd('photo.jpg', 'small.jpg');\n// gm convert 'photo.jpg' -filter 'Lanczos' -resize '200x200' 'small.jpg'\n```\n\n### img.define(value)\n\nType: `method`\n\nOdovzdá voľbu kodeku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Definícia `format:key=value`. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-define`, napríklad `'jpeg:extent=200kb'` alebo `'png:compression-level=9'`.\n\nExample: Define\n```js\nimg.define('jpeg:extent=200kb');\n```\n\n### img.minify()\n\nType: `method`\n\nOdstráni profily a metadáta.\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `+profile '*'`, čo odstráni EXIF, ICC a ďalšie profily. `save()`, `pipe()` a `writer()` ju volajú, keď obrázok nemá žiadne operácie.\n\nExample: Odstránenie metadát\n```js\nImage.load(filename).minify().save(target);\n```\n\n### img.limit(type, value)\n\nType: `method`\n\nObmedzí zdroj programu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Zdroj. |\n| `value` | `Number|String` | yes |  | Limit, napríklad `256MB`. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá `-limit type value`, napríklad `limit('memory', '256MB')`. Typy a jednotky sú tie, ktoré používa program (`memory`, `map`, `disk`…). Číslo bez jednotky je v bajtoch.\n\nExample: Obmedzenie pamäte\n```js\nimg.limit('memory', '256MB').limit('map', '512MB');\n```\n\n### img.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nNakreslí cez obrázok iný obrázok.\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ý objekt obrázka, na reťazenie.\n\nPridá `-draw 'image over x,y w,h filename'`. Posun sa meria od ľavého horného rohu. Šírka a výška 0 zachovajú veľkosť vodoznaku. Jednoduché úvodzovky sa z názvu súboru odstránia.\n\nExample: Logo v rohu\n```js\nImage.load(filename)\n\t.watermark(PATH.public('img/logo.png'), 20, 20, 120, 40)\n\t.save(target);\n```\n\n### img.command(key, [value], [priority], [escape])\n\nType: `method`\n\nPridá ľubovoľnú voľbu programu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Voľba, napríklad `-sharpen`. |\n| `value` | `String|Number` | no |  | Hodnota. |\n| `priority` | `Number|Boolean` | no | `10` | Pozícia alebo `true` na uzavretie hodnoty do úvodzoviek. |\n| `escape` | `Boolean` | no | `false` | Uzavrieť hodnotu do úvodzoviek. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPridá do príkazu `key value`. `priority` určuje pozíciu (nižšia skôr, predvolene 10; veľkosti majú 1, gravitácia 3, crop 4, kvalita 5, rotate 8). `escape` vloží hodnotu do úvodzoviek; odovzdanie `true` ako `priority` tiež zapne `escape` (s prioritou 10).\n\nExample: Vlastné voľby\n```js\nimg.command('-sharpen', '0x1');\nimg.command('-strip');\nimg.command('-label', 'My photo', true);\n```\n\n### img.make(fn)\n\nType: `method`\n\nAplikuje na obrázok funkciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Dostane obrázok. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nZavolá `fn(img)` s `this` nastaveným na obrázok. Použi ju na opakované použitie sady operácií.\n\nExample: Predvoľba\n```js\nfunction avatar(img) {\n\timg.resizecenter(128, 128).quality(90);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n### img.clear()\n\nType: `method`\n\nOdstráni všetky operácie.\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nVyprázdni zoznam operácií. `save()` ju volá po skončení programu.\n\nExample: Vyčistenie\n```js\nimg.clear().resize(100);\n```\n\n### img.output(type)\n\nType: `method`\n\nNastaví typ obrázka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Typ, napríklad `png` alebo `.webp`. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nNastaví `img.type` (úvodná bodka sa odstráni). `pipe()` a `writer()` vytvoria tento formát, keď žiadny neodovzdáš, a porovnáva sa s ním `Image.middleware()`. `save()` berie formát z prípony cieľového súboru.\n\nExample: Buffer do PNG\n```js\nImage.load(buffer).output('png').resize(100).pipe($.res);\n```\n\n### img.save([filename], [callback])\n\nType: `method`\n\nSpustí program a zapíše výsledok do súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `img.filename` | Cieľový súbor. |\n| `callback` | `Function` | no |  | `function(err, success)`. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nZostaví príkaz a spustí ho. Formát sa určí z prípony `filename`. Bez `filename` sa prepíše zdrojový súbor. Zdroj typu Buffer alebo stream sa pošle na štandardný vstup. Callback dostane `(err, success)`, kde `success` je `true` alebo `false`. Operácie sa potom vyčistia.\n\nExample: Uloženie\n```js\nImage.load(file.path).resize(1024).quality(80).save(PATH.public('photos/' + id + '.jpg'), function(err) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success();\n});\n```\n\n### img.pipe(stream, [type], [options])\n\nType: `method`\n\nSpustí program a pošle výsledok do streamu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Zapisovateľný stream, napríklad `$.res`. |\n| `type` | `String` | no | `img.type` | Výstupný formát. |\n| `options` | `Object` | no |  | Voľby `stream.pipe()`. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nZapíše výstup programu do `stream`. `type` je výstupný formát: `jpg`, `jpeg`, `png`, `gif`, `apng`, `webp`, `heif`, `heic` alebo `ico`; iné hodnoty použijú `img.type`. `options` ide do `stream.pipe()` (napríklad `{ end: false }`); môžeš ho odovzdať ako druhý argument. Správy programu na štandardnom chybovom výstupe sa na `stream` emitujú ako udalosti `error`.\n\nExample: Odoslanie do odpovede\n```js\nfunction preview($) {\n\t$.res.writeHead(200, { 'content-type': 'image/png' });\n\tImage.load(PATH.public('photo.jpg')).resize(300).pipe($.res, 'png');\n}\n```\n\n### img.writer([type])\n\nType: `method`\n\nSpustí program a vráti výstupný stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `img.type` | Výstupný formát. |\n\nReturns: `Stream` Čitateľný stream s výsledkom.\n\nSpustí program a vráti jeho čitateľný výstup (prejde cez `Image.middleware()` daného typu, ak existuje). `type` prijíma rovnaké hodnoty ako v `pipe()`.\n\nExample: Zozbieranie do buffera\n```js\nvar chunks = [];\nvar stream = Image.load(buffer).resize(100, 100).writer('webp');\nstream.on('data', chunk => chunks.push(chunk));\nstream.on('end', function() {\n\tvar output = Buffer.concat(chunks);\n});\n```\n\n### img.measure(callback)\n\nType: `method`\n\nPrečíta veľkosť zdrojového súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, size)`. |\n\nReturns: `Image` Ten istý objekt obrázka, na reťazenie.\n\nPrečíta hlavičku zdrojového súboru a zavolá `callback(err, size)` s `{ width, height }`. Pre súbor `.jpg` bez hlavičky snímky v prvých 40 kB je `size` `null`. Zdrojom musí byť názov súboru s príponou `.jpg`, `.png`, `.gif` alebo `.webp`; iné prípony vrátia chybu. Externý program nepoužíva.\n\nExample: Meranie súboru\n```js\nImage.load(PATH.public('photo.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### img.cmd(from, to)\n\nType: `method`\n\nVráti príkazový riadok bez jeho spustenia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | Zdrojový súbor alebo `-`. |\n| `to` | `String` | yes |  | Cieľový súbor alebo `-`. |\n\nReturns: `String` Príkazový riadok.\n\nZostaví príkaz, ktorý používa `save()`: program, zdroj v úvodzovkách, zoradené operácie a cieľ v úvodzovkách. Pre štandardný vstup alebo výstup použi `'-'`. Užitočné pri ladení.\n\nExample: Zobrazenie príkazu\n```js\nvar img = Image.load('photo.jpg').resize(200, 100);\nconsole.log(img.cmd('photo.jpg', 'small.jpg'));\n// gm convert 'photo.jpg' -resize '200x100' 'small.jpg'\n```\n","entries":[{"type":"class","name":"Image","signature":"Image","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"F.image()","signature":"F.image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"class","name":"Image.Image","signature":"new Image.Image(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.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(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.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"property","name":"img.width","signature":"img.width","since":"","deprecated":false},{"type":"property","name":"img.filename","signature":"img.filename","since":"","deprecated":false},{"type":"property","name":"img.stream","signature":"img.stream","since":"","deprecated":false},{"type":"property","name":"img.type","signature":"img.type","since":"","deprecated":false},{"type":"property","name":"img.shell","signature":"img.shell","since":"","deprecated":false},{"type":"method","name":"img.resize()","signature":"img.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.thumbnail()","signature":"img.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.scale()","signature":"img.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.geometry()","signature":"img.geometry([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"img.crop()","signature":"img.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.extent()","signature":"img.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"img.miniature()","signature":"img.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"img.resizecenter()","signature":"img.resizecenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"img.resizealign()","signature":"img.resizealign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"img.align()","signature":"img.align(type)","since":"","deprecated":false},{"type":"method","name":"img.gravity()","signature":"img.gravity(type)","since":"","deprecated":false},{"type":"method","name":"img.quality()","signature":"img.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"img.rotate()","signature":"img.rotate([deg])","since":"","deprecated":false},{"type":"method","name":"img.flip()","signature":"img.flip()","since":"","deprecated":false},{"type":"method","name":"img.flop()","signature":"img.flop()","since":"","deprecated":false},{"type":"method","name":"img.blur()","signature":"img.blur(radius)","since":"","deprecated":false},{"type":"method","name":"img.grayscale()","signature":"img.grayscale()","since":"","deprecated":false},{"type":"method","name":"img.sepia()","signature":"img.sepia()","since":"","deprecated":false},{"type":"method","name":"img.normalize()","signature":"img.normalize()","since":"","deprecated":false},{"type":"method","name":"img.colors()","signature":"img.colors(value)","since":"","deprecated":false},{"type":"method","name":"img.bitdepth()","signature":"img.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"img.background()","signature":"img.background(color)","since":"","deprecated":false},{"type":"method","name":"img.fill()","signature":"img.fill(color)","since":"","deprecated":false},{"type":"method","name":"img.filter()","signature":"img.filter(type)","since":"","deprecated":false},{"type":"method","name":"img.define()","signature":"img.define(value)","since":"","deprecated":false},{"type":"method","name":"img.minify()","signature":"img.minify()","since":"","deprecated":false},{"type":"method","name":"img.limit()","signature":"img.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"img.watermark()","signature":"img.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"img.command()","signature":"img.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"img.make()","signature":"img.make(fn)","since":"","deprecated":false},{"type":"method","name":"img.clear()","signature":"img.clear()","since":"","deprecated":false},{"type":"method","name":"img.output()","signature":"img.output(type)","since":"","deprecated":false},{"type":"method","name":"img.save()","signature":"img.save([filename], [callback])","since":"","deprecated":false},{"type":"method","name":"img.pipe()","signature":"img.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"img.writer()","signature":"img.writer([type])","since":"","deprecated":false},{"type":"method","name":"img.measure()","signature":"img.measure(callback)","since":"","deprecated":false},{"type":"method","name":"img.cmd()","signature":"img.cmd(from, to)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwSk45x60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/ai-models/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"AI models","summary":"NEWAIMODEL(), AIMODEL(), the request methods and properties, and the AI stream parser.","markdown":"---\ntitle: AI models\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/ai-models/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# AI models\n\n> NEWAIMODEL(), AIMODEL(), the request methods and properties, and the AI stream parser.\n\nThis page lists the global functions for AI models, the methods and properties of the request object of `AIMODEL()`, the model handler and, where available, the stream parser and its events. The guide [AI models](../../guides/ai-models/) explains how they work together, with a complete handler.\n\n## API\n\n### NEWAIMODEL(name, [config], handler)\n\nType: `method` · Since: `0.0.16`\n\nRegisters a handler for one or more AI models.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The model name, or several names separated by commas. |\n| `config` | `Object` | no |  | Default config (URL, token, settings) copied into `ai.config` of each request. |\n| `handler` | `Function` | yes |  | `function(ai, callback)`. Calls the provider and ends with `callback(err, response)`. |\n\nReturns: `undefined`\n\nStores `handler` with `config` in `F.aimodels` under each name of `name` (names separated by commas are trimmed). A name registered again replaces the previous handler. The handler is called by every request of `AIMODEL()` with that name. Before it runs, every key of `config` that the request did not set with `ai.configure()` is copied into `ai.config`. When the second argument is a function, it is the handler and there is no config.\n\nExample: Ollama model\n```js\nNEWAIMODEL('llama3', { url: 'http://localhost:11434/api/chat' }, function(ai, callback) {\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json' };\n\topt.body = JSON.stringify({ model: ai.payload.model, messages: ai.payload.messages, stream: false });\n\tfetch(ai.config.url, opt).then(res => res.json()).then(function(json) {\n\t\tcallback(null, json.message.content);\n\t}).catch(callback);\n});\n```\n\n### function(ai, callback)\n\nType: `delegate` · Since: `0.0.16`\n\nThe model handler passed to NEWAIMODEL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ai` | `AIModel` | yes |  | The request. |\n| `callback` | `Function` | yes |  | `function(err, response)` that ends the request. |\n\nCalled once per request when the request runs. `ai` is the request object of `AIMODEL()`: read `ai.payload` for the data to send, `ai.config` for the settings (with the defaults of `NEWAIMODEL()` already applied) and `ai.options.stream` for the stream function of the caller. Call `ai.options.stream(piece)` for each piece of a streamed answer, then `callback(err, response)` once. The `response` reaches the caller unchanged.\n\nExample: Echo handler for tests\n```js\nNEWAIMODEL('echo', function(ai, callback) {\n\tvar last = ai.payload.messages[ai.payload.messages.length - 1];\n\tai.options.stream && ai.options.stream(last.content);\n\tcallback(null, last.content);\n});\n```\n\n### AIMODEL(name)\n\nType: `method` · Since: `0.0.16`\n\nCreates a request for a registered AI model.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name used in `NEWAIMODEL()`. It is also stored as `payload.model`. |\n\nReturns: `AIModel` A new request.\n\nReturns a new request object. Add messages and settings with its methods, then run it with `callback()`, `stream()` or `promise()`. The request looks up the model when it runs; when no model with the name is registered, the callback gets the error `'AI model not found.'`.\n\nExample: Simple question\n```js\nAIMODEL('assistant').user('What is 2 + 2?').callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ai.system(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAdds a system message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | The text, or an object whose keys are copied into the message. |\n| `merge` | `String` | no |  | A separator. When set and a system message exists, the content is appended to it. |\n\nReturns: `AIModel` The same request, for chaining.\n\nThe same as `ai.message('system', content, merge)`. Use it for the instructions of the model.\n\nExample: Instructions\n```js\nAIMODEL('assistant').system('Answer in one sentence.').user('What is Node.js?').callback(console.log);\n```\n\n### ai.user(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAdds a user message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | The text, or an object whose keys are copied into the message. |\n| `merge` | `String` | no |  | A separator. When set and a user message exists, the content is appended to it. |\n\nReturns: `AIModel` The same request, for chaining.\n\nThe same as `ai.message('user', content, merge)`.\n\nExample: Message with an image\n```js\nAIMODEL('vision').user({ content: 'What is in this picture?', images: [base64] }).callback(console.log);\n```\n\n### ai.assistant(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAdds an assistant message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | The text, or an object whose keys are copied into the message. |\n| `merge` | `String` | no |  | A separator. When set and an assistant message exists, the content is appended to it. |\n\nReturns: `AIModel` The same request, for chaining.\n\nThe same as `ai.message('assistant', content, merge)`. Use it to replay earlier answers of the model in a conversation.\n\nExample: Conversation history\n```js\nvar ai = AIMODEL('assistant');\nfor (var item of history) {\n\tif (item.fromuser)\n\t\tai.user(item.text);\n\telse\n\t\tai.assistant(item.text);\n}\nai.user(question).callback(console.log);\n```\n\n### ai.message(role, content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAdds a message with any role.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `role` | `String` | yes |  | The role, e.g. `system`, `user`, `assistant` or `tool`. |\n| `content` | `String|Object` | yes |  | The text, or an object whose keys are copied into the message. |\n| `merge` | `String` | no |  | A separator string that turns on merging. |\n\nReturns: `AIModel` The same request, for chaining.\n\nPushes `{ role, content }` to `ai.payload.messages`. When `content` is an object, its keys are copied into the message instead of `content`. When `merge` is set and a message with the same role exists, nothing is added: a string is appended to the content of the first such message with `merge` between them, and the keys of an object are copied into it.\n\nExample: Merged instructions\n```js\nAIMODEL('assistant')\n\t.message('system', 'You are a translator.')\n\t.message('system', 'Translate to German.', '\\n')\n\t.user('Good morning')\n\t.callback(console.log);\n```\n\n### ai.prompt(content)\n\nType: `method` · Since: `0.0.16`\n\nSets a single prompt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String` | yes |  | The prompt. |\n\nReturns: `AIModel` The same request, for chaining.\n\nSets `ai.payload.prompt`. Useful for handlers of endpoints that take one prompt instead of a list of messages (for example the `/api/generate` endpoint of Ollama). The handler decides how to use it.\n\nExample: Prompt\n```js\nAIMODEL('generator').prompt('Write a slogan for a bakery').callback(console.log);\n```\n\n### ai.think()\n\nType: `method` · Since: `0.0.16`\n\nAsks for the thinking mode.\n\nReturns: `AIModel` The same request, for chaining.\n\nSets `ai.payload.think = true`. The handler maps it to the option of the provider (for example `think` of Ollama).\n\nExample: Thinking\n```js\nAIMODEL('reasoner').think().user('Is 1001 a prime number?').callback(console.log);\n```\n\n### ai.configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nSets the config of the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The keys to set. |\n\nReturns: `AIModel` The same request, for chaining.\n\nCopies the keys of `obj` into `ai.config`. These values win over the defaults of `NEWAIMODEL()`, which fill only the keys that are not set.\n\nExample: Temperature for one request\n```js\nAIMODEL('assistant').configure({ temperature: 0 }).user('List three colors').callback(console.log);\n```\n\n### ai.callback(fn)\n\nType: `method` · Since: `0.0.16`\n\nSets the callback and runs the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `AIModel` The same request, for chaining.\n\nStores `fn` and runs the request on the next turn of the event loop. Calling `callback()`, `stream()` or `promise()` again in the same turn moves the run, so the handler is called only once.\n\nExample: Callback\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\terr && console.log(err);\n});\n```\n\n### ai.stream(fn)\n\nType: `method` · Since: `0.0.16`\n\nSets the stream function and runs the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Called by the handler with each piece of the answer. |\n\nReturns: `AIModel` The same request, for chaining.\n\nStores `fn` in `ai.options.stream` and runs the request on the next turn of the event loop. The handler calls `fn` with the pieces of the answer; what a piece is (text, an object) is up to the handler. Add `callback()` to know when the answer ends.\n\nExample: Stream to the console\n```js\nAIMODEL('assistant').user('Tell a story').stream(function(text) {\n\tprocess.stdout.write(text);\n}).callback(function(err) {\n\tconsole.log('end', err);\n});\n```\n\n### ai.promise([$])\n\nType: `method` · Since: `0.0.16`\n\nRuns the request and returns a Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | The `$` of an action or controller, to report errors with `$.invalid()`. |\n\nReturns: `Promise` Resolves with the response of the handler.\n\nRuns the request through `callback()`. The promise resolves with the response. An error rejects it with an `Error`; when `$` with `$.invalid()` is passed, the error goes to `$.invalid(err)` instead and the promise stays pending.\n\nExample: In an action\n```js\nNEWACTION('Assistant/ask', {\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar answer = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: answer });\n\t}\n});\n```\n\n### ai.payload {Object}\n\nType: `property` · Since: `0.0.16`\n\nThe data of the request for the provider.\n\nReturns: `Object`\n\nHolds `model` (the name given to `AIMODEL()`), `messages` (an array of message objects) and `tools` (an array of tool definitions, empty by default), plus `prompt` and `think` when set. The handler reads it to build the body of the provider request.\n\nExample: Read the payload\n```js\nNEWAIMODEL('debug', function(ai, callback) {\n\tcallback(null, JSON.stringify(ai.payload));\n});\n```\n\n### ai.config {Object}\n\nType: `property` · Since: `0.0.16`\n\nThe config of the request.\n\nReturns: `Object`\n\nThe keys set with `ai.configure()`, completed with the defaults of `NEWAIMODEL()` just before the handler runs.\n\n### ai.options {Object}\n\nType: `property` · Since: `0.0.16`\n\nThe run options of the request.\n\nReturns: `Object`\n\nHolds `callback` (the function set by `callback()` or `promise()`, `NOOP` by default) and `stream` (the function set by `stream()`, or undefined). A handler checks `ai.options.stream` to know if the caller wants a stream.\n\nExample: Check for streaming\n```js\nif (ai.options.stream)\n\tbody.stream = true;\n```\n\n### F.aimodels {Object}\n\nType: `property` · Since: `0.0.16`\n\nThe registered AI models.\n\nReturns: `Object`\n\nAn object with the names of the models as keys and `{ config, callback }` as values, filled by `NEWAIMODEL()`.\n\nExample: Is a model registered?\n```js\nif (F.aimodels.assistant)\n\tconsole.log('ready');\n```\n\n### ai.tool(content)\n\nType: `method` · Since: `0.0.17`\n\nAdds a tool definition.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `Object` | yes |  | The tool definition. |\n\nReturns: `AIModel` The same request, for chaining.\n\nPushes `content` to `ai.payload.tools`. The framework does not change or check it; the handler sends the tools to the provider in its format. `schema.toAITool(name)` of an inline schema returns the common function format.\n\nExample: Tool from a schema\n```js\nNEWSCHEMA('@Task', '*name:String // The name of the task,due:Date');\n\nAIMODEL('assistant')\n\t.user('Create a task: call Peter tomorrow')\n\t.tool(F.jsonschemas.Task.toAITool('create_task'))\n\t.callback(console.log);\n```\n\n### AIPARSER(provider)\n\nType: `method` · Since: `0.0.17`\n\nCreates a parser for streamed AI responses.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `provider` | `String` | no | `generic` | The format of the stream. |\n\nReturns: `AIParser` A new parser.\n\nReturns a stream parser for the format of `provider`: `ollama`, `openai` (or `openai_chat`), `openai_responses`, `claude` (or `anthropic`), `gemini` (or `google`). Any other value uses a generic parser. Write the raw chunks with `parser.write()` and finish with `parser.end()`.\n\nExample: Parse a Claude stream\n```js\nvar parser = AIPARSER('claude');\nparser.on('content', e => process.stdout.write(e.delta));\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\nvar output = parser.end();\n```\n\n### parser.write(chunk)\n\nType: `method` · Since: `0.0.17`\n\nWrites a piece of the stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `chunk` | `Buffer|String|Object` | yes |  | Raw data or a parsed event. |\n\nReturns: `Object` The current output, the same as `parser.output()`.\n\nA `Buffer`, a string, a `Uint8Array` or an `ArrayBuffer` is added to an internal buffer and every complete line is parsed: empty lines and `[DONE]` are skipped, a `data:` prefix is removed and the rest is parsed as JSON. A line that is not JSON is ignored. An object is parsed directly as one event of the provider. `null` only returns the output.\n\nExample: Write parsed objects\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { content: 'Hel' } });\nparser.write({ message: { content: 'lo' } });\nparser.end().content; // 'Hello'\n```\n\n### parser.end()\n\nType: `method` · Since: `0.0.17`\n\nFinishes the stream.\n\nReturns: `Object` `{ content, thinking, tools, reasoning }`, plus `thinking_signature` or `thought_signatures` when the provider sends them.\n\nParses the rest of the buffer (a last line without a newline), parses the joined arguments of every tool call, emits `done` with `{ output }` and returns the output.\n\nExample: Final output\n```js\nvar output = parser.end();\nconsole.log(output.content);\n```\n\nExample: Tool calls of a Claude stream\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.output()\n\nType: `method` · Since: `0.0.17`\n\nReturns the current output.\n\nReturns: `Object` The output so far.\n\nReturns `{ content, thinking, tools, reasoning }`. `tools` is an array of `{ id, name, arguments }` with the tool calls of every provider, where `arguments` is the parsed JSON of the joined arguments (the trimmed text when it is not valid JSON, for example while the arguments still stream, and `{}` when it is empty). `reasoning` is `tool` when there are tool calls, else `thinking` or `content` by the last kind of data. `thinking_signature` (Claude) and `thought_signatures` (Gemini) are added when present.\n\n### parser.on(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nListens to an event of the parser.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The event name. |\n| `fn` | `Function` | yes |  | `function(event)`. |\n\nReturns: `AIParser` The parser, for chaining.\n\nAdds `fn` for the event `type`: `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments`, `done`, or `*` for all events. `fn` gets an object with `type` and the data of the event.\n\nExample: All events\n```js\nAIPARSER('openai').on('*', function(e) {\n\tconsole.log(e.type);\n});\n```\n\n### parser.off(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nRemoves a listener.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The event name. |\n| `fn` | `Function` | yes |  | The function given to `parser.on()`. |\n\nReturns: `AIParser` The parser, for chaining.\n\nRemoves `fn` from the listeners of `type`.\n\n### parser.reset()\n\nType: `method` · Since: `0.0.17`\n\nClears the parser.\n\nReturns: `AIParser` The parser.\n\nClears the content, the thinking, the tools, the buffer and the signatures, so the parser can read another stream of the same provider. The listeners stay.\n\n### parser.content {String}\n\nType: `property` · Since: `0.0.17`\n\nThe text collected so far.\n\nReturns: `String`\n\nAll text of the answer, joined from the deltas.\n\n### parser.thinking {String}\n\nType: `property` · Since: `0.0.17`\n\nThe reasoning collected so far.\n\nReturns: `String`\n\nAll reasoning or thinking text sent by the model (for example `reasoning_content`, Claude `thinking_delta` or Gemini thought parts).\n\n### parser.reasoning {String}\n\nType: `property` · Since: `0.0.17`\n\nWhat the model is producing now.\n\nReturns: `String`\n\n`content`, `thinking` or `tool`, by the last kind of data received.\n\n### parser.tools {Array}\n\nType: `property`\n\nThe tool calls collected so far.\n\nReturns: `Array`\n\nOne object for each tool call, in the order the calls started: `id` and `name` of the call, `arguments` (the argument text joined from the pieces; for providers that send the arguments as an object, its JSON) and `input` (the parsed arguments, filled by `parser.output()` and `parser.end()`). Use `output.tools` of `parser.end()` for the final calls with the parsed arguments.\n\nExample: Raw and parsed arguments\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { role: 'assistant', content: '', tool_calls: [{ function: { name: 'weather', arguments: { city: 'Bratislava' } } }] } });\nconsole.log(parser.tools[0].name);      // 'weather'\nconsole.log(parser.tools[0].arguments); // '{\"city\":\"Bratislava\"}'\nconsole.log(parser.end().tools[0].arguments); // { city: 'Bratislava' }\n```\n\n### parser.on('content', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNew text of the answer.\n\n`e.delta` is the new text and `e.content` all text so far.\n\n### parser.on('thinking', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNew reasoning text.\n\n`e.delta` is the new text and `e.thinking` all reasoning so far.\n\n### parser.on('tool_start', function(e) {})\n\nType: `event`\n\nA new tool call appears.\n\n`e.tool` is `{ id, name, arguments }` of the new call; `arguments` is usually `{}` at this point. `e.reasoning` is `tool`.\n\nExample: Log the calls\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_start', function(e) {\n\tconsole.log('The model calls', e.tool.name, e.tool.id);\n});\n```\n\n### parser.on('tool_update', function(e) {})\n\nType: `event`\n\nMore data of a known tool call.\n\nEmitted when the stream sends more data for a call that already started, before each further piece of its arguments. `e.tool` is `{ id, name, arguments }` with the arguments parsed so far: an object once the joined text is valid JSON, else the trimmed text.\n\nExample: Watch the arguments grow\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_update', function(e) {\n\tconsole.log(e.tool.id, e.tool.arguments);\n});\n```\n\n### parser.on('tool_arguments', function(e) {})\n\nType: `event`\n\nA piece of the arguments of a tool call.\n\n`e.delta` is the new piece and `e.arguments` all argument text of the call so far. For providers that send the arguments whole as an object (Ollama, Gemini), both are that object. `e.tool` is `{ id, name, arguments }` with the arguments parsed so far.\n\nExample: Arguments of a Claude stream\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.on('done', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nThe stream ended.\n\nEmitted by `parser.end()`. `e.output` is the final output.\n","entries":[{"type":"method","name":"NEWAIMODEL()","signature":"NEWAIMODEL(name, [config], handler)","since":"0.0.16","deprecated":false},{"type":"delegate","name":"handler(ai, callback)","signature":"function(ai, callback)","since":"0.0.16","deprecated":false},{"type":"method","name":"AIMODEL()","signature":"AIMODEL(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.system()","signature":"ai.system(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.user()","signature":"ai.user(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.assistant()","signature":"ai.assistant(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.message()","signature":"ai.message(role, content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.prompt()","signature":"ai.prompt(content)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.think()","signature":"ai.think()","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.configure()","signature":"ai.configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.callback()","signature":"ai.callback(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.stream()","signature":"ai.stream(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.promise()","signature":"ai.promise([$])","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.payload","signature":"ai.payload {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.config","signature":"ai.config {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.options","signature":"ai.options {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"F.aimodels","signature":"F.aimodels {Object}","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.tool()","signature":"ai.tool(content)","since":"0.0.17","deprecated":false},{"type":"method","name":"AIPARSER()","signature":"AIPARSER(provider)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.write()","signature":"parser.write(chunk)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.end()","signature":"parser.end()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.output()","signature":"parser.output()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.on()","signature":"parser.on(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.off()","signature":"parser.off(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.reset()","signature":"parser.reset()","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.content","signature":"parser.content {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.thinking","signature":"parser.thinking {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.reasoning","signature":"parser.reasoning {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.tools","signature":"parser.tools {Array}","since":"","deprecated":false},{"type":"event","name":"content","signature":"parser.on('content', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"thinking","signature":"parser.on('thinking', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"tool_start","signature":"parser.on('tool_start', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_update","signature":"parser.on('tool_update', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_arguments","signature":"parser.on('tool_arguments', function(e) {})","since":"","deprecated":false},{"type":"event","name":"done","signature":"parser.on('done', function(e) {})","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwSk45x60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/ai-models/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"KI-Modelle","summary":"NEWAIMODEL(), AIMODEL(), die Methoden und Eigenschaften der Anfrage und der KI-Stream-Parser.","markdown":"---\ntitle: KI-Modelle\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/ai-models/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# KI-Modelle\n\n> NEWAIMODEL(), AIMODEL(), die Methoden und Eigenschaften der Anfrage und der KI-Stream-Parser.\n\nDiese Seite listet die globalen Funktionen für KI-Modelle, die Methoden und Eigenschaften des Anfrageobjekts von `AIMODEL()`, den Modell-Handler und, sofern vorhanden, den Stream-Parser und seine Events auf. Der Leitfaden [KI-Modelle](../../guides/ai-models/) erklärt, wie sie zusammenarbeiten, mit einem vollständigen Handler.\n\n## API\n\n### NEWAIMODEL(name, [config], handler)\n\nType: `method` · Since: `0.0.16`\n\nRegistriert einen Handler für ein oder mehrere KI-Modelle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Modellname oder mehrere durch Kommas getrennte Namen. |\n| `config` | `Object` | no |  | Standardkonfiguration (URL, Token, Einstellungen), die in `ai.config` jeder Anfrage kopiert wird. |\n| `handler` | `Function` | yes |  | `function(ai, callback)`. Ruft den Anbieter auf und endet mit `callback(err, response)`. |\n\nReturns: `undefined`\n\nSpeichert `handler` mit `config` in `F.aimodels` unter jedem Namen von `name` (durch Kommas getrennte Namen werden getrimmt). Ein erneut registrierter Name ersetzt den vorherigen Handler. Der Handler wird von jeder Anfrage von `AIMODEL()` mit diesem Namen aufgerufen. Bevor er läuft, wird jeder Schlüssel von `config`, den die Anfrage nicht mit `ai.configure()` gesetzt hat, nach `ai.config` kopiert. Ist das zweite Argument eine Funktion, ist sie der Handler, und es gibt keine Konfiguration.\n\nExample: Ollama-Modell\n```js\nNEWAIMODEL('llama3', { url: 'http://localhost:11434/api/chat' }, function(ai, callback) {\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json' };\n\topt.body = JSON.stringify({ model: ai.payload.model, messages: ai.payload.messages, stream: false });\n\tfetch(ai.config.url, opt).then(res => res.json()).then(function(json) {\n\t\tcallback(null, json.message.content);\n\t}).catch(callback);\n});\n```\n\n### function(ai, callback)\n\nType: `delegate` · Since: `0.0.16`\n\nDer an NEWAIMODEL() übergebene Modell-Handler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ai` | `AIModel` | yes |  | Die Anfrage. |\n| `callback` | `Function` | yes |  | `function(err, response)`, die die Anfrage beendet. |\n\nWird einmal pro Anfrage aufgerufen, wenn die Anfrage läuft. `ai` ist das Anfrageobjekt von `AIMODEL()`: Lies `ai.payload` für die zu sendenden Daten, `ai.config` für die Einstellungen (mit bereits angewendeten Standardwerten von `NEWAIMODEL()`) und `ai.options.stream` für die Stream-Funktion des Aufrufers. Rufe `ai.options.stream(piece)` für jedes Stück einer gestreamten Antwort auf und danach einmal `callback(err, response)`. Die `response` erreicht den Aufrufer unverändert.\n\nExample: Echo-Handler für Tests\n```js\nNEWAIMODEL('echo', function(ai, callback) {\n\tvar last = ai.payload.messages[ai.payload.messages.length - 1];\n\tai.options.stream && ai.options.stream(last.content);\n\tcallback(null, last.content);\n});\n```\n\n### AIMODEL(name)\n\nType: `method` · Since: `0.0.16`\n\nErstellt eine Anfrage für ein registriertes KI-Modell.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der in `NEWAIMODEL()` verwendete Name. Er wird auch als `payload.model` gespeichert. |\n\nReturns: `AIModel` Eine neue Anfrage.\n\nGibt ein neues Anfrageobjekt zurück. Füge Nachrichten und Einstellungen mit seinen Methoden hinzu und führe es dann mit `callback()`, `stream()` oder `promise()` aus. Die Anfrage sucht das Modell, wenn sie läuft; ist kein Modell mit dem Namen registriert, erhält der Callback den Fehler `'AI model not found.'`.\n\nExample: Einfache Frage\n```js\nAIMODEL('assistant').user('What is 2 + 2?').callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ai.system(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nFügt eine System-Nachricht hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Der Text oder ein Objekt, dessen Schlüssel in die Nachricht kopiert werden. |\n| `merge` | `String` | no |  | Ein Trennzeichen. Ist es gesetzt und existiert eine System-Nachricht, wird der Inhalt an sie angehängt. |\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nDasselbe wie `ai.message('system', content, merge)`. Verwende es für die Anweisungen an das Modell.\n\nExample: Anweisungen\n```js\nAIMODEL('assistant').system('Answer in one sentence.').user('What is Node.js?').callback(console.log);\n```\n\n### ai.user(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nFügt eine Benutzer-Nachricht hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Der Text oder ein Objekt, dessen Schlüssel in die Nachricht kopiert werden. |\n| `merge` | `String` | no |  | Ein Trennzeichen. Ist es gesetzt und existiert eine Benutzer-Nachricht, wird der Inhalt an sie angehängt. |\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nDasselbe wie `ai.message('user', content, merge)`.\n\nExample: Nachricht mit einem Bild\n```js\nAIMODEL('vision').user({ content: 'What is in this picture?', images: [base64] }).callback(console.log);\n```\n\n### ai.assistant(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nFügt eine Assistenten-Nachricht hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Der Text oder ein Objekt, dessen Schlüssel in die Nachricht kopiert werden. |\n| `merge` | `String` | no |  | Ein Trennzeichen. Ist es gesetzt und existiert eine Assistenten-Nachricht, wird der Inhalt an sie angehängt. |\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nDasselbe wie `ai.message('assistant', content, merge)`. Verwende es, um frühere Antworten des Modells in einer Unterhaltung wiederzugeben.\n\nExample: Gesprächsverlauf\n```js\nvar ai = AIMODEL('assistant');\nfor (var item of history) {\n\tif (item.fromuser)\n\t\tai.user(item.text);\n\telse\n\t\tai.assistant(item.text);\n}\nai.user(question).callback(console.log);\n```\n\n### ai.message(role, content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nFügt eine Nachricht mit einer beliebigen Rolle hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `role` | `String` | yes |  | Die Rolle, z. B. `system`, `user`, `assistant` oder `tool`. |\n| `content` | `String|Object` | yes |  | Der Text oder ein Objekt, dessen Schlüssel in die Nachricht kopiert werden. |\n| `merge` | `String` | no |  | Ein Trenn-String, der das Zusammenführen einschaltet. |\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nFügt `{ role, content }` zu `ai.payload.messages` hinzu. Ist `content` ein Objekt, werden seine Schlüssel statt `content` in die Nachricht kopiert. Ist `merge` gesetzt und existiert eine Nachricht mit derselben Rolle, wird nichts hinzugefügt: Ein String wird an den Inhalt der ersten solchen Nachricht angehängt, mit `merge` dazwischen, und die Schlüssel eines Objekts werden in sie kopiert.\n\nExample: Zusammengeführte Anweisungen\n```js\nAIMODEL('assistant')\n\t.message('system', 'You are a translator.')\n\t.message('system', 'Translate to German.', '\\n')\n\t.user('Good morning')\n\t.callback(console.log);\n```\n\n### ai.prompt(content)\n\nType: `method` · Since: `0.0.16`\n\nSetzt einen einzelnen Prompt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String` | yes |  | Der Prompt. |\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nSetzt `ai.payload.prompt`. Nützlich für Handler von Endpunkten, die einen Prompt statt einer Liste von Nachrichten erwarten (zum Beispiel der Endpunkt `/api/generate` von Ollama). Der Handler entscheidet, wie er ihn verwendet.\n\nExample: Prompt\n```js\nAIMODEL('generator').prompt('Write a slogan for a bakery').callback(console.log);\n```\n\n### ai.think()\n\nType: `method` · Since: `0.0.16`\n\nFordert den Denkmodus an.\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nSetzt `ai.payload.think = true`. Der Handler bildet es auf die Option des Anbieters ab (zum Beispiel `think` von Ollama).\n\nExample: Denken\n```js\nAIMODEL('reasoner').think().user('Is 1001 a prime number?').callback(console.log);\n```\n\n### ai.configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nSetzt die Konfiguration der Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Die zu setzenden Schlüssel. |\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nKopiert die Schlüssel von `obj` nach `ai.config`. Diese Werte haben Vorrang vor den Standardwerten von `NEWAIMODEL()`, die nur die nicht gesetzten Schlüssel füllen.\n\nExample: Temperatur für eine Anfrage\n```js\nAIMODEL('assistant').configure({ temperature: 0 }).user('List three colors').callback(console.log);\n```\n\n### ai.callback(fn)\n\nType: `method` · Since: `0.0.16`\n\nSetzt den Callback und führt die Anfrage aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nSpeichert `fn` und führt die Anfrage im nächsten Durchlauf der Event-Loop aus. Ein erneuter Aufruf von `callback()`, `stream()` oder `promise()` im selben Durchlauf verschiebt die Ausführung, sodass der Handler nur einmal aufgerufen wird.\n\nExample: Callback\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\terr && console.log(err);\n});\n```\n\n### ai.stream(fn)\n\nType: `method` · Since: `0.0.16`\n\nSetzt die Stream-Funktion und führt die Anfrage aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Wird vom Handler mit jedem Stück der Antwort aufgerufen. |\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nSpeichert `fn` in `ai.options.stream` und führt die Anfrage im nächsten Durchlauf der Event-Loop aus. Der Handler ruft `fn` mit den Stücken der Antwort auf; was ein Stück ist (Text, ein Objekt), bestimmt der Handler. Füge `callback()` hinzu, um zu erfahren, wann die Antwort endet.\n\nExample: Stream in die Konsole\n```js\nAIMODEL('assistant').user('Tell a story').stream(function(text) {\n\tprocess.stdout.write(text);\n}).callback(function(err) {\n\tconsole.log('end', err);\n});\n```\n\n### ai.promise([$])\n\nType: `method` · Since: `0.0.16`\n\nFührt die Anfrage aus und gibt eine Promise zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Das `$` einer Aktion oder eines Controllers, um Fehler mit `$.invalid()` zu melden. |\n\nReturns: `Promise` Wird mit der Antwort des Handlers erfüllt.\n\nFührt die Anfrage über `callback()` aus. Die Promise wird mit der Antwort erfüllt. Ein Fehler lehnt sie mit einem `Error` ab; wird `$` mit `$.invalid()` übergeben, geht der Fehler stattdessen an `$.invalid(err)`, und die Promise bleibt ausstehend.\n\nExample: In einer Aktion\n```js\nNEWACTION('Assistant/ask', {\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar answer = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: answer });\n\t}\n});\n```\n\n### ai.payload {Object}\n\nType: `property` · Since: `0.0.16`\n\nDie Daten der Anfrage für den Anbieter.\n\nReturns: `Object`\n\nEnthält `model` (den an `AIMODEL()` übergebenen Namen), `messages` (ein Array von Nachrichtenobjekten) und `tools` (ein Array von Tool-Definitionen, standardmäßig leer), dazu `prompt` und `think`, wenn gesetzt. Der Handler liest es, um den Body der Anfrage an den Anbieter zu bauen.\n\nExample: Den Payload lesen\n```js\nNEWAIMODEL('debug', function(ai, callback) {\n\tcallback(null, JSON.stringify(ai.payload));\n});\n```\n\n### ai.config {Object}\n\nType: `property` · Since: `0.0.16`\n\nDie Konfiguration der Anfrage.\n\nReturns: `Object`\n\nDie mit `ai.configure()` gesetzten Schlüssel, ergänzt um die Standardwerte von `NEWAIMODEL()` kurz bevor der Handler läuft.\n\n### ai.options {Object}\n\nType: `property` · Since: `0.0.16`\n\nDie Ausführungsoptionen der Anfrage.\n\nReturns: `Object`\n\nEnthält `callback` (die von `callback()` oder `promise()` gesetzte Funktion, standardmäßig `NOOP`) und `stream` (die von `stream()` gesetzte Funktion oder undefined). Ein Handler prüft `ai.options.stream`, um zu wissen, ob der Aufrufer einen Stream möchte.\n\nExample: Auf Streaming prüfen\n```js\nif (ai.options.stream)\n\tbody.stream = true;\n```\n\n### F.aimodels {Object}\n\nType: `property` · Since: `0.0.16`\n\nDie registrierten KI-Modelle.\n\nReturns: `Object`\n\nEin Objekt mit den Namen der Modelle als Schlüssel und `{ config, callback }` als Werten, gefüllt von `NEWAIMODEL()`.\n\nExample: Ist ein Modell registriert?\n```js\nif (F.aimodels.assistant)\n\tconsole.log('ready');\n```\n\n### ai.tool(content)\n\nType: `method` · Since: `0.0.17`\n\nFügt eine Tool-Definition hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `Object` | yes |  | Die Tool-Definition. |\n\nReturns: `AIModel` Dieselbe Anfrage, zum Verketten.\n\nFügt `content` zu `ai.payload.tools` hinzu. Das Framework ändert oder prüft es nicht; der Handler sendet die Tools im Format des Anbieters. `schema.toAITool(name)` eines Inline-Schemas gibt das übliche Funktionsformat zurück.\n\nExample: Tool aus einem Schema\n```js\nNEWSCHEMA('@Task', '*name:String // The name of the task,due:Date');\n\nAIMODEL('assistant')\n\t.user('Create a task: call Peter tomorrow')\n\t.tool(F.jsonschemas.Task.toAITool('create_task'))\n\t.callback(console.log);\n```\n\n### AIPARSER(provider)\n\nType: `method` · Since: `0.0.17`\n\nErstellt einen Parser für gestreamte KI-Antworten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `provider` | `String` | no | `generic` | Das Format des Streams. |\n\nReturns: `AIParser` Ein neuer Parser.\n\nGibt einen Stream-Parser für das Format von `provider` zurück: `ollama`, `openai` (oder `openai_chat`), `openai_responses`, `claude` (oder `anthropic`), `gemini` (oder `google`). Jeder andere Wert verwendet einen generischen Parser. Schreibe die rohen Chunks mit `parser.write()` und schließe mit `parser.end()` ab.\n\nExample: Einen Claude-Stream parsen\n```js\nvar parser = AIPARSER('claude');\nparser.on('content', e => process.stdout.write(e.delta));\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\nvar output = parser.end();\n```\n\n### parser.write(chunk)\n\nType: `method` · Since: `0.0.17`\n\nSchreibt ein Stück des Streams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `chunk` | `Buffer|String|Object` | yes |  | Rohdaten oder ein geparstes Event. |\n\nReturns: `Object` Die aktuelle Ausgabe, dasselbe wie `parser.output()`.\n\nEin `Buffer`, ein String, ein `Uint8Array` oder ein `ArrayBuffer` wird einem internen Puffer hinzugefügt, und jede vollständige Zeile wird geparst: Leere Zeilen und `[DONE]` werden übersprungen, ein Präfix `data:` wird entfernt und der Rest als JSON geparst. Eine Zeile, die kein JSON ist, wird ignoriert. Ein Objekt wird direkt als ein Event des Anbieters geparst. `null` gibt nur die Ausgabe zurück.\n\nExample: Geparste Objekte schreiben\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { content: 'Hel' } });\nparser.write({ message: { content: 'lo' } });\nparser.end().content; // 'Hello'\n```\n\n### parser.end()\n\nType: `method` · Since: `0.0.17`\n\nBeendet den Stream.\n\nReturns: `Object` `{ content, thinking, tools, reasoning }`, dazu `thinking_signature` oder `thought_signatures`, wenn der Anbieter sie sendet.\n\nParst den Rest des Puffers (eine letzte Zeile ohne Zeilenumbruch), parst die zusammengefügten Argumente jedes Tool-Aufrufs, sendet `done` mit `{ output }` und gibt die Ausgabe zurück.\n\nExample: Endgültige Ausgabe\n```js\nvar output = parser.end();\nconsole.log(output.content);\n```\n\nExample: Tool-Aufrufe eines Claude-Streams\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.output()\n\nType: `method` · Since: `0.0.17`\n\nGibt die aktuelle Ausgabe zurück.\n\nReturns: `Object` Die bisherige Ausgabe.\n\nGibt `{ content, thinking, tools, reasoning }` zurück. `tools` ist ein Array von `{ id, name, arguments }` mit den Tool-Aufrufen jedes Anbieters, wobei `arguments` das geparste JSON der zusammengefügten Argumente ist (der getrimmte Text, wenn es kein gültiges JSON ist, zum Beispiel während die Argumente noch gestreamt werden, und `{}`, wenn es leer ist). `reasoning` ist `tool`, wenn es Tool-Aufrufe gibt, sonst `thinking` oder `content` je nach der letzten Art von Daten. `thinking_signature` (Claude) und `thought_signatures` (Gemini) werden hinzugefügt, wenn vorhanden.\n\n### parser.on(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nHört auf ein Event des Parsers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Der Name des Events. |\n| `fn` | `Function` | yes |  | `function(event)`. |\n\nReturns: `AIParser` Der Parser, zum Verketten.\n\nFügt `fn` für das Event `type` hinzu: `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments`, `done` oder `*` für alle Events. `fn` erhält ein Objekt mit `type` und den Daten des Events.\n\nExample: Alle Events\n```js\nAIPARSER('openai').on('*', function(e) {\n\tconsole.log(e.type);\n});\n```\n\n### parser.off(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nEntfernt einen Listener.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Der Name des Events. |\n| `fn` | `Function` | yes |  | Die an `parser.on()` übergebene Funktion. |\n\nReturns: `AIParser` Der Parser, zum Verketten.\n\nEntfernt `fn` aus den Listenern von `type`.\n\n### parser.reset()\n\nType: `method` · Since: `0.0.17`\n\nLeert den Parser.\n\nReturns: `AIParser` Der Parser.\n\nLeert den Inhalt, das Thinking, die Tools, den Puffer und die Signaturen, sodass der Parser einen weiteren Stream desselben Anbieters lesen kann. Die Listener bleiben erhalten.\n\n### parser.content {String}\n\nType: `property` · Since: `0.0.17`\n\nDer bisher gesammelte Text.\n\nReturns: `String`\n\nDer gesamte Text der Antwort, aus den Deltas zusammengesetzt.\n\n### parser.thinking {String}\n\nType: `property` · Since: `0.0.17`\n\nDas bisher gesammelte Reasoning.\n\nReturns: `String`\n\nDer gesamte Reasoning- oder Thinking-Text, den das Modell gesendet hat (zum Beispiel `reasoning_content`, Claude `thinking_delta` oder Gemini-Thought-Teile).\n\n### parser.reasoning {String}\n\nType: `property` · Since: `0.0.17`\n\nWas das Modell gerade erzeugt.\n\nReturns: `String`\n\n`content`, `thinking` oder `tool`, je nach der zuletzt empfangenen Art von Daten.\n\n### parser.tools {Array}\n\nType: `property`\n\nDie bisher gesammelten Tool-Aufrufe.\n\nReturns: `Array`\n\nEin Objekt für jeden Tool-Aufruf, in der Reihenfolge, in der die Aufrufe begonnen haben: `id` und `name` des Aufrufs, `arguments` (der aus den Stücken zusammengefügte Argumenttext; bei Anbietern, die die Argumente als Objekt senden, dessen JSON) und `input` (die geparsten Argumente, gefüllt von `parser.output()` und `parser.end()`). Verwende `output.tools` von `parser.end()` für die endgültigen Aufrufe mit den geparsten Argumenten.\n\nExample: Rohe und geparste Argumente\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { role: 'assistant', content: '', tool_calls: [{ function: { name: 'weather', arguments: { city: 'Bratislava' } } }] } });\nconsole.log(parser.tools[0].name);      // 'weather'\nconsole.log(parser.tools[0].arguments); // '{\"city\":\"Bratislava\"}'\nconsole.log(parser.end().tools[0].arguments); // { city: 'Bratislava' }\n```\n\n### parser.on('content', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNeuer Text der Antwort.\n\n`e.delta` ist der neue Text und `e.content` der gesamte bisherige Text.\n\n### parser.on('thinking', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNeuer Reasoning-Text.\n\n`e.delta` ist der neue Text und `e.thinking` das gesamte bisherige Reasoning.\n\n### parser.on('tool_start', function(e) {})\n\nType: `event`\n\nEin neuer Tool-Aufruf erscheint.\n\n`e.tool` ist `{ id, name, arguments }` des neuen Aufrufs; `arguments` ist an diesem Punkt meist `{}`. `e.reasoning` ist `tool`.\n\nExample: Die Aufrufe loggen\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_start', function(e) {\n\tconsole.log('The model calls', e.tool.name, e.tool.id);\n});\n```\n\n### parser.on('tool_update', function(e) {})\n\nType: `event`\n\nWeitere Daten eines bekannten Tool-Aufrufs.\n\nWird gesendet, wenn der Stream weitere Daten für einen bereits begonnenen Aufruf sendet, vor jedem weiteren Stück seiner Argumente. `e.tool` ist `{ id, name, arguments }` mit den bisher geparsten Argumenten: ein Objekt, sobald der zusammengefügte Text gültiges JSON ist, sonst der getrimmte Text.\n\nExample: Den Argumenten beim Wachsen zusehen\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_update', function(e) {\n\tconsole.log(e.tool.id, e.tool.arguments);\n});\n```\n\n### parser.on('tool_arguments', function(e) {})\n\nType: `event`\n\nEin Stück der Argumente eines Tool-Aufrufs.\n\n`e.delta` ist das neue Stück und `e.arguments` der gesamte bisherige Argumenttext des Aufrufs. Bei Anbietern, die die Argumente vollständig als Objekt senden (Ollama, Gemini), sind beide dieses Objekt. `e.tool` ist `{ id, name, arguments }` mit den bisher geparsten Argumenten.\n\nExample: Argumente eines Claude-Streams\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.on('done', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nDer Stream ist beendet.\n\nWird von `parser.end()` gesendet. `e.output` ist die endgültige Ausgabe.\n","entries":[{"type":"method","name":"NEWAIMODEL()","signature":"NEWAIMODEL(name, [config], handler)","since":"0.0.16","deprecated":false},{"type":"delegate","name":"handler(ai, callback)","signature":"function(ai, callback)","since":"0.0.16","deprecated":false},{"type":"method","name":"AIMODEL()","signature":"AIMODEL(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.system()","signature":"ai.system(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.user()","signature":"ai.user(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.assistant()","signature":"ai.assistant(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.message()","signature":"ai.message(role, content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.prompt()","signature":"ai.prompt(content)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.think()","signature":"ai.think()","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.configure()","signature":"ai.configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.callback()","signature":"ai.callback(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.stream()","signature":"ai.stream(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.promise()","signature":"ai.promise([$])","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.payload","signature":"ai.payload {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.config","signature":"ai.config {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.options","signature":"ai.options {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"F.aimodels","signature":"F.aimodels {Object}","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.tool()","signature":"ai.tool(content)","since":"0.0.17","deprecated":false},{"type":"method","name":"AIPARSER()","signature":"AIPARSER(provider)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.write()","signature":"parser.write(chunk)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.end()","signature":"parser.end()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.output()","signature":"parser.output()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.on()","signature":"parser.on(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.off()","signature":"parser.off(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.reset()","signature":"parser.reset()","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.content","signature":"parser.content {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.thinking","signature":"parser.thinking {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.reasoning","signature":"parser.reasoning {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.tools","signature":"parser.tools {Array}","since":"","deprecated":false},{"type":"event","name":"content","signature":"parser.on('content', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"thinking","signature":"parser.on('thinking', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"tool_start","signature":"parser.on('tool_start', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_update","signature":"parser.on('tool_update', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_arguments","signature":"parser.on('tool_arguments', function(e) {})","since":"","deprecated":false},{"type":"event","name":"done","signature":"parser.on('done', function(e) {})","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwSk45x60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/ai-models/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Modelos de IA","summary":"NEWAIMODEL(), AIMODEL(), los métodos y propiedades de la petición y el parser de streams de IA.","markdown":"---\ntitle: Modelos de IA\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/ai-models/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Modelos de IA\n\n> NEWAIMODEL(), AIMODEL(), los métodos y propiedades de la petición y el parser de streams de IA.\n\nEsta página enumera las funciones globales para modelos de IA, los métodos y propiedades del objeto de petición de `AIMODEL()`, el handler del modelo y, cuando está disponible, el parser de streams y sus eventos. La guía [Modelos de IA](../../guides/ai-models/) explica cómo funcionan juntos, con un handler completo.\n\n## API\n\n### NEWAIMODEL(name, [config], handler)\n\nType: `method` · Since: `0.0.16`\n\nRegistra un handler para uno o varios modelos de IA.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del modelo, o varios nombres separados por comas. |\n| `config` | `Object` | no |  | Config por defecto (URL, token, ajustes) copiada en `ai.config` de cada petición. |\n| `handler` | `Function` | yes |  | `function(ai, callback)`. Llama al proveedor y termina con `callback(err, response)`. |\n\nReturns: `undefined`\n\nGuarda `handler` con `config` en `F.aimodels` bajo cada nombre de `name` (los nombres separados por comas se recortan). Un nombre registrado de nuevo sustituye el handler anterior. Cada petición de `AIMODEL()` con ese nombre llama al handler. Antes de que se ejecute, cada clave de `config` que la petición no estableció con `ai.configure()` se copia en `ai.config`. Cuando el segundo argumento es una función, es el handler y no hay config.\n\nExample: Modelo de Ollama\n```js\nNEWAIMODEL('llama3', { url: 'http://localhost:11434/api/chat' }, function(ai, callback) {\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json' };\n\topt.body = JSON.stringify({ model: ai.payload.model, messages: ai.payload.messages, stream: false });\n\tfetch(ai.config.url, opt).then(res => res.json()).then(function(json) {\n\t\tcallback(null, json.message.content);\n\t}).catch(callback);\n});\n```\n\n### function(ai, callback)\n\nType: `delegate` · Since: `0.0.16`\n\nEl handler del modelo que se pasa a NEWAIMODEL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ai` | `AIModel` | yes |  | La petición. |\n| `callback` | `Function` | yes |  | `function(err, response)` que termina la petición. |\n\nSe llama una vez por petición cuando la petición se ejecuta. `ai` es el objeto de petición de `AIMODEL()`: lee `ai.payload` para los datos que enviar, `ai.config` para los ajustes (con los valores por defecto de `NEWAIMODEL()` ya aplicados) y `ai.options.stream` para la función de stream de quien llama. Llama a `ai.options.stream(piece)` por cada trozo de una respuesta en streaming y luego a `callback(err, response)` una vez. La `response` llega sin cambios a quien llama.\n\nExample: Handler de eco para pruebas\n```js\nNEWAIMODEL('echo', function(ai, callback) {\n\tvar last = ai.payload.messages[ai.payload.messages.length - 1];\n\tai.options.stream && ai.options.stream(last.content);\n\tcallback(null, last.content);\n});\n```\n\n### AIMODEL(name)\n\nType: `method` · Since: `0.0.16`\n\nCrea una petición para un modelo de IA registrado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre usado en `NEWAIMODEL()`. También se guarda como `payload.model`. |\n\nReturns: `AIModel` Una nueva petición.\n\nDevuelve un nuevo objeto de petición. Añade mensajes y ajustes con sus métodos y luego ejecútala con `callback()`, `stream()` o `promise()`. La petición busca el modelo cuando se ejecuta; cuando no hay ningún modelo registrado con ese nombre, el callback recibe el error `'AI model not found.'`.\n\nExample: Pregunta sencilla\n```js\nAIMODEL('assistant').user('What is 2 + 2?').callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ai.system(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAñade un mensaje de sistema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | El texto, o un objeto cuyas claves se copian en el mensaje. |\n| `merge` | `String` | no |  | Un separador. Cuando se establece y existe un mensaje de sistema, el contenido se añade a él. |\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nLo mismo que `ai.message('system', content, merge)`. Úsalo para las instrucciones del modelo.\n\nExample: Instrucciones\n```js\nAIMODEL('assistant').system('Answer in one sentence.').user('What is Node.js?').callback(console.log);\n```\n\n### ai.user(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAñade un mensaje de usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | El texto, o un objeto cuyas claves se copian en el mensaje. |\n| `merge` | `String` | no |  | Un separador. Cuando se establece y existe un mensaje de usuario, el contenido se añade a él. |\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nLo mismo que `ai.message('user', content, merge)`.\n\nExample: Mensaje con una imagen\n```js\nAIMODEL('vision').user({ content: 'What is in this picture?', images: [base64] }).callback(console.log);\n```\n\n### ai.assistant(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAñade un mensaje del asistente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | El texto, o un objeto cuyas claves se copian en el mensaje. |\n| `merge` | `String` | no |  | Un separador. Cuando se establece y existe un mensaje del asistente, el contenido se añade a él. |\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nLo mismo que `ai.message('assistant', content, merge)`. Úsalo para reproducir respuestas anteriores del modelo en una conversación.\n\nExample: Historial de la conversación\n```js\nvar ai = AIMODEL('assistant');\nfor (var item of history) {\n\tif (item.fromuser)\n\t\tai.user(item.text);\n\telse\n\t\tai.assistant(item.text);\n}\nai.user(question).callback(console.log);\n```\n\n### ai.message(role, content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAñade un mensaje con cualquier rol.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `role` | `String` | yes |  | El rol, p. ej. `system`, `user`, `assistant` o `tool`. |\n| `content` | `String|Object` | yes |  | El texto, o un objeto cuyas claves se copian en el mensaje. |\n| `merge` | `String` | no |  | Un string separador que activa la fusión. |\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nAñade `{ role, content }` a `ai.payload.messages`. Cuando `content` es un objeto, sus claves se copian en el mensaje en lugar de `content`. Cuando se establece `merge` y existe un mensaje con el mismo rol, no se añade nada: un string se añade al contenido del primero de esos mensajes con `merge` entre ambos, y las claves de un objeto se copian en él.\n\nExample: Instrucciones fusionadas\n```js\nAIMODEL('assistant')\n\t.message('system', 'You are a translator.')\n\t.message('system', 'Translate to German.', '\\n')\n\t.user('Good morning')\n\t.callback(console.log);\n```\n\n### ai.prompt(content)\n\nType: `method` · Since: `0.0.16`\n\nEstablece un único prompt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String` | yes |  | El prompt. |\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nEstablece `ai.payload.prompt`. Útil para handlers de endpoints que reciben un prompt en lugar de una lista de mensajes (por ejemplo el endpoint `/api/generate` de Ollama). El handler decide cómo usarlo.\n\nExample: Prompt\n```js\nAIMODEL('generator').prompt('Write a slogan for a bakery').callback(console.log);\n```\n\n### ai.think()\n\nType: `method` · Since: `0.0.16`\n\nPide el modo de razonamiento.\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nEstablece `ai.payload.think = true`. El handler lo mapea a la opción del proveedor (por ejemplo `think` de Ollama).\n\nExample: Razonamiento\n```js\nAIMODEL('reasoner').think().user('Is 1001 a prime number?').callback(console.log);\n```\n\n### ai.configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nEstablece la config de la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Las claves que establecer. |\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nCopia las claves de `obj` en `ai.config`. Estos valores prevalecen sobre los valores por defecto de `NEWAIMODEL()`, que solo rellenan las claves que no están establecidas.\n\nExample: Temperatura para una petición\n```js\nAIMODEL('assistant').configure({ temperature: 0 }).user('List three colors').callback(console.log);\n```\n\n### ai.callback(fn)\n\nType: `method` · Since: `0.0.16`\n\nEstablece el callback y ejecuta la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nGuarda `fn` y ejecuta la petición en el siguiente turno del event loop. Llamar de nuevo a `callback()`, `stream()` o `promise()` en el mismo turno aplaza la ejecución, así que el handler se llama una sola vez.\n\nExample: Callback\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\terr && console.log(err);\n});\n```\n\n### ai.stream(fn)\n\nType: `method` · Since: `0.0.16`\n\nEstablece la función de stream y ejecuta la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | El handler la llama con cada trozo de la respuesta. |\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nGuarda `fn` en `ai.options.stream` y ejecuta la petición en el siguiente turno del event loop. El handler llama a `fn` con los trozos de la respuesta; qué es un trozo (texto, un objeto) depende del handler. Añade `callback()` para saber cuándo termina la respuesta.\n\nExample: Stream a la consola\n```js\nAIMODEL('assistant').user('Tell a story').stream(function(text) {\n\tprocess.stdout.write(text);\n}).callback(function(err) {\n\tconsole.log('end', err);\n});\n```\n\n### ai.promise([$])\n\nType: `method` · Since: `0.0.16`\n\nEjecuta la petición y devuelve una Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | El `$` de una acción o un controlador, para notificar errores con `$.invalid()`. |\n\nReturns: `Promise` Se resuelve con la respuesta del handler.\n\nEjecuta la petición mediante `callback()`. La promesa se resuelve con la respuesta. Un error la rechaza con un `Error`; cuando se pasa `$` con `$.invalid()`, el error va en su lugar a `$.invalid(err)` y la promesa queda pendiente.\n\nExample: En una acción\n```js\nNEWACTION('Assistant/ask', {\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar answer = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: answer });\n\t}\n});\n```\n\n### ai.payload {Object}\n\nType: `property` · Since: `0.0.16`\n\nLos datos de la petición para el proveedor.\n\nReturns: `Object`\n\nContiene `model` (el nombre pasado a `AIMODEL()`), `messages` (un array de objetos de mensaje) y `tools` (un array de definiciones de herramientas, vacío por defecto), además de `prompt` y `think` cuando están establecidos. El handler lo lee para construir el cuerpo de la petición al proveedor.\n\nExample: Leer el payload\n```js\nNEWAIMODEL('debug', function(ai, callback) {\n\tcallback(null, JSON.stringify(ai.payload));\n});\n```\n\n### ai.config {Object}\n\nType: `property` · Since: `0.0.16`\n\nLa config de la petición.\n\nReturns: `Object`\n\nLas claves establecidas con `ai.configure()`, completadas con los valores por defecto de `NEWAIMODEL()` justo antes de que se ejecute el handler.\n\n### ai.options {Object}\n\nType: `property` · Since: `0.0.16`\n\nLas opciones de ejecución de la petición.\n\nReturns: `Object`\n\nContiene `callback` (la función establecida por `callback()` o `promise()`, `NOOP` por defecto) y `stream` (la función establecida por `stream()`, o undefined). Un handler comprueba `ai.options.stream` para saber si quien llama quiere un stream.\n\nExample: Comprobar si hay streaming\n```js\nif (ai.options.stream)\n\tbody.stream = true;\n```\n\n### F.aimodels {Object}\n\nType: `property` · Since: `0.0.16`\n\nLos modelos de IA registrados.\n\nReturns: `Object`\n\nUn objeto con los nombres de los modelos como claves y `{ config, callback }` como valores, rellenado por `NEWAIMODEL()`.\n\nExample: ¿Está registrado un modelo?\n```js\nif (F.aimodels.assistant)\n\tconsole.log('ready');\n```\n\n### ai.tool(content)\n\nType: `method` · Since: `0.0.17`\n\nAñade una definición de herramienta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `Object` | yes |  | La definición de la herramienta. |\n\nReturns: `AIModel` La misma petición, para encadenar.\n\nAñade `content` a `ai.payload.tools`. El framework no lo modifica ni lo comprueba; el handler envía las herramientas al proveedor en su formato. `schema.toAITool(name)` de un esquema en línea devuelve el formato de función común.\n\nExample: Herramienta desde un esquema\n```js\nNEWSCHEMA('@Task', '*name:String // The name of the task,due:Date');\n\nAIMODEL('assistant')\n\t.user('Create a task: call Peter tomorrow')\n\t.tool(F.jsonschemas.Task.toAITool('create_task'))\n\t.callback(console.log);\n```\n\n### AIPARSER(provider)\n\nType: `method` · Since: `0.0.17`\n\nCrea un parser para respuestas de IA en streaming.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `provider` | `String` | no | `generic` | El formato del stream. |\n\nReturns: `AIParser` Un nuevo parser.\n\nDevuelve un parser de streams para el formato de `provider`: `ollama`, `openai` (o `openai_chat`), `openai_responses`, `claude` (o `anthropic`), `gemini` (o `google`). Cualquier otro valor usa un parser genérico. Escribe los fragmentos en bruto con `parser.write()` y termina con `parser.end()`.\n\nExample: Parsear un stream de Claude\n```js\nvar parser = AIPARSER('claude');\nparser.on('content', e => process.stdout.write(e.delta));\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\nvar output = parser.end();\n```\n\n### parser.write(chunk)\n\nType: `method` · Since: `0.0.17`\n\nEscribe un fragmento del stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `chunk` | `Buffer|String|Object` | yes |  | Datos en bruto o un evento ya parseado. |\n\nReturns: `Object` La salida actual, igual que `parser.output()`.\n\nUn `Buffer`, un string, un `Uint8Array` o un `ArrayBuffer` se añade a un buffer interno y se parsea cada línea completa: las líneas vacías y `[DONE]` se omiten, se elimina el prefijo `data:` y el resto se parsea como JSON. Una línea que no es JSON se ignora. Un objeto se parsea directamente como un evento del proveedor. `null` solo devuelve la salida.\n\nExample: Escribir objetos ya parseados\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { content: 'Hel' } });\nparser.write({ message: { content: 'lo' } });\nparser.end().content; // 'Hello'\n```\n\n### parser.end()\n\nType: `method` · Since: `0.0.17`\n\nTermina el stream.\n\nReturns: `Object` `{ content, thinking, tools, reasoning }`, además de `thinking_signature` o `thought_signatures` cuando el proveedor los envía.\n\nParsea el resto del buffer (una última línea sin salto de línea), parsea los argumentos unidos de cada llamada a herramienta, emite `done` con `{ output }` y devuelve la salida.\n\nExample: Salida final\n```js\nvar output = parser.end();\nconsole.log(output.content);\n```\n\nExample: Llamadas a herramientas de un stream de Claude\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.output()\n\nType: `method` · Since: `0.0.17`\n\nDevuelve la salida actual.\n\nReturns: `Object` La salida hasta el momento.\n\nDevuelve `{ content, thinking, tools, reasoning }`. `tools` es un array de `{ id, name, arguments }` con las llamadas a herramientas de todos los proveedores, donde `arguments` es el JSON parseado de los argumentos unidos (el texto recortado cuando no es JSON válido, por ejemplo mientras los argumentos aún llegan por el stream, y `{}` cuando está vacío). `reasoning` es `tool` cuando hay llamadas a herramientas; si no, `thinking` o `content` según el último tipo de datos. `thinking_signature` (Claude) y `thought_signatures` (Gemini) se añaden cuando están presentes.\n\n### parser.on(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nEscucha un evento del parser.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El nombre del evento. |\n| `fn` | `Function` | yes |  | `function(event)`. |\n\nReturns: `AIParser` El parser, para encadenar.\n\nAñade `fn` para el evento `type`: `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments`, `done`, o `*` para todos los eventos. `fn` recibe un objeto con `type` y los datos del evento.\n\nExample: Todos los eventos\n```js\nAIPARSER('openai').on('*', function(e) {\n\tconsole.log(e.type);\n});\n```\n\n### parser.off(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nElimina un listener.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El nombre del evento. |\n| `fn` | `Function` | yes |  | La función pasada a `parser.on()`. |\n\nReturns: `AIParser` El parser, para encadenar.\n\nElimina `fn` de los listeners de `type`.\n\n### parser.reset()\n\nType: `method` · Since: `0.0.17`\n\nLimpia el parser.\n\nReturns: `AIParser` El parser.\n\nLimpia el contenido, el razonamiento, las herramientas, el buffer y las firmas, para que el parser pueda leer otro stream del mismo proveedor. Los listeners se mantienen.\n\n### parser.content {String}\n\nType: `property` · Since: `0.0.17`\n\nEl texto recogido hasta el momento.\n\nReturns: `String`\n\nTodo el texto de la respuesta, unido a partir de los deltas.\n\n### parser.thinking {String}\n\nType: `property` · Since: `0.0.17`\n\nEl razonamiento recogido hasta el momento.\n\nReturns: `String`\n\nTodo el texto de razonamiento enviado por el modelo (por ejemplo `reasoning_content`, `thinking_delta` de Claude o las partes de pensamiento de Gemini).\n\n### parser.reasoning {String}\n\nType: `property` · Since: `0.0.17`\n\nLo que el modelo está produciendo ahora.\n\nReturns: `String`\n\n`content`, `thinking` o `tool`, según el último tipo de datos recibido.\n\n### parser.tools {Array}\n\nType: `property`\n\nLas llamadas a herramientas recogidas hasta el momento.\n\nReturns: `Array`\n\nUn objeto por cada llamada a herramienta, en el orden en que empezaron las llamadas: `id` y `name` de la llamada, `arguments` (el texto de los argumentos unido a partir de los fragmentos; para los proveedores que envían los argumentos como objeto, su JSON) e `input` (los argumentos parseados, que rellenan `parser.output()` y `parser.end()`). Usa `output.tools` de `parser.end()` para las llamadas finales con los argumentos parseados.\n\nExample: Argumentos en bruto y parseados\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { role: 'assistant', content: '', tool_calls: [{ function: { name: 'weather', arguments: { city: 'Bratislava' } } }] } });\nconsole.log(parser.tools[0].name);      // 'weather'\nconsole.log(parser.tools[0].arguments); // '{\"city\":\"Bratislava\"}'\nconsole.log(parser.end().tools[0].arguments); // { city: 'Bratislava' }\n```\n\n### parser.on('content', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNuevo texto de la respuesta.\n\n`e.delta` es el texto nuevo y `e.content` todo el texto hasta el momento.\n\n### parser.on('thinking', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNuevo texto de razonamiento.\n\n`e.delta` es el texto nuevo y `e.thinking` todo el razonamiento hasta el momento.\n\n### parser.on('tool_start', function(e) {})\n\nType: `event`\n\nAparece una nueva llamada a herramienta.\n\n`e.tool` es `{ id, name, arguments }` de la nueva llamada; `arguments` suele ser `{}` en este momento. `e.reasoning` es `tool`.\n\nExample: Registrar las llamadas\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_start', function(e) {\n\tconsole.log('The model calls', e.tool.name, e.tool.id);\n});\n```\n\n### parser.on('tool_update', function(e) {})\n\nType: `event`\n\nMás datos de una llamada a herramienta conocida.\n\nSe emite cuando el stream envía más datos para una llamada que ya empezó, antes de cada nuevo fragmento de sus argumentos. `e.tool` es `{ id, name, arguments }` con los argumentos parseados hasta el momento: un objeto una vez que el texto unido es JSON válido; si no, el texto recortado.\n\nExample: Ver cómo crecen los argumentos\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_update', function(e) {\n\tconsole.log(e.tool.id, e.tool.arguments);\n});\n```\n\n### parser.on('tool_arguments', function(e) {})\n\nType: `event`\n\nUn fragmento de los argumentos de una llamada a herramienta.\n\n`e.delta` es el nuevo fragmento y `e.arguments` todo el texto de los argumentos de la llamada hasta el momento. Para los proveedores que envían los argumentos enteros como objeto (Ollama, Gemini), ambos son ese objeto. `e.tool` es `{ id, name, arguments }` con los argumentos parseados hasta el momento.\n\nExample: Argumentos de un stream de Claude\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.on('done', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nEl stream ha terminado.\n\nLo emite `parser.end()`. `e.output` es la salida final.\n","entries":[{"type":"method","name":"NEWAIMODEL()","signature":"NEWAIMODEL(name, [config], handler)","since":"0.0.16","deprecated":false},{"type":"delegate","name":"handler(ai, callback)","signature":"function(ai, callback)","since":"0.0.16","deprecated":false},{"type":"method","name":"AIMODEL()","signature":"AIMODEL(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.system()","signature":"ai.system(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.user()","signature":"ai.user(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.assistant()","signature":"ai.assistant(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.message()","signature":"ai.message(role, content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.prompt()","signature":"ai.prompt(content)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.think()","signature":"ai.think()","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.configure()","signature":"ai.configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.callback()","signature":"ai.callback(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.stream()","signature":"ai.stream(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.promise()","signature":"ai.promise([$])","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.payload","signature":"ai.payload {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.config","signature":"ai.config {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.options","signature":"ai.options {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"F.aimodels","signature":"F.aimodels {Object}","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.tool()","signature":"ai.tool(content)","since":"0.0.17","deprecated":false},{"type":"method","name":"AIPARSER()","signature":"AIPARSER(provider)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.write()","signature":"parser.write(chunk)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.end()","signature":"parser.end()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.output()","signature":"parser.output()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.on()","signature":"parser.on(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.off()","signature":"parser.off(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.reset()","signature":"parser.reset()","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.content","signature":"parser.content {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.thinking","signature":"parser.thinking {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.reasoning","signature":"parser.reasoning {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.tools","signature":"parser.tools {Array}","since":"","deprecated":false},{"type":"event","name":"content","signature":"parser.on('content', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"thinking","signature":"parser.on('thinking', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"tool_start","signature":"parser.on('tool_start', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_update","signature":"parser.on('tool_update', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_arguments","signature":"parser.on('tool_arguments', function(e) {})","since":"","deprecated":false},{"type":"event","name":"done","signature":"parser.on('done', function(e) {})","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwSk45x60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/ai-models/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Modèles d'IA","summary":"NEWAIMODEL(), AIMODEL(), les méthodes et propriétés de la requête, et le parseur de stream d'IA.","markdown":"---\ntitle: \"Modèles d'IA\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/ai-models/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Modèles d'IA\n\n> NEWAIMODEL(), AIMODEL(), les méthodes et propriétés de la requête, et le parseur de stream d'IA.\n\nCette page liste les fonctions globales pour les modèles d'IA, les méthodes et propriétés de l'objet de requête de `AIMODEL()`, le handler du modèle et, quand ils sont disponibles, le parseur de stream et ses événements. Le guide [Modèles d'IA](../../guides/ai-models/) explique comment ils fonctionnent ensemble, avec un handler complet.\n\n## API\n\n### NEWAIMODEL(name, [config], handler)\n\nType: `method` · Since: `0.0.16`\n\nEnregistre un handler pour un ou plusieurs modèles d'IA.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du modèle, ou plusieurs noms séparés par des virgules. |\n| `config` | `Object` | no |  | Configuration par défaut (URL, token, paramètres) copiée dans `ai.config` de chaque requête. |\n| `handler` | `Function` | yes |  | `function(ai, callback)`. Appelle le fournisseur et se termine par `callback(err, response)`. |\n\nReturns: `undefined`\n\nStocke `handler` avec `config` dans `F.aimodels` sous chaque nom de `name` (les noms séparés par des virgules sont nettoyés de leurs espaces). Un nom enregistré à nouveau remplace le handler précédent. Le handler est appelé par chaque requête de `AIMODEL()` portant ce nom. Avant son exécution, chaque clé de `config` que la requête n'a pas définie avec `ai.configure()` est copiée dans `ai.config`. Lorsque le second argument est une fonction, c'est le handler et il n'y a pas de configuration.\n\nExample: Modèle Ollama\n```js\nNEWAIMODEL('llama3', { url: 'http://localhost:11434/api/chat' }, function(ai, callback) {\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json' };\n\topt.body = JSON.stringify({ model: ai.payload.model, messages: ai.payload.messages, stream: false });\n\tfetch(ai.config.url, opt).then(res => res.json()).then(function(json) {\n\t\tcallback(null, json.message.content);\n\t}).catch(callback);\n});\n```\n\n### function(ai, callback)\n\nType: `delegate` · Since: `0.0.16`\n\nLe handler de modèle passé à NEWAIMODEL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ai` | `AIModel` | yes |  | La requête. |\n| `callback` | `Function` | yes |  | `function(err, response)` qui termine la requête. |\n\nAppelé une fois par requête, lorsque la requête s'exécute. `ai` est l'objet de requête de `AIMODEL()` : lis `ai.payload` pour les données à envoyer, `ai.config` pour les paramètres (avec les valeurs par défaut de `NEWAIMODEL()` déjà appliquées) et `ai.options.stream` pour la fonction de stream de l'appelant. Appelle `ai.options.stream(piece)` pour chaque morceau d'une réponse en stream, puis `callback(err, response)` une seule fois. La `response` parvient telle quelle à l'appelant.\n\nExample: Handler d'écho pour les tests\n```js\nNEWAIMODEL('echo', function(ai, callback) {\n\tvar last = ai.payload.messages[ai.payload.messages.length - 1];\n\tai.options.stream && ai.options.stream(last.content);\n\tcallback(null, last.content);\n});\n```\n\n### AIMODEL(name)\n\nType: `method` · Since: `0.0.16`\n\nCrée une requête pour un modèle d'IA enregistré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom utilisé dans `NEWAIMODEL()`. Il est aussi stocké dans `payload.model`. |\n\nReturns: `AIModel` Une nouvelle requête.\n\nRenvoie un nouvel objet de requête. Ajoute des messages et des paramètres avec ses méthodes, puis exécute-la avec `callback()`, `stream()` ou `promise()`. La requête recherche le modèle au moment de son exécution ; lorsqu'aucun modèle n'est enregistré sous ce nom, le callback reçoit l'erreur `'AI model not found.'`.\n\nExample: Question simple\n```js\nAIMODEL('assistant').user('What is 2 + 2?').callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ai.system(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAjoute un message système.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Le texte, ou un objet dont les clés sont copiées dans le message. |\n| `merge` | `String` | no |  | Un séparateur. S'il est défini et qu'un message système existe, le contenu y est ajouté. |\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nIdentique à `ai.message('system', content, merge)`. Utilise-la pour les instructions du modèle.\n\nExample: Instructions\n```js\nAIMODEL('assistant').system('Answer in one sentence.').user('What is Node.js?').callback(console.log);\n```\n\n### ai.user(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAjoute un message utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Le texte, ou un objet dont les clés sont copiées dans le message. |\n| `merge` | `String` | no |  | Un séparateur. S'il est défini et qu'un message utilisateur existe, le contenu y est ajouté. |\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nIdentique à `ai.message('user', content, merge)`.\n\nExample: Message avec une image\n```js\nAIMODEL('vision').user({ content: 'What is in this picture?', images: [base64] }).callback(console.log);\n```\n\n### ai.assistant(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAjoute un message assistant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Le texte, ou un objet dont les clés sont copiées dans le message. |\n| `merge` | `String` | no |  | Un séparateur. S'il est défini et qu'un message assistant existe, le contenu y est ajouté. |\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nIdentique à `ai.message('assistant', content, merge)`. Utilise-la pour rejouer des réponses précédentes du modèle dans une conversation.\n\nExample: Historique de conversation\n```js\nvar ai = AIMODEL('assistant');\nfor (var item of history) {\n\tif (item.fromuser)\n\t\tai.user(item.text);\n\telse\n\t\tai.assistant(item.text);\n}\nai.user(question).callback(console.log);\n```\n\n### ai.message(role, content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAjoute un message avec n'importe quel rôle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `role` | `String` | yes |  | Le rôle, par ex. `system`, `user`, `assistant` ou `tool`. |\n| `content` | `String|Object` | yes |  | Le texte, ou un objet dont les clés sont copiées dans le message. |\n| `merge` | `String` | no |  | Une chaîne de séparation qui active la fusion. |\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nAjoute `{ role, content }` à `ai.payload.messages`. Lorsque `content` est un objet, ses clés sont copiées dans le message à la place de `content`. Lorsque `merge` est défini et qu'un message avec le même rôle existe, rien n'est ajouté : une chaîne est ajoutée au contenu du premier message de ce type avec `merge` entre les deux, et les clés d'un objet y sont copiées.\n\nExample: Instructions fusionnées\n```js\nAIMODEL('assistant')\n\t.message('system', 'You are a translator.')\n\t.message('system', 'Translate to German.', '\\n')\n\t.user('Good morning')\n\t.callback(console.log);\n```\n\n### ai.prompt(content)\n\nType: `method` · Since: `0.0.16`\n\nDéfinit un prompt unique.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String` | yes |  | Le prompt. |\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nDéfinit `ai.payload.prompt`. Utile pour les handlers d'endpoints qui acceptent un seul prompt au lieu d'une liste de messages (par exemple l'endpoint `/api/generate` d'Ollama). Le handler décide comment l'utiliser.\n\nExample: Prompt\n```js\nAIMODEL('generator').prompt('Write a slogan for a bakery').callback(console.log);\n```\n\n### ai.think()\n\nType: `method` · Since: `0.0.16`\n\nDemande le mode de réflexion.\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nDéfinit `ai.payload.think = true`. Le handler l'associe à l'option du fournisseur (par exemple `think` d'Ollama).\n\nExample: Réflexion\n```js\nAIMODEL('reasoner').think().user('Is 1001 a prime number?').callback(console.log);\n```\n\n### ai.configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nDéfinit la configuration de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Les clés à définir. |\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nCopie les clés de `obj` dans `ai.config`. Ces valeurs l'emportent sur les valeurs par défaut de `NEWAIMODEL()`, qui ne remplissent que les clés non définies.\n\nExample: Température pour une seule requête\n```js\nAIMODEL('assistant').configure({ temperature: 0 }).user('List three colors').callback(console.log);\n```\n\n### ai.callback(fn)\n\nType: `method` · Since: `0.0.16`\n\nDéfinit le callback et exécute la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nStocke `fn` et exécute la requête au tour suivant de la boucle d'événements. Appeler à nouveau `callback()`, `stream()` ou `promise()` dans le même tour déplace l'exécution : le handler n'est donc appelé qu'une seule fois.\n\nExample: Callback\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\terr && console.log(err);\n});\n```\n\n### ai.stream(fn)\n\nType: `method` · Since: `0.0.16`\n\nDéfinit la fonction de stream et exécute la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Appelée par le handler avec chaque morceau de la réponse. |\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nStocke `fn` dans `ai.options.stream` et exécute la requête au tour suivant de la boucle d'événements. Le handler appelle `fn` avec les morceaux de la réponse ; la nature d'un morceau (texte, objet) dépend du handler. Ajoute `callback()` pour savoir quand la réponse se termine.\n\nExample: Stream vers la console\n```js\nAIMODEL('assistant').user('Tell a story').stream(function(text) {\n\tprocess.stdout.write(text);\n}).callback(function(err) {\n\tconsole.log('end', err);\n});\n```\n\n### ai.promise([$])\n\nType: `method` · Since: `0.0.16`\n\nExécute la requête et renvoie une Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Le `$` d'une action ou d'un contrôleur, pour signaler les erreurs avec `$.invalid()`. |\n\nReturns: `Promise` Résolue avec la réponse du handler.\n\nExécute la requête via `callback()`. La promesse est résolue avec la réponse. Une erreur la rejette avec une `Error` ; lorsqu'un `$` avec `$.invalid()` est passé, l'erreur va à `$.invalid(err)` à la place et la promesse reste en attente.\n\nExample: Dans une action\n```js\nNEWACTION('Assistant/ask', {\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar answer = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: answer });\n\t}\n});\n```\n\n### ai.payload {Object}\n\nType: `property` · Since: `0.0.16`\n\nLes données de la requête destinées au fournisseur.\n\nReturns: `Object`\n\nContient `model` (le nom donné à `AIMODEL()`), `messages` (un tableau d'objets message) et `tools` (un tableau de définitions d'outils, vide par défaut), plus `prompt` et `think` lorsqu'ils sont définis. Le handler le lit pour construire le corps de la requête au fournisseur.\n\nExample: Lire la charge utile\n```js\nNEWAIMODEL('debug', function(ai, callback) {\n\tcallback(null, JSON.stringify(ai.payload));\n});\n```\n\n### ai.config {Object}\n\nType: `property` · Since: `0.0.16`\n\nLa configuration de la requête.\n\nReturns: `Object`\n\nLes clés définies avec `ai.configure()`, complétées par les valeurs par défaut de `NEWAIMODEL()` juste avant l'exécution du handler.\n\n### ai.options {Object}\n\nType: `property` · Since: `0.0.16`\n\nLes options d'exécution de la requête.\n\nReturns: `Object`\n\nContient `callback` (la fonction définie par `callback()` ou `promise()`, `NOOP` par défaut) et `stream` (la fonction définie par `stream()`, ou undefined). Un handler vérifie `ai.options.stream` pour savoir si l'appelant veut un stream.\n\nExample: Vérifier le streaming\n```js\nif (ai.options.stream)\n\tbody.stream = true;\n```\n\n### F.aimodels {Object}\n\nType: `property` · Since: `0.0.16`\n\nLes modèles d'IA enregistrés.\n\nReturns: `Object`\n\nUn objet avec les noms des modèles comme clés et `{ config, callback }` comme valeurs, rempli par `NEWAIMODEL()`.\n\nExample: Un modèle est-il enregistré ?\n```js\nif (F.aimodels.assistant)\n\tconsole.log('ready');\n```\n\n### ai.tool(content)\n\nType: `method` · Since: `0.0.17`\n\nAjoute une définition d'outil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `Object` | yes |  | La définition de l'outil. |\n\nReturns: `AIModel` La même requête, pour le chaînage.\n\nAjoute `content` à `ai.payload.tools`. Le framework ne le modifie ni ne le vérifie ; le handler envoie les outils au fournisseur dans son format. `schema.toAITool(name)` d'un schéma en ligne renvoie le format de fonction courant.\n\nExample: Outil à partir d'un schéma\n```js\nNEWSCHEMA('@Task', '*name:String // The name of the task,due:Date');\n\nAIMODEL('assistant')\n\t.user('Create a task: call Peter tomorrow')\n\t.tool(F.jsonschemas.Task.toAITool('create_task'))\n\t.callback(console.log);\n```\n\n### AIPARSER(provider)\n\nType: `method` · Since: `0.0.17`\n\nCrée un parser pour les réponses IA en streaming.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `provider` | `String` | no | `generic` | Le format du stream. |\n\nReturns: `AIParser` Un nouveau parser.\n\nRenvoie un parser de stream pour le format de `provider` : `ollama`, `openai` (ou `openai_chat`), `openai_responses`, `claude` (ou `anthropic`), `gemini` (ou `google`). Toute autre valeur utilise un parser générique. Écris les morceaux bruts avec `parser.write()` et termine avec `parser.end()`.\n\nExample: Parser un stream Claude\n```js\nvar parser = AIPARSER('claude');\nparser.on('content', e => process.stdout.write(e.delta));\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\nvar output = parser.end();\n```\n\n### parser.write(chunk)\n\nType: `method` · Since: `0.0.17`\n\nÉcrit un morceau du stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `chunk` | `Buffer|String|Object` | yes |  | Données brutes ou un événement déjà analysé. |\n\nReturns: `Object` La sortie actuelle, identique à `parser.output()`.\n\nUn `Buffer`, une chaîne, un `Uint8Array` ou un `ArrayBuffer` est ajouté à un buffer interne et chaque ligne complète est analysée : les lignes vides et `[DONE]` sont ignorées, un préfixe `data:` est retiré et le reste est analysé comme JSON. Une ligne qui n'est pas du JSON est ignorée. Un objet est analysé directement comme un événement du fournisseur. `null` renvoie seulement la sortie.\n\nExample: Écrire des objets analysés\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { content: 'Hel' } });\nparser.write({ message: { content: 'lo' } });\nparser.end().content; // 'Hello'\n```\n\n### parser.end()\n\nType: `method` · Since: `0.0.17`\n\nTermine le stream.\n\nReturns: `Object` `{ content, thinking, tools, reasoning }`, plus `thinking_signature` ou `thought_signatures` quand le fournisseur les envoie.\n\nAnalyse le reste du buffer (une dernière ligne sans retour à la ligne), analyse les arguments assemblés de chaque appel d'outil, émet `done` avec `{ output }` et renvoie la sortie.\n\nExample: Sortie finale\n```js\nvar output = parser.end();\nconsole.log(output.content);\n```\n\nExample: Appels d'outils d'un stream Claude\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.output()\n\nType: `method` · Since: `0.0.17`\n\nRenvoie la sortie actuelle.\n\nReturns: `Object` La sortie jusqu'à présent.\n\nRenvoie `{ content, thinking, tools, reasoning }`. `tools` est un tableau de `{ id, name, arguments }` avec les appels d'outils de chaque fournisseur, où `arguments` est le JSON analysé des arguments assemblés (le texte nettoyé des espaces quand ce n'est pas du JSON valide, par exemple pendant que les arguments sont encore en streaming, et `{}` quand il est vide). `reasoning` vaut `tool` quand il y a des appels d'outils, sinon `thinking` ou `content` selon le dernier type de données. `thinking_signature` (Claude) et `thought_signatures` (Gemini) sont ajoutés lorsqu'ils sont présents.\n\n### parser.on(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nÉcoute un événement du parser.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le nom de l'événement. |\n| `fn` | `Function` | yes |  | `function(event)`. |\n\nReturns: `AIParser` Le parser, pour le chaînage.\n\nAjoute `fn` pour l'événement `type` : `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments`, `done`, ou `*` pour tous les événements. `fn` reçoit un objet avec `type` et les données de l'événement.\n\nExample: Tous les événements\n```js\nAIPARSER('openai').on('*', function(e) {\n\tconsole.log(e.type);\n});\n```\n\n### parser.off(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nSupprime un écouteur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le nom de l'événement. |\n| `fn` | `Function` | yes |  | La fonction passée à `parser.on()`. |\n\nReturns: `AIParser` Le parser, pour le chaînage.\n\nRetire `fn` des écouteurs de `type`.\n\n### parser.reset()\n\nType: `method` · Since: `0.0.17`\n\nRéinitialise le parser.\n\nReturns: `AIParser` Le parser.\n\nEfface le contenu, la réflexion, les outils, le buffer et les signatures, afin que le parser puisse lire un autre stream du même fournisseur. Les écouteurs restent.\n\n### parser.content {String}\n\nType: `property` · Since: `0.0.17`\n\nLe texte collecté jusqu'à présent.\n\nReturns: `String`\n\nTout le texte de la réponse, assemblé à partir des deltas.\n\n### parser.thinking {String}\n\nType: `property` · Since: `0.0.17`\n\nLe raisonnement collecté jusqu'à présent.\n\nReturns: `String`\n\nTout le texte de raisonnement ou de réflexion envoyé par le modèle (par exemple `reasoning_content`, `thinking_delta` de Claude ou les parties thought de Gemini).\n\n### parser.reasoning {String}\n\nType: `property` · Since: `0.0.17`\n\nCe que le modèle produit en ce moment.\n\nReturns: `String`\n\n`content`, `thinking` ou `tool`, selon le dernier type de données reçu.\n\n### parser.tools {Array}\n\nType: `property`\n\nLes appels d'outils collectés jusque-là.\n\nReturns: `Array`\n\nUn objet pour chaque appel d'outil, dans l'ordre où les appels ont commencé : `id` et `name` de l'appel, `arguments` (le texte des arguments assemblé à partir des morceaux ; pour les fournisseurs qui envoient les arguments sous forme d'objet, son JSON) et `input` (les arguments analysés, remplis par `parser.output()` et `parser.end()`). Utilise `output.tools` de `parser.end()` pour les appels finaux avec les arguments analysés.\n\nExample: Arguments bruts et analysés\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { role: 'assistant', content: '', tool_calls: [{ function: { name: 'weather', arguments: { city: 'Bratislava' } } }] } });\nconsole.log(parser.tools[0].name);      // 'weather'\nconsole.log(parser.tools[0].arguments); // '{\"city\":\"Bratislava\"}'\nconsole.log(parser.end().tools[0].arguments); // { city: 'Bratislava' }\n```\n\n### parser.on('content', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNouveau texte de la réponse.\n\n`e.delta` est le nouveau texte et `e.content` tout le texte jusqu'à présent.\n\n### parser.on('thinking', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNouveau texte de raisonnement.\n\n`e.delta` est le nouveau texte et `e.thinking` tout le raisonnement jusqu'à présent.\n\n### parser.on('tool_start', function(e) {})\n\nType: `event`\n\nUn nouvel appel d'outil apparaît.\n\n`e.tool` est `{ id, name, arguments }` du nouvel appel ; `arguments` vaut généralement `{}` à ce stade. `e.reasoning` vaut `tool`.\n\nExample: Journaliser les appels\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_start', function(e) {\n\tconsole.log('The model calls', e.tool.name, e.tool.id);\n});\n```\n\n### parser.on('tool_update', function(e) {})\n\nType: `event`\n\nD'autres données d'un appel d'outil connu.\n\nÉmis quand le stream envoie d'autres données pour un appel déjà commencé, avant chaque nouveau morceau de ses arguments. `e.tool` est `{ id, name, arguments }` avec les arguments analysés jusque-là : un objet dès que le texte assemblé est du JSON valide, sinon le texte nettoyé des espaces.\n\nExample: Voir les arguments grandir\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_update', function(e) {\n\tconsole.log(e.tool.id, e.tool.arguments);\n});\n```\n\n### parser.on('tool_arguments', function(e) {})\n\nType: `event`\n\nUn morceau des arguments d'un appel d'outil.\n\n`e.delta` est le nouveau morceau et `e.arguments` tout le texte des arguments de l'appel jusque-là. Pour les fournisseurs qui envoient les arguments en entier sous forme d'objet (Ollama, Gemini), les deux sont cet objet. `e.tool` est `{ id, name, arguments }` avec les arguments analysés jusque-là.\n\nExample: Arguments d'un stream Claude\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.on('done', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nLe stream est terminé.\n\nÉmis par `parser.end()`. `e.output` est la sortie finale.\n","entries":[{"type":"method","name":"NEWAIMODEL()","signature":"NEWAIMODEL(name, [config], handler)","since":"0.0.16","deprecated":false},{"type":"delegate","name":"handler(ai, callback)","signature":"function(ai, callback)","since":"0.0.16","deprecated":false},{"type":"method","name":"AIMODEL()","signature":"AIMODEL(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.system()","signature":"ai.system(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.user()","signature":"ai.user(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.assistant()","signature":"ai.assistant(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.message()","signature":"ai.message(role, content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.prompt()","signature":"ai.prompt(content)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.think()","signature":"ai.think()","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.configure()","signature":"ai.configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.callback()","signature":"ai.callback(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.stream()","signature":"ai.stream(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.promise()","signature":"ai.promise([$])","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.payload","signature":"ai.payload {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.config","signature":"ai.config {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.options","signature":"ai.options {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"F.aimodels","signature":"F.aimodels {Object}","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.tool()","signature":"ai.tool(content)","since":"0.0.17","deprecated":false},{"type":"method","name":"AIPARSER()","signature":"AIPARSER(provider)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.write()","signature":"parser.write(chunk)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.end()","signature":"parser.end()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.output()","signature":"parser.output()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.on()","signature":"parser.on(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.off()","signature":"parser.off(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.reset()","signature":"parser.reset()","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.content","signature":"parser.content {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.thinking","signature":"parser.thinking {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.reasoning","signature":"parser.reasoning {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.tools","signature":"parser.tools {Array}","since":"","deprecated":false},{"type":"event","name":"content","signature":"parser.on('content', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"thinking","signature":"parser.on('thinking', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"tool_start","signature":"parser.on('tool_start', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_update","signature":"parser.on('tool_update', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_arguments","signature":"parser.on('tool_arguments', function(e) {})","since":"","deprecated":false},{"type":"event","name":"done","signature":"parser.on('done', function(e) {})","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwSk45x60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/ai-models/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Modelli AI","summary":"NEWAIMODEL(), AIMODEL(), i metodi e le proprietà della richiesta e il parser dello stream AI.","markdown":"---\ntitle: Modelli AI\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/ai-models/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Modelli AI\n\n> NEWAIMODEL(), AIMODEL(), i metodi e le proprietà della richiesta e il parser dello stream AI.\n\nQuesta pagina elenca le funzioni globali per i modelli AI, i metodi e le proprietà dell'oggetto richiesta di `AIMODEL()`, l'handler del modello e, dove disponibili, il parser dello stream e i suoi eventi. La guida [Modelli AI](../../guides/ai-models/) spiega come funzionano insieme, con un handler completo.\n\n## API\n\n### NEWAIMODEL(name, [config], handler)\n\nType: `method` · Since: `0.0.16`\n\nRegistra un handler per uno o più modelli AI.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del modello, o più nomi separati da virgole. |\n| `config` | `Object` | no |  | Config predefinita (URL, token, impostazioni) copiata in `ai.config` di ogni richiesta. |\n| `handler` | `Function` | yes |  | `function(ai, callback)`. Chiama il provider e termina con `callback(err, response)`. |\n\nReturns: `undefined`\n\nSalva `handler` con `config` in `F.aimodels` sotto ogni nome di `name` (i nomi separati da virgole vengono ripuliti dagli spazi). Un nome registrato di nuovo sostituisce l'handler precedente. L'handler viene chiamato da ogni richiesta di `AIMODEL()` con quel nome. Prima che venga eseguito, ogni chiave di `config` che la richiesta non ha impostato con `ai.configure()` viene copiata in `ai.config`. Quando il secondo argomento è una funzione, è l'handler e non c'è config.\n\nExample: Modello Ollama\n```js\nNEWAIMODEL('llama3', { url: 'http://localhost:11434/api/chat' }, function(ai, callback) {\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json' };\n\topt.body = JSON.stringify({ model: ai.payload.model, messages: ai.payload.messages, stream: false });\n\tfetch(ai.config.url, opt).then(res => res.json()).then(function(json) {\n\t\tcallback(null, json.message.content);\n\t}).catch(callback);\n});\n```\n\n### function(ai, callback)\n\nType: `delegate` · Since: `0.0.16`\n\nL'handler del modello passato a NEWAIMODEL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ai` | `AIModel` | yes |  | La richiesta. |\n| `callback` | `Function` | yes |  | `function(err, response)` che termina la richiesta. |\n\nChiamato una volta per richiesta, quando la richiesta viene eseguita. `ai` è l'oggetto richiesta di `AIMODEL()`: leggi `ai.payload` per i dati da inviare, `ai.config` per le impostazioni (con i valori predefiniti di `NEWAIMODEL()` già applicati) e `ai.options.stream` per la funzione di stream del chiamante. Chiama `ai.options.stream(piece)` per ogni pezzo di una risposta in streaming, poi `callback(err, response)` una volta. La `response` arriva al chiamante invariata.\n\nExample: Handler eco per i test\n```js\nNEWAIMODEL('echo', function(ai, callback) {\n\tvar last = ai.payload.messages[ai.payload.messages.length - 1];\n\tai.options.stream && ai.options.stream(last.content);\n\tcallback(null, last.content);\n});\n```\n\n### AIMODEL(name)\n\nType: `method` · Since: `0.0.16`\n\nCrea una richiesta per un modello AI registrato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome usato in `NEWAIMODEL()`. Viene salvato anche come `payload.model`. |\n\nReturns: `AIModel` Una nuova richiesta.\n\nRestituisce un nuovo oggetto richiesta. Aggiungi messaggi e impostazioni con i suoi metodi, poi eseguilo con `callback()`, `stream()` o `promise()`. La richiesta cerca il modello quando viene eseguita; quando non è registrato alcun modello con quel nome, la callback riceve l'errore `'AI model not found.'`.\n\nExample: Domanda semplice\n```js\nAIMODEL('assistant').user('What is 2 + 2?').callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ai.system(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAggiunge un messaggio di sistema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Il testo, o un oggetto le cui chiavi vengono copiate nel messaggio. |\n| `merge` | `String` | no |  | Un separatore. Quando è impostato ed esiste un messaggio di sistema, il contenuto viene accodato ad esso. |\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nEquivale a `ai.message('system', content, merge)`. Usalo per le istruzioni del modello.\n\nExample: Istruzioni\n```js\nAIMODEL('assistant').system('Answer in one sentence.').user('What is Node.js?').callback(console.log);\n```\n\n### ai.user(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAggiunge un messaggio dell'utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Il testo, o un oggetto le cui chiavi vengono copiate nel messaggio. |\n| `merge` | `String` | no |  | Un separatore. Quando è impostato ed esiste un messaggio dell'utente, il contenuto viene accodato ad esso. |\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nEquivale a `ai.message('user', content, merge)`.\n\nExample: Messaggio con un'immagine\n```js\nAIMODEL('vision').user({ content: 'What is in this picture?', images: [base64] }).callback(console.log);\n```\n\n### ai.assistant(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAggiunge un messaggio dell'assistente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Il testo, o un oggetto le cui chiavi vengono copiate nel messaggio. |\n| `merge` | `String` | no |  | Un separatore. Quando è impostato ed esiste un messaggio dell'assistente, il contenuto viene accodato ad esso. |\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nEquivale a `ai.message('assistant', content, merge)`. Usalo per riproporre in una conversazione le risposte precedenti del modello.\n\nExample: Cronologia della conversazione\n```js\nvar ai = AIMODEL('assistant');\nfor (var item of history) {\n\tif (item.fromuser)\n\t\tai.user(item.text);\n\telse\n\t\tai.assistant(item.text);\n}\nai.user(question).callback(console.log);\n```\n\n### ai.message(role, content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nAggiunge un messaggio con un ruolo qualsiasi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `role` | `String` | yes |  | Il ruolo, ad es. `system`, `user`, `assistant` o `tool`. |\n| `content` | `String|Object` | yes |  | Il testo, o un oggetto le cui chiavi vengono copiate nel messaggio. |\n| `merge` | `String` | no |  | Una stringa separatore che attiva l'unione. |\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nAggiunge `{ role, content }` a `ai.payload.messages`. Quando `content` è un oggetto, le sue chiavi vengono copiate nel messaggio al posto di `content`. Quando `merge` è impostato ed esiste un messaggio con lo stesso ruolo, non viene aggiunto nulla: una stringa viene accodata al contenuto del primo di questi messaggi con `merge` in mezzo, e le chiavi di un oggetto vengono copiate in esso.\n\nExample: Istruzioni unite\n```js\nAIMODEL('assistant')\n\t.message('system', 'You are a translator.')\n\t.message('system', 'Translate to German.', '\\n')\n\t.user('Good morning')\n\t.callback(console.log);\n```\n\n### ai.prompt(content)\n\nType: `method` · Since: `0.0.16`\n\nImposta un prompt singolo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String` | yes |  | Il prompt. |\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nImposta `ai.payload.prompt`. Utile per gli handler di endpoint che accettano un solo prompt invece di un elenco di messaggi (per esempio l'endpoint `/api/generate` di Ollama). È l'handler a decidere come usarlo.\n\nExample: Prompt\n```js\nAIMODEL('generator').prompt('Write a slogan for a bakery').callback(console.log);\n```\n\n### ai.think()\n\nType: `method` · Since: `0.0.16`\n\nRichiede la modalità di ragionamento.\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nImposta `ai.payload.think = true`. L'handler lo mappa sull'opzione del provider (per esempio `think` di Ollama).\n\nExample: Ragionamento\n```js\nAIMODEL('reasoner').think().user('Is 1001 a prime number?').callback(console.log);\n```\n\n### ai.configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nImposta la config della richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Le chiavi da impostare. |\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nCopia le chiavi di `obj` in `ai.config`. Questi valori hanno la precedenza sui valori predefiniti di `NEWAIMODEL()`, che riempiono solo le chiavi non impostate.\n\nExample: Temperatura per una sola richiesta\n```js\nAIMODEL('assistant').configure({ temperature: 0 }).user('List three colors').callback(console.log);\n```\n\n### ai.callback(fn)\n\nType: `method` · Since: `0.0.16`\n\nImposta la callback ed esegue la richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nSalva `fn` ed esegue la richiesta al giro successivo dell'event loop. Chiamare di nuovo `callback()`, `stream()` o `promise()` nello stesso giro sposta l'esecuzione, quindi l'handler viene chiamato una sola volta.\n\nExample: Callback\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\terr && console.log(err);\n});\n```\n\n### ai.stream(fn)\n\nType: `method` · Since: `0.0.16`\n\nImposta la funzione di stream ed esegue la richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Chiamata dall'handler con ogni pezzo della risposta. |\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nSalva `fn` in `ai.options.stream` ed esegue la richiesta al giro successivo dell'event loop. L'handler chiama `fn` con i pezzi della risposta; cosa sia un pezzo (testo, un oggetto) dipende dall'handler. Aggiungi `callback()` per sapere quando la risposta finisce.\n\nExample: Stream verso la console\n```js\nAIMODEL('assistant').user('Tell a story').stream(function(text) {\n\tprocess.stdout.write(text);\n}).callback(function(err) {\n\tconsole.log('end', err);\n});\n```\n\n### ai.promise([$])\n\nType: `method` · Since: `0.0.16`\n\nEsegue la richiesta e restituisce una Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Il `$` di un'azione o di un controller, per segnalare gli errori con `$.invalid()`. |\n\nReturns: `Promise` Si risolve con la risposta dell'handler.\n\nEsegue la richiesta tramite `callback()`. La promise si risolve con la risposta. Un errore la rifiuta con un `Error`; quando viene passato `$` con `$.invalid()`, l'errore va invece a `$.invalid(err)` e la promise resta in sospeso.\n\nExample: In un'azione\n```js\nNEWACTION('Assistant/ask', {\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar answer = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: answer });\n\t}\n});\n```\n\n### ai.payload {Object}\n\nType: `property` · Since: `0.0.16`\n\nI dati della richiesta per il provider.\n\nReturns: `Object`\n\nContiene `model` (il nome passato ad `AIMODEL()`), `messages` (un array di oggetti messaggio) e `tools` (un array di definizioni di tool, vuoto per impostazione predefinita), più `prompt` e `think` quando sono impostati. L'handler lo legge per costruire il body della richiesta al provider.\n\nExample: Leggere il payload\n```js\nNEWAIMODEL('debug', function(ai, callback) {\n\tcallback(null, JSON.stringify(ai.payload));\n});\n```\n\n### ai.config {Object}\n\nType: `property` · Since: `0.0.16`\n\nLa config della richiesta.\n\nReturns: `Object`\n\nLe chiavi impostate con `ai.configure()`, completate con i valori predefiniti di `NEWAIMODEL()` subito prima che l'handler venga eseguito.\n\n### ai.options {Object}\n\nType: `property` · Since: `0.0.16`\n\nLe opzioni di esecuzione della richiesta.\n\nReturns: `Object`\n\nContiene `callback` (la funzione impostata da `callback()` o `promise()`, `NOOP` per impostazione predefinita) e `stream` (la funzione impostata da `stream()`, oppure undefined). Un handler controlla `ai.options.stream` per sapere se il chiamante vuole uno stream.\n\nExample: Verificare lo streaming\n```js\nif (ai.options.stream)\n\tbody.stream = true;\n```\n\n### F.aimodels {Object}\n\nType: `property` · Since: `0.0.16`\n\nI modelli AI registrati.\n\nReturns: `Object`\n\nUn oggetto con i nomi dei modelli come chiavi e `{ config, callback }` come valori, riempito da `NEWAIMODEL()`.\n\nExample: Un modello è registrato?\n```js\nif (F.aimodels.assistant)\n\tconsole.log('ready');\n```\n\n### ai.tool(content)\n\nType: `method` · Since: `0.0.17`\n\nAggiunge una definizione di tool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `Object` | yes |  | La definizione del tool. |\n\nReturns: `AIModel` La stessa richiesta, per il concatenamento.\n\nAggiunge `content` a `ai.payload.tools`. Il framework non lo modifica né lo verifica; l'handler invia i tool al provider nel suo formato. `schema.toAITool(name)` di uno schema inline restituisce il formato comune delle funzioni.\n\nExample: Tool da uno schema\n```js\nNEWSCHEMA('@Task', '*name:String // The name of the task,due:Date');\n\nAIMODEL('assistant')\n\t.user('Create a task: call Peter tomorrow')\n\t.tool(F.jsonschemas.Task.toAITool('create_task'))\n\t.callback(console.log);\n```\n\n### AIPARSER(provider)\n\nType: `method` · Since: `0.0.17`\n\nCrea un parser per le risposte AI in streaming.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `provider` | `String` | no | `generic` | Il formato dello stream. |\n\nReturns: `AIParser` Un nuovo parser.\n\nRestituisce un parser di stream per il formato di `provider`: `ollama`, `openai` (o `openai_chat`), `openai_responses`, `claude` (o `anthropic`), `gemini` (o `google`). Qualsiasi altro valore usa un parser generico. Scrivi i chunk grezzi con `parser.write()` e termina con `parser.end()`.\n\nExample: Analizzare uno stream di Claude\n```js\nvar parser = AIPARSER('claude');\nparser.on('content', e => process.stdout.write(e.delta));\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\nvar output = parser.end();\n```\n\n### parser.write(chunk)\n\nType: `method` · Since: `0.0.17`\n\nScrive una parte dello stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `chunk` | `Buffer|String|Object` | yes |  | Dati grezzi o un evento già analizzato. |\n\nReturns: `Object` L'output attuale, uguale a `parser.output()`.\n\nUn `Buffer`, una stringa, un `Uint8Array` o un `ArrayBuffer` viene aggiunto a un buffer interno e ogni riga completa viene analizzata: le righe vuote e `[DONE]` vengono saltate, il prefisso `data:` viene rimosso e il resto viene analizzato come JSON. Una riga che non è JSON viene ignorata. Un oggetto viene analizzato direttamente come un evento del provider. `null` restituisce solo l'output.\n\nExample: Scrivere oggetti già analizzati\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { content: 'Hel' } });\nparser.write({ message: { content: 'lo' } });\nparser.end().content; // 'Hello'\n```\n\n### parser.end()\n\nType: `method` · Since: `0.0.17`\n\nTermina lo stream.\n\nReturns: `Object` `{ content, thinking, tools, reasoning }`, più `thinking_signature` o `thought_signatures` quando il provider li invia.\n\nAnalizza il resto del buffer (un'ultima riga senza a capo), interpreta gli argomenti uniti di ogni chiamata di tool, emette `done` con `{ output }` e restituisce l'output.\n\nExample: Output finale\n```js\nvar output = parser.end();\nconsole.log(output.content);\n```\n\nExample: Chiamate di tool di uno stream di Claude\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.output()\n\nType: `method` · Since: `0.0.17`\n\nRestituisce l'output attuale.\n\nReturns: `Object` L'output fino a questo momento.\n\nRestituisce `{ content, thinking, tools, reasoning }`. `tools` è un array di `{ id, name, arguments }` con le chiamate di tool di ogni provider, dove `arguments` è il JSON analizzato degli argomenti uniti (il testo senza spazi iniziali e finali quando non è JSON valido, per esempio mentre gli argomenti stanno ancora arrivando in streaming, e `{}` quando è vuoto). `reasoning` è `tool` quando ci sono chiamate di tool, altrimenti `thinking` o `content` in base all'ultimo tipo di dati. `thinking_signature` (Claude) e `thought_signatures` (Gemini) vengono aggiunti quando presenti.\n\n### parser.on(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nAscolta un evento del parser.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il nome dell'evento. |\n| `fn` | `Function` | yes |  | `function(event)`. |\n\nReturns: `AIParser` Il parser, per il concatenamento.\n\nAggiunge `fn` per l'evento `type`: `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments`, `done`, oppure `*` per tutti gli eventi. `fn` riceve un oggetto con `type` e i dati dell'evento.\n\nExample: Tutti gli eventi\n```js\nAIPARSER('openai').on('*', function(e) {\n\tconsole.log(e.type);\n});\n```\n\n### parser.off(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nRimuove un listener.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il nome dell'evento. |\n| `fn` | `Function` | yes |  | La funzione passata a `parser.on()`. |\n\nReturns: `AIParser` Il parser, per il concatenamento.\n\nRimuove `fn` dai listener di `type`.\n\n### parser.reset()\n\nType: `method` · Since: `0.0.17`\n\nSvuota il parser.\n\nReturns: `AIParser` Il parser.\n\nSvuota il contenuto, il ragionamento, i tool, il buffer e le firme, così il parser può leggere un altro stream dello stesso provider. I listener restano.\n\n### parser.content {String}\n\nType: `property` · Since: `0.0.17`\n\nIl testo raccolto finora.\n\nReturns: `String`\n\nTutto il testo della risposta, unito a partire dai delta.\n\n### parser.thinking {String}\n\nType: `property` · Since: `0.0.17`\n\nIl ragionamento raccolto finora.\n\nReturns: `String`\n\nTutto il testo di ragionamento o di thinking inviato dal modello (per esempio `reasoning_content`, `thinking_delta` di Claude o le parti thought di Gemini).\n\n### parser.reasoning {String}\n\nType: `property` · Since: `0.0.17`\n\nCosa sta producendo ora il modello.\n\nReturns: `String`\n\n`content`, `thinking` o `tool`, in base all'ultimo tipo di dati ricevuto.\n\n### parser.tools {Array}\n\nType: `property`\n\nLe chiamate di tool raccolte finora.\n\nReturns: `Array`\n\nUn oggetto per ogni chiamata di tool, nell'ordine in cui le chiamate sono iniziate: `id` e `name` della chiamata, `arguments` (il testo degli argomenti unito dai pezzi; per i provider che inviano gli argomenti come oggetto, il suo JSON) e `input` (gli argomenti interpretati, riempiti da `parser.output()` e `parser.end()`). Usa `output.tools` di `parser.end()` per le chiamate finali con gli argomenti interpretati.\n\nExample: Argomenti grezzi e interpretati\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { role: 'assistant', content: '', tool_calls: [{ function: { name: 'weather', arguments: { city: 'Bratislava' } } }] } });\nconsole.log(parser.tools[0].name);      // 'weather'\nconsole.log(parser.tools[0].arguments); // '{\"city\":\"Bratislava\"}'\nconsole.log(parser.end().tools[0].arguments); // { city: 'Bratislava' }\n```\n\n### parser.on('content', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNuovo testo della risposta.\n\n`e.delta` è il nuovo testo ed `e.content` tutto il testo finora.\n\n### parser.on('thinking', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNuovo testo di ragionamento.\n\n`e.delta` è il nuovo testo ed `e.thinking` tutto il ragionamento finora.\n\n### parser.on('tool_start', function(e) {})\n\nType: `event`\n\nCompare una nuova chiamata di tool.\n\n`e.tool` è `{ id, name, arguments }` della nuova chiamata; `arguments` a questo punto è di solito `{}`. `e.reasoning` è `tool`.\n\nExample: Registrare le chiamate\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_start', function(e) {\n\tconsole.log('The model calls', e.tool.name, e.tool.id);\n});\n```\n\n### parser.on('tool_update', function(e) {})\n\nType: `event`\n\nAltri dati di una chiamata di tool nota.\n\nEmesso quando lo stream invia altri dati per una chiamata già iniziata, prima di ogni ulteriore pezzo dei suoi argomenti. `e.tool` è `{ id, name, arguments }` con gli argomenti interpretati fino a quel momento: un oggetto quando il testo unito è JSON valido, altrimenti il testo ripulito dagli spazi.\n\nExample: Osservare gli argomenti che crescono\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_update', function(e) {\n\tconsole.log(e.tool.id, e.tool.arguments);\n});\n```\n\n### parser.on('tool_arguments', function(e) {})\n\nType: `event`\n\nUn pezzo degli argomenti di una chiamata di tool.\n\n`e.delta` è il nuovo pezzo e `e.arguments` tutto il testo degli argomenti della chiamata fino a quel momento. Per i provider che inviano gli argomenti interi come oggetto (Ollama, Gemini), entrambi sono quell'oggetto. `e.tool` è `{ id, name, arguments }` con gli argomenti interpretati fino a quel momento.\n\nExample: Argomenti di uno stream di Claude\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.on('done', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nLo stream è terminato.\n\nEmesso da `parser.end()`. `e.output` è l'output finale.\n","entries":[{"type":"method","name":"NEWAIMODEL()","signature":"NEWAIMODEL(name, [config], handler)","since":"0.0.16","deprecated":false},{"type":"delegate","name":"handler(ai, callback)","signature":"function(ai, callback)","since":"0.0.16","deprecated":false},{"type":"method","name":"AIMODEL()","signature":"AIMODEL(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.system()","signature":"ai.system(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.user()","signature":"ai.user(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.assistant()","signature":"ai.assistant(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.message()","signature":"ai.message(role, content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.prompt()","signature":"ai.prompt(content)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.think()","signature":"ai.think()","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.configure()","signature":"ai.configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.callback()","signature":"ai.callback(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.stream()","signature":"ai.stream(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.promise()","signature":"ai.promise([$])","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.payload","signature":"ai.payload {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.config","signature":"ai.config {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.options","signature":"ai.options {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"F.aimodels","signature":"F.aimodels {Object}","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.tool()","signature":"ai.tool(content)","since":"0.0.17","deprecated":false},{"type":"method","name":"AIPARSER()","signature":"AIPARSER(provider)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.write()","signature":"parser.write(chunk)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.end()","signature":"parser.end()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.output()","signature":"parser.output()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.on()","signature":"parser.on(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.off()","signature":"parser.off(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.reset()","signature":"parser.reset()","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.content","signature":"parser.content {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.thinking","signature":"parser.thinking {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.reasoning","signature":"parser.reasoning {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.tools","signature":"parser.tools {Array}","since":"","deprecated":false},{"type":"event","name":"content","signature":"parser.on('content', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"thinking","signature":"parser.on('thinking', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"tool_start","signature":"parser.on('tool_start', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_update","signature":"parser.on('tool_update', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_arguments","signature":"parser.on('tool_arguments', function(e) {})","since":"","deprecated":false},{"type":"event","name":"done","signature":"parser.on('done', function(e) {})","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwSk45x60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/ai-models/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"AI modely","summary":"NEWAIMODEL(), AIMODEL(), metódy a vlastnosti požiadavky a parser AI streamu.","markdown":"---\ntitle: AI modely\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/ai-models/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# AI modely\n\n> NEWAIMODEL(), AIMODEL(), metódy a vlastnosti požiadavky a parser AI streamu.\n\nTáto stránka uvádza globálne funkcie pre AI modely, metódy a vlastnosti objektu požiadavky `AIMODEL()`, handler modelu a, ak sú k dispozícii, parser streamu a jeho udalosti. Návod [AI modely](../../guides/ai-models/) vysvetľuje, ako spolupracujú, s kompletným handlerom.\n\n## API\n\n### NEWAIMODEL(name, [config], handler)\n\nType: `method` · Since: `0.0.16`\n\nRegistruje handler pre jeden alebo viac AI modelov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov modelu alebo viac názvov oddelených čiarkami. |\n| `config` | `Object` | no |  | Predvolená konfigurácia (URL, token, nastavenia) kopírovaná do `ai.config` každej požiadavky. |\n| `handler` | `Function` | yes |  | `function(ai, callback)`. Zavolá poskytovateľa a skončí cez `callback(err, response)`. |\n\nReturns: `undefined`\n\nUloží `handler` s `config` do `F.aimodels` pod každým názvom z `name` (názvy oddelené čiarkami sa orežú). Znova zaregistrovaný názov nahradí predchádzajúci handler. Handler volá každá požiadavka `AIMODEL()` s týmto názvom. Pred jeho spustením sa do `ai.config` skopíruje každý kľúč `config`, ktorý požiadavka nenastavila cez `ai.configure()`. Keď je druhý argument funkcia, je to handler a konfigurácia nie je.\n\nExample: Model Ollama\n```js\nNEWAIMODEL('llama3', { url: 'http://localhost:11434/api/chat' }, function(ai, callback) {\n\tvar opt = {};\n\topt.method = 'POST';\n\topt.headers = { 'Content-Type': 'application/json' };\n\topt.body = JSON.stringify({ model: ai.payload.model, messages: ai.payload.messages, stream: false });\n\tfetch(ai.config.url, opt).then(res => res.json()).then(function(json) {\n\t\tcallback(null, json.message.content);\n\t}).catch(callback);\n});\n```\n\n### function(ai, callback)\n\nType: `delegate` · Since: `0.0.16`\n\nHandler modelu odovzdaný do NEWAIMODEL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ai` | `AIModel` | yes |  | Požiadavka. |\n| `callback` | `Function` | yes |  | `function(err, response)`, ktorá ukončí požiadavku. |\n\nVolá sa raz za požiadavku, keď sa požiadavka spustí. `ai` je objekt požiadavky z `AIMODEL()`: čítaj `ai.payload` pre dáta na odoslanie, `ai.config` pre nastavenia (s už použitými predvolenými hodnotami z `NEWAIMODEL()`) a `ai.options.stream` pre stream funkciu volajúceho. Zavolaj `ai.options.stream(piece)` pre každú časť streamovanej odpovede, potom raz `callback(err, response)`. `response` sa dostane k volajúcemu nezmenená.\n\nExample: Echo handler pre testy\n```js\nNEWAIMODEL('echo', function(ai, callback) {\n\tvar last = ai.payload.messages[ai.payload.messages.length - 1];\n\tai.options.stream && ai.options.stream(last.content);\n\tcallback(null, last.content);\n});\n```\n\n### AIMODEL(name)\n\nType: `method` · Since: `0.0.16`\n\nVytvorí požiadavku pre zaregistrovaný AI model.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov použitý v `NEWAIMODEL()`. Ukladá sa aj ako `payload.model`. |\n\nReturns: `AIModel` Nová požiadavka.\n\nVráti nový objekt požiadavky. Pridaj správy a nastavenia jeho metódami, potom ho spusti cez `callback()`, `stream()` alebo `promise()`. Požiadavka vyhľadá model, keď sa spustí; keď nie je zaregistrovaný žiadny model s daným názvom, callback dostane chybu `'AI model not found.'`.\n\nExample: Jednoduchá otázka\n```js\nAIMODEL('assistant').user('What is 2 + 2?').callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### ai.system(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nPridá systémovú správu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Text alebo objekt, ktorého kľúče sa skopírujú do správy. |\n| `merge` | `String` | no |  | Oddeľovač. Keď je nastavený a systémová správa existuje, obsah sa k nej pripojí. |\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nTo isté ako `ai.message('system', content, merge)`. Použi to na inštrukcie modelu.\n\nExample: Inštrukcie\n```js\nAIMODEL('assistant').system('Answer in one sentence.').user('What is Node.js?').callback(console.log);\n```\n\n### ai.user(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nPridá správu používateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Text alebo objekt, ktorého kľúče sa skopírujú do správy. |\n| `merge` | `String` | no |  | Oddeľovač. Keď je nastavený a správa používateľa existuje, obsah sa k nej pripojí. |\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nTo isté ako `ai.message('user', content, merge)`.\n\nExample: Správa s obrázkom\n```js\nAIMODEL('vision').user({ content: 'What is in this picture?', images: [base64] }).callback(console.log);\n```\n\n### ai.assistant(content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nPridá správu asistenta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|Object` | yes |  | Text alebo objekt, ktorého kľúče sa skopírujú do správy. |\n| `merge` | `String` | no |  | Oddeľovač. Keď je nastavený a správa asistenta existuje, obsah sa k nej pripojí. |\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nTo isté ako `ai.message('assistant', content, merge)`. Použi to na zopakovanie skorších odpovedí modelu v konverzácii.\n\nExample: História konverzácie\n```js\nvar ai = AIMODEL('assistant');\nfor (var item of history) {\n\tif (item.fromuser)\n\t\tai.user(item.text);\n\telse\n\t\tai.assistant(item.text);\n}\nai.user(question).callback(console.log);\n```\n\n### ai.message(role, content, [merge])\n\nType: `method` · Since: `0.0.16`\n\nPridá správu s ľubovoľnou rolou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `role` | `String` | yes |  | Rola, napr. `system`, `user`, `assistant` alebo `tool`. |\n| `content` | `String|Object` | yes |  | Text alebo objekt, ktorého kľúče sa skopírujú do správy. |\n| `merge` | `String` | no |  | Reťazec oddeľovača, ktorý zapne zlučovanie. |\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nVloží `{ role, content }` do `ai.payload.messages`. Keď je `content` objekt, do správy sa namiesto `content` skopírujú jeho kľúče. Keď je nastavené `merge` a správa s rovnakou rolou existuje, nič sa nepridá: reťazec sa pripojí k obsahu prvej takej správy s `merge` medzi nimi a kľúče objektu sa do nej skopírujú.\n\nExample: Zlúčené inštrukcie\n```js\nAIMODEL('assistant')\n\t.message('system', 'You are a translator.')\n\t.message('system', 'Translate to German.', '\\n')\n\t.user('Good morning')\n\t.callback(console.log);\n```\n\n### ai.prompt(content)\n\nType: `method` · Since: `0.0.16`\n\nNastaví jeden prompt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String` | yes |  | Prompt. |\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nNastaví `ai.payload.prompt`. Užitočné pre handlery endpointov, ktoré prijímajú jeden prompt namiesto zoznamu správ (napríklad endpoint `/api/generate` v Ollama). Handler rozhodne, ako ho použije.\n\nExample: Prompt\n```js\nAIMODEL('generator').prompt('Write a slogan for a bakery').callback(console.log);\n```\n\n### ai.think()\n\nType: `method` · Since: `0.0.16`\n\nPožiada o režim premýšľania.\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nNastaví `ai.payload.think = true`. Handler to namapuje na voľbu poskytovateľa (napríklad `think` v Ollama).\n\nExample: Premýšľanie\n```js\nAIMODEL('reasoner').think().user('Is 1001 a prime number?').callback(console.log);\n```\n\n### ai.configure(obj)\n\nType: `method` · Since: `0.0.16`\n\nNastaví konfiguráciu požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Kľúče na nastavenie. |\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nSkopíruje kľúče `obj` do `ai.config`. Tieto hodnoty majú prednosť pred predvolenými hodnotami z `NEWAIMODEL()`, ktoré doplnia iba nenastavené kľúče.\n\nExample: Teplota pre jednu požiadavku\n```js\nAIMODEL('assistant').configure({ temperature: 0 }).user('List three colors').callback(console.log);\n```\n\n### ai.callback(fn)\n\nType: `method` · Since: `0.0.16`\n\nNastaví callback a spustí požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nUloží `fn` a spustí požiadavku v ďalšom kole event loopu. Opätovné zavolanie `callback()`, `stream()` alebo `promise()` v tom istom kole presunie spustenie, takže handler sa zavolá iba raz.\n\nExample: Callback\n```js\nAIMODEL('assistant').user('Hello').callback(function(err, response) {\n\terr && console.log(err);\n});\n```\n\n### ai.stream(fn)\n\nType: `method` · Since: `0.0.16`\n\nNastaví stream funkciu a spustí požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Handler ju volá s každou časťou odpovede. |\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nUloží `fn` do `ai.options.stream` a spustí požiadavku v ďalšom kole event loopu. Handler volá `fn` s časťami odpovede; čo je časť (text, objekt), určuje handler. Pridaj `callback()`, aby si vedel, kedy odpoveď skončí.\n\nExample: Stream do konzoly\n```js\nAIMODEL('assistant').user('Tell a story').stream(function(text) {\n\tprocess.stdout.write(text);\n}).callback(function(err) {\n\tconsole.log('end', err);\n});\n```\n\n### ai.promise([$])\n\nType: `method` · Since: `0.0.16`\n\nSpustí požiadavku a vráti Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | `$` akcie alebo kontroléra na hlásenie chýb cez `$.invalid()`. |\n\nReturns: `Promise` Splní sa s odpoveďou handlera.\n\nSpustí požiadavku cez `callback()`. Promise sa splní s odpoveďou. Chyba ho zamietne s `Error`; keď sa odovzdá `$` s `$.invalid()`, chyba ide namiesto toho do `$.invalid(err)` a promise zostane čakať.\n\nExample: V akcii\n```js\nNEWACTION('Assistant/ask', {\n\tinput: '*question:String',\n\taction: async function($, model) {\n\t\tvar answer = await AIMODEL('assistant').user(model.question).promise($);\n\t\t$.callback({ answer: answer });\n\t}\n});\n```\n\n### ai.payload {Object}\n\nType: `property` · Since: `0.0.16`\n\nDáta požiadavky pre poskytovateľa.\n\nReturns: `Object`\n\nObsahuje `model` (názov odovzdaný do `AIMODEL()`), `messages` (pole objektov správ) a `tools` (pole definícií nástrojov, predvolene prázdne), plus `prompt` a `think`, ak sú nastavené. Handler ho číta, aby zostavil telo požiadavky na poskytovateľa.\n\nExample: Čítanie payloadu\n```js\nNEWAIMODEL('debug', function(ai, callback) {\n\tcallback(null, JSON.stringify(ai.payload));\n});\n```\n\n### ai.config {Object}\n\nType: `property` · Since: `0.0.16`\n\nKonfigurácia požiadavky.\n\nReturns: `Object`\n\nKľúče nastavené cez `ai.configure()`, doplnené o predvolené hodnoty z `NEWAIMODEL()` tesne pred spustením handlera.\n\n### ai.options {Object}\n\nType: `property` · Since: `0.0.16`\n\nMožnosti spustenia požiadavky.\n\nReturns: `Object`\n\nObsahuje `callback` (funkcia nastavená cez `callback()` alebo `promise()`, predvolene `NOOP`) a `stream` (funkcia nastavená cez `stream()`, alebo undefined). Handler kontroluje `ai.options.stream`, aby vedel, či volajúci chce stream.\n\nExample: Kontrola streamovania\n```js\nif (ai.options.stream)\n\tbody.stream = true;\n```\n\n### F.aimodels {Object}\n\nType: `property` · Since: `0.0.16`\n\nZaregistrované AI modely.\n\nReturns: `Object`\n\nObjekt s názvami modelov ako kľúčmi a `{ config, callback }` ako hodnotami, plnený cez `NEWAIMODEL()`.\n\nExample: Je model zaregistrovaný?\n```js\nif (F.aimodels.assistant)\n\tconsole.log('ready');\n```\n\n### ai.tool(content)\n\nType: `method` · Since: `0.0.17`\n\nPridá definíciu nástroja.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `Object` | yes |  | Definícia nástroja. |\n\nReturns: `AIModel` Tá istá požiadavka na reťazenie.\n\nPridá `content` do `ai.payload.tools`. Framework ho nemení ani nekontroluje; handler pošle nástroje poskytovateľovi v jeho formáte. `schema.toAITool(name)` inline schémy vráti bežný formát funkcie.\n\nExample: Nástroj zo schémy\n```js\nNEWSCHEMA('@Task', '*name:String // The name of the task,due:Date');\n\nAIMODEL('assistant')\n\t.user('Create a task: call Peter tomorrow')\n\t.tool(F.jsonschemas.Task.toAITool('create_task'))\n\t.callback(console.log);\n```\n\n### AIPARSER(provider)\n\nType: `method` · Since: `0.0.17`\n\nVytvorí parser pre streamované AI odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `provider` | `String` | no | `generic` | Formát streamu. |\n\nReturns: `AIParser` Nový parser.\n\nVráti stream parser pre formát `provider`: `ollama`, `openai` (alebo `openai_chat`), `openai_responses`, `claude` (alebo `anthropic`), `gemini` (alebo `google`). Akákoľvek iná hodnota použije všeobecný parser. Surové časti zapisuj cez `parser.write()` a ukonči cez `parser.end()`.\n\nExample: Parsovanie streamu Claude\n```js\nvar parser = AIPARSER('claude');\nparser.on('content', e => process.stdout.write(e.delta));\nfor await (var chunk of res.body)\n\tparser.write(Buffer.from(chunk));\nvar output = parser.end();\n```\n\n### parser.write(chunk)\n\nType: `method` · Since: `0.0.17`\n\nZapíše časť streamu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `chunk` | `Buffer|String|Object` | yes |  | Surové dáta alebo sparsovaná udalosť. |\n\nReturns: `Object` Aktuálny výstup, rovnaký ako `parser.output()`.\n\n`Buffer`, reťazec, `Uint8Array` alebo `ArrayBuffer` sa pridá do interného buffera a každý úplný riadok sa sparsuje: prázdne riadky a `[DONE]` sa preskočia, prefix `data:` sa odstráni a zvyšok sa sparsuje ako JSON. Riadok, ktorý nie je JSON, sa ignoruje. Objekt sa sparsuje priamo ako jedna udalosť poskytovateľa. `null` iba vráti výstup.\n\nExample: Zápis sparsovaných objektov\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { content: 'Hel' } });\nparser.write({ message: { content: 'lo' } });\nparser.end().content; // 'Hello'\n```\n\n### parser.end()\n\nType: `method` · Since: `0.0.17`\n\nUkončí stream.\n\nReturns: `Object` `{ content, thinking, tools, reasoning }`, plus `thinking_signature` alebo `thought_signatures`, keď ich poskytovateľ pošle.\n\nSparsuje zvyšok buffera (posledný riadok bez nového riadku), sparsuje spojené argumenty každého volania nástroja, vyšle `done` s `{ output }` a vráti výstup.\n\nExample: Konečný výstup\n```js\nvar output = parser.end();\nconsole.log(output.content);\n```\n\nExample: Volania nástrojov zo streamu Claude\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.output()\n\nType: `method` · Since: `0.0.17`\n\nVráti aktuálny výstup.\n\nReturns: `Object` Doterajší výstup.\n\nVráti `{ content, thinking, tools, reasoning }`. `tools` je pole `{ id, name, arguments }` s volaniami nástrojov každého poskytovateľa, kde `arguments` je sparsovaný JSON spojených argumentov (orezaný text, keď nie je platný JSON, napríklad kým sa argumenty ešte streamujú, a `{}`, keď je prázdny). `reasoning` je `tool`, keď existujú volania nástrojov, inak `thinking` alebo `content` podľa posledného druhu dát. `thinking_signature` (Claude) a `thought_signatures` (Gemini) sa pridajú, ak sú prítomné.\n\n### parser.on(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nPočúva udalosť parsera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Názov udalosti. |\n| `fn` | `Function` | yes |  | `function(event)`. |\n\nReturns: `AIParser` Parser, na reťazenie.\n\nPridá `fn` pre udalosť `type`: `content`, `thinking`, `tool_start`, `tool_update`, `tool_arguments`, `done` alebo `*` pre všetky udalosti. `fn` dostane objekt s `type` a dátami udalosti.\n\nExample: Všetky udalosti\n```js\nAIPARSER('openai').on('*', function(e) {\n\tconsole.log(e.type);\n});\n```\n\n### parser.off(type, fn)\n\nType: `method` · Since: `0.0.17`\n\nOdstráni listener.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Názov udalosti. |\n| `fn` | `Function` | yes |  | Funkcia odovzdaná do `parser.on()`. |\n\nReturns: `AIParser` Parser, na reťazenie.\n\nOdstráni `fn` z listenerov udalosti `type`.\n\n### parser.reset()\n\nType: `method` · Since: `0.0.17`\n\nVyčistí parser.\n\nReturns: `AIParser` Parser.\n\nVyčistí obsah, uvažovanie, nástroje, buffer a podpisy, takže parser môže čítať ďalší stream toho istého poskytovateľa. Listenery zostanú.\n\n### parser.content {String}\n\nType: `property` · Since: `0.0.17`\n\nDoteraz zozbieraný text.\n\nReturns: `String`\n\nCelý text odpovede, spojený z delt.\n\n### parser.thinking {String}\n\nType: `property` · Since: `0.0.17`\n\nDoteraz zozbierané uvažovanie.\n\nReturns: `String`\n\nCelý text uvažovania (reasoning alebo thinking), ktorý model poslal (napríklad `reasoning_content`, `thinking_delta` od Claude alebo časti thought od Gemini).\n\n### parser.reasoning {String}\n\nType: `property` · Since: `0.0.17`\n\nČo model práve produkuje.\n\nReturns: `String`\n\n`content`, `thinking` alebo `tool` podľa posledného druhu prijatých dát.\n\n### parser.tools {Array}\n\nType: `property`\n\nDoteraz zozbierané volania nástrojov.\n\nReturns: `Array`\n\nJeden objekt pre každé volanie nástroja, v poradí, v akom volania začali: `id` a `name` volania, `arguments` (text argumentov spojený z kúskov; pri poskytovateľoch, ktorí posielajú argumenty ako objekt, jeho JSON) a `input` (sparsované argumenty, vyplní ich `parser.output()` a `parser.end()`). Pre konečné volania so sparsovanými argumentmi použi `output.tools` z `parser.end()`.\n\nExample: Surové a sparsované argumenty\n```js\nvar parser = AIPARSER('ollama');\nparser.write({ message: { role: 'assistant', content: '', tool_calls: [{ function: { name: 'weather', arguments: { city: 'Bratislava' } } }] } });\nconsole.log(parser.tools[0].name);      // 'weather'\nconsole.log(parser.tools[0].arguments); // '{\"city\":\"Bratislava\"}'\nconsole.log(parser.end().tools[0].arguments); // { city: 'Bratislava' }\n```\n\n### parser.on('content', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNový text odpovede.\n\n`e.delta` je nový text a `e.content` celý doterajší text.\n\n### parser.on('thinking', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nNový text uvažovania.\n\n`e.delta` je nový text a `e.thinking` celé doterajšie uvažovanie.\n\n### parser.on('tool_start', function(e) {})\n\nType: `event`\n\nObjaví sa nové volanie nástroja.\n\n`e.tool` je `{ id, name, arguments }` nového volania; `arguments` je v tejto chvíli zvyčajne `{}`. `e.reasoning` je `tool`.\n\nExample: Logovanie volaní\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_start', function(e) {\n\tconsole.log('The model calls', e.tool.name, e.tool.id);\n});\n```\n\n### parser.on('tool_update', function(e) {})\n\nType: `event`\n\nĎalšie dáta známeho volania nástroja.\n\nVysiela sa, keď stream pošle ďalšie dáta pre volanie, ktoré už začalo, pred každým ďalším kúskom jeho argumentov. `e.tool` je `{ id, name, arguments }` s doteraz sparsovanými argumentmi: objekt, keď je spojený text platný JSON, inak orezaný text.\n\nExample: Sledovanie, ako argumenty rastú\n```js\nvar parser = AIPARSER('openai');\nparser.on('tool_update', function(e) {\n\tconsole.log(e.tool.id, e.tool.arguments);\n});\n```\n\n### parser.on('tool_arguments', function(e) {})\n\nType: `event`\n\nKúsok argumentov volania nástroja.\n\n`e.delta` je nový kúsok a `e.arguments` celý doterajší text argumentov volania. Pri poskytovateľoch, ktorí posielajú argumenty celé ako objekt (Ollama, Gemini), sú obe tento objekt. `e.tool` je `{ id, name, arguments }` s doteraz sparsovanými argumentmi.\n\nExample: Argumenty zo streamu Claude\n```js\nvar parser = AIPARSER('claude');\n\nparser.on('tool_arguments', function(e) {\n\tconsole.log(e.tool.name, e.delta);\n});\n\n// recorded events of an Anthropic Messages stream\nparser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{\"city\": \"Bra' } });\nparser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava\"}' } });\nparser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });\n\nvar output = parser.end();\n// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]\n```\n\n### parser.on('done', function(e) {})\n\nType: `event` · Since: `0.0.17`\n\nStream skončil.\n\nVysiela ju `parser.end()`. `e.output` je konečný výstup.\n","entries":[{"type":"method","name":"NEWAIMODEL()","signature":"NEWAIMODEL(name, [config], handler)","since":"0.0.16","deprecated":false},{"type":"delegate","name":"handler(ai, callback)","signature":"function(ai, callback)","since":"0.0.16","deprecated":false},{"type":"method","name":"AIMODEL()","signature":"AIMODEL(name)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.system()","signature":"ai.system(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.user()","signature":"ai.user(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.assistant()","signature":"ai.assistant(content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.message()","signature":"ai.message(role, content, [merge])","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.prompt()","signature":"ai.prompt(content)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.think()","signature":"ai.think()","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.configure()","signature":"ai.configure(obj)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.callback()","signature":"ai.callback(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.stream()","signature":"ai.stream(fn)","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.promise()","signature":"ai.promise([$])","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.payload","signature":"ai.payload {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.config","signature":"ai.config {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"ai.options","signature":"ai.options {Object}","since":"0.0.16","deprecated":false},{"type":"property","name":"F.aimodels","signature":"F.aimodels {Object}","since":"0.0.16","deprecated":false},{"type":"method","name":"ai.tool()","signature":"ai.tool(content)","since":"0.0.17","deprecated":false},{"type":"method","name":"AIPARSER()","signature":"AIPARSER(provider)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.write()","signature":"parser.write(chunk)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.end()","signature":"parser.end()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.output()","signature":"parser.output()","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.on()","signature":"parser.on(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.off()","signature":"parser.off(type, fn)","since":"0.0.17","deprecated":false},{"type":"method","name":"parser.reset()","signature":"parser.reset()","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.content","signature":"parser.content {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.thinking","signature":"parser.thinking {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.reasoning","signature":"parser.reasoning {String}","since":"0.0.17","deprecated":false},{"type":"property","name":"parser.tools","signature":"parser.tools {Array}","since":"","deprecated":false},{"type":"event","name":"content","signature":"parser.on('content', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"thinking","signature":"parser.on('thinking', function(e) {})","since":"0.0.17","deprecated":false},{"type":"event","name":"tool_start","signature":"parser.on('tool_start', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_update","signature":"parser.on('tool_update', function(e) {})","since":"","deprecated":false},{"type":"event","name":"tool_arguments","signature":"parser.on('tool_arguments', function(e) {})","since":"","deprecated":false},{"type":"event","name":"done","signature":"parser.on('done', function(e) {})","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwweDgx61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/proxy/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Proxy","summary":"PROXYSERVER() and PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/proxy/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Proxy\n\n> PROXYSERVER() and PROXYCLIENT().\n\n## API\n\n### PROXYSERVER([endpoint], [socketendpoint], [logger])\n\nType: `method` · Since: `0.0.17`\n\nForwards HTTP requests to a proxy client connected over a WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | no | `'/'` | Path prefix of the requests to forward. |\n| `socketendpoint` | `String` | no | `'/'` | Path of the WebSocket route for the client. |\n| `logger` | `Function` | no | `console with a date` | Called as `logger(status, message)` when the client connects or disconnects. |\n\nRegisters `PROXY(endpoint)` for all requests except WebSocket ones and a binary WebSocket route at `socketendpoint` (messages up to 100 MB) for the client started with `PROXYCLIENT()`. Each request is sent to the client with its method, URL, headers, IP and body, and the response of the client is streamed back.\n\nOnly one client can be connected; a second one closes the first with code `4001` and is not used, so connect the client again. Without a client, requests get `400` with `Not yet available.`. Choose a `socketendpoint` that does not collide with your routes. When the request to the local app fails (the app does not run or closes the connection), the visitor gets an empty response with the status `200`.\n\nExample: Public server\n```js\nexports.install = function() {\n\tPROXYSERVER('/', '/$proxy/');\n};\n```\n\n### PROXYCLIENT(proxyserver, target, [logger])\n\nType: `method` · Since: `0.0.17`\n\nConnects a local HTTP server to a `PROXYSERVER()` and answers its requests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `proxyserver` | `String` | yes |  | URL of the WebSocket endpoint of `PROXYSERVER()`. |\n| `target` | `String` | yes |  | Local server as `'ip:port'` or `'port'`. |\n| `logger` | `Function` | no | `console with a date` | Called with the status and a message on connect, disconnect and each request. |\n\nReturns: `WebSocketClient` The client connection.\n\nOpens a binary WebSocket to `proxyserver` (an `http`/`https` URL is changed to `ws`/`wss`). Every request that arrives is made against the local server `target` with the original method, path, headers and body, plus the header `x-proxy: Total.js` and the `host` of the target. The response is streamed back.\n\n`target` is `'ip:port'` or only a port (then `127.0.0.1` is used). The function returns the WebSocket client; it returns nothing and prints its usage when an argument is missing.\n\nExample: Publish a local app\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '8000');\n```\n\nExample: Quiet\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '192.168.1.10:8000', NOOP);\n```\n","entries":[{"type":"method","name":"PROXYSERVER()","signature":"PROXYSERVER([endpoint], [socketendpoint], [logger])","since":"0.0.17","deprecated":false},{"type":"method","name":"PROXYCLIENT()","signature":"PROXYCLIENT(proxyserver, target, [logger])","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwweDgx61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/proxy/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Proxy","summary":"PROXYSERVER() und PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/proxy/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Proxy\n\n> PROXYSERVER() und PROXYCLIENT().\n\n## API\n\n### PROXYSERVER([endpoint], [socketendpoint], [logger])\n\nType: `method` · Since: `0.0.17`\n\nLeitet HTTP-Anfragen an einen Proxy-Client weiter, der über einen WebSocket verbunden ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | no | `'/'` | Pfadpräfix der weiterzuleitenden Anfragen. |\n| `socketendpoint` | `String` | no | `'/'` | Pfad der WebSocket-Route für den Client. |\n| `logger` | `Function` | no | `console with a date` | Wird als `logger(status, message)` aufgerufen, wenn sich der Client verbindet oder trennt. |\n\nRegistriert `PROXY(endpoint)` für alle Anfragen außer WebSocket-Anfragen und eine binäre WebSocket-Route unter `socketendpoint` (Nachrichten bis 100 MB) für den mit `PROXYCLIENT()` gestarteten Client. Jede Anfrage wird mit ihrer Methode, URL, ihren Headern, ihrer IP und ihrem Body an den Client gesendet, und die Antwort des Clients wird zurückgestreamt.\n\nEs kann nur ein Client verbunden sein; ein zweiter schließt den ersten mit dem Code `4001` und wird nicht verwendet, verbinde den Client also erneut. Ohne Client erhalten Anfragen `400` mit `Not yet available.`. Wähle einen `socketendpoint`, der nicht mit deinen Routen kollidiert. Wenn die Anfrage an die lokale Anwendung fehlschlägt (die Anwendung läuft nicht oder schließt die Verbindung), erhält der Besucher eine leere Antwort mit dem Status `200`.\n\nExample: Öffentlicher Server\n```js\nexports.install = function() {\n\tPROXYSERVER('/', '/$proxy/');\n};\n```\n\n### PROXYCLIENT(proxyserver, target, [logger])\n\nType: `method` · Since: `0.0.17`\n\nVerbindet einen lokalen HTTP-Server mit einem `PROXYSERVER()` und beantwortet dessen Anfragen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `proxyserver` | `String` | yes |  | URL des WebSocket-Endpunkts von `PROXYSERVER()`. |\n| `target` | `String` | yes |  | Lokaler Server als `'ip:port'` oder `'port'`. |\n| `logger` | `Function` | no | `console with a date` | Wird beim Verbinden, beim Trennen und bei jeder Anfrage mit dem Status und einer Nachricht aufgerufen. |\n\nReturns: `WebSocketClient` Die Client-Verbindung.\n\nÖffnet einen binären WebSocket zu `proxyserver` (eine `http`/`https`-URL wird zu `ws`/`wss` geändert). Jede eintreffende Anfrage wird gegen den lokalen Server `target` gestellt, mit der ursprünglichen Methode, dem Pfad, den Headern und dem Body, dazu dem Header `x-proxy: Total.js` und dem `host` des Ziels. Die Antwort wird zurückgestreamt.\n\n`target` ist `'ip:port'` oder nur ein Port (dann wird `127.0.0.1` verwendet). Die Funktion gibt den WebSocket-Client zurück; fehlt ein Argument, gibt sie nichts zurück und gibt ihre Verwendung aus.\n\nExample: Eine lokale Anwendung veröffentlichen\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '8000');\n```\n\nExample: Ohne Ausgabe\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '192.168.1.10:8000', NOOP);\n```\n","entries":[{"type":"method","name":"PROXYSERVER()","signature":"PROXYSERVER([endpoint], [socketendpoint], [logger])","since":"0.0.17","deprecated":false},{"type":"method","name":"PROXYCLIENT()","signature":"PROXYCLIENT(proxyserver, target, [logger])","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwweDgx61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/proxy/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Proxy","summary":"PROXYSERVER() y PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/proxy/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Proxy\n\n> PROXYSERVER() y PROXYCLIENT().\n\n## API\n\n### PROXYSERVER([endpoint], [socketendpoint], [logger])\n\nType: `method` · Since: `0.0.17`\n\nReenvía peticiones HTTP a un cliente proxy conectado mediante un WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | no | `'/'` | Prefijo de ruta de las peticiones que se reenvían. |\n| `socketendpoint` | `String` | no | `'/'` | Ruta de la ruta WebSocket para el cliente. |\n| `logger` | `Function` | no | `console with a date` | Se llama como `logger(status, message)` cuando el cliente se conecta o se desconecta. |\n\nRegistra `PROXY(endpoint)` para todas las peticiones excepto las de WebSocket y una ruta WebSocket binaria en `socketendpoint` (mensajes de hasta 100 MB) para el cliente iniciado con `PROXYCLIENT()`. Cada petición se envía al cliente con su método, URL, cabeceras, IP y cuerpo, y la respuesta del cliente se transmite de vuelta.\n\nSolo puede haber un cliente conectado; un segundo cliente cierra el primero con el código `4001` y no se usa, así que vuelve a conectar el cliente. Sin cliente, las peticiones reciben `400` con `Not yet available.`. Elige un `socketendpoint` que no choque con tus rutas. Cuando la petición a la aplicación local falla (la aplicación no se está ejecutando o cierra la conexión), el visitante recibe una respuesta vacía con el estado `200`.\n\nExample: Servidor público\n```js\nexports.install = function() {\n\tPROXYSERVER('/', '/$proxy/');\n};\n```\n\n### PROXYCLIENT(proxyserver, target, [logger])\n\nType: `method` · Since: `0.0.17`\n\nConecta un servidor HTTP local a un `PROXYSERVER()` y responde a sus peticiones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `proxyserver` | `String` | yes |  | URL del endpoint WebSocket de `PROXYSERVER()`. |\n| `target` | `String` | yes |  | Servidor local como `'ip:port'` o `'port'`. |\n| `logger` | `Function` | no | `console with a date` | Se llama con el estado y un mensaje al conectar, al desconectar y en cada petición. |\n\nReturns: `WebSocketClient` La conexión del cliente.\n\nAbre un WebSocket binario hacia `proxyserver` (una URL `http`/`https` se cambia a `ws`/`wss`). Cada petición que llega se realiza contra el servidor local `target` con el método, la ruta, las cabeceras y el cuerpo originales, más la cabecera `x-proxy: Total.js` y el `host` del destino. La respuesta se devuelve en streaming.\n\n`target` es `'ip:port'` o solo un puerto (entonces se usa `127.0.0.1`). La función devuelve el cliente WebSocket; no devuelve nada e imprime su uso cuando falta un argumento.\n\nExample: Publicar una aplicación local\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '8000');\n```\n\nExample: Silencioso\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '192.168.1.10:8000', NOOP);\n```\n","entries":[{"type":"method","name":"PROXYSERVER()","signature":"PROXYSERVER([endpoint], [socketendpoint], [logger])","since":"0.0.17","deprecated":false},{"type":"method","name":"PROXYCLIENT()","signature":"PROXYCLIENT(proxyserver, target, [logger])","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwweDgx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/proxy/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Proxy","summary":"PROXYSERVER() et PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/proxy/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Proxy\n\n> PROXYSERVER() et PROXYCLIENT().\n\n## API\n\n### PROXYSERVER([endpoint], [socketendpoint], [logger])\n\nType: `method` · Since: `0.0.17`\n\nTransmet les requêtes HTTP à un client proxy connecté par un WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | no | `'/'` | Préfixe de chemin des requêtes à transférer. |\n| `socketendpoint` | `String` | no | `'/'` | Chemin de la route WebSocket pour le client. |\n| `logger` | `Function` | no | `console with a date` | Appelé sous la forme `logger(status, message)` lorsque le client se connecte ou se déconnecte. |\n\nEnregistre `PROXY(endpoint)` pour toutes les requêtes sauf les WebSocket, et une route WebSocket binaire sur `socketendpoint` (messages jusqu'à 100 MB) pour le client démarré avec `PROXYCLIENT()`. Chaque requête est envoyée au client avec sa méthode, son URL, ses en-têtes, son IP et son corps, et la réponse du client est renvoyée en streaming.\n\nUn seul client peut être connecté ; un deuxième ferme le premier avec le code `4001` et n'est pas utilisé : reconnecte donc le client. Sans client, les requêtes reçoivent `400` avec `Not yet available.`. Choisis un `socketendpoint` qui n'entre pas en conflit avec tes routes. Quand la requête vers l'application locale échoue (l'application ne tourne pas ou ferme la connexion), le visiteur reçoit une réponse vide avec le statut `200`.\n\nExample: Serveur public\n```js\nexports.install = function() {\n\tPROXYSERVER('/', '/$proxy/');\n};\n```\n\n### PROXYCLIENT(proxyserver, target, [logger])\n\nType: `method` · Since: `0.0.17`\n\nConnecte un serveur HTTP local à un `PROXYSERVER()` et répond à ses requêtes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `proxyserver` | `String` | yes |  | URL de l'endpoint WebSocket de `PROXYSERVER()`. |\n| `target` | `String` | yes |  | Serveur local sous la forme `'ip:port'` ou `'port'`. |\n| `logger` | `Function` | no | `console with a date` | Appelé avec l'état et un message à la connexion, à la déconnexion et à chaque requête. |\n\nReturns: `WebSocketClient` La connexion du client.\n\nOuvre un WebSocket binaire vers `proxyserver` (une URL `http`/`https` est changée en `ws`/`wss`). Chaque requête qui arrive est effectuée sur le serveur local `target` avec la méthode, le chemin, les en-têtes et le corps d'origine, plus l'en-tête `x-proxy: Total.js` et le `host` de la cible. La réponse est renvoyée en streaming.\n\n`target` vaut `'ip:port'` ou seulement un port (`127.0.0.1` est alors utilisé). La fonction renvoie le client WebSocket ; elle ne renvoie rien et affiche son utilisation quand un argument manque.\n\nExample: Publier une application locale\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '8000');\n```\n\nExample: Silencieux\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '192.168.1.10:8000', NOOP);\n```\n","entries":[{"type":"method","name":"PROXYSERVER()","signature":"PROXYSERVER([endpoint], [socketendpoint], [logger])","since":"0.0.17","deprecated":false},{"type":"method","name":"PROXYCLIENT()","signature":"PROXYCLIENT(proxyserver, target, [logger])","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwweDgx61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/proxy/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Proxy","summary":"PROXYSERVER() e PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/proxy/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Proxy\n\n> PROXYSERVER() e PROXYCLIENT().\n\n## API\n\n### PROXYSERVER([endpoint], [socketendpoint], [logger])\n\nType: `method` · Since: `0.0.17`\n\nInoltra le richieste HTTP a un client proxy collegato tramite WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | no | `'/'` | Prefisso del percorso delle richieste da inoltrare. |\n| `socketendpoint` | `String` | no | `'/'` | Percorso della route WebSocket per il client. |\n| `logger` | `Function` | no | `console with a date` | Chiamata come `logger(status, message)` quando il client si connette o si disconnette. |\n\nRegistra `PROXY(endpoint)` per tutte le richieste tranne quelle WebSocket e una route WebSocket binaria su `socketendpoint` (messaggi fino a 100 MB) per il client avviato con `PROXYCLIENT()`. Ogni richiesta viene inviata al client con il suo metodo, URL, header, IP e body, e la risposta del client viene restituita in streaming.\n\nPuò essere connesso un solo client; un secondo chiude il primo con il codice `4001` e non viene usato, quindi connetti di nuovo il client. Senza client, le richieste ricevono `400` con `Not yet available.`. Scegli un `socketendpoint` che non entri in conflitto con le tue route. Quando la richiesta all'app locale fallisce (l'app non è in esecuzione o chiude la connessione), il visitatore riceve una risposta vuota con lo stato `200`.\n\nExample: Server pubblico\n```js\nexports.install = function() {\n\tPROXYSERVER('/', '/$proxy/');\n};\n```\n\n### PROXYCLIENT(proxyserver, target, [logger])\n\nType: `method` · Since: `0.0.17`\n\nCollega un server HTTP locale a un `PROXYSERVER()` e risponde alle sue richieste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `proxyserver` | `String` | yes |  | URL dell'endpoint WebSocket di `PROXYSERVER()`. |\n| `target` | `String` | yes |  | Server locale come `'ip:port'` o `'port'`. |\n| `logger` | `Function` | no | `console with a date` | Chiamato con lo stato e un messaggio alla connessione, alla disconnessione e a ogni richiesta. |\n\nReturns: `WebSocketClient` La connessione del client.\n\nApre un WebSocket binario verso `proxyserver` (un URL `http`/`https` viene cambiato in `ws`/`wss`). Ogni richiesta che arriva viene eseguita sul server locale `target` con il metodo, il percorso, gli header e il body originali, più l'header `x-proxy: Total.js` e l'`host` della destinazione. La risposta viene restituita in streaming.\n\n`target` è `'ip:port'` o solo una porta (in tal caso viene usato `127.0.0.1`). La funzione restituisce il client WebSocket; non restituisce nulla e stampa il suo utilizzo quando manca un argomento.\n\nExample: Pubblicare un'app locale\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '8000');\n```\n\nExample: Silenzioso\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '192.168.1.10:8000', NOOP);\n```\n","entries":[{"type":"method","name":"PROXYSERVER()","signature":"PROXYSERVER([endpoint], [socketendpoint], [logger])","since":"0.0.17","deprecated":false},{"type":"method","name":"PROXYCLIENT()","signature":"PROXYCLIENT(proxyserver, target, [logger])","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwweDgx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/proxy/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Proxy","summary":"PROXYSERVER() a PROXYCLIENT().","markdown":"---\ntitle: Proxy\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/proxy/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Proxy\n\n> PROXYSERVER() a PROXYCLIENT().\n\n## API\n\n### PROXYSERVER([endpoint], [socketendpoint], [logger])\n\nType: `method` · Since: `0.0.17`\n\nPreposiela HTTP požiadavky proxy klientovi pripojenému cez WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | no | `'/'` | Prefix cesty požiadaviek na preposlanie. |\n| `socketendpoint` | `String` | no | `'/'` | Cesta WebSocket routy pre klienta. |\n| `logger` | `Function` | no | `console with a date` | Volá sa ako `logger(status, message)`, keď sa klient pripojí alebo odpojí. |\n\nZaregistruje `PROXY(endpoint)` pre všetky požiadavky okrem WebSocket požiadaviek a binárnu WebSocket routu na `socketendpoint` (správy do 100 MB) pre klienta spusteného cez `PROXYCLIENT()`. Každá požiadavka sa pošle klientovi s jej metódou, URL, hlavičkami, IP a telom a odpoveď klienta sa streamuje späť.\n\nPripojený môže byť iba jeden klient; druhý zatvorí prvého s kódom `4001` a nepoužije sa, preto klienta pripoj znova. Bez klienta dostanú požiadavky `400` s `Not yet available.`. Zvoľ `socketendpoint`, ktorý nekoliduje s tvojimi routami. Keď požiadavka na lokálnu aplikáciu zlyhá (aplikácia nebeží alebo zatvorí spojenie), návštevník dostane prázdnu odpoveď so stavom `200`.\n\nExample: Verejný server\n```js\nexports.install = function() {\n\tPROXYSERVER('/', '/$proxy/');\n};\n```\n\n### PROXYCLIENT(proxyserver, target, [logger])\n\nType: `method` · Since: `0.0.17`\n\nPripojí lokálny HTTP server k `PROXYSERVER()` a odpovedá na jeho požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `proxyserver` | `String` | yes |  | URL WebSocket endpointu `PROXYSERVER()`. |\n| `target` | `String` | yes |  | Lokálny server ako `'ip:port'` alebo `'port'`. |\n| `logger` | `Function` | no | `console with a date` | Volá sa so stavom a správou pri pripojení, odpojení a každej požiadavke. |\n\nReturns: `WebSocketClient` Spojenie klienta.\n\nOtvorí binárny WebSocket k `proxyserver` (URL `http`/`https` sa zmení na `ws`/`wss`). Každá prichádzajúca požiadavka sa vykoná na lokálnom serveri `target` s pôvodnou metódou, cestou, hlavičkami a telom, plus s hlavičkou `x-proxy: Total.js` a `host` cieľa. Odpoveď sa streamuje späť.\n\n`target` je `'ip:port'` alebo iba port (vtedy sa použije `127.0.0.1`). Funkcia vráti WebSocket klienta; keď chýba argument, nevráti nič a vypíše návod na použitie.\n\nExample: Zverejnenie lokálnej aplikácie\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '8000');\n```\n\nExample: Potichu\n```js\nPROXYCLIENT('https://public.example.com/$proxy/', '192.168.1.10:8000', NOOP);\n```\n","entries":[{"type":"method","name":"PROXYSERVER()","signature":"PROXYSERVER([endpoint], [socketendpoint], [logger])","since":"0.0.17","deprecated":false},{"type":"method","name":"PROXYCLIENT()","signature":"PROXYCLIENT(proxyserver, target, [logger])","since":"0.0.17","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwuZ6Hx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/ldap/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"LDAP","summary":"LDAP() and its options.","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/ldap/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# LDAP\n\n> LDAP() and its options.\n\n## API\n\n### LDAP(options, [callback])\n\nType: `method`\n\nSearches an LDAP server (Active Directory) and returns users or groups.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | The connection and the search, see below. |\n| `callback` | `Function` | no |  | `function(err, response)`. Without it the function returns a promise. |\n\nReturns: `Promise` With the response when no callback is given.\n\nBinds to the server with `user` and `password` (a simple bind), runs one search and returns the entries. The connection is closed afterwards. The search is complete when the server stops sending data for 1.5 seconds.\n\n| Option | Description |\n| --- | --- |\n| `ldap` | `{ host, port, secure, timeout }`. `port` defaults to `389`; `secure: true` connects with TLS; `timeout` limits the connection in ms |\n| `user`, `password` | Credentials for the bind (a DN or, for Active Directory, also `user@domain`) |\n| `dn` | Base DN of the search |\n| `type` | `objectClass` to search for, such as `person` or `group`; `profile` searches one person by `login` |\n| `login` | The `sAMAccountName` for `type: 'profile'` |\n| `noauth` | `true` skips the bind |\n| `attributes` | How to read attributes: `{ thumbnailPhoto: 'buffer' }`. Types: `string`, `number`, `date`, `buffer`, `binary` (also a buffer), `hex`, `base64`, `ascii`, `utf8`, in lower case |\n\nThe response is an array of objects, or one object (or `null`) for `type: 'profile'` and when `dn` is missing. Without `dn` the search uses `user` as the base DN, so you get the entry of the user that logged in. Values are strings, arrays of strings for several values, and hex strings for `objectGUID` and `objectSid`.\n\nWhen the server refuses the bind (a wrong user or password), the error is the text of the server or, when the server sends no text, `LDAP bind error <code>` (`LDAP bind error 49` for invalid credentials). This error is a string, so the promise rejects with a string; the response is `null` for a profile and an empty array for a search. An invalid `ldap.host` gives the error `Invalid hostname`; the host is converted with `U.tohost()` before the connection.\n\nExample: Groups\n```js\nvar groups = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'reader@example.com',\n\tpassword: CONF.ldap_password,\n\tdn: 'OU=Groups,DC=example,DC=com',\n\ttype: 'group'\n});\n```\n\nExample: One account\n```js\nLDAP({ ldap: { host: 'ad.example.com', port: 636, secure: true }, user: 'reader@example.com', password: CONF.ldap_password, dn: 'DC=example,DC=com', type: 'profile', login: 'peter' }, function(err, profile) {\n\tprofile && console.log(profile.mail);\n});\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(options, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwuZ6Hx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/ldap/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"LDAP","summary":"LDAP() und seine Optionen.","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/ldap/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# LDAP\n\n> LDAP() und seine Optionen.\n\n## API\n\n### LDAP(options, [callback])\n\nType: `method`\n\nDurchsucht einen LDAP-Server (Active Directory) und gibt Benutzer oder Gruppen zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Die Verbindung und die Suche, siehe unten. |\n| `callback` | `Function` | no |  | `function(err, response)`. Ohne ihn gibt die Funktion ein Promise zurück. |\n\nReturns: `Promise` Mit der Antwort, wenn kein Callback angegeben ist.\n\nBindet sich mit `user` und `password` an den Server (ein einfaches Bind), führt eine Suche aus und gibt die Einträge zurück. Die Verbindung wird danach geschlossen. Die Suche ist abgeschlossen, wenn der Server 1,5 Sekunden lang keine Daten mehr sendet.\n\n| Option | Beschreibung |\n| --- | --- |\n| `ldap` | `{ host, port, secure, timeout }`. `port` ist standardmäßig `389`; `secure: true` verbindet sich mit TLS; `timeout` begrenzt die Verbindung in ms |\n| `user`, `password` | Zugangsdaten für das Bind (ein DN oder bei Active Directory auch `user@domain`) |\n| `dn` | Basis-DN der Suche |\n| `type` | Zu suchende `objectClass`, etwa `person` oder `group`; `profile` sucht eine Person per `login` |\n| `login` | Der `sAMAccountName` für `type: 'profile'` |\n| `noauth` | `true` überspringt das Bind |\n| `attributes` | Wie Attribute gelesen werden: `{ thumbnailPhoto: 'buffer' }`. Typen: `string`, `number`, `date`, `buffer`, `binary` (ebenfalls ein Buffer), `hex`, `base64`, `ascii`, `utf8`, kleingeschrieben |\n\nDie Antwort ist ein Array von Objekten oder ein einzelnes Objekt (oder `null`) für `type: 'profile'` und wenn `dn` fehlt. Ohne `dn` verwendet die Suche `user` als Basis-DN, sodass du den Eintrag des angemeldeten Benutzers erhältst. Werte sind Strings, Arrays von Strings bei mehreren Werten und Hex-Strings für `objectGUID` und `objectSid`.\n\nWenn der Server den Bind ablehnt (ein falscher Benutzer oder ein falsches Passwort), ist der Fehler der Text des Servers oder, wenn der Server keinen Text sendet, `LDAP bind error <code>` (`LDAP bind error 49` bei ungültigen Zugangsdaten). Dieser Fehler ist ein String, daher wird die Promise mit einem String abgelehnt; die Antwort ist `null` bei einem Profil und ein leeres Array bei einer Suche. Ein ungültiges `ldap.host` führt zum Fehler `Invalid hostname`; der Host wird vor der Verbindung mit `U.tohost()` umgewandelt.\n\nExample: Gruppen\n```js\nvar groups = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'reader@example.com',\n\tpassword: CONF.ldap_password,\n\tdn: 'OU=Groups,DC=example,DC=com',\n\ttype: 'group'\n});\n```\n\nExample: Ein Konto\n```js\nLDAP({ ldap: { host: 'ad.example.com', port: 636, secure: true }, user: 'reader@example.com', password: CONF.ldap_password, dn: 'DC=example,DC=com', type: 'profile', login: 'peter' }, function(err, profile) {\n\tprofile && console.log(profile.mail);\n});\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(options, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwuZ6Hx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/ldap/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"LDAP","summary":"LDAP() y sus opciones.","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/ldap/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# LDAP\n\n> LDAP() y sus opciones.\n\n## API\n\n### LDAP(options, [callback])\n\nType: `method`\n\nBusca en un servidor LDAP (Active Directory) y devuelve usuarios o grupos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | La conexión y la búsqueda, ver abajo. |\n| `callback` | `Function` | no |  | `function(err, response)`. Sin él, la función devuelve una promesa. |\n\nReturns: `Promise` Con la respuesta cuando no se indica callback.\n\nSe autentica en el servidor con `user` y `password` (un bind simple), ejecuta una búsqueda y devuelve las entradas. Después se cierra la conexión. La búsqueda se completa cuando el servidor deja de enviar datos durante 1,5 segundos.\n\n| Opción | Descripción |\n| --- | --- |\n| `ldap` | `{ host, port, secure, timeout }`. `port` es `389` por defecto; `secure: true` se conecta con TLS; `timeout` limita la conexión en ms |\n| `user`, `password` | Credenciales para el bind (un DN o, en Active Directory, también `user@domain`) |\n| `dn` | DN base de la búsqueda |\n| `type` | `objectClass` que se busca, como `person` o `group`; `profile` busca una persona por `login` |\n| `login` | El `sAMAccountName` para `type: 'profile'` |\n| `noauth` | `true` omite el bind |\n| `attributes` | Cómo leer los atributos: `{ thumbnailPhoto: 'buffer' }`. Tipos: `string`, `number`, `date`, `buffer`, `binary` (también un buffer), `hex`, `base64`, `ascii`, `utf8`, en minúsculas |\n\nLa respuesta es un array de objetos, o un objeto (o `null`) para `type: 'profile'` y cuando falta `dn`. Sin `dn` la búsqueda usa `user` como DN base, así que obtienes la entrada del usuario que inició sesión. Los valores son strings, arrays de strings para varios valores, y strings hexadecimales para `objectGUID` y `objectSid`.\n\nCuando el servidor rechaza el bind (un usuario o una contraseña incorrectos), el error es el texto del servidor o, cuando el servidor no envía texto, `LDAP bind error <code>` (`LDAP bind error 49` para credenciales no válidas). Este error es un string, así que la promesa se rechaza con un string; la respuesta es `null` para un perfil y un array vacío para una búsqueda. Un `ldap.host` no válido da el error `Invalid hostname`; el host se convierte con `U.tohost()` antes de la conexión.\n\nExample: Grupos\n```js\nvar groups = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'reader@example.com',\n\tpassword: CONF.ldap_password,\n\tdn: 'OU=Groups,DC=example,DC=com',\n\ttype: 'group'\n});\n```\n\nExample: Una cuenta\n```js\nLDAP({ ldap: { host: 'ad.example.com', port: 636, secure: true }, user: 'reader@example.com', password: CONF.ldap_password, dn: 'DC=example,DC=com', type: 'profile', login: 'peter' }, function(err, profile) {\n\tprofile && console.log(profile.mail);\n});\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(options, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwuZ6Hx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/ldap/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"LDAP","summary":"LDAP() et ses options.","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/ldap/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# LDAP\n\n> LDAP() et ses options.\n\n## API\n\n### LDAP(options, [callback])\n\nType: `method`\n\nRecherche sur un serveur LDAP (Active Directory) et renvoie des utilisateurs ou des groupes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | La connexion et la recherche, voir ci-dessous. |\n| `callback` | `Function` | no |  | `function(err, response)`. Sans lui, la fonction renvoie une promesse. |\n\nReturns: `Promise` Avec la réponse quand aucun callback n'est fourni.\n\nEffectue un bind sur le serveur avec `user` et `password` (un bind simple), exécute une recherche et renvoie les entrées. La connexion est ensuite fermée. La recherche est terminée quand le serveur cesse d'envoyer des données pendant 1,5 seconde.\n\n| Option | Description |\n| --- | --- |\n| `ldap` | `{ host, port, secure, timeout }`. `port` vaut `389` par défaut ; `secure: true` se connecte avec TLS ; `timeout` limite la connexion en ms |\n| `user`, `password` | Identifiants pour le bind (un DN ou, pour Active Directory, aussi `user@domain`) |\n| `dn` | DN de base de la recherche |\n| `type` | `objectClass` à rechercher, comme `person` ou `group` ; `profile` recherche une personne par `login` |\n| `login` | Le `sAMAccountName` pour `type: 'profile'` |\n| `noauth` | `true` ignore le bind |\n| `attributes` | Comment lire les attributs : `{ thumbnailPhoto: 'buffer' }`. Types : `string`, `number`, `date`, `buffer`, `binary` (aussi un buffer), `hex`, `base64`, `ascii`, `utf8`, en minuscules |\n\nLa réponse est un tableau d'objets, ou un seul objet (ou `null`) pour `type: 'profile'` et lorsque `dn` manque. Sans `dn`, la recherche utilise `user` comme DN de base : tu obtiens donc l'entrée de l'utilisateur qui s'est connecté. Les valeurs sont des chaînes, des tableaux de chaînes pour plusieurs valeurs, et des chaînes hexadécimales pour `objectGUID` et `objectSid`.\n\nQuand le serveur refuse le bind (un mauvais utilisateur ou mot de passe), l'erreur est le texte du serveur ou, quand le serveur n'envoie aucun texte, `LDAP bind error <code>` (`LDAP bind error 49` pour des identifiants non valides). Cette erreur est une chaîne, donc la promesse est rejetée avec une chaîne ; la réponse est `null` pour un profil et un tableau vide pour une recherche. Un `ldap.host` non valide donne l'erreur `Invalid hostname` ; l'hôte est converti avec `U.tohost()` avant la connexion.\n\nExample: Groupes\n```js\nvar groups = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'reader@example.com',\n\tpassword: CONF.ldap_password,\n\tdn: 'OU=Groups,DC=example,DC=com',\n\ttype: 'group'\n});\n```\n\nExample: Un compte\n```js\nLDAP({ ldap: { host: 'ad.example.com', port: 636, secure: true }, user: 'reader@example.com', password: CONF.ldap_password, dn: 'DC=example,DC=com', type: 'profile', login: 'peter' }, function(err, profile) {\n\tprofile && console.log(profile.mail);\n});\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(options, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwuZ6Hx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/ldap/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"LDAP","summary":"LDAP() e le sue opzioni.","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/ldap/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# LDAP\n\n> LDAP() e le sue opzioni.\n\n## API\n\n### LDAP(options, [callback])\n\nType: `method`\n\nEsegue una ricerca su un server LDAP (Active Directory) e restituisce utenti o gruppi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | La connessione e la ricerca, vedi sotto. |\n| `callback` | `Function` | no |  | `function(err, response)`. Senza di essa la funzione restituisce una promise. |\n\nReturns: `Promise` Con la risposta quando non viene passata una callback.\n\nEsegue il bind al server con `user` e `password` (un bind semplice), esegue una ricerca e restituisce le voci. Poi la connessione viene chiusa. La ricerca è completa quando il server smette di inviare dati per 1,5 secondi.\n\n| Opzione | Descrizione |\n| --- | --- |\n| `ldap` | `{ host, port, secure, timeout }`. `port` vale `389` per impostazione predefinita; `secure: true` si connette con TLS; `timeout` limita la connessione in ms |\n| `user`, `password` | Credenziali per il bind (un DN o, per Active Directory, anche `user@domain`) |\n| `dn` | DN base della ricerca |\n| `type` | `objectClass` da cercare, come `person` o `group`; `profile` cerca una persona tramite `login` |\n| `login` | Il `sAMAccountName` per `type: 'profile'` |\n| `noauth` | `true` salta il bind |\n| `attributes` | Come leggere gli attributi: `{ thumbnailPhoto: 'buffer' }`. Tipi: `string`, `number`, `date`, `buffer`, `binary` (anch'esso un buffer), `hex`, `base64`, `ascii`, `utf8`, in minuscolo |\n\nLa risposta è un array di oggetti, oppure un oggetto (o `null`) per `type: 'profile'` e quando manca `dn`. Senza `dn` la ricerca usa `user` come DN base, quindi ottieni la voce dell'utente che ha effettuato l'accesso. I valori sono stringhe, array di stringhe per più valori, e stringhe esadecimali per `objectGUID` e `objectSid`.\n\nQuando il server rifiuta il bind (utente o password sbagliati), l'errore è il testo del server oppure, quando il server non invia alcun testo, `LDAP bind error <code>` (`LDAP bind error 49` per credenziali non valide). Questo errore è una stringa, quindi la promise viene rifiutata con una stringa; la risposta è `null` per un profilo e un array vuoto per una ricerca. Un `ldap.host` non valido dà l'errore `Invalid hostname`; l'host viene convertito con `U.tohost()` prima della connessione.\n\nExample: Gruppi\n```js\nvar groups = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'reader@example.com',\n\tpassword: CONF.ldap_password,\n\tdn: 'OU=Groups,DC=example,DC=com',\n\ttype: 'group'\n});\n```\n\nExample: Un account\n```js\nLDAP({ ldap: { host: 'ad.example.com', port: 636, secure: true }, user: 'reader@example.com', password: CONF.ldap_password, dn: 'DC=example,DC=com', type: 'profile', login: 'peter' }, function(err, profile) {\n\tprofile && console.log(profile.mail);\n});\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(options, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwuZ6Hx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/ldap/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"LDAP","summary":"LDAP() a jeho voľby.","markdown":"---\ntitle: LDAP\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/ldap/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# LDAP\n\n> LDAP() a jeho voľby.\n\n## API\n\n### LDAP(options, [callback])\n\nType: `method`\n\nPrehľadá LDAP server (Active Directory) a vráti používateľov alebo skupiny.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Spojenie a vyhľadávanie, pozri nižšie. |\n| `callback` | `Function` | no |  | `function(err, response)`. Bez neho funkcia vráti promise. |\n\nReturns: `Promise` S odpoveďou, keď nie je zadaný callback.\n\nPrihlási sa na server cez `user` a `password` (jednoduchý bind), spustí jedno vyhľadávanie a vráti záznamy. Spojenie sa potom zatvorí. Vyhľadávanie je dokončené, keď server 1,5 sekundy neposiela dáta.\n\n| Možnosť | Popis |\n| --- | --- |\n| `ldap` | `{ host, port, secure, timeout }`. `port` je predvolene `389`; `secure: true` sa pripojí cez TLS; `timeout` obmedzí spojenie v ms |\n| `user`, `password` | Prihlasovacie údaje pre bind (DN alebo pre Active Directory aj `user@domain`) |\n| `dn` | Základné DN vyhľadávania |\n| `type` | `objectClass`, ktorú hľadáš, napríklad `person` alebo `group`; `profile` hľadá jednu osobu podľa `login` |\n| `login` | `sAMAccountName` pre `type: 'profile'` |\n| `noauth` | `true` preskočí bind |\n| `attributes` | Ako čítať atribúty: `{ thumbnailPhoto: 'buffer' }`. Typy: `string`, `number`, `date`, `buffer`, `binary` (tiež buffer), `hex`, `base64`, `ascii`, `utf8`, malými písmenami |\n\nOdpoveď je pole objektov, alebo jeden objekt (alebo `null`) pre `type: 'profile'` a keď chýba `dn`. Bez `dn` vyhľadávanie použije `user` ako základné DN, takže dostaneš záznam používateľa, ktorý sa prihlásil. Hodnoty sú reťazce, polia reťazcov pre viac hodnôt a hex reťazce pre `objectGUID` a `objectSid`.\n\nKeď server odmietne bind (nesprávny používateľ alebo heslo), chybou je text servera, alebo, keď server nepošle žiadny text, `LDAP bind error <code>` (`LDAP bind error 49` pre neplatné prihlasovacie údaje). Táto chyba je reťazec, takže promise sa zamietne s reťazcom; odpoveď je `null` pre profil a prázdne pole pre vyhľadávanie. Neplatný `ldap.host` vráti chybu `Invalid hostname`; host sa pred pripojením skonvertuje cez `U.tohost()`.\n\nExample: Skupiny\n```js\nvar groups = await LDAP({\n\tldap: { host: 'ad.example.com' },\n\tuser: 'reader@example.com',\n\tpassword: CONF.ldap_password,\n\tdn: 'OU=Groups,DC=example,DC=com',\n\ttype: 'group'\n});\n```\n\nExample: Jeden účet\n```js\nLDAP({ ldap: { host: 'ad.example.com', port: 636, secure: true }, user: 'reader@example.com', password: CONF.ldap_password, dn: 'DC=example,DC=com', type: 'profile', login: 'peter' }, function(err, profile) {\n\tprofile && console.log(profile.mail);\n});\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(options, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafiQ22cD61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/markdown/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Markdown","summary":"String.prototype.markdown() and the Markdown syntax.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/markdown/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Markdown\n\n> String.prototype.markdown() and the Markdown syntax.\n\n## API\n\n### String.prototype.markdown([options], [nested])\n\nType: `method`\n\nConverts a Markdown string to HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Options, see the table. |\n| `nested` | `Boolean` | no | `false` | Leaves out the `markdown-container` class. |\n\nReturns: `String` HTML.\n\nEvery option is on by default; set it to `false` to skip that syntax.\n\n| Option | Description |\n| --- | --- |\n| `wrap` | Wraps the output in `<div class=\"markdown markdown-container\">` |\n| `linetag` | Tag of paragraphs, default `'p'`; an empty string gives plain lines |\n| `bookmarks` | Adds an `id` made from the text to headings |\n| `prefix` | Text before the `id` of headings |\n| `headlines`, `ul`, `tables`, `code`, `blockquotes`, `sections`, `hr`, `blocks` | Block syntax |\n| `formatting`, `links`, `images`, `icons`, `keywords`, `footnotes`, `urlify`, `br` | Inline syntax (`urlify` turns plain URLs into links, `br` keeps `<br>`) |\n| `emptynewline` | Two empty lines give `<br />` |\n| `custom` | `function(line)` that changes each line before it is parsed |\n| `html` | `function(text, type)` that changes the text of a block; `type` is `'#'`…`'#####'`, `'li'`, `'blockquote'`, `'section'`, `'block'` or the line tag |\n\n`<` and `>` in the source are encoded, so raw HTML is not passed through; a text in angle brackets, such as `<www.totaljs.com>`, becomes a link. With `nested: true` the wrapper has only the class `markdown`.\n\nExample: Article\n```js\nvar html = article.body.markdown();\n```\n\nExample: Plain fragment\n```js\n'**Note:** see [docs](https://docs.totaljs.com)'.markdown({ wrap: false, linetag: '' });\n// '<strong>Note:</strong> see <a href=\"https://docs.totaljs.com\" target=\"_blank\">docs</a>'\n```\n\n### Markdown syntax\n\nType: `type`\n\nMarkdown supported by `String.prototype.markdown()`, with the Total.js extensions.\n\n| Syntax | Result |\n| --- | --- |\n| `# Title` … `##### Title` | `<h1>` … `<h5>` with an `id` |\n| `**text**`, `*text*` | `<strong>`, `<em>` |\n| `__text__`, `_text_`, `~~text~~` | `<b>`, `<u>`, `<strike>` |\n| `` `code` `` and ```` ```js ```` blocks | `<code>`, `<pre><code class=\"lang-js\">` |\n| `- item`, `* item`, `+ item`, `1. item`, `a. item` | Lists; a tab nests them; `[ ]` and `[x]` make tasks |\n| `\\| a \\| b \\|` with a `\\|---\\|--:\\|` line | A table with `left`, `right` or `center` columns |\n| `> text` | `<blockquote>` |\n| `< text` | `<section>` |\n| `---`, `***` | `<hr>` |\n| `[text](url)`, `![alt](url)`, `[![alt](img)](url)` | Links (external ones open in a new tab; e-mails and phone numbers get `mailto:` and `tel:`) and lazy images |\n| `![+alt](url)`, `![-alt](url)` | An image without `img-responsive`, a gallery image |\n| `:check:`, `:ti ti-user:` | Icons |\n| `{text}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` and `#1: text` | A footnote and its body |\n| `::: Title` … `:::` | An expandable block |\n","entries":[{"type":"method","name":"String.prototype.markdown()","signature":"String.prototype.markdown([options], [nested])","since":"","deprecated":false},{"type":"type","name":"Markdown syntax","signature":"Markdown syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafiQ22cD61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/markdown/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Markdown","summary":"String.prototype.markdown() und die Markdown-Syntax.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/markdown/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Markdown\n\n> String.prototype.markdown() und die Markdown-Syntax.\n\n## API\n\n### String.prototype.markdown([options], [nested])\n\nType: `method`\n\nKonvertiert einen Markdown-String in HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Optionen, siehe Tabelle. |\n| `nested` | `Boolean` | no | `false` | Lässt die Klasse `markdown-container` weg. |\n\nReturns: `String` HTML.\n\nJede Option ist standardmäßig eingeschaltet; setze sie auf `false`, um diese Syntax zu überspringen.\n\n| Option | Beschreibung |\n| --- | --- |\n| `wrap` | Umschließt die Ausgabe mit `<div class=\"markdown markdown-container\">` |\n| `linetag` | Tag der Absätze, Standard `'p'`; ein leerer String ergibt einfache Zeilen |\n| `bookmarks` | Fügt Überschriften eine aus dem Text gebildete `id` hinzu |\n| `prefix` | Text vor der `id` von Überschriften |\n| `headlines`, `ul`, `tables`, `code`, `blockquotes`, `sections`, `hr`, `blocks` | Block-Syntax |\n| `formatting`, `links`, `images`, `icons`, `keywords`, `footnotes`, `urlify`, `br` | Inline-Syntax (`urlify` macht aus einfachen URLs Links, `br` behält `<br>` bei) |\n| `emptynewline` | Zwei leere Zeilen ergeben `<br />` |\n| `custom` | `function(line)`, die jede Zeile vor dem Parsen ändert |\n| `html` | `function(text, type)`, die den Text eines Blocks ändert; `type` ist `'#'`…`'#####'`, `'li'`, `'blockquote'`, `'section'`, `'block'` oder das Zeilen-Tag |\n\n`<` und `>` in der Quelle werden codiert, rohes HTML wird also nicht durchgereicht; ein Text in spitzen Klammern, etwa `<www.totaljs.com>`, wird zu einem Link. Mit `nested: true` hat der Wrapper nur die Klasse `markdown`.\n\nExample: Artikel\n```js\nvar html = article.body.markdown();\n```\n\nExample: Einfaches Fragment\n```js\n'**Note:** see [docs](https://docs.totaljs.com)'.markdown({ wrap: false, linetag: '' });\n// '<strong>Note:</strong> see <a href=\"https://docs.totaljs.com\" target=\"_blank\">docs</a>'\n```\n\n### Markdown syntax\n\nType: `type`\n\nVon `String.prototype.markdown()` unterstütztes Markdown, mit den Total.js-Erweiterungen.\n\n| Syntax | Ergebnis |\n| --- | --- |\n| `# Title` … `##### Title` | `<h1>` … `<h5>` mit einer `id` |\n| `**text**`, `*text*` | `<strong>`, `<em>` |\n| `__text__`, `_text_`, `~~text~~` | `<b>`, `<u>`, `<strike>` |\n| `` `code` `` und ```` ```js ````-Blöcke | `<code>`, `<pre><code class=\"lang-js\">` |\n| `- item`, `* item`, `+ item`, `1. item`, `a. item` | Listen; ein Tab verschachtelt sie; `[ ]` und `[x]` erzeugen Aufgaben |\n| `\\| a \\| b \\|` mit einer `\\|---\\|--:\\|`-Zeile | Eine Tabelle mit Spalten `left`, `right` oder `center` |\n| `> text` | `<blockquote>` |\n| `< text` | `<section>` |\n| `---`, `***` | `<hr>` |\n| `[text](url)`, `![alt](url)`, `[![alt](img)](url)` | Links (externe öffnen sich in einem neuen Tab; E-Mail-Adressen und Telefonnummern erhalten `mailto:` und `tel:`) und Lazy-Loading-Bilder |\n| `![+alt](url)`, `![-alt](url)` | Ein Bild ohne `img-responsive`, ein Galeriebild |\n| `:check:`, `:ti ti-user:` | Icons |\n| `{text}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` und `#1: text` | Eine Fußnote und ihr Inhalt |\n| `::: Title` … `:::` | Ein aufklappbarer Block |\n","entries":[{"type":"method","name":"String.prototype.markdown()","signature":"String.prototype.markdown([options], [nested])","since":"","deprecated":false},{"type":"type","name":"Markdown syntax","signature":"Markdown syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafiQ22cD61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/markdown/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Markdown","summary":"String.prototype.markdown() y la sintaxis de Markdown.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/markdown/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Markdown\n\n> String.prototype.markdown() y la sintaxis de Markdown.\n\n## API\n\n### String.prototype.markdown([options], [nested])\n\nType: `method`\n\nConvierte un string Markdown en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Opciones, consulta la tabla. |\n| `nested` | `Boolean` | no | `false` | Deja fuera la clase `markdown-container`. |\n\nReturns: `String` HTML.\n\nTodas las opciones están activadas por defecto; ponlas en `false` para omitir esa sintaxis.\n\n| Opción | Descripción |\n| --- | --- |\n| `wrap` | Envuelve la salida en `<div class=\"markdown markdown-container\">` |\n| `linetag` | Etiqueta de los párrafos, por defecto `'p'`; un string vacío da líneas simples |\n| `bookmarks` | Añade a los encabezados un `id` creado a partir del texto |\n| `prefix` | Texto antes del `id` de los encabezados |\n| `headlines`, `ul`, `tables`, `code`, `blockquotes`, `sections`, `hr`, `blocks` | Sintaxis de bloque |\n| `formatting`, `links`, `images`, `icons`, `keywords`, `footnotes`, `urlify`, `br` | Sintaxis en línea (`urlify` convierte las URLs simples en enlaces, `br` conserva `<br>`) |\n| `emptynewline` | Dos líneas vacías dan `<br />` |\n| `custom` | `function(line)` que cambia cada línea antes de parsearla |\n| `html` | `function(text, type)` que cambia el texto de un bloque; `type` es `'#'`…`'#####'`, `'li'`, `'blockquote'`, `'section'`, `'block'` o la etiqueta de línea |\n\n`<` y `>` en el código fuente se codifican, así que el HTML en bruto no pasa; un texto entre corchetes angulares, como `<www.totaljs.com>`, se convierte en un enlace. Con `nested: true` el contenedor solo tiene la clase `markdown`.\n\nExample: Artículo\n```js\nvar html = article.body.markdown();\n```\n\nExample: Fragmento simple\n```js\n'**Note:** see [docs](https://docs.totaljs.com)'.markdown({ wrap: false, linetag: '' });\n// '<strong>Note:</strong> see <a href=\"https://docs.totaljs.com\" target=\"_blank\">docs</a>'\n```\n\n### Markdown syntax\n\nType: `type`\n\nMarkdown admitido por `String.prototype.markdown()`, con las extensiones de Total.js.\n\n| Sintaxis | Resultado |\n| --- | --- |\n| `# Title` … `##### Title` | `<h1>` … `<h5>` con un `id` |\n| `**text**`, `*text*` | `<strong>`, `<em>` |\n| `__text__`, `_text_`, `~~text~~` | `<b>`, `<u>`, `<strike>` |\n| `` `code` `` y bloques ```` ```js ```` | `<code>`, `<pre><code class=\"lang-js\">` |\n| `- item`, `* item`, `+ item`, `1. item`, `a. item` | Listas; un tabulador las anida; `[ ]` y `[x]` crean tareas |\n| `\\| a \\| b \\|` con una línea `\\|---\\|--:\\|` | Una tabla con columnas `left`, `right` o `center` |\n| `> text` | `<blockquote>` |\n| `< text` | `<section>` |\n| `---`, `***` | `<hr>` |\n| `[text](url)`, `![alt](url)`, `[![alt](img)](url)` | Enlaces (los externos se abren en una pestaña nueva; los e-mails y números de teléfono reciben `mailto:` y `tel:`) e imágenes con carga diferida |\n| `![+alt](url)`, `![-alt](url)` | Una imagen sin `img-responsive`, una imagen de galería |\n| `:check:`, `:ti ti-user:` | Iconos |\n| `{text}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` y `#1: text` | Una nota al pie y su cuerpo |\n| `::: Title` … `:::` | Un bloque desplegable |\n","entries":[{"type":"method","name":"String.prototype.markdown()","signature":"String.prototype.markdown([options], [nested])","since":"","deprecated":false},{"type":"type","name":"Markdown syntax","signature":"Markdown syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafiQ22cD61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/markdown/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Markdown","summary":"String.prototype.markdown() et la syntaxe Markdown.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/markdown/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Markdown\n\n> String.prototype.markdown() et la syntaxe Markdown.\n\n## API\n\n### String.prototype.markdown([options], [nested])\n\nType: `method`\n\nConvertit une chaîne Markdown en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Options, voir le tableau. |\n| `nested` | `Boolean` | no | `false` | Omet la classe `markdown-container`. |\n\nReturns: `String` Du HTML.\n\nChaque option est activée par défaut ; mets-la à `false` pour ignorer cette syntaxe.\n\n| Option | Description |\n| --- | --- |\n| `wrap` | Enveloppe la sortie dans `<div class=\"markdown markdown-container\">` |\n| `linetag` | Balise des paragraphes, par défaut `'p'` ; une chaîne vide donne des lignes simples |\n| `bookmarks` | Ajoute aux titres un `id` créé à partir du texte |\n| `prefix` | Texte placé avant l'`id` des titres |\n| `headlines`, `ul`, `tables`, `code`, `blockquotes`, `sections`, `hr`, `blocks` | Syntaxe de bloc |\n| `formatting`, `links`, `images`, `icons`, `keywords`, `footnotes`, `urlify`, `br` | Syntaxe inline (`urlify` transforme les URL simples en liens, `br` conserve `<br>`) |\n| `emptynewline` | Deux lignes vides donnent `<br />` |\n| `custom` | `function(line)` qui modifie chaque ligne avant son analyse |\n| `html` | `function(text, type)` qui modifie le texte d'un bloc ; `type` vaut `'#'`…`'#####'`, `'li'`, `'blockquote'`, `'section'`, `'block'` ou la balise de ligne |\n\n`<` et `>` dans la source sont encodés : le HTML brut n'est donc pas transmis ; un texte entre chevrons, comme `<www.totaljs.com>`, devient un lien. Avec `nested: true`, l'enveloppe n'a que la classe `markdown`.\n\nExample: Article\n```js\nvar html = article.body.markdown();\n```\n\nExample: Fragment simple\n```js\n'**Note:** see [docs](https://docs.totaljs.com)'.markdown({ wrap: false, linetag: '' });\n// '<strong>Note:</strong> see <a href=\"https://docs.totaljs.com\" target=\"_blank\">docs</a>'\n```\n\n### Markdown syntax\n\nType: `type`\n\nLe Markdown pris en charge par `String.prototype.markdown()`, avec les extensions de Total.js.\n\n| Syntaxe | Résultat |\n| --- | --- |\n| `# Title` … `##### Title` | `<h1>` … `<h5>` avec un `id` |\n| `**text**`, `*text*` | `<strong>`, `<em>` |\n| `__text__`, `_text_`, `~~text~~` | `<b>`, `<u>`, `<strike>` |\n| `` `code` `` et les blocs ```` ```js ```` | `<code>`, `<pre><code class=\"lang-js\">` |\n| `- item`, `* item`, `+ item`, `1. item`, `a. item` | Listes ; une tabulation les imbrique ; `[ ]` et `[x]` créent des tâches |\n| `\\| a \\| b \\|` avec une ligne `\\|---\\|--:\\|` | Un tableau avec des colonnes `left`, `right` ou `center` |\n| `> text` | `<blockquote>` |\n| `< text` | `<section>` |\n| `---`, `***` | `<hr>` |\n| `[text](url)`, `![alt](url)`, `[![alt](img)](url)` | Liens (les liens externes s'ouvrent dans un nouvel onglet ; les e-mails et les numéros de téléphone reçoivent `mailto:` et `tel:`) et images en chargement différé |\n| `![+alt](url)`, `![-alt](url)` | Une image sans `img-responsive`, une image de galerie |\n| `:check:`, `:ti ti-user:` | Icônes |\n| `{text}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` et `#1: text` | Une note de bas de page et son contenu |\n| `::: Title` … `:::` | Un bloc dépliable |\n","entries":[{"type":"method","name":"String.prototype.markdown()","signature":"String.prototype.markdown([options], [nested])","since":"","deprecated":false},{"type":"type","name":"Markdown syntax","signature":"Markdown syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafiQ22cD61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/markdown/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Markdown","summary":"String.prototype.markdown() e la sintassi Markdown.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/markdown/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Markdown\n\n> String.prototype.markdown() e la sintassi Markdown.\n\n## API\n\n### String.prototype.markdown([options], [nested])\n\nType: `method`\n\nConverte una stringa Markdown in HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Opzioni, vedi la tabella. |\n| `nested` | `Boolean` | no | `false` | Omette la classe `markdown-container`. |\n\nReturns: `String` HTML.\n\nOgni opzione è attiva per impostazione predefinita; impostala a `false` per saltare quella sintassi.\n\n| Opzione | Descrizione |\n| --- | --- |\n| `wrap` | Racchiude l'output in `<div class=\"markdown markdown-container\">` |\n| `linetag` | Tag dei paragrafi, predefinito `'p'`; una stringa vuota produce righe semplici |\n| `bookmarks` | Aggiunge ai titoli un `id` ricavato dal testo |\n| `prefix` | Testo prima dell'`id` dei titoli |\n| `headlines`, `ul`, `tables`, `code`, `blockquotes`, `sections`, `hr`, `blocks` | Sintassi di blocco |\n| `formatting`, `links`, `images`, `icons`, `keywords`, `footnotes`, `urlify`, `br` | Sintassi inline (`urlify` trasforma gli URL semplici in link, `br` mantiene `<br>`) |\n| `emptynewline` | Due righe vuote producono `<br />` |\n| `custom` | `function(line)` che modifica ogni riga prima che venga analizzata |\n| `html` | `function(text, type)` che modifica il testo di un blocco; `type` è `'#'`…`'#####'`, `'li'`, `'blockquote'`, `'section'`, `'block'` o il tag di riga |\n\n`<` e `>` nella sorgente vengono codificati, quindi l'HTML grezzo non viene lasciato passare; un testo tra parentesi angolari, come `<www.totaljs.com>`, diventa un link. Con `nested: true` il contenitore ha solo la classe `markdown`.\n\nExample: Articolo\n```js\nvar html = article.body.markdown();\n```\n\nExample: Frammento semplice\n```js\n'**Note:** see [docs](https://docs.totaljs.com)'.markdown({ wrap: false, linetag: '' });\n// '<strong>Note:</strong> see <a href=\"https://docs.totaljs.com\" target=\"_blank\">docs</a>'\n```\n\n### Markdown syntax\n\nType: `type`\n\nIl Markdown supportato da `String.prototype.markdown()`, con le estensioni di Total.js.\n\n| Sintassi | Risultato |\n| --- | --- |\n| `# Title` … `##### Title` | `<h1>` … `<h5>` con un `id` |\n| `**text**`, `*text*` | `<strong>`, `<em>` |\n| `__text__`, `_text_`, `~~text~~` | `<b>`, `<u>`, `<strike>` |\n| `` `code` `` e blocchi ```` ```js ```` | `<code>`, `<pre><code class=\"lang-js\">` |\n| `- item`, `* item`, `+ item`, `1. item`, `a. item` | Elenchi; una tabulazione li annida; `[ ]` e `[x]` creano attività |\n| `\\| a \\| b \\|` con una riga `\\|---\\|--:\\|` | Una tabella con colonne `left`, `right` o `center` |\n| `> text` | `<blockquote>` |\n| `< text` | `<section>` |\n| `---`, `***` | `<hr>` |\n| `[text](url)`, `![alt](url)`, `[![alt](img)](url)` | Link (quelli esterni si aprono in una nuova scheda; e-mail e numeri di telefono ricevono `mailto:` e `tel:`) e immagini con caricamento lazy |\n| `![+alt](url)`, `![-alt](url)` | Un'immagine senza `img-responsive`, un'immagine di galleria |\n| `:check:`, `:ti ti-user:` | Icone |\n| `{text}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` e `#1: text` | Una nota a piè di pagina e il suo testo |\n| `::: Title` … `:::` | Un blocco espandibile |\n","entries":[{"type":"method","name":"String.prototype.markdown()","signature":"String.prototype.markdown([options], [nested])","since":"","deprecated":false},{"type":"type","name":"Markdown syntax","signature":"Markdown syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JafiQ22cD61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/markdown/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Markdown","summary":"String.prototype.markdown() a syntax Markdownu.","markdown":"---\ntitle: Markdown\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/markdown/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Markdown\n\n> String.prototype.markdown() a syntax Markdownu.\n\n## API\n\n### String.prototype.markdown([options], [nested])\n\nType: `method`\n\nPrevedie Markdown reťazec na HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Voľby, pozri tabuľku. |\n| `nested` | `Boolean` | no | `false` | Vynechá triedu `markdown-container`. |\n\nReturns: `String` HTML.\n\nKaždá voľba je predvolene zapnutá; nastav ju na `false`, aby sa daná syntax preskočila.\n\n| Voľba | Popis |\n| --- | --- |\n| `wrap` | Obalí výstup do `<div class=\"markdown markdown-container\">` |\n| `linetag` | Tag odsekov, predvolene `'p'`; prázdny reťazec dá obyčajné riadky |\n| `bookmarks` | Pridá k nadpisom `id` vytvorené z textu |\n| `prefix` | Text pred `id` nadpisov |\n| `headlines`, `ul`, `tables`, `code`, `blockquotes`, `sections`, `hr`, `blocks` | Bloková syntax |\n| `formatting`, `links`, `images`, `icons`, `keywords`, `footnotes`, `urlify`, `br` | Inline syntax (`urlify` zmení obyčajné URL na odkazy, `br` zachová `<br>`) |\n| `emptynewline` | Dva prázdne riadky dajú `<br />` |\n| `custom` | `function(line)`, ktorá zmení každý riadok pred spracovaním |\n| `html` | `function(text, type)`, ktorá zmení text bloku; `type` je `'#'`…`'#####'`, `'li'`, `'blockquote'`, `'section'`, `'block'` alebo tag riadka |\n\n`<` a `>` v zdroji sa zakódujú, takže surové HTML neprejde; text v lomených zátvorkách, napríklad `<www.totaljs.com>`, sa stane odkazom. S `nested: true` má obal iba triedu `markdown`.\n\nExample: Článok\n```js\nvar html = article.body.markdown();\n```\n\nExample: Obyčajný fragment\n```js\n'**Note:** see [docs](https://docs.totaljs.com)'.markdown({ wrap: false, linetag: '' });\n// '<strong>Note:</strong> see <a href=\"https://docs.totaljs.com\" target=\"_blank\">docs</a>'\n```\n\n### Markdown syntax\n\nType: `type`\n\nMarkdown podporovaný funkciou `String.prototype.markdown()`, s rozšíreniami Total.js.\n\n| Syntax | Výsledok |\n| --- | --- |\n| `# Title` … `##### Title` | `<h1>` … `<h5>` s `id` |\n| `**text**`, `*text*` | `<strong>`, `<em>` |\n| `__text__`, `_text_`, `~~text~~` | `<b>`, `<u>`, `<strike>` |\n| `` `code` `` a bloky ```` ```js ```` | `<code>`, `<pre><code class=\"lang-js\">` |\n| `- item`, `* item`, `+ item`, `1. item`, `a. item` | Zoznamy; tabulátor ich vnorí; `[ ]` a `[x]` vytvoria úlohy |\n| `\\| a \\| b \\|` s riadkom `\\|---\\|--:\\|` | Tabuľka so stĺpcami `left`, `right` alebo `center` |\n| `> text` | `<blockquote>` |\n| `< text` | `<section>` |\n| `---`, `***` | `<hr>` |\n| `[text](url)`, `![alt](url)`, `[![alt](img)](url)` | Odkazy (externé sa otvoria v novej karte; e-maily a telefónne čísla dostanú `mailto:` a `tel:`) a lazy obrázky |\n| `![+alt](url)`, `![-alt](url)` | Obrázok bez `img-responsive`, obrázok galérie |\n| `:check:`, `:ti ti-user:` | Ikony |\n| `{text}(type)` | `<span class=\"markdown-keyword\" data-type=\"type\">` |\n| `[1](#1)` a `#1: text` | Poznámka pod čiarou a jej telo |\n| `::: Title` … `:::` | Rozbaľovací blok |\n","entries":[{"type":"method","name":"String.prototype.markdown()","signature":"String.prototype.markdown([options], [nested])","since":"","deprecated":false},{"type":"type","name":"Markdown syntax","signature":"Markdown syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JaqmCf3kc61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/html-parser/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"HTML and XML parser","summary":"String.prototype.parseHTML(), HTMLElement and the methods of an element.","markdown":"---\ntitle: HTML and XML parser\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/html-parser/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# HTML and XML parser\n\n> String.prototype.parseHTML(), HTMLElement and the methods of an element.\n\n## API\n\n### String.prototype.parseHTML([trim])\n\nType: `method`\n\nParses HTML into a tree of elements.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Trims text nodes. |\n\nReturns: `HTMLElement` The root element.\n\nReturns the root element; its `children` are the top-level nodes. Comments are removed. `<script>`, `<style>` and `<template>` keep their content as text. With `trim: true` the text nodes are trimmed.\n\n`String.prototype.parseXML2()` parses XML the same way: every element keeps its prefix (`soap:Body`) and text of elements is joined with new lines by `text()`.\n\nExample: Read links\n```js\nvar dom = html.parseHTML();\nvar links = dom.find('a').map(function(a) {\n\treturn { url: a.attr('href'), text: a.text() };\n});\n```\n\nExample: XML\n```js\nvar xml = body.parseXML2();\nvar items = xml.find('*:item'); // any prefix\n```\n\n### HTMLElement\n\nType: `class`\n\nAn element (or a text node) of a tree from `parseHTML()`.\n\n| Property | Description |\n| --- | --- |\n| `tagName` | Tag name in upper case, `TEXT` for a text node |\n| `raw` | Tag name as written |\n| `prefix` | XML prefix with the colon, such as `SOAP:` |\n| `attrs` | Attributes as an object |\n| `children` | Child nodes |\n| `parentNode` | Parent element |\n| `textContent` | Text of a `TEXT` node |\n| `innerHTML`, `outerHTML`, `innerText` | Getters for `html()`, the element with its tag, and `text()` |\n\nExample: Walk\n```js\nvar dom = '<ul><li>A</li><li>B</li></ul>'.parseHTML();\nvar ul = dom.children[0];\nul.tagName;\t\t   // 'UL'\nul.children.length;   // 2\nul.outerHTML;\t\t // '<ul><li>A</li><li>B</li></ul>'\n```\n\n### element.find(selector)\n\nType: `method`\n\nFinds elements below this element.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | CSS-like selector. |\n\nReturns: `Array` Found elements.\n\nSupports tag names, `*`, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (the element has the attribute), `prefix:` and `*:name` for XML, descendants (`div p`), children (`div > p`, or `> p` for direct children of this element) and several selectors separated by commas.\n\nThe result is an array with the methods `aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()`, `find()`, `html()` (same as `toString()`) and `text()`, applied to all found elements.\n\nExample: Find\n```js\ndom.find('table.data > tr td').text();\ndom.find('a').attr('rel', 'nofollow');\n```\n\nExample: Elements with an attribute\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt]');      // images with an alt text\nvar ids = dom.find('[data-id]');\n```\n\n### element.parent()\n\nType: `method`\n\nReturns the parent element.\n\nReturns: `HTMLElement` The parent.\n\nThe same as `element.parentNode`.\n\nExample: Parent\n```js\nvar td = dom.find('td.price')[0];\nvar row = td.parent();\n```\n\n### element.browse(fn, [reverse])\n\nType: `method`\n\nCalls a function for every node below this one.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(node)`; `true` skips the children. |\n| `reverse` | `Boolean` | no | `false` | Walks the parents. |\n\nReturns: `HTMLElement` This element.\n\n`fn(node)` is called for each node below, text nodes (`tagName` `TEXT`) included, depth first. Return `true` to skip the children of that element. With `reverse: true` it goes up through the parents instead.\n\nExample: Collect\n```js\nvar tags = {};\ndom.browse(function(el) {\n\ttags[el.tagName] = (tags[el.tagName] || 0) + 1;\n});\n```\n\n### element.attr(name, [value])\n\nType: `method`\n\nReads or sets an attribute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Attribute name. |\n| `value` | `Object` | no |  | New value. |\n\nReturns: `String` The value when reading, otherwise the element.\n\nWithout `value` it returns the attribute. An empty value or `null` removes it; other values are stored as strings.\n\nExample: Attributes\n```js\nvar href = a.attr('href');\na.attr('rel', 'nofollow');\na.attr('target', null);\n```\n\n### element.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 |  | Name without `data-`. |\n| `value` | `Object` | no |  | New value. |\n\nReturns: `String` The value when reading, otherwise the element.\n\n`attrd('id')` is `attr('data-id')`.\n\nExample: Data\n```js\nel.attrd('id', 123);\nel.attrd('id'); // '123'\n```\n\n### element.aclass(cls)\n\nType: `method`\n\nAdds classes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Class names. |\n\nReturns: `HTMLElement` This element.\n\nSeveral classes are separated by spaces or commas.\n\nExample: Add\n```js\nel.aclass('active selected');\n```\n\n### element.rclass(cls)\n\nType: `method`\n\nRemoves classes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Class names. |\n\nReturns: `HTMLElement` This element.\n\nSeveral classes are separated by spaces or commas.\n\nExample: Remove\n```js\nel.rclass('hidden');\n```\n\n### element.tclass(cls, [value])\n\nType: `method`\n\nToggles classes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Class names. |\n| `value` | `Boolean` | no |  | Force add or remove. |\n\nReturns: `HTMLElement` This element.\n\nWithout `value` each class is switched; `true` adds and `false` removes.\n\nExample: Toggle\n```js\nel.tclass('active', item.id === current);\n```\n\n### element.hclass(cls)\n\nType: `method`\n\nTests a 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: Test\n```js\nif (el.hclass('price'))\n\tconsole.log(el.text());\n```\n\n### element.css(key, [value])\n\nType: `method`\n\nSets inline styles.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | yes |  | Property or object. |\n| `value` | `String` | no |  | Value; empty removes. |\n\nReturns: `HTMLElement` This element.\n\nAccepts a property and a value, or an object of properties. An empty value removes the property from the `style` attribute.\n\nExample: Styles\n```js\nel.css('color', 'red');\nel.css({ width: '100px', display: '' });\n```\n\n### element.remove()\n\nType: `method`\n\nRemoves the element from its parent.\n\nReturns: `HTMLElement` The removed element.\n\nExample: Remove scripts\n```js\ndom.find('script').forEach(function(el) {\n\tel.remove();\n});\n```\n\n### element.append(html)\n\nType: `method`\n\nParses HTML and adds it at the end of the children.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML to add. |\n\nReturns: `HTMLElement` The new element or elements.\n\nReturns the new element, or an array when the HTML has more top-level nodes.\n\nExample: Append\n```js\nul.append('<li>New</li>');\n```\n\n### element.prepend(html)\n\nType: `method`\n\nParses HTML and adds it at the beginning of the children.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML to add. |\n\nReturns: `HTMLElement` The parsed root.\n\nReturns the parsed root of the new HTML.\n\nExample: Prepend\n```js\nbody.prepend('<p>Notice</p>');\n```\n\n### element.text()\n\nType: `method`\n\nReturns the text of the element.\n\nReturns: `String` Text.\n\nText nodes are joined and decoded; text of block elements (`div`, `p`, headings, lists, tables...) is separated by new lines.\n\nExample: Text\n```js\n'<p>Hello <b>world</b></p>'.parseHTML().text(); // 'Hello world'\n```\n\n### element.html([formatted])\n\nType: `method`\n\nReturns the inner HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Indents the output. |\n\nReturns: `String` HTML.\n\n`formatted: true` puts each node on a new line with tabs. `toString(formatted, outer)` does the same and with `outer: true` includes the element itself.\n\nExample: Serialize\n```js\nvar html = dom.html();\nvar pretty = dom.html(true);\n```\n","entries":[{"type":"method","name":"String.prototype.parseHTML()","signature":"String.prototype.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"element.find()","signature":"element.find(selector)","since":"","deprecated":false},{"type":"method","name":"element.parent()","signature":"element.parent()","since":"","deprecated":false},{"type":"method","name":"element.browse()","signature":"element.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"element.attr()","signature":"element.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.attrd()","signature":"element.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.aclass()","signature":"element.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.rclass()","signature":"element.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.tclass()","signature":"element.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"element.hclass()","signature":"element.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.css()","signature":"element.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"element.remove()","signature":"element.remove()","since":"","deprecated":false},{"type":"method","name":"element.append()","signature":"element.append(html)","since":"","deprecated":false},{"type":"method","name":"element.prepend()","signature":"element.prepend(html)","since":"","deprecated":false},{"type":"method","name":"element.text()","signature":"element.text()","since":"","deprecated":false},{"type":"method","name":"element.html()","signature":"element.html([formatted])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCf3kc61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/html-parser/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"HTML- und XML-Parser","summary":"String.prototype.parseHTML(), HTMLElement und die Methoden eines Elements.","markdown":"---\ntitle: HTML- und XML-Parser\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/html-parser/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# HTML- und XML-Parser\n\n> String.prototype.parseHTML(), HTMLElement und die Methoden eines Elements.\n\n## API\n\n### String.prototype.parseHTML([trim])\n\nType: `method`\n\nParst HTML in einen Baum von Elementen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Trimmt Textknoten. |\n\nReturns: `HTMLElement` Das Wurzelelement.\n\nGibt das Wurzelelement zurück; seine `children` sind die Knoten der obersten Ebene. Kommentare werden entfernt. `<script>`, `<style>` und `<template>` behalten ihren Inhalt als Text. Mit `trim: true` werden die Textknoten getrimmt.\n\n`String.prototype.parseXML2()` parst XML auf dieselbe Weise: Jedes Element behält sein Präfix (`soap:Body`), und der Text von Elementen wird von `text()` mit Zeilenumbrüchen verbunden.\n\nExample: Links lesen\n```js\nvar dom = html.parseHTML();\nvar links = dom.find('a').map(function(a) {\n\treturn { url: a.attr('href'), text: a.text() };\n});\n```\n\nExample: XML\n```js\nvar xml = body.parseXML2();\nvar items = xml.find('*:item'); // any prefix\n```\n\n### HTMLElement\n\nType: `class`\n\nEin Element (oder ein Textknoten) eines Baums aus `parseHTML()`.\n\n| Eigenschaft | Beschreibung |\n| --- | --- |\n| `tagName` | Tag-Name in Großbuchstaben, `TEXT` für einen Textknoten |\n| `raw` | Tag-Name wie geschrieben |\n| `prefix` | XML-Präfix mit dem Doppelpunkt, etwa `SOAP:` |\n| `attrs` | Attribute als Objekt |\n| `children` | Kindknoten |\n| `parentNode` | Elternelement |\n| `textContent` | Text eines `TEXT`-Knotens |\n| `innerHTML`, `outerHTML`, `innerText` | Getter für `html()`, das Element mit seinem Tag und `text()` |\n\nExample: Durchlaufen\n```js\nvar dom = '<ul><li>A</li><li>B</li></ul>'.parseHTML();\nvar ul = dom.children[0];\nul.tagName;\t\t   // 'UL'\nul.children.length;   // 2\nul.outerHTML;\t\t // '<ul><li>A</li><li>B</li></ul>'\n```\n\n### element.find(selector)\n\nType: `method`\n\nFindet Elemente unterhalb dieses Elements.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | CSS-ähnlicher Selektor. |\n\nReturns: `Array` Gefundene Elemente.\n\nUnterstützt Tag-Namen, `*`, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (das Element hat das Attribut), `prefix:` und `*:name` für XML, Nachfahren (`div p`), Kinder (`div > p` oder `> p` für direkte Kinder dieses Elements) und mehrere durch Kommas getrennte Selektoren.\n\nDas Ergebnis ist ein Array mit den Methoden `aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()`, `find()`, `html()` (wie `toString()`) und `text()`, die auf alle gefundenen Elemente angewendet werden.\n\nExample: Finden\n```js\ndom.find('table.data > tr td').text();\ndom.find('a').attr('rel', 'nofollow');\n```\n\nExample: Elemente mit einem Attribut\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt]');      // images with an alt text\nvar ids = dom.find('[data-id]');\n```\n\n### element.parent()\n\nType: `method`\n\nGibt das Elternelement zurück.\n\nReturns: `HTMLElement` Das Elternelement.\n\nDasselbe wie `element.parentNode`.\n\nExample: Elternelement\n```js\nvar td = dom.find('td.price')[0];\nvar row = td.parent();\n```\n\n### element.browse(fn, [reverse])\n\nType: `method`\n\nRuft eine Funktion für jeden Knoten unterhalb dieses Knotens auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(node)`; `true` überspringt die Kinder. |\n| `reverse` | `Boolean` | no | `false` | Durchläuft die Elternelemente. |\n\nReturns: `HTMLElement` Dieses Element.\n\n`fn(node)` wird für jeden darunterliegenden Knoten aufgerufen, Textknoten (`tagName` `TEXT`) eingeschlossen, in Tiefensuche. Gib `true` zurück, um die Kinder dieses Elements zu überspringen. Mit `reverse: true` geht sie stattdessen aufwärts durch die Elternelemente.\n\nExample: Sammeln\n```js\nvar tags = {};\ndom.browse(function(el) {\n\ttags[el.tagName] = (tags[el.tagName] || 0) + 1;\n});\n```\n\n### element.attr(name, [value])\n\nType: `method`\n\nLiest oder setzt ein Attribut.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Attributname. |\n| `value` | `Object` | no |  | Neuer Wert. |\n\nReturns: `String` Beim Lesen der Wert, andernfalls das Element.\n\nOhne `value` gibt sie das Attribut zurück. Ein leerer Wert oder `null` entfernt es; andere Werte werden als Strings gespeichert.\n\nExample: Attribute\n```js\nvar href = a.attr('href');\na.attr('rel', 'nofollow');\na.attr('target', null);\n```\n\n### element.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 |  | Name ohne `data-`. |\n| `value` | `Object` | no |  | Neuer Wert. |\n\nReturns: `String` Beim Lesen der Wert, andernfalls das Element.\n\n`attrd('id')` ist `attr('data-id')`.\n\nExample: Daten\n```js\nel.attrd('id', 123);\nel.attrd('id'); // '123'\n```\n\n### element.aclass(cls)\n\nType: `method`\n\nFügt Klassen hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Klassennamen. |\n\nReturns: `HTMLElement` Dieses Element.\n\nMehrere Klassen werden durch Leerzeichen oder Kommas getrennt.\n\nExample: Hinzufügen\n```js\nel.aclass('active selected');\n```\n\n### element.rclass(cls)\n\nType: `method`\n\nEntfernt Klassen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Klassennamen. |\n\nReturns: `HTMLElement` Dieses Element.\n\nMehrere Klassen werden durch Leerzeichen oder Kommas getrennt.\n\nExample: Entfernen\n```js\nel.rclass('hidden');\n```\n\n### element.tclass(cls, [value])\n\nType: `method`\n\nSchaltet Klassen um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Klassennamen. |\n| `value` | `Boolean` | no |  | Hinzufügen oder Entfernen erzwingen. |\n\nReturns: `HTMLElement` Dieses Element.\n\nOhne `value` wird jede Klasse umgeschaltet; `true` fügt hinzu und `false` entfernt.\n\nExample: Umschalten\n```js\nel.tclass('active', item.id === current);\n```\n\n### element.hclass(cls)\n\nType: `method`\n\nPrüft eine 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 (el.hclass('price'))\n\tconsole.log(el.text());\n```\n\n### element.css(key, [value])\n\nType: `method`\n\nSetzt Inline-Styles.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | yes |  | Eigenschaft oder Objekt. |\n| `value` | `String` | no |  | Wert; leer entfernt. |\n\nReturns: `HTMLElement` Dieses Element.\n\nAkzeptiert eine Eigenschaft und einen Wert oder ein Objekt mit Eigenschaften. Ein leerer Wert entfernt die Eigenschaft aus dem `style`-Attribut.\n\nExample: Stile\n```js\nel.css('color', 'red');\nel.css({ width: '100px', display: '' });\n```\n\n### element.remove()\n\nType: `method`\n\nEntfernt das Element aus seinem Elternelement.\n\nReturns: `HTMLElement` Das entfernte Element.\n\nExample: Skripte entfernen\n```js\ndom.find('script').forEach(function(el) {\n\tel.remove();\n});\n```\n\n### element.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 |  | Hinzuzufügendes HTML. |\n\nReturns: `HTMLElement` Das neue Element oder die neuen Elemente.\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\nul.append('<li>New</li>');\n```\n\n### element.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 |  | Hinzuzufügendes HTML. |\n\nReturns: `HTMLElement` Die geparste Wurzel.\n\nGibt die geparste Wurzel des neuen HTML zurück.\n\nExample: Voranstellen\n```js\nbody.prepend('<p>Notice</p>');\n```\n\n### element.text()\n\nType: `method`\n\nGibt den Text des Elements zurück.\n\nReturns: `String` Text.\n\nTextknoten werden verbunden und dekodiert; der Text von Blockelementen (`div`, `p`, Überschriften, Listen, Tabellen...) wird durch Zeilenumbrüche getrennt.\n\nExample: Text\n```js\n'<p>Hello <b>world</b></p>'.parseHTML().text(); // 'Hello world'\n```\n\n### element.html([formatted])\n\nType: `method`\n\nGibt das innere HTML zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Rückt die Ausgabe ein. |\n\nReturns: `String` HTML.\n\n`formatted: true` setzt jeden Knoten mit Tabs in eine neue Zeile. `toString(formatted, outer)` macht dasselbe und schließt mit `outer: true` das Element selbst ein.\n\nExample: Serialisieren\n```js\nvar html = dom.html();\nvar pretty = dom.html(true);\n```\n","entries":[{"type":"method","name":"String.prototype.parseHTML()","signature":"String.prototype.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"element.find()","signature":"element.find(selector)","since":"","deprecated":false},{"type":"method","name":"element.parent()","signature":"element.parent()","since":"","deprecated":false},{"type":"method","name":"element.browse()","signature":"element.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"element.attr()","signature":"element.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.attrd()","signature":"element.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.aclass()","signature":"element.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.rclass()","signature":"element.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.tclass()","signature":"element.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"element.hclass()","signature":"element.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.css()","signature":"element.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"element.remove()","signature":"element.remove()","since":"","deprecated":false},{"type":"method","name":"element.append()","signature":"element.append(html)","since":"","deprecated":false},{"type":"method","name":"element.prepend()","signature":"element.prepend(html)","since":"","deprecated":false},{"type":"method","name":"element.text()","signature":"element.text()","since":"","deprecated":false},{"type":"method","name":"element.html()","signature":"element.html([formatted])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCf3kc61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/html-parser/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Parser de HTML y XML","summary":"String.prototype.parseHTML(), HTMLElement y los métodos de un elemento.","markdown":"---\ntitle: Parser de HTML y XML\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/html-parser/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Parser de HTML y XML\n\n> String.prototype.parseHTML(), HTMLElement y los métodos de un elemento.\n\n## API\n\n### String.prototype.parseHTML([trim])\n\nType: `method`\n\nAnaliza HTML en un árbol de elementos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Recorta los nodos de texto. |\n\nReturns: `HTMLElement` El elemento raíz.\n\nDevuelve el elemento raíz; sus `children` son los nodos de nivel superior. Los comentarios se eliminan. `<script>`, `<style>` y `<template>` mantienen su contenido como texto. Con `trim: true` se recortan los nodos de texto.\n\n`String.prototype.parseXML2()` analiza XML de la misma forma: cada elemento mantiene su prefijo (`soap:Body`) y `text()` une el texto de los elementos con saltos de línea.\n\nExample: Leer enlaces\n```js\nvar dom = html.parseHTML();\nvar links = dom.find('a').map(function(a) {\n\treturn { url: a.attr('href'), text: a.text() };\n});\n```\n\nExample: XML\n```js\nvar xml = body.parseXML2();\nvar items = xml.find('*:item'); // any prefix\n```\n\n### HTMLElement\n\nType: `class`\n\nUn elemento (o un nodo de texto) de un árbol de `parseHTML()`.\n\n| Propiedad | Descripción |\n| --- | --- |\n| `tagName` | Nombre de la etiqueta en mayúsculas, `TEXT` para un nodo de texto |\n| `raw` | Nombre de la etiqueta tal como está escrito |\n| `prefix` | Prefijo XML con los dos puntos, como `SOAP:` |\n| `attrs` | Atributos como objeto |\n| `children` | Nodos hijos |\n| `parentNode` | Elemento padre |\n| `textContent` | Texto de un nodo `TEXT` |\n| `innerHTML`, `outerHTML`, `innerText` | Getters para `html()`, el elemento con su etiqueta, y `text()` |\n\nExample: Recorrer\n```js\nvar dom = '<ul><li>A</li><li>B</li></ul>'.parseHTML();\nvar ul = dom.children[0];\nul.tagName;\t\t   // 'UL'\nul.children.length;   // 2\nul.outerHTML;\t\t // '<ul><li>A</li><li>B</li></ul>'\n```\n\n### element.find(selector)\n\nType: `method`\n\nBusca elementos por debajo de este elemento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Selector de estilo CSS. |\n\nReturns: `Array` Elementos encontrados.\n\nAdmite nombres de etiqueta, `*`, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (el elemento tiene el atributo), `prefix:` y `*:name` para XML, descendientes (`div p`), hijos (`div > p`, o `> p` para los hijos directos de este elemento) y varios selectores separados por comas.\n\nEl resultado es un array con los métodos `aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()`, `find()`, `html()` (lo mismo que `toString()`) y `text()`, que se aplican a todos los elementos encontrados.\n\nExample: Buscar\n```js\ndom.find('table.data > tr td').text();\ndom.find('a').attr('rel', 'nofollow');\n```\n\nExample: Elementos con un atributo\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt]');      // images with an alt text\nvar ids = dom.find('[data-id]');\n```\n\n### element.parent()\n\nType: `method`\n\nDevuelve el elemento padre.\n\nReturns: `HTMLElement` El padre.\n\nLo mismo que `element.parentNode`.\n\nExample: Padre\n```js\nvar td = dom.find('td.price')[0];\nvar row = td.parent();\n```\n\n### element.browse(fn, [reverse])\n\nType: `method`\n\nLlama a una función para cada nodo por debajo de este.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(node)`; `true` omite los hijos. |\n| `reverse` | `Boolean` | no | `false` | Recorre los padres. |\n\nReturns: `HTMLElement` Este elemento.\n\n`fn(node)` se llama para cada nodo por debajo, incluidos los nodos de texto (`tagName` `TEXT`), en profundidad. Devuelve `true` para omitir los hijos de ese elemento. Con `reverse: true` sube en cambio por los padres.\n\nExample: Recopilar\n```js\nvar tags = {};\ndom.browse(function(el) {\n\ttags[el.tagName] = (tags[el.tagName] || 0) + 1;\n});\n```\n\n### element.attr(name, [value])\n\nType: `method`\n\nLee o asigna un atributo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del atributo. |\n| `value` | `Object` | no |  | Nuevo valor. |\n\nReturns: `String` El valor al leer; si no, el elemento.\n\nSin `value` devuelve el atributo. Un valor vacío o `null` lo elimina; los demás valores se guardan como cadenas.\n\nExample: Atributos\n```js\nvar href = a.attr('href');\na.attr('rel', 'nofollow');\na.attr('target', null);\n```\n\n### element.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 |  | Nombre sin `data-`. |\n| `value` | `Object` | no |  | Nuevo valor. |\n\nReturns: `String` El valor al leer; si no, el elemento.\n\n`attrd('id')` es `attr('data-id')`.\n\nExample: Datos\n```js\nel.attrd('id', 123);\nel.attrd('id'); // '123'\n```\n\n### element.aclass(cls)\n\nType: `method`\n\nAñade clases.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Nombres de clase. |\n\nReturns: `HTMLElement` Este elemento.\n\nVarias clases se separan con espacios o comas.\n\nExample: Añadir\n```js\nel.aclass('active selected');\n```\n\n### element.rclass(cls)\n\nType: `method`\n\nElimina clases.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Nombres de clase. |\n\nReturns: `HTMLElement` Este elemento.\n\nVarias clases se separan con espacios o comas.\n\nExample: Eliminar\n```js\nel.rclass('hidden');\n```\n\n### element.tclass(cls, [value])\n\nType: `method`\n\nAlterna clases.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Nombres de clase. |\n| `value` | `Boolean` | no |  | Fuerza añadir o eliminar. |\n\nReturns: `HTMLElement` Este elemento.\n\nSin `value` cada clase se alterna; `true` añade y `false` elimina.\n\nExample: Alternar\n```js\nel.tclass('active', item.id === current);\n```\n\n### element.hclass(cls)\n\nType: `method`\n\nComprueba una clase.\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 (el.hclass('price'))\n\tconsole.log(el.text());\n```\n\n### element.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 |  | Propiedad u objeto. |\n| `value` | `String` | no |  | Valor; vacío elimina. |\n\nReturns: `HTMLElement` Este elemento.\n\nAcepta una propiedad y un valor, o un objeto de propiedades. Un valor vacío elimina la propiedad del atributo `style`.\n\nExample: Estilos\n```js\nel.css('color', 'red');\nel.css({ width: '100px', display: '' });\n```\n\n### element.remove()\n\nType: `method`\n\nElimina el elemento de su padre.\n\nReturns: `HTMLElement` El elemento eliminado.\n\nExample: Eliminar scripts\n```js\ndom.find('script').forEach(function(el) {\n\tel.remove();\n});\n```\n\n### element.append(html)\n\nType: `method`\n\nAnaliza HTML y lo añade al final de los hijos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML a añadir. |\n\nReturns: `HTMLElement` El nuevo elemento o elementos.\n\nDevuelve el nuevo elemento, o un array cuando el HTML tiene varios nodos de primer nivel.\n\nExample: Añadir al final\n```js\nul.append('<li>New</li>');\n```\n\n### element.prepend(html)\n\nType: `method`\n\nAnaliza HTML y lo añade al principio de los hijos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML a añadir. |\n\nReturns: `HTMLElement` La raíz analizada.\n\nDevuelve la raíz analizada del nuevo HTML.\n\nExample: Añadir al principio\n```js\nbody.prepend('<p>Notice</p>');\n```\n\n### element.text()\n\nType: `method`\n\nDevuelve el texto del elemento.\n\nReturns: `String` Texto.\n\nLos nodos de texto se unen y se decodifican; el texto de los elementos de bloque (`div`, `p`, encabezados, listas, tablas...) se separa con saltos de línea.\n\nExample: Texto\n```js\n'<p>Hello <b>world</b></p>'.parseHTML().text(); // 'Hello world'\n```\n\n### element.html([formatted])\n\nType: `method`\n\nDevuelve el HTML interior.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Sangra la salida. |\n\nReturns: `String` HTML.\n\n`formatted: true` pone cada nodo en una línea nueva con tabuladores. `toString(formatted, outer)` hace lo mismo y con `outer: true` incluye el propio elemento.\n\nExample: Serializar\n```js\nvar html = dom.html();\nvar pretty = dom.html(true);\n```\n","entries":[{"type":"method","name":"String.prototype.parseHTML()","signature":"String.prototype.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"element.find()","signature":"element.find(selector)","since":"","deprecated":false},{"type":"method","name":"element.parent()","signature":"element.parent()","since":"","deprecated":false},{"type":"method","name":"element.browse()","signature":"element.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"element.attr()","signature":"element.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.attrd()","signature":"element.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.aclass()","signature":"element.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.rclass()","signature":"element.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.tclass()","signature":"element.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"element.hclass()","signature":"element.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.css()","signature":"element.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"element.remove()","signature":"element.remove()","since":"","deprecated":false},{"type":"method","name":"element.append()","signature":"element.append(html)","since":"","deprecated":false},{"type":"method","name":"element.prepend()","signature":"element.prepend(html)","since":"","deprecated":false},{"type":"method","name":"element.text()","signature":"element.text()","since":"","deprecated":false},{"type":"method","name":"element.html()","signature":"element.html([formatted])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCf3kc61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/html-parser/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Parseur HTML et XML","summary":"String.prototype.parseHTML(), HTMLElement et les méthodes d'un élément.","markdown":"---\ntitle: Parseur HTML et XML\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/html-parser/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Parseur HTML et XML\n\n> String.prototype.parseHTML(), HTMLElement et les méthodes d'un élément.\n\n## API\n\n### String.prototype.parseHTML([trim])\n\nType: `method`\n\nAnalyse du HTML en un arbre d'éléments.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Supprime les espaces des nœuds texte. |\n\nReturns: `HTMLElement` L'élément racine.\n\nRenvoie l'élément racine ; ses `children` sont les nœuds de premier niveau. Les commentaires sont supprimés. `<script>`, `<style>` et `<template>` conservent leur contenu sous forme de texte. Avec `trim: true`, les espaces des nœuds texte sont supprimés.\n\n`String.prototype.parseXML2()` analyse le XML de la même façon : chaque élément conserve son préfixe (`soap:Body`) et le texte des éléments est joint par des sauts de ligne par `text()`.\n\nExample: Lire les liens\n```js\nvar dom = html.parseHTML();\nvar links = dom.find('a').map(function(a) {\n\treturn { url: a.attr('href'), text: a.text() };\n});\n```\n\nExample: XML\n```js\nvar xml = body.parseXML2();\nvar items = xml.find('*:item'); // any prefix\n```\n\n### HTMLElement\n\nType: `class`\n\nUn élément (ou un nœud texte) d'un arbre issu de `parseHTML()`.\n\n| Propriété | Description |\n| --- | --- |\n| `tagName` | Nom de la balise en majuscules, `TEXT` pour un nœud texte |\n| `raw` | Nom de la balise tel qu'écrit |\n| `prefix` | Préfixe XML avec les deux-points, comme `SOAP:` |\n| `attrs` | Attributs sous forme d'objet |\n| `children` | Nœuds enfants |\n| `parentNode` | Élément parent |\n| `textContent` | Texte d'un nœud `TEXT` |\n| `innerHTML`, `outerHTML`, `innerText` | Getters pour `html()`, l'élément avec sa balise, et `text()` |\n\nExample: Parcourir\n```js\nvar dom = '<ul><li>A</li><li>B</li></ul>'.parseHTML();\nvar ul = dom.children[0];\nul.tagName;\t\t   // 'UL'\nul.children.length;   // 2\nul.outerHTML;\t\t // '<ul><li>A</li><li>B</li></ul>'\n```\n\n### element.find(selector)\n\nType: `method`\n\nTrouve des éléments sous cet élément.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Sélecteur de type CSS. |\n\nReturns: `Array` Les éléments trouvés.\n\nPrend en charge les noms de balises, `*`, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (l'élément a l'attribut), `prefix:` et `*:name` pour le XML, les descendants (`div p`), les enfants (`div > p`, ou `> p` pour les enfants directs de cet élément) et plusieurs sélecteurs séparés par des virgules.\n\nLe résultat est un tableau avec les méthodes `aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()`, `find()`, `html()` (identique à `toString()`) et `text()`, appliquées à tous les éléments trouvés.\n\nExample: Trouver\n```js\ndom.find('table.data > tr td').text();\ndom.find('a').attr('rel', 'nofollow');\n```\n\nExample: Éléments avec un attribut\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt]');      // images with an alt text\nvar ids = dom.find('[data-id]');\n```\n\n### element.parent()\n\nType: `method`\n\nRenvoie l'élément parent.\n\nReturns: `HTMLElement` Le parent.\n\nIdentique à `element.parentNode`.\n\nExample: Parent\n```js\nvar td = dom.find('td.price')[0];\nvar row = td.parent();\n```\n\n### element.browse(fn, [reverse])\n\nType: `method`\n\nAppelle une fonction pour chaque nœud situé sous celui-ci.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(node)` ; `true` ignore les enfants. |\n| `reverse` | `Boolean` | no | `false` | Parcourt les parents. |\n\nReturns: `HTMLElement` Cet élément.\n\n`fn(node)` est appelée pour chaque nœud situé en dessous, nœuds texte (`tagName` `TEXT`) compris, en profondeur d'abord. Renvoie `true` pour ignorer les enfants de cet élément. Avec `reverse: true`, elle remonte plutôt à travers les parents.\n\nExample: Collecter\n```js\nvar tags = {};\ndom.browse(function(el) {\n\ttags[el.tagName] = (tags[el.tagName] || 0) + 1;\n});\n```\n\n### element.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 |  | Nom de l'attribut. |\n| `value` | `Object` | no |  | Nouvelle valeur. |\n\nReturns: `String` La valeur en lecture, sinon l'élément.\n\nSans `value`, elle renvoie l'attribut. Une valeur vide ou `null` le supprime ; les autres valeurs sont stockées sous forme de chaînes.\n\nExample: Attributs\n```js\nvar href = a.attr('href');\na.attr('rel', 'nofollow');\na.attr('target', null);\n```\n\n### element.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 |  | Nom sans `data-`. |\n| `value` | `Object` | no |  | Nouvelle valeur. |\n\nReturns: `String` La valeur en lecture, sinon l'élément.\n\n`attrd('id')` équivaut à `attr('data-id')`.\n\nExample: Données\n```js\nel.attrd('id', 123);\nel.attrd('id'); // '123'\n```\n\n### element.aclass(cls)\n\nType: `method`\n\nAjoute des classes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Noms de classes. |\n\nReturns: `HTMLElement` Cet élément.\n\nPlusieurs classes sont séparées par des espaces ou des virgules.\n\nExample: Ajouter\n```js\nel.aclass('active selected');\n```\n\n### element.rclass(cls)\n\nType: `method`\n\nSupprime des classes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Noms de classes. |\n\nReturns: `HTMLElement` Cet élément.\n\nPlusieurs classes sont séparées par des espaces ou des virgules.\n\nExample: Supprimer\n```js\nel.rclass('hidden');\n```\n\n### element.tclass(cls, [value])\n\nType: `method`\n\nBascule des classes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Noms de classes. |\n| `value` | `Boolean` | no |  | Force l'ajout ou la suppression. |\n\nReturns: `HTMLElement` Cet élément.\n\nSans `value`, chaque classe est basculée ; `true` ajoute et `false` supprime.\n\nExample: Basculer\n```js\nel.tclass('active', item.id === current);\n```\n\n### element.hclass(cls)\n\nType: `method`\n\nTeste une classe.\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: Tester\n```js\nif (el.hclass('price'))\n\tconsole.log(el.text());\n```\n\n### element.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 |  | Propriété ou objet. |\n| `value` | `String` | no |  | Valeur ; vide supprime. |\n\nReturns: `HTMLElement` Cet élément.\n\nAccepte une propriété et une valeur, ou un objet de propriétés. Une valeur vide supprime la propriété de l'attribut `style`.\n\nExample: Styles\n```js\nel.css('color', 'red');\nel.css({ width: '100px', display: '' });\n```\n\n### element.remove()\n\nType: `method`\n\nSupprime l'élément de son parent.\n\nReturns: `HTMLElement` L'élément supprimé.\n\nExample: Supprimer les scripts\n```js\ndom.find('script').forEach(function(el) {\n\tel.remove();\n});\n```\n\n### element.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` Le ou les nouveaux éléments.\n\nRenvoie le nouvel élément, ou un tableau lorsque le HTML contient plusieurs nœuds de premier niveau.\n\nExample: Ajouter à la fin\n```js\nul.append('<li>New</li>');\n```\n\n### element.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` La racine analysée.\n\nRenvoie la racine analysée du nouveau HTML.\n\nExample: Ajouter au début\n```js\nbody.prepend('<p>Notice</p>');\n```\n\n### element.text()\n\nType: `method`\n\nRenvoie le texte de l'élément.\n\nReturns: `String` Le texte.\n\nLes nœuds texte sont joints et décodés ; le texte des éléments de bloc (`div`, `p`, titres, listes, tableaux...) est séparé par des sauts de ligne.\n\nExample: Texte\n```js\n'<p>Hello <b>world</b></p>'.parseHTML().text(); // 'Hello world'\n```\n\n### element.html([formatted])\n\nType: `method`\n\nRenvoie le HTML intérieur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Indente le résultat. |\n\nReturns: `String` Du HTML.\n\n`formatted: true` place chaque nœud sur une nouvelle ligne avec des tabulations. `toString(formatted, outer)` fait de même et, avec `outer: true`, inclut l'élément lui-même.\n\nExample: Sérialiser\n```js\nvar html = dom.html();\nvar pretty = dom.html(true);\n```\n","entries":[{"type":"method","name":"String.prototype.parseHTML()","signature":"String.prototype.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"element.find()","signature":"element.find(selector)","since":"","deprecated":false},{"type":"method","name":"element.parent()","signature":"element.parent()","since":"","deprecated":false},{"type":"method","name":"element.browse()","signature":"element.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"element.attr()","signature":"element.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.attrd()","signature":"element.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.aclass()","signature":"element.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.rclass()","signature":"element.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.tclass()","signature":"element.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"element.hclass()","signature":"element.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.css()","signature":"element.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"element.remove()","signature":"element.remove()","since":"","deprecated":false},{"type":"method","name":"element.append()","signature":"element.append(html)","since":"","deprecated":false},{"type":"method","name":"element.prepend()","signature":"element.prepend(html)","since":"","deprecated":false},{"type":"method","name":"element.text()","signature":"element.text()","since":"","deprecated":false},{"type":"method","name":"element.html()","signature":"element.html([formatted])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCf3kc61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/html-parser/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Parser HTML e XML","summary":"String.prototype.parseHTML(), HTMLElement e i metodi di un elemento.","markdown":"---\ntitle: Parser HTML e XML\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/html-parser/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Parser HTML e XML\n\n> String.prototype.parseHTML(), HTMLElement e i metodi di un elemento.\n\n## API\n\n### String.prototype.parseHTML([trim])\n\nType: `method`\n\nAnalizza l'HTML in un albero di elementi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Ripulisce dagli spazi i nodi di testo. |\n\nReturns: `HTMLElement` L'elemento radice.\n\nRestituisce l'elemento radice; i suoi `children` sono i nodi di primo livello. I commenti vengono rimossi. `<script>`, `<style>` e `<template>` mantengono il loro contenuto come testo. Con `trim: true` i nodi di testo vengono ripuliti dagli spazi.\n\n`String.prototype.parseXML2()` analizza l'XML allo stesso modo: ogni elemento mantiene il suo prefisso (`soap:Body`) e il testo degli elementi viene unito con a capo da `text()`.\n\nExample: Leggere i link\n```js\nvar dom = html.parseHTML();\nvar links = dom.find('a').map(function(a) {\n\treturn { url: a.attr('href'), text: a.text() };\n});\n```\n\nExample: XML\n```js\nvar xml = body.parseXML2();\nvar items = xml.find('*:item'); // any prefix\n```\n\n### HTMLElement\n\nType: `class`\n\nUn elemento (o un nodo di testo) di un albero di `parseHTML()`.\n\n| Proprietà | Descrizione |\n| --- | --- |\n| `tagName` | Nome del tag in maiuscolo, `TEXT` per un nodo di testo |\n| `raw` | Nome del tag come è scritto |\n| `prefix` | Prefisso XML con i due punti, come `SOAP:` |\n| `attrs` | Attributi come oggetto |\n| `children` | Nodi figli |\n| `parentNode` | Elemento genitore |\n| `textContent` | Testo di un nodo `TEXT` |\n| `innerHTML`, `outerHTML`, `innerText` | Getter per `html()`, l'elemento con il suo tag, e `text()` |\n\nExample: Attraversare\n```js\nvar dom = '<ul><li>A</li><li>B</li></ul>'.parseHTML();\nvar ul = dom.children[0];\nul.tagName;\t\t   // 'UL'\nul.children.length;   // 2\nul.outerHTML;\t\t // '<ul><li>A</li><li>B</li></ul>'\n```\n\n### element.find(selector)\n\nType: `method`\n\nTrova gli elementi sotto questo elemento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Selettore simile a CSS. |\n\nReturns: `Array` Elementi trovati.\n\nSupporta nomi di tag, `*`, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (l'elemento ha l'attributo), `prefix:` e `*:name` per XML, discendenti (`div p`), figli (`div > p`, o `> p` per i figli diretti di questo elemento) e più selettori separati da virgole.\n\nIl risultato è un array con i metodi `aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()`, `find()`, `html()` (uguale a `toString()`) e `text()`, applicati a tutti gli elementi trovati.\n\nExample: Trovare\n```js\ndom.find('table.data > tr td').text();\ndom.find('a').attr('rel', 'nofollow');\n```\n\nExample: Elementi con un attributo\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt]');      // images with an alt text\nvar ids = dom.find('[data-id]');\n```\n\n### element.parent()\n\nType: `method`\n\nRestituisce l'elemento genitore.\n\nReturns: `HTMLElement` Il genitore.\n\nUguale a `element.parentNode`.\n\nExample: Genitore\n```js\nvar td = dom.find('td.price')[0];\nvar row = td.parent();\n```\n\n### element.browse(fn, [reverse])\n\nType: `method`\n\nChiama una funzione per ogni nodo sotto questo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(node)`; `true` salta i figli. |\n| `reverse` | `Boolean` | no | `false` | Attraversa i genitori. |\n\nReturns: `HTMLElement` Questo elemento.\n\n`fn(node)` viene chiamata per ogni nodo sottostante, nodi di testo (`tagName` `TEXT`) inclusi, in profondità. Restituisci `true` per saltare i figli di quell'elemento. Con `reverse: true` risale invece attraverso i genitori.\n\nExample: Raccogliere\n```js\nvar tags = {};\ndom.browse(function(el) {\n\ttags[el.tagName] = (tags[el.tagName] || 0) + 1;\n});\n```\n\n### element.attr(name, [value])\n\nType: `method`\n\nLegge o imposta un attributo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'attributo. |\n| `value` | `Object` | no |  | Nuovo valore. |\n\nReturns: `String` Il valore in lettura, altrimenti l'elemento.\n\nSenza `value` restituisce l'attributo. Un valore vuoto o `null` lo rimuove; gli altri valori vengono salvati come stringhe.\n\nExample: Attributi\n```js\nvar href = a.attr('href');\na.attr('rel', 'nofollow');\na.attr('target', null);\n```\n\n### element.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 |  | Nome senza `data-`. |\n| `value` | `Object` | no |  | Nuovo valore. |\n\nReturns: `String` Il valore in lettura, altrimenti l'elemento.\n\n`attrd('id')` equivale a `attr('data-id')`.\n\nExample: Dati\n```js\nel.attrd('id', 123);\nel.attrd('id'); // '123'\n```\n\n### element.aclass(cls)\n\nType: `method`\n\nAggiunge classi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Nomi delle classi. |\n\nReturns: `HTMLElement` Questo elemento.\n\nPiù classi sono separate da spazi o virgole.\n\nExample: Aggiungere\n```js\nel.aclass('active selected');\n```\n\n### element.rclass(cls)\n\nType: `method`\n\nRimuove classi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Nomi delle classi. |\n\nReturns: `HTMLElement` Questo elemento.\n\nPiù classi sono separate da spazi o virgole.\n\nExample: Rimuovere\n```js\nel.rclass('hidden');\n```\n\n### element.tclass(cls, [value])\n\nType: `method`\n\nAlterna classi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Nomi delle classi. |\n| `value` | `Boolean` | no |  | Forza l'aggiunta o la rimozione. |\n\nReturns: `HTMLElement` Questo elemento.\n\nSenza `value` ogni classe viene alternata; `true` aggiunge e `false` rimuove.\n\nExample: Alternare\n```js\nel.tclass('active', item.id === current);\n```\n\n### element.hclass(cls)\n\nType: `method`\n\nVerifica una classe.\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: Verificare\n```js\nif (el.hclass('price'))\n\tconsole.log(el.text());\n```\n\n### element.css(key, [value])\n\nType: `method`\n\nImposta gli stili inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | yes |  | Proprietà o oggetto. |\n| `value` | `String` | no |  | Valore; vuoto rimuove. |\n\nReturns: `HTMLElement` Questo elemento.\n\nAccetta una proprietà e un valore, o un oggetto di proprietà. Un valore vuoto rimuove la proprietà dall'attributo `style`.\n\nExample: Stili\n```js\nel.css('color', 'red');\nel.css({ width: '100px', display: '' });\n```\n\n### element.remove()\n\nType: `method`\n\nRimuove l'elemento dal suo genitore.\n\nReturns: `HTMLElement` L'elemento rimosso.\n\nExample: Rimuovere gli script\n```js\ndom.find('script').forEach(function(el) {\n\tel.remove();\n});\n```\n\n### element.append(html)\n\nType: `method`\n\nAnalizza l'HTML e lo aggiunge alla fine dei figli.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML da aggiungere. |\n\nReturns: `HTMLElement` Il nuovo elemento o i nuovi elementi.\n\nRestituisce il nuovo elemento, oppure un array quando l'HTML ha più nodi di primo livello.\n\nExample: Accodare\n```js\nul.append('<li>New</li>');\n```\n\n### element.prepend(html)\n\nType: `method`\n\nAnalizza l'HTML e lo aggiunge all'inizio dei figli.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML da aggiungere. |\n\nReturns: `HTMLElement` La radice analizzata.\n\nRestituisce la radice analizzata del nuovo HTML.\n\nExample: Anteporre\n```js\nbody.prepend('<p>Notice</p>');\n```\n\n### element.text()\n\nType: `method`\n\nRestituisce il testo dell'elemento.\n\nReturns: `String` Testo.\n\nI nodi di testo vengono uniti e decodificati; il testo degli elementi di blocco (`div`, `p`, titoli, elenchi, tabelle...) è separato da a capo.\n\nExample: Testo\n```js\n'<p>Hello <b>world</b></p>'.parseHTML().text(); // 'Hello world'\n```\n\n### element.html([formatted])\n\nType: `method`\n\nRestituisce l'HTML interno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Indenta l'output. |\n\nReturns: `String` HTML.\n\n`formatted: true` mette ogni nodo su una nuova riga con tabulazioni. `toString(formatted, outer)` fa lo stesso e con `outer: true` include l'elemento stesso.\n\nExample: Serializzare\n```js\nvar html = dom.html();\nvar pretty = dom.html(true);\n```\n","entries":[{"type":"method","name":"String.prototype.parseHTML()","signature":"String.prototype.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"element.find()","signature":"element.find(selector)","since":"","deprecated":false},{"type":"method","name":"element.parent()","signature":"element.parent()","since":"","deprecated":false},{"type":"method","name":"element.browse()","signature":"element.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"element.attr()","signature":"element.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.attrd()","signature":"element.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.aclass()","signature":"element.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.rclass()","signature":"element.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.tclass()","signature":"element.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"element.hclass()","signature":"element.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.css()","signature":"element.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"element.remove()","signature":"element.remove()","since":"","deprecated":false},{"type":"method","name":"element.append()","signature":"element.append(html)","since":"","deprecated":false},{"type":"method","name":"element.prepend()","signature":"element.prepend(html)","since":"","deprecated":false},{"type":"method","name":"element.text()","signature":"element.text()","since":"","deprecated":false},{"type":"method","name":"element.html()","signature":"element.html([formatted])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmCf3kc61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/html-parser/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"HTML a XML parser","summary":"String.prototype.parseHTML(), HTMLElement a metódy prvku.","markdown":"---\ntitle: HTML a XML parser\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/html-parser/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# HTML a XML parser\n\n> String.prototype.parseHTML(), HTMLElement a metódy prvku.\n\n## API\n\n### String.prototype.parseHTML([trim])\n\nType: `method`\n\nSparsuje HTML do stromu elementov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Oreže textové uzly. |\n\nReturns: `HTMLElement` Koreňový element.\n\nVráti koreňový element; jeho `children` sú uzly najvyššej úrovne. Komentáre sa odstránia. `<script>`, `<style>` a `<template>` si ponechajú svoj obsah ako text. S `trim: true` sa textové uzly orežú.\n\n`String.prototype.parseXML2()` parsuje XML rovnakým spôsobom: každý element si ponechá svoj prefix (`soap:Body`) a text elementov spája `text()` novými riadkami.\n\nExample: Čítanie odkazov\n```js\nvar dom = html.parseHTML();\nvar links = dom.find('a').map(function(a) {\n\treturn { url: a.attr('href'), text: a.text() };\n});\n```\n\nExample: XML\n```js\nvar xml = body.parseXML2();\nvar items = xml.find('*:item'); // any prefix\n```\n\n### HTMLElement\n\nType: `class`\n\nElement (alebo textový uzol) stromu z `parseHTML()`.\n\n| Vlastnosť | Popis |\n| --- | --- |\n| `tagName` | Názov tagu veľkými písmenami, `TEXT` pre textový uzol |\n| `raw` | Názov tagu tak, ako je zapísaný |\n| `prefix` | XML prefix s dvojbodkou, napríklad `SOAP:` |\n| `attrs` | Atribúty ako objekt |\n| `children` | Podriadené uzly |\n| `parentNode` | Rodičovský element |\n| `textContent` | Text uzla `TEXT` |\n| `innerHTML`, `outerHTML`, `innerText` | Gettery pre `html()`, element s jeho tagom a `text()` |\n\nExample: Prechádzanie\n```js\nvar dom = '<ul><li>A</li><li>B</li></ul>'.parseHTML();\nvar ul = dom.children[0];\nul.tagName;\t\t   // 'UL'\nul.children.length;   // 2\nul.outerHTML;\t\t // '<ul><li>A</li><li>B</li></ul>'\n```\n\n### element.find(selector)\n\nType: `method`\n\nNájde elementy pod týmto elementom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Selektor podobný CSS. |\n\nReturns: `Array` Nájdené elementy.\n\nPodporuje názvy tagov, `*`, `#id`, `.class`, `[attr=\"value\"]`, `[attr]` (element má daný atribút), `prefix:` a `*:name` pre XML, potomkov (`div p`), deti (`div > p` alebo `> p` pre priame deti tohto elementu) a viac selektorov oddelených čiarkami.\n\nVýsledok je pole s metódami `aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()`, `find()`, `html()` (to isté ako `toString()`) a `text()`, ktoré sa použijú na všetky nájdené elementy.\n\nExample: Hľadanie\n```js\ndom.find('table.data > tr td').text();\ndom.find('a').attr('rel', 'nofollow');\n```\n\nExample: Elementy s atribútom\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt]');      // images with an alt text\nvar ids = dom.find('[data-id]');\n```\n\n### element.parent()\n\nType: `method`\n\nVráti rodičovský element.\n\nReturns: `HTMLElement` Rodič.\n\nTo isté ako `element.parentNode`.\n\nExample: Rodič\n```js\nvar td = dom.find('td.price')[0];\nvar row = td.parent();\n```\n\n### element.browse(fn, [reverse])\n\nType: `method`\n\nZavolá funkciu pre každý uzol pod týmto uzlom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(node)`; `true` preskočí deti. |\n| `reverse` | `Boolean` | no | `false` | Prechádza rodičov. |\n\nReturns: `HTMLElement` Tento element.\n\n`fn(node)` sa zavolá pre každý uzol pod ním, vrátane textových uzlov (`tagName` `TEXT`), do hĺbky. Vráť `true`, ak chceš preskočiť deti daného elementu. S `reverse: true` namiesto toho prechádza nahor cez rodičov.\n\nExample: Zber\n```js\nvar tags = {};\ndom.browse(function(el) {\n\ttags[el.tagName] = (tags[el.tagName] || 0) + 1;\n});\n```\n\n### element.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` | `Object` | no |  | Nová hodnota. |\n\nReturns: `String` Hodnota pri čítaní, inak element.\n\nBez `value` vráti atribút. Prázdna hodnota alebo `null` ho odstráni; ostatné hodnoty sa uložia ako reťazce.\n\nExample: Atribúty\n```js\nvar href = a.attr('href');\na.attr('rel', 'nofollow');\na.attr('target', null);\n```\n\n### element.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` | `Object` | no |  | Nová hodnota. |\n\nReturns: `String` Hodnota pri čítaní, inak element.\n\n`attrd('id')` je `attr('data-id')`.\n\nExample: Dáta\n```js\nel.attrd('id', 123);\nel.attrd('id'); // '123'\n```\n\n### element.aclass(cls)\n\nType: `method`\n\nPridá triedy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Názvy tried. |\n\nReturns: `HTMLElement` Tento element.\n\nViacero tried sa oddeľuje medzerami alebo čiarkami.\n\nExample: Pridanie\n```js\nel.aclass('active selected');\n```\n\n### element.rclass(cls)\n\nType: `method`\n\nOdstráni triedy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Názvy tried. |\n\nReturns: `HTMLElement` Tento element.\n\nViacero tried sa oddeľuje medzerami alebo čiarkami.\n\nExample: Odstránenie\n```js\nel.rclass('hidden');\n```\n\n### element.tclass(cls, [value])\n\nType: `method`\n\nPrepne triedy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Názvy tried. |\n| `value` | `Boolean` | no |  | Vynútené pridanie alebo odstránenie. |\n\nReturns: `HTMLElement` Tento element.\n\nBez `value` sa každá trieda prepne; `true` pridá a `false` odstráni.\n\nExample: Prepnutie\n```js\nel.tclass('active', item.id === current);\n```\n\n### element.hclass(cls)\n\nType: `method`\n\nOtestuje 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: Test\n```js\nif (el.hclass('price'))\n\tconsole.log(el.text());\n```\n\n### element.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. |\n| `value` | `String` | no |  | Hodnota; prázdna odstráni. |\n\nReturns: `HTMLElement` Tento element.\n\nPrijíma vlastnosť a hodnotu, alebo objekt vlastností. Prázdna hodnota odstráni vlastnosť z atribútu `style`.\n\nExample: Štýly\n```js\nel.css('color', 'red');\nel.css({ width: '100px', display: '' });\n```\n\n### element.remove()\n\nType: `method`\n\nOdstráni element z jeho rodiča.\n\nReturns: `HTMLElement` Odstránený element.\n\nExample: Odstránenie skriptov\n```js\ndom.find('script').forEach(function(el) {\n\tel.remove();\n});\n```\n\n### element.append(html)\n\nType: `method`\n\nSparsuje HTML a pridá ho na koniec detí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML na pridanie. |\n\nReturns: `HTMLElement` Nový element alebo elementy.\n\nVráti nový element alebo pole, keď má HTML viac uzlov najvyššej úrovne.\n\nExample: Pripojenie na koniec\n```js\nul.append('<li>New</li>');\n```\n\n### element.prepend(html)\n\nType: `method`\n\nSparsuje HTML a pridá ho na začiatok detí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML na pridanie. |\n\nReturns: `HTMLElement` Sparsovaný koreň.\n\nVráti sparsovaný koreň nového HTML.\n\nExample: Vloženie na začiatok\n```js\nbody.prepend('<p>Notice</p>');\n```\n\n### element.text()\n\nType: `method`\n\nVráti text elementu.\n\nReturns: `String` Text.\n\nTextové uzly sa spoja a dekódujú; text blokových elementov (`div`, `p`, nadpisy, zoznamy, tabuľky...) sa oddelí novými riadkami.\n\nExample: Text\n```js\n'<p>Hello <b>world</b></p>'.parseHTML().text(); // 'Hello world'\n```\n\n### element.html([formatted])\n\nType: `method`\n\nVráti vnútorné HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Odsadí výstup. |\n\nReturns: `String` HTML.\n\n`formatted: true` umiestni každý uzol na nový riadok s tabulátormi. `toString(formatted, outer)` robí to isté a s `outer: true` zahrnie aj samotný element.\n\nExample: Serializácia\n```js\nvar html = dom.html();\nvar pretty = dom.html(true);\n```\n","entries":[{"type":"method","name":"String.prototype.parseHTML()","signature":"String.prototype.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"element.find()","signature":"element.find(selector)","since":"","deprecated":false},{"type":"method","name":"element.parent()","signature":"element.parent()","since":"","deprecated":false},{"type":"method","name":"element.browse()","signature":"element.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"element.attr()","signature":"element.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.attrd()","signature":"element.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"element.aclass()","signature":"element.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.rclass()","signature":"element.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.tclass()","signature":"element.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"element.hclass()","signature":"element.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"element.css()","signature":"element.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"element.remove()","signature":"element.remove()","since":"","deprecated":false},{"type":"method","name":"element.append()","signature":"element.append(html)","since":"","deprecated":false},{"type":"method","name":"element.prepend()","signature":"element.prepend(html)","since":"","deprecated":false},{"type":"method","name":"element.text()","signature":"element.text()","since":"","deprecated":false},{"type":"method","name":"element.html()","signature":"element.html([formatted])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JafiZW3hK60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/macros/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Macros","summary":"NEWMACRO() and the macro syntax.","markdown":"---\ntitle: Macros\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/macros/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Macros\n\n> NEWMACRO() and the macro syntax.\n\n## API\n\n### NEWMACRO(code, [nocompile], [isasync])\n\nType: `method`\n\nCompiles a macro into a function `fn(model, helpers)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | The macro, one command per line (or separated by `;`). |\n| `nocompile` | `Boolean` | no | `false` | Returns the JavaScript code instead of a function. |\n| `isasync` | `Boolean` | no | `false` | Makes an async function. |\n\nReturns: `Function` `function(model, [helpers])`, or a string with `nocompile`.\n\nThe function returns the value of the first `RETURN` that runs, or `undefined`. Words are read from `model` and `name(...)` calls `helpers.name` with the model as `this`. With `isasync` the function is async and every helper call is awaited. With `nocompile` you get the generated JavaScript as a string, which is useful to check a rule.\n\nExample: Shipping\n```js\nvar shipping = NEWMACRO('IF weight > 10\\n\\tRETURN 15\\nELSE IF weight > 2\\n\\tRETURN 8\\nFI\\nRETURN 4');\nshipping({ weight: 5 }); // 8\n```\n\nExample: Async helpers\n```js\nvar fn = NEWMACRO('RETURN rate(currency) * price', false, true);\nvar value = await fn({ price: 10, currency: 'EUR' }, { rate: async function(code) { return 1.1; } });\n```\n\n### Macro syntax\n\nType: `type`\n\nCommands and values of `NEWMACRO()`.\n\n| Syntax | Meaning |\n| --- | --- |\n| `IF condition` … `ELSE IF condition` … `ELSE` … `FI` | Conditions; `FI` closes them |\n| `RETURN expression` | Returns a value |\n| `AND`, `OR` | `&&`, `\\|\\|` |\n| `==`, `!=`, `>`, `>=`, `<`, `<=`, `+`, `-`, `*`, `/` | Operators as in JavaScript |\n| `price`, `order.total` | Properties of the model, read in lower case |\n| `#name` | A temporary variable: `#total = price * count` |\n| `name(a, b)` | A helper call |\n| `\"text\"`, `'text'` | Text; a quoted number becomes a number |\n| `TRUE`, `FALSE`, `YES`, `NO`, `NULL` | Values |\n| `// text` | A comment line |\n\nKeywords can be in any case.\n\nExample: Rule\n```js\nIF total >= 100 AND customer.vip == YES\n\tRETURN total * 0.9\nFI\nRETURN total\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(code, [nocompile], [isasync])","since":"","deprecated":false},{"type":"type","name":"Macro syntax","signature":"Macro syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"JafiZW3hK60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/macros/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Makros","summary":"NEWMACRO() und die Makro-Syntax.","markdown":"---\ntitle: Makros\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/macros/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Makros\n\n> NEWMACRO() und die Makro-Syntax.\n\n## API\n\n### NEWMACRO(code, [nocompile], [isasync])\n\nType: `method`\n\nKompiliert ein Makro zu einer Funktion `fn(model, helpers)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Das Makro, ein Befehl pro Zeile (oder durch `;` getrennt). |\n| `nocompile` | `Boolean` | no | `false` | Gibt den JavaScript-Code statt einer Funktion zurück. |\n| `isasync` | `Boolean` | no | `false` | Erzeugt eine asynchrone Funktion. |\n\nReturns: `Function` `function(model, [helpers])` oder mit `nocompile` ein String.\n\nDie Funktion gibt den Wert des ersten ausgeführten `RETURN` zurück, oder `undefined`. Wörter werden aus `model` gelesen, und `name(...)` ruft `helpers.name` mit dem Modell als `this` auf. Mit `isasync` ist die Funktion asynchron, und auf jeden Aufruf einer Hilfsfunktion wird gewartet. Mit `nocompile` erhältst du das erzeugte JavaScript als String, was nützlich ist, um eine Regel zu prüfen.\n\nExample: Versand\n```js\nvar shipping = NEWMACRO('IF weight > 10\\n\\tRETURN 15\\nELSE IF weight > 2\\n\\tRETURN 8\\nFI\\nRETURN 4');\nshipping({ weight: 5 }); // 8\n```\n\nExample: Asynchrone Hilfsfunktionen\n```js\nvar fn = NEWMACRO('RETURN rate(currency) * price', false, true);\nvar value = await fn({ price: 10, currency: 'EUR' }, { rate: async function(code) { return 1.1; } });\n```\n\n### Macro syntax\n\nType: `type`\n\nBefehle und Werte von `NEWMACRO()`.\n\n| Syntax | Bedeutung |\n| --- | --- |\n| `IF condition` … `ELSE IF condition` … `ELSE` … `FI` | Bedingungen; `FI` schließt sie |\n| `RETURN expression` | Gibt einen Wert zurück |\n| `AND`, `OR` | `&&`, `\\|\\|` |\n| `==`, `!=`, `>`, `>=`, `<`, `<=`, `+`, `-`, `*`, `/` | Operatoren wie in JavaScript |\n| `price`, `order.total` | Eigenschaften des Modells, in Kleinbuchstaben gelesen |\n| `#name` | Eine temporäre Variable: `#total = price * count` |\n| `name(a, b)` | Ein Aufruf einer Hilfsfunktion |\n| `\"text\"`, `'text'` | Text; eine Zahl in Anführungszeichen wird zu einer Zahl |\n| `TRUE`, `FALSE`, `YES`, `NO`, `NULL` | Werte |\n| `// text` | Eine Kommentarzeile |\n\nSchlüsselwörter können beliebig groß oder klein geschrieben sein.\n\nExample: Regel\n```js\nIF total >= 100 AND customer.vip == YES\n\tRETURN total * 0.9\nFI\nRETURN total\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(code, [nocompile], [isasync])","since":"","deprecated":false},{"type":"type","name":"Macro syntax","signature":"Macro syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"JafiZW3hK60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/macros/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Macros","summary":"NEWMACRO() y la sintaxis de las macros.","markdown":"---\ntitle: Macros\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/macros/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Macros\n\n> NEWMACRO() y la sintaxis de las macros.\n\n## API\n\n### NEWMACRO(code, [nocompile], [isasync])\n\nType: `method`\n\nCompila una macro en una función `fn(model, helpers)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | La macro, un comando por línea (o separados por `;`). |\n| `nocompile` | `Boolean` | no | `false` | Devuelve el código JavaScript en lugar de una función. |\n| `isasync` | `Boolean` | no | `false` | Crea una función async. |\n\nReturns: `Function` `function(model, [helpers])`, o una cadena con `nocompile`.\n\nLa función devuelve el valor del primer `RETURN` que se ejecuta, o `undefined`. Las palabras se leen de `model` y `name(...)` llama a `helpers.name` con el modelo como `this`. Con `isasync` la función es async y se espera (await) cada llamada a un helper. Con `nocompile` obtienes el JavaScript generado como cadena, lo que es útil para revisar una regla.\n\nExample: Envío\n```js\nvar shipping = NEWMACRO('IF weight > 10\\n\\tRETURN 15\\nELSE IF weight > 2\\n\\tRETURN 8\\nFI\\nRETURN 4');\nshipping({ weight: 5 }); // 8\n```\n\nExample: Helpers asíncronos\n```js\nvar fn = NEWMACRO('RETURN rate(currency) * price', false, true);\nvar value = await fn({ price: 10, currency: 'EUR' }, { rate: async function(code) { return 1.1; } });\n```\n\n### Macro syntax\n\nType: `type`\n\nComandos y valores de `NEWMACRO()`.\n\n| Sintaxis | Significado |\n| --- | --- |\n| `IF condition` … `ELSE IF condition` … `ELSE` … `FI` | Condiciones; `FI` las cierra |\n| `RETURN expression` | Devuelve un valor |\n| `AND`, `OR` | `&&`, `\\|\\|` |\n| `==`, `!=`, `>`, `>=`, `<`, `<=`, `+`, `-`, `*`, `/` | Operadores como en JavaScript |\n| `price`, `order.total` | Propiedades del modelo, leídas en minúsculas |\n| `#name` | Una variable temporal: `#total = price * count` |\n| `name(a, b)` | Una llamada a un helper |\n| `\"text\"`, `'text'` | Texto; un número entre comillas se convierte en número |\n| `TRUE`, `FALSE`, `YES`, `NO`, `NULL` | Valores |\n| `// text` | Una línea de comentario |\n\nLas palabras clave pueden estar en mayúsculas o minúsculas.\n\nExample: Regla\n```js\nIF total >= 100 AND customer.vip == YES\n\tRETURN total * 0.9\nFI\nRETURN total\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(code, [nocompile], [isasync])","since":"","deprecated":false},{"type":"type","name":"Macro syntax","signature":"Macro syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"JafiZW3hK60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/macros/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Macros","summary":"NEWMACRO() et la syntaxe des macros.","markdown":"---\ntitle: Macros\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/macros/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Macros\n\n> NEWMACRO() et la syntaxe des macros.\n\n## API\n\n### NEWMACRO(code, [nocompile], [isasync])\n\nType: `method`\n\nCompile une macro en une fonction `fn(model, helpers)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | La macro, une commande par ligne (ou séparées par `;`). |\n| `nocompile` | `Boolean` | no | `false` | Renvoie le code JavaScript au lieu d'une fonction. |\n| `isasync` | `Boolean` | no | `false` | Crée une fonction async. |\n\nReturns: `Function` `function(model, [helpers])`, ou une chaîne avec `nocompile`.\n\nLa fonction renvoie la valeur du premier `RETURN` exécuté, ou `undefined`. Les mots sont lus dans `model` et `name(...)` appelle `helpers.name` avec le modèle comme `this`. Avec `isasync`, la fonction est async et chaque appel de helper est attendu. Avec `nocompile`, tu obtiens le JavaScript généré sous forme de chaîne, ce qui est utile pour vérifier une règle.\n\nExample: Livraison\n```js\nvar shipping = NEWMACRO('IF weight > 10\\n\\tRETURN 15\\nELSE IF weight > 2\\n\\tRETURN 8\\nFI\\nRETURN 4');\nshipping({ weight: 5 }); // 8\n```\n\nExample: Helpers asynchrones\n```js\nvar fn = NEWMACRO('RETURN rate(currency) * price', false, true);\nvar value = await fn({ price: 10, currency: 'EUR' }, { rate: async function(code) { return 1.1; } });\n```\n\n### Macro syntax\n\nType: `type`\n\nLes commandes et les valeurs de `NEWMACRO()`.\n\n| Syntaxe | Signification |\n| --- | --- |\n| `IF condition` … `ELSE IF condition` … `ELSE` … `FI` | Conditions ; `FI` les ferme |\n| `RETURN expression` | Renvoie une valeur |\n| `AND`, `OR` | `&&`, `\\|\\|` |\n| `==`, `!=`, `>`, `>=`, `<`, `<=`, `+`, `-`, `*`, `/` | Opérateurs comme en JavaScript |\n| `price`, `order.total` | Propriétés du modèle, lues en minuscules |\n| `#name` | Une variable temporaire : `#total = price * count` |\n| `name(a, b)` | Un appel de helper |\n| `\"text\"`, `'text'` | Texte ; un nombre entre guillemets devient un nombre |\n| `TRUE`, `FALSE`, `YES`, `NO`, `NULL` | Valeurs |\n| `// text` | Une ligne de commentaire |\n\nLes mots-clés peuvent être écrits dans n'importe quelle casse.\n\nExample: Règle\n```js\nIF total >= 100 AND customer.vip == YES\n\tRETURN total * 0.9\nFI\nRETURN total\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(code, [nocompile], [isasync])","since":"","deprecated":false},{"type":"type","name":"Macro syntax","signature":"Macro syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"JafiZW3hK60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/macros/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Macro","summary":"NEWMACRO() e la sintassi delle macro.","markdown":"---\ntitle: Macro\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/macros/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Macro\n\n> NEWMACRO() e la sintassi delle macro.\n\n## API\n\n### NEWMACRO(code, [nocompile], [isasync])\n\nType: `method`\n\nCompila una macro in una funzione `fn(model, helpers)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | La macro, un comando per riga (o separati da `;`). |\n| `nocompile` | `Boolean` | no | `false` | Restituisce il codice JavaScript invece di una funzione. |\n| `isasync` | `Boolean` | no | `false` | Crea una funzione async. |\n\nReturns: `Function` `function(model, [helpers])`, o una stringa con `nocompile`.\n\nLa funzione restituisce il valore del primo `RETURN` eseguito, o `undefined`. Le parole vengono lette da `model` e `name(...)` chiama `helpers.name` con il modello come `this`. Con `isasync` la funzione è async e ogni chiamata a un helper viene attesa. Con `nocompile` ottieni il JavaScript generato come stringa, utile per verificare una regola.\n\nExample: Spedizione\n```js\nvar shipping = NEWMACRO('IF weight > 10\\n\\tRETURN 15\\nELSE IF weight > 2\\n\\tRETURN 8\\nFI\\nRETURN 4');\nshipping({ weight: 5 }); // 8\n```\n\nExample: Helper asincroni\n```js\nvar fn = NEWMACRO('RETURN rate(currency) * price', false, true);\nvar value = await fn({ price: 10, currency: 'EUR' }, { rate: async function(code) { return 1.1; } });\n```\n\n### Macro syntax\n\nType: `type`\n\nComandi e valori di `NEWMACRO()`.\n\n| Sintassi | Significato |\n| --- | --- |\n| `IF condition` … `ELSE IF condition` … `ELSE` … `FI` | Condizioni; `FI` le chiude |\n| `RETURN expression` | Restituisce un valore |\n| `AND`, `OR` | `&&`, `\\|\\|` |\n| `==`, `!=`, `>`, `>=`, `<`, `<=`, `+`, `-`, `*`, `/` | Operatori come in JavaScript |\n| `price`, `order.total` | Proprietà del modello, lette in minuscolo |\n| `#name` | Una variabile temporanea: `#total = price * count` |\n| `name(a, b)` | Una chiamata a un helper |\n| `\"text\"`, `'text'` | Testo; un numero tra virgolette diventa un numero |\n| `TRUE`, `FALSE`, `YES`, `NO`, `NULL` | Valori |\n| `// text` | Una riga di commento |\n\nLe parole chiave possono essere maiuscole o minuscole.\n\nExample: Regola\n```js\nIF total >= 100 AND customer.vip == YES\n\tRETURN total * 0.9\nFI\nRETURN total\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(code, [nocompile], [isasync])","since":"","deprecated":false},{"type":"type","name":"Macro syntax","signature":"Macro syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"JafiZW3hK60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/macros/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Makrá","summary":"NEWMACRO() a syntax makier.","markdown":"---\ntitle: \"Makrá\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/macros/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Makrá\n\n> NEWMACRO() a syntax makier.\n\n## API\n\n### NEWMACRO(code, [nocompile], [isasync])\n\nType: `method`\n\nSkompiluje makro do funkcie `fn(model, helpers)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Makro, jeden príkaz na riadok (alebo oddelené `;`). |\n| `nocompile` | `Boolean` | no | `false` | Vráti kód JavaScript namiesto funkcie. |\n| `isasync` | `Boolean` | no | `false` | Vytvorí asynchrónnu funkciu. |\n\nReturns: `Function` `function(model, [helpers])`, alebo reťazec s `nocompile`.\n\nFunkcia vráti hodnotu prvého `RETURN`, ktorý sa vykoná, alebo `undefined`. Slová sa čítajú z `model` a `name(...)` volá `helpers.name` s modelom ako `this`. S `isasync` je funkcia asynchrónna a na každé volanie pomocnej funkcie sa čaká pomocou await. S `nocompile` dostaneš vygenerovaný JavaScript ako reťazec, čo sa hodí na kontrolu pravidla.\n\nExample: Doprava\n```js\nvar shipping = NEWMACRO('IF weight > 10\\n\\tRETURN 15\\nELSE IF weight > 2\\n\\tRETURN 8\\nFI\\nRETURN 4');\nshipping({ weight: 5 }); // 8\n```\n\nExample: Asynchrónne pomocné funkcie\n```js\nvar fn = NEWMACRO('RETURN rate(currency) * price', false, true);\nvar value = await fn({ price: 10, currency: 'EUR' }, { rate: async function(code) { return 1.1; } });\n```\n\n### Macro syntax\n\nType: `type`\n\nPríkazy a hodnoty `NEWMACRO()`.\n\n| Syntax | Význam |\n| --- | --- |\n| `IF condition` … `ELSE IF condition` … `ELSE` … `FI` | Podmienky; `FI` ich uzatvára |\n| `RETURN expression` | Vráti hodnotu |\n| `AND`, `OR` | `&&`, `\\|\\|` |\n| `==`, `!=`, `>`, `>=`, `<`, `<=`, `+`, `-`, `*`, `/` | Operátory ako v JavaScripte |\n| `price`, `order.total` | Vlastnosti modelu, čítané malými písmenami |\n| `#name` | Dočasná premenná: `#total = price * count` |\n| `name(a, b)` | Volanie pomocnej funkcie |\n| `\"text\"`, `'text'` | Text; číslo v úvodzovkách sa stane číslom |\n| `TRUE`, `FALSE`, `YES`, `NO`, `NULL` | Hodnoty |\n| `// text` | Riadok komentára |\n\nKľúčové slová môžu byť v ľubovoľnej veľkosti písmen.\n\nExample: Pravidlo\n```js\nIF total >= 100 AND customer.vip == YES\n\tRETURN total * 0.9\nFI\nRETURN total\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(code, [nocompile], [isasync])","since":"","deprecated":false},{"type":"type","name":"Macro syntax","signature":"Macro syntax","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"Jafidn4lK60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/tangular/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Tangular","summary":"Tangular.compile(), Tangular.render(), Tangular.register() and Tangular.helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/tangular/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Tangular\n\n> Tangular.compile(), Tangular.render(), Tangular.register() and Tangular.helpers.\n\n## API\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nCompiles a Tangular template into a function.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | The template. |\n| `tagbeg` | `String` | no | `'{{'` | Start of a command. |\n| `tagend` | `String` | no | `'}}'` | End of a command. |\n\nReturns: `Function` `function(model, [repository], [helpers])`.\n\nThe function is `template(model, [repository], [helpers])` and returns a string. Names in the template are read from the model, `$` is the repository and `$index` the index in a loop. Errors while rendering are printed to the console. `tagbeg` and `tagend` replace `{{` and `}}` (as parts of a regular expression). Commands are described in [Views](../../guides/views/#templates).\n\nExample: Compile once\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = items.map(item => row(item)).join('');\n```\n\nExample: Local helpers\n```js\nvar t = Tangular.compile('{{ name | badge }}');\nt({ name: 'New' }, null, { badge: function(value) { return '<span class=\"badge\">' + value + '</span>'; } });\n```\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nCompiles and renders a template in one call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | The template. |\n| `model` | `Object` | no | `{}` | The model. |\n| `repository` | `Object` | no |  | Available as `$`. |\n| `helpers` | `Object` | no |  | Helpers for this call. |\n\nReturns: `String` The output.\n\nUse `Tangular.compile()` for templates that you render often.\n\nExample: Render\n```js\nTangular.render('Hello {{ name }}!', { name: 'Peter' }); // 'Hello Peter!'\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nAdds a helper for all Tangular templates.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Helper name. |\n| `fn` | `Function` | yes |  | `function(value, [args...])`. |\n\nReturns: `Object` Tangular, for chaining.\n\nThe helper is called as `fn.call(model, value, ...arguments)`: `{{ price | money('EUR') }}` calls `money(price, 'EUR')`. A missing helper prints a warning and returns the value.\n\nExample: Helper\n```js\nTangular.register('money', function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n});\n```\n\n### Tangular.helpers\n\nType: `property`\n\nBuilt-in helpers of Tangular, also available as the global `Thelpers`.\n\nReturns: `Object`\n\n| Helper | Description |\n| --- | --- |\n| `encode([type])` | HTML-encodes; used for every value without `raw`. Types: `json`, `json2`, `url`, `querify` |\n| `raw` | The value without encoding |\n| `format([format], ...)` | Formats a number or a date (strings are detected) |\n| `currency([code])` | Formats a number with a formatter from `DEF.currencies[code]` (or `DEF.currencies.default`); without one it uses two decimals |\n| `pluralize(zero, one, few, other)` | Chooses a word by a number |\n| `empty([text])`, `def([text])` | The value, or `text` (default `---`) when it is empty |\n\nExample: Usage\n```js\nTangular.render('{{ count | pluralize(\\'no items\\', \\'# item\\', \\'# items\\', \\'# items\\') }}', { count: 3 });\n```\n","entries":[{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Tangular.helpers","signature":"Tangular.helpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"Jafidn4lK60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/tangular/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Tangular","summary":"Tangular.compile(), Tangular.render(), Tangular.register() und Tangular.helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/tangular/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Tangular\n\n> Tangular.compile(), Tangular.render(), Tangular.register() und Tangular.helpers.\n\n## API\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nKompiliert ein Tangular-Template zu einer Funktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Das Template. |\n| `tagbeg` | `String` | no | `'{{'` | Anfang eines Befehls. |\n| `tagend` | `String` | no | `'}}'` | Ende eines Befehls. |\n\nReturns: `Function` `function(model, [repository], [helpers])`.\n\nDie Funktion ist `template(model, [repository], [helpers])` und gibt einen String zurück. Namen im Template werden aus dem Modell gelesen, `$` ist das Repository und `$index` der Index in einer Schleife. Fehler beim Rendern werden in die Konsole ausgegeben. `tagbeg` und `tagend` ersetzen `{{` und `}}` (als Teile eines regulären Ausdrucks). Die Befehle sind in [Views](../../guides/views/#templates) beschrieben.\n\nExample: Einmal kompilieren\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = items.map(item => row(item)).join('');\n```\n\nExample: Lokale Hilfsfunktionen\n```js\nvar t = Tangular.compile('{{ name | badge }}');\nt({ name: 'New' }, null, { badge: function(value) { return '<span class=\"badge\">' + value + '</span>'; } });\n```\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nKompiliert und rendert ein Template in einem Aufruf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Das Template. |\n| `model` | `Object` | no | `{}` | Das Modell. |\n| `repository` | `Object` | no |  | Verfügbar als `$`. |\n| `helpers` | `Object` | no |  | Hilfsfunktionen für diesen Aufruf. |\n\nReturns: `String` Die Ausgabe.\n\nVerwende `Tangular.compile()` für Templates, die du oft renderst.\n\nExample: Rendern\n```js\nTangular.render('Hello {{ name }}!', { name: 'Peter' }); // 'Hello Peter!'\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nFügt eine Hilfsfunktion für alle Tangular-Templates hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Hilfsfunktion. |\n| `fn` | `Function` | yes |  | `function(value, [args...])`. |\n\nReturns: `Object` Tangular, zum Verketten.\n\nDie Hilfsfunktion wird als `fn.call(model, value, ...arguments)` aufgerufen: `{{ price | money('EUR') }}` ruft `money(price, 'EUR')` auf. Eine fehlende Hilfsfunktion gibt eine Warnung aus und liefert den Wert zurück.\n\nExample: Hilfsfunktion\n```js\nTangular.register('money', function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n});\n```\n\n### Tangular.helpers\n\nType: `property`\n\nEingebaute Hilfsfunktionen von Tangular, auch als globales `Thelpers` verfügbar.\n\nReturns: `Object`\n\n| Hilfsfunktion | Beschreibung |\n| --- | --- |\n| `encode([type])` | HTML-kodiert; wird für jeden Wert ohne `raw` verwendet. Typen: `json`, `json2`, `url`, `querify` |\n| `raw` | Der Wert ohne Kodierung |\n| `format([format], ...)` | Formatiert eine Zahl oder ein Datum (Strings werden erkannt) |\n| `currency([code])` | Formatiert eine Zahl mit einem Formatierer aus `DEF.currencies[code]` (oder `DEF.currencies.default`); ohne einen verwendet sie zwei Dezimalstellen |\n| `pluralize(zero, one, few, other)` | Wählt ein Wort anhand einer Zahl |\n| `empty([text])`, `def([text])` | Der Wert, oder `text` (Standard `---`), wenn er leer ist |\n\nExample: Verwendung\n```js\nTangular.render('{{ count | pluralize(\\'no items\\', \\'# item\\', \\'# items\\', \\'# items\\') }}', { count: 3 });\n```\n","entries":[{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Tangular.helpers","signature":"Tangular.helpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"Jafidn4lK60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/tangular/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Tangular","summary":"Tangular.compile(), Tangular.render(), Tangular.register() y Tangular.helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/tangular/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Tangular\n\n> Tangular.compile(), Tangular.render(), Tangular.register() y Tangular.helpers.\n\n## API\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nCompila una plantilla Tangular en una función.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | La plantilla. |\n| `tagbeg` | `String` | no | `'{{'` | Inicio de un comando. |\n| `tagend` | `String` | no | `'}}'` | Fin de un comando. |\n\nReturns: `Function` `function(model, [repository], [helpers])`.\n\nLa función es `template(model, [repository], [helpers])` y devuelve una cadena. Los nombres de la plantilla se leen del modelo, `$` es el repositorio y `$index` el índice dentro de un bucle. Los errores durante el renderizado se imprimen en la consola. `tagbeg` y `tagend` sustituyen a `{{` y `}}` (como partes de una expresión regular). Los comandos se describen en [Vistas](../../guides/views/#templates).\n\nExample: Compilar una vez\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = items.map(item => row(item)).join('');\n```\n\nExample: Helpers locales\n```js\nvar t = Tangular.compile('{{ name | badge }}');\nt({ name: 'New' }, null, { badge: function(value) { return '<span class=\"badge\">' + value + '</span>'; } });\n```\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nCompila y renderiza una plantilla en una sola llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | La plantilla. |\n| `model` | `Object` | no | `{}` | El modelo. |\n| `repository` | `Object` | no |  | Disponible como `$`. |\n| `helpers` | `Object` | no |  | Helpers para esta llamada. |\n\nReturns: `String` La salida.\n\nUsa `Tangular.compile()` para las plantillas que renderizas a menudo.\n\nExample: Renderizar\n```js\nTangular.render('Hello {{ name }}!', { name: 'Peter' }); // 'Hello Peter!'\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nAñade un helper para todas las plantillas Tangular.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del helper. |\n| `fn` | `Function` | yes |  | `function(value, [args...])`. |\n\nReturns: `Object` Tangular, para encadenar.\n\nEl helper se llama como `fn.call(model, value, ...arguments)`: `{{ price | money('EUR') }}` llama a `money(price, 'EUR')`. Un helper que no existe imprime un aviso y devuelve el valor.\n\nExample: Helper\n```js\nTangular.register('money', function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n});\n```\n\n### Tangular.helpers\n\nType: `property`\n\nHelpers integrados de Tangular, disponibles también como la global `Thelpers`.\n\nReturns: `Object`\n\n| Helper | Descripción |\n| --- | --- |\n| `encode([type])` | Codifica en HTML; se usa para cada valor sin `raw`. Tipos: `json`, `json2`, `url`, `querify` |\n| `raw` | El valor sin codificar |\n| `format([format], ...)` | Formatea un número o una fecha (las cadenas se detectan) |\n| `currency([code])` | Formatea un número con un formateador de `DEF.currencies[code]` (o `DEF.currencies.default`); si no hay ninguno, usa dos decimales |\n| `pluralize(zero, one, few, other)` | Elige una palabra según un número |\n| `empty([text])`, `def([text])` | El valor, o `text` (por defecto `---`) cuando está vacío |\n\nExample: Uso\n```js\nTangular.render('{{ count | pluralize(\\'no items\\', \\'# item\\', \\'# items\\', \\'# items\\') }}', { count: 3 });\n```\n","entries":[{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Tangular.helpers","signature":"Tangular.helpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"Jafidn4lK60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/tangular/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Tangular","summary":"Tangular.compile(), Tangular.render(), Tangular.register() et Tangular.helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/tangular/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Tangular\n\n> Tangular.compile(), Tangular.render(), Tangular.register() et Tangular.helpers.\n\n## API\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nCompile un template Tangular en une fonction.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Le template. |\n| `tagbeg` | `String` | no | `'{{'` | Début d'une commande. |\n| `tagend` | `String` | no | `'}}'` | Fin d'une commande. |\n\nReturns: `Function` `function(model, [repository], [helpers])`.\n\nLa fonction est `template(model, [repository], [helpers])` et renvoie une chaîne. Les noms du template sont lus dans le modèle, `$` est le repository et `$index` l'index dans une boucle. Les erreurs de rendu sont affichées dans la console. `tagbeg` et `tagend` remplacent `{{` et `}}` (en tant que parties d'une expression régulière). Les commandes sont décrites dans [Vues](../../guides/views/#templates).\n\nExample: Compiler une seule fois\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = items.map(item => row(item)).join('');\n```\n\nExample: Helpers locaux\n```js\nvar t = Tangular.compile('{{ name | badge }}');\nt({ name: 'New' }, null, { badge: function(value) { return '<span class=\"badge\">' + value + '</span>'; } });\n```\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nCompile et effectue le rendu d'un template en un seul appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Le template. |\n| `model` | `Object` | no | `{}` | Le modèle. |\n| `repository` | `Object` | no |  | Disponible sous `$`. |\n| `helpers` | `Object` | no |  | Les helpers pour cet appel. |\n\nReturns: `String` Le résultat.\n\nUtilise `Tangular.compile()` pour les templates dont tu fais souvent le rendu.\n\nExample: Rendu\n```js\nTangular.render('Hello {{ name }}!', { name: 'Peter' }); // 'Hello Peter!'\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nAjoute un helper pour tous les templates Tangular.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du helper. |\n| `fn` | `Function` | yes |  | `function(value, [args...])`. |\n\nReturns: `Object` Tangular, pour le chaînage.\n\nLe helper est appelé sous la forme `fn.call(model, value, ...arguments)` : `{{ price | money('EUR') }}` appelle `money(price, 'EUR')`. Un helper manquant affiche un avertissement et renvoie la valeur.\n\nExample: Helper\n```js\nTangular.register('money', function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n});\n```\n\n### Tangular.helpers\n\nType: `property`\n\nLes helpers intégrés de Tangular, également disponibles via la variable globale `Thelpers`.\n\nReturns: `Object`\n\n| Helper | Description |\n| --- | --- |\n| `encode([type])` | Encode en HTML ; utilisé pour chaque valeur sans `raw`. Types : `json`, `json2`, `url`, `querify` |\n| `raw` | La valeur sans encodage |\n| `format([format], ...)` | Formate un nombre ou une date (les chaînes sont détectées) |\n| `currency([code])` | Formate un nombre avec un formateur de `DEF.currencies[code]` (ou `DEF.currencies.default`) ; sans formateur, il utilise deux décimales |\n| `pluralize(zero, one, few, other)` | Choisit un mot en fonction d'un nombre |\n| `empty([text])`, `def([text])` | La valeur, ou `text` (`---` par défaut) quand elle est vide |\n\nExample: Utilisation\n```js\nTangular.render('{{ count | pluralize(\\'no items\\', \\'# item\\', \\'# items\\', \\'# items\\') }}', { count: 3 });\n```\n","entries":[{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Tangular.helpers","signature":"Tangular.helpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"Jafidn4lK60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/tangular/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Tangular","summary":"Tangular.compile(), Tangular.render(), Tangular.register() e Tangular.helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/tangular/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Tangular\n\n> Tangular.compile(), Tangular.render(), Tangular.register() e Tangular.helpers.\n\n## API\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nCompila un template Tangular in una funzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Il template. |\n| `tagbeg` | `String` | no | `'{{'` | Inizio di un comando. |\n| `tagend` | `String` | no | `'}}'` | Fine di un comando. |\n\nReturns: `Function` `function(model, [repository], [helpers])`.\n\nLa funzione è `template(model, [repository], [helpers])` e restituisce una stringa. I nomi nel template vengono letti dal modello, `$` è il repository e `$index` l'indice in un ciclo. Gli errori durante il rendering vengono stampati nella console. `tagbeg` e `tagend` sostituiscono `{{` e `}}` (come parti di un'espressione regolare). I comandi sono descritti in [View](../../guides/views/#templates).\n\nExample: Compilare una volta\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = items.map(item => row(item)).join('');\n```\n\nExample: Helper locali\n```js\nvar t = Tangular.compile('{{ name | badge }}');\nt({ name: 'New' }, null, { badge: function(value) { return '<span class=\"badge\">' + value + '</span>'; } });\n```\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nCompila ed esegue il rendering di un template in una sola chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Il template. |\n| `model` | `Object` | no | `{}` | Il modello. |\n| `repository` | `Object` | no |  | Disponibile come `$`. |\n| `helpers` | `Object` | no |  | Helper per questa chiamata. |\n\nReturns: `String` L'output.\n\nUsa `Tangular.compile()` per i template di cui esegui spesso il rendering.\n\nExample: Rendering\n```js\nTangular.render('Hello {{ name }}!', { name: 'Peter' }); // 'Hello Peter!'\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nAggiunge un helper per tutti i template Tangular.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'helper. |\n| `fn` | `Function` | yes |  | `function(value, [args...])`. |\n\nReturns: `Object` Tangular, per il concatenamento.\n\nL'helper viene chiamato come `fn.call(model, value, ...arguments)`: `{{ price | money('EUR') }}` chiama `money(price, 'EUR')`. Un helper mancante stampa un avviso e restituisce il valore.\n\nExample: Helper\n```js\nTangular.register('money', function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n});\n```\n\n### Tangular.helpers\n\nType: `property`\n\nGli helper integrati di Tangular, disponibili anche come variabile globale `Thelpers`.\n\nReturns: `Object`\n\n| Helper | Descrizione |\n| --- | --- |\n| `encode([type])` | Codifica in HTML; usato per ogni valore senza `raw`. Tipi: `json`, `json2`, `url`, `querify` |\n| `raw` | Il valore senza codifica |\n| `format([format], ...)` | Formatta un numero o una data (le stringhe vengono riconosciute) |\n| `currency([code])` | Formatta un numero con un formatter da `DEF.currencies[code]` (o `DEF.currencies.default`); senza di esso usa due decimali |\n| `pluralize(zero, one, few, other)` | Sceglie una parola in base a un numero |\n| `empty([text])`, `def([text])` | Il valore, o `text` (predefinito `---`) quando è vuoto |\n\nExample: Utilizzo\n```js\nTangular.render('{{ count | pluralize(\\'no items\\', \\'# item\\', \\'# items\\', \\'# items\\') }}', { count: 3 });\n```\n","entries":[{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Tangular.helpers","signature":"Tangular.helpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"Jafidn4lK60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/tangular/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Tangular","summary":"Tangular.compile(), Tangular.render(), Tangular.register() a Tangular.helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/tangular/\nupdated: 2026-11-18T16:56:54.572Z\n---\n\n# Tangular\n\n> Tangular.compile(), Tangular.render(), Tangular.register() a Tangular.helpers.\n\n## API\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nSkompiluje šablónu Tangular do funkcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Šablóna. |\n| `tagbeg` | `String` | no | `'{{'` | Začiatok príkazu. |\n| `tagend` | `String` | no | `'}}'` | Koniec príkazu. |\n\nReturns: `Function` `function(model, [repository], [helpers])`.\n\nFunkcia je `template(model, [repository], [helpers])` a vracia reťazec. Názvy v šablóne sa čítajú z modelu, `$` je repository a `$index` index v cykle. Chyby počas renderovania sa vypíšu do konzoly. `tagbeg` a `tagend` nahradia `{{` a `}}` (ako časti regulárneho výrazu). Príkazy sú opísané vo [Views](../../guides/views/#templates).\n\nExample: Jednorazová kompilácia\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = items.map(item => row(item)).join('');\n```\n\nExample: Lokálne pomocné funkcie\n```js\nvar t = Tangular.compile('{{ name | badge }}');\nt({ name: 'New' }, null, { badge: function(value) { return '<span class=\"badge\">' + value + '</span>'; } });\n```\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nSkompiluje a vyrenderuje šablónu jedným volaním.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Šablóna. |\n| `model` | `Object` | no | `{}` | Model. |\n| `repository` | `Object` | no |  | Dostupné ako `$`. |\n| `helpers` | `Object` | no |  | Pomocné funkcie pre toto volanie. |\n\nReturns: `String` Výstup.\n\nPre šablóny, ktoré renderuješ často, použi `Tangular.compile()`.\n\nExample: Renderovanie\n```js\nTangular.render('Hello {{ name }}!', { name: 'Peter' }); // 'Hello Peter!'\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nPridá pomocnú funkciu pre všetky šablóny Tangular.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov pomocnej funkcie. |\n| `fn` | `Function` | yes |  | `function(value, [args...])`. |\n\nReturns: `Object` Tangular, na reťazenie.\n\nPomocná funkcia sa volá ako `fn.call(model, value, ...arguments)`: `{{ price | money('EUR') }}` zavolá `money(price, 'EUR')`. Chýbajúca pomocná funkcia vypíše varovanie a vráti hodnotu.\n\nExample: Pomocná funkcia\n```js\nTangular.register('money', function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n});\n```\n\n### Tangular.helpers\n\nType: `property`\n\nVstavané pomocné funkcie Tangularu, dostupné aj ako globálny `Thelpers`.\n\nReturns: `Object`\n\n| Pomocná funkcia | Popis |\n| --- | --- |\n| `encode([type])` | Zakóduje pre HTML; používa sa pre každú hodnotu bez `raw`. Typy: `json`, `json2`, `url`, `querify` |\n| `raw` | Hodnota bez kódovania |\n| `format([format], ...)` | Naformátuje číslo alebo dátum (reťazce sa rozpoznajú) |\n| `currency([code])` | Naformátuje číslo formátovačom z `DEF.currencies[code]` (alebo `DEF.currencies.default`); bez neho použije dve desatinné miesta |\n| `pluralize(zero, one, few, other)` | Vyberie slovo podľa čísla |\n| `empty([text])`, `def([text])` | Hodnota, alebo `text` (predvolene `---`), keď je prázdna |\n\nExample: Použitie\n```js\nTangular.render('{{ count | pluralize(\\'no items\\', \\'# item\\', \\'# items\\', \\'# items\\') }}', { count: 3 });\n```\n","entries":[{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Tangular.helpers","signature":"Tangular.helpers","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:56:54.572Z"}
{"id":"Jafin73oY61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/minification/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Minification","summary":"U.minify_css(), U.minify_js() and U.minify_html().","markdown":"---\ntitle: Minification\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/minification/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Minification\n\n> U.minify_css(), U.minify_js() and U.minify_html().\n\n## API\n\n### U.minify_css(css)\n\nType: `method`\n\nMinifies CSS and compiles nested rules and `$variables`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `css` | `String` | yes |  | CSS source. |\n\nReturns: `String` Minified CSS.\n\nRemoves comments and whitespace, shortens `margin` and `padding` (`0 0 0 0` to `0`, `10px 20px 10px 20px` to `10px 20px`) and colours such as `#FFFFFF`. A rule that contains only other rules is expanded (`.a { .b { } }` to `.a .b{}`). Variables are declared as `$name: value;` and used as `$name`. On an error the function logs `CSS compiler error` and returns an empty string.\n\nExample: Nested rules\n```js\nU.minify_css('.menu {\\n\\t.item { color: red; }\\n\\t.active { font-weight: bold; }\\n}');\n// '.menu .item{color:red}.menu .active{font-weight:bold}'\n```\n\nExample: Variables\n```js\nU.minify_css('$brand: #0066FF;\\n.button { background: $brand; }');\n// '.button{background:#0066FF}'\n```\n\n### U.minify_js(js)\n\nType: `method`\n\nMinifies JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `js` | `String` | yes |  | JavaScript source. |\n\nReturns: `String` Minified code.\n\nRemoves comments, line breaks and unneeded whitespace. Strings are kept as they are. It does not rename variables.\n\nExample: Minify\n```js\nU.minify_js('if (a) {\\n\\tconsole.log(a); // log\\n}'); // 'if(a){console.log(a);}'\n```\n\n### U.minify_html(html)\n\nType: `method`\n\nMinifies HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML source. |\n\nReturns: `String` Minified HTML.\n\nRemoves comments (not conditional comments such as `<!--[if IE]>`) and collapses runs of spaces between words to one space. Line breaks and indentation between tags are kept. The content of `<script>`, `<textarea>`, `<pre>`, `<code>` and `<readme>` is not changed. Inline `<script>` and `<style>` are minified with the JS and CSS minificators when `$minifyjs` and `$minifycss` are on.\n\nExample: Minify\n```js\nvar html = U.minify_html(source);\n```\n","entries":[{"type":"method","name":"U.minify_css()","signature":"U.minify_css(css)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(js)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"Jafin73oY61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/minification/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Minifizierung","summary":"U.minify_css(), U.minify_js() und U.minify_html().","markdown":"---\ntitle: Minifizierung\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/minification/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Minifizierung\n\n> U.minify_css(), U.minify_js() und U.minify_html().\n\n## API\n\n### U.minify_css(css)\n\nType: `method`\n\nMinifiziert CSS und kompiliert verschachtelte Regeln und `$variables`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `css` | `String` | yes |  | CSS-Quellcode. |\n\nReturns: `String` Minifiziertes CSS.\n\nEntfernt Kommentare und Leerraum, kürzt `margin` und `padding` (`0 0 0 0` zu `0`, `10px 20px 10px 20px` zu `10px 20px`) und Farben wie `#FFFFFF`. Eine Regel, die nur andere Regeln enthält, wird aufgelöst (`.a { .b { } }` zu `.a .b{}`). Variablen werden als `$name: value;` deklariert und als `$name` verwendet. Bei einem Fehler protokolliert die Funktion `CSS compiler error` und gibt einen leeren String zurück.\n\nExample: Verschachtelte Regeln\n```js\nU.minify_css('.menu {\\n\\t.item { color: red; }\\n\\t.active { font-weight: bold; }\\n}');\n// '.menu .item{color:red}.menu .active{font-weight:bold}'\n```\n\nExample: Variablen\n```js\nU.minify_css('$brand: #0066FF;\\n.button { background: $brand; }');\n// '.button{background:#0066FF}'\n```\n\n### U.minify_js(js)\n\nType: `method`\n\nMinifiziert JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `js` | `String` | yes |  | JavaScript-Quelltext. |\n\nReturns: `String` Minifizierter Code.\n\nEntfernt Kommentare, Zeilenumbrüche und unnötigen Leerraum. Strings bleiben unverändert. Variablen werden nicht umbenannt.\n\nExample: Minifizieren\n```js\nU.minify_js('if (a) {\\n\\tconsole.log(a); // log\\n}'); // 'if(a){console.log(a);}'\n```\n\n### U.minify_html(html)\n\nType: `method`\n\nMinifiziert HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML-Quelltext. |\n\nReturns: `String` Minifiziertes HTML.\n\nEntfernt Kommentare (keine bedingten Kommentare wie `<!--[if IE]>`) und fasst Folgen von Leerzeichen zwischen Wörtern zu einem Leerzeichen zusammen. Zeilenumbrüche und Einrückungen zwischen Tags bleiben erhalten. Der Inhalt von `<script>`, `<textarea>`, `<pre>`, `<code>` und `<readme>` wird nicht verändert. Eingebettete `<script>` und `<style>` werden mit den JS- und CSS-Minifiern minifiziert, wenn `$minifyjs` und `$minifycss` aktiv sind.\n\nExample: Minifizieren\n```js\nvar html = U.minify_html(source);\n```\n","entries":[{"type":"method","name":"U.minify_css()","signature":"U.minify_css(css)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(js)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"Jafin73oY61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/minification/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Minificación","summary":"U.minify_css(), U.minify_js() y U.minify_html().","markdown":"---\ntitle: \"Minificación\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/minification/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Minificación\n\n> U.minify_css(), U.minify_js() y U.minify_html().\n\n## API\n\n### U.minify_css(css)\n\nType: `method`\n\nMinifica CSS y compila reglas anidadas y `$variables`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `css` | `String` | yes |  | Código fuente CSS. |\n\nReturns: `String` CSS minificado.\n\nElimina los comentarios y los espacios en blanco, acorta `margin` y `padding` (`0 0 0 0` a `0`, `10px 20px 10px 20px` a `10px 20px`) y colores como `#FFFFFF`. Una regla que solo contiene otras reglas se expande (`.a { .b { } }` a `.a .b{}`). Las variables se declaran como `$name: value;` y se usan como `$name`. Ante un error, la función registra `CSS compiler error` y devuelve una cadena vacía.\n\nExample: Reglas anidadas\n```js\nU.minify_css('.menu {\\n\\t.item { color: red; }\\n\\t.active { font-weight: bold; }\\n}');\n// '.menu .item{color:red}.menu .active{font-weight:bold}'\n```\n\nExample: Variables\n```js\nU.minify_css('$brand: #0066FF;\\n.button { background: $brand; }');\n// '.button{background:#0066FF}'\n```\n\n### U.minify_js(js)\n\nType: `method`\n\nMinifica JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `js` | `String` | yes |  | Código fuente JavaScript. |\n\nReturns: `String` Código minificado.\n\nElimina los comentarios, los saltos de línea y los espacios en blanco innecesarios. Las cadenas se mantienen tal cual. No renombra variables.\n\nExample: Minificar\n```js\nU.minify_js('if (a) {\\n\\tconsole.log(a); // log\\n}'); // 'if(a){console.log(a);}'\n```\n\n### U.minify_html(html)\n\nType: `method`\n\nMinifica HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Código fuente HTML. |\n\nReturns: `String` HTML minificado.\n\nElimina los comentarios (no los comentarios condicionales como `<!--[if IE]>`) y colapsa las secuencias de espacios entre palabras en un solo espacio. Se conservan los saltos de línea y la sangría entre etiquetas. El contenido de `<script>`, `<textarea>`, `<pre>`, `<code>` y `<readme>` no se modifica. Los `<script>` y `<style>` en línea se minifican con los minificadores de JS y CSS cuando `$minifyjs` y `$minifycss` están activados.\n\nExample: Minificar\n```js\nvar html = U.minify_html(source);\n```\n","entries":[{"type":"method","name":"U.minify_css()","signature":"U.minify_css(css)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(js)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"Jafin73oY61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/minification/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Minification","summary":"U.minify_css(), U.minify_js() et U.minify_html().","markdown":"---\ntitle: Minification\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/minification/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Minification\n\n> U.minify_css(), U.minify_js() et U.minify_html().\n\n## API\n\n### U.minify_css(css)\n\nType: `method`\n\nMinifie du CSS et compile les règles imbriquées et les `$variables`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `css` | `String` | yes |  | Source CSS. |\n\nReturns: `String` Le CSS minifié.\n\nSupprime les commentaires et les espaces, raccourcit `margin` et `padding` (`0 0 0 0` en `0`, `10px 20px 10px 20px` en `10px 20px`) et les couleurs comme `#FFFFFF`. Une règle qui ne contient que d'autres règles est développée (`.a { .b { } }` en `.a .b{}`). Les variables sont déclarées sous la forme `$name: value;` et utilisées sous la forme `$name`. En cas d'erreur, la fonction journalise `CSS compiler error` et renvoie une chaîne vide.\n\nExample: Règles imbriquées\n```js\nU.minify_css('.menu {\\n\\t.item { color: red; }\\n\\t.active { font-weight: bold; }\\n}');\n// '.menu .item{color:red}.menu .active{font-weight:bold}'\n```\n\nExample: Variables\n```js\nU.minify_css('$brand: #0066FF;\\n.button { background: $brand; }');\n// '.button{background:#0066FF}'\n```\n\n### U.minify_js(js)\n\nType: `method`\n\nMinifie du JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `js` | `String` | yes |  | Source JavaScript. |\n\nReturns: `String` Le code minifié.\n\nSupprime les commentaires, les sauts de ligne et les espaces inutiles. Les chaînes sont conservées telles quelles. Elle ne renomme pas les variables.\n\nExample: Minifier\n```js\nU.minify_js('if (a) {\\n\\tconsole.log(a); // log\\n}'); // 'if(a){console.log(a);}'\n```\n\n### U.minify_html(html)\n\nType: `method`\n\nMinifie du HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Source HTML. |\n\nReturns: `String` HTML minifié.\n\nRetire les commentaires (pas les commentaires conditionnels comme `<!--[if IE]>`) et réduit les suites d'espaces entre les mots à un seul espace. Les retours à la ligne et l'indentation entre les balises sont conservés. Le contenu de `<script>`, `<textarea>`, `<pre>`, `<code>` et `<readme>` n'est pas modifié. Les `<script>` et `<style>` inline sont minifiés avec les minificateurs JS et CSS lorsque `$minifyjs` et `$minifycss` sont activés.\n\nExample: Minifier\n```js\nvar html = U.minify_html(source);\n```\n","entries":[{"type":"method","name":"U.minify_css()","signature":"U.minify_css(css)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(js)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"Jafin73oY61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/minification/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Minificazione","summary":"U.minify_css(), U.minify_js() e U.minify_html().","markdown":"---\ntitle: Minificazione\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/minification/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Minificazione\n\n> U.minify_css(), U.minify_js() e U.minify_html().\n\n## API\n\n### U.minify_css(css)\n\nType: `method`\n\nMinifica il CSS e compila le regole annidate e le `$variables`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `css` | `String` | yes |  | Sorgente CSS. |\n\nReturns: `String` CSS minificato.\n\nRimuove commenti e spazi, abbrevia `margin` e `padding` (`0 0 0 0` in `0`, `10px 20px 10px 20px` in `10px 20px`) e colori come `#FFFFFF`. Una regola che contiene solo altre regole viene espansa (`.a { .b { } }` in `.a .b{}`). Le variabili vengono dichiarate come `$name: value;` e usate come `$name`. In caso di errore la funzione registra `CSS compiler error` e restituisce una stringa vuota.\n\nExample: Regole annidate\n```js\nU.minify_css('.menu {\\n\\t.item { color: red; }\\n\\t.active { font-weight: bold; }\\n}');\n// '.menu .item{color:red}.menu .active{font-weight:bold}'\n```\n\nExample: Variabili\n```js\nU.minify_css('$brand: #0066FF;\\n.button { background: $brand; }');\n// '.button{background:#0066FF}'\n```\n\n### U.minify_js(js)\n\nType: `method`\n\nMinifica JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `js` | `String` | yes |  | Sorgente JavaScript. |\n\nReturns: `String` Codice minificato.\n\nRimuove commenti, a capo e spazi non necessari. Le stringhe restano come sono. Non rinomina le variabili.\n\nExample: Minificare\n```js\nU.minify_js('if (a) {\\n\\tconsole.log(a); // log\\n}'); // 'if(a){console.log(a);}'\n```\n\n### U.minify_html(html)\n\nType: `method`\n\nMinifica l'HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Sorgente HTML. |\n\nReturns: `String` HTML minificato.\n\nRimuove i commenti (non i commenti condizionali come `<!--[if IE]>`) e riduce a uno solo le sequenze di spazi tra le parole. Le interruzioni di riga e l'indentazione tra i tag vengono mantenute. Il contenuto di `<script>`, `<textarea>`, `<pre>`, `<code>` e `<readme>` non viene modificato. `<script>` e `<style>` inline vengono minificati con i minificatori JS e CSS quando `$minifyjs` e `$minifycss` sono attivi.\n\nExample: Minificare\n```js\nvar html = U.minify_html(source);\n```\n","entries":[{"type":"method","name":"U.minify_css()","signature":"U.minify_css(css)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(js)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"Jafin73oY61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/minification/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Minifikácia","summary":"U.minify_css(), U.minify_js() a U.minify_html().","markdown":"---\ntitle: \"Minifikácia\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/minification/\nupdated: 2026-11-18T16:57:24.576Z\n---\n\n# Minifikácia\n\n> U.minify_css(), U.minify_js() a U.minify_html().\n\n## API\n\n### U.minify_css(css)\n\nType: `method`\n\nMinifikuje CSS a kompiluje vnorené pravidlá a `$variables`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `css` | `String` | yes |  | Zdrojové CSS. |\n\nReturns: `String` Minifikované CSS.\n\nOdstráni komentáre a biele znaky, skráti `margin` a `padding` (`0 0 0 0` na `0`, `10px 20px 10px 20px` na `10px 20px`) a farby ako `#FFFFFF`. Pravidlo, ktoré obsahuje len iné pravidlá, sa rozvinie (`.a { .b { } }` na `.a .b{}`). Premenné sa deklarujú ako `$name: value;` a používajú ako `$name`. Pri chybe funkcia zaznamená `CSS compiler error` a vráti prázdny reťazec.\n\nExample: Vnorené pravidlá\n```js\nU.minify_css('.menu {\\n\\t.item { color: red; }\\n\\t.active { font-weight: bold; }\\n}');\n// '.menu .item{color:red}.menu .active{font-weight:bold}'\n```\n\nExample: Premenné\n```js\nU.minify_css('$brand: #0066FF;\\n.button { background: $brand; }');\n// '.button{background:#0066FF}'\n```\n\n### U.minify_js(js)\n\nType: `method`\n\nMinifikuje JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `js` | `String` | yes |  | Zdrojový JavaScript. |\n\nReturns: `String` Minifikovaný kód.\n\nOdstráni komentáre, zalomenia riadkov a nepotrebné biele znaky. Reťazce zostanú tak, ako sú. Premenné nepremenúva.\n\nExample: Minifikácia\n```js\nU.minify_js('if (a) {\\n\\tconsole.log(a); // log\\n}'); // 'if(a){console.log(a);}'\n```\n\n### U.minify_html(html)\n\nType: `method`\n\nMinifikuje HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML zdroj. |\n\nReturns: `String` Minifikované HTML.\n\nOdstráni komentáre (nie podmienené komentáre ako `<!--[if IE]>`) a viacnásobné medzery medzi slovami zlúči do jednej medzery. Zalomenia riadkov a odsadenie medzi tagmi sa zachovajú. Obsah `<script>`, `<textarea>`, `<pre>`, `<code>` a `<readme>` sa nemení. Inline `<script>` a `<style>` sa minifikujú JS a CSS minifikátormi, keď sú zapnuté `$minifyjs` a `$minifycss`.\n\nExample: Minifikácia\n```js\nvar html = U.minify_html(source);\n```\n","entries":[{"type":"method","name":"U.minify_css()","signature":"U.minify_css(css)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(js)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:24.576Z"}
{"id":"JaqmC62Dc60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/cms/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"CMS compiler","summary":"F.TCMS.compile(), the methods of a compiled page, F.TCMS.widgets() and F.TCMS.run().","markdown":"---\ntitle: CMS compiler\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/cms/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# CMS compiler\n\n> F.TCMS.compile(), the methods of a compiled page, F.TCMS.widgets() and F.TCMS.run().\n\n## API\n\n### F.TCMS.compile(html, widgets, [used])\n\nType: `method`\n\nCompiles a page of the Total.js CMS into a render object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML of the page. |\n| `widgets` | `Array|Object` | yes |  | Widgets as an array with `id`, or an object by id. A widget has `render(opt, next)` and optional `css`, `js` and `ui`. |\n| `used` | `Boolean` | no | `false` | Joins CSS and JS only of the widgets used on the page. |\n\nReturns: `CMSRender` Compiled page with `render()`, `importcss()`, `importjs()`, `importmeta()`, `css`, `js` and `widgets`.\n\nFinds the widgets (elements with `data-cms=\"<id>__<config>\"`, where config is URL-encoded JSON) and looks them up in `widgets` by `id`. Elements of unknown widgets are removed, widgets without `render` stay as static HTML. `<script type=\"text/navigation\" id=\"...\">` and `<script type=\"text/breadcrumb\">` become Tangular templates; the `id` of a navigation is its `id` attribute, or a hash of its `name` attribute when it has no `id`. Elements with the class `CMS_trash` or `CMS_editor` are removed. An element with `id=\"CMS\"` marks the place for the body when the page is used as a layout.\n\nThe CSS and JS of the widgets (`widget.css`, `widget.js`, and `widget.ui.css`, `widget.ui.js` from `F.TCMS.run()`) are minified into `page.css` and `page.js`, for all widgets or, with `used: true`, only for the widgets on the page.\n\nExample: Compile\n```js\nvar page = F.TCMS.compile(item.html, MAIN.widgets, true);\npage.importcss().importjs();\n```\n\n### cmsrender.render(meta, [layout], [callback])\n\nType: `method`\n\nRenders a compiled CMS page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Data for the widgets and templates, see the table. |\n| `layout` | `CMSRender` | no |  | A compiled layout page. |\n| `callback` | `Function` | no |  | `function(err, html)`. Without it a promise is returned. |\n\nReturns: `Promise` With the HTML when no callback is given.\n\nCalls `render(opt, next)` of every widget on the page, one after another, and fills the navigation and breadcrumb templates. `opt` contains all keys of `meta` (except `widgets`) and `id` (the `data-cms-id` of the element), `widget` (widget id), `config`, `html` (the inner HTML from the editor), `body`, `template` (the `<template>` of a widget from `F.TCMS.run()`, or an empty string) and `cacheid`.\n\nThe widget answers with `next(html, [replace], [cache])`: the HTML is put inside the widget element, or replaces the element with `replace: true`; `cache: true` keeps the output in the page for the next renders (a widget in `meta.widgets` with `cache: 'url'` caches per URL).\n\n| `meta` key | Description |\n| --- | --- |\n| `url` | URL of the request |\n| `navigation` | `function(id)` that returns the value of a navigation template |\n| `breadcrumb` | Array for the breadcrumb template |\n| `widgets` | Widgets that override the `render` of the compiled ones |\n| `body` | Content for the `id=\"CMS\"` element of a layout |\n| `inlinecache` | Object that stores the rendered navigations and breadcrumbs |\n\nWith `layout` (another compiled page) the output goes into `meta.body` and the layout is rendered.\n\nExample: In a route\n```js\nasync function page($) {\n\tvar html = await MAIN.page.render({ url: $.url, controller: $, navigation: id => MAIN.navigations[id] });\n\t$.html(html);\n}\n```\n\n### cmsrender.importcss([html])\n\nType: `method`\n\nInserts CSS before `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<style>' + page.css + '</style>'` | HTML to insert. |\n\nReturns: `CMSRender` The page.\n\nWithout an argument it inserts `<style>` with `page.css` (nothing when it is empty). When the page has no `</head>`, the CSS is appended to the end of the first static HTML part of the page: before the first widget when there is HTML before it, at the end of the page when the page has no widgets.\n\nExample: Link a file\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/page.css\">');\n```\n\n### cmsrender.importjs([html])\n\nType: `method`\n\nInserts JavaScript before `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<script>' + page.js + '</script>'` | HTML to insert. |\n\nReturns: `CMSRender` The page.\n\nWithout an argument it inserts `<script>` with `page.js` (nothing when it is empty). When the page has no `</body>`, the script is added at the end.\n\nExample: Inline\n```js\npage.importjs();\n```\n\n### cmsrender.importmeta(html)\n\nType: `method`\n\nInserts HTML before `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML to insert. |\n\nReturns: `CMSRender` The page.\n\nFor meta tags, a title or other head content. Nothing happens when the page has no `</head>`.\n\nExample: Meta\n```js\npage.importmeta('<meta name=\"description\" content=\"' + item.description.encode() + '\">');\n```\n\n### F.TCMS.widgets(html)\n\nType: `method`\n\nLists the widgets used in a CMS page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML of the page. |\n\nReturns: `Array` Widget elements.\n\nReturns an array with `id` (widget id), `uid` (`data-cms-id`), `config` (parsed JSON), `html` (inner HTML), `beg` and `end` (opening and closing tag) and `indexer` for every widget element. Useful to find which widgets a page needs.\n\nExample: Used widgets\n```js\nvar ids = F.TCMS.widgets(item.html).map(w => w.id);\n```\n\n### F.TCMS.run(html)\n\nType: `method`\n\nCreates a widget from its HTML source.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Widget source. |\n\nReturns: `Object` The widget.\n\nA widget source has the parts `<script total>` (server code that fills `exports`, such as `exports.id`, `exports.name` and `exports.render`), `<style>`, `<script>`, `<body>`, `<template>`, `<settings>` and `<readme>`. The word `CLASS` in the style, settings, template, script and body parts is replaced with `w-` and the id as a slug without dashes (`My Widget` gives `w-mywidget`). The returned object is the `exports` with `ui` (the parts, plus `cls` and `editor`), `id` (the name when missing), `dependencies` turned into `<script>`/`<link>` tags and `uninstall`. Pass such objects to `F.TCMS.compile()`.\n\nExample: Load widgets\n```js\nvar widgets = sources.map(source => F.TCMS.run(source));\nvar page = F.TCMS.compile(html, widgets);\n```\n","entries":[{"type":"method","name":"F.TCMS.compile()","signature":"F.TCMS.compile(html, widgets, [used])","since":"","deprecated":false},{"type":"method","name":"cmsrender.render()","signature":"cmsrender.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importcss()","signature":"cmsrender.importcss([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importjs()","signature":"cmsrender.importjs([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importmeta()","signature":"cmsrender.importmeta(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.widgets()","signature":"F.TCMS.widgets(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.run()","signature":"F.TCMS.run(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmC62Dc60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/cms/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"CMS-Compiler","summary":"F.TCMS.compile(), die Methoden einer kompilierten Seite, F.TCMS.widgets() und F.TCMS.run().","markdown":"---\ntitle: CMS-Compiler\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/cms/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# CMS-Compiler\n\n> F.TCMS.compile(), die Methoden einer kompilierten Seite, F.TCMS.widgets() und F.TCMS.run().\n\n## API\n\n### F.TCMS.compile(html, widgets, [used])\n\nType: `method`\n\nKompiliert eine Seite des Total.js CMS zu einem Render-Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML der Seite. |\n| `widgets` | `Array|Object` | yes |  | Widgets als Array mit `id` oder als Objekt nach ID. Ein Widget hat `render(opt, next)` und optional `css`, `js` und `ui`. |\n| `used` | `Boolean` | no | `false` | Fasst CSS und JS nur der auf der Seite verwendeten Widgets zusammen. |\n\nReturns: `CMSRender` Kompilierte Seite mit `render()`, `importcss()`, `importjs()`, `importmeta()`, `css`, `js` und `widgets`.\n\nFindet die Widgets (Elemente mit `data-cms=\"<id>__<config>\"`, wobei config URL-codiertes JSON ist) und sucht sie in `widgets` anhand der `id`. Elemente unbekannter Widgets werden entfernt, Widgets ohne `render` bleiben statisches HTML. `<script type=\"text/navigation\" id=\"...\">` und `<script type=\"text/breadcrumb\">` werden zu Tangular-Templates; die `id` einer Navigation ist ihr Attribut `id` oder ein Hash ihres Attributs `name`, wenn sie keine `id` hat. Elemente mit der Klasse `CMS_trash` oder `CMS_editor` werden entfernt. Ein Element mit `id=\"CMS\"` markiert die Stelle für den Body, wenn die Seite als Layout verwendet wird.\n\nDas CSS und JS der Widgets (`widget.css`, `widget.js` sowie `widget.ui.css`, `widget.ui.js` aus `F.TCMS.run()`) wird in `page.css` und `page.js` minifiziert, für alle Widgets oder, mit `used: true`, nur für die Widgets auf der Seite.\n\nExample: Kompilieren\n```js\nvar page = F.TCMS.compile(item.html, MAIN.widgets, true);\npage.importcss().importjs();\n```\n\n### cmsrender.render(meta, [layout], [callback])\n\nType: `method`\n\nRendert eine kompilierte CMS-Seite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Daten für die Widgets und Templates, siehe die Tabelle. |\n| `layout` | `CMSRender` | no |  | Eine kompilierte Layout-Seite. |\n| `callback` | `Function` | no |  | `function(err, html)`. Ohne ihn wird eine Promise zurückgegeben. |\n\nReturns: `Promise` Mit dem HTML, wenn kein Callback angegeben ist.\n\nRuft `render(opt, next)` jedes Widgets auf der Seite nacheinander auf und füllt die Navigations- und Breadcrumb-Templates. `opt` enthält alle Schlüssel von `meta` (außer `widgets`) sowie `id` (die `data-cms-id` des Elements), `widget` (Widget-ID), `config`, `html` (das innere HTML aus dem Editor), `body`, `template` (das `<template>` eines Widgets aus `F.TCMS.run()` oder ein leerer String) und `cacheid`.\n\nDas Widget antwortet mit `next(html, [replace], [cache])`: Das HTML wird in das Widget-Element eingefügt oder ersetzt mit `replace: true` das Element; `cache: true` behält die Ausgabe für die nächsten Render-Vorgänge in der Seite (ein Widget in `meta.widgets` mit `cache: 'url'` cacht pro URL).\n\n| Schlüssel von `meta` | Beschreibung |\n| --- | --- |\n| `url` | URL der Anfrage |\n| `navigation` | `function(id)`, die den Wert eines Navigations-Templates zurückgibt |\n| `breadcrumb` | Array für das Breadcrumb-Template |\n| `widgets` | Widgets, die das `render` der kompilierten überschreiben |\n| `body` | Inhalt für das Element `id=\"CMS\"` eines Layouts |\n| `inlinecache` | Objekt, das die gerenderten Navigationen und Breadcrumbs speichert |\n\nMit `layout` (einer anderen kompilierten Seite) geht die Ausgabe in `meta.body`, und das Layout wird gerendert.\n\nExample: In einer Route\n```js\nasync function page($) {\n\tvar html = await MAIN.page.render({ url: $.url, controller: $, navigation: id => MAIN.navigations[id] });\n\t$.html(html);\n}\n```\n\n### cmsrender.importcss([html])\n\nType: `method`\n\nFügt CSS vor `</head>` ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<style>' + page.css + '</style>'` | Einzufügendes HTML. |\n\nReturns: `CMSRender` Die Seite.\n\nOhne Argument fügt es `<style>` mit `page.css` ein (nichts, wenn es leer ist). Hat die Seite kein `</head>`, wird das CSS an das Ende des ersten statischen HTML-Teils der Seite angehängt: vor dem ersten Widget, wenn davor HTML steht, am Ende der Seite, wenn die Seite keine Widgets hat.\n\nExample: Eine Datei verlinken\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/page.css\">');\n```\n\n### cmsrender.importjs([html])\n\nType: `method`\n\nFügt JavaScript vor `</body>` ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<script>' + page.js + '</script>'` | Einzufügendes HTML. |\n\nReturns: `CMSRender` Die Seite.\n\nOhne Argument fügt sie `<script>` mit `page.js` ein (nichts, wenn es leer ist). Hat die Seite kein `</body>`, wird das Skript am Ende hinzugefügt.\n\nExample: Inline\n```js\npage.importjs();\n```\n\n### cmsrender.importmeta(html)\n\nType: `method`\n\nFügt HTML vor `</head>` ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Einzufügendes HTML. |\n\nReturns: `CMSRender` Die Seite.\n\nFür Meta-Tags, einen Titel oder anderen Head-Inhalt. Es passiert nichts, wenn die Seite kein `</head>` hat.\n\nExample: Meta\n```js\npage.importmeta('<meta name=\"description\" content=\"' + item.description.encode() + '\">');\n```\n\n### F.TCMS.widgets(html)\n\nType: `method`\n\nListet die in einer CMS-Seite verwendeten Widgets auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML der Seite. |\n\nReturns: `Array` Widget-Elemente.\n\nGibt für jedes Widget-Element ein Array mit `id` (Widget-ID), `uid` (`data-cms-id`), `config` (geparstes JSON), `html` (inneres HTML), `beg` und `end` (öffnendes und schließendes Tag) und `indexer` zurück. Nützlich, um herauszufinden, welche Widgets eine Seite braucht.\n\nExample: Verwendete Widgets\n```js\nvar ids = F.TCMS.widgets(item.html).map(w => w.id);\n```\n\n### F.TCMS.run(html)\n\nType: `method`\n\nErstellt ein Widget aus seinem HTML-Quellcode.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Widget-Quellcode. |\n\nReturns: `Object` Das Widget.\n\nEine Widget-Quelle hat die Teile `<script total>` (Servercode, der `exports` füllt, etwa `exports.id`, `exports.name` und `exports.render`), `<style>`, `<script>`, `<body>`, `<template>`, `<settings>` und `<readme>`. Das Wort `CLASS` in den Teilen style, settings, template, script und body wird durch `w-` und die ID als Slug ohne Bindestriche ersetzt (`My Widget` ergibt `w-mywidget`). Das zurückgegebene Objekt ist `exports` mit `ui` (die Teile, dazu `cls` und `editor`), `id` (der Name, wenn sie fehlt), `dependencies` umgewandelt in `<script>`/`<link>`-Tags und `uninstall`. Übergib solche Objekte an `F.TCMS.compile()`.\n\nExample: Widgets laden\n```js\nvar widgets = sources.map(source => F.TCMS.run(source));\nvar page = F.TCMS.compile(html, widgets);\n```\n","entries":[{"type":"method","name":"F.TCMS.compile()","signature":"F.TCMS.compile(html, widgets, [used])","since":"","deprecated":false},{"type":"method","name":"cmsrender.render()","signature":"cmsrender.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importcss()","signature":"cmsrender.importcss([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importjs()","signature":"cmsrender.importjs([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importmeta()","signature":"cmsrender.importmeta(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.widgets()","signature":"F.TCMS.widgets(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.run()","signature":"F.TCMS.run(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmC62Dc60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/cms/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Compilador del CMS","summary":"F.TCMS.compile(), los métodos de una página compilada, F.TCMS.widgets() y F.TCMS.run().","markdown":"---\ntitle: Compilador del CMS\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/cms/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Compilador del CMS\n\n> F.TCMS.compile(), los métodos de una página compilada, F.TCMS.widgets() y F.TCMS.run().\n\n## API\n\n### F.TCMS.compile(html, widgets, [used])\n\nType: `method`\n\nCompila una página del Total.js CMS en un objeto de renderizado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML de la página. |\n| `widgets` | `Array|Object` | yes |  | Widgets como array con `id`, o como objeto por id. Un widget tiene `render(opt, next)` y, opcionalmente, `css`, `js` y `ui`. |\n| `used` | `Boolean` | no | `false` | Une el CSS y el JS solo de los widgets usados en la página. |\n\nReturns: `CMSRender` Página compilada con `render()`, `importcss()`, `importjs()`, `importmeta()`, `css`, `js` y `widgets`.\n\nBusca los widgets (elementos con `data-cms=\"<id>__<config>\"`, donde config es JSON URL-encoded) y los localiza en `widgets` por `id`. Los elementos de widgets desconocidos se eliminan, y los widgets sin `render` quedan como HTML estático. `<script type=\"text/navigation\" id=\"...\">` y `<script type=\"text/breadcrumb\">` se convierten en plantillas Tangular; el `id` de una navegación es su atributo `id`, o un hash de su atributo `name` cuando no tiene `id`. Se eliminan los elementos con la clase `CMS_trash` o `CMS_editor`. Un elemento con `id=\"CMS\"` marca el lugar del cuerpo cuando la página se usa como plantilla (layout).\n\nEl CSS y el JS de los widgets (`widget.css`, `widget.js`, y `widget.ui.css`, `widget.ui.js` de `F.TCMS.run()`) se minifican en `page.css` y `page.js`, para todos los widgets o, con `used: true`, solo para los widgets de la página.\n\nExample: Compilar\n```js\nvar page = F.TCMS.compile(item.html, MAIN.widgets, true);\npage.importcss().importjs();\n```\n\n### cmsrender.render(meta, [layout], [callback])\n\nType: `method`\n\nRenderiza una página compilada del CMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Datos para los widgets y las plantillas, consulta la tabla. |\n| `layout` | `CMSRender` | no |  | Una página de plantilla (layout) compilada. |\n| `callback` | `Function` | no |  | `function(err, html)`. Sin él se devuelve una promesa. |\n\nReturns: `Promise` Con el HTML cuando no se indica callback.\n\nLlama a `render(opt, next)` de cada widget de la página, uno tras otro, y rellena las plantillas de navegación y de breadcrumb. `opt` contiene todas las claves de `meta` (excepto `widgets`) e `id` (el `data-cms-id` del elemento), `widget` (id del widget), `config`, `html` (el HTML interior del editor), `body`, `template` (el `<template>` de un widget de `F.TCMS.run()`, o un string vacío) y `cacheid`.\n\nEl widget responde con `next(html, [replace], [cache])`: el HTML se coloca dentro del elemento del widget, o sustituye el elemento con `replace: true`; `cache: true` guarda la salida en la página para los siguientes renderizados (un widget en `meta.widgets` con `cache: 'url'` guarda en caché por URL).\n\n| Clave de `meta` | Descripción |\n| --- | --- |\n| `url` | URL de la petición |\n| `navigation` | `function(id)` que devuelve el valor de una plantilla de navegación |\n| `breadcrumb` | Array para la plantilla de breadcrumb |\n| `widgets` | Widgets que sobrescriben el `render` de los compilados |\n| `body` | Contenido para el elemento `id=\"CMS\"` de una plantilla (layout) |\n| `inlinecache` | Objeto que guarda las navegaciones y breadcrumbs renderizados |\n\nCon `layout` (otra página compilada) la salida va a `meta.body` y se renderiza la plantilla (layout).\n\nExample: En una ruta\n```js\nasync function page($) {\n\tvar html = await MAIN.page.render({ url: $.url, controller: $, navigation: id => MAIN.navigations[id] });\n\t$.html(html);\n}\n```\n\n### cmsrender.importcss([html])\n\nType: `method`\n\nInserta CSS antes de `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<style>' + page.css + '</style>'` | HTML a insertar. |\n\nReturns: `CMSRender` La página.\n\nSin argumento inserta `<style>` con `page.css` (nada cuando está vacío). Cuando la página no tiene `</head>`, el CSS se añade al final de la primera parte HTML estática de la página: antes del primer widget cuando hay HTML antes de él, y al final de la página cuando la página no tiene widgets.\n\nExample: Enlazar un archivo\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/page.css\">');\n```\n\n### cmsrender.importjs([html])\n\nType: `method`\n\nInserta JavaScript antes de `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<script>' + page.js + '</script>'` | HTML a insertar. |\n\nReturns: `CMSRender` La página.\n\nSin argumento inserta `<script>` con `page.js` (nada cuando está vacío). Cuando la página no tiene `</body>`, el script se añade al final.\n\nExample: En línea\n```js\npage.importjs();\n```\n\n### cmsrender.importmeta(html)\n\nType: `method`\n\nInserta HTML antes de `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML a insertar. |\n\nReturns: `CMSRender` La página.\n\nPara meta tags, un título u otro contenido del head. No ocurre nada cuando la página no tiene `</head>`.\n\nExample: Meta\n```js\npage.importmeta('<meta name=\"description\" content=\"' + item.description.encode() + '\">');\n```\n\n### F.TCMS.widgets(html)\n\nType: `method`\n\nLista los widgets usados en una página del CMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML de la página. |\n\nReturns: `Array` Elementos de widget.\n\nDevuelve un array con `id` (id del widget), `uid` (`data-cms-id`), `config` (JSON analizado), `html` (HTML interior), `beg` y `end` (etiqueta de apertura y de cierre) e `indexer` para cada elemento de widget. Útil para saber qué widgets necesita una página.\n\nExample: Widgets usados\n```js\nvar ids = F.TCMS.widgets(item.html).map(w => w.id);\n```\n\n### F.TCMS.run(html)\n\nType: `method`\n\nCrea un widget a partir de su código fuente HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Código fuente del widget. |\n\nReturns: `Object` El widget.\n\nEl código fuente de un widget tiene las partes `<script total>` (código de servidor que rellena `exports`, como `exports.id`, `exports.name` y `exports.render`), `<style>`, `<script>`, `<body>`, `<template>`, `<settings>` y `<readme>`. La palabra `CLASS` en las partes style, settings, template, script y body se sustituye por `w-` y el id como slug sin guiones (`My Widget` da `w-mywidget`). El objeto devuelto es el `exports` con `ui` (las partes, más `cls` y `editor`), `id` (el nombre cuando falta), `dependencies` convertidas en etiquetas `<script>`/`<link>` y `uninstall`. Pasa estos objetos a `F.TCMS.compile()`.\n\nExample: Cargar widgets\n```js\nvar widgets = sources.map(source => F.TCMS.run(source));\nvar page = F.TCMS.compile(html, widgets);\n```\n","entries":[{"type":"method","name":"F.TCMS.compile()","signature":"F.TCMS.compile(html, widgets, [used])","since":"","deprecated":false},{"type":"method","name":"cmsrender.render()","signature":"cmsrender.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importcss()","signature":"cmsrender.importcss([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importjs()","signature":"cmsrender.importjs([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importmeta()","signature":"cmsrender.importmeta(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.widgets()","signature":"F.TCMS.widgets(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.run()","signature":"F.TCMS.run(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmC62Dc60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/cms/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Compilateur CMS","summary":"F.TCMS.compile(), les méthodes d'une page compilée, F.TCMS.widgets() et F.TCMS.run().","markdown":"---\ntitle: Compilateur CMS\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/cms/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Compilateur CMS\n\n> F.TCMS.compile(), les méthodes d'une page compilée, F.TCMS.widgets() et F.TCMS.run().\n\n## API\n\n### F.TCMS.compile(html, widgets, [used])\n\nType: `method`\n\nCompile une page du Total.js CMS en un objet de rendu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Le HTML de la page. |\n| `widgets` | `Array|Object` | yes |  | Les widgets sous forme de tableau avec `id`, ou d'objet indexé par id. Un widget possède `render(opt, next)` et, en option, `css`, `js` et `ui`. |\n| `used` | `Boolean` | no | `false` | Ne réunit le CSS et le JS que des widgets utilisés dans la page. |\n\nReturns: `CMSRender` La page compilée avec `render()`, `importcss()`, `importjs()`, `importmeta()`, `css`, `js` et `widgets`.\n\nTrouve les widgets (éléments avec `data-cms=\"<id>__<config>\"`, où config est du JSON URL-encoded) et les recherche dans `widgets` par `id`. Les éléments de widgets inconnus sont supprimés, les widgets sans `render` restent du HTML statique. `<script type=\"text/navigation\" id=\"...\">` et `<script type=\"text/breadcrumb\">` deviennent des templates Tangular ; l'`id` d'une navigation est son attribut `id`, ou un hash de son attribut `name` lorsqu'elle n'a pas d'`id`. Les éléments ayant la classe `CMS_trash` ou `CMS_editor` sont supprimés. Un élément avec `id=\"CMS\"` marque l'emplacement du corps lorsque la page est utilisée comme layout.\n\nLe CSS et le JS des widgets (`widget.css`, `widget.js`, ainsi que `widget.ui.css`, `widget.ui.js` de `F.TCMS.run()`) sont minifiés dans `page.css` et `page.js`, pour tous les widgets ou, avec `used: true`, uniquement pour les widgets de la page.\n\nExample: Compiler\n```js\nvar page = F.TCMS.compile(item.html, MAIN.widgets, true);\npage.importcss().importjs();\n```\n\n### cmsrender.render(meta, [layout], [callback])\n\nType: `method`\n\nEffectue le rendu d'une page CMS compilée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Les données pour les widgets et les templates, voir le tableau. |\n| `layout` | `CMSRender` | no |  | Une page de layout compilée. |\n| `callback` | `Function` | no |  | `function(err, html)`. Sans lui, une promesse est renvoyée. |\n\nReturns: `Promise` Avec le HTML quand aucun callback n'est fourni.\n\nAppelle `render(opt, next)` de chaque widget de la page, l'un après l'autre, et remplit les templates de navigation et de fil d'Ariane. `opt` contient toutes les clés de `meta` (sauf `widgets`) ainsi que `id` (le `data-cms-id` de l'élément), `widget` (l'id du widget), `config`, `html` (le HTML interne provenant de l'éditeur), `body`, `template` (le `<template>` d'un widget de `F.TCMS.run()`, ou une chaîne vide) et `cacheid`.\n\nLe widget répond avec `next(html, [replace], [cache])` : le HTML est placé dans l'élément du widget, ou remplace l'élément avec `replace: true` ; `cache: true` conserve la sortie dans la page pour les rendus suivants (un widget de `meta.widgets` avec `cache: 'url'` met en cache par URL).\n\n| Clé de `meta` | Description |\n| --- | --- |\n| `url` | URL de la requête |\n| `navigation` | `function(id)` qui renvoie la valeur d'un template de navigation |\n| `breadcrumb` | Tableau pour le template de fil d'Ariane |\n| `widgets` | Widgets qui remplacent le `render` des widgets compilés |\n| `body` | Contenu pour l'élément `id=\"CMS\"` d'un layout |\n| `inlinecache` | Objet qui stocke les navigations et fils d'Ariane rendus |\n\nAvec `layout` (une autre page compilée), la sortie va dans `meta.body` et le rendu du layout est effectué.\n\nExample: Dans une route\n```js\nasync function page($) {\n\tvar html = await MAIN.page.render({ url: $.url, controller: $, navigation: id => MAIN.navigations[id] });\n\t$.html(html);\n}\n```\n\n### cmsrender.importcss([html])\n\nType: `method`\n\nInsère du CSS avant `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<style>' + page.css + '</style>'` | Le HTML à insérer. |\n\nReturns: `CMSRender` La page.\n\nSans argument, elle insère `<style>` avec `page.css` (rien lorsqu'il est vide). Lorsque la page n'a pas de `</head>`, le CSS est ajouté à la fin de la première partie HTML statique de la page : avant le premier widget lorsqu'il y a du HTML avant lui, à la fin de la page lorsque la page n'a pas de widgets.\n\nExample: Lier un fichier\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/page.css\">');\n```\n\n### cmsrender.importjs([html])\n\nType: `method`\n\nInsère du JavaScript avant `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<script>' + page.js + '</script>'` | Le HTML à insérer. |\n\nReturns: `CMSRender` La page.\n\nSans argument, elle insère `<script>` avec `page.js` (rien quand il est vide). Quand la page n'a pas de `</body>`, le script est ajouté à la fin.\n\nExample: En ligne\n```js\npage.importjs();\n```\n\n### cmsrender.importmeta(html)\n\nType: `method`\n\nInsère du HTML avant `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Le HTML à insérer. |\n\nReturns: `CMSRender` La page.\n\nPour les balises meta, un titre ou tout autre contenu de l'en-tête. Rien ne se passe quand la page n'a pas de `</head>`.\n\nExample: Meta\n```js\npage.importmeta('<meta name=\"description\" content=\"' + item.description.encode() + '\">');\n```\n\n### F.TCMS.widgets(html)\n\nType: `method`\n\nListe les widgets utilisés dans une page CMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Le HTML de la page. |\n\nReturns: `Array` Les éléments de widgets.\n\nRenvoie un tableau avec `id` (l'id du widget), `uid` (`data-cms-id`), `config` (le JSON analysé), `html` (le HTML intérieur), `beg` et `end` (les balises ouvrante et fermante) et `indexer` pour chaque élément de widget. Utile pour savoir de quels widgets une page a besoin.\n\nExample: Widgets utilisés\n```js\nvar ids = F.TCMS.widgets(item.html).map(w => w.id);\n```\n\n### F.TCMS.run(html)\n\nType: `method`\n\nCrée un widget à partir de sa source HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | La source du widget. |\n\nReturns: `Object` Le widget.\n\nUne source de widget comporte les parties `<script total>` (code serveur qui remplit `exports`, comme `exports.id`, `exports.name` et `exports.render`), `<style>`, `<script>`, `<body>`, `<template>`, `<settings>` et `<readme>`. Le mot `CLASS` dans les parties style, settings, template, script et body est remplacé par `w-` et l'id sous forme de slug sans tirets (`My Widget` donne `w-mywidget`). L'objet renvoyé est l'`exports` avec `ui` (les parties, plus `cls` et `editor`), `id` (le nom lorsqu'il manque), `dependencies` transformées en balises `<script>`/`<link>` et `uninstall`. Passe de tels objets à `F.TCMS.compile()`.\n\nExample: Charger des widgets\n```js\nvar widgets = sources.map(source => F.TCMS.run(source));\nvar page = F.TCMS.compile(html, widgets);\n```\n","entries":[{"type":"method","name":"F.TCMS.compile()","signature":"F.TCMS.compile(html, widgets, [used])","since":"","deprecated":false},{"type":"method","name":"cmsrender.render()","signature":"cmsrender.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importcss()","signature":"cmsrender.importcss([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importjs()","signature":"cmsrender.importjs([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importmeta()","signature":"cmsrender.importmeta(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.widgets()","signature":"F.TCMS.widgets(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.run()","signature":"F.TCMS.run(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmC62Dc60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/cms/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Compilatore CMS","summary":"F.TCMS.compile(), i metodi di una pagina compilata, F.TCMS.widgets() e F.TCMS.run().","markdown":"---\ntitle: Compilatore CMS\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/cms/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# Compilatore CMS\n\n> F.TCMS.compile(), i metodi di una pagina compilata, F.TCMS.widgets() e F.TCMS.run().\n\n## API\n\n### F.TCMS.compile(html, widgets, [used])\n\nType: `method`\n\nCompila una pagina del Total.js CMS in un oggetto di rendering.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML della pagina. |\n| `widgets` | `Array|Object` | yes |  | Widget come array con `id`, o come oggetto per id. Un widget ha `render(opt, next)` e facoltativamente `css`, `js` e `ui`. |\n| `used` | `Boolean` | no | `false` | Unisce CSS e JS solo dei widget usati nella pagina. |\n\nReturns: `CMSRender` Pagina compilata con `render()`, `importcss()`, `importjs()`, `importmeta()`, `css`, `js` e `widgets`.\n\nTrova i widget (elementi con `data-cms=\"<id>__<config>\"`, dove config è JSON URL-encoded) e li cerca in `widgets` per `id`. Gli elementi di widget sconosciuti vengono rimossi, i widget senza `render` restano come HTML statico. `<script type=\"text/navigation\" id=\"...\">` e `<script type=\"text/breadcrumb\">` diventano template Tangular; l'`id` di una navigazione è il suo attributo `id`, o un hash del suo attributo `name` quando non ha un `id`. Gli elementi con la classe `CMS_trash` o `CMS_editor` vengono rimossi. Un elemento con `id=\"CMS\"` indica il punto per il body quando la pagina viene usata come layout.\n\nIl CSS e il JS dei widget (`widget.css`, `widget.js`, e `widget.ui.css`, `widget.ui.js` da `F.TCMS.run()`) vengono minificati in `page.css` e `page.js`, per tutti i widget o, con `used: true`, solo per i widget presenti nella pagina.\n\nExample: Compilare\n```js\nvar page = F.TCMS.compile(item.html, MAIN.widgets, true);\npage.importcss().importjs();\n```\n\n### cmsrender.render(meta, [layout], [callback])\n\nType: `method`\n\nEsegue il rendering di una pagina CMS compilata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Dati per i widget e i template, vedi la tabella. |\n| `layout` | `CMSRender` | no |  | Una pagina di layout compilata. |\n| `callback` | `Function` | no |  | `function(err, html)`. Senza di essa viene restituita una promise. |\n\nReturns: `Promise` Con l'HTML quando non viene passata una callback.\n\nChiama `render(opt, next)` di ogni widget della pagina, uno dopo l'altro, e riempie i template di navigazione e breadcrumb. `opt` contiene tutte le chiavi di `meta` (tranne `widgets`) e `id` (il `data-cms-id` dell'elemento), `widget` (id del widget), `config`, `html` (l'HTML interno dall'editor), `body`, `template` (il `<template>` di un widget da `F.TCMS.run()`, oppure una stringa vuota) e `cacheid`.\n\nIl widget risponde con `next(html, [replace], [cache])`: l'HTML viene inserito dentro l'elemento del widget, oppure sostituisce l'elemento con `replace: true`; `cache: true` conserva l'output nella pagina per i rendering successivi (un widget in `meta.widgets` con `cache: 'url'` usa una cache per URL).\n\n| Chiave di `meta` | Descrizione |\n| --- | --- |\n| `url` | URL della richiesta |\n| `navigation` | `function(id)` che restituisce il valore di un template di navigazione |\n| `breadcrumb` | Array per il template del breadcrumb |\n| `widgets` | Widget che sostituiscono il `render` di quelli compilati |\n| `body` | Contenuto per l'elemento `id=\"CMS\"` di un layout |\n| `inlinecache` | Oggetto che conserva le navigazioni e i breadcrumb renderizzati |\n\nCon `layout` (un'altra pagina compilata) l'output va in `meta.body` e viene renderizzato il layout.\n\nExample: In una route\n```js\nasync function page($) {\n\tvar html = await MAIN.page.render({ url: $.url, controller: $, navigation: id => MAIN.navigations[id] });\n\t$.html(html);\n}\n```\n\n### cmsrender.importcss([html])\n\nType: `method`\n\nInserisce CSS prima di `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<style>' + page.css + '</style>'` | HTML da inserire. |\n\nReturns: `CMSRender` La pagina.\n\nSenza argomenti inserisce `<style>` con `page.css` (nulla quando è vuoto). Quando la pagina non ha `</head>`, il CSS viene aggiunto alla fine della prima parte HTML statica della pagina: prima del primo widget quando c'è HTML prima di esso, alla fine della pagina quando la pagina non ha widget.\n\nExample: Collegare un file\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/page.css\">');\n```\n\n### cmsrender.importjs([html])\n\nType: `method`\n\nInserisce JavaScript prima di `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<script>' + page.js + '</script>'` | HTML da inserire. |\n\nReturns: `CMSRender` La pagina.\n\nSenza argomento inserisce `<script>` con `page.js` (niente quando è vuoto). Quando la pagina non ha `</body>`, lo script viene aggiunto alla fine.\n\nExample: Inline\n```js\npage.importjs();\n```\n\n### cmsrender.importmeta(html)\n\nType: `method`\n\nInserisce HTML prima di `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML da inserire. |\n\nReturns: `CMSRender` La pagina.\n\nPer meta tag, un titolo o altro contenuto dell'head. Non succede nulla quando la pagina non ha `</head>`.\n\nExample: Meta\n```js\npage.importmeta('<meta name=\"description\" content=\"' + item.description.encode() + '\">');\n```\n\n### F.TCMS.widgets(html)\n\nType: `method`\n\nElenca i widget usati in una pagina CMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML della pagina. |\n\nReturns: `Array` Elementi widget.\n\nRestituisce un array con `id` (id del widget), `uid` (`data-cms-id`), `config` (JSON analizzato), `html` (HTML interno), `beg` ed `end` (tag di apertura e di chiusura) e `indexer` per ogni elemento widget. Utile per scoprire quali widget servono a una pagina.\n\nExample: Widget usati\n```js\nvar ids = F.TCMS.widgets(item.html).map(w => w.id);\n```\n\n### F.TCMS.run(html)\n\nType: `method`\n\nCrea un widget dal suo sorgente HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Sorgente del widget. |\n\nReturns: `Object` Il widget.\n\nUna sorgente di widget ha le parti `<script total>` (codice server che riempie `exports`, come `exports.id`, `exports.name` e `exports.render`), `<style>`, `<script>`, `<body>`, `<template>`, `<settings>` e `<readme>`. La parola `CLASS` nelle parti style, settings, template, script e body viene sostituita con `w-` e l'id come slug senza trattini (`My Widget` dà `w-mywidget`). L'oggetto restituito è l'`exports` con `ui` (le parti, più `cls` e `editor`), `id` (il nome quando manca), `dependencies` trasformate in tag `<script>`/`<link>` e `uninstall`. Passa tali oggetti a `F.TCMS.compile()`.\n\nExample: Caricare i widget\n```js\nvar widgets = sources.map(source => F.TCMS.run(source));\nvar page = F.TCMS.compile(html, widgets);\n```\n","entries":[{"type":"method","name":"F.TCMS.compile()","signature":"F.TCMS.compile(html, widgets, [used])","since":"","deprecated":false},{"type":"method","name":"cmsrender.render()","signature":"cmsrender.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importcss()","signature":"cmsrender.importcss([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importjs()","signature":"cmsrender.importjs([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importmeta()","signature":"cmsrender.importmeta(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.widgets()","signature":"F.TCMS.widgets(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.run()","signature":"F.TCMS.run(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"JaqmC62Dc60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/cms/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"CMS kompilátor","summary":"F.TCMS.compile(), metódy skompilovanej stránky, F.TCMS.widgets() a F.TCMS.run().","markdown":"---\ntitle: \"CMS kompilátor\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/cms/\nupdated: 2026-11-19T16:17:02.153Z\n---\n\n# CMS kompilátor\n\n> F.TCMS.compile(), metódy skompilovanej stránky, F.TCMS.widgets() a F.TCMS.run().\n\n## API\n\n### F.TCMS.compile(html, widgets, [used])\n\nType: `method`\n\nSkompiluje stránku Total.js CMS do renderovacieho objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML stránky. |\n| `widgets` | `Array|Object` | yes |  | Widgety ako pole s `id`, alebo objekt podľa id. Widget má `render(opt, next)` a voliteľne `css`, `js` a `ui`. |\n| `used` | `Boolean` | no | `false` | Spojí CSS a JS len widgetov použitých na stránke. |\n\nReturns: `CMSRender` Skompilovaná stránka s `render()`, `importcss()`, `importjs()`, `importmeta()`, `css`, `js` a `widgets`.\n\nNájde widgety (elementy s `data-cms=\"<id>__<config>\"`, kde config je URL-encoded JSON) a vyhľadá ich vo `widgets` podľa `id`. Elementy neznámych widgetov sa odstránia, widgety bez `render` zostanú ako statické HTML. `<script type=\"text/navigation\" id=\"...\">` a `<script type=\"text/breadcrumb\">` sa stanú šablónami Tangular; `id` navigácie je jej atribút `id` alebo hash jej atribútu `name`, keď `id` nemá. Elementy s triedou `CMS_trash` alebo `CMS_editor` sa odstránia. Element s `id=\"CMS\"` označuje miesto pre telo, keď sa stránka používa ako layout.\n\nCSS a JS widgetov (`widget.css`, `widget.js` a `widget.ui.css`, `widget.ui.js` z `F.TCMS.run()`) sa minifikujú do `page.css` a `page.js`, pre všetky widgety alebo s `used: true` iba pre widgety na stránke.\n\nExample: Kompilácia\n```js\nvar page = F.TCMS.compile(item.html, MAIN.widgets, true);\npage.importcss().importjs();\n```\n\n### cmsrender.render(meta, [layout], [callback])\n\nType: `method`\n\nVyrenderuje skompilovanú stránku CMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Dáta pre widgety a šablóny, pozri tabuľku. |\n| `layout` | `CMSRender` | no |  | Skompilovaná stránka layoutu. |\n| `callback` | `Function` | no |  | `function(err, html)`. Bez neho sa vráti promise. |\n\nReturns: `Promise` S HTML, keď nie je zadaný callback.\n\nZavolá `render(opt, next)` každého widgetu na stránke, jeden po druhom, a vyplní šablóny navigácie a breadcrumbu. `opt` obsahuje všetky kľúče z `meta` (okrem `widgets`) a `id` (`data-cms-id` elementu), `widget` (id widgetu), `config`, `html` (vnútorné HTML z editora), `body`, `template` (`<template>` widgetu z `F.TCMS.run()` alebo prázdny reťazec) a `cacheid`.\n\nWidget odpovie cez `next(html, [replace], [cache])`: HTML sa vloží do elementu widgetu alebo s `replace: true` element nahradí; `cache: true` ponechá výstup v stránke pre ďalšie vykreslenia (widget v `meta.widgets` s `cache: 'url'` ukladá do cache podľa URL).\n\n| Kľúč `meta` | Popis |\n| --- | --- |\n| `url` | URL požiadavky |\n| `navigation` | `function(id)`, ktorá vráti hodnotu šablóny navigácie |\n| `breadcrumb` | Pole pre šablónu breadcrumbu |\n| `widgets` | Widgety, ktoré prepíšu `render` skompilovaných widgetov |\n| `body` | Obsah pre element `id=\"CMS\"` layoutu |\n| `inlinecache` | Objekt, ktorý ukladá vykreslené navigácie a breadcrumby |\n\nS `layout` (inou skompilovanou stránkou) ide výstup do `meta.body` a vykreslí sa layout.\n\nExample: V route\n```js\nasync function page($) {\n\tvar html = await MAIN.page.render({ url: $.url, controller: $, navigation: id => MAIN.navigations[id] });\n\t$.html(html);\n}\n```\n\n### cmsrender.importcss([html])\n\nType: `method`\n\nVloží CSS pred `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<style>' + page.css + '</style>'` | HTML na vloženie. |\n\nReturns: `CMSRender` Stránka.\n\nBez argumentu vloží `<style>` s `page.css` (nič, keď je prázdne). Keď stránka nemá `</head>`, CSS sa pripojí na koniec prvej statickej HTML časti stránky: pred prvý widget, keď je pred ním HTML, na koniec stránky, keď stránka nemá widgety.\n\nExample: Prepojenie súboru\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/page.css\">');\n```\n\n### cmsrender.importjs([html])\n\nType: `method`\n\nVloží JavaScript pred `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | no | `'<script>' + page.js + '</script>'` | HTML na vloženie. |\n\nReturns: `CMSRender` Stránka.\n\nBez argumentu vloží `<script>` s `page.js` (nič, keď je prázdne). Keď stránka nemá `</body>`, skript sa pridá na koniec.\n\nExample: Inline\n```js\npage.importjs();\n```\n\n### cmsrender.importmeta(html)\n\nType: `method`\n\nVloží HTML pred `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML na vloženie. |\n\nReturns: `CMSRender` Stránka.\n\nPre meta tagy, titulok alebo iný obsah hlavičky. Keď stránka nemá `</head>`, nestane sa nič.\n\nExample: Meta\n```js\npage.importmeta('<meta name=\"description\" content=\"' + item.description.encode() + '\">');\n```\n\n### F.TCMS.widgets(html)\n\nType: `method`\n\nVypíše widgety použité na stránke CMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML stránky. |\n\nReturns: `Array` Elementy widgetov.\n\nVráti pole s `id` (id widgetu), `uid` (`data-cms-id`), `config` (sparsovaný JSON), `html` (vnútorné HTML), `beg` a `end` (otvárací a zatvárací tag) a `indexer` pre každý element widgetu. Hodí sa na zistenie, ktoré widgety stránka potrebuje.\n\nExample: Použité widgety\n```js\nvar ids = F.TCMS.widgets(item.html).map(w => w.id);\n```\n\n### F.TCMS.run(html)\n\nType: `method`\n\nVytvorí widget z jeho HTML zdroja.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Zdroj widgetu. |\n\nReturns: `Object` Widget.\n\nZdroj widgetu má časti `<script total>` (serverový kód, ktorý napĺňa `exports`, napríklad `exports.id`, `exports.name` a `exports.render`), `<style>`, `<script>`, `<body>`, `<template>`, `<settings>` a `<readme>`. Slovo `CLASS` v častiach style, settings, template, script a body sa nahradí `w-` a id ako slugom bez pomlčiek (`My Widget` dá `w-mywidget`). Vrátený objekt je `exports` s `ui` (časti plus `cls` a `editor`), `id` (názov, keď chýba), `dependencies` zmenenými na tagy `<script>`/`<link>` a `uninstall`. Takéto objekty odovzdaj do `F.TCMS.compile()`.\n\nExample: Načítanie widgetov\n```js\nvar widgets = sources.map(source => F.TCMS.run(source));\nvar page = F.TCMS.compile(html, widgets);\n```\n","entries":[{"type":"method","name":"F.TCMS.compile()","signature":"F.TCMS.compile(html, widgets, [used])","since":"","deprecated":false},{"type":"method","name":"cmsrender.render()","signature":"cmsrender.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importcss()","signature":"cmsrender.importcss([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importjs()","signature":"cmsrender.importjs([html])","since":"","deprecated":false},{"type":"method","name":"cmsrender.importmeta()","signature":"cmsrender.importmeta(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.widgets()","signature":"F.TCMS.widgets(html)","since":"","deprecated":false},{"type":"method","name":"F.TCMS.run()","signature":"F.TCMS.run(html)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T16:17:02.153Z"}
{"id":"Jafwuo6Px60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/application-structure/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Application structure and modes","summary":"F.run() and its start options, LOAD(), IMPORT(), REQUIRE(), MODS and the framework statistics.","markdown":"---\ntitle: Application structure and modes\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/application-structure/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Application structure and modes\n\n> F.run() and its start options, LOAD(), IMPORT(), REQUIRE(), MODS and the framework statistics.\n\nThe functions that start and load a Total.js 5 application: `F.run()` with every start option, `F.http()`, `LOAD()`, `IMPORT()`, `REQUIRE()`, `MODS`, `F.restart()`, `F.exit()`, the statistics in `F.stats` and `F.consumption`, the watcher events and the `bundling` key.\n\nThe guide [Application structure and modes](../../guides/application-structure/) explains the folders, the loading order, debug and release mode, bundles and remote editing.\n\nThe `Test` runner has its own page: [Unit tests](../unit-tests/).\n\n## API\n\n### F.run([options])\n\nType: `method`\n\nStarts the application in debug mode with the watcher, or in release mode.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | The start options: `ip`, `port`, `unixsocket`, `config`, `load`, `watcher`, `release`, `servicemode`, `watch`, `livereload`, `inspector`, `debugger`, `cluster`, `limit`, `edit`, `editmcp`. |\n\nReturns: `undefined`\n\nThe usual last line of the start script. Without `options.watcher = false` it starts the debug watcher (`debug.js`): the application runs in a child process and restarts when a file changes. With `watcher: false` it starts release mode (`release.js`): the application runs in the same process with `DEBUG = false`. The options are passed to `F.http()` (or to `LOAD()` in service mode) in the application process. `Total.run()` is the same function.\n\nExample: Debug mode\n```js\nrequire('total5');\nF.run({ port: 8000 });\n```\n\nExample: Release mode\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nExample: Mode from the command line\n```js\nrequire('total5');\n\nvar options = {};\noptions.port = 8000;\n\nif (process.argv.includes('--release'))\n\toptions.watcher = false;\n\nF.run(options);\n```\n\n### F.http([options])\n\nType: `method`\n\nLoads the application and starts the HTTP server in the current process.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | `ip`, `port`, `unixsocket`, `unixsocket777`, `config`, `load` (alias `type`) and `clear`. |\n\nReturns: `undefined`\n\nApplies `options.config` with `LOADCONFIG()`, calls `LOAD()` with `options.load` and then starts the server. When the application is already loaded, it only (re)starts the server; a running server is closed first. With the default `CONF.$port = 'auto'`, the port is taken from `options.port`, then from the `PORT` environment variable, then from the first argument of the process with 3 to 5 digits (`node index.js 8000`), and the default is `8000`. When the process has no parent, it prints the start information.\n\n`F.run()` calls it for you; call it directly in scripts that start the server without a watcher (tests, tools).\n\nExample: Server for tests\n```js\nrequire('total5');\nF.http({ port: 8001, config: { name: 'Test' } });\n```\n\n### LOAD([types], [callback], [clear])\n\nType: `method`\n\nLoads the configuration, the resources and the JavaScript files of the application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no | `''` | The parts to load, as a comma-separated string or an array; empty loads everything. |\n| `callback` | `Function` | no |  | `function()` called when everything is loaded. |\n| `clear` | `Boolean` | no | `true` | Clears the temporary folder before loading. |\n\nReturns: `Promise` Resolves when everything is loaded.\n\n`F.load()` is the same function. It sets the directories, builds bundles, removes the `.js`, `.css`, `.html`, `.htm`, `.tmp` and `.upload` files from the temporary folder (when `clear` is `true`) and then loads the parts in the order of the guide. Without `types` it loads everything. The names are `env`, `config`, `version`, `resources`, `jsonschemas`, `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers`, `middleware`, `plugins`, `flowstreams` and `stats`; any other name, such as `none`, loads nothing. When `types` is given without `stats`, the statistics and the source maps are turned off.\n\nAt the end it starts the service timer, sets `F.isLoaded`, `F.stats.compiled` and `F.stats.compilation`, calls `callback` and emits `ready` and `load`. It does not start the HTTP server.\n\nExample: Background process\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\tACTION('Jobs/run').callback(console.log);\n});\n```\n\nExample: With await\n```js\nrequire('total5');\n\n(async function() {\n\tawait LOAD('env,config');\n\tconsole.log(CONF.name);\n})();\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nDownloads a JavaScript file and loads it as a module.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL of a `.js` file. |\n| `callback` | `Function` | no |  | `function(err, module, response)` |\n\nReturns: `Promise` When `callback` is not set.\n\nThe file is downloaded into the temporary folder and loaded with `require()`. Further calls with the same URL in the same process return the loaded module without downloading it again. An answer with the status `400` or more gives the error `The address answered with the status <status>` and nothing is loaded. A file that is not a valid module gives the error of `require()`, for example a `SyntaxError`. The callback receives `(err, module, response)`; without a callback the function returns a Promise with the module.\n\nExample: Promise\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n\nExample: Callback\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, helpers) {\n\tif (err)\n\t\tconsole.error(err);\n\telse\n\t\thelpers.hello();\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nLoads a Node.js module or an NPM package.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the module or package. |\n\nReturns: `Object` The module.\n\nNames with the `node:` prefix and Node.js built-in modules (`fs`, `path`, `crypto`, ...) are loaded directly. Other names are loaded with `require()` and, when that fails, from the folder in `CONF.$nodemodules` (`<application>/node_modules` by default), so packages installed with `NPMINSTALL()` are found. It throws when the module cannot be loaded.\n\nExample: Load\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### MODS\n\nType: `property`\n\nThe loaded modules from the `modules` folder, by their id.\n\nReturns: `Object`\n\nThe same object as `F.modules`. Each file in `modules` is registered under its `exports.id`, or under the file name without `.js` when `id` is missing, before its `install()` is called. Use it to call the functions that a module exports.\n\nExample: Call a module\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// a controller or an action\nMODS.counter.increment();\n```\n\n### F.isLoaded\n\nType: `property`\n\n`true` when the application is loaded.\n\nReturns: `Boolean`\n\nSet by `LOAD()` after all files are loaded, just before the `ready` and `load` events.\n\nExample: Check\n```js\nif (F.isLoaded)\n\tconsole.log('Ready');\n```\n\n### F.directory\n\nType: `property`\n\nThe root folder of the application.\n\nReturns: `String`\n\nThe current working directory of the process when `total5` is loaded. When the application runs from bundles, it points to the `.src` folder. All `PATH.root()` paths start here.\n\nExample: Read\n```js\nconsole.log(F.directory);\nconsole.log(PATH.root('config'));\n```\n\n### F.isBundle\n\nType: `property`\n\n`true` when the application runs from bundles.\n\nReturns: `Boolean`\n\nSet when the `bundles` folder contains bundles (or `bundles.debug` exists) and the application was built into `.src`.\n\nExample: Check\n```js\nif (F.isBundle)\n\tconsole.log('Running from', F.directory);\n```\n\n### F.dir([directory])\n\nType: `method`\n\nSets the root folder and recomputes the folders of the application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no |  | A new root folder. |\n\nReturns: `undefined`\n\nWith `directory` it changes `F.directory`. Then it sets the paths in `F.temporary.directories` for `public`, `tmp`, `logs`, `databases`, `controllers`, `resources`, `plugins`, `modules`, `views`, `definitions`, `schemas`, `models`, `flowstreams`, `bundles`, `actions`, `extensions`, `source`, `services`, `updates`, `templates`, `private` and `scripts`: each one is the value of `CONF.$dir<name>` when it is set, otherwise `<root>/<name>`. `LOAD()` calls it at the start.\n\nExample: Read a folder\n```js\nF.dir();\nconsole.log(F.temporary.directories.public);\n```\n\n### F.restart()\n\nType: `method`\n\nAsks the watcher to restart the application.\n\nReturns: `undefined`\n\nSends `total:restart` to the parent process. The debug watcher, and the release watcher started with `--watcher`, print `RES` and start the application again. Without a watcher nothing happens.\n\nExample: After an update\n```js\nNEWACTION('Settings/save', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tF.Fs.writeFile(PATH.root('config'), 'name : ' + model.name, function() {\n\t\t\t$.success();\n\t\t\tF.restart();\n\t\t});\n\t}\n});\n```\n\n### F.exit([signal])\n\nType: `method`\n\nStops the application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | no | `15` | The signal for the child processes. |\n\nReturns: `undefined`\n\nKills the workers and Python pipelines with `signal`, destroys the FlowStream instances, emits `exit`, tells the parent process `total:stop`, stops the service timer and closes the HTTP server. The process ends 300 ms later. The framework calls it on `SIGTERM`, `SIGINT` and when the process exits.\n\nExample: Stop\n```js\nON('exit', function() {\n\tconsole.log('Bye');\n});\n\nF.exit();\n```\n\n### F.console()\n\nType: `method`\n\nPrints the start information.\n\nReturns: `undefined`\n\nPrints the PID, the versions of Node.js and Total.js, the system, the memory, the user, the name, version and author of the application, the date with the time zone, the mode (`debug` or `release`), the number of compiled files with the time, the root, directory and `node_modules` paths and the address of the server. Nothing is printed when `CONF.$imprint` is `false`. The framework calls it after the start.\n\nExample: Print it again\n```js\nON('ready', function() {\n\tF.console();\n});\n```\n\n### F.remote(url, [directory])\n\nType: `method`\n\nConnects the folder of the application to the Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL from the editor, `wss://...?id=project`. |\n| `directory` | `String` | no | `F.directory` | The folder to edit. |\n\nReturns: `undefined`\n\nStarts the remote editing client in the current process: a WebSocket connection to `url` that lets the editor browse and change the files in `directory`. It reconnects every 10 seconds when the connection is lost. The `edit` start option does the same in the watcher process.\n\nExample: Connect\n```js\nF.remote('wss://code.example.com/?id=myproject');\n```\n\n### F.consumption\n\nType: `property`\n\nThe usage statistics of the process, updated once a minute.\n\nReturns: `Object`\n\nThe same object every minute (the first time 5 seconds after the application is loaded); `ON('$stats')` gets it too and, with `CONF.$stats`, it is written into `<script>.json`. Fields: `id`, `pid`, `thread`, `mode` (`debug` or `release`), `version` (`node`, `total`, `build`, `app` from `CONF.version`), `app` (`name` and `url` from the configuration), `date`, `memory` (used heap in MB), `requests`, `pending`, `external`, `errors`, `timeouts`, `online` (WebSocket clients), `download` and `upload` (MB in total), `lasterror`, `lasttimeout`, `usage` (percent), `overload` (hours with high load), `uptime` (minutes since the start) and the per-minute counters `rm`, `fm`, `wm`, `em`, `mm`, `om`, `dm`, `um`, `pm`, `sm`, `cm`, `dbrm` and `dbwm`.\n\nExample: Read\n```js\nsetInterval(function() {\n\tconsole.log(F.consumption.memory, 'MB', F.consumption.requests, 'requests');\n}, 60000);\n```\n\n### F.stats\n\nType: `property`\n\nCounters of the framework for the whole life of the process.\n\nReturns: `Object`\n\n`F.stats.request` counts requests (`request`, `web`, `xhr`, `file`, `websocket`, `get`, `post`, `put`, `patch`, `delete`, `upload`, `mobile`, `desktop`, `blocked`, `pending`, `size` ...), `F.stats.response` counts responses by type (`json`, `html`, `file`, `redirect`, `stream`, `timeout`, `error404`, `error500` ...), `F.stats.performance` holds the per-minute values, `F.stats.error` the number of errors, and `F.stats.compiled` and `F.stats.compilation` the number of loaded files and the loading time in ms.\n\nExample: Simple report\n```js\nROUTE('GET /stats/', function($) {\n\tvar s = F.stats;\n\t$.json({ requests: s.request.request, errors: s.error, notfound: s.response.error404 });\n});\n```\n\n### ON('$watcher', function(child) {})\n\nType: `event`\n\nEmitted in the debug watcher after it starts the application process.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | The process of the application. |\n\nIt runs in the watcher process, not in the application, after each start or restart. `child` is the `ChildProcess` of the application. Register it in the start script before `F.run()`.\n\nExample: Log restarts\n```js\nrequire('total5');\n\nON('$watcher', function(child) {\n\tconsole.log('Application PID:', child.pid);\n});\n\nF.run();\n```\n\n### ON('watcher', function(child) {})\n\nType: `event`\n\nEmitted in the release watcher after it starts the application process.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | The process of the application. |\n\nRelease mode started with `--watcher` only. It runs in the watcher process after each start. `child` is the `ChildProcess` of the application.\n\nExample: Log starts\n```js\nrequire('total5');\n\nON('watcher', function(child) {\n\tconsole.log('Started PID:', child.pid);\n});\n\nF.run({ watcher: false });\n```\n\n### options.ip = String\n\nType: `property`\n\nThe IP address the server listens on.\n\nReturns: `String` Default: `CONF.$ip` (`0.0.0.0`)\n\nStored into `CONF.$ip`. The default `0.0.0.0` listens on all interfaces.\n\nExample: Local only\n```js\nF.run({ ip: '127.0.0.1', port: 8000 });\n```\n\n### options.port = Number\n\nType: `property`\n\nThe port of the server.\n\nReturns: `Number` Default: `8000`\n\nStored into `CONF.$port`. Without it the port comes from the `PORT` environment variable or a numeric argument of the process (`node index.js 8000`), and the default is `8000`.\n\nExample: Port from the arguments\n```js\nF.run({ port: parseInt(process.argv[2]) || 8000 });\n```\n\n### options.unixsocket = String\n\nType: `property`\n\nListens on a Unix socket instead of a port.\n\nReturns: `String`\n\nAn existing socket file is removed first. On Windows the path is placed into the named pipe space. Stored into `CONF.$unixsocket`.\n\nExample: Socket\n```js\nF.run({ unixsocket: require('node:path').join(require('node:os').tmpdir(), 'app_name') });\n```\n\n### options.unixsocket777 = Boolean\n\nType: `property`\n\nGives the Unix socket the permissions 777.\n\nReturns: `Boolean` Default: `false`\n\nWith `unixsocket`, the socket file gets `chmod 777` when it is created, so another user (for example the web server) can connect to it.\n\nExample: Socket for nginx\n```js\nF.run({ unixsocket: '/tmp/app.socket', unixsocket777: true });\n```\n\n### options.config = Object\n\nType: `property`\n\nConfiguration keys applied before the application is loaded.\n\nReturns: `Object`\n\nEvery key is applied with `LOADCONFIG()` before `LOAD()`. The `config` file is read later and can override them. Use it for keys that are needed before the `config` file is read, such as `bundling`.\n\nExample: Name and bundling\n```js\nF.run({ config: { name: 'My app', bundling: 'shallow' } });\n```\n\n### options.load = String\n\nType: `property`\n\nThe parts of the application that are loaded.\n\nReturns: `String` Default: `''`\n\nPassed to `LOAD()`: a comma-separated list such as `'config,controllers'`. Empty loads everything; `'none'` starts only the web server. `options.type` is an alias.\n\nExample: Static file server\n```js\nF.http({ load: 'none', port: 8000 });\n```\n\n### options.watcher = Boolean\n\nType: `property`\n\n`false` starts release mode.\n\nReturns: `Boolean` Default: `true`\n\nWith `F.run()`, `false` runs the application in release mode in the current process; any other value starts the debug watcher. In release mode the `--watcher` argument of the process starts a release watcher that restarts the application when it ends.\n\nExample: Release\n```js\nF.run({ watcher: false });\n```\n\n### options.release = Boolean\n\nType: `property`\n\nRuns the application with `DEBUG = false` under the debug watcher or the cluster.\n\nReturns: `Boolean` Default: `false`\n\nIn debug mode the watcher still restarts the application on changes, but the application runs with `DEBUG = false`. With `cluster` it starts the threads in release mode without the watcher.\n\nExample: Release cluster\n```js\nF.run({ cluster: 4, release: true });\n```\n\n### options.servicemode = Boolean|String\n\nType: `property`\n\nLoads the application without the HTTP server.\n\nReturns: `Boolean|String`\n\n`true` loads everything, a string loads the listed parts (the names of `LOAD()`), for example `'config,modules,actions'`.\n\nExample: Worker process\n```js\nF.run({ servicemode: 'config,modules,actions' });\n```\n\n### options.watch = Array\n\nType: `property`\n\nMore folders for the debug watcher.\n\nReturns: `Array`\n\nPaths relative to the root of the application. A leading and a trailing slash are removed.\n\nExample: Watch a folder\n```js\nF.run({ watch: ['adminer', '/libs/'] });\n```\n\n### options.livereload = String\n\nType: `property`\n\nSends changed files to the Total.js live reload service.\n\nReturns: `String`\n\nThe hostname of your application (`http://` and `https://` are removed). The debug watcher connects to `wss://livereload.totaljs.com/?hostname=<hostname>` and sends the name of each changed `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` or `.resource` file, including files in `public` and `views` (other files in the folders are not watched); changes in `public` and `views` do not restart the application.\n\nExample: Live reload\n```js\nF.run({ livereload: 'myapp.example.com' });\n```\n\n### options.inspector = Number\n\nType: `property`\n\nStarts the application process with the Node.js inspector.\n\nReturns: `Number` Default: `9229`\n\nThe debug watcher adds `--inspect=<port>` to the Node.js arguments of the application. The same happens when the watcher itself was started with `--inspect`, with the port `9229`.\n\nExample: Inspector\n```js\nF.run({ inspector: 9229 });\n```\n\n### options.debugger = Number\n\nType: `property`\n\nStarts the application process with `--debug=<port>`.\n\nReturns: `Number` Default: `40894`\n\nThe debug watcher adds `--debug=<port>` to the Node.js arguments of the application. The same happens when the watcher was started with `--debug`, with the port `40894`.\n\nExample: Debugger\n```js\nF.run({ debugger: 40894 });\n```\n\n### options.cluster = Number|String\n\nType: `property`\n\nRuns the application in several cluster threads.\n\nReturns: `Number|String`\n\nA number of threads, or `'auto'`: it starts with one thread and adds a thread when the average latency of the threads is above 70 ms, up to `options.limit`. In debug mode the watcher restarts all threads after a change; with `release: true` there is no watcher. Every thread loads the whole application.\n\nExample: Four threads\n```js\nF.run({ cluster: 4, port: 8000 });\n```\n\nExample: Automatic\n```js\nF.run({ cluster: 'auto', limit: 8, release: true });\n```\n\n### options.limit = Number\n\nType: `property`\n\nThe maximum number of threads for `cluster: 'auto'`.\n\nReturns: `Number`\n\nWithout it, the automatic cluster adds threads without a limit.\n\nExample: Limit\n```js\nF.run({ cluster: 'auto', limit: 4 });\n```\n\n### options.edit = String\n\nType: `property`\n\nConnects the application to the Total.js Code Editor.\n\nReturns: `String`\n\nThe URL from the editor (`wss://...?id=project`; `http` is changed to `ws`). The client runs in the debug watcher, or in the release watcher started with `--watcher`, and starts the application one second later.\n\nExample: Remote editing\n```js\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\n### options.editmcp = String\n\nType: `property`\n\nConnects the application to an MCP edit proxy, so an AI agent can work on its files.\n\nReturns: `String`\n\nThe URL of the WebSocket route of the proxy with the id of the project (`wss://proxy.example.com/$mcp/?id=myproject`; `http` is changed to `ws`). The client runs in the watcher (so not with `watcher: false`), reconnects every 10 seconds and starts the application one second later. When `edit` is set too, `edit` is used.\n\nThe proxy is another Total.js application with `$mcp : true` that passes its WebSocket route to `require('total5/edit-mcp').proxy()`. Its MCP endpoint `/$mcp/?id=myproject` lists the tools `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` and `App_restart` and runs them in the connected application with the id `myproject`; without a connected application the tools answer `App is offline.`. Paths are relative to the application root, with or without the leading `/`. `App_write` saves every written content as a numbered revision in the folder `revisions/` of the application, `App_read` returns the current revision number and `App_restore` the content of a revision, `App_move` moves the revisions with the files and `App_delete` removes them (`/` cannot be deleted). `App_shell` runs any shell command in the application folder, so protect the proxy with `Total.mcp.auth`.\n\nExample: The application\n```js\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nExample: The proxy\n```js\n// config: $mcp : true\nconst editmcp = require('total5/edit-mcp');\n\nROUTE('SOCKET /$mcp/', function($) {\n\teditmcp.proxy($);\n});\n\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_token)\n\t\t$.success({ id: 'agent', name: 'Agent', sa: true });\n\telse\n\t\t$.invalid();\n};\n\n// the AI client connects to https://proxy.example.com/$mcp/?id=myproject\n```\n\n### bundling : shallow\n\nType: `config`\n\n`shallow` reuses the extracted `.src` folder instead of building it again.\n\nReturns: `String`\n\nWhen it is `shallow` and `.src/bundle.json` exists, the bundles are not extracted and the files are not copied; the application runs from the existing `.src`. Bundles are processed before the `config` file is read, so set the key in `options.config`.\n\nExample: Shallow bundling\n```js\nF.run({ watcher: false, config: { bundling: 'shallow' } });\n```\n","entries":[{"type":"method","name":"F.run()","signature":"F.run([options])","since":"","deprecated":false},{"type":"method","name":"F.http()","signature":"F.http([options])","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [callback], [clear])","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"F.directory","signature":"F.directory","since":"","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"method","name":"F.dir()","signature":"F.dir([directory])","since":"","deprecated":false},{"type":"method","name":"F.restart()","signature":"F.restart()","since":"","deprecated":false},{"type":"method","name":"F.exit()","signature":"F.exit([signal])","since":"","deprecated":false},{"type":"method","name":"F.console()","signature":"F.console()","since":"","deprecated":false},{"type":"method","name":"F.remote()","signature":"F.remote(url, [directory])","since":"","deprecated":false},{"type":"property","name":"F.consumption","signature":"F.consumption","since":"","deprecated":false},{"type":"property","name":"F.stats","signature":"F.stats","since":"","deprecated":false},{"type":"event","name":"ON('$watcher')","signature":"ON('$watcher', function(child) {})","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(child) {})","since":"","deprecated":false},{"type":"property","name":"options.ip","signature":"options.ip = String","since":"","deprecated":false},{"type":"property","name":"options.port","signature":"options.port = Number","since":"","deprecated":false},{"type":"property","name":"options.unixsocket","signature":"options.unixsocket = String","since":"","deprecated":false},{"type":"property","name":"options.unixsocket777","signature":"options.unixsocket777 = Boolean","since":"","deprecated":false},{"type":"property","name":"options.config","signature":"options.config = Object","since":"","deprecated":false},{"type":"property","name":"options.load","signature":"options.load = String","since":"","deprecated":false},{"type":"property","name":"options.watcher","signature":"options.watcher = Boolean","since":"","deprecated":false},{"type":"property","name":"options.release","signature":"options.release = Boolean","since":"","deprecated":false},{"type":"property","name":"options.servicemode","signature":"options.servicemode = Boolean|String","since":"","deprecated":false},{"type":"property","name":"options.watch","signature":"options.watch = Array","since":"","deprecated":false},{"type":"property","name":"options.livereload","signature":"options.livereload = String","since":"","deprecated":false},{"type":"property","name":"options.inspector","signature":"options.inspector = Number","since":"","deprecated":false},{"type":"property","name":"options.debugger","signature":"options.debugger = Number","since":"","deprecated":false},{"type":"property","name":"options.cluster","signature":"options.cluster = Number|String","since":"","deprecated":false},{"type":"property","name":"options.limit","signature":"options.limit = Number","since":"","deprecated":false},{"type":"property","name":"options.edit","signature":"options.edit = String","since":"","deprecated":false},{"type":"property","name":"options.editmcp","signature":"options.editmcp = String","since":"","deprecated":false},{"type":"config","name":"bundling","signature":"bundling : shallow","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafwuo6Px60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/application-structure/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Anwendungsstruktur und Modi","summary":"F.run() und seine Startoptionen, LOAD(), IMPORT(), REQUIRE(), MODS und die Statistiken des Frameworks.","markdown":"---\ntitle: Anwendungsstruktur und Modi\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/application-structure/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Anwendungsstruktur und Modi\n\n> F.run() und seine Startoptionen, LOAD(), IMPORT(), REQUIRE(), MODS und die Statistiken des Frameworks.\n\nDie Funktionen, die eine Total.js 5-Anwendung starten und laden: `F.run()` mit allen Startoptionen, `F.http()`, `LOAD()`, `IMPORT()`, `REQUIRE()`, `MODS`, `F.restart()`, `F.exit()`, die Statistiken in `F.stats` und `F.consumption`, die Watcher-Events und der Schlüssel `bundling`.\n\nDie Anleitung [Anwendungsstruktur und Modi](../../guides/application-structure/) erklärt die Ordner, die Ladereihenfolge, den Debug- und Release-Modus, Bundles und die Remote-Bearbeitung.\n\nDer `Test`-Runner hat eine eigene Seite: [Unit-Tests](../unit-tests/).\n\n## API\n\n### F.run([options])\n\nType: `method`\n\nStartet die Anwendung im Debug-Modus mit dem Watcher oder im Release-Modus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Die Startoptionen: `ip`, `port`, `unixsocket`, `config`, `load`, `watcher`, `release`, `servicemode`, `watch`, `livereload`, `inspector`, `debugger`, `cluster`, `limit`, `edit`, `editmcp`. |\n\nReturns: `undefined`\n\nDie übliche letzte Zeile des Startskripts. Ohne `options.watcher = false` startet sie den Debug-Watcher (`debug.js`): Die Anwendung läuft in einem Kindprozess und startet neu, wenn sich eine Datei ändert. Mit `watcher: false` startet sie den Release-Modus (`release.js`): Die Anwendung läuft im selben Prozess mit `DEBUG = false`. Die Optionen werden im Anwendungsprozess an `F.http()` übergeben (oder im Service-Modus an `LOAD()`). `Total.run()` ist dieselbe Funktion.\n\nExample: Debug-Modus\n```js\nrequire('total5');\nF.run({ port: 8000 });\n```\n\nExample: Release-Modus\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nExample: Modus über die Kommandozeile\n```js\nrequire('total5');\n\nvar options = {};\noptions.port = 8000;\n\nif (process.argv.includes('--release'))\n\toptions.watcher = false;\n\nF.run(options);\n```\n\n### F.http([options])\n\nType: `method`\n\nLädt die Anwendung und startet den HTTP-Server im aktuellen Prozess.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | `ip`, `port`, `unixsocket`, `unixsocket777`, `config`, `load` (Alias `type`) und `clear`. |\n\nReturns: `undefined`\n\nWendet `options.config` mit `LOADCONFIG()` an, ruft `LOAD()` mit `options.load` auf und startet dann den Server. Ist die Anwendung bereits geladen, startet sie nur den Server (neu); ein laufender Server wird zuerst geschlossen. Mit dem Standard `CONF.$port = 'auto'` wird der Port aus `options.port` genommen, dann aus der Umgebungsvariable `PORT`, dann aus dem ersten Argument des Prozesses mit 3 bis 5 Ziffern (`node index.js 8000`), und der Standard ist `8000`. Hat der Prozess keinen Elternprozess, gibt sie die Startinformationen aus.\n\n`F.run()` ruft sie für dich auf; rufe sie direkt in Skripten auf, die den Server ohne Watcher starten (Tests, Tools).\n\nExample: Server für Tests\n```js\nrequire('total5');\nF.http({ port: 8001, config: { name: 'Test' } });\n```\n\n### LOAD([types], [callback], [clear])\n\nType: `method`\n\nLädt die Konfiguration, die Ressourcen und die JavaScript-Dateien der Anwendung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no | `''` | Die zu ladenden Teile, als kommagetrennter String oder als Array; leer lädt alles. |\n| `callback` | `Function` | no |  | `function()`, aufgerufen, wenn alles geladen ist. |\n| `clear` | `Boolean` | no | `true` | Leert den temporären Ordner vor dem Laden. |\n\nReturns: `Promise` Wird erfüllt, wenn alles geladen ist.\n\n`F.load()` ist dieselbe Funktion. Sie setzt die Verzeichnisse, baut Bundles, entfernt die Dateien `.js`, `.css`, `.html`, `.htm`, `.tmp` und `.upload` aus dem temporären Ordner (wenn `clear` gleich `true` ist) und lädt dann die Teile in der Reihenfolge des Leitfadens. Ohne `types` lädt sie alles. Die Namen sind `env`, `config`, `version`, `resources`, `jsonschemas`, `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers`, `middleware`, `plugins`, `flowstreams` und `stats`; jeder andere Name, etwa `none`, lädt nichts. Wird `types` ohne `stats` angegeben, werden die Statistiken und die Source Maps abgeschaltet.\n\nAm Ende startet sie den Service-Timer, setzt `F.isLoaded`, `F.stats.compiled` und `F.stats.compilation`, ruft `callback` auf und löst `ready` und `load` aus. Den HTTP-Server startet sie nicht.\n\nExample: Hintergrundprozess\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\tACTION('Jobs/run').callback(console.log);\n});\n```\n\nExample: Mit await\n```js\nrequire('total5');\n\n(async function() {\n\tawait LOAD('env,config');\n\tconsole.log(CONF.name);\n})();\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nLädt eine JavaScript-Datei herunter und lädt sie als Modul.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL einer `.js`-Datei. |\n| `callback` | `Function` | no |  | `function(err, module, response)` |\n\nReturns: `Promise` Wenn `callback` nicht gesetzt ist.\n\nDie Datei wird in den temporären Ordner heruntergeladen und mit `require()` geladen. Weitere Aufrufe mit derselben URL im selben Prozess geben das geladene Modul zurück, ohne es erneut herunterzuladen. Eine Antwort mit dem Status `400` oder mehr führt zum Fehler `The address answered with the status <status>`, und es wird nichts geladen. Eine Datei, die kein gültiges Modul ist, führt zum Fehler von `require()`, zum Beispiel einem `SyntaxError`. Der Callback erhält `(err, module, response)`; ohne Callback gibt die Funktion eine Promise mit dem Modul zurück.\n\nExample: Promise\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n\nExample: Callback\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, helpers) {\n\tif (err)\n\t\tconsole.error(err);\n\telse\n\t\thelpers.hello();\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nLädt ein Node.js-Modul oder ein NPM-Paket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Moduls oder Pakets. |\n\nReturns: `Object` Das Modul.\n\nNamen mit dem Präfix `node:` und eingebaute Node.js-Module (`fs`, `path`, `crypto`, ...) werden direkt geladen. Andere Namen werden mit `require()` geladen und, wenn das fehlschlägt, aus dem Ordner in `CONF.$nodemodules` (standardmäßig `<application>/node_modules`), sodass mit `NPMINSTALL()` installierte Pakete gefunden werden. Sie löst einen Fehler aus, wenn das Modul nicht geladen werden kann.\n\nExample: Laden\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### MODS\n\nType: `property`\n\nDie geladenen Module aus dem Ordner `modules`, nach ihrer ID.\n\nReturns: `Object`\n\nDasselbe Objekt wie `F.modules`. Jede Datei in `modules` wird unter ihrer `exports.id` registriert, oder unter dem Dateinamen ohne `.js`, wenn `id` fehlt, bevor ihr `install()` aufgerufen wird. Verwende es, um die Funktionen aufzurufen, die ein Modul exportiert.\n\nExample: Ein Modul aufrufen\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// a controller or an action\nMODS.counter.increment();\n```\n\n### F.isLoaded\n\nType: `property`\n\n`true`, wenn die Anwendung geladen ist.\n\nReturns: `Boolean`\n\nWird von `LOAD()` gesetzt, nachdem alle Dateien geladen sind, kurz vor den Events `ready` und `load`.\n\nExample: Prüfen\n```js\nif (F.isLoaded)\n\tconsole.log('Ready');\n```\n\n### F.directory\n\nType: `property`\n\nDas Stammverzeichnis der Anwendung.\n\nReturns: `String`\n\nDas aktuelle Arbeitsverzeichnis des Prozesses, wenn `total5` geladen wird. Läuft die Anwendung aus Bundles, zeigt es auf den Ordner `.src`. Alle `PATH.root()`-Pfade beginnen hier.\n\nExample: Lesen\n```js\nconsole.log(F.directory);\nconsole.log(PATH.root('config'));\n```\n\n### F.isBundle\n\nType: `property`\n\n`true`, wenn die Anwendung aus Bundles läuft.\n\nReturns: `Boolean`\n\nWird gesetzt, wenn der Ordner `bundles` Bundles enthält (oder `bundles.debug` existiert) und die Anwendung in `.src` gebaut wurde.\n\nExample: Prüfen\n```js\nif (F.isBundle)\n\tconsole.log('Running from', F.directory);\n```\n\n### F.dir([directory])\n\nType: `method`\n\nSetzt das Stammverzeichnis und berechnet die Ordner der Anwendung neu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no |  | Ein neues Stammverzeichnis. |\n\nReturns: `undefined`\n\nMit `directory` ändert sie `F.directory`. Dann setzt sie die Pfade in `F.temporary.directories` für `public`, `tmp`, `logs`, `databases`, `controllers`, `resources`, `plugins`, `modules`, `views`, `definitions`, `schemas`, `models`, `flowstreams`, `bundles`, `actions`, `extensions`, `source`, `services`, `updates`, `templates`, `private` und `scripts`: Jeder ist der Wert von `CONF.$dir<name>`, wenn er gesetzt ist, andernfalls `<root>/<name>`. `LOAD()` ruft sie am Anfang auf.\n\nExample: Einen Ordner lesen\n```js\nF.dir();\nconsole.log(F.temporary.directories.public);\n```\n\n### F.restart()\n\nType: `method`\n\nBittet den Watcher, die Anwendung neu zu starten.\n\nReturns: `undefined`\n\nSendet `total:restart` an den Elternprozess. Der Debug-Watcher und der mit `--watcher` gestartete Release-Watcher geben `RES` aus und starten die Anwendung erneut. Ohne Watcher passiert nichts.\n\nExample: Nach einem Update\n```js\nNEWACTION('Settings/save', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tF.Fs.writeFile(PATH.root('config'), 'name : ' + model.name, function() {\n\t\t\t$.success();\n\t\t\tF.restart();\n\t\t});\n\t}\n});\n```\n\n### F.exit([signal])\n\nType: `method`\n\nBeendet die Anwendung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | no | `15` | Das Signal für die Kindprozesse. |\n\nReturns: `undefined`\n\nBeendet die Worker und Python-Pipelines mit `signal`, zerstört die FlowStream-Instanzen, löst `exit` aus, teilt dem Elternprozess `total:stop` mit, stoppt den Service-Timer und schließt den HTTP-Server. Der Prozess endet 300 ms später. Das Framework ruft sie bei `SIGTERM`, `SIGINT` und beim Beenden des Prozesses auf.\n\nExample: Beenden\n```js\nON('exit', function() {\n\tconsole.log('Bye');\n});\n\nF.exit();\n```\n\n### F.console()\n\nType: `method`\n\nGibt die Startinformationen aus.\n\nReturns: `undefined`\n\nGibt die PID, die Versionen von Node.js und Total.js, das System, den Speicher, den Benutzer, Name, Version und Autor der Anwendung, das Datum mit der Zeitzone, den Modus (`debug` oder `release`), die Anzahl der kompilierten Dateien mit der Zeit, die Pfade von Stammverzeichnis, Verzeichnis und `node_modules` sowie die Adresse des Servers aus. Es wird nichts ausgegeben, wenn `CONF.$imprint` `false` ist. Das Framework ruft sie nach dem Start auf.\n\nExample: Erneut ausgeben\n```js\nON('ready', function() {\n\tF.console();\n});\n```\n\n### F.remote(url, [directory])\n\nType: `method`\n\nVerbindet den Ordner der Anwendung mit dem Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL aus dem Editor, `wss://...?id=project`. |\n| `directory` | `String` | no | `F.directory` | Der zu bearbeitende Ordner. |\n\nReturns: `undefined`\n\nStartet den Client für die Remote-Bearbeitung im aktuellen Prozess: eine WebSocket-Verbindung zu `url`, über die der Editor die Dateien in `directory` durchsuchen und ändern kann. Sie verbindet sich alle 10 Sekunden neu, wenn die Verbindung verloren geht. Die Startoption `edit` macht dasselbe im Watcher-Prozess.\n\nExample: Verbinden\n```js\nF.remote('wss://code.example.com/?id=myproject');\n```\n\n### F.consumption\n\nType: `property`\n\nDie Nutzungsstatistiken des Prozesses, einmal pro Minute aktualisiert.\n\nReturns: `Object`\n\nJede Minute dasselbe Objekt (das erste Mal 5 Sekunden nach dem Laden der Anwendung); `ON('$stats')` erhält es ebenfalls, und mit `CONF.$stats` wird es in `<script>.json` geschrieben. Felder: `id`, `pid`, `thread`, `mode` (`debug` oder `release`), `version` (`node`, `total`, `build`, `app` aus `CONF.version`), `app` (`name` und `url` aus der Konfiguration), `date`, `memory` (genutzter Heap in MB), `requests`, `pending`, `external`, `errors`, `timeouts`, `online` (WebSocket-Clients), `download` und `upload` (MB insgesamt), `lasterror`, `lasttimeout`, `usage` (Prozent), `overload` (Stunden mit hoher Last), `uptime` (Minuten seit dem Start) und die Zähler pro Minute `rm`, `fm`, `wm`, `em`, `mm`, `om`, `dm`, `um`, `pm`, `sm`, `cm`, `dbrm` und `dbwm`.\n\nExample: Lesen\n```js\nsetInterval(function() {\n\tconsole.log(F.consumption.memory, 'MB', F.consumption.requests, 'requests');\n}, 60000);\n```\n\n### F.stats\n\nType: `property`\n\nZähler des Frameworks für die gesamte Lebensdauer des Prozesses.\n\nReturns: `Object`\n\n`F.stats.request` zählt Anfragen (`request`, `web`, `xhr`, `file`, `websocket`, `get`, `post`, `put`, `patch`, `delete`, `upload`, `mobile`, `desktop`, `blocked`, `pending`, `size` ...), `F.stats.response` zählt Antworten nach Typ (`json`, `html`, `file`, `redirect`, `stream`, `timeout`, `error404`, `error500` ...), `F.stats.performance` enthält die Werte pro Minute, `F.stats.error` die Anzahl der Fehler, und `F.stats.compiled` und `F.stats.compilation` die Anzahl der geladenen Dateien und die Ladezeit in ms.\n\nExample: Einfacher Bericht\n```js\nROUTE('GET /stats/', function($) {\n\tvar s = F.stats;\n\t$.json({ requests: s.request.request, errors: s.error, notfound: s.response.error404 });\n});\n```\n\n### ON('$watcher', function(child) {})\n\nType: `event`\n\nWird im Debug-Watcher ausgelöst, nachdem er den Anwendungsprozess gestartet hat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | Der Prozess der Anwendung. |\n\nEs läuft im Watcher-Prozess, nicht in der Anwendung, nach jedem Start oder Neustart. `child` ist der `ChildProcess` der Anwendung. Registriere es im Startskript vor `F.run()`.\n\nExample: Neustarts protokollieren\n```js\nrequire('total5');\n\nON('$watcher', function(child) {\n\tconsole.log('Application PID:', child.pid);\n});\n\nF.run();\n```\n\n### ON('watcher', function(child) {})\n\nType: `event`\n\nWird im Release-Watcher ausgelöst, nachdem er den Anwendungsprozess gestartet hat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | Der Prozess der Anwendung. |\n\nNur im mit `--watcher` gestarteten Release-Modus. Es läuft nach jedem Start im Watcher-Prozess. `child` ist der `ChildProcess` der Anwendung.\n\nExample: Starts protokollieren\n```js\nrequire('total5');\n\nON('watcher', function(child) {\n\tconsole.log('Started PID:', child.pid);\n});\n\nF.run({ watcher: false });\n```\n\n### options.ip = String\n\nType: `property`\n\nDie IP-Adresse, auf der der Server lauscht.\n\nReturns: `String` Standard: `CONF.$ip` (`0.0.0.0`)\n\nWird in `CONF.$ip` gespeichert. Der Standard `0.0.0.0` lauscht auf allen Schnittstellen.\n\nExample: Nur lokal\n```js\nF.run({ ip: '127.0.0.1', port: 8000 });\n```\n\n### options.port = Number\n\nType: `property`\n\nDer Port des Servers.\n\nReturns: `Number` Standard: `8000`\n\nWird in `CONF.$port` gespeichert. Ohne diese Option stammt der Port aus der Umgebungsvariable `PORT` oder einem numerischen Argument des Prozesses (`node index.js 8000`), und der Standard ist `8000`.\n\nExample: Port aus den Argumenten\n```js\nF.run({ port: parseInt(process.argv[2]) || 8000 });\n```\n\n### options.unixsocket = String\n\nType: `property`\n\nLauscht auf einem Unix-Socket statt auf einem Port.\n\nReturns: `String`\n\nEine vorhandene Socket-Datei wird zuerst entfernt. Unter Windows wird der Pfad in den Named-Pipe-Bereich gelegt. Wird in `CONF.$unixsocket` gespeichert.\n\nExample: Socket\n```js\nF.run({ unixsocket: require('node:path').join(require('node:os').tmpdir(), 'app_name') });\n```\n\n### options.unixsocket777 = Boolean\n\nType: `property`\n\nGibt dem Unix-Socket die Berechtigungen 777.\n\nReturns: `Boolean` Standard: `false`\n\nMit `unixsocket` erhält die Socket-Datei beim Erstellen `chmod 777`, sodass sich ein anderer Benutzer (zum Beispiel der Webserver) mit ihr verbinden kann.\n\nExample: Socket für nginx\n```js\nF.run({ unixsocket: '/tmp/app.socket', unixsocket777: true });\n```\n\n### options.config = Object\n\nType: `property`\n\nKonfigurationsschlüssel, die vor dem Laden der Anwendung angewendet werden.\n\nReturns: `Object`\n\nJeder Schlüssel wird vor `LOAD()` mit `LOADCONFIG()` angewendet. Die `config`-Datei wird später gelesen und kann sie überschreiben. Verwende es für Schlüssel, die benötigt werden, bevor die `config`-Datei gelesen wird, etwa `bundling`.\n\nExample: Name und Bundling\n```js\nF.run({ config: { name: 'My app', bundling: 'shallow' } });\n```\n\n### options.load = String\n\nType: `property`\n\nDie Teile der Anwendung, die geladen werden.\n\nReturns: `String` Standard: `''`\n\nWird an `LOAD()` übergeben: eine kommagetrennte Liste wie `'config,controllers'`. Leer lädt alles; `'none'` startet nur den Webserver. `options.type` ist ein Alias.\n\nExample: Server für statische Dateien\n```js\nF.http({ load: 'none', port: 8000 });\n```\n\n### options.watcher = Boolean\n\nType: `property`\n\n`false` startet den Release-Modus.\n\nReturns: `Boolean` Standard: `true`\n\nMit `F.run()` führt `false` die Anwendung im Release-Modus im aktuellen Prozess aus; jeder andere Wert startet den Debug-Watcher. Im Release-Modus startet das Prozessargument `--watcher` einen Release-Watcher, der die Anwendung neu startet, wenn sie endet.\n\nExample: Release\n```js\nF.run({ watcher: false });\n```\n\n### options.release = Boolean\n\nType: `property`\n\nFührt die Anwendung unter dem Debug-Watcher oder dem Cluster mit `DEBUG = false` aus.\n\nReturns: `Boolean` Standard: `false`\n\nIm Debug-Modus startet der Watcher die Anwendung bei Änderungen weiterhin neu, aber die Anwendung läuft mit `DEBUG = false`. Mit `cluster` startet sie die Threads im Release-Modus ohne den Watcher.\n\nExample: Release-Cluster\n```js\nF.run({ cluster: 4, release: true });\n```\n\n### options.servicemode = Boolean|String\n\nType: `property`\n\nLädt die Anwendung ohne den HTTP-Server.\n\nReturns: `Boolean|String`\n\n`true` lädt alles, ein String lädt die aufgelisteten Teile (die Namen von `LOAD()`), zum Beispiel `'config,modules,actions'`.\n\nExample: Worker-Prozess\n```js\nF.run({ servicemode: 'config,modules,actions' });\n```\n\n### options.watch = Array\n\nType: `property`\n\nWeitere Ordner für den Debug-Watcher.\n\nReturns: `Array`\n\nPfade relativ zum Stammverzeichnis der Anwendung. Ein führender und ein abschließender Schrägstrich werden entfernt.\n\nExample: Einen Ordner überwachen\n```js\nF.run({ watch: ['adminer', '/libs/'] });\n```\n\n### options.livereload = String\n\nType: `property`\n\nSendet geänderte Dateien an den Live-Reload-Dienst von Total.js.\n\nReturns: `String`\n\nDer Hostname deiner Anwendung (`http://` und `https://` werden entfernt). Der Debug-Watcher verbindet sich mit `wss://livereload.totaljs.com/?hostname=<hostname>` und sendet den Namen jeder geänderten Datei `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` oder `.resource`, einschließlich Dateien in `public` und `views` (andere Dateien in den Ordnern werden nicht überwacht); Änderungen in `public` und `views` starten die Anwendung nicht neu.\n\nExample: Live Reload\n```js\nF.run({ livereload: 'myapp.example.com' });\n```\n\n### options.inspector = Number\n\nType: `property`\n\nStartet den Anwendungsprozess mit dem Node.js-Inspector.\n\nReturns: `Number` Standard: `9229`\n\nDer Debug-Watcher fügt `--inspect=<port>` zu den Node.js-Argumenten der Anwendung hinzu. Dasselbe passiert, wenn der Watcher selbst mit `--inspect` gestartet wurde, mit dem Port `9229`.\n\nExample: Inspector\n```js\nF.run({ inspector: 9229 });\n```\n\n### options.debugger = Number\n\nType: `property`\n\nStartet den Anwendungsprozess mit `--debug=<port>`.\n\nReturns: `Number` Standard: `40894`\n\nDer Debug-Watcher fügt `--debug=<port>` zu den Node.js-Argumenten der Anwendung hinzu. Dasselbe passiert, wenn der Watcher mit `--debug` gestartet wurde, mit dem Port `40894`.\n\nExample: Debugger\n```js\nF.run({ debugger: 40894 });\n```\n\n### options.cluster = Number|String\n\nType: `property`\n\nFührt die Anwendung in mehreren Cluster-Threads aus.\n\nReturns: `Number|String`\n\nEine Anzahl von Threads oder `'auto'`: Es startet mit einem Thread und fügt einen Thread hinzu, wenn die durchschnittliche Latenz der Threads über 70 ms liegt, bis zu `options.limit`. Im Debug-Modus startet der Watcher nach einer Änderung alle Threads neu; mit `release: true` gibt es keinen Watcher. Jeder Thread lädt die ganze Anwendung.\n\nExample: Vier Threads\n```js\nF.run({ cluster: 4, port: 8000 });\n```\n\nExample: Automatisch\n```js\nF.run({ cluster: 'auto', limit: 8, release: true });\n```\n\n### options.limit = Number\n\nType: `property`\n\nDie maximale Anzahl von Threads für `cluster: 'auto'`.\n\nReturns: `Number`\n\nOhne diese Option fügt der automatische Cluster Threads ohne Begrenzung hinzu.\n\nExample: Begrenzung\n```js\nF.run({ cluster: 'auto', limit: 4 });\n```\n\n### options.edit = String\n\nType: `property`\n\nVerbindet die Anwendung mit dem Total.js Code Editor.\n\nReturns: `String`\n\nDie URL aus dem Editor (`wss://...?id=project`; `http` wird zu `ws` geändert). Der Client läuft im Debug-Watcher oder im mit `--watcher` gestarteten Release-Watcher und startet die Anwendung eine Sekunde später.\n\nExample: Remote-Bearbeitung\n```js\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\n### options.editmcp = String\n\nType: `property`\n\nVerbindet die Anwendung mit einem MCP-Bearbeitungs-Proxy, damit ein KI-Agent an ihren Dateien arbeiten kann.\n\nReturns: `String`\n\nDie URL der WebSocket-Route des Proxys mit der ID des Projekts (`wss://proxy.example.com/$mcp/?id=myproject`; `http` wird zu `ws` geändert). Der Client läuft im Watcher (also nicht mit `watcher: false`), verbindet sich alle 10 Sekunden neu und startet die Anwendung eine Sekunde später. Ist auch `edit` gesetzt, wird `edit` verwendet.\n\nDer Proxy ist eine weitere Total.js-Anwendung mit `$mcp : true`, die ihre WebSocket-Route an `require('total5/edit-mcp').proxy()` übergibt. Der MCP-Endpunkt `/$mcp/?id=myproject` des Proxys listet die Tools `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` und `App_restart` auf und führt sie in der verbundenen Anwendung mit der ID `myproject` aus; ohne verbundene Anwendung antworten die Tools mit `App is offline.`. Pfade sind relativ zum Stammverzeichnis der Anwendung, mit oder ohne führendes `/`. `App_write` speichert jeden geschriebenen Inhalt als nummerierte Revision im Ordner `revisions/` der Anwendung, `App_read` gibt die aktuelle Revisionsnummer zurück und `App_restore` den Inhalt einer Revision, `App_move` verschiebt die Revisionen mit den Dateien und `App_delete` entfernt sie (`/` kann nicht gelöscht werden). `App_shell` führt jeden beliebigen Shell-Befehl im Ordner der Anwendung aus, also schütze den Proxy mit `Total.mcp.auth`.\n\nExample: Die Anwendung\n```js\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nExample: Der Proxy\n```js\n// config: $mcp : true\nconst editmcp = require('total5/edit-mcp');\n\nROUTE('SOCKET /$mcp/', function($) {\n\teditmcp.proxy($);\n});\n\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_token)\n\t\t$.success({ id: 'agent', name: 'Agent', sa: true });\n\telse\n\t\t$.invalid();\n};\n\n// the AI client connects to https://proxy.example.com/$mcp/?id=myproject\n```\n\n### bundling : shallow\n\nType: `config`\n\n`shallow` verwendet den entpackten Ordner `.src` wieder, statt ihn neu zu bauen.\n\nReturns: `String`\n\nWenn der Wert `shallow` ist und `.src/bundle.json` existiert, werden die Bundles nicht entpackt und die Dateien nicht kopiert; die Anwendung läuft aus dem vorhandenen `.src`. Bundles werden verarbeitet, bevor die `config`-Datei gelesen wird, setze den Schlüssel also in `options.config`.\n\nExample: Shallow Bundling\n```js\nF.run({ watcher: false, config: { bundling: 'shallow' } });\n```\n","entries":[{"type":"method","name":"F.run()","signature":"F.run([options])","since":"","deprecated":false},{"type":"method","name":"F.http()","signature":"F.http([options])","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [callback], [clear])","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"F.directory","signature":"F.directory","since":"","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"method","name":"F.dir()","signature":"F.dir([directory])","since":"","deprecated":false},{"type":"method","name":"F.restart()","signature":"F.restart()","since":"","deprecated":false},{"type":"method","name":"F.exit()","signature":"F.exit([signal])","since":"","deprecated":false},{"type":"method","name":"F.console()","signature":"F.console()","since":"","deprecated":false},{"type":"method","name":"F.remote()","signature":"F.remote(url, [directory])","since":"","deprecated":false},{"type":"property","name":"F.consumption","signature":"F.consumption","since":"","deprecated":false},{"type":"property","name":"F.stats","signature":"F.stats","since":"","deprecated":false},{"type":"event","name":"ON('$watcher')","signature":"ON('$watcher', function(child) {})","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(child) {})","since":"","deprecated":false},{"type":"property","name":"options.ip","signature":"options.ip = String","since":"","deprecated":false},{"type":"property","name":"options.port","signature":"options.port = Number","since":"","deprecated":false},{"type":"property","name":"options.unixsocket","signature":"options.unixsocket = String","since":"","deprecated":false},{"type":"property","name":"options.unixsocket777","signature":"options.unixsocket777 = Boolean","since":"","deprecated":false},{"type":"property","name":"options.config","signature":"options.config = Object","since":"","deprecated":false},{"type":"property","name":"options.load","signature":"options.load = String","since":"","deprecated":false},{"type":"property","name":"options.watcher","signature":"options.watcher = Boolean","since":"","deprecated":false},{"type":"property","name":"options.release","signature":"options.release = Boolean","since":"","deprecated":false},{"type":"property","name":"options.servicemode","signature":"options.servicemode = Boolean|String","since":"","deprecated":false},{"type":"property","name":"options.watch","signature":"options.watch = Array","since":"","deprecated":false},{"type":"property","name":"options.livereload","signature":"options.livereload = String","since":"","deprecated":false},{"type":"property","name":"options.inspector","signature":"options.inspector = Number","since":"","deprecated":false},{"type":"property","name":"options.debugger","signature":"options.debugger = Number","since":"","deprecated":false},{"type":"property","name":"options.cluster","signature":"options.cluster = Number|String","since":"","deprecated":false},{"type":"property","name":"options.limit","signature":"options.limit = Number","since":"","deprecated":false},{"type":"property","name":"options.edit","signature":"options.edit = String","since":"","deprecated":false},{"type":"property","name":"options.editmcp","signature":"options.editmcp = String","since":"","deprecated":false},{"type":"config","name":"bundling","signature":"bundling : shallow","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafwuo6Px60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/application-structure/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Estructura de la aplicación y modos","summary":"F.run() y sus opciones de arranque, LOAD(), IMPORT(), REQUIRE(), MODS y las estadísticas del framework.","markdown":"---\ntitle: \"Estructura de la aplicación y modos\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/application-structure/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Estructura de la aplicación y modos\n\n> F.run() y sus opciones de arranque, LOAD(), IMPORT(), REQUIRE(), MODS y las estadísticas del framework.\n\nLas funciones que arrancan y cargan una aplicación Total.js 5: `F.run()` con todas las opciones de arranque, `F.http()`, `LOAD()`, `IMPORT()`, `REQUIRE()`, `MODS`, `F.restart()`, `F.exit()`, las estadísticas de `F.stats` y `F.consumption`, los eventos del watcher y la clave `bundling`.\n\nLa guía [Estructura de la aplicación y modos](../../guides/application-structure/) explica las carpetas, el orden de carga, el modo debug y release, los bundles y la edición remota.\n\nEl ejecutor `Test` tiene su propia página: [Tests unitarios](../unit-tests/).\n\n## API\n\n### F.run([options])\n\nType: `method`\n\nArranca la aplicación en modo debug con el watcher, o en modo release.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Las opciones de arranque: `ip`, `port`, `unixsocket`, `config`, `load`, `watcher`, `release`, `servicemode`, `watch`, `livereload`, `inspector`, `debugger`, `cluster`, `limit`, `edit`, `editmcp`. |\n\nReturns: `undefined`\n\nLa última línea habitual del script de arranque. Sin `options.watcher = false` arranca el watcher de debug (`debug.js`): la aplicación se ejecuta en un proceso hijo y se reinicia cuando cambia un archivo. Con `watcher: false` arranca el modo release (`release.js`): la aplicación se ejecuta en el mismo proceso con `DEBUG = false`. Las opciones se pasan a `F.http()` (o a `LOAD()` en modo servicio) en el proceso de la aplicación. `Total.run()` es la misma función.\n\nExample: Modo debug\n```js\nrequire('total5');\nF.run({ port: 8000 });\n```\n\nExample: Modo release\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nExample: Modo desde la línea de comandos\n```js\nrequire('total5');\n\nvar options = {};\noptions.port = 8000;\n\nif (process.argv.includes('--release'))\n\toptions.watcher = false;\n\nF.run(options);\n```\n\n### F.http([options])\n\nType: `method`\n\nCarga la aplicación y arranca el servidor HTTP en el proceso actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | `ip`, `port`, `unixsocket`, `unixsocket777`, `config`, `load` (alias `type`) y `clear`. |\n\nReturns: `undefined`\n\nAplica `options.config` con `LOADCONFIG()`, llama a `LOAD()` con `options.load` y luego arranca el servidor. Cuando la aplicación ya está cargada, solo (re)arranca el servidor; un servidor en ejecución se cierra primero. Con el valor por defecto `CONF.$port = 'auto'`, el puerto se toma de `options.port`, luego de la variable de entorno `PORT`, luego del primer argumento del proceso con 3 a 5 dígitos (`node index.js 8000`), y el valor por defecto es `8000`. Cuando el proceso no tiene padre, imprime la información de arranque.\n\n`F.run()` la llama por ti; llámala directamente en scripts que arrancan el servidor sin watcher (tests, herramientas).\n\nExample: Servidor para tests\n```js\nrequire('total5');\nF.http({ port: 8001, config: { name: 'Test' } });\n```\n\n### LOAD([types], [callback], [clear])\n\nType: `method`\n\nCarga la configuración, los recursos y los archivos JavaScript de la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no | `''` | Las partes a cargar, como cadena separada por comas o como array; vacío lo carga todo. |\n| `callback` | `Function` | no |  | `function()` que se llama cuando todo está cargado. |\n| `clear` | `Boolean` | no | `true` | Vacía la carpeta temporal antes de cargar. |\n\nReturns: `Promise` Se resuelve cuando todo está cargado.\n\n`F.load()` es la misma función. Establece los directorios, construye los bundles, elimina los archivos `.js`, `.css`, `.html`, `.htm`, `.tmp` y `.upload` de la carpeta temporal (cuando `clear` es `true`) y luego carga las partes en el orden de la guía. Sin `types` lo carga todo. Los nombres son `env`, `config`, `version`, `resources`, `jsonschemas`, `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers`, `middleware`, `plugins`, `flowstreams` y `stats`; cualquier otro nombre, como `none`, no carga nada. Cuando se da `types` sin `stats`, las estadísticas y los source maps se desactivan.\n\nAl final inicia el temporizador de servicio, establece `F.isLoaded`, `F.stats.compiled` y `F.stats.compilation`, llama a `callback` y emite `ready` y `load`. No inicia el servidor HTTP.\n\nExample: Proceso en segundo plano\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\tACTION('Jobs/run').callback(console.log);\n});\n```\n\nExample: Con await\n```js\nrequire('total5');\n\n(async function() {\n\tawait LOAD('env,config');\n\tconsole.log(CONF.name);\n})();\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nDescarga un archivo JavaScript y lo carga como módulo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL de un archivo `.js`. |\n| `callback` | `Function` | no |  | `function(err, module, response)` |\n\nReturns: `Promise` Cuando no se indica `callback`.\n\nEl archivo se descarga en la carpeta temporal y se carga con `require()`. Las llamadas posteriores con la misma URL en el mismo proceso devuelven el módulo cargado sin volver a descargarlo. Una respuesta con el estado `400` o más da el error `The address answered with the status <status>` y no se carga nada. Un archivo que no es un módulo válido da el error de `require()`, por ejemplo un `SyntaxError`. El callback recibe `(err, module, response)`; sin callback, la función devuelve una Promise con el módulo.\n\nExample: Promesa\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n\nExample: Callback\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, helpers) {\n\tif (err)\n\t\tconsole.error(err);\n\telse\n\t\thelpers.hello();\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nCarga un módulo de Node.js o un paquete de NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del módulo o paquete. |\n\nReturns: `Object` El módulo.\n\nLos nombres con el prefijo `node:` y los módulos integrados de Node.js (`fs`, `path`, `crypto`, ...) se cargan directamente. Los demás nombres se cargan con `require()` y, cuando falla, desde la carpeta de `CONF.$nodemodules` (`<application>/node_modules` por defecto), así que se encuentran los paquetes instalados con `NPMINSTALL()`. Lanza una excepción cuando el módulo no se puede cargar.\n\nExample: Cargar\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### MODS\n\nType: `property`\n\nLos módulos cargados de la carpeta `modules`, por su id.\n\nReturns: `Object`\n\nEl mismo objeto que `F.modules`. Cada archivo de `modules` se registra bajo su `exports.id`, o bajo el nombre del archivo sin `.js` cuando falta `id`, antes de llamar a su `install()`. Úsalo para llamar a las funciones que exporta un módulo.\n\nExample: Llamar a un módulo\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// a controller or an action\nMODS.counter.increment();\n```\n\n### F.isLoaded\n\nType: `property`\n\n`true` cuando la aplicación está cargada.\n\nReturns: `Boolean`\n\nLo establece `LOAD()` después de cargar todos los archivos, justo antes de los eventos `ready` y `load`.\n\nExample: Comprobar\n```js\nif (F.isLoaded)\n\tconsole.log('Ready');\n```\n\n### F.directory\n\nType: `property`\n\nLa carpeta raíz de la aplicación.\n\nReturns: `String`\n\nEl directorio de trabajo actual del proceso cuando se carga `total5`. Cuando la aplicación se ejecuta desde bundles, apunta a la carpeta `.src`. Todas las rutas de `PATH.root()` empiezan aquí.\n\nExample: Leer\n```js\nconsole.log(F.directory);\nconsole.log(PATH.root('config'));\n```\n\n### F.isBundle\n\nType: `property`\n\n`true` cuando la aplicación se ejecuta desde bundles.\n\nReturns: `Boolean`\n\nSe establece cuando la carpeta `bundles` contiene bundles (o existe `bundles.debug`) y la aplicación se construyó en `.src`.\n\nExample: Comprobar\n```js\nif (F.isBundle)\n\tconsole.log('Running from', F.directory);\n```\n\n### F.dir([directory])\n\nType: `method`\n\nEstablece la carpeta raíz y recalcula las carpetas de la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no |  | Una nueva carpeta raíz. |\n\nReturns: `undefined`\n\nCon `directory` cambia `F.directory`. Luego establece las rutas en `F.temporary.directories` para `public`, `tmp`, `logs`, `databases`, `controllers`, `resources`, `plugins`, `modules`, `views`, `definitions`, `schemas`, `models`, `flowstreams`, `bundles`, `actions`, `extensions`, `source`, `services`, `updates`, `templates`, `private` y `scripts`: cada una es el valor de `CONF.$dir<name>` cuando está definido, y si no, `<root>/<name>`. `LOAD()` la llama al principio.\n\nExample: Leer una carpeta\n```js\nF.dir();\nconsole.log(F.temporary.directories.public);\n```\n\n### F.restart()\n\nType: `method`\n\nPide al watcher que reinicie la aplicación.\n\nReturns: `undefined`\n\nEnvía `total:restart` al proceso padre. El watcher de debug, y el watcher de release arrancado con `--watcher`, imprimen `RES` y arrancan de nuevo la aplicación. Sin watcher no ocurre nada.\n\nExample: Después de una actualización\n```js\nNEWACTION('Settings/save', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tF.Fs.writeFile(PATH.root('config'), 'name : ' + model.name, function() {\n\t\t\t$.success();\n\t\t\tF.restart();\n\t\t});\n\t}\n});\n```\n\n### F.exit([signal])\n\nType: `method`\n\nDetiene la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | no | `15` | La señal para los procesos hijos. |\n\nReturns: `undefined`\n\nMata los workers y los pipelines de Python con `signal`, destruye las instancias de FlowStream, emite `exit`, comunica `total:stop` al proceso padre, detiene el temporizador de servicio y cierra el servidor HTTP. El proceso termina 300 ms después. El framework la llama con `SIGTERM`, `SIGINT` y cuando el proceso termina.\n\nExample: Detener\n```js\nON('exit', function() {\n\tconsole.log('Bye');\n});\n\nF.exit();\n```\n\n### F.console()\n\nType: `method`\n\nImprime la información de arranque.\n\nReturns: `undefined`\n\nImprime el PID, las versiones de Node.js y Total.js, el sistema, la memoria, el usuario, el nombre, la versión y el autor de la aplicación, la fecha con la zona horaria, el modo (`debug` o `release`), el número de archivos compilados con el tiempo, las rutas de la raíz, del directorio y de `node_modules`, y la dirección del servidor. No se imprime nada cuando `CONF.$imprint` es `false`. El framework la llama después del arranque.\n\nExample: Imprimirla de nuevo\n```js\nON('ready', function() {\n\tF.console();\n});\n```\n\n### F.remote(url, [directory])\n\nType: `method`\n\nConecta la carpeta de la aplicación al Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL del editor, `wss://...?id=project`. |\n| `directory` | `String` | no | `F.directory` | La carpeta a editar. |\n\nReturns: `undefined`\n\nArranca el cliente de edición remota en el proceso actual: una conexión WebSocket a `url` que permite al editor explorar y modificar los archivos de `directory`. Se reconecta cada 10 segundos cuando se pierde la conexión. La opción de arranque `edit` hace lo mismo en el proceso del watcher.\n\nExample: Conectar\n```js\nF.remote('wss://code.example.com/?id=myproject');\n```\n\n### F.consumption\n\nType: `property`\n\nLas estadísticas de uso del proceso, actualizadas una vez por minuto.\n\nReturns: `Object`\n\nEl mismo objeto cada minuto (la primera vez 5 segundos después de cargar la aplicación); `ON('$stats')` también lo recibe y, con `CONF.$stats`, se escribe en `<script>.json`. Campos: `id`, `pid`, `thread`, `mode` (`debug` o `release`), `version` (`node`, `total`, `build`, `app` de `CONF.version`), `app` (`name` y `url` de la configuración), `date`, `memory` (heap usado en MB), `requests`, `pending`, `external`, `errors`, `timeouts`, `online` (clientes WebSocket), `download` y `upload` (MB en total), `lasterror`, `lasttimeout`, `usage` (porcentaje), `overload` (horas con carga alta), `uptime` (minutos desde el inicio) y los contadores por minuto `rm`, `fm`, `wm`, `em`, `mm`, `om`, `dm`, `um`, `pm`, `sm`, `cm`, `dbrm` y `dbwm`.\n\nExample: Leer\n```js\nsetInterval(function() {\n\tconsole.log(F.consumption.memory, 'MB', F.consumption.requests, 'requests');\n}, 60000);\n```\n\n### F.stats\n\nType: `property`\n\nContadores del framework para toda la vida del proceso.\n\nReturns: `Object`\n\n`F.stats.request` cuenta las peticiones (`request`, `web`, `xhr`, `file`, `websocket`, `get`, `post`, `put`, `patch`, `delete`, `upload`, `mobile`, `desktop`, `blocked`, `pending`, `size` ...), `F.stats.response` cuenta las respuestas por tipo (`json`, `html`, `file`, `redirect`, `stream`, `timeout`, `error404`, `error500` ...), `F.stats.performance` contiene los valores por minuto, `F.stats.error` el número de errores, y `F.stats.compiled` y `F.stats.compilation` el número de archivos cargados y el tiempo de carga en ms.\n\nExample: Informe sencillo\n```js\nROUTE('GET /stats/', function($) {\n\tvar s = F.stats;\n\t$.json({ requests: s.request.request, errors: s.error, notfound: s.response.error404 });\n});\n```\n\n### ON('$watcher', function(child) {})\n\nType: `event`\n\nSe emite en el watcher de debug después de arrancar el proceso de la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | El proceso de la aplicación. |\n\nSe ejecuta en el proceso del watcher, no en la aplicación, después de cada arranque o reinicio. `child` es el `ChildProcess` de la aplicación. Regístralo en el script de arranque antes de `F.run()`.\n\nExample: Registrar los reinicios\n```js\nrequire('total5');\n\nON('$watcher', function(child) {\n\tconsole.log('Application PID:', child.pid);\n});\n\nF.run();\n```\n\n### ON('watcher', function(child) {})\n\nType: `event`\n\nSe emite en el watcher de release después de arrancar el proceso de la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | El proceso de la aplicación. |\n\nSolo en modo release arrancado con `--watcher`. Se ejecuta en el proceso del watcher después de cada arranque. `child` es el `ChildProcess` de la aplicación.\n\nExample: Registrar los arranques\n```js\nrequire('total5');\n\nON('watcher', function(child) {\n\tconsole.log('Started PID:', child.pid);\n});\n\nF.run({ watcher: false });\n```\n\n### options.ip = String\n\nType: `property`\n\nLa dirección IP en la que escucha el servidor.\n\nReturns: `String` Por defecto: `CONF.$ip` (`0.0.0.0`)\n\nSe guarda en `CONF.$ip`. El valor por defecto `0.0.0.0` escucha en todas las interfaces.\n\nExample: Solo local\n```js\nF.run({ ip: '127.0.0.1', port: 8000 });\n```\n\n### options.port = Number\n\nType: `property`\n\nEl puerto del servidor.\n\nReturns: `Number` Por defecto: `8000`\n\nSe guarda en `CONF.$port`. Sin él, el puerto se toma de la variable de entorno `PORT` o de un argumento numérico del proceso (`node index.js 8000`), y el valor por defecto es `8000`.\n\nExample: Puerto desde los argumentos\n```js\nF.run({ port: parseInt(process.argv[2]) || 8000 });\n```\n\n### options.unixsocket = String\n\nType: `property`\n\nEscucha en un socket Unix en lugar de un puerto.\n\nReturns: `String`\n\nUn archivo de socket existente se elimina primero. En Windows la ruta se coloca en el espacio de named pipes. Se guarda en `CONF.$unixsocket`.\n\nExample: Socket\n```js\nF.run({ unixsocket: require('node:path').join(require('node:os').tmpdir(), 'app_name') });\n```\n\n### options.unixsocket777 = Boolean\n\nType: `property`\n\nDa al socket Unix los permisos 777.\n\nReturns: `Boolean` Por defecto: `false`\n\nCon `unixsocket`, el archivo de socket recibe `chmod 777` al crearse, para que otro usuario (por ejemplo, el servidor web) pueda conectarse a él.\n\nExample: Socket para nginx\n```js\nF.run({ unixsocket: '/tmp/app.socket', unixsocket777: true });\n```\n\n### options.config = Object\n\nType: `property`\n\nClaves de configuración que se aplican antes de cargar la aplicación.\n\nReturns: `Object`\n\nCada clave se aplica con `LOADCONFIG()` antes de `LOAD()`. El archivo `config` se lee después y puede sobrescribirlas. Úsalo para claves que se necesitan antes de leer el archivo `config`, como `bundling`.\n\nExample: Nombre y bundling\n```js\nF.run({ config: { name: 'My app', bundling: 'shallow' } });\n```\n\n### options.load = String\n\nType: `property`\n\nLas partes de la aplicación que se cargan.\n\nReturns: `String` Por defecto: `''`\n\nSe pasa a `LOAD()`: una lista separada por comas como `'config,controllers'`. Vacío lo carga todo; `'none'` arranca solo el servidor web. `options.type` es un alias.\n\nExample: Servidor de archivos estáticos\n```js\nF.http({ load: 'none', port: 8000 });\n```\n\n### options.watcher = Boolean\n\nType: `property`\n\n`false` arranca el modo release.\n\nReturns: `Boolean` Por defecto: `true`\n\nCon `F.run()`, `false` ejecuta la aplicación en modo release en el proceso actual; cualquier otro valor arranca el watcher de debug. En modo release, el argumento `--watcher` del proceso arranca un watcher de release que reinicia la aplicación cuando termina.\n\nExample: Release\n```js\nF.run({ watcher: false });\n```\n\n### options.release = Boolean\n\nType: `property`\n\nEjecuta la aplicación con `DEBUG = false` bajo el watcher de debug o el clúster.\n\nReturns: `Boolean` Por defecto: `false`\n\nEn modo debug el watcher sigue reiniciando la aplicación con los cambios, pero la aplicación se ejecuta con `DEBUG = false`. Con `cluster` arranca los hilos en modo release sin el watcher.\n\nExample: Clúster en release\n```js\nF.run({ cluster: 4, release: true });\n```\n\n### options.servicemode = Boolean|String\n\nType: `property`\n\nCarga la aplicación sin el servidor HTTP.\n\nReturns: `Boolean|String`\n\n`true` lo carga todo, y una cadena carga las partes listadas (los nombres de `LOAD()`), por ejemplo `'config,modules,actions'`.\n\nExample: Proceso worker\n```js\nF.run({ servicemode: 'config,modules,actions' });\n```\n\n### options.watch = Array\n\nType: `property`\n\nMás carpetas para el watcher de debug.\n\nReturns: `Array`\n\nRutas relativas a la raíz de la aplicación. Se eliminan la barra inicial y la final.\n\nExample: Vigilar una carpeta\n```js\nF.run({ watch: ['adminer', '/libs/'] });\n```\n\n### options.livereload = String\n\nType: `property`\n\nEnvía los archivos modificados al servicio de live reload de Total.js.\n\nReturns: `String`\n\nEl hostname de tu aplicación (se eliminan `http://` y `https://`). El vigilante de debug se conecta a `wss://livereload.totaljs.com/?hostname=<hostname>` y envía el nombre de cada archivo `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` o `.resource` modificado, incluidos los archivos de `public` y `views` (los demás archivos de las carpetas no se vigilan); los cambios en `public` y `views` no reinician la aplicación.\n\nExample: Live reload\n```js\nF.run({ livereload: 'myapp.example.com' });\n```\n\n### options.inspector = Number\n\nType: `property`\n\nArranca el proceso de la aplicación con el inspector de Node.js.\n\nReturns: `Number` Por defecto: `9229`\n\nEl watcher de debug añade `--inspect=<port>` a los argumentos de Node.js de la aplicación. Lo mismo ocurre cuando el propio watcher se arrancó con `--inspect`, con el puerto `9229`.\n\nExample: Inspector\n```js\nF.run({ inspector: 9229 });\n```\n\n### options.debugger = Number\n\nType: `property`\n\nArranca el proceso de la aplicación con `--debug=<port>`.\n\nReturns: `Number` Por defecto: `40894`\n\nEl watcher de debug añade `--debug=<port>` a los argumentos de Node.js de la aplicación. Lo mismo ocurre cuando el watcher se arrancó con `--debug`, con el puerto `40894`.\n\nExample: Depurador\n```js\nF.run({ debugger: 40894 });\n```\n\n### options.cluster = Number|String\n\nType: `property`\n\nEjecuta la aplicación en varios hilos del clúster.\n\nReturns: `Number|String`\n\nUn número de hilos, o `'auto'`: empieza con un hilo y añade un hilo cuando la latencia media de los hilos supera los 70 ms, hasta `options.limit`. En modo debug, el watcher reinicia todos los hilos después de un cambio; con `release: true` no hay watcher. Cada hilo carga la aplicación completa.\n\nExample: Cuatro hilos\n```js\nF.run({ cluster: 4, port: 8000 });\n```\n\nExample: Automático\n```js\nF.run({ cluster: 'auto', limit: 8, release: true });\n```\n\n### options.limit = Number\n\nType: `property`\n\nEl número máximo de hilos para `cluster: 'auto'`.\n\nReturns: `Number`\n\nSin él, el clúster automático añade hilos sin límite.\n\nExample: Límite\n```js\nF.run({ cluster: 'auto', limit: 4 });\n```\n\n### options.edit = String\n\nType: `property`\n\nConecta la aplicación al Total.js Code Editor.\n\nReturns: `String`\n\nLa URL del editor (`wss://...?id=project`; `http` se cambia por `ws`). El cliente se ejecuta en el watcher de debug, o en el watcher de release arrancado con `--watcher`, y arranca la aplicación un segundo después.\n\nExample: Edición remota\n```js\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\n### options.editmcp = String\n\nType: `property`\n\nConecta la aplicación a un proxy de edición MCP, para que un agente de IA pueda trabajar con sus archivos.\n\nReturns: `String`\n\nLa URL de la ruta WebSocket del proxy con el id del proyecto (`wss://proxy.example.com/$mcp/?id=myproject`; `http` se cambia a `ws`). El cliente se ejecuta en el watcher (así que no con `watcher: false`), se reconecta cada 10 segundos y arranca la aplicación un segundo después. Cuando también está definido `edit`, se usa `edit`.\n\nEl proxy es otra aplicación Total.js con `$mcp : true` que pasa su ruta WebSocket a `require('total5/edit-mcp').proxy()`. Su endpoint MCP `/$mcp/?id=myproject` lista las herramientas `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` y `App_restart` y las ejecuta en la aplicación conectada con el id `myproject`; sin una aplicación conectada, las herramientas responden `App is offline.`. Las rutas son relativas a la raíz de la aplicación, con o sin la `/` inicial. `App_write` guarda cada contenido escrito como una revisión numerada en la carpeta `revisions/` de la aplicación, `App_read` devuelve el número de la revisión actual y `App_restore` el contenido de una revisión, `App_move` mueve las revisiones junto con los archivos y `App_delete` las elimina (`/` no se puede eliminar). `App_shell` ejecuta cualquier comando de shell en la carpeta de la aplicación, así que protege el proxy con `Total.mcp.auth`.\n\nExample: La aplicación\n```js\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nExample: El proxy\n```js\n// config: $mcp : true\nconst editmcp = require('total5/edit-mcp');\n\nROUTE('SOCKET /$mcp/', function($) {\n\teditmcp.proxy($);\n});\n\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_token)\n\t\t$.success({ id: 'agent', name: 'Agent', sa: true });\n\telse\n\t\t$.invalid();\n};\n\n// the AI client connects to https://proxy.example.com/$mcp/?id=myproject\n```\n\n### bundling : shallow\n\nType: `config`\n\n`shallow` reutiliza la carpeta `.src` extraída en lugar de construirla de nuevo.\n\nReturns: `String`\n\nCuando es `shallow` y existe `.src/bundle.json`, los bundles no se extraen y los archivos no se copian; la aplicación se ejecuta desde el `.src` existente. Los bundles se procesan antes de leer el archivo `config`, así que establece la clave en `options.config`.\n\nExample: Bundling shallow\n```js\nF.run({ watcher: false, config: { bundling: 'shallow' } });\n```\n","entries":[{"type":"method","name":"F.run()","signature":"F.run([options])","since":"","deprecated":false},{"type":"method","name":"F.http()","signature":"F.http([options])","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [callback], [clear])","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"F.directory","signature":"F.directory","since":"","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"method","name":"F.dir()","signature":"F.dir([directory])","since":"","deprecated":false},{"type":"method","name":"F.restart()","signature":"F.restart()","since":"","deprecated":false},{"type":"method","name":"F.exit()","signature":"F.exit([signal])","since":"","deprecated":false},{"type":"method","name":"F.console()","signature":"F.console()","since":"","deprecated":false},{"type":"method","name":"F.remote()","signature":"F.remote(url, [directory])","since":"","deprecated":false},{"type":"property","name":"F.consumption","signature":"F.consumption","since":"","deprecated":false},{"type":"property","name":"F.stats","signature":"F.stats","since":"","deprecated":false},{"type":"event","name":"ON('$watcher')","signature":"ON('$watcher', function(child) {})","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(child) {})","since":"","deprecated":false},{"type":"property","name":"options.ip","signature":"options.ip = String","since":"","deprecated":false},{"type":"property","name":"options.port","signature":"options.port = Number","since":"","deprecated":false},{"type":"property","name":"options.unixsocket","signature":"options.unixsocket = String","since":"","deprecated":false},{"type":"property","name":"options.unixsocket777","signature":"options.unixsocket777 = Boolean","since":"","deprecated":false},{"type":"property","name":"options.config","signature":"options.config = Object","since":"","deprecated":false},{"type":"property","name":"options.load","signature":"options.load = String","since":"","deprecated":false},{"type":"property","name":"options.watcher","signature":"options.watcher = Boolean","since":"","deprecated":false},{"type":"property","name":"options.release","signature":"options.release = Boolean","since":"","deprecated":false},{"type":"property","name":"options.servicemode","signature":"options.servicemode = Boolean|String","since":"","deprecated":false},{"type":"property","name":"options.watch","signature":"options.watch = Array","since":"","deprecated":false},{"type":"property","name":"options.livereload","signature":"options.livereload = String","since":"","deprecated":false},{"type":"property","name":"options.inspector","signature":"options.inspector = Number","since":"","deprecated":false},{"type":"property","name":"options.debugger","signature":"options.debugger = Number","since":"","deprecated":false},{"type":"property","name":"options.cluster","signature":"options.cluster = Number|String","since":"","deprecated":false},{"type":"property","name":"options.limit","signature":"options.limit = Number","since":"","deprecated":false},{"type":"property","name":"options.edit","signature":"options.edit = String","since":"","deprecated":false},{"type":"property","name":"options.editmcp","signature":"options.editmcp = String","since":"","deprecated":false},{"type":"config","name":"bundling","signature":"bundling : shallow","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafwuo6Px60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/application-structure/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Structure de l'application et modes","summary":"F.run() et ses options de démarrage, LOAD(), IMPORT(), REQUIRE(), MODS et les statistiques du framework.","markdown":"---\ntitle: \"Structure de l'application et modes\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/application-structure/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Structure de l'application et modes\n\n> F.run() et ses options de démarrage, LOAD(), IMPORT(), REQUIRE(), MODS et les statistiques du framework.\n\nLes fonctions qui démarrent et chargent une application Total.js 5 : `F.run()` avec toutes les options de démarrage, `F.http()`, `LOAD()`, `IMPORT()`, `REQUIRE()`, `MODS`, `F.restart()`, `F.exit()`, les statistiques de `F.stats` et `F.consumption`, les événements du watcher et la clé `bundling`.\n\nLe guide [Structure de l'application et modes](../../guides/application-structure/) explique les dossiers, l'ordre de chargement, les modes debug et release, les bundles et l'édition à distance.\n\nL'exécuteur `Test` a sa propre page : [Tests unitaires](../unit-tests/).\n\n## API\n\n### F.run([options])\n\nType: `method`\n\nDémarre l'application en mode debug avec le watcher, ou en mode release.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Les options de démarrage : `ip`, `port`, `unixsocket`, `config`, `load`, `watcher`, `release`, `servicemode`, `watch`, `livereload`, `inspector`, `debugger`, `cluster`, `limit`, `edit`, `editmcp`. |\n\nReturns: `undefined`\n\nLa dernière ligne habituelle du script de démarrage. Sans `options.watcher = false`, elle démarre le watcher de debug (`debug.js`) : l'application s'exécute dans un processus enfant et redémarre quand un fichier change. Avec `watcher: false`, elle démarre le mode release (`release.js`) : l'application s'exécute dans le même processus avec `DEBUG = false`. Les options sont transmises à `F.http()` (ou à `LOAD()` en mode service) dans le processus de l'application. `Total.run()` est la même fonction.\n\nExample: Mode debug\n```js\nrequire('total5');\nF.run({ port: 8000 });\n```\n\nExample: Mode release\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nExample: Mode depuis la ligne de commande\n```js\nrequire('total5');\n\nvar options = {};\noptions.port = 8000;\n\nif (process.argv.includes('--release'))\n\toptions.watcher = false;\n\nF.run(options);\n```\n\n### F.http([options])\n\nType: `method`\n\nCharge l'application et démarre le serveur HTTP dans le processus courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | `ip`, `port`, `unixsocket`, `unixsocket777`, `config`, `load` (alias `type`) et `clear`. |\n\nReturns: `undefined`\n\nApplique `options.config` avec `LOADCONFIG()`, appelle `LOAD()` avec `options.load`, puis démarre le serveur. Quand l'application est déjà chargée, elle se contente de (re)démarrer le serveur ; un serveur en cours d'exécution est d'abord fermé. Avec la valeur par défaut `CONF.$port = 'auto'`, le port est pris dans `options.port`, puis dans la variable d'environnement `PORT`, puis dans le premier argument du processus comportant 3 à 5 chiffres (`node index.js 8000`), et la valeur par défaut est `8000`. Quand le processus n'a pas de parent, elle affiche les informations de démarrage.\n\n`F.run()` l'appelle pour toi ; appelle-la directement dans les scripts qui démarrent le serveur sans watcher (tests, outils).\n\nExample: Serveur pour les tests\n```js\nrequire('total5');\nF.http({ port: 8001, config: { name: 'Test' } });\n```\n\n### LOAD([types], [callback], [clear])\n\nType: `method`\n\nCharge la configuration, les ressources et les fichiers JavaScript de l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no | `''` | Les parties à charger, sous forme de chaîne séparée par des virgules ou de tableau ; vide charge tout. |\n| `callback` | `Function` | no |  | `function()` appelée quand tout est chargé. |\n| `clear` | `Boolean` | no | `true` | Vide le dossier temporaire avant le chargement. |\n\nReturns: `Promise` Résolue quand tout est chargé.\n\n`F.load()` est la même fonction. Elle définit les répertoires, construit les bundles, supprime les fichiers `.js`, `.css`, `.html`, `.htm`, `.tmp` et `.upload` du dossier temporaire (lorsque `clear` vaut `true`), puis charge les parties dans l'ordre du guide. Sans `types`, elle charge tout. Les noms sont `env`, `config`, `version`, `resources`, `jsonschemas`, `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers`, `middleware`, `plugins`, `flowstreams` et `stats` ; tout autre nom, comme `none`, ne charge rien. Lorsque `types` est donné sans `stats`, les statistiques et les source maps sont désactivées.\n\nÀ la fin, elle démarre le timer du service, définit `F.isLoaded`, `F.stats.compiled` et `F.stats.compilation`, appelle `callback` et émet `ready` et `load`. Elle ne démarre pas le serveur HTTP.\n\nExample: Processus en arrière-plan\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\tACTION('Jobs/run').callback(console.log);\n});\n```\n\nExample: Avec await\n```js\nrequire('total5');\n\n(async function() {\n\tawait LOAD('env,config');\n\tconsole.log(CONF.name);\n})();\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nTélécharge un fichier JavaScript et le charge comme module.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL d'un fichier `.js`. |\n| `callback` | `Function` | no |  | `function(err, module, response)` |\n\nReturns: `Promise` Quand `callback` n'est pas défini.\n\nLe fichier est téléchargé dans le dossier temporaire et chargé avec `require()`. Les appels suivants avec la même URL dans le même processus renvoient le module chargé sans le télécharger à nouveau. Une réponse avec le statut `400` ou plus donne l'erreur `The address answered with the status <status>` et rien n'est chargé. Un fichier qui n'est pas un module valide donne l'erreur de `require()`, par exemple une `SyntaxError`. Le callback reçoit `(err, module, response)` ; sans callback, la fonction renvoie une Promise avec le module.\n\nExample: Promesse\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n\nExample: Callback\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, helpers) {\n\tif (err)\n\t\tconsole.error(err);\n\telse\n\t\thelpers.hello();\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nCharge un module Node.js ou un paquet NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du module ou du paquet. |\n\nReturns: `Object` Le module.\n\nLes noms avec le préfixe `node:` et les modules intégrés de Node.js (`fs`, `path`, `crypto`, ...) sont chargés directement. Les autres noms sont chargés avec `require()` et, en cas d'échec, depuis le dossier indiqué dans `CONF.$nodemodules` (`<application>/node_modules` par défaut), de sorte que les paquets installés avec `NPMINSTALL()` sont trouvés. Elle lève une exception quand le module ne peut pas être chargé.\n\nExample: Charger\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### MODS\n\nType: `property`\n\nLes modules chargés depuis le dossier `modules`, par leur id.\n\nReturns: `Object`\n\nLe même objet que `F.modules`. Chaque fichier de `modules` est enregistré sous son `exports.id`, ou sous le nom du fichier sans `.js` quand `id` est absent, avant l'appel de son `install()`. Utilise-le pour appeler les fonctions qu'exporte un module.\n\nExample: Appeler un module\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// a controller or an action\nMODS.counter.increment();\n```\n\n### F.isLoaded\n\nType: `property`\n\n`true` quand l'application est chargée.\n\nReturns: `Boolean`\n\nDéfini par `LOAD()` une fois tous les fichiers chargés, juste avant les événements `ready` et `load`.\n\nExample: Vérifier\n```js\nif (F.isLoaded)\n\tconsole.log('Ready');\n```\n\n### F.directory\n\nType: `property`\n\nLe dossier racine de l'application.\n\nReturns: `String`\n\nLe répertoire de travail courant du processus au chargement de `total5`. Quand l'application s'exécute depuis des bundles, il pointe vers le dossier `.src`. Tous les chemins de `PATH.root()` partent d'ici.\n\nExample: Lire\n```js\nconsole.log(F.directory);\nconsole.log(PATH.root('config'));\n```\n\n### F.isBundle\n\nType: `property`\n\n`true` quand l'application s'exécute depuis des bundles.\n\nReturns: `Boolean`\n\nDéfini quand le dossier `bundles` contient des bundles (ou que `bundles.debug` existe) et que l'application a été construite dans `.src`.\n\nExample: Vérifier\n```js\nif (F.isBundle)\n\tconsole.log('Running from', F.directory);\n```\n\n### F.dir([directory])\n\nType: `method`\n\nDéfinit le dossier racine et recalcule les dossiers de l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no |  | Un nouveau dossier racine. |\n\nReturns: `undefined`\n\nAvec `directory`, elle modifie `F.directory`. Ensuite, elle définit les chemins dans `F.temporary.directories` pour `public`, `tmp`, `logs`, `databases`, `controllers`, `resources`, `plugins`, `modules`, `views`, `definitions`, `schemas`, `models`, `flowstreams`, `bundles`, `actions`, `extensions`, `source`, `services`, `updates`, `templates`, `private` et `scripts` : chacun prend la valeur de `CONF.$dir<name>` si elle est définie, sinon `<root>/<name>`. `LOAD()` l'appelle au démarrage.\n\nExample: Lire un dossier\n```js\nF.dir();\nconsole.log(F.temporary.directories.public);\n```\n\n### F.restart()\n\nType: `method`\n\nDemande au watcher de redémarrer l'application.\n\nReturns: `undefined`\n\nEnvoie `total:restart` au processus parent. Le watcher de debug, et le watcher de release démarré avec `--watcher`, affichent `RES` et redémarrent l'application. Sans watcher, rien ne se passe.\n\nExample: Après une mise à jour\n```js\nNEWACTION('Settings/save', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tF.Fs.writeFile(PATH.root('config'), 'name : ' + model.name, function() {\n\t\t\t$.success();\n\t\t\tF.restart();\n\t\t});\n\t}\n});\n```\n\n### F.exit([signal])\n\nType: `method`\n\nArrête l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | no | `15` | Le signal pour les processus enfants. |\n\nReturns: `undefined`\n\nTue les workers et les pipelines Python avec `signal`, détruit les instances FlowStream, émet `exit`, envoie `total:stop` au processus parent, arrête le timer de service et ferme le serveur HTTP. Le processus se termine 300 ms plus tard. Le framework l'appelle sur `SIGTERM`, `SIGINT` et à la sortie du processus.\n\nExample: Arrêter\n```js\nON('exit', function() {\n\tconsole.log('Bye');\n});\n\nF.exit();\n```\n\n### F.console()\n\nType: `method`\n\nAffiche les informations de démarrage.\n\nReturns: `undefined`\n\nAffiche le PID, les versions de Node.js et de Total.js, le système, la mémoire, l'utilisateur, le nom, la version et l'auteur de l'application, la date avec le fuseau horaire, le mode (`debug` ou `release`), le nombre de fichiers compilés avec la durée, les chemins de la racine, du répertoire et de `node_modules`, et l'adresse du serveur. Rien n'est affiché quand `CONF.$imprint` vaut `false`. Le framework l'appelle après le démarrage.\n\nExample: Les afficher à nouveau\n```js\nON('ready', function() {\n\tF.console();\n});\n```\n\n### F.remote(url, [directory])\n\nType: `method`\n\nConnecte le dossier de l'application au Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL fournie par l'éditeur, `wss://...?id=project`. |\n| `directory` | `String` | no | `F.directory` | Le dossier à modifier. |\n\nReturns: `undefined`\n\nDémarre le client d'édition à distance dans le processus courant : une connexion WebSocket vers `url` qui permet à l'éditeur de parcourir et de modifier les fichiers de `directory`. Il se reconnecte toutes les 10 secondes quand la connexion est perdue. L'option de démarrage `edit` fait la même chose dans le processus du watcher.\n\nExample: Connecter\n```js\nF.remote('wss://code.example.com/?id=myproject');\n```\n\n### F.consumption\n\nType: `property`\n\nLes statistiques d'utilisation du processus, mises à jour une fois par minute.\n\nReturns: `Object`\n\nLe même objet chaque minute (la première fois 5 secondes après le chargement de l'application) ; `ON('$stats')` le reçoit aussi et, avec `CONF.$stats`, il est écrit dans `<script>.json`. Champs : `id`, `pid`, `thread`, `mode` (`debug` ou `release`), `version` (`node`, `total`, `build`, `app` depuis `CONF.version`), `app` (`name` et `url` depuis la configuration), `date`, `memory` (heap utilisé en Mo), `requests`, `pending`, `external`, `errors`, `timeouts`, `online` (clients WebSocket), `download` et `upload` (Mo au total), `lasterror`, `lasttimeout`, `usage` (pourcentage), `overload` (heures de forte charge), `uptime` (minutes depuis le démarrage) et les compteurs par minute `rm`, `fm`, `wm`, `em`, `mm`, `om`, `dm`, `um`, `pm`, `sm`, `cm`, `dbrm` et `dbwm`.\n\nExample: Lire\n```js\nsetInterval(function() {\n\tconsole.log(F.consumption.memory, 'MB', F.consumption.requests, 'requests');\n}, 60000);\n```\n\n### F.stats\n\nType: `property`\n\nLes compteurs du framework pour toute la durée de vie du processus.\n\nReturns: `Object`\n\n`F.stats.request` compte les requêtes (`request`, `web`, `xhr`, `file`, `websocket`, `get`, `post`, `put`, `patch`, `delete`, `upload`, `mobile`, `desktop`, `blocked`, `pending`, `size` ...), `F.stats.response` compte les réponses par type (`json`, `html`, `file`, `redirect`, `stream`, `timeout`, `error404`, `error500` ...), `F.stats.performance` contient les valeurs par minute, `F.stats.error` le nombre d'erreurs, et `F.stats.compiled` et `F.stats.compilation` le nombre de fichiers chargés et la durée de chargement en ms.\n\nExample: Rapport simple\n```js\nROUTE('GET /stats/', function($) {\n\tvar s = F.stats;\n\t$.json({ requests: s.request.request, errors: s.error, notfound: s.response.error404 });\n});\n```\n\n### ON('$watcher', function(child) {})\n\nType: `event`\n\nÉmis dans le watcher de debug après qu'il a démarré le processus de l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | Le processus de l'application. |\n\nIl s'exécute dans le processus du watcher, pas dans l'application, après chaque démarrage ou redémarrage. `child` est le `ChildProcess` de l'application. Enregistre-le dans le script de démarrage avant `F.run()`.\n\nExample: Journaliser les redémarrages\n```js\nrequire('total5');\n\nON('$watcher', function(child) {\n\tconsole.log('Application PID:', child.pid);\n});\n\nF.run();\n```\n\n### ON('watcher', function(child) {})\n\nType: `event`\n\nÉmis dans le watcher de release après qu'il a démarré le processus de l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | Le processus de l'application. |\n\nUniquement en mode release démarré avec `--watcher`. Il s'exécute dans le processus du watcher après chaque démarrage. `child` est le `ChildProcess` de l'application.\n\nExample: Journaliser les démarrages\n```js\nrequire('total5');\n\nON('watcher', function(child) {\n\tconsole.log('Started PID:', child.pid);\n});\n\nF.run({ watcher: false });\n```\n\n### options.ip = String\n\nType: `property`\n\nL'adresse IP sur laquelle le serveur écoute.\n\nReturns: `String` Valeur par défaut : `CONF.$ip` (`0.0.0.0`)\n\nStocké dans `CONF.$ip`. La valeur par défaut `0.0.0.0` écoute sur toutes les interfaces.\n\nExample: Local uniquement\n```js\nF.run({ ip: '127.0.0.1', port: 8000 });\n```\n\n### options.port = Number\n\nType: `property`\n\nLe port du serveur.\n\nReturns: `Number` Valeur par défaut : `8000`\n\nStocké dans `CONF.$port`. Sans lui, le port provient de la variable d'environnement `PORT` ou d'un argument numérique du processus (`node index.js 8000`), et la valeur par défaut est `8000`.\n\nExample: Port depuis les arguments\n```js\nF.run({ port: parseInt(process.argv[2]) || 8000 });\n```\n\n### options.unixsocket = String\n\nType: `property`\n\nÉcoute sur un socket Unix au lieu d'un port.\n\nReturns: `String`\n\nUn fichier de socket existant est d'abord supprimé. Sous Windows, le chemin est placé dans l'espace des named pipes. Stocké dans `CONF.$unixsocket`.\n\nExample: Socket\n```js\nF.run({ unixsocket: require('node:path').join(require('node:os').tmpdir(), 'app_name') });\n```\n\n### options.unixsocket777 = Boolean\n\nType: `property`\n\nDonne au socket Unix les permissions 777.\n\nReturns: `Boolean` Valeur par défaut : `false`\n\nAvec `unixsocket`, le fichier de socket reçoit `chmod 777` à sa création, de sorte qu'un autre utilisateur (par exemple le serveur web) peut s'y connecter.\n\nExample: Socket pour nginx\n```js\nF.run({ unixsocket: '/tmp/app.socket', unixsocket777: true });\n```\n\n### options.config = Object\n\nType: `property`\n\nLes clés de configuration appliquées avant le chargement de l'application.\n\nReturns: `Object`\n\nChaque clé est appliquée avec `LOADCONFIG()` avant `LOAD()`. Le fichier `config` est lu plus tard et peut les remplacer. Utilise-la pour les clés nécessaires avant la lecture du fichier `config`, comme `bundling`.\n\nExample: Nom et bundling\n```js\nF.run({ config: { name: 'My app', bundling: 'shallow' } });\n```\n\n### options.load = String\n\nType: `property`\n\nLes parties de l'application qui sont chargées.\n\nReturns: `String` Valeur par défaut : `''`\n\nTransmise à `LOAD()` : une liste séparée par des virgules comme `'config,controllers'`. Vide charge tout ; `'none'` ne démarre que le serveur web. `options.type` est un alias.\n\nExample: Serveur de fichiers statiques\n```js\nF.http({ load: 'none', port: 8000 });\n```\n\n### options.watcher = Boolean\n\nType: `property`\n\n`false` démarre le mode release.\n\nReturns: `Boolean` Valeur par défaut : `true`\n\nAvec `F.run()`, `false` exécute l'application en mode release dans le processus courant ; toute autre valeur démarre le watcher de debug. En mode release, l'argument `--watcher` du processus démarre un watcher de release qui redémarre l'application quand elle se termine.\n\nExample: Release\n```js\nF.run({ watcher: false });\n```\n\n### options.release = Boolean\n\nType: `property`\n\nExécute l'application avec `DEBUG = false` sous le watcher de debug ou le cluster.\n\nReturns: `Boolean` Valeur par défaut : `false`\n\nEn mode debug, le watcher redémarre toujours l'application lors des modifications, mais l'application s'exécute avec `DEBUG = false`. Avec `cluster`, elle démarre les threads en mode release sans le watcher.\n\nExample: Cluster en release\n```js\nF.run({ cluster: 4, release: true });\n```\n\n### options.servicemode = Boolean|String\n\nType: `property`\n\nCharge l'application sans le serveur HTTP.\n\nReturns: `Boolean|String`\n\n`true` charge tout, une chaîne charge les parties listées (les noms de `LOAD()`), par exemple `'config,modules,actions'`.\n\nExample: Processus worker\n```js\nF.run({ servicemode: 'config,modules,actions' });\n```\n\n### options.watch = Array\n\nType: `property`\n\nDes dossiers supplémentaires pour le watcher de debug.\n\nReturns: `Array`\n\nChemins relatifs à la racine de l'application. Une barre oblique initiale et une barre oblique finale sont supprimées.\n\nExample: Surveiller un dossier\n```js\nF.run({ watch: ['adminer', '/libs/'] });\n```\n\n### options.livereload = String\n\nType: `property`\n\nEnvoie les fichiers modifiés au service de live reload de Total.js.\n\nReturns: `String`\n\nLe nom d'hôte de ton application (`http://` et `https://` sont supprimés). Le watcher debug se connecte à `wss://livereload.totaljs.com/?hostname=<hostname>` et envoie le nom de chaque fichier `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` ou `.resource` modifié, y compris les fichiers de `public` et `views` (les autres fichiers des dossiers ne sont pas surveillés) ; les modifications dans `public` et `views` ne redémarrent pas l'application.\n\nExample: Live reload\n```js\nF.run({ livereload: 'myapp.example.com' });\n```\n\n### options.inspector = Number\n\nType: `property`\n\nDémarre le processus de l'application avec l'inspecteur de Node.js.\n\nReturns: `Number` Valeur par défaut : `9229`\n\nLe watcher de debug ajoute `--inspect=<port>` aux arguments Node.js de l'application. Il en va de même quand le watcher lui-même a été démarré avec `--inspect`, avec le port `9229`.\n\nExample: Inspecteur\n```js\nF.run({ inspector: 9229 });\n```\n\n### options.debugger = Number\n\nType: `property`\n\nDémarre le processus de l'application avec `--debug=<port>`.\n\nReturns: `Number` Valeur par défaut : `40894`\n\nLe watcher de debug ajoute `--debug=<port>` aux arguments Node.js de l'application. Il en va de même quand le watcher a été démarré avec `--debug`, avec le port `40894`.\n\nExample: Débogueur\n```js\nF.run({ debugger: 40894 });\n```\n\n### options.cluster = Number|String\n\nType: `property`\n\nExécute l'application dans plusieurs threads de cluster.\n\nReturns: `Number|String`\n\nUn nombre de threads, ou `'auto'` : il démarre avec un thread et ajoute un thread quand la latence moyenne des threads dépasse 70 ms, jusqu'à `options.limit`. En mode debug, le watcher redémarre tous les threads après une modification ; avec `release: true`, il n'y a pas de watcher. Chaque thread charge toute l'application.\n\nExample: Quatre threads\n```js\nF.run({ cluster: 4, port: 8000 });\n```\n\nExample: Automatique\n```js\nF.run({ cluster: 'auto', limit: 8, release: true });\n```\n\n### options.limit = Number\n\nType: `property`\n\nLe nombre maximal de threads pour `cluster: 'auto'`.\n\nReturns: `Number`\n\nSans elle, le cluster automatique ajoute des threads sans limite.\n\nExample: Limite\n```js\nF.run({ cluster: 'auto', limit: 4 });\n```\n\n### options.edit = String\n\nType: `property`\n\nConnecte l'application au Total.js Code Editor.\n\nReturns: `String`\n\nL'URL fournie par l'éditeur (`wss://...?id=project` ; `http` est remplacé par `ws`). Le client s'exécute dans le watcher de debug, ou dans le watcher de release démarré avec `--watcher`, et démarre l'application une seconde plus tard.\n\nExample: Édition à distance\n```js\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\n### options.editmcp = String\n\nType: `property`\n\nConnecte l'application à un proxy d'édition MCP, pour qu'un agent IA puisse travailler sur ses fichiers.\n\nReturns: `String`\n\nL'URL de la route WebSocket du proxy avec l'id du projet (`wss://proxy.example.com/$mcp/?id=myproject` ; `http` est changé en `ws`). Le client s'exécute dans le watcher (donc pas avec `watcher: false`), se reconnecte toutes les 10 secondes et démarre l'application une seconde plus tard. Quand `edit` est aussi défini, c'est `edit` qui est utilisé.\n\nLe proxy est une autre application Total.js avec `$mcp : true` qui transmet sa route WebSocket à `require('total5/edit-mcp').proxy()`. Son endpoint MCP `/$mcp/?id=myproject` liste les outils `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` et `App_restart` et les exécute dans l'application connectée avec l'id `myproject` ; sans application connectée, les outils répondent `App is offline.`. Les chemins sont relatifs à la racine de l'application, avec ou sans le `/` initial. `App_write` enregistre chaque contenu écrit comme une révision numérotée dans le dossier `revisions/` de l'application, `App_read` renvoie le numéro de la révision actuelle et `App_restore` le contenu d'une révision, `App_move` déplace les révisions avec les fichiers et `App_delete` les supprime (`/` ne peut pas être supprimé). `App_shell` exécute n'importe quelle commande shell dans le dossier de l'application, alors protège le proxy avec `Total.mcp.auth`.\n\nExample: L'application\n```js\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nExample: Le proxy\n```js\n// config: $mcp : true\nconst editmcp = require('total5/edit-mcp');\n\nROUTE('SOCKET /$mcp/', function($) {\n\teditmcp.proxy($);\n});\n\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_token)\n\t\t$.success({ id: 'agent', name: 'Agent', sa: true });\n\telse\n\t\t$.invalid();\n};\n\n// the AI client connects to https://proxy.example.com/$mcp/?id=myproject\n```\n\n### bundling : shallow\n\nType: `config`\n\n`shallow` réutilise le dossier `.src` extrait au lieu de le reconstruire.\n\nReturns: `String`\n\nQuand elle vaut `shallow` et que `.src/bundle.json` existe, les bundles ne sont pas extraits et les fichiers ne sont pas copiés ; l'application s'exécute depuis le `.src` existant. Les bundles sont traités avant la lecture du fichier `config` : définis donc la clé dans `options.config`.\n\nExample: Bundling shallow\n```js\nF.run({ watcher: false, config: { bundling: 'shallow' } });\n```\n","entries":[{"type":"method","name":"F.run()","signature":"F.run([options])","since":"","deprecated":false},{"type":"method","name":"F.http()","signature":"F.http([options])","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [callback], [clear])","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"F.directory","signature":"F.directory","since":"","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"method","name":"F.dir()","signature":"F.dir([directory])","since":"","deprecated":false},{"type":"method","name":"F.restart()","signature":"F.restart()","since":"","deprecated":false},{"type":"method","name":"F.exit()","signature":"F.exit([signal])","since":"","deprecated":false},{"type":"method","name":"F.console()","signature":"F.console()","since":"","deprecated":false},{"type":"method","name":"F.remote()","signature":"F.remote(url, [directory])","since":"","deprecated":false},{"type":"property","name":"F.consumption","signature":"F.consumption","since":"","deprecated":false},{"type":"property","name":"F.stats","signature":"F.stats","since":"","deprecated":false},{"type":"event","name":"ON('$watcher')","signature":"ON('$watcher', function(child) {})","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(child) {})","since":"","deprecated":false},{"type":"property","name":"options.ip","signature":"options.ip = String","since":"","deprecated":false},{"type":"property","name":"options.port","signature":"options.port = Number","since":"","deprecated":false},{"type":"property","name":"options.unixsocket","signature":"options.unixsocket = String","since":"","deprecated":false},{"type":"property","name":"options.unixsocket777","signature":"options.unixsocket777 = Boolean","since":"","deprecated":false},{"type":"property","name":"options.config","signature":"options.config = Object","since":"","deprecated":false},{"type":"property","name":"options.load","signature":"options.load = String","since":"","deprecated":false},{"type":"property","name":"options.watcher","signature":"options.watcher = Boolean","since":"","deprecated":false},{"type":"property","name":"options.release","signature":"options.release = Boolean","since":"","deprecated":false},{"type":"property","name":"options.servicemode","signature":"options.servicemode = Boolean|String","since":"","deprecated":false},{"type":"property","name":"options.watch","signature":"options.watch = Array","since":"","deprecated":false},{"type":"property","name":"options.livereload","signature":"options.livereload = String","since":"","deprecated":false},{"type":"property","name":"options.inspector","signature":"options.inspector = Number","since":"","deprecated":false},{"type":"property","name":"options.debugger","signature":"options.debugger = Number","since":"","deprecated":false},{"type":"property","name":"options.cluster","signature":"options.cluster = Number|String","since":"","deprecated":false},{"type":"property","name":"options.limit","signature":"options.limit = Number","since":"","deprecated":false},{"type":"property","name":"options.edit","signature":"options.edit = String","since":"","deprecated":false},{"type":"property","name":"options.editmcp","signature":"options.editmcp = String","since":"","deprecated":false},{"type":"config","name":"bundling","signature":"bundling : shallow","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafwuo6Px60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/application-structure/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Struttura dell'applicazione e modalità","summary":"F.run() e le sue opzioni di avvio, LOAD(), IMPORT(), REQUIRE(), MODS e le statistiche del framework.","markdown":"---\ntitle: \"Struttura dell'applicazione e modalità\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/application-structure/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Struttura dell'applicazione e modalità\n\n> F.run() e le sue opzioni di avvio, LOAD(), IMPORT(), REQUIRE(), MODS e le statistiche del framework.\n\nLe funzioni che avviano e caricano un'applicazione Total.js 5: `F.run()` con tutte le opzioni di avvio, `F.http()`, `LOAD()`, `IMPORT()`, `REQUIRE()`, `MODS`, `F.restart()`, `F.exit()`, le statistiche in `F.stats` e `F.consumption`, gli eventi del watcher e la chiave `bundling`.\n\nLa guida [Struttura dell'applicazione e modalità](../../guides/application-structure/) spiega le cartelle, l'ordine di caricamento, le modalità debug e release, i bundle e la modifica remota.\n\nIl runner `Test` ha una pagina propria: [Test unitari](../unit-tests/).\n\n## API\n\n### F.run([options])\n\nType: `method`\n\nAvvia l'applicazione in modalità debug con il watcher, o in modalità release.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Le opzioni di avvio: `ip`, `port`, `unixsocket`, `config`, `load`, `watcher`, `release`, `servicemode`, `watch`, `livereload`, `inspector`, `debugger`, `cluster`, `limit`, `edit`, `editmcp`. |\n\nReturns: `undefined`\n\nLa consueta ultima riga dello script di avvio. Senza `options.watcher = false` avvia il watcher di debug (`debug.js`): l'applicazione gira in un processo figlio e si riavvia quando un file cambia. Con `watcher: false` avvia la modalità release (`release.js`): l'applicazione gira nello stesso processo con `DEBUG = false`. Le opzioni vengono passate a `F.http()` (o a `LOAD()` in modalità servizio) nel processo dell'applicazione. `Total.run()` è la stessa funzione.\n\nExample: Modalità debug\n```js\nrequire('total5');\nF.run({ port: 8000 });\n```\n\nExample: Modalità release\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nExample: Modalità dalla riga di comando\n```js\nrequire('total5');\n\nvar options = {};\noptions.port = 8000;\n\nif (process.argv.includes('--release'))\n\toptions.watcher = false;\n\nF.run(options);\n```\n\n### F.http([options])\n\nType: `method`\n\nCarica l'applicazione e avvia il server HTTP nel processo corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | `ip`, `port`, `unixsocket`, `unixsocket777`, `config`, `load` (alias `type`) e `clear`. |\n\nReturns: `undefined`\n\nApplica `options.config` con `LOADCONFIG()`, chiama `LOAD()` con `options.load` e poi avvia il server. Quando l'applicazione è già caricata, (ri)avvia solo il server; un server in esecuzione viene prima chiuso. Con il predefinito `CONF.$port = 'auto'`, la porta viene presa da `options.port`, poi dalla variabile d'ambiente `PORT`, poi dal primo argomento del processo con 3-5 cifre (`node index.js 8000`), e il predefinito è `8000`. Quando il processo non ha un genitore, stampa le informazioni di avvio.\n\n`F.run()` la chiama per te; chiamala direttamente negli script che avviano il server senza watcher (test, strumenti).\n\nExample: Server per i test\n```js\nrequire('total5');\nF.http({ port: 8001, config: { name: 'Test' } });\n```\n\n### LOAD([types], [callback], [clear])\n\nType: `method`\n\nCarica la configurazione, le risorse e i file JavaScript dell'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no | `''` | Le parti da caricare, come stringa separata da virgole o array; vuoto carica tutto. |\n| `callback` | `Function` | no |  | `function()` chiamata quando tutto è caricato. |\n| `clear` | `Boolean` | no | `true` | Svuota la cartella temporanea prima del caricamento. |\n\nReturns: `Promise` Si risolve quando tutto è caricato.\n\n`F.load()` è la stessa funzione. Imposta le directory, costruisce i bundle, rimuove i file `.js`, `.css`, `.html`, `.htm`, `.tmp` e `.upload` dalla cartella temporanea (quando `clear` è `true`) e poi carica le parti nell'ordine della guida. Senza `types` carica tutto. I nomi sono `env`, `config`, `version`, `resources`, `jsonschemas`, `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers`, `middleware`, `plugins`, `flowstreams` e `stats`; qualsiasi altro nome, come `none`, non carica nulla. Quando `types` viene indicato senza `stats`, le statistiche e le source map vengono disattivate.\n\nAlla fine avvia il timer del servizio, imposta `F.isLoaded`, `F.stats.compiled` e `F.stats.compilation`, chiama `callback` ed emette `ready` e `load`. Non avvia il server HTTP.\n\nExample: Processo in background\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\tACTION('Jobs/run').callback(console.log);\n});\n```\n\nExample: Con await\n```js\nrequire('total5');\n\n(async function() {\n\tawait LOAD('env,config');\n\tconsole.log(CONF.name);\n})();\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nScarica un file JavaScript e lo carica come modulo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL di un file `.js`. |\n| `callback` | `Function` | no |  | `function(err, module, response)` |\n\nReturns: `Promise` Quando `callback` non è impostata.\n\nIl file viene scaricato nella cartella temporanea e caricato con `require()`. Le chiamate successive con lo stesso URL nello stesso processo restituiscono il modulo caricato senza scaricarlo di nuovo. Una risposta con lo stato `400` o superiore dà l'errore `The address answered with the status <status>` e non viene caricato nulla. Un file che non è un modulo valido dà l'errore di `require()`, per esempio un `SyntaxError`. La callback riceve `(err, module, response)`; senza callback la funzione restituisce una Promise con il modulo.\n\nExample: Promise\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n\nExample: Callback\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, helpers) {\n\tif (err)\n\t\tconsole.error(err);\n\telse\n\t\thelpers.hello();\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nCarica un modulo Node.js o un pacchetto NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del modulo o del pacchetto. |\n\nReturns: `Object` Il modulo.\n\nI nomi con il prefisso `node:` e i moduli integrati di Node.js (`fs`, `path`, `crypto`, ...) vengono caricati direttamente. Gli altri nomi vengono caricati con `require()` e, quando questo fallisce, dalla cartella in `CONF.$nodemodules` (`<application>/node_modules` per impostazione predefinita), così i pacchetti installati con `NPMINSTALL()` vengono trovati. Genera un'eccezione quando il modulo non può essere caricato.\n\nExample: Caricare\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### MODS\n\nType: `property`\n\nI moduli caricati dalla cartella `modules`, per id.\n\nReturns: `Object`\n\nLo stesso oggetto di `F.modules`. Ogni file in `modules` viene registrato sotto il suo `exports.id`, o sotto il nome del file senza `.js` quando `id` manca, prima che venga chiamata la sua `install()`. Usalo per chiamare le funzioni esportate da un modulo.\n\nExample: Chiamare un modulo\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// a controller or an action\nMODS.counter.increment();\n```\n\n### F.isLoaded\n\nType: `property`\n\n`true` quando l'applicazione è caricata.\n\nReturns: `Boolean`\n\nImpostata da `LOAD()` dopo che tutti i file sono caricati, subito prima degli eventi `ready` e `load`.\n\nExample: Verificare\n```js\nif (F.isLoaded)\n\tconsole.log('Ready');\n```\n\n### F.directory\n\nType: `property`\n\nLa cartella root dell'applicazione.\n\nReturns: `String`\n\nLa directory di lavoro corrente del processo quando viene caricato `total5`. Quando l'applicazione gira dai bundle, punta alla cartella `.src`. Tutti i percorsi di `PATH.root()` partono da qui.\n\nExample: Leggere\n```js\nconsole.log(F.directory);\nconsole.log(PATH.root('config'));\n```\n\n### F.isBundle\n\nType: `property`\n\n`true` quando l'applicazione gira dai bundle.\n\nReturns: `Boolean`\n\nImpostata quando la cartella `bundles` contiene bundle (o esiste `bundles.debug`) e l'applicazione è stata costruita in `.src`.\n\nExample: Verificare\n```js\nif (F.isBundle)\n\tconsole.log('Running from', F.directory);\n```\n\n### F.dir([directory])\n\nType: `method`\n\nImposta la cartella root e ricalcola le cartelle dell'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no |  | Una nuova cartella root. |\n\nReturns: `undefined`\n\nCon `directory` cambia `F.directory`. Poi imposta i percorsi in `F.temporary.directories` per `public`, `tmp`, `logs`, `databases`, `controllers`, `resources`, `plugins`, `modules`, `views`, `definitions`, `schemas`, `models`, `flowstreams`, `bundles`, `actions`, `extensions`, `source`, `services`, `updates`, `templates`, `private` e `scripts`: ciascuno è il valore di `CONF.$dir<name>` quando è impostato, altrimenti `<root>/<name>`. `LOAD()` la chiama all'avvio.\n\nExample: Leggere una cartella\n```js\nF.dir();\nconsole.log(F.temporary.directories.public);\n```\n\n### F.restart()\n\nType: `method`\n\nChiede al watcher di riavviare l'applicazione.\n\nReturns: `undefined`\n\nInvia `total:restart` al processo genitore. Il watcher di debug, e il watcher di release avviato con `--watcher`, stampano `RES` e avviano di nuovo l'applicazione. Senza watcher non succede nulla.\n\nExample: Dopo un aggiornamento\n```js\nNEWACTION('Settings/save', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tF.Fs.writeFile(PATH.root('config'), 'name : ' + model.name, function() {\n\t\t\t$.success();\n\t\t\tF.restart();\n\t\t});\n\t}\n});\n```\n\n### F.exit([signal])\n\nType: `method`\n\nFerma l'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | no | `15` | Il segnale per i processi figli. |\n\nReturns: `undefined`\n\nTermina i worker e le pipeline Python con `signal`, distrugge le istanze FlowStream, emette `exit`, comunica `total:stop` al processo genitore, ferma il timer di servizio e chiude il server HTTP. Il processo termina 300 ms dopo. Il framework la chiama su `SIGTERM`, `SIGINT` e quando il processo esce.\n\nExample: Fermare\n```js\nON('exit', function() {\n\tconsole.log('Bye');\n});\n\nF.exit();\n```\n\n### F.console()\n\nType: `method`\n\nStampa le informazioni di avvio.\n\nReturns: `undefined`\n\nStampa il PID, le versioni di Node.js e Total.js, il sistema, la memoria, l'utente, il nome, la versione e l'autore dell'applicazione, la data con il fuso orario, la modalità (`debug` o `release`), il numero di file compilati con il tempo, i percorsi di root, directory e `node_modules` e l'indirizzo del server. Non viene stampato nulla quando `CONF.$imprint` è `false`. Il framework la chiama dopo l'avvio.\n\nExample: Stamparle di nuovo\n```js\nON('ready', function() {\n\tF.console();\n});\n```\n\n### F.remote(url, [directory])\n\nType: `method`\n\nConnette la cartella dell'applicazione al Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL fornito dall'editor, `wss://...?id=project`. |\n| `directory` | `String` | no | `F.directory` | La cartella da modificare. |\n\nReturns: `undefined`\n\nAvvia il client di modifica remota nel processo corrente: una connessione WebSocket a `url` che permette all'editor di sfogliare e modificare i file in `directory`. Si riconnette ogni 10 secondi quando la connessione si interrompe. L'opzione di avvio `edit` fa lo stesso nel processo del watcher.\n\nExample: Connettere\n```js\nF.remote('wss://code.example.com/?id=myproject');\n```\n\n### F.consumption\n\nType: `property`\n\nLe statistiche di utilizzo del processo, aggiornate una volta al minuto.\n\nReturns: `Object`\n\nLo stesso oggetto ogni minuto (la prima volta 5 secondi dopo il caricamento dell'applicazione); lo riceve anche `ON('$stats')` e, con `CONF.$stats`, viene scritto in `<script>.json`. Campi: `id`, `pid`, `thread`, `mode` (`debug` o `release`), `version` (`node`, `total`, `build`, `app` da `CONF.version`), `app` (`name` e `url` dalla configurazione), `date`, `memory` (heap usato in MB), `requests`, `pending`, `external`, `errors`, `timeouts`, `online` (client WebSocket), `download` e `upload` (MB in totale), `lasterror`, `lasttimeout`, `usage` (percentuale), `overload` (ore con carico elevato), `uptime` (minuti dall'avvio) e i contatori al minuto `rm`, `fm`, `wm`, `em`, `mm`, `om`, `dm`, `um`, `pm`, `sm`, `cm`, `dbrm` e `dbwm`.\n\nExample: Leggere\n```js\nsetInterval(function() {\n\tconsole.log(F.consumption.memory, 'MB', F.consumption.requests, 'requests');\n}, 60000);\n```\n\n### F.stats\n\nType: `property`\n\nContatori del framework per l'intera vita del processo.\n\nReturns: `Object`\n\n`F.stats.request` conta le richieste (`request`, `web`, `xhr`, `file`, `websocket`, `get`, `post`, `put`, `patch`, `delete`, `upload`, `mobile`, `desktop`, `blocked`, `pending`, `size` ...), `F.stats.response` conta le risposte per tipo (`json`, `html`, `file`, `redirect`, `stream`, `timeout`, `error404`, `error500` ...), `F.stats.performance` contiene i valori al minuto, `F.stats.error` il numero di errori, e `F.stats.compiled` e `F.stats.compilation` il numero di file caricati e il tempo di caricamento in ms.\n\nExample: Report semplice\n```js\nROUTE('GET /stats/', function($) {\n\tvar s = F.stats;\n\t$.json({ requests: s.request.request, errors: s.error, notfound: s.response.error404 });\n});\n```\n\n### ON('$watcher', function(child) {})\n\nType: `event`\n\nEmesso nel watcher di debug dopo che ha avviato il processo dell'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | Il processo dell'applicazione. |\n\nViene eseguito nel processo del watcher, non nell'applicazione, dopo ogni avvio o riavvio. `child` è il `ChildProcess` dell'applicazione. Registralo nello script di avvio prima di `F.run()`.\n\nExample: Registrare i riavvii\n```js\nrequire('total5');\n\nON('$watcher', function(child) {\n\tconsole.log('Application PID:', child.pid);\n});\n\nF.run();\n```\n\n### ON('watcher', function(child) {})\n\nType: `event`\n\nEmesso nel watcher di release dopo che ha avviato il processo dell'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | Il processo dell'applicazione. |\n\nSolo in modalità release avviata con `--watcher`. Viene eseguito nel processo del watcher dopo ogni avvio. `child` è il `ChildProcess` dell'applicazione.\n\nExample: Registrare gli avvii\n```js\nrequire('total5');\n\nON('watcher', function(child) {\n\tconsole.log('Started PID:', child.pid);\n});\n\nF.run({ watcher: false });\n```\n\n### options.ip = String\n\nType: `property`\n\nL'indirizzo IP su cui il server è in ascolto.\n\nReturns: `String` Predefinito: `CONF.$ip` (`0.0.0.0`)\n\nSalvato in `CONF.$ip`. Il predefinito `0.0.0.0` è in ascolto su tutte le interfacce.\n\nExample: Solo locale\n```js\nF.run({ ip: '127.0.0.1', port: 8000 });\n```\n\n### options.port = Number\n\nType: `property`\n\nLa porta del server.\n\nReturns: `Number` Predefinito: `8000`\n\nSalvata in `CONF.$port`. Senza di essa la porta viene dalla variabile d'ambiente `PORT` o da un argomento numerico del processo (`node index.js 8000`), e il predefinito è `8000`.\n\nExample: Porta dagli argomenti\n```js\nF.run({ port: parseInt(process.argv[2]) || 8000 });\n```\n\n### options.unixsocket = String\n\nType: `property`\n\nResta in ascolto su un socket Unix invece che su una porta.\n\nReturns: `String`\n\nUn file socket esistente viene prima rimosso. Su Windows il percorso viene collocato nello spazio delle named pipe. Salvato in `CONF.$unixsocket`.\n\nExample: Socket\n```js\nF.run({ unixsocket: require('node:path').join(require('node:os').tmpdir(), 'app_name') });\n```\n\n### options.unixsocket777 = Boolean\n\nType: `property`\n\nAssegna al socket Unix i permessi 777.\n\nReturns: `Boolean` Predefinito: `false`\n\nCon `unixsocket`, il file socket riceve `chmod 777` quando viene creato, così un altro utente (per esempio il web server) può connettersi.\n\nExample: Socket per nginx\n```js\nF.run({ unixsocket: '/tmp/app.socket', unixsocket777: true });\n```\n\n### options.config = Object\n\nType: `property`\n\nChiavi di configurazione applicate prima del caricamento dell'applicazione.\n\nReturns: `Object`\n\nOgni chiave viene applicata con `LOADCONFIG()` prima di `LOAD()`. Il file `config` viene letto dopo e può sovrascriverle. Usalo per le chiavi necessarie prima della lettura del file `config`, come `bundling`.\n\nExample: Nome e bundling\n```js\nF.run({ config: { name: 'My app', bundling: 'shallow' } });\n```\n\n### options.load = String\n\nType: `property`\n\nLe parti dell'applicazione che vengono caricate.\n\nReturns: `String` Predefinito: `''`\n\nPassato a `LOAD()`: un elenco separato da virgole come `'config,controllers'`. Vuoto carica tutto; `'none'` avvia solo il web server. `options.type` è un alias.\n\nExample: Server di file statici\n```js\nF.http({ load: 'none', port: 8000 });\n```\n\n### options.watcher = Boolean\n\nType: `property`\n\n`false` avvia la modalità release.\n\nReturns: `Boolean` Predefinito: `true`\n\nCon `F.run()`, `false` esegue l'applicazione in modalità release nel processo corrente; qualsiasi altro valore avvia il watcher di debug. In modalità release l'argomento `--watcher` del processo avvia un watcher di release che riavvia l'applicazione quando termina.\n\nExample: Release\n```js\nF.run({ watcher: false });\n```\n\n### options.release = Boolean\n\nType: `property`\n\nEsegue l'applicazione con `DEBUG = false` sotto il watcher di debug o il cluster.\n\nReturns: `Boolean` Predefinito: `false`\n\nIn modalità debug il watcher riavvia comunque l'applicazione in caso di modifiche, ma l'applicazione gira con `DEBUG = false`. Con `cluster` avvia i thread in modalità release senza il watcher.\n\nExample: Cluster in release\n```js\nF.run({ cluster: 4, release: true });\n```\n\n### options.servicemode = Boolean|String\n\nType: `property`\n\nCarica l'applicazione senza il server HTTP.\n\nReturns: `Boolean|String`\n\n`true` carica tutto, una stringa carica le parti elencate (i nomi di `LOAD()`), per esempio `'config,modules,actions'`.\n\nExample: Processo worker\n```js\nF.run({ servicemode: 'config,modules,actions' });\n```\n\n### options.watch = Array\n\nType: `property`\n\nCartelle aggiuntive per il watcher di debug.\n\nReturns: `Array`\n\nPercorsi relativi alla root dell'applicazione. Una barra iniziale e una finale vengono rimosse.\n\nExample: Osservare una cartella\n```js\nF.run({ watch: ['adminer', '/libs/'] });\n```\n\n### options.livereload = String\n\nType: `property`\n\nInvia i file modificati al servizio di live reload di Total.js.\n\nReturns: `String`\n\nL'hostname della tua applicazione (`http://` e `https://` vengono rimossi). Il watcher di debug si collega a `wss://livereload.totaljs.com/?hostname=<hostname>` e invia il nome di ogni file `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` o `.resource` modificato, compresi i file in `public` e `views` (gli altri file delle cartelle non vengono osservati); le modifiche in `public` e `views` non riavviano l'applicazione.\n\nExample: Live reload\n```js\nF.run({ livereload: 'myapp.example.com' });\n```\n\n### options.inspector = Number\n\nType: `property`\n\nAvvia il processo dell'applicazione con l'inspector di Node.js.\n\nReturns: `Number` Predefinito: `9229`\n\nIl watcher di debug aggiunge `--inspect=<port>` agli argomenti Node.js dell'applicazione. Lo stesso accade quando il watcher stesso è stato avviato con `--inspect`, con la porta `9229`.\n\nExample: Inspector\n```js\nF.run({ inspector: 9229 });\n```\n\n### options.debugger = Number\n\nType: `property`\n\nAvvia il processo dell'applicazione con `--debug=<port>`.\n\nReturns: `Number` Predefinito: `40894`\n\nIl watcher di debug aggiunge `--debug=<port>` agli argomenti Node.js dell'applicazione. Lo stesso accade quando il watcher è stato avviato con `--debug`, con la porta `40894`.\n\nExample: Debugger\n```js\nF.run({ debugger: 40894 });\n```\n\n### options.cluster = Number|String\n\nType: `property`\n\nEsegue l'applicazione in più thread del cluster.\n\nReturns: `Number|String`\n\nUn numero di thread, oppure `'auto'`: parte con un thread e aggiunge un thread quando la latenza media dei thread supera i 70 ms, fino a `options.limit`. In modalità debug il watcher riavvia tutti i thread dopo una modifica; con `release: true` non c'è watcher. Ogni thread carica l'intera applicazione.\n\nExample: Quattro thread\n```js\nF.run({ cluster: 4, port: 8000 });\n```\n\nExample: Automatico\n```js\nF.run({ cluster: 'auto', limit: 8, release: true });\n```\n\n### options.limit = Number\n\nType: `property`\n\nIl numero massimo di thread per `cluster: 'auto'`.\n\nReturns: `Number`\n\nSenza di esso, il cluster automatico aggiunge thread senza limite.\n\nExample: Limite\n```js\nF.run({ cluster: 'auto', limit: 4 });\n```\n\n### options.edit = String\n\nType: `property`\n\nConnette l'applicazione al Total.js Code Editor.\n\nReturns: `String`\n\nL'URL fornito dall'editor (`wss://...?id=project`; `http` viene cambiato in `ws`). Il client gira nel watcher di debug, o nel watcher di release avviato con `--watcher`, e avvia l'applicazione un secondo dopo.\n\nExample: Modifica remota\n```js\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\n### options.editmcp = String\n\nType: `property`\n\nCollega l'applicazione a un proxy di modifica MCP, così un agente di IA può lavorare sui suoi file.\n\nReturns: `String`\n\nL'URL della route WebSocket del proxy con l'id del progetto (`wss://proxy.example.com/$mcp/?id=myproject`; `http` viene cambiato in `ws`). Il client gira nel watcher (quindi non con `watcher: false`), si riconnette ogni 10 secondi e avvia l'applicazione un secondo dopo. Quando è impostato anche `edit`, viene usato `edit`.\n\nIl proxy è un'altra applicazione Total.js con `$mcp : true` che passa la sua route WebSocket a `require('total5/edit-mcp').proxy()`. Il suo endpoint MCP `/$mcp/?id=myproject` elenca i tool `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` e `App_restart` e li esegue nell'applicazione collegata con l'id `myproject`; senza un'applicazione collegata i tool rispondono `App is offline.`. I percorsi sono relativi alla radice dell'applicazione, con o senza la `/` iniziale. `App_write` salva ogni contenuto scritto come revisione numerata nella cartella `revisions/` dell'applicazione, `App_read` restituisce il numero della revisione attuale e `App_restore` il contenuto di una revisione, `App_move` sposta le revisioni insieme ai file e `App_delete` le rimuove (`/` non si può eliminare). `App_shell` esegue qualsiasi comando di shell nella cartella dell'applicazione, quindi proteggi il proxy con `Total.mcp.auth`.\n\nExample: L'applicazione\n```js\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nExample: Il proxy\n```js\n// config: $mcp : true\nconst editmcp = require('total5/edit-mcp');\n\nROUTE('SOCKET /$mcp/', function($) {\n\teditmcp.proxy($);\n});\n\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_token)\n\t\t$.success({ id: 'agent', name: 'Agent', sa: true });\n\telse\n\t\t$.invalid();\n};\n\n// the AI client connects to https://proxy.example.com/$mcp/?id=myproject\n```\n\n### bundling : shallow\n\nType: `config`\n\n`shallow` riutilizza la cartella `.src` estratta invece di ricostruirla.\n\nReturns: `String`\n\nQuando è `shallow` ed esiste `.src/bundle.json`, i bundle non vengono estratti e i file non vengono copiati; l'applicazione gira dalla `.src` esistente. I bundle vengono elaborati prima della lettura del file `config`, quindi imposta la chiave in `options.config`.\n\nExample: Bundling shallow\n```js\nF.run({ watcher: false, config: { bundling: 'shallow' } });\n```\n","entries":[{"type":"method","name":"F.run()","signature":"F.run([options])","since":"","deprecated":false},{"type":"method","name":"F.http()","signature":"F.http([options])","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [callback], [clear])","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"F.directory","signature":"F.directory","since":"","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"method","name":"F.dir()","signature":"F.dir([directory])","since":"","deprecated":false},{"type":"method","name":"F.restart()","signature":"F.restart()","since":"","deprecated":false},{"type":"method","name":"F.exit()","signature":"F.exit([signal])","since":"","deprecated":false},{"type":"method","name":"F.console()","signature":"F.console()","since":"","deprecated":false},{"type":"method","name":"F.remote()","signature":"F.remote(url, [directory])","since":"","deprecated":false},{"type":"property","name":"F.consumption","signature":"F.consumption","since":"","deprecated":false},{"type":"property","name":"F.stats","signature":"F.stats","since":"","deprecated":false},{"type":"event","name":"ON('$watcher')","signature":"ON('$watcher', function(child) {})","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(child) {})","since":"","deprecated":false},{"type":"property","name":"options.ip","signature":"options.ip = String","since":"","deprecated":false},{"type":"property","name":"options.port","signature":"options.port = Number","since":"","deprecated":false},{"type":"property","name":"options.unixsocket","signature":"options.unixsocket = String","since":"","deprecated":false},{"type":"property","name":"options.unixsocket777","signature":"options.unixsocket777 = Boolean","since":"","deprecated":false},{"type":"property","name":"options.config","signature":"options.config = Object","since":"","deprecated":false},{"type":"property","name":"options.load","signature":"options.load = String","since":"","deprecated":false},{"type":"property","name":"options.watcher","signature":"options.watcher = Boolean","since":"","deprecated":false},{"type":"property","name":"options.release","signature":"options.release = Boolean","since":"","deprecated":false},{"type":"property","name":"options.servicemode","signature":"options.servicemode = Boolean|String","since":"","deprecated":false},{"type":"property","name":"options.watch","signature":"options.watch = Array","since":"","deprecated":false},{"type":"property","name":"options.livereload","signature":"options.livereload = String","since":"","deprecated":false},{"type":"property","name":"options.inspector","signature":"options.inspector = Number","since":"","deprecated":false},{"type":"property","name":"options.debugger","signature":"options.debugger = Number","since":"","deprecated":false},{"type":"property","name":"options.cluster","signature":"options.cluster = Number|String","since":"","deprecated":false},{"type":"property","name":"options.limit","signature":"options.limit = Number","since":"","deprecated":false},{"type":"property","name":"options.edit","signature":"options.edit = String","since":"","deprecated":false},{"type":"property","name":"options.editmcp","signature":"options.editmcp = String","since":"","deprecated":false},{"type":"config","name":"bundling","signature":"bundling : shallow","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafwuo6Px60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/application-structure/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Štruktúra aplikácie a režimy","summary":"F.run() a jeho štartovacie voľby, LOAD(), IMPORT(), REQUIRE(), MODS a štatistiky frameworku.","markdown":"---\ntitle: \"Štruktúra aplikácie a režimy\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/application-structure/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Štruktúra aplikácie a režimy\n\n> F.run() a jeho štartovacie voľby, LOAD(), IMPORT(), REQUIRE(), MODS a štatistiky frameworku.\n\nFunkcie, ktoré spúšťajú a načítavajú aplikáciu Total.js 5: `F.run()` so všetkými štartovacími voľbami, `F.http()`, `LOAD()`, `IMPORT()`, `REQUIRE()`, `MODS`, `F.restart()`, `F.exit()`, štatistiky v `F.stats` a `F.consumption`, udalosti watchera a kľúč `bundling`.\n\nNávod [Štruktúra aplikácie a režimy](../../guides/application-structure/) vysvetľuje priečinky, poradie načítania, režim debug a release, bundly a vzdialenú úpravu.\n\nSpúšťač `Test` má vlastnú stránku: [Unit testy](../unit-tests/).\n\n## API\n\n### F.run([options])\n\nType: `method`\n\nSpustí aplikáciu v režime debug s watcherom alebo v režime release.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Štartovacie voľby: `ip`, `port`, `unixsocket`, `config`, `load`, `watcher`, `release`, `servicemode`, `watch`, `livereload`, `inspector`, `debugger`, `cluster`, `limit`, `edit`, `editmcp`. |\n\nReturns: `undefined`\n\nZvyčajný posledný riadok štartovacieho skriptu. Bez `options.watcher = false` spustí debug watcher (`debug.js`): aplikácia beží v podriadenom procese a reštartuje sa, keď sa zmení súbor. S `watcher: false` spustí režim release (`release.js`): aplikácia beží v tom istom procese s `DEBUG = false`. Voľby sa v procese aplikácie odovzdajú do `F.http()` (alebo do `LOAD()` v servisnom režime). `Total.run()` je tá istá funkcia.\n\nExample: Režim debug\n```js\nrequire('total5');\nF.run({ port: 8000 });\n```\n\nExample: Režim release\n```js\nrequire('total5');\nF.run({ watcher: false, port: 8000 });\n```\n\nExample: Režim z príkazového riadku\n```js\nrequire('total5');\n\nvar options = {};\noptions.port = 8000;\n\nif (process.argv.includes('--release'))\n\toptions.watcher = false;\n\nF.run(options);\n```\n\n### F.http([options])\n\nType: `method`\n\nNačíta aplikáciu a spustí HTTP server v aktuálnom procese.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | `ip`, `port`, `unixsocket`, `unixsocket777`, `config`, `load` (alias `type`) a `clear`. |\n\nReturns: `undefined`\n\nPoužije `options.config` pomocou `LOADCONFIG()`, zavolá `LOAD()` s `options.load` a potom spustí server. Keď je aplikácia už načítaná, len (znova) spustí server; bežiaci server sa najprv zatvorí. S predvoleným `CONF.$port = 'auto'` sa port vezme z `options.port`, potom z premennej prostredia `PORT`, potom z prvého argumentu procesu s 3 až 5 číslicami (`node index.js 8000`) a predvolená hodnota je `8000`. Keď proces nemá rodiča, vypíše štartovacie informácie.\n\n`F.run()` ju zavolá za teba; priamo ju volaj v skriptoch, ktoré spúšťajú server bez watchera (testy, nástroje).\n\nExample: Server pre testy\n```js\nrequire('total5');\nF.http({ port: 8001, config: { name: 'Test' } });\n```\n\n### LOAD([types], [callback], [clear])\n\nType: `method`\n\nNačíta konfiguráciu, resources a súbory JavaScript aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no | `''` | Časti na načítanie ako reťazec oddelený čiarkami alebo pole; prázdne načíta všetko. |\n| `callback` | `Function` | no |  | `function()` zavolaná, keď je všetko načítané. |\n| `clear` | `Boolean` | no | `true` | Vyprázdni dočasný priečinok pred načítaním. |\n\nReturns: `Promise` Splní sa, keď je všetko načítané.\n\n`F.load()` je tá istá funkcia. Nastaví adresáre, zostaví bundly, odstráni súbory `.js`, `.css`, `.html`, `.htm`, `.tmp` a `.upload` z dočasného priečinka (keď je `clear` `true`) a potom načíta časti v poradí podľa návodu. Bez `types` načíta všetko. Názvy sú `env`, `config`, `version`, `resources`, `jsonschemas`, `extensions`, `modules`, `actions`, `schemas`, `models`, `definitions`, `controllers`, `middleware`, `plugins`, `flowstreams` a `stats`; akýkoľvek iný názov, napríklad `none`, nenačíta nič. Keď je `types` zadané bez `stats`, štatistiky a source mapy sa vypnú.\n\nNa konci spustí servisný časovač, nastaví `F.isLoaded`, `F.stats.compiled` a `F.stats.compilation`, zavolá `callback` a vyšle `ready` a `load`. HTTP server nespúšťa.\n\nExample: Proces na pozadí\n```js\nrequire('total5');\n\nLOAD('config,modules,actions', function() {\n\tACTION('Jobs/run').callback(console.log);\n});\n```\n\nExample: S await\n```js\nrequire('total5');\n\n(async function() {\n\tawait LOAD('env,config');\n\tconsole.log(CONF.name);\n})();\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nStiahne súbor JavaScript a načíta ho ako modul.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL súboru `.js`. |\n| `callback` | `Function` | no |  | `function(err, module, response)` |\n\nReturns: `Promise` Keď `callback` nie je nastavený.\n\nSúbor sa stiahne do dočasného priečinka a načíta pomocou `require()`. Ďalšie volania s tou istou URL v tom istom procese vrátia načítaný modul bez opätovného sťahovania. Odpoveď so stavom `400` alebo vyšším vráti chybu `The address answered with the status <status>` a nič sa nenačíta. Súbor, ktorý nie je platný modul, vráti chybu z `require()`, napríklad `SyntaxError`. Callback dostane `(err, module, response)`; bez callbacku funkcia vráti Promise s modulom.\n\nExample: Promise\n```js\nvar helpers = await IMPORT('https://cdn.example.com/helpers.js');\nhelpers.hello();\n```\n\nExample: Callback\n```js\nIMPORT('https://cdn.example.com/helpers.js', function(err, helpers) {\n\tif (err)\n\t\tconsole.error(err);\n\telse\n\t\thelpers.hello();\n});\n```\n\n### REQUIRE(name)\n\nType: `method`\n\nNačíta modul Node.js alebo balík NPM.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov modulu alebo balíka. |\n\nReturns: `Object` Modul.\n\nNázvy s prefixom `node:` a vstavané moduly Node.js (`fs`, `path`, `crypto`, ...) sa načítajú priamo. Ostatné názvy sa načítajú pomocou `require()` a keď to zlyhá, z priečinka v `CONF.$nodemodules` (predvolene `<application>/node_modules`), takže sa nájdu aj balíky nainštalované pomocou `NPMINSTALL()`. Keď sa modul nedá načítať, vyhodí chybu.\n\nExample: Načítanie\n```js\nvar Fs = REQUIRE('fs');\nvar mqtt = REQUIRE('mqtt');\n```\n\n### MODS\n\nType: `property`\n\nNačítané moduly z priečinka `modules` podľa ich id.\n\nReturns: `Object`\n\nTen istý objekt ako `F.modules`. Každý súbor v `modules` sa zaregistruje pod svojím `exports.id`, alebo pod názvom súboru bez `.js`, keď `id` chýba, ešte pred zavolaním jeho `install()`. Použi ho na volanie funkcií, ktoré modul exportuje.\n\nExample: Volanie modulu\n```js\n// modules/counter.js\nexports.id = 'counter';\n\nvar count = 0;\n\nexports.increment = function() {\n\treturn ++count;\n};\n\n// a controller or an action\nMODS.counter.increment();\n```\n\n### F.isLoaded\n\nType: `property`\n\n`true`, keď je aplikácia načítaná.\n\nReturns: `Boolean`\n\nNastavuje ho `LOAD()` po načítaní všetkých súborov, tesne pred udalosťami `ready` a `load`.\n\nExample: Kontrola\n```js\nif (F.isLoaded)\n\tconsole.log('Ready');\n```\n\n### F.directory\n\nType: `property`\n\nKoreňový priečinok aplikácie.\n\nReturns: `String`\n\nAktuálny pracovný adresár procesu v čase načítania `total5`. Keď aplikácia beží z bundlov, ukazuje na priečinok `.src`. Odtiaľto začínajú všetky cesty `PATH.root()`.\n\nExample: Čítanie\n```js\nconsole.log(F.directory);\nconsole.log(PATH.root('config'));\n```\n\n### F.isBundle\n\nType: `property`\n\n`true`, keď aplikácia beží z bundlov.\n\nReturns: `Boolean`\n\nNastaví sa, keď priečinok `bundles` obsahuje bundly (alebo existuje `bundles.debug`) a aplikácia bola zostavená do `.src`.\n\nExample: Kontrola\n```js\nif (F.isBundle)\n\tconsole.log('Running from', F.directory);\n```\n\n### F.dir([directory])\n\nType: `method`\n\nNastaví koreňový priečinok a znova vypočíta priečinky aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no |  | Nový koreňový priečinok. |\n\nReturns: `undefined`\n\nS `directory` zmení `F.directory`. Potom nastaví cesty v `F.temporary.directories` pre `public`, `tmp`, `logs`, `databases`, `controllers`, `resources`, `plugins`, `modules`, `views`, `definitions`, `schemas`, `models`, `flowstreams`, `bundles`, `actions`, `extensions`, `source`, `services`, `updates`, `templates`, `private` a `scripts`: každá je hodnotou `CONF.$dir<name>`, keď je nastavená, inak `<root>/<name>`. `LOAD()` ju volá na začiatku.\n\nExample: Čítanie priečinka\n```js\nF.dir();\nconsole.log(F.temporary.directories.public);\n```\n\n### F.restart()\n\nType: `method`\n\nPožiada watcher o reštart aplikácie.\n\nReturns: `undefined`\n\nPošle `total:restart` rodičovskému procesu. Debug watcher a release watcher spustený s `--watcher` vypíšu `RES` a znova spustia aplikáciu. Bez watchera sa nestane nič.\n\nExample: Po aktualizácii\n```js\nNEWACTION('Settings/save', {\n\tinput: '*name:String',\n\taction: function($, model) {\n\t\tF.Fs.writeFile(PATH.root('config'), 'name : ' + model.name, function() {\n\t\t\t$.success();\n\t\t\tF.restart();\n\t\t});\n\t}\n});\n```\n\n### F.exit([signal])\n\nType: `method`\n\nZastaví aplikáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number` | no | `15` | Signál pre podriadené procesy. |\n\nReturns: `undefined`\n\nUkončí workery a Python pipeliny signálom `signal`, zruší inštancie FlowStream, vyvolá `exit`, oznámi rodičovskému procesu `total:stop`, zastaví servisný časovač a zatvorí HTTP server. Proces skončí o 300 ms neskôr. Framework ju volá pri `SIGTERM`, `SIGINT` a pri ukončení procesu.\n\nExample: Zastavenie\n```js\nON('exit', function() {\n\tconsole.log('Bye');\n});\n\nF.exit();\n```\n\n### F.console()\n\nType: `method`\n\nVypíše štartovacie informácie.\n\nReturns: `undefined`\n\nVypíše PID, verzie Node.js a Total.js, systém, pamäť, používateľa, názov, verziu a autora aplikácie, dátum s časovým pásmom, režim (`debug` alebo `release`), počet skompilovaných súborov s časom, cesty ku koreňu, adresáru a `node_modules` a adresu servera. Keď je `CONF.$imprint` `false`, nevypíše sa nič. Framework ju volá po štarte.\n\nExample: Opätovný výpis\n```js\nON('ready', function() {\n\tF.console();\n});\n```\n\n### F.remote(url, [directory])\n\nType: `method`\n\nPripojí priečinok aplikácie k Total.js Code Editoru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL z editora, `wss://...?id=project`. |\n| `directory` | `String` | no | `F.directory` | Priečinok na úpravu. |\n\nReturns: `undefined`\n\nSpustí klienta vzdialenej úpravy v aktuálnom procese: spojenie WebSocket na `url`, ktoré editoru umožní prehliadať a meniť súbory v `directory`. Pri strate spojenia sa pripája znova každých 10 sekúnd. Štartovacia voľba `edit` robí to isté v procese watchera.\n\nExample: Pripojenie\n```js\nF.remote('wss://code.example.com/?id=myproject');\n```\n\n### F.consumption\n\nType: `property`\n\nŠtatistiky využitia procesu, aktualizované raz za minútu.\n\nReturns: `Object`\n\nKaždú minútu ten istý objekt (prvýkrát 5 sekúnd po načítaní aplikácie); dostane ho aj `ON('$stats')` a s `CONF.$stats` sa zapíše do `<script>.json`. Polia: `id`, `pid`, `thread`, `mode` (`debug` alebo `release`), `version` (`node`, `total`, `build`, `app` z `CONF.version`), `app` (`name` a `url` z konfigurácie), `date`, `memory` (použitý heap v MB), `requests`, `pending`, `external`, `errors`, `timeouts`, `online` (WebSocket klienti), `download` a `upload` (MB celkovo), `lasterror`, `lasttimeout`, `usage` (percentá), `overload` (hodiny s vysokou záťažou), `uptime` (minúty od štartu) a počítadlá za minútu `rm`, `fm`, `wm`, `em`, `mm`, `om`, `dm`, `um`, `pm`, `sm`, `cm`, `dbrm` a `dbwm`.\n\nExample: Čítanie\n```js\nsetInterval(function() {\n\tconsole.log(F.consumption.memory, 'MB', F.consumption.requests, 'requests');\n}, 60000);\n```\n\n### F.stats\n\nType: `property`\n\nPočítadlá frameworku za celý život procesu.\n\nReturns: `Object`\n\n`F.stats.request` počíta požiadavky (`request`, `web`, `xhr`, `file`, `websocket`, `get`, `post`, `put`, `patch`, `delete`, `upload`, `mobile`, `desktop`, `blocked`, `pending`, `size` ...), `F.stats.response` počíta odpovede podľa typu (`json`, `html`, `file`, `redirect`, `stream`, `timeout`, `error404`, `error500` ...), `F.stats.performance` obsahuje hodnoty za minútu, `F.stats.error` počet chýb a `F.stats.compiled` a `F.stats.compilation` počet načítaných súborov a čas načítania v ms.\n\nExample: Jednoduchý report\n```js\nROUTE('GET /stats/', function($) {\n\tvar s = F.stats;\n\t$.json({ requests: s.request.request, errors: s.error, notfound: s.response.error404 });\n});\n```\n\n### ON('$watcher', function(child) {})\n\nType: `event`\n\nVyvolá sa v debug watcheri po spustení procesu aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | Proces aplikácie. |\n\nBeží v procese watchera, nie v aplikácii, po každom štarte alebo reštarte. `child` je `ChildProcess` aplikácie. Zaregistruj ju v štartovacom skripte pred `F.run()`.\n\nExample: Zaznamenanie reštartov\n```js\nrequire('total5');\n\nON('$watcher', function(child) {\n\tconsole.log('Application PID:', child.pid);\n});\n\nF.run();\n```\n\n### ON('watcher', function(child) {})\n\nType: `event`\n\nVyvolá sa v release watcheri po spustení procesu aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `child` | `ChildProcess` | yes |  | Proces aplikácie. |\n\nLen v režime release spustenom s `--watcher`. Beží v procese watchera po každom štarte. `child` je `ChildProcess` aplikácie.\n\nExample: Zaznamenanie štartov\n```js\nrequire('total5');\n\nON('watcher', function(child) {\n\tconsole.log('Started PID:', child.pid);\n});\n\nF.run({ watcher: false });\n```\n\n### options.ip = String\n\nType: `property`\n\nIP adresa, na ktorej server počúva.\n\nReturns: `String` Predvolene: `CONF.$ip` (`0.0.0.0`)\n\nUloží sa do `CONF.$ip`. Predvolená hodnota `0.0.0.0` počúva na všetkých rozhraniach.\n\nExample: Len lokálne\n```js\nF.run({ ip: '127.0.0.1', port: 8000 });\n```\n\n### options.port = Number\n\nType: `property`\n\nPort servera.\n\nReturns: `Number` Predvolene: `8000`\n\nUloží sa do `CONF.$port`. Bez neho sa port vezme z premennej prostredia `PORT` alebo z číselného argumentu procesu (`node index.js 8000`) a predvolená hodnota je `8000`.\n\nExample: Port z argumentov\n```js\nF.run({ port: parseInt(process.argv[2]) || 8000 });\n```\n\n### options.unixsocket = String\n\nType: `property`\n\nPočúva na Unix sockete namiesto portu.\n\nReturns: `String`\n\nExistujúci súbor socketu sa najprv odstráni. Vo Windows sa cesta umiestni do priestoru pomenovaných rúr (named pipe). Uloží sa do `CONF.$unixsocket`.\n\nExample: Socket\n```js\nF.run({ unixsocket: require('node:path').join(require('node:os').tmpdir(), 'app_name') });\n```\n\n### options.unixsocket777 = Boolean\n\nType: `property`\n\nNastaví Unix socketu oprávnenia 777.\n\nReturns: `Boolean` Predvolene: `false`\n\nS `unixsocket` dostane súbor socketu pri vytvorení `chmod 777`, takže sa k nemu môže pripojiť iný používateľ (napríklad webový server).\n\nExample: Socket pre nginx\n```js\nF.run({ unixsocket: '/tmp/app.socket', unixsocket777: true });\n```\n\n### options.config = Object\n\nType: `property`\n\nKonfiguračné kľúče použité pred načítaním aplikácie.\n\nReturns: `Object`\n\nKaždý kľúč sa použije pomocou `LOADCONFIG()` pred `LOAD()`. Súbor `config` sa načíta neskôr a môže ich prepísať. Použi to pre kľúče, ktoré sú potrebné pred načítaním súboru `config`, napríklad `bundling`.\n\nExample: Názov a bundling\n```js\nF.run({ config: { name: 'My app', bundling: 'shallow' } });\n```\n\n### options.load = String\n\nType: `property`\n\nČasti aplikácie, ktoré sa načítajú.\n\nReturns: `String` Predvolene: `''`\n\nOdovzdá sa do `LOAD()`: zoznam oddelený čiarkami, napríklad `'config,controllers'`. Prázdne načíta všetko; `'none'` spustí len webový server. `options.type` je alias.\n\nExample: Server statických súborov\n```js\nF.http({ load: 'none', port: 8000 });\n```\n\n### options.watcher = Boolean\n\nType: `property`\n\n`false` spustí režim release.\n\nReturns: `Boolean` Predvolene: `true`\n\nS `F.run()` spustí `false` aplikáciu v režime release v aktuálnom procese; akákoľvek iná hodnota spustí debug watcher. V režime release spustí argument procesu `--watcher` release watcher, ktorý reštartuje aplikáciu, keď skončí.\n\nExample: Release\n```js\nF.run({ watcher: false });\n```\n\n### options.release = Boolean\n\nType: `property`\n\nSpustí aplikáciu s `DEBUG = false` pod debug watcherom alebo clusterom.\n\nReturns: `Boolean` Predvolene: `false`\n\nV režime debug watcher stále reštartuje aplikáciu pri zmenách, ale aplikácia beží s `DEBUG = false`. S `cluster` spustí vlákna v režime release bez watchera.\n\nExample: Release cluster\n```js\nF.run({ cluster: 4, release: true });\n```\n\n### options.servicemode = Boolean|String\n\nType: `property`\n\nNačíta aplikáciu bez HTTP servera.\n\nReturns: `Boolean|String`\n\n`true` načíta všetko, reťazec načíta uvedené časti (názvy z `LOAD()`), napríklad `'config,modules,actions'`.\n\nExample: Proces workera\n```js\nF.run({ servicemode: 'config,modules,actions' });\n```\n\n### options.watch = Array\n\nType: `property`\n\nĎalšie priečinky pre debug watcher.\n\nReturns: `Array`\n\nCesty relatívne ku koreňu aplikácie. Úvodná a koncová lomka sa odstránia.\n\nExample: Sledovanie priečinka\n```js\nF.run({ watch: ['adminer', '/libs/'] });\n```\n\n### options.livereload = String\n\nType: `property`\n\nPosiela zmenené súbory do služby live reload Total.js.\n\nReturns: `String`\n\nHostname tvojej aplikácie (`http://` a `https://` sa odstránia). Debug watcher sa pripojí na `wss://livereload.totaljs.com/?hostname=<hostname>` a pošle názov každého zmeneného súboru `.js`, `.ts`, `.py`, `.css`, `.html`, `.htm`, `.jpg`, `.png`, `.gif`, `.ico`, `.svg`, `.webp` alebo `.resource`, vrátane súborov v `public` a `views` (ostatné súbory v priečinkoch sa nesledujú); zmeny v `public` a `views` aplikáciu nereštartujú.\n\nExample: Live reload\n```js\nF.run({ livereload: 'myapp.example.com' });\n```\n\n### options.inspector = Number\n\nType: `property`\n\nSpustí proces aplikácie s inšpektorom Node.js.\n\nReturns: `Number` Predvolene: `9229`\n\nDebug watcher pridá `--inspect=<port>` k argumentom Node.js aplikácie. To isté sa stane, keď bol samotný watcher spustený s `--inspect`, s portom `9229`.\n\nExample: Inšpektor\n```js\nF.run({ inspector: 9229 });\n```\n\n### options.debugger = Number\n\nType: `property`\n\nSpustí proces aplikácie s `--debug=<port>`.\n\nReturns: `Number` Predvolene: `40894`\n\nDebug watcher pridá `--debug=<port>` k argumentom Node.js aplikácie. To isté sa stane, keď bol watcher spustený s `--debug`, s portom `40894`.\n\nExample: Debugger\n```js\nF.run({ debugger: 40894 });\n```\n\n### options.cluster = Number|String\n\nType: `property`\n\nSpustí aplikáciu vo viacerých vláknach clustera.\n\nReturns: `Number|String`\n\nPočet vlákien, alebo `'auto'`: začne s jedným vláknom a pridá vlákno, keď je priemerná latencia vlákien nad 70 ms, až po `options.limit`. V režime debug watcher po zmene reštartuje všetky vlákna; s `release: true` watcher nie je. Každé vlákno načíta celú aplikáciu.\n\nExample: Štyri vlákna\n```js\nF.run({ cluster: 4, port: 8000 });\n```\n\nExample: Automaticky\n```js\nF.run({ cluster: 'auto', limit: 8, release: true });\n```\n\n### options.limit = Number\n\nType: `property`\n\nMaximálny počet vlákien pre `cluster: 'auto'`.\n\nReturns: `Number`\n\nBez neho automatický cluster pridáva vlákna bez obmedzenia.\n\nExample: Limit\n```js\nF.run({ cluster: 'auto', limit: 4 });\n```\n\n### options.edit = String\n\nType: `property`\n\nPripojí aplikáciu k Total.js Code Editoru.\n\nReturns: `String`\n\nURL z editora (`wss://...?id=project`; `http` sa zmení na `ws`). Klient beží v debug watcheri alebo v release watcheri spustenom s `--watcher` a aplikáciu spustí o sekundu neskôr.\n\nExample: Vzdialená úprava\n```js\nF.run({ edit: 'wss://code.example.com/?id=myproject' });\n```\n\n### options.editmcp = String\n\nType: `property`\n\nPripojí aplikáciu k MCP edit proxy, aby AI agent mohol pracovať s jej súbormi.\n\nReturns: `String`\n\nURL WebSocket trasy proxy s id projektu (`wss://proxy.example.com/$mcp/?id=myproject`; `http` sa zmení na `ws`). Klient beží vo watcheri (takže nie s `watcher: false`), pripája sa znova každých 10 sekúnd a aplikáciu spustí o sekundu neskôr. Keď je nastavené aj `edit`, použije sa `edit`.\n\nProxy je ďalšia Total.js aplikácia s `$mcp : true`, ktorá odovzdá svoju WebSocket trasu do `require('total5/edit-mcp').proxy()`. Jej MCP endpoint `/$mcp/?id=myproject` vypíše nástroje `App_info`, `App_tree`, `App_read`, `App_write`, `App_delete`, `App_restore`, `App_move`, `App_mkdir`, `App_search`, `App_logs`, `App_shell` a `App_restart` a spúšťa ich v pripojenej aplikácii s id `myproject`; bez pripojenej aplikácie nástroje odpovedia `App is offline.`. Cesty sú relatívne ku koreňu aplikácie, s úvodným `/` aj bez neho. `App_write` uloží každý zapísaný obsah ako očíslovanú revíziu v priečinku `revisions/` aplikácie, `App_read` vráti číslo aktuálnej revízie a `App_restore` obsah revízie, `App_move` presúva revízie spolu so súbormi a `App_delete` ich odstráni (`/` sa vymazať nedá). `App_shell` spustí ľubovoľný shell príkaz v priečinku aplikácie, preto proxy chráň cez `Total.mcp.auth`.\n\nExample: Aplikácia\n```js\nF.run({ editmcp: 'wss://proxy.example.com/$mcp/?id=myproject' });\n```\n\nExample: Proxy\n```js\n// config: $mcp : true\nconst editmcp = require('total5/edit-mcp');\n\nROUTE('SOCKET /$mcp/', function($) {\n\teditmcp.proxy($);\n});\n\nTotal.mcp.auth = function($) {\n\tif ($.token === CONF.mcp_token)\n\t\t$.success({ id: 'agent', name: 'Agent', sa: true });\n\telse\n\t\t$.invalid();\n};\n\n// the AI client connects to https://proxy.example.com/$mcp/?id=myproject\n```\n\n### bundling : shallow\n\nType: `config`\n\n`shallow` znova použije rozbalený priečinok `.src` namiesto jeho opätovného zostavenia.\n\nReturns: `String`\n\nKeď je nastavený na `shallow` a existuje `.src/bundle.json`, bundly sa nerozbaľujú a súbory sa nekopírujú; aplikácia beží z existujúceho `.src`. Bundly sa spracujú pred načítaním súboru `config`, preto kľúč nastav v `options.config`.\n\nExample: Shallow bundling\n```js\nF.run({ watcher: false, config: { bundling: 'shallow' } });\n```\n","entries":[{"type":"method","name":"F.run()","signature":"F.run([options])","since":"","deprecated":false},{"type":"method","name":"F.http()","signature":"F.http([options])","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [callback], [clear])","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"F.directory","signature":"F.directory","since":"","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"method","name":"F.dir()","signature":"F.dir([directory])","since":"","deprecated":false},{"type":"method","name":"F.restart()","signature":"F.restart()","since":"","deprecated":false},{"type":"method","name":"F.exit()","signature":"F.exit([signal])","since":"","deprecated":false},{"type":"method","name":"F.console()","signature":"F.console()","since":"","deprecated":false},{"type":"method","name":"F.remote()","signature":"F.remote(url, [directory])","since":"","deprecated":false},{"type":"property","name":"F.consumption","signature":"F.consumption","since":"","deprecated":false},{"type":"property","name":"F.stats","signature":"F.stats","since":"","deprecated":false},{"type":"event","name":"ON('$watcher')","signature":"ON('$watcher', function(child) {})","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(child) {})","since":"","deprecated":false},{"type":"property","name":"options.ip","signature":"options.ip = String","since":"","deprecated":false},{"type":"property","name":"options.port","signature":"options.port = Number","since":"","deprecated":false},{"type":"property","name":"options.unixsocket","signature":"options.unixsocket = String","since":"","deprecated":false},{"type":"property","name":"options.unixsocket777","signature":"options.unixsocket777 = Boolean","since":"","deprecated":false},{"type":"property","name":"options.config","signature":"options.config = Object","since":"","deprecated":false},{"type":"property","name":"options.load","signature":"options.load = String","since":"","deprecated":false},{"type":"property","name":"options.watcher","signature":"options.watcher = Boolean","since":"","deprecated":false},{"type":"property","name":"options.release","signature":"options.release = Boolean","since":"","deprecated":false},{"type":"property","name":"options.servicemode","signature":"options.servicemode = Boolean|String","since":"","deprecated":false},{"type":"property","name":"options.watch","signature":"options.watch = Array","since":"","deprecated":false},{"type":"property","name":"options.livereload","signature":"options.livereload = String","since":"","deprecated":false},{"type":"property","name":"options.inspector","signature":"options.inspector = Number","since":"","deprecated":false},{"type":"property","name":"options.debugger","signature":"options.debugger = Number","since":"","deprecated":false},{"type":"property","name":"options.cluster","signature":"options.cluster = Number|String","since":"","deprecated":false},{"type":"property","name":"options.limit","signature":"options.limit = Number","since":"","deprecated":false},{"type":"property","name":"options.edit","signature":"options.edit = String","since":"","deprecated":false},{"type":"property","name":"options.editmcp","signature":"options.editmcp = String","since":"","deprecated":false},{"type":"config","name":"bundling","signature":"bundling : shallow","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwU09Ax61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Unit tests","summary":"The Test runner of total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count and Test.items.","markdown":"---\ntitle: Unit tests\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/unit-tests/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Unit tests\n\n> The Test runner of total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count and Test.items.\n\nThe `Test` runner from `total5/test`. The guide [Unit tests](../../guides/unit-tests/) explains how to use it with examples.\n\n## API\n\n### Test\n\nType: `class`\n\nThe global test runner created by `require('total5/test')`.\n\nReturns: `Object`\n\nLoads `total5` when it is not loaded and creates the global `Test` object with `push()`, `run()`, `print()`, `start()`, `fake()`, `restore()`, `count` and `items`. Run the test file with `node`, or the test scripts of a project with `total5 test` (see [Command line](../../reference/command-line/)).\n\nExample: Load\n```js\nrequire('total5/test');\n\nTest.push('Numbers', function(next) {\n\tTest.print('sum', 1 + 1 === 2 ? null : 'Wrong sum');\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.push(name, fn)\n\nType: `method`\n\nAdds a group of tests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name printed as the header of the group. |\n| `fn` | `Function` | yes |  | `function(next)` |\n\nReturns: `undefined`\n\nThe groups run in the order they were added. `fn` gets `next` and must call it when the group is done, also after asynchronous checks.\n\nExample: Async group\n```js\nTest.push('Download', function(next) {\n\tRESTBuilder.GET('https://www.example.com').callback(function(err) {\n\t\tTest.print('GET', err);\n\t\tnext();\n\t});\n});\n```\n\n### Test.run([callback])\n\nType: `method`\n\nRuns all groups one by one.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function()` called instead of ending the process. |\n\nReturns: `undefined`\n\nPrints the header of each group, then the number of checks and the time. Without `callback` the process ends with exit code 0 when all groups are done.\n\nExample: Run and stop the server\n```js\nTest.run(function() {\n\tF.exit();\n});\n```\n\n### Test.print(message, [err])\n\nType: `method`\n\nPrints the result of one check.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | The name of the check. |\n| `err` | `Error|String` | no |  | The reason of a failure. |\n\nReturns: `undefined`\n\nWithout `err` (or with a falsy value) it prints `[OK] message` and counts the check. With `err` it prints `[FAIL] message`, throws the error (a string becomes an `Error`) and ends the process with exit code 1.\n\nExample: Check a value\n```js\nvar value = 'Total.js'.slug();\nTest.print('slug()', value === 'total-js' ? null : 'Unexpected: ' + value);\n```\n\n### Test.start(message)\n\nType: `method`\n\nPrints a header between two divider lines.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | The text of the header. |\n\nReturns: `undefined`\n\n`Test.run()` calls it with the name of each group. Call it yourself to separate parts of a long group.\n\nExample: Header\n```js\nTest.start('Second part');\n```\n\n### Test.fake(name, action)\n\nType: `method`\n\nReplaces an action with a fake.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the action. |\n| `action` | `Object` | yes |  | The definition of the fake, the same object as in `NEWACTION()`. |\n\nReturns: `Object` The registered fake action.\n\nKeeps the action `name` aside (only the first time until `Test.restore()`) and registers `action` under the same name with `NEWACTION()`. Calls of `ACTION(name)` then run the fake. It also works for a name that has no action.\n\nExample: Fake and restore\n```js\nNEWACTION('Users/read', {\n\taction: $ => $.callback('real')\n});\n\nTest.push('Fake', async function(next) {\n\tTest.fake('Users/read', { action: $ => $.callback('fake') });\n\tvar value = await ACTION('Users/read').promise();\n\tTest.print('fake', value === 'fake' ? null : 'Unexpected: ' + value);\n\tTest.restore();\n\tvalue = await ACTION('Users/read').promise();\n\tTest.print('restore', value === 'real' ? null : 'Unexpected: ' + value);\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.count\n\nType: `property`\n\nThe number of checks printed by `Test.print()`.\n\nReturns: `Number`\n\n`Test.run()` prints it at the end as `Tests: <count>`.\n\nExample: Read\n```js\nTest.run(function() {\n\tconsole.log('Checks:', Test.count);\n\tprocess.exit(0);\n});\n```\n\n### Test.restore()\n\nType: `method`\n\nPuts the original actions back.\n\nReturns: `undefined`\n\nRemoves every fake registered with `Test.fake()` and puts the original actions back. A fake of a name that had no action is only removed.\n\nExample: After a group\n```js\nTest.push('Payments', function(next) {\n\tTest.fake('Payments/charge', { action: $ => $.callback({ paid: true }) });\n\t// ... the checks\n\tTest.restore();\n\tnext();\n});\n```\n\n### Test.items\n\nType: `property`\n\nThe groups added with `Test.push()`.\n\nReturns: `Array`\n\nAn array of `{ name, fn }` objects. `Test.run()` runs them one by one; the array keeps them.\n\nExample: Count groups\n```js\nconsole.log(Test.items.length, 'groups');\n```\n","entries":[{"type":"class","name":"Test","signature":"Test","since":"","deprecated":false},{"type":"method","name":"Test.push()","signature":"Test.push(name, fn)","since":"","deprecated":false},{"type":"method","name":"Test.run()","signature":"Test.run([callback])","since":"","deprecated":false},{"type":"method","name":"Test.print()","signature":"Test.print(message, [err])","since":"","deprecated":false},{"type":"method","name":"Test.start()","signature":"Test.start(message)","since":"","deprecated":false},{"type":"method","name":"Test.fake()","signature":"Test.fake(name, action)","since":"","deprecated":false},{"type":"property","name":"Test.count","signature":"Test.count","since":"","deprecated":false},{"type":"method","name":"Test.restore()","signature":"Test.restore()","since":"","deprecated":false},{"type":"property","name":"Test.items","signature":"Test.items","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwU09Ax61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Unit-Tests","summary":"Der Test-Runner von total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count und Test.items.","markdown":"---\ntitle: Unit-Tests\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/unit-tests/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Unit-Tests\n\n> Der Test-Runner von total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count und Test.items.\n\nDer `Test`-Runner aus `total5/test`. Die Anleitung [Unit-Tests](../../guides/unit-tests/) erklärt mit Beispielen, wie du ihn verwendest.\n\n## API\n\n### Test\n\nType: `class`\n\nDer globale Test-Runner, erstellt von `require('total5/test')`.\n\nReturns: `Object`\n\nLädt `total5`, wenn es nicht geladen ist, und erstellt das globale Objekt `Test` mit `push()`, `run()`, `print()`, `start()`, `fake()`, `restore()`, `count` und `items`. Führe die Testdatei mit `node` aus oder die Testskripte eines Projekts mit `total5 test` (siehe [Kommandozeile](../../reference/command-line/)).\n\nExample: Laden\n```js\nrequire('total5/test');\n\nTest.push('Numbers', function(next) {\n\tTest.print('sum', 1 + 1 === 2 ? null : 'Wrong sum');\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.push(name, fn)\n\nType: `method`\n\nFügt eine Gruppe von Tests hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name, der als Überschrift der Gruppe ausgegeben wird. |\n| `fn` | `Function` | yes |  | `function(next)` |\n\nReturns: `undefined`\n\nDie Gruppen laufen in der Reihenfolge, in der sie hinzugefügt wurden. `fn` erhält `next` und muss es aufrufen, wenn die Gruppe fertig ist, auch nach asynchronen Prüfungen.\n\nExample: Asynchrone Gruppe\n```js\nTest.push('Download', function(next) {\n\tRESTBuilder.GET('https://www.example.com').callback(function(err) {\n\t\tTest.print('GET', err);\n\t\tnext();\n\t});\n});\n```\n\n### Test.run([callback])\n\nType: `method`\n\nFührt alle Gruppen nacheinander aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function()`, die statt des Beendens des Prozesses aufgerufen wird. |\n\nReturns: `undefined`\n\nGibt die Überschrift jeder Gruppe aus, danach die Anzahl der Prüfungen und die Zeit. Ohne `callback` endet der Prozess mit dem Exit-Code 0, wenn alle Gruppen fertig sind.\n\nExample: Ausführen und den Server stoppen\n```js\nTest.run(function() {\n\tF.exit();\n});\n```\n\n### Test.print(message, [err])\n\nType: `method`\n\nGibt das Ergebnis einer Prüfung aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Der Name der Prüfung. |\n| `err` | `Error|String` | no |  | Der Grund eines Fehlschlags. |\n\nReturns: `undefined`\n\nOhne `err` (oder mit einem falsy Wert) gibt sie `[OK] message` aus und zählt die Prüfung. Mit `err` gibt sie `[FAIL] message` aus, löst den Fehler aus (ein String wird zu einem `Error`) und beendet den Prozess mit dem Exit-Code 1.\n\nExample: Einen Wert prüfen\n```js\nvar value = 'Total.js'.slug();\nTest.print('slug()', value === 'total-js' ? null : 'Unexpected: ' + value);\n```\n\n### Test.start(message)\n\nType: `method`\n\nGibt eine Überschrift zwischen zwei Trennlinien aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Der Text der Überschrift. |\n\nReturns: `undefined`\n\n`Test.run()` ruft sie mit dem Namen jeder Gruppe auf. Rufe sie selbst auf, um Teile einer langen Gruppe zu trennen.\n\nExample: Überschrift\n```js\nTest.start('Second part');\n```\n\n### Test.fake(name, action)\n\nType: `method`\n\nErsetzt eine Aktion durch einen Fake.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Aktion. |\n| `action` | `Object` | yes |  | Die Definition des Fakes, dasselbe Objekt wie in `NEWACTION()`. |\n\nReturns: `Object` Die registrierte Fake-Aktion.\n\nLegt die Aktion `name` beiseite (nur beim ersten Mal bis `Test.restore()`) und registriert `action` unter demselben Namen mit `NEWACTION()`. Aufrufe von `ACTION(name)` führen dann den Fake aus. Es funktioniert auch für einen Namen, der keine Aktion hat.\n\nExample: Faken und wiederherstellen\n```js\nNEWACTION('Users/read', {\n\taction: $ => $.callback('real')\n});\n\nTest.push('Fake', async function(next) {\n\tTest.fake('Users/read', { action: $ => $.callback('fake') });\n\tvar value = await ACTION('Users/read').promise();\n\tTest.print('fake', value === 'fake' ? null : 'Unexpected: ' + value);\n\tTest.restore();\n\tvalue = await ACTION('Users/read').promise();\n\tTest.print('restore', value === 'real' ? null : 'Unexpected: ' + value);\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.count\n\nType: `property`\n\nDie Anzahl der von `Test.print()` ausgegebenen Prüfungen.\n\nReturns: `Number`\n\n`Test.run()` gibt sie am Ende als `Tests: <count>` aus.\n\nExample: Lesen\n```js\nTest.run(function() {\n\tconsole.log('Checks:', Test.count);\n\tprocess.exit(0);\n});\n```\n\n### Test.restore()\n\nType: `method`\n\nStellt die ursprünglichen Aktionen wieder her.\n\nReturns: `undefined`\n\nEntfernt jeden mit `Test.fake()` registrierten Fake und stellt die ursprünglichen Aktionen wieder her. Ein Fake eines Namens, der keine Aktion hatte, wird nur entfernt.\n\nExample: Nach einer Gruppe\n```js\nTest.push('Payments', function(next) {\n\tTest.fake('Payments/charge', { action: $ => $.callback({ paid: true }) });\n\t// ... the checks\n\tTest.restore();\n\tnext();\n});\n```\n\n### Test.items\n\nType: `property`\n\nDie mit `Test.push()` hinzugefügten Gruppen.\n\nReturns: `Array`\n\nEin Array von `{ name, fn }`-Objekten. `Test.run()` führt sie nacheinander aus; das Array behält sie.\n\nExample: Gruppen zählen\n```js\nconsole.log(Test.items.length, 'groups');\n```\n","entries":[{"type":"class","name":"Test","signature":"Test","since":"","deprecated":false},{"type":"method","name":"Test.push()","signature":"Test.push(name, fn)","since":"","deprecated":false},{"type":"method","name":"Test.run()","signature":"Test.run([callback])","since":"","deprecated":false},{"type":"method","name":"Test.print()","signature":"Test.print(message, [err])","since":"","deprecated":false},{"type":"method","name":"Test.start()","signature":"Test.start(message)","since":"","deprecated":false},{"type":"method","name":"Test.fake()","signature":"Test.fake(name, action)","since":"","deprecated":false},{"type":"property","name":"Test.count","signature":"Test.count","since":"","deprecated":false},{"type":"method","name":"Test.restore()","signature":"Test.restore()","since":"","deprecated":false},{"type":"property","name":"Test.items","signature":"Test.items","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwU09Ax61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Tests unitarios","summary":"El ejecutor Test de total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count y Test.items.","markdown":"---\ntitle: Tests unitarios\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/unit-tests/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Tests unitarios\n\n> El ejecutor Test de total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count y Test.items.\n\nEl ejecutor `Test` de `total5/test`. La guía [Tests unitarios](../../guides/unit-tests/) explica cómo usarlo, con ejemplos.\n\n## API\n\n### Test\n\nType: `class`\n\nEl ejecutor de tests global creado por `require('total5/test')`.\n\nReturns: `Object`\n\nCarga `total5` cuando no está cargado y crea el objeto global `Test` con `push()`, `run()`, `print()`, `start()`, `fake()`, `restore()`, `count` e `items`. Ejecuta el archivo de tests con `node`, o los scripts de test de un proyecto con `total5 test` (consulta [Línea de comandos](../../reference/command-line/)).\n\nExample: Cargar\n```js\nrequire('total5/test');\n\nTest.push('Numbers', function(next) {\n\tTest.print('sum', 1 + 1 === 2 ? null : 'Wrong sum');\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.push(name, fn)\n\nType: `method`\n\nAñade un grupo de tests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre que se imprime como cabecera del grupo. |\n| `fn` | `Function` | yes |  | `function(next)` |\n\nReturns: `undefined`\n\nLos grupos se ejecutan en el orden en que se añadieron. `fn` recibe `next` y debe llamarlo cuando el grupo termina, también después de comprobaciones asíncronas.\n\nExample: Grupo asíncrono\n```js\nTest.push('Download', function(next) {\n\tRESTBuilder.GET('https://www.example.com').callback(function(err) {\n\t\tTest.print('GET', err);\n\t\tnext();\n\t});\n});\n```\n\n### Test.run([callback])\n\nType: `method`\n\nEjecuta todos los grupos uno tras otro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function()` que se llama en lugar de terminar el proceso. |\n\nReturns: `undefined`\n\nImprime la cabecera de cada grupo y luego el número de comprobaciones y el tiempo. Sin `callback`, el proceso termina con el código de salida 0 cuando todos los grupos han terminado.\n\nExample: Ejecutar y detener el servidor\n```js\nTest.run(function() {\n\tF.exit();\n});\n```\n\n### Test.print(message, [err])\n\nType: `method`\n\nImprime el resultado de una comprobación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | El nombre de la comprobación. |\n| `err` | `Error|String` | no |  | El motivo de un fallo. |\n\nReturns: `undefined`\n\nSin `err` (o con un valor falso) imprime `[OK] message` y cuenta la comprobación. Con `err` imprime `[FAIL] message`, lanza el error (una cadena se convierte en un `Error`) y termina el proceso con el código de salida 1.\n\nExample: Comprobar un valor\n```js\nvar value = 'Total.js'.slug();\nTest.print('slug()', value === 'total-js' ? null : 'Unexpected: ' + value);\n```\n\n### Test.start(message)\n\nType: `method`\n\nImprime una cabecera entre dos líneas divisorias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | El texto de la cabecera. |\n\nReturns: `undefined`\n\n`Test.run()` la llama con el nombre de cada grupo. Llámala tú mismo para separar partes de un grupo largo.\n\nExample: Cabecera\n```js\nTest.start('Second part');\n```\n\n### Test.fake(name, action)\n\nType: `method`\n\nSustituye una acción por una falsa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la acción. |\n| `action` | `Object` | yes |  | La definición de la falsa, el mismo objeto que en `NEWACTION()`. |\n\nReturns: `Object` La acción falsa registrada.\n\nGuarda aparte la acción `name` (solo la primera vez hasta `Test.restore()`) y registra `action` con el mismo nombre mediante `NEWACTION()`. Las llamadas a `ACTION(name)` ejecutan entonces la falsa. También funciona con un nombre que no tiene acción.\n\nExample: Falsear y restaurar\n```js\nNEWACTION('Users/read', {\n\taction: $ => $.callback('real')\n});\n\nTest.push('Fake', async function(next) {\n\tTest.fake('Users/read', { action: $ => $.callback('fake') });\n\tvar value = await ACTION('Users/read').promise();\n\tTest.print('fake', value === 'fake' ? null : 'Unexpected: ' + value);\n\tTest.restore();\n\tvalue = await ACTION('Users/read').promise();\n\tTest.print('restore', value === 'real' ? null : 'Unexpected: ' + value);\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.count\n\nType: `property`\n\nEl número de comprobaciones impresas por `Test.print()`.\n\nReturns: `Number`\n\n`Test.run()` lo imprime al final como `Tests: <count>`.\n\nExample: Leer\n```js\nTest.run(function() {\n\tconsole.log('Checks:', Test.count);\n\tprocess.exit(0);\n});\n```\n\n### Test.restore()\n\nType: `method`\n\nVuelve a poner las acciones originales.\n\nReturns: `undefined`\n\nElimina todas las falsas registradas con `Test.fake()` y vuelve a poner las acciones originales. Una falsa de un nombre que no tenía acción solo se elimina.\n\nExample: Después de un grupo\n```js\nTest.push('Payments', function(next) {\n\tTest.fake('Payments/charge', { action: $ => $.callback({ paid: true }) });\n\t// ... the checks\n\tTest.restore();\n\tnext();\n});\n```\n\n### Test.items\n\nType: `property`\n\nLos grupos añadidos con `Test.push()`.\n\nReturns: `Array`\n\nUn array de objetos `{ name, fn }`. `Test.run()` los ejecuta uno a uno; el array los conserva.\n\nExample: Contar grupos\n```js\nconsole.log(Test.items.length, 'groups');\n```\n","entries":[{"type":"class","name":"Test","signature":"Test","since":"","deprecated":false},{"type":"method","name":"Test.push()","signature":"Test.push(name, fn)","since":"","deprecated":false},{"type":"method","name":"Test.run()","signature":"Test.run([callback])","since":"","deprecated":false},{"type":"method","name":"Test.print()","signature":"Test.print(message, [err])","since":"","deprecated":false},{"type":"method","name":"Test.start()","signature":"Test.start(message)","since":"","deprecated":false},{"type":"method","name":"Test.fake()","signature":"Test.fake(name, action)","since":"","deprecated":false},{"type":"property","name":"Test.count","signature":"Test.count","since":"","deprecated":false},{"type":"method","name":"Test.restore()","signature":"Test.restore()","since":"","deprecated":false},{"type":"property","name":"Test.items","signature":"Test.items","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwU09Ax61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Tests unitaires","summary":"L'exécuteur Test de total5/test : Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count et Test.items.","markdown":"---\ntitle: Tests unitaires\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/unit-tests/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Tests unitaires\n\n> L'exécuteur Test de total5/test : Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count et Test.items.\n\nL'exécuteur `Test` de `total5/test`. Le guide [Tests unitaires](../../guides/unit-tests/) explique comment l'utiliser, avec des exemples.\n\n## API\n\n### Test\n\nType: `class`\n\nL'exécuteur de tests global créé par `require('total5/test')`.\n\nReturns: `Object`\n\nCharge `total5` s'il n'est pas chargé et crée l'objet global `Test` avec `push()`, `run()`, `print()`, `start()`, `fake()`, `restore()`, `count` et `items`. Exécute le fichier de test avec `node`, ou les scripts de test d'un projet avec `total5 test` (voir [Ligne de commande](../../reference/command-line/)).\n\nExample: Charger\n```js\nrequire('total5/test');\n\nTest.push('Numbers', function(next) {\n\tTest.print('sum', 1 + 1 === 2 ? null : 'Wrong sum');\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.push(name, fn)\n\nType: `method`\n\nAjoute un groupe de tests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom affiché en en-tête du groupe. |\n| `fn` | `Function` | yes |  | `function(next)` |\n\nReturns: `undefined`\n\nLes groupes s'exécutent dans l'ordre de leur ajout. `fn` reçoit `next` et doit l'appeler quand le groupe est terminé, y compris après des vérifications asynchrones.\n\nExample: Groupe asynchrone\n```js\nTest.push('Download', function(next) {\n\tRESTBuilder.GET('https://www.example.com').callback(function(err) {\n\t\tTest.print('GET', err);\n\t\tnext();\n\t});\n});\n```\n\n### Test.run([callback])\n\nType: `method`\n\nExécute tous les groupes l'un après l'autre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function()` appelée au lieu de terminer le processus. |\n\nReturns: `undefined`\n\nAffiche l'en-tête de chaque groupe, puis le nombre de vérifications et la durée. Sans `callback`, le processus se termine avec le code de sortie 0 quand tous les groupes sont terminés.\n\nExample: Exécuter et arrêter le serveur\n```js\nTest.run(function() {\n\tF.exit();\n});\n```\n\n### Test.print(message, [err])\n\nType: `method`\n\nAffiche le résultat d'une vérification.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Le nom de la vérification. |\n| `err` | `Error|String` | no |  | La raison d'un échec. |\n\nReturns: `undefined`\n\nSans `err` (ou avec une valeur falsy), il affiche `[OK] message` et compte la vérification. Avec `err`, il affiche `[FAIL] message`, lève l'erreur (une chaîne devient une `Error`) et termine le processus avec le code de sortie 1.\n\nExample: Vérifier une valeur\n```js\nvar value = 'Total.js'.slug();\nTest.print('slug()', value === 'total-js' ? null : 'Unexpected: ' + value);\n```\n\n### Test.start(message)\n\nType: `method`\n\nAffiche un en-tête entre deux lignes de séparation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Le texte de l'en-tête. |\n\nReturns: `undefined`\n\n`Test.run()` l'appelle avec le nom de chaque groupe. Appelle-la toi-même pour séparer les parties d'un long groupe.\n\nExample: En-tête\n```js\nTest.start('Second part');\n```\n\n### Test.fake(name, action)\n\nType: `method`\n\nRemplace une action par une fausse action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'action. |\n| `action` | `Object` | yes |  | La définition de la fausse action, le même objet que dans `NEWACTION()`. |\n\nReturns: `Object` La fausse action enregistrée.\n\nMet de côté l'action `name` (seulement la première fois jusqu'à `Test.restore()`) et enregistre `action` sous le même nom avec `NEWACTION()`. Les appels de `ACTION(name)` exécutent alors la fausse action. Elle fonctionne aussi pour un nom qui n'a pas d'action.\n\nExample: Remplacer et restaurer\n```js\nNEWACTION('Users/read', {\n\taction: $ => $.callback('real')\n});\n\nTest.push('Fake', async function(next) {\n\tTest.fake('Users/read', { action: $ => $.callback('fake') });\n\tvar value = await ACTION('Users/read').promise();\n\tTest.print('fake', value === 'fake' ? null : 'Unexpected: ' + value);\n\tTest.restore();\n\tvalue = await ACTION('Users/read').promise();\n\tTest.print('restore', value === 'real' ? null : 'Unexpected: ' + value);\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.count\n\nType: `property`\n\nLe nombre de vérifications affichées par `Test.print()`.\n\nReturns: `Number`\n\n`Test.run()` l'affiche à la fin sous la forme `Tests: <count>`.\n\nExample: Lire\n```js\nTest.run(function() {\n\tconsole.log('Checks:', Test.count);\n\tprocess.exit(0);\n});\n```\n\n### Test.restore()\n\nType: `method`\n\nRemet les actions d'origine.\n\nReturns: `undefined`\n\nSupprime chaque fausse action enregistrée avec `Test.fake()` et remet les actions d'origine. Une fausse action d'un nom qui n'avait pas d'action est seulement supprimée.\n\nExample: Après un groupe\n```js\nTest.push('Payments', function(next) {\n\tTest.fake('Payments/charge', { action: $ => $.callback({ paid: true }) });\n\t// ... the checks\n\tTest.restore();\n\tnext();\n});\n```\n\n### Test.items\n\nType: `property`\n\nLes groupes ajoutés avec `Test.push()`.\n\nReturns: `Array`\n\nUn tableau d'objets `{ name, fn }`. `Test.run()` les exécute un par un ; le tableau les conserve.\n\nExample: Compter les groupes\n```js\nconsole.log(Test.items.length, 'groups');\n```\n","entries":[{"type":"class","name":"Test","signature":"Test","since":"","deprecated":false},{"type":"method","name":"Test.push()","signature":"Test.push(name, fn)","since":"","deprecated":false},{"type":"method","name":"Test.run()","signature":"Test.run([callback])","since":"","deprecated":false},{"type":"method","name":"Test.print()","signature":"Test.print(message, [err])","since":"","deprecated":false},{"type":"method","name":"Test.start()","signature":"Test.start(message)","since":"","deprecated":false},{"type":"method","name":"Test.fake()","signature":"Test.fake(name, action)","since":"","deprecated":false},{"type":"property","name":"Test.count","signature":"Test.count","since":"","deprecated":false},{"type":"method","name":"Test.restore()","signature":"Test.restore()","since":"","deprecated":false},{"type":"property","name":"Test.items","signature":"Test.items","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwU09Ax61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Test unitari","summary":"Il test runner di total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count e Test.items.","markdown":"---\ntitle: Test unitari\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/unit-tests/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Test unitari\n\n> Il test runner di total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count e Test.items.\n\nIl runner `Test` di `total5/test`. La guida [Test unitari](../../guides/unit-tests/) spiega come usarlo, con esempi.\n\n## API\n\n### Test\n\nType: `class`\n\nIl test runner globale creato da `require('total5/test')`.\n\nReturns: `Object`\n\nCarica `total5` quando non è caricato e crea l'oggetto globale `Test` con `push()`, `run()`, `print()`, `start()`, `fake()`, `restore()`, `count` e `items`. Esegui il file di test con `node`, oppure gli script di test di un progetto con `total5 test` (vedi [Riga di comando](../../reference/command-line/)).\n\nExample: Caricare\n```js\nrequire('total5/test');\n\nTest.push('Numbers', function(next) {\n\tTest.print('sum', 1 + 1 === 2 ? null : 'Wrong sum');\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.push(name, fn)\n\nType: `method`\n\nAggiunge un gruppo di test.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome stampato come intestazione del gruppo. |\n| `fn` | `Function` | yes |  | `function(next)` |\n\nReturns: `undefined`\n\nI gruppi vengono eseguiti nell'ordine in cui sono stati aggiunti. `fn` riceve `next` e deve chiamarlo quando il gruppo è terminato, anche dopo verifiche asincrone.\n\nExample: Gruppo asincrono\n```js\nTest.push('Download', function(next) {\n\tRESTBuilder.GET('https://www.example.com').callback(function(err) {\n\t\tTest.print('GET', err);\n\t\tnext();\n\t});\n});\n```\n\n### Test.run([callback])\n\nType: `method`\n\nEsegue tutti i gruppi uno alla volta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function()` chiamata invece di terminare il processo. |\n\nReturns: `undefined`\n\nStampa l'intestazione di ogni gruppo, poi il numero di verifiche e il tempo. Senza `callback` il processo termina con codice di uscita 0 quando tutti i gruppi sono terminati.\n\nExample: Eseguire e fermare il server\n```js\nTest.run(function() {\n\tF.exit();\n});\n```\n\n### Test.print(message, [err])\n\nType: `method`\n\nStampa il risultato di una verifica.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Il nome della verifica. |\n| `err` | `Error|String` | no |  | Il motivo di un fallimento. |\n\nReturns: `undefined`\n\nSenza `err` (o con un valore falsy) stampa `[OK] message` e conta la verifica. Con `err` stampa `[FAIL] message`, genera l'errore (una stringa diventa un `Error`) e termina il processo con codice di uscita 1.\n\nExample: Verificare un valore\n```js\nvar value = 'Total.js'.slug();\nTest.print('slug()', value === 'total-js' ? null : 'Unexpected: ' + value);\n```\n\n### Test.start(message)\n\nType: `method`\n\nStampa un'intestazione tra due linee divisorie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Il testo dell'intestazione. |\n\nReturns: `undefined`\n\n`Test.run()` la chiama con il nome di ogni gruppo. Chiamala tu per separare le parti di un gruppo lungo.\n\nExample: Intestazione\n```js\nTest.start('Second part');\n```\n\n### Test.fake(name, action)\n\nType: `method`\n\nSostituisce un'azione con una finta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'azione. |\n| `action` | `Object` | yes |  | La definizione dell'azione finta, lo stesso oggetto di `NEWACTION()`. |\n\nReturns: `Object` L'azione finta registrata.\n\nMette da parte l'azione `name` (solo la prima volta fino a `Test.restore()`) e registra `action` con lo stesso nome tramite `NEWACTION()`. Le chiamate di `ACTION(name)` eseguono allora l'azione finta. Funziona anche per un nome che non ha un'azione.\n\nExample: Sostituire e ripristinare\n```js\nNEWACTION('Users/read', {\n\taction: $ => $.callback('real')\n});\n\nTest.push('Fake', async function(next) {\n\tTest.fake('Users/read', { action: $ => $.callback('fake') });\n\tvar value = await ACTION('Users/read').promise();\n\tTest.print('fake', value === 'fake' ? null : 'Unexpected: ' + value);\n\tTest.restore();\n\tvalue = await ACTION('Users/read').promise();\n\tTest.print('restore', value === 'real' ? null : 'Unexpected: ' + value);\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.count\n\nType: `property`\n\nIl numero di verifiche stampate da `Test.print()`.\n\nReturns: `Number`\n\n`Test.run()` lo stampa alla fine come `Tests: <count>`.\n\nExample: Leggere\n```js\nTest.run(function() {\n\tconsole.log('Checks:', Test.count);\n\tprocess.exit(0);\n});\n```\n\n### Test.restore()\n\nType: `method`\n\nRimette le azioni originali.\n\nReturns: `undefined`\n\nRimuove ogni azione finta registrata con `Test.fake()` e rimette le azioni originali. Un'azione finta di un nome che non aveva un'azione viene solo rimossa.\n\nExample: Dopo un gruppo\n```js\nTest.push('Payments', function(next) {\n\tTest.fake('Payments/charge', { action: $ => $.callback({ paid: true }) });\n\t// ... the checks\n\tTest.restore();\n\tnext();\n});\n```\n\n### Test.items\n\nType: `property`\n\nI gruppi aggiunti con `Test.push()`.\n\nReturns: `Array`\n\nUn array di oggetti `{ name, fn }`. `Test.run()` li esegue uno alla volta; l'array li conserva.\n\nExample: Contare i gruppi\n```js\nconsole.log(Test.items.length, 'groups');\n```\n","entries":[{"type":"class","name":"Test","signature":"Test","since":"","deprecated":false},{"type":"method","name":"Test.push()","signature":"Test.push(name, fn)","since":"","deprecated":false},{"type":"method","name":"Test.run()","signature":"Test.run([callback])","since":"","deprecated":false},{"type":"method","name":"Test.print()","signature":"Test.print(message, [err])","since":"","deprecated":false},{"type":"method","name":"Test.start()","signature":"Test.start(message)","since":"","deprecated":false},{"type":"method","name":"Test.fake()","signature":"Test.fake(name, action)","since":"","deprecated":false},{"type":"property","name":"Test.count","signature":"Test.count","since":"","deprecated":false},{"type":"method","name":"Test.restore()","signature":"Test.restore()","since":"","deprecated":false},{"type":"property","name":"Test.items","signature":"Test.items","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwU09Ax61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/unit-tests/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Unit testy","summary":"Spúšťač Test z total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count a Test.items.","markdown":"---\ntitle: Unit testy\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/unit-tests/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Unit testy\n\n> Spúšťač Test z total5/test: Test.push(), Test.run(), Test.print(), Test.start(), Test.fake(), Test.restore(), Test.count a Test.items.\n\nSpúšťač `Test` z `total5/test`. Ako ho používať, vysvetľuje s príkladmi návod [Unit testy](../../guides/unit-tests/).\n\n## API\n\n### Test\n\nType: `class`\n\nGlobálny spúšťač testov vytvorený pomocou `require('total5/test')`.\n\nReturns: `Object`\n\nNačíta `total5`, keď nie je načítaný, a vytvorí globálny objekt `Test` s `push()`, `run()`, `print()`, `start()`, `fake()`, `restore()`, `count` a `items`. Testovací súbor spusti pomocou `node`, alebo testovacie skripty projektu cez `total5 test` (pozri [Príkazový riadok](../../reference/command-line/)).\n\nExample: Načítanie\n```js\nrequire('total5/test');\n\nTest.push('Numbers', function(next) {\n\tTest.print('sum', 1 + 1 === 2 ? null : 'Wrong sum');\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.push(name, fn)\n\nType: `method`\n\nPridá skupinu testov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov vypísaný ako hlavička skupiny. |\n| `fn` | `Function` | yes |  | `function(next)` |\n\nReturns: `undefined`\n\nSkupiny bežia v poradí, v akom boli pridané. `fn` dostane `next` a musí ho zavolať, keď je skupina hotová, aj po asynchrónnych kontrolách.\n\nExample: Asynchrónna skupina\n```js\nTest.push('Download', function(next) {\n\tRESTBuilder.GET('https://www.example.com').callback(function(err) {\n\t\tTest.print('GET', err);\n\t\tnext();\n\t});\n});\n```\n\n### Test.run([callback])\n\nType: `method`\n\nSpustí všetky skupiny jednu po druhej.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function()` zavolaná namiesto ukončenia procesu. |\n\nReturns: `undefined`\n\nVypíše hlavičku každej skupiny, potom počet kontrol a čas. Bez `callback` proces skončí s návratovým kódom 0, keď sú všetky skupiny hotové.\n\nExample: Spustenie a zastavenie servera\n```js\nTest.run(function() {\n\tF.exit();\n});\n```\n\n### Test.print(message, [err])\n\nType: `method`\n\nVypíše výsledok jednej kontroly.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Názov kontroly. |\n| `err` | `Error|String` | no |  | Dôvod zlyhania. |\n\nReturns: `undefined`\n\nBez `err` (alebo s nepravdivou hodnotou) vypíše `[OK] message` a započíta kontrolu. S `err` vypíše `[FAIL] message`, vyhodí chybu (reťazec sa zmení na `Error`) a ukončí proces s návratovým kódom 1.\n\nExample: Kontrola hodnoty\n```js\nvar value = 'Total.js'.slug();\nTest.print('slug()', value === 'total-js' ? null : 'Unexpected: ' + value);\n```\n\n### Test.start(message)\n\nType: `method`\n\nVypíše hlavičku medzi dvoma deliacimi čiarami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Text hlavičky. |\n\nReturns: `undefined`\n\n`Test.run()` ju volá s názvom každej skupiny. Zavolaj ju sám, ak chceš oddeliť časti dlhej skupiny.\n\nExample: Hlavička\n```js\nTest.start('Second part');\n```\n\n### Test.fake(name, action)\n\nType: `method`\n\nNahradí akciu falošnou akciou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov akcie. |\n| `action` | `Object` | yes |  | Definícia falošnej akcie, ten istý objekt ako v `NEWACTION()`. |\n\nReturns: `Object` Zaregistrovaná falošná akcia.\n\nOdloží akciu `name` bokom (iba prvýkrát až do `Test.restore()`) a pod tým istým názvom zaregistruje `action` cez `NEWACTION()`. Volania `ACTION(name)` potom spúšťajú falošnú akciu. Funguje aj pre názov, ktorý žiadnu akciu nemá.\n\nExample: Nahradenie a obnovenie\n```js\nNEWACTION('Users/read', {\n\taction: $ => $.callback('real')\n});\n\nTest.push('Fake', async function(next) {\n\tTest.fake('Users/read', { action: $ => $.callback('fake') });\n\tvar value = await ACTION('Users/read').promise();\n\tTest.print('fake', value === 'fake' ? null : 'Unexpected: ' + value);\n\tTest.restore();\n\tvalue = await ACTION('Users/read').promise();\n\tTest.print('restore', value === 'real' ? null : 'Unexpected: ' + value);\n\tnext();\n});\n\nTest.run();\n```\n\n### Test.count\n\nType: `property`\n\nPočet kontrol vypísaných pomocou `Test.print()`.\n\nReturns: `Number`\n\n`Test.run()` ho na konci vypíše ako `Tests: <count>`.\n\nExample: Čítanie\n```js\nTest.run(function() {\n\tconsole.log('Checks:', Test.count);\n\tprocess.exit(0);\n});\n```\n\n### Test.restore()\n\nType: `method`\n\nVráti pôvodné akcie späť.\n\nReturns: `undefined`\n\nOdstráni každú falošnú akciu zaregistrovanú cez `Test.fake()` a vráti pôvodné akcie späť. Falošná akcia názvu, ktorý žiadnu akciu nemal, sa iba odstráni.\n\nExample: Po skupine\n```js\nTest.push('Payments', function(next) {\n\tTest.fake('Payments/charge', { action: $ => $.callback({ paid: true }) });\n\t// ... the checks\n\tTest.restore();\n\tnext();\n});\n```\n\n### Test.items\n\nType: `property`\n\nSkupiny pridané pomocou `Test.push()`.\n\nReturns: `Array`\n\nPole objektov `{ name, fn }`. `Test.run()` ich spúšťa jeden po druhom; pole ich ponecháva.\n\nExample: Počet skupín\n```js\nconsole.log(Test.items.length, 'groups');\n```\n","entries":[{"type":"class","name":"Test","signature":"Test","since":"","deprecated":false},{"type":"method","name":"Test.push()","signature":"Test.push(name, fn)","since":"","deprecated":false},{"type":"method","name":"Test.run()","signature":"Test.run([callback])","since":"","deprecated":false},{"type":"method","name":"Test.print()","signature":"Test.print(message, [err])","since":"","deprecated":false},{"type":"method","name":"Test.start()","signature":"Test.start(message)","since":"","deprecated":false},{"type":"method","name":"Test.fake()","signature":"Test.fake(name, action)","since":"","deprecated":false},{"type":"property","name":"Test.count","signature":"Test.count","since":"","deprecated":false},{"type":"method","name":"Test.restore()","signature":"Test.restore()","since":"","deprecated":false},{"type":"property","name":"Test.items","signature":"Test.items","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwUK9Zx60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/reference/command-line/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"en","title":"Command line (total5)","summary":"Every command and argument of the total5 and flow5 programs.","markdown":"---\ntitle: Command line (total5)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/reference/command-line/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Command line (total5)\n\n> Every command and argument of the total5 and flow5 programs.\n\nThe commands of the two programs that the `total5` package installs: `total5`, which works on the current directory, and `flow5`, which runs FlowStream schemas. Each entry shows the syntax, the arguments and an example. For an introduction read [Command line (total5)](../../guides/command-line/).\n\n```bash\nnpm install -g total5\ntotal5 help\nflow5\n```\n\n## API\n\n### total5 [command] [arguments]\n\nType: `command`\n\nThe command-line toolbox of the total5 package.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | no | `help` | The name of the command. |\n| `arguments` | `String` | no |  | The arguments of the command, in order. |\n\nRuns one command on the current directory. Without a command it shows the help. Each command prints `* Total.js v5: [Command]` first; the short ones end with a `[Done]` line with the time they took. A command the program does not know prints only that header.\n\nExample: Show the help\n```bash\ntotal5\n```\n\n### total5 help\n\nType: `command`\n\nPrints the list of commands.\n\nPrints one line for each command with its arguments and what it does: `translate`, `minify`, `bundle`, `extract`, `edit`, `proxy`, `test` and the web server (`8000`). `total5` with no command does the same.\n\nExample: Help\n```bash\ntotal5 help\ntotal5 --help\n```\n\n### total5 --<command> [arguments]\n\nType: `command`\n\nDashes in front of a command are ignored.\n\nThe program removes every run of two or more dashes from the command, so `--help` is `help` and `--minify` is `minify`. Use the form you prefer.\n\nExample: The same command twice\n```bash\ntotal5 --help\ntotal5 help\n```\n\n### total5 minify <filename>\n\nType: `command`\n\nMinifies a JavaScript, CSS or HTML file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The full path of the file to minify. |\n\nReads the file, minifies it by its extension and writes the result next to it as `name.min.ext`. JavaScript and CSS are fully minified. The HTML minifier removes comments, shortens runs of spaces inside the markup and minifies inline `<script>` and `<style>` blocks; it keeps the line breaks and the indentation between tags. A file with another extension is copied without change. It prints the input and the output file names. Give the full path of the file.\n\nExample: Minify a script\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"\n# Output    : /home/me/shop/public/js/app.min.js\n```\n\n### total5 edit <url>\n\nType: `command`\n\nOpens the current directory for remote editing in the Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address of the project in the Code Editor, for example `https://code.example.com/?id=project`. |\n\nConnects to the URL of the project with a WebSocket (`http` and `https` become `ws` and `wss`) and serves the requests of the editor on the current directory (see Code Editor requests). When the editor accepts the connection it prints a welcome with the name of the editor and of the project. The connection reconnects every 10 seconds and is pinged every 30 seconds. `404 project not found` and `409 project is already open` are printed when the editor refuses the project. Without a URL the program throws `Invalid URL address`.\n\nExample: Edit a project\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n```\n\n### TYPE: browse | load | save | ...\n\nType: `type`\n\nWhat the Code Editor can do through total5 edit.\n\nThe editor sends requests and the program answers them inside the current directory: `browse` (the list of files and folders), `load`, `save`, `create`, `remove`, `rename`, `modify`, `info`, `upload`, `download`, `send`, `import`, `log` and `logclear` (log files), `wiki`, `ip` (the public IP address), `exec` (runs a file: `.js` files with Node.js, `.sh` files with `sh`, or a command the editor sends), `restart` and `ping`. An unknown request is answered with an error 400.\n\nExample: A request and its answer\n```js\n// sent by the editor\n{ TYPE: 'browse', data: '{}' }\n// answer\n{ TYPE: 'browse', data: '{}', success: true, response: { files: ['/index.js'], directories: ['/controllers/'] } }\n```\n\n### total5 <port>\n\nType: `command`\n\nStarts a static web server for the current directory on the given port.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | The port of the server. |\n\nA number as the command starts the web server: `total5 8000` is `total5 server 8000`. The current directory is the public folder, minification and source maps are off, and the application folders are not loaded. A directory URL shows a listing of the directory. The program prints the start information of the framework and runs until you stop it.\n\nExample: Serve a folder\n```bash\ncd ~/projects/landing\ntotal5 8000\n# open http://127.0.0.1:8000/\n```\n\n### total5 proxy <endpoint> <port>\n\nType: `command` · Since: `0.0.17`\n\nConnects a local port to a remote Total.js proxy server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | yes |  | The WebSocket address of the proxy server. |\n| `port` | `String` | yes |  | A local port (on `127.0.0.1`) or an `ip:port` pair. |\n\nOpens a WebSocket to the proxy server, an application that calls `PROXYSERVER()` (`http` and `https` are replaced with `ws` and `wss`), and forwards every request that arrives through it to the local address. The answer goes back the same way. The program prints a line when it connects or disconnects and one line for each request with its method, the IP address of the visitor and the URL. Without both arguments it prints `client [WSS proxy server] [port or ip:port]`. It is the same client as the `PROXYCLIENT()` function.\n\nExample: Share a local server\n```bash\ntotal5 proxy wss://proxy.example.com/ 8000\n```\n\nExample: The server side\n```js\n// index.js of the proxy server\nrequire('total5');\nPROXYSERVER('/', '/proxy/');\nF.http({ port: 8000, load: 'none' });\n\n// on your machine:\n// total5 proxy wss://proxy.example.com/proxy/ 8000\n```\n\n### total5 server [port]\n\nType: `command`\n\nStarts a static web server for the current directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `8000` | The port of the server. |\n\nThe long form of `total5 <port>`. Without a port it listens on `8000`.\n\nExample: Default port\n```bash\ntotal5 server\n# http://0.0.0.0:8000/\n```\n\nExample: Another port\n```bash\ntotal5 server 8080\n```\n\n### total5 test [name1] [name2] [...]\n\nType: `command`\n\nRuns the unit tests of the current directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The name of a test script without `.js`; several names with spaces or commas. |\n\nTakes the `tests` directory of the current directory, or the current directory when there is no `tests` directory. It loads the `config` file of that directory with `LOADCONFIG()`, creates the global `Test`, loads `init.js` when it exists and then the named scripts in their order, or every `.js` file except `init.js` in alphabetical order when no name is given. Then it calls `Test.run()`. Names can be separated with spaces or commas and the `.js` extension is optional. A missing script prints `ERROR: the test \"name\" not found (path)` and ends with exit code 1. The exit code is 0 when all groups are done and 1 when a check fails or the run stops before the end. The command uses the `total5` package installed in the current directory or in a parent directory (so it also runs from `tests`), otherwise its own package. The application itself is not started and the current directory is the root (`PATH.root()`). See [Unit tests](../../guides/unit-tests/).\n\nExample: All tests\n```bash\ncd ~/projects/shop\ntotal5 test\n```\n\nExample: Two scripts\n```bash\ntotal5 test strings orders\ntotal5 test strings,orders\n```\n\n### flow5\n\nType: `command`\n\nPrints the help of the Flow engine.\n\nWithout arguments `flow5` prints `[Total.js v5 Flow Engine]` and the ways to call it.\n\nExample: Help\n```bash\nflow5\n# flow5 [path or URL address] [PORT_NUMBER]\n# flow5 path/to/flowschema.json\n# flow5 flow1.json flow2.json flowN.json 8001\n# flow5 https://yourdomain.com/flowschema.json\n```\n\n### GET /{path}/\n\nType: `type`\n\nWhat the web server shows for a directory.\n\nFor a directory URL the server shows an HTML page with a `..` link to the parent (except at `/`), the subdirectories and the files with their sizes. Every link opens the item on the same server; open `index.html` from the listing like any other file.\n\nExample: Browse\n```bash\ntotal5 8000\n# http://127.0.0.1:8000/            -> the listing of the directory\n# http://127.0.0.1:8000/index.html  -> the page\n```\n\n### total5 translate <filename>\n\nType: `command`\n\nCollects the @(...) texts of the current directory into a resource file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The full path of the resource file to write. |\n\nReads every `.js` and `.html` file of the current directory and of all its subdirectories, finds the texts written as `@(text)` (nested parentheses are kept) and writes them into the resource file, one `KEY : text` line for each text. The same text gives one line. An existing file is overwritten. Give the full path of the file.\n\nExample: Into resources\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n### flow5 <file> [port]\n\nType: `command`\n\nRuns the flows of a local schema file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | The full path of the schema file. |\n| `port` | `Number` | no | `8000` | The port of the HTTP server. |\n\nLoads the FlowStream schema of the file and runs it. The HTTP server starts when at least one flow is loaded. For each flow the program prints a link to the Flow editor. When the flow is saved in the editor, the file is written again as JSON indented with tabs. A file that is not valid JSON prints `ERROR: invalid meta - <path>` and is skipped. Give the full path of the file.\n\nExample: One file\n```bash\nflow5 \"$PWD/flowschema.json\"\n# |--- http://127.0.0.1:8000\n# |--- Orders: https://flow.totaljs.com/?socket=...\n```\n\n### flow5 <url> [port]\n\nType: `command`\n\nRuns the flows of a schema downloaded from an https address.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The `https://` address of the schema. |\n| `port` | `Number` | no | `8000` | The port of the HTTP server. |\n\nAn argument that starts with `https://` is downloaded with a `GET` request and loaded like a file. The certificate of the server is checked. Changes made in the editor are not saved anywhere for these flows.\n\nExample: Remote schema\n```bash\nflow5 https://example.com/flowschema.json 8001\n```\n\n### KEY : text\n\nType: `type`\n\nThe file that total5 translate writes.\n\nA plain text file with one line for each text: the key, padded to 12 characters, then ` : ` and the text. The key is `T` followed by a hash of the text in base 36, the key that the view engine looks up for `@(text)`. Put a translated copy into `resources/` (for example `resources/sk.resource`) and translate the right side. See [Localization](../../guides/localization/).\n\nExample: Content\n```text\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\n### flow5 <files...> <port>\n\nType: `command`\n\nSets the port of the Flow engine and runs several schemas at once.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String` | yes |  | One or more schema files or addresses. |\n| `port` | `Number` | no | `8000` | The port of the HTTP server. |\n\nArguments can come in any order. Every argument made only of digits is the port (the last one wins); every other one is a schema file, with its full path, or an `https://` address. All the flows of all the sources run in one process on that port.\n\nExample: Several files\n```bash\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\n```\n\n### total5 bundle <filename>\n\nType: `command`\n\nPacks the current directory into a bundle file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The full path of the bundle file. |\n\nWrites the files of the current directory and its subdirectories into one `.bundle` file. `.bundle` is added to the name when it is missing. The machine files are left out (see Bundle content). Give the full path of the bundle, outside the directory you pack. The framework unpacks the bundles of `bundles/` when it starts.\n\nExample: Pack a project\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop\n# ~/backups/shop.bundle\n```\n\n### { id, name, components, design } | { <id>: schema }\n\nType: `type`\n\nThe two shapes of a file that flow5 reads.\n\nA file with **one flow** is an object with `components` and `design` (and `id`, `name` and the other fields of a FlowStream schema). A file with **several flows** is an object whose keys are the ids of the flows; a `variables` key is skipped. A flow without `id` gets an id made from the path. To save changes back into the file, give the flow an `id`, and in a file with several flows use the id as its key.\n\nExample: One flow\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {},\n\t\"design\": {}\n}\n```\n\nExample: Several flows\n```json\n{\n\t\"orders\": { \"id\": \"orders\", \"name\": \"Orders\", \"components\": {}, \"design\": {} },\n\t\"mail\": { \"id\": \"mail\", \"name\": \"Mail\", \"components\": {}, \"design\": {} }\n}\n```\n\n### .bundle\n\nType: `type`\n\nWhich files total5 bundle puts into a bundle.\n\nAll the files of the directory, except: `/index.js`, `/debug.js`, `/release.js` with their `.json` and `.pid` files, `/bundle.json`, `/package.json`, `/readme.md`, `/license.txt` and the folders `/bundles/`, `/tmp/`, `/.src/` and `/.git/`.\n\nExample: Deploy with a bundle\n```bash\ntotal5 bundle ~/backups/shop\nscp ~/backups/shop.bundle server:/www/shop/bundles/\n```\n\n### GET|POST /notify/{id}/\n\nType: `property`\n\nThe notification route of the Flow engine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | `<flow id>-<instance id>[-param...]`. |\n\nSends a notification to a component instance of a running flow. The id is `<flow id>-<instance id>`; more parts separated with `-` arrive as `params`. The component gets the method, headers, query, body (up to 1 MB), URL and IP address. A `REDIRECT` query value redirects the visitor; a browser gets a page that closes itself, other clients get a success answer. See [FlowStream](../../guides/flowstream/).\n\nExample: Notify a component\n```bash\ncurl -X POST -d '{\"paid\":true}' -H \"Content-Type: application/json\" http://127.0.0.1:8000/notify/orders-c1x8a/\n```\n\n### total5 extract <filename>\n\nType: `command`\n\nUnpacks a bundle into the current directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The full path of the bundle file to unpack. |\n\nRestores all the files of the bundle into the current directory, with their subdirectories. Existing files with the same names are overwritten. When the argument is a directory, nothing happens. Give the full path of the file.\n\nExample: Unpack\n```bash\nmkdir shop-copy && cd shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n### SOCKET /flowstreams/{id}/\n\nType: `property`\n\nThe WebSocket of the Flow editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the flow. |\n\nThe Flow editor connects here to show and change the flow with the given id (messages up to 8 MB). The link that `flow5` prints for each flow opens `https://flow.totaljs.com/?socket=` with this address.\n\nExample: Open the editor\n```text\nhttps://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n","entries":[{"type":"command","name":"total5","signature":"total5 [command] [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 help","signature":"total5 help","since":"","deprecated":false},{"type":"command","name":"total5 --command","signature":"total5 --<command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 minify","signature":"total5 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total5 edit","signature":"total5 edit <url>","since":"","deprecated":false},{"type":"type","name":"Code Editor requests","signature":"TYPE: browse | load | save | ...","since":"","deprecated":false},{"type":"command","name":"total5 <port>","signature":"total5 <port>","since":"","deprecated":false},{"type":"command","name":"total5 proxy","signature":"total5 proxy <endpoint> <port>","since":"0.0.17","deprecated":false},{"type":"command","name":"total5 server","signature":"total5 server [port]","since":"","deprecated":false},{"type":"command","name":"total5 test","signature":"total5 test [name1] [name2] [...]","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5","since":"","deprecated":false},{"type":"type","name":"Directory listing","signature":"GET /{path}/","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate <filename>","since":"","deprecated":false},{"type":"command","name":"flow5 <file>","signature":"flow5 <file> [port]","since":"","deprecated":false},{"type":"command","name":"flow5 <url>","signature":"flow5 <url> [port]","since":"","deprecated":false},{"type":"type","name":"Resource file","signature":"KEY : text","since":"","deprecated":false},{"type":"command","name":"flow5 <port>","signature":"flow5 <files...> <port>","since":"","deprecated":false},{"type":"command","name":"total5 bundle","signature":"total5 bundle <filename>","since":"","deprecated":false},{"type":"type","name":"Flow schema file","signature":"{ id, name, components, design } | { <id>: schema }","since":"","deprecated":false},{"type":"type","name":"Bundle content","signature":".bundle","since":"","deprecated":false},{"type":"property","name":"flow5 /notify/{id}/","signature":"GET|POST /notify/{id}/","since":"","deprecated":false},{"type":"command","name":"total5 extract","signature":"total5 extract <filename>","since":"","deprecated":false},{"type":"property","name":"flow5 /flowstreams/{id}/","signature":"SOCKET /flowstreams/{id}/","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwUK9Zx60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/command-line/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"de","title":"Kommandozeile (total5)","summary":"Jeder Befehl und jedes Argument der Programme total5 und flow5.","markdown":"---\ntitle: Kommandozeile (total5)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/reference/command-line/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Kommandozeile (total5)\n\n> Jeder Befehl und jedes Argument der Programme total5 und flow5.\n\nDie Befehle der beiden Programme, die das Paket `total5` installiert: `total5`, das im aktuellen Verzeichnis arbeitet, und `flow5`, das FlowStream-Schemas ausführt. Jeder Eintrag zeigt die Syntax, die Argumente und ein Beispiel. Für eine Einführung lies [Kommandozeile (total5)](../../guides/command-line/).\n\n```bash\nnpm install -g total5\ntotal5 help\nflow5\n```\n\n## API\n\n### total5 [command] [arguments]\n\nType: `command`\n\nDie Kommandozeilen-Werkzeugkiste des Pakets total5.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | no | `help` | Der Name des Befehls. |\n| `arguments` | `String` | no |  | Die Argumente des Befehls, in ihrer Reihenfolge. |\n\nFührt einen Befehl im aktuellen Verzeichnis aus. Ohne Befehl zeigt es die Hilfe. Jeder Befehl gibt zuerst `* Total.js v5: [Command]` aus; die kurzen enden mit einer `[Done]`-Zeile mit der benötigten Zeit. Ein Befehl, den das Programm nicht kennt, gibt nur diesen Header aus.\n\nExample: Die Hilfe anzeigen\n```bash\ntotal5\n```\n\n### total5 help\n\nType: `command`\n\nGibt die Liste der Befehle aus.\n\nGibt für jeden Befehl eine Zeile mit seinen Argumenten und seiner Funktion aus: `translate`, `minify`, `bundle`, `extract`, `edit`, `proxy`, `test` und den Webserver (`8000`). `total5` ohne Befehl macht dasselbe.\n\nExample: Hilfe\n```bash\ntotal5 help\ntotal5 --help\n```\n\n### total5 --<command> [arguments]\n\nType: `command`\n\nBindestriche vor einem Befehl werden ignoriert.\n\nDas Programm entfernt jede Folge von zwei oder mehr Bindestrichen aus dem Befehl, also ist `--help` gleich `help` und `--minify` gleich `minify`. Verwende die Form, die du bevorzugst.\n\nExample: Derselbe Befehl zweimal\n```bash\ntotal5 --help\ntotal5 help\n```\n\n### total5 minify <filename>\n\nType: `command`\n\nMinifiziert eine JavaScript-, CSS- oder HTML-Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der vollständige Pfad der zu minifizierenden Datei. |\n\nLiest die Datei, minifiziert sie anhand ihrer Endung und schreibt das Ergebnis daneben als `name.min.ext`. JavaScript und CSS werden vollständig minifiziert. Der HTML-Minifier entfernt Kommentare, verkürzt Folgen von Leerzeichen im Markup und minifiziert eingebettete `<script>`- und `<style>`-Blöcke; Zeilenumbrüche und Einrückungen zwischen Tags bleiben erhalten. Eine Datei mit einer anderen Endung wird unverändert kopiert. Es gibt die Namen der Eingabe- und der Ausgabedatei aus. Gib den vollständigen Pfad der Datei an.\n\nExample: Ein Skript minifizieren\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"\n# Output    : /home/me/shop/public/js/app.min.js\n```\n\n### total5 edit <url>\n\nType: `command`\n\nÖffnet das aktuelle Verzeichnis zur Remote-Bearbeitung im Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse des Projekts im Code Editor, zum Beispiel `https://code.example.com/?id=project`. |\n\nVerbindet sich per WebSocket mit der URL des Projekts (`http` und `https` werden zu `ws` und `wss`) und bedient die Anfragen des Editors im aktuellen Verzeichnis (siehe Anfragen des Code Editors). Wenn der Editor die Verbindung annimmt, gibt es eine Begrüßung mit dem Namen des Editors und des Projekts aus. Die Verbindung wird alle 10 Sekunden neu aufgebaut und alle 30 Sekunden angepingt. `404 project not found` und `409 project is already open` werden ausgegeben, wenn der Editor das Projekt ablehnt. Ohne URL wirft das Programm `Invalid URL address`.\n\nExample: Ein Projekt bearbeiten\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n```\n\n### TYPE: browse | load | save | ...\n\nType: `type`\n\nWas der Code Editor über total5 edit tun kann.\n\nDer Editor sendet Anfragen, und das Programm beantwortet sie innerhalb des aktuellen Verzeichnisses: `browse` (die Liste der Dateien und Ordner), `load`, `save`, `create`, `remove`, `rename`, `modify`, `info`, `upload`, `download`, `send`, `import`, `log` und `logclear` (Logdateien), `wiki`, `ip` (die öffentliche IP-Adresse), `exec` (führt eine Datei aus: `.js`-Dateien mit Node.js, `.sh`-Dateien mit `sh` oder einen Befehl, den der Editor sendet), `restart` und `ping`. Eine unbekannte Anfrage wird mit einem Fehler 400 beantwortet.\n\nExample: Eine Anfrage und ihre Antwort\n```js\n// sent by the editor\n{ TYPE: 'browse', data: '{}' }\n// answer\n{ TYPE: 'browse', data: '{}', success: true, response: { files: ['/index.js'], directories: ['/controllers/'] } }\n```\n\n### total5 <port>\n\nType: `command`\n\nStartet einen statischen Webserver für das aktuelle Verzeichnis auf dem angegebenen Port.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | Der Port des Servers. |\n\nEine Zahl als Befehl startet den Webserver: `total5 8000` ist `total5 server 8000`. Das aktuelle Verzeichnis ist der öffentliche Ordner, Minifizierung und Source Maps sind aus, und die Ordner der Anwendung werden nicht geladen. Eine Verzeichnis-URL zeigt eine Auflistung des Verzeichnisses. Das Programm gibt die Startinformationen des Frameworks aus und läuft, bis du es stoppst.\n\nExample: Einen Ordner ausliefern\n```bash\ncd ~/projects/landing\ntotal5 8000\n# open http://127.0.0.1:8000/\n```\n\n### total5 proxy <endpoint> <port>\n\nType: `command` · Since: `0.0.17`\n\nVerbindet einen lokalen Port mit einem entfernten Total.js-Proxyserver.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | yes |  | Die WebSocket-Adresse des Proxyservers. |\n| `port` | `String` | yes |  | Ein lokaler Port (auf `127.0.0.1`) oder ein Paar `ip:port`. |\n\nÖffnet einen WebSocket zum Proxy-Server, einer Anwendung, die `PROXYSERVER()` aufruft (`http` und `https` werden durch `ws` und `wss` ersetzt), und leitet jede Anfrage, die darüber eintrifft, an die lokale Adresse weiter. Die Antwort geht denselben Weg zurück. Das Programm gibt eine Zeile aus, wenn es sich verbindet oder trennt, und eine Zeile für jede Anfrage mit ihrer Methode, der IP-Adresse des Besuchers und der URL. Ohne beide Argumente gibt es `client [WSS proxy server] [port or ip:port]` aus. Es ist derselbe Client wie die Funktion `PROXYCLIENT()`.\n\nExample: Einen lokalen Server freigeben\n```bash\ntotal5 proxy wss://proxy.example.com/ 8000\n```\n\nExample: Die Serverseite\n```js\n// index.js of the proxy server\nrequire('total5');\nPROXYSERVER('/', '/proxy/');\nF.http({ port: 8000, load: 'none' });\n\n// on your machine:\n// total5 proxy wss://proxy.example.com/proxy/ 8000\n```\n\n### total5 server [port]\n\nType: `command`\n\nStartet einen statischen Webserver für das aktuelle Verzeichnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `8000` | Der Port des Servers. |\n\nDie lange Form von `total5 <port>`. Ohne Port lauscht er auf `8000`.\n\nExample: Standardport\n```bash\ntotal5 server\n# http://0.0.0.0:8000/\n```\n\nExample: Ein anderer Port\n```bash\ntotal5 server 8080\n```\n\n### total5 test [name1] [name2] [...]\n\nType: `command`\n\nFührt die Unit-Tests des aktuellen Verzeichnisses aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Der Name eines Testskripts ohne `.js`; mehrere Namen durch Leerzeichen oder Kommas getrennt. |\n\nNimmt das Verzeichnis `tests` des aktuellen Verzeichnisses oder das aktuelle Verzeichnis, wenn es kein Verzeichnis `tests` gibt. Es lädt die Datei `config` dieses Verzeichnisses mit `LOADCONFIG()`, erstellt das globale `Test`, lädt `init.js`, wenn es existiert, und dann die genannten Skripte in ihrer Reihenfolge oder, wenn kein Name angegeben ist, jede `.js`-Datei außer `init.js` in alphabetischer Reihenfolge. Danach ruft es `Test.run()` auf. Namen können durch Leerzeichen oder Kommas getrennt werden, und die Endung `.js` ist optional. Ein fehlendes Skript gibt `ERROR: the test \"name\" not found (path)` aus und endet mit Exit-Code 1. Der Exit-Code ist 0, wenn alle Gruppen fertig sind, und 1, wenn eine Prüfung fehlschlägt oder der Lauf vor dem Ende stoppt. Der Befehl verwendet das Paket `total5`, das im aktuellen Verzeichnis oder in einem übergeordneten Verzeichnis installiert ist (daher läuft er auch aus `tests`), sonst sein eigenes Paket. Die Anwendung selbst wird nicht gestartet, und das aktuelle Verzeichnis ist die Wurzel (`PATH.root()`). Siehe [Unit-Tests](../../guides/unit-tests/).\n\nExample: Alle Tests\n```bash\ncd ~/projects/shop\ntotal5 test\n```\n\nExample: Zwei Skripte\n```bash\ntotal5 test strings orders\ntotal5 test strings,orders\n```\n\n### flow5\n\nType: `command`\n\nGibt die Hilfe der Flow-Engine aus.\n\nOhne Argumente gibt `flow5` den Text `[Total.js v5 Flow Engine]` und die Aufrufmöglichkeiten aus.\n\nExample: Hilfe\n```bash\nflow5\n# flow5 [path or URL address] [PORT_NUMBER]\n# flow5 path/to/flowschema.json\n# flow5 flow1.json flow2.json flowN.json 8001\n# flow5 https://yourdomain.com/flowschema.json\n```\n\n### GET /{path}/\n\nType: `type`\n\nWas der Webserver für ein Verzeichnis anzeigt.\n\nFür eine Verzeichnis-URL zeigt der Server eine HTML-Seite mit einem Link `..` zum übergeordneten Verzeichnis (außer bei `/`), den Unterverzeichnissen und den Dateien mit ihren Größen. Jeder Link öffnet das Element auf demselben Server; öffne `index.html` aus der Auflistung wie jede andere Datei.\n\nExample: Durchsuchen\n```bash\ntotal5 8000\n# http://127.0.0.1:8000/            -> the listing of the directory\n# http://127.0.0.1:8000/index.html  -> the page\n```\n\n### total5 translate <filename>\n\nType: `command`\n\nSammelt die @(...)-Texte des aktuellen Verzeichnisses in einer Ressourcendatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der vollständige Pfad der zu schreibenden Ressourcendatei. |\n\nLiest jede `.js`- und `.html`-Datei des aktuellen Verzeichnisses und all seiner Unterverzeichnisse, findet die als `@(text)` geschriebenen Texte (verschachtelte Klammern bleiben erhalten) und schreibt sie in die Ressourcendatei, eine Zeile `KEY : text` pro Text. Derselbe Text ergibt eine Zeile. Eine vorhandene Datei wird überschrieben. Gib den vollständigen Pfad der Datei an.\n\nExample: In resources\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n### flow5 <file> [port]\n\nType: `command`\n\nFührt die Flows einer lokalen Schemadatei aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Der vollständige Pfad der Schema-Datei. |\n| `port` | `Number` | no | `8000` | Der Port des HTTP-Servers. |\n\nLädt das FlowStream-Schema der Datei und führt es aus. Der HTTP-Server startet, wenn mindestens ein Flow geladen ist. Für jeden Flow gibt das Programm einen Link zum Flow-Editor aus. Wird der Flow im Editor gespeichert, wird die Datei erneut als mit Tabs eingerücktes JSON geschrieben. Eine Datei, die kein gültiges JSON ist, gibt `ERROR: invalid meta - <path>` aus und wird übersprungen. Gib den vollständigen Pfad der Datei an.\n\nExample: Eine Datei\n```bash\nflow5 \"$PWD/flowschema.json\"\n# |--- http://127.0.0.1:8000\n# |--- Orders: https://flow.totaljs.com/?socket=...\n```\n\n### flow5 <url> [port]\n\nType: `command`\n\nFührt die Flows eines von einer https-Adresse heruntergeladenen Schemas aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die `https://`-Adresse des Schemas. |\n| `port` | `Number` | no | `8000` | Der Port des HTTP-Servers. |\n\nEin Argument, das mit `https://` beginnt, wird mit einer `GET`-Anfrage heruntergeladen und wie eine Datei geladen. Das Zertifikat des Servers wird geprüft. Im Editor vorgenommene Änderungen werden für diese Flows nirgends gespeichert.\n\nExample: Entferntes Schema\n```bash\nflow5 https://example.com/flowschema.json 8001\n```\n\n### KEY : text\n\nType: `type`\n\nDie Datei, die total5 translate schreibt.\n\nEine einfache Textdatei mit einer Zeile pro Text: der Schlüssel, auf 12 Zeichen aufgefüllt, dann ` : ` und der Text. Der Schlüssel ist `T`, gefolgt von einem Hash des Textes in Base 36, der Schlüssel, den die View-Engine für `@(text)` nachschlägt. Lege eine übersetzte Kopie in `resources/` ab (zum Beispiel `resources/sk.resource`) und übersetze die rechte Seite. Siehe [Lokalisierung](../../guides/localization/).\n\nExample: Inhalt\n```text\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\n### flow5 <files...> <port>\n\nType: `command`\n\nLegt den Port der Flow-Engine fest und führt mehrere Schemas gleichzeitig aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String` | yes |  | Eine oder mehrere Schemadateien oder Adressen. |\n| `port` | `Number` | no | `8000` | Der Port des HTTP-Servers. |\n\nArgumente können in beliebiger Reihenfolge kommen. Jedes Argument, das nur aus Ziffern besteht, ist der Port (das letzte gewinnt); jedes andere ist eine Schema-Datei, mit ihrem vollständigen Pfad, oder eine `https://`-Adresse. Alle Flows aller Quellen laufen in einem Prozess auf diesem Port.\n\nExample: Mehrere Dateien\n```bash\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\n```\n\n### total5 bundle <filename>\n\nType: `command`\n\nPackt das aktuelle Verzeichnis in eine Bundle-Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der vollständige Pfad der Bundle-Datei. |\n\nSchreibt die Dateien des aktuellen Verzeichnisses und seiner Unterverzeichnisse in eine `.bundle`-Datei. `.bundle` wird an den Namen angehängt, wenn es fehlt. Die Dateien des Rechners werden weggelassen (siehe Inhalt des Bundles). Gib den vollständigen Pfad des Bundles an, außerhalb des Verzeichnisses, das du packst. Das Framework entpackt beim Start die Bundles aus `bundles/`.\n\nExample: Ein Projekt packen\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop\n# ~/backups/shop.bundle\n```\n\n### { id, name, components, design } | { <id>: schema }\n\nType: `type`\n\nDie zwei Formen einer Datei, die flow5 liest.\n\nEine Datei mit **einem Flow** ist ein Objekt mit `components` und `design` (sowie `id`, `name` und den anderen Feldern eines FlowStream-Schemas). Eine Datei mit **mehreren Flows** ist ein Objekt, dessen Schlüssel die IDs der Flows sind; ein Schlüssel `variables` wird übersprungen. Ein Flow ohne `id` erhält eine aus dem Pfad gebildete ID. Um Änderungen zurück in die Datei zu speichern, gib dem Flow eine `id`, und verwende in einer Datei mit mehreren Flows die ID als seinen Schlüssel.\n\nExample: Ein Flow\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {},\n\t\"design\": {}\n}\n```\n\nExample: Mehrere Flows\n```json\n{\n\t\"orders\": { \"id\": \"orders\", \"name\": \"Orders\", \"components\": {}, \"design\": {} },\n\t\"mail\": { \"id\": \"mail\", \"name\": \"Mail\", \"components\": {}, \"design\": {} }\n}\n```\n\n### .bundle\n\nType: `type`\n\nWelche Dateien total5 bundle in ein Bundle aufnimmt.\n\nAlle Dateien des Verzeichnisses außer: `/index.js`, `/debug.js`, `/release.js` mit ihren `.json`- und `.pid`-Dateien, `/bundle.json`, `/package.json`, `/readme.md`, `/license.txt` und die Ordner `/bundles/`, `/tmp/`, `/.src/` und `/.git/`.\n\nExample: Mit einem Bundle ausrollen\n```bash\ntotal5 bundle ~/backups/shop\nscp ~/backups/shop.bundle server:/www/shop/bundles/\n```\n\n### GET|POST /notify/{id}/\n\nType: `property`\n\nDie Benachrichtigungsroute der Flow-Engine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | `<flow id>-<instance id>[-param...]`. |\n\nSendet eine Benachrichtigung an eine Komponenteninstanz eines laufenden Flows. Die ID ist `<flow id>-<instance id>`; weitere durch `-` getrennte Teile kommen als `params` an. Die Komponente erhält Methode, Header, Query, Body (bis zu 1 MB), URL und IP-Adresse. Ein Query-Wert `REDIRECT` leitet den Besucher weiter; ein Browser erhält eine Seite, die sich selbst schließt, andere Clients erhalten eine Erfolgsantwort. Siehe [FlowStream](../../guides/flowstream/).\n\nExample: Eine Komponente benachrichtigen\n```bash\ncurl -X POST -d '{\"paid\":true}' -H \"Content-Type: application/json\" http://127.0.0.1:8000/notify/orders-c1x8a/\n```\n\n### total5 extract <filename>\n\nType: `command`\n\nEntpackt ein Bundle in das aktuelle Verzeichnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der vollständige Pfad der zu entpackenden Bundle-Datei. |\n\nStellt alle Dateien des Bundles mit ihren Unterverzeichnissen im aktuellen Verzeichnis wieder her. Vorhandene Dateien mit denselben Namen werden überschrieben. Wenn das Argument ein Verzeichnis ist, passiert nichts. Gib den vollständigen Pfad der Datei an.\n\nExample: Entpacken\n```bash\nmkdir shop-copy && cd shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n### SOCKET /flowstreams/{id}/\n\nType: `property`\n\nDer WebSocket des Flow-Editors.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID des Flows. |\n\nDer Flow-Editor verbindet sich hier, um den Flow mit der angegebenen ID anzuzeigen und zu ändern (Nachrichten bis zu 8 MB). Der Link, den `flow5` für jeden Flow ausgibt, öffnet `https://flow.totaljs.com/?socket=` mit dieser Adresse.\n\nExample: Den Editor öffnen\n```text\nhttps://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n","entries":[{"type":"command","name":"total5","signature":"total5 [command] [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 help","signature":"total5 help","since":"","deprecated":false},{"type":"command","name":"total5 --command","signature":"total5 --<command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 minify","signature":"total5 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total5 edit","signature":"total5 edit <url>","since":"","deprecated":false},{"type":"type","name":"Code Editor requests","signature":"TYPE: browse | load | save | ...","since":"","deprecated":false},{"type":"command","name":"total5 <port>","signature":"total5 <port>","since":"","deprecated":false},{"type":"command","name":"total5 proxy","signature":"total5 proxy <endpoint> <port>","since":"0.0.17","deprecated":false},{"type":"command","name":"total5 server","signature":"total5 server [port]","since":"","deprecated":false},{"type":"command","name":"total5 test","signature":"total5 test [name1] [name2] [...]","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5","since":"","deprecated":false},{"type":"type","name":"Directory listing","signature":"GET /{path}/","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate <filename>","since":"","deprecated":false},{"type":"command","name":"flow5 <file>","signature":"flow5 <file> [port]","since":"","deprecated":false},{"type":"command","name":"flow5 <url>","signature":"flow5 <url> [port]","since":"","deprecated":false},{"type":"type","name":"Resource file","signature":"KEY : text","since":"","deprecated":false},{"type":"command","name":"flow5 <port>","signature":"flow5 <files...> <port>","since":"","deprecated":false},{"type":"command","name":"total5 bundle","signature":"total5 bundle <filename>","since":"","deprecated":false},{"type":"type","name":"Flow schema file","signature":"{ id, name, components, design } | { <id>: schema }","since":"","deprecated":false},{"type":"type","name":"Bundle content","signature":".bundle","since":"","deprecated":false},{"type":"property","name":"flow5 /notify/{id}/","signature":"GET|POST /notify/{id}/","since":"","deprecated":false},{"type":"command","name":"total5 extract","signature":"total5 extract <filename>","since":"","deprecated":false},{"type":"property","name":"flow5 /flowstreams/{id}/","signature":"SOCKET /flowstreams/{id}/","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwUK9Zx60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/command-line/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"es","title":"Línea de comandos (total5)","summary":"Todos los comandos y argumentos de los programas total5 y flow5.","markdown":"---\ntitle: \"Línea de comandos (total5)\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/reference/command-line/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Línea de comandos (total5)\n\n> Todos los comandos y argumentos de los programas total5 y flow5.\n\nLos comandos de los dos programas que instala el paquete `total5`: `total5`, que trabaja sobre el directorio actual, y `flow5`, que ejecuta esquemas FlowStream. Cada entrada muestra la sintaxis, los argumentos y un ejemplo. Para una introducción lee [Línea de comandos (total5)](../../guides/command-line/).\n\n```bash\nnpm install -g total5\ntotal5 help\nflow5\n```\n\n## API\n\n### total5 [command] [arguments]\n\nType: `command`\n\nLa caja de herramientas de línea de comandos del paquete total5.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | no | `help` | El nombre del comando. |\n| `arguments` | `String` | no |  | Los argumentos del comando, en orden. |\n\nEjecuta un comando sobre el directorio actual. Sin comando muestra la ayuda. Cada comando imprime primero `* Total.js v5: [Command]`; los cortos terminan con una línea `[Done]` con el tiempo que tardaron. Un comando que el programa no conoce imprime solo esa cabecera.\n\nExample: Mostrar la ayuda\n```bash\ntotal5\n```\n\n### total5 help\n\nType: `command`\n\nImprime la lista de comandos.\n\nImprime una línea por cada comando con sus argumentos y lo que hace: `translate`, `minify`, `bundle`, `extract`, `edit`, `proxy`, `test` y el servidor web (`8000`). `total5` sin comando hace lo mismo.\n\nExample: Ayuda\n```bash\ntotal5 help\ntotal5 --help\n```\n\n### total5 --<command> [arguments]\n\nType: `command`\n\nLos guiones delante de un comando se ignoran.\n\nEl programa elimina del comando cada secuencia de dos o más guiones, así que `--help` es `help` y `--minify` es `minify`. Usa la forma que prefieras.\n\nExample: El mismo comando dos veces\n```bash\ntotal5 --help\ntotal5 help\n```\n\n### total5 minify <filename>\n\nType: `command`\n\nMinifica un archivo JavaScript, CSS o HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | La ruta completa del archivo que minificar. |\n\nLee el archivo, lo minifica según su extensión y escribe el resultado a su lado como `name.min.ext`. JavaScript y CSS se minifican por completo. El minificador de HTML elimina los comentarios, acorta las secuencias de espacios dentro del marcado y minifica los bloques `<script>` y `<style>` en línea; conserva los saltos de línea y la sangría entre etiquetas. Un archivo con otra extensión se copia sin cambios. Imprime los nombres de los archivos de entrada y de salida. Indica la ruta completa del archivo.\n\nExample: Minificar un script\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"\n# Output    : /home/me/shop/public/js/app.min.js\n```\n\n### total5 edit <url>\n\nType: `command`\n\nAbre el directorio actual para edición remota en Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección del proyecto en Code Editor, por ejemplo `https://code.example.com/?id=project`. |\n\nSe conecta a la URL del proyecto con un WebSocket (`http` y `https` pasan a `ws` y `wss`) y atiende las peticiones del editor sobre el directorio actual (consulta Peticiones de Code Editor). Cuando el editor acepta la conexión, imprime una bienvenida con el nombre del editor y del proyecto. La conexión se reconecta cada 10 segundos y recibe un ping cada 30 segundos. Se imprimen `404 project not found` y `409 project is already open` cuando el editor rechaza el proyecto. Sin URL, el programa lanza `Invalid URL address`.\n\nExample: Editar un proyecto\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n```\n\n### TYPE: browse | load | save | ...\n\nType: `type`\n\nLo que puede hacer Code Editor mediante total5 edit.\n\nEl editor envía peticiones y el programa las responde dentro del directorio actual: `browse` (la lista de archivos y carpetas), `load`, `save`, `create`, `remove`, `rename`, `modify`, `info`, `upload`, `download`, `send`, `import`, `log` y `logclear` (archivos de log), `wiki`, `ip` (la dirección IP pública), `exec` (ejecuta un archivo: los archivos `.js` con Node.js, los archivos `.sh` con `sh`, o un comando que envía el editor), `restart` y `ping`. A una petición desconocida se responde con un error 400.\n\nExample: Una petición y su respuesta\n```js\n// sent by the editor\n{ TYPE: 'browse', data: '{}' }\n// answer\n{ TYPE: 'browse', data: '{}', success: true, response: { files: ['/index.js'], directories: ['/controllers/'] } }\n```\n\n### total5 <port>\n\nType: `command`\n\nInicia un servidor web estático para el directorio actual en el puerto indicado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | El puerto del servidor. |\n\nUn número como comando inicia el servidor web: `total5 8000` es `total5 server 8000`. El directorio actual es la carpeta pública, la minificación y los source maps están desactivados, y las carpetas de la aplicación no se cargan. La URL de un directorio muestra un listado del directorio. El programa imprime la información de inicio del framework y se ejecuta hasta que lo detienes.\n\nExample: Servir una carpeta\n```bash\ncd ~/projects/landing\ntotal5 8000\n# open http://127.0.0.1:8000/\n```\n\n### total5 proxy <endpoint> <port>\n\nType: `command` · Since: `0.0.17`\n\nConecta un puerto local a un servidor proxy remoto de Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | yes |  | La dirección WebSocket del servidor proxy. |\n| `port` | `String` | yes |  | Un puerto local (en `127.0.0.1`) o un par `ip:port`. |\n\nAbre un WebSocket hacia el servidor proxy, una aplicación que llama a `PROXYSERVER()` (`http` y `https` se reemplazan por `ws` y `wss`), y reenvía a la dirección local cada petición que llega a través de él. La respuesta vuelve por el mismo camino. El programa imprime una línea cuando se conecta o desconecta y una línea por cada petición con su método, la dirección IP del visitante y la URL. Sin ambos argumentos imprime `client [WSS proxy server] [port or ip:port]`. Es el mismo cliente que la función `PROXYCLIENT()`.\n\nExample: Compartir un servidor local\n```bash\ntotal5 proxy wss://proxy.example.com/ 8000\n```\n\nExample: El lado del servidor\n```js\n// index.js of the proxy server\nrequire('total5');\nPROXYSERVER('/', '/proxy/');\nF.http({ port: 8000, load: 'none' });\n\n// on your machine:\n// total5 proxy wss://proxy.example.com/proxy/ 8000\n```\n\n### total5 server [port]\n\nType: `command`\n\nInicia un servidor web estático para el directorio actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `8000` | El puerto del servidor. |\n\nLa forma larga de `total5 <port>`. Sin puerto escucha en `8000`.\n\nExample: Puerto por defecto\n```bash\ntotal5 server\n# http://0.0.0.0:8000/\n```\n\nExample: Otro puerto\n```bash\ntotal5 server 8080\n```\n\n### total5 test [name1] [name2] [...]\n\nType: `command`\n\nEjecuta los tests unitarios del directorio actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | El nombre de un script de test sin `.js`; varios nombres con espacios o comas. |\n\nToma el directorio `tests` del directorio actual, o el directorio actual cuando no hay directorio `tests`. Carga el archivo `config` de ese directorio con `LOADCONFIG()`, crea el `Test` global, carga `init.js` cuando existe y después los scripts indicados en su orden, o todos los archivos `.js` excepto `init.js` en orden alfabético cuando no se indica ningún nombre. Después llama a `Test.run()`. Los nombres se pueden separar con espacios o comas y la extensión `.js` es opcional. Un script que falta imprime `ERROR: the test \"name\" not found (path)` y termina con el código de salida 1. El código de salida es 0 cuando todos los grupos han terminado y 1 cuando falla una comprobación o la ejecución se detiene antes del final. El comando usa el paquete `total5` instalado en el directorio actual o en un directorio padre (así que también funciona desde `tests`); si no, su propio paquete. La aplicación en sí no se arranca y el directorio actual es la raíz (`PATH.root()`). Consulta [Tests unitarios](../../guides/unit-tests/).\n\nExample: Todos los tests\n```bash\ncd ~/projects/shop\ntotal5 test\n```\n\nExample: Dos scripts\n```bash\ntotal5 test strings orders\ntotal5 test strings,orders\n```\n\n### flow5\n\nType: `command`\n\nImprime la ayuda del motor Flow.\n\nSin argumentos, `flow5` imprime `[Total.js v5 Flow Engine]` y las formas de llamarlo.\n\nExample: Ayuda\n```bash\nflow5\n# flow5 [path or URL address] [PORT_NUMBER]\n# flow5 path/to/flowschema.json\n# flow5 flow1.json flow2.json flowN.json 8001\n# flow5 https://yourdomain.com/flowschema.json\n```\n\n### GET /{path}/\n\nType: `type`\n\nLo que muestra el servidor web para un directorio.\n\nPara la URL de un directorio, el servidor muestra una página HTML con un enlace `..` al directorio padre (excepto en `/`), los subdirectorios y los archivos con sus tamaños. Cada enlace abre el elemento en el mismo servidor; abre `index.html` desde el listado como cualquier otro archivo.\n\nExample: Explorar\n```bash\ntotal5 8000\n# http://127.0.0.1:8000/            -> the listing of the directory\n# http://127.0.0.1:8000/index.html  -> the page\n```\n\n### total5 translate <filename>\n\nType: `command`\n\nReúne los textos @(...) del directorio actual en un archivo de recursos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | La ruta completa del archivo de recursos que se escribe. |\n\nLee cada archivo `.js` y `.html` del directorio actual y de todos sus subdirectorios, encuentra los textos escritos como `@(text)` (se conservan los paréntesis anidados) y los escribe en el archivo de recursos, una línea `KEY : text` por cada texto. Un mismo texto da una sola línea. Un archivo existente se sobrescribe. Indica la ruta completa del archivo.\n\nExample: En resources\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n### flow5 <file> [port]\n\nType: `command`\n\nEjecuta los flujos de un archivo de esquema local.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | La ruta completa del archivo de esquema. |\n| `port` | `Number` | no | `8000` | El puerto del servidor HTTP. |\n\nCarga el esquema de FlowStream del archivo y lo ejecuta. El servidor HTTP se inicia cuando se carga al menos un flujo. Para cada flujo el programa imprime un enlace al editor Flow. Cuando el flujo se guarda en el editor, el archivo se vuelve a escribir como JSON indentado con tabuladores. Un archivo que no es JSON válido imprime `ERROR: invalid meta - <path>` y se omite. Indica la ruta completa del archivo.\n\nExample: Un archivo\n```bash\nflow5 \"$PWD/flowschema.json\"\n# |--- http://127.0.0.1:8000\n# |--- Orders: https://flow.totaljs.com/?socket=...\n```\n\n### flow5 <url> [port]\n\nType: `command`\n\nEjecuta los flujos de un esquema descargado de una dirección https.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección `https://` del esquema. |\n| `port` | `Number` | no | `8000` | El puerto del servidor HTTP. |\n\nUn argumento que empieza por `https://` se descarga con una petición `GET` y se carga como un archivo. Se comprueba el certificado del servidor. Los cambios hechos en el editor no se guardan en ningún sitio para estos flujos.\n\nExample: Esquema remoto\n```bash\nflow5 https://example.com/flowschema.json 8001\n```\n\n### KEY : text\n\nType: `type`\n\nEl archivo que escribe total5 translate.\n\nUn archivo de texto plano con una línea por cada texto: la clave, rellenada hasta 12 caracteres, luego ` : ` y el texto. La clave es `T` seguida de un hash del texto en base 36, la clave que busca el motor de vistas para `@(text)`. Pon una copia traducida en `resources/` (por ejemplo `resources/sk.resource`) y traduce el lado derecho. Consulta [Localización](../../guides/localization/).\n\nExample: Contenido\n```text\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\n### flow5 <files...> <port>\n\nType: `command`\n\nDefine el puerto del motor Flow y ejecuta varios esquemas a la vez.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String` | yes |  | Uno o más archivos o direcciones de esquemas. |\n| `port` | `Number` | no | `8000` | El puerto del servidor HTTP. |\n\nLos argumentos pueden ir en cualquier orden. Cada argumento formado solo por dígitos es el puerto (gana el último); cualquier otro es un archivo de esquema, con su ruta completa, o una dirección `https://`. Todos los flujos de todas las fuentes se ejecutan en un proceso en ese puerto.\n\nExample: Varios archivos\n```bash\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\n```\n\n### total5 bundle <filename>\n\nType: `command`\n\nEmpaqueta el directorio actual en un archivo bundle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | La ruta completa del archivo bundle. |\n\nEscribe los archivos del directorio actual y de sus subdirectorios en un único archivo `.bundle`. Se añade `.bundle` al nombre si falta. Los archivos de la máquina se excluyen (consulta Contenido del bundle). Indica la ruta completa del bundle, fuera del directorio que empaquetas. El framework desempaqueta los bundles de `bundles/` al arrancar.\n\nExample: Empaquetar un proyecto\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop\n# ~/backups/shop.bundle\n```\n\n### { id, name, components, design } | { <id>: schema }\n\nType: `type`\n\nLas dos formas de un archivo que lee flow5.\n\nUn archivo con **un flujo** es un objeto con `components` y `design` (y `id`, `name` y los demás campos de un esquema FlowStream). Un archivo con **varios flujos** es un objeto cuyas claves son los ids de los flujos; se omite una clave `variables`. Un flujo sin `id` recibe un id formado a partir de la ruta. Para guardar los cambios de vuelta en el archivo, da al flujo un `id`, y en un archivo con varios flujos usa el id como su clave.\n\nExample: Un flujo\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {},\n\t\"design\": {}\n}\n```\n\nExample: Varios flujos\n```json\n{\n\t\"orders\": { \"id\": \"orders\", \"name\": \"Orders\", \"components\": {}, \"design\": {} },\n\t\"mail\": { \"id\": \"mail\", \"name\": \"Mail\", \"components\": {}, \"design\": {} }\n}\n```\n\n### .bundle\n\nType: `type`\n\nQué archivos pone total5 bundle en un bundle.\n\nTodos los archivos del directorio, excepto: `/index.js`, `/debug.js`, `/release.js` con sus archivos `.json` y `.pid`, `/bundle.json`, `/package.json`, `/readme.md`, `/license.txt` y las carpetas `/bundles/`, `/tmp/`, `/.src/` y `/.git/`.\n\nExample: Desplegar con un bundle\n```bash\ntotal5 bundle ~/backups/shop\nscp ~/backups/shop.bundle server:/www/shop/bundles/\n```\n\n### GET|POST /notify/{id}/\n\nType: `property`\n\nLa ruta de notificaciones del motor Flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | `<flow id>-<instance id>[-param...]`. |\n\nEnvía una notificación a una instancia de componente de un flujo en ejecución. El id es `<flow id>-<instance id>`; las partes adicionales separadas con `-` llegan como `params`. El componente recibe el método, las cabeceras, la query, el cuerpo (hasta 1 MB), la URL y la dirección IP. Un valor `REDIRECT` en la query redirige al visitante; un navegador recibe una página que se cierra sola, los demás clientes reciben una respuesta de éxito. Consulta [FlowStream](../../guides/flowstream/).\n\nExample: Notificar a un componente\n```bash\ncurl -X POST -d '{\"paid\":true}' -H \"Content-Type: application/json\" http://127.0.0.1:8000/notify/orders-c1x8a/\n```\n\n### total5 extract <filename>\n\nType: `command`\n\nDesempaqueta un bundle en el directorio actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | La ruta completa del archivo bundle que se desempaqueta. |\n\nRestaura todos los archivos del bundle en el directorio actual, con sus subdirectorios. Los archivos existentes con los mismos nombres se sobrescriben. Cuando el argumento es un directorio, no ocurre nada. Indica la ruta completa del archivo.\n\nExample: Desempaquetar\n```bash\nmkdir shop-copy && cd shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n### SOCKET /flowstreams/{id}/\n\nType: `property`\n\nEl WebSocket del editor Flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del flujo. |\n\nEl editor Flow se conecta aquí para mostrar y modificar el flujo con el id indicado (mensajes de hasta 8 MB). El enlace que `flow5` imprime para cada flujo abre `https://flow.totaljs.com/?socket=` con esta dirección.\n\nExample: Abrir el editor\n```text\nhttps://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n","entries":[{"type":"command","name":"total5","signature":"total5 [command] [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 help","signature":"total5 help","since":"","deprecated":false},{"type":"command","name":"total5 --command","signature":"total5 --<command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 minify","signature":"total5 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total5 edit","signature":"total5 edit <url>","since":"","deprecated":false},{"type":"type","name":"Code Editor requests","signature":"TYPE: browse | load | save | ...","since":"","deprecated":false},{"type":"command","name":"total5 <port>","signature":"total5 <port>","since":"","deprecated":false},{"type":"command","name":"total5 proxy","signature":"total5 proxy <endpoint> <port>","since":"0.0.17","deprecated":false},{"type":"command","name":"total5 server","signature":"total5 server [port]","since":"","deprecated":false},{"type":"command","name":"total5 test","signature":"total5 test [name1] [name2] [...]","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5","since":"","deprecated":false},{"type":"type","name":"Directory listing","signature":"GET /{path}/","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate <filename>","since":"","deprecated":false},{"type":"command","name":"flow5 <file>","signature":"flow5 <file> [port]","since":"","deprecated":false},{"type":"command","name":"flow5 <url>","signature":"flow5 <url> [port]","since":"","deprecated":false},{"type":"type","name":"Resource file","signature":"KEY : text","since":"","deprecated":false},{"type":"command","name":"flow5 <port>","signature":"flow5 <files...> <port>","since":"","deprecated":false},{"type":"command","name":"total5 bundle","signature":"total5 bundle <filename>","since":"","deprecated":false},{"type":"type","name":"Flow schema file","signature":"{ id, name, components, design } | { <id>: schema }","since":"","deprecated":false},{"type":"type","name":"Bundle content","signature":".bundle","since":"","deprecated":false},{"type":"property","name":"flow5 /notify/{id}/","signature":"GET|POST /notify/{id}/","since":"","deprecated":false},{"type":"command","name":"total5 extract","signature":"total5 extract <filename>","since":"","deprecated":false},{"type":"property","name":"flow5 /flowstreams/{id}/","signature":"SOCKET /flowstreams/{id}/","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwUK9Zx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/command-line/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"fr","title":"Ligne de commande (total5)","summary":"Chaque commande et chaque argument des programmes total5 et flow5.","markdown":"---\ntitle: Ligne de commande (total5)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/reference/command-line/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Ligne de commande (total5)\n\n> Chaque commande et chaque argument des programmes total5 et flow5.\n\nLes commandes des deux programmes que le paquet `total5` installe : `total5`, qui travaille sur le répertoire courant, et `flow5`, qui exécute des schémas FlowStream. Chaque entrée présente la syntaxe, les arguments et un exemple. Pour une introduction, lis [Ligne de commande (total5)](../../guides/command-line/).\n\n```bash\nnpm install -g total5\ntotal5 help\nflow5\n```\n\n## API\n\n### total5 [command] [arguments]\n\nType: `command`\n\nLa boîte à outils en ligne de commande du paquet total5.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | no | `help` | Le nom de la commande. |\n| `arguments` | `String` | no |  | Les arguments de la commande, dans l'ordre. |\n\nExécute une commande sur le répertoire courant. Sans commande, elle affiche l'aide. Chaque commande affiche d'abord `* Total.js v5: [Command]` ; les commandes courtes se terminent par une ligne `[Done]` avec leur durée. Une commande que le programme ne connaît pas affiche seulement cet en-tête.\n\nExample: Afficher l'aide\n```bash\ntotal5\n```\n\n### total5 help\n\nType: `command`\n\nAffiche la liste des commandes.\n\nAffiche une ligne pour chaque commande avec ses arguments et ce qu'elle fait : `translate`, `minify`, `bundle`, `extract`, `edit`, `proxy`, `test` et le serveur web (`8000`). `total5` sans commande fait de même.\n\nExample: Aide\n```bash\ntotal5 help\ntotal5 --help\n```\n\n### total5 --<command> [arguments]\n\nType: `command`\n\nLes tirets devant une commande sont ignorés.\n\nLe programme supprime de la commande chaque suite de deux tirets ou plus, donc `--help` équivaut à `help` et `--minify` à `minify`. Utilise la forme que tu préfères.\n\nExample: La même commande deux fois\n```bash\ntotal5 --help\ntotal5 help\n```\n\n### total5 minify <filename>\n\nType: `command`\n\nMinifie un fichier JavaScript, CSS ou HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le chemin complet du fichier à minifier. |\n\nLit le fichier, le minifie selon son extension et écrit le résultat à côté de lui sous `name.min.ext`. JavaScript et CSS sont entièrement minifiés. Le minificateur HTML retire les commentaires, réduit les suites d'espaces dans le balisage et minifie les blocs `<script>` et `<style>` inline ; il conserve les retours à la ligne et l'indentation entre les balises. Un fichier avec une autre extension est copié sans modification. Il affiche les noms des fichiers d'entrée et de sortie. Indique le chemin complet du fichier.\n\nExample: Minifier un script\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"\n# Output    : /home/me/shop/public/js/app.min.js\n```\n\n### total5 edit <url>\n\nType: `command`\n\nOuvre le répertoire courant pour l'édition à distance dans le Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse du projet dans le Code Editor, par exemple `https://code.example.com/?id=project`. |\n\nSe connecte à l'URL du projet avec un WebSocket (`http` et `https` deviennent `ws` et `wss`) et sert les requêtes de l'éditeur sur le répertoire courant (consulte Requêtes du Code Editor). Quand l'éditeur accepte la connexion, il affiche un message de bienvenue avec le nom de l'éditeur et du projet. La connexion se rétablit toutes les 10 secondes et reçoit un ping toutes les 30 secondes. `404 project not found` et `409 project is already open` sont affichés quand l'éditeur refuse le projet. Sans URL, le programme lève `Invalid URL address`.\n\nExample: Éditer un projet\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n```\n\n### TYPE: browse | load | save | ...\n\nType: `type`\n\nCe que le Code Editor peut faire via total5 edit.\n\nL'éditeur envoie des requêtes et le programme y répond à l'intérieur du répertoire courant : `browse` (la liste des fichiers et des dossiers), `load`, `save`, `create`, `remove`, `rename`, `modify`, `info`, `upload`, `download`, `send`, `import`, `log` et `logclear` (fichiers de log), `wiki`, `ip` (l'adresse IP publique), `exec` (exécute un fichier : les fichiers `.js` avec Node.js, les fichiers `.sh` avec `sh`, ou une commande envoyée par l'éditeur), `restart` et `ping`. Une requête inconnue reçoit en réponse une erreur 400.\n\nExample: Une requête et sa réponse\n```js\n// sent by the editor\n{ TYPE: 'browse', data: '{}' }\n// answer\n{ TYPE: 'browse', data: '{}', success: true, response: { files: ['/index.js'], directories: ['/controllers/'] } }\n```\n\n### total5 <port>\n\nType: `command`\n\nDémarre un serveur web statique pour le répertoire courant sur le port indiqué.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | Le port du serveur. |\n\nUn nombre comme commande démarre le serveur web : `total5 8000` équivaut à `total5 server 8000`. Le répertoire courant est le dossier public, la minification et les source maps sont désactivées, et les dossiers de l'application ne sont pas chargés. L'URL d'un répertoire affiche la liste de son contenu. Le programme affiche les informations de démarrage du framework et tourne jusqu'à ce que tu l'arrêtes.\n\nExample: Servir un dossier\n```bash\ncd ~/projects/landing\ntotal5 8000\n# open http://127.0.0.1:8000/\n```\n\n### total5 proxy <endpoint> <port>\n\nType: `command` · Since: `0.0.17`\n\nConnecte un port local à un serveur proxy Total.js distant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | yes |  | L'adresse WebSocket du serveur proxy. |\n| `port` | `String` | yes |  | Un port local (sur `127.0.0.1`) ou une paire `ip:port`. |\n\nOuvre un WebSocket vers le serveur proxy, une application qui appelle `PROXYSERVER()` (`http` et `https` sont remplacés par `ws` et `wss`), et transmet à l'adresse locale chaque requête qui arrive par ce canal. La réponse repart par le même chemin. Le programme affiche une ligne lorsqu'il se connecte ou se déconnecte, et une ligne pour chaque requête avec sa méthode, l'adresse IP du visiteur et l'URL. Sans les deux arguments, il affiche `client [WSS proxy server] [port or ip:port]`. C'est le même client que la fonction `PROXYCLIENT()`.\n\nExample: Partager un serveur local\n```bash\ntotal5 proxy wss://proxy.example.com/ 8000\n```\n\nExample: Le côté serveur\n```js\n// index.js of the proxy server\nrequire('total5');\nPROXYSERVER('/', '/proxy/');\nF.http({ port: 8000, load: 'none' });\n\n// on your machine:\n// total5 proxy wss://proxy.example.com/proxy/ 8000\n```\n\n### total5 server [port]\n\nType: `command`\n\nDémarre un serveur web statique pour le répertoire courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `8000` | Le port du serveur. |\n\nLa forme longue de `total5 <port>`. Sans port, il écoute sur `8000`.\n\nExample: Port par défaut\n```bash\ntotal5 server\n# http://0.0.0.0:8000/\n```\n\nExample: Un autre port\n```bash\ntotal5 server 8080\n```\n\n### total5 test [name1] [name2] [...]\n\nType: `command`\n\nLance les tests unitaires du répertoire courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Le nom d'un script de test sans `.js` ; plusieurs noms séparés par des espaces ou des virgules. |\n\nPrend le répertoire `tests` du répertoire courant, ou le répertoire courant quand il n'y a pas de répertoire `tests`. Elle charge le fichier `config` de ce répertoire avec `LOADCONFIG()`, crée le `Test` global, charge `init.js` s'il existe, puis les scripts nommés dans leur ordre, ou chaque fichier `.js` sauf `init.js` dans l'ordre alphabétique quand aucun nom n'est donné. Ensuite elle appelle `Test.run()`. Les noms peuvent être séparés par des espaces ou des virgules et l'extension `.js` est facultative. Un script absent affiche `ERROR: the test \"name\" not found (path)` et se termine avec le code de sortie 1. Le code de sortie est 0 quand tous les groupes sont terminés et 1 quand une vérification échoue ou que l'exécution s'arrête avant la fin. La commande utilise le paquet `total5` installé dans le répertoire courant ou dans un répertoire parent (elle fonctionne donc aussi depuis `tests`), sinon son propre paquet. L'application elle-même n'est pas démarrée et le répertoire courant est la racine (`PATH.root()`). Voir [Tests unitaires](../../guides/unit-tests/).\n\nExample: Tous les tests\n```bash\ncd ~/projects/shop\ntotal5 test\n```\n\nExample: Deux scripts\n```bash\ntotal5 test strings orders\ntotal5 test strings,orders\n```\n\n### flow5\n\nType: `command`\n\nAffiche l'aide du moteur Flow.\n\nSans arguments, `flow5` affiche `[Total.js v5 Flow Engine]` et les façons de l'appeler.\n\nExample: Aide\n```bash\nflow5\n# flow5 [path or URL address] [PORT_NUMBER]\n# flow5 path/to/flowschema.json\n# flow5 flow1.json flow2.json flowN.json 8001\n# flow5 https://yourdomain.com/flowschema.json\n```\n\n### GET /{path}/\n\nType: `type`\n\nCe que le serveur web affiche pour un répertoire.\n\nPour l'URL d'un répertoire, le serveur affiche une page HTML avec un lien `..` vers le parent (sauf à `/`), les sous-répertoires et les fichiers avec leurs tailles. Chaque lien ouvre l'élément sur le même serveur ; ouvre `index.html` depuis la liste comme n'importe quel autre fichier.\n\nExample: Parcourir\n```bash\ntotal5 8000\n# http://127.0.0.1:8000/            -> the listing of the directory\n# http://127.0.0.1:8000/index.html  -> the page\n```\n\n### total5 translate <filename>\n\nType: `command`\n\nRassemble les textes @(...) du répertoire courant dans un fichier de ressources.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le chemin complet du fichier de ressources à écrire. |\n\nLit chaque fichier `.js` et `.html` du répertoire courant et de tous ses sous-répertoires, trouve les textes écrits sous la forme `@(text)` (les parenthèses imbriquées sont conservées) et les écrit dans le fichier de ressources, une ligne `KEY : text` par texte. Un même texte donne une seule ligne. Un fichier existant est écrasé. Indique le chemin complet du fichier.\n\nExample: Dans resources\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n### flow5 <file> [port]\n\nType: `command`\n\nExécute les flux d'un fichier de schéma local.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Le chemin complet du fichier de schéma. |\n| `port` | `Number` | no | `8000` | Le port du serveur HTTP. |\n\nCharge le schéma FlowStream du fichier et l'exécute. Le serveur HTTP démarre dès qu'au moins un flux est chargé. Pour chaque flux, le programme affiche un lien vers l'éditeur Flow. Lorsque le flux est enregistré dans l'éditeur, le fichier est réécrit en JSON indenté avec des tabulations. Un fichier qui n'est pas du JSON valide affiche `ERROR: invalid meta - <path>` et est ignoré. Indique le chemin complet du fichier.\n\nExample: Un fichier\n```bash\nflow5 \"$PWD/flowschema.json\"\n# |--- http://127.0.0.1:8000\n# |--- Orders: https://flow.totaljs.com/?socket=...\n```\n\n### flow5 <url> [port]\n\nType: `command`\n\nExécute les flux d'un schéma téléchargé depuis une adresse https.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse `https://` du schéma. |\n| `port` | `Number` | no | `8000` | Le port du serveur HTTP. |\n\nUn argument qui commence par `https://` est téléchargé avec une requête `GET` et chargé comme un fichier. Le certificat du serveur est vérifié. Pour ces flux, les modifications faites dans l'éditeur ne sont enregistrées nulle part.\n\nExample: Schéma distant\n```bash\nflow5 https://example.com/flowschema.json 8001\n```\n\n### KEY : text\n\nType: `type`\n\nLe fichier qu'écrit total5 translate.\n\nUn fichier texte brut avec une ligne par texte : la clé, complétée à 12 caractères, puis ` : ` et le texte. La clé est `T` suivi d'un hash du texte en base 36, la clé que le moteur de vues recherche pour `@(text)`. Place une copie traduite dans `resources/` (par exemple `resources/sk.resource`) et traduis la partie droite. Consulte [Localisation](../../guides/localization/).\n\nExample: Contenu\n```text\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\n### flow5 <files...> <port>\n\nType: `command`\n\nDéfinit le port du moteur Flow et exécute plusieurs schémas à la fois.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String` | yes |  | Un ou plusieurs fichiers ou adresses de schémas. |\n| `port` | `Number` | no | `8000` | Le port du serveur HTTP. |\n\nLes arguments peuvent être dans n'importe quel ordre. Chaque argument composé uniquement de chiffres est le port (le dernier l'emporte) ; chacun des autres est un fichier de schéma, avec son chemin complet, ou une adresse `https://`. Tous les flux de toutes les sources s'exécutent dans un seul processus sur ce port.\n\nExample: Plusieurs fichiers\n```bash\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\n```\n\n### total5 bundle <filename>\n\nType: `command`\n\nRegroupe le répertoire courant dans un fichier bundle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le chemin complet du fichier bundle. |\n\nÉcrit les fichiers du répertoire courant et de ses sous-répertoires dans un seul fichier `.bundle`. `.bundle` est ajouté au nom s'il manque. Les fichiers de la machine sont exclus (voir Contenu du bundle). Indique le chemin complet du bundle, hors du répertoire que tu regroupes. Le framework décompresse les bundles de `bundles/` au démarrage.\n\nExample: Regrouper un projet\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop\n# ~/backups/shop.bundle\n```\n\n### { id, name, components, design } | { <id>: schema }\n\nType: `type`\n\nLes deux formes d'un fichier que lit flow5.\n\nUn fichier avec **un seul flux** est un objet avec `components` et `design` (et `id`, `name` et les autres champs d'un schéma FlowStream). Un fichier avec **plusieurs flux** est un objet dont les clés sont les identifiants des flux ; une clé `variables` est ignorée. Un flux sans `id` reçoit un identifiant construit à partir du chemin. Pour enregistrer les modifications dans le fichier, donne au flux un `id`, et dans un fichier avec plusieurs flux, utilise l'identifiant comme clé.\n\nExample: Un flux\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {},\n\t\"design\": {}\n}\n```\n\nExample: Plusieurs flux\n```json\n{\n\t\"orders\": { \"id\": \"orders\", \"name\": \"Orders\", \"components\": {}, \"design\": {} },\n\t\"mail\": { \"id\": \"mail\", \"name\": \"Mail\", \"components\": {}, \"design\": {} }\n}\n```\n\n### .bundle\n\nType: `type`\n\nLes fichiers que total5 bundle place dans un bundle.\n\nTous les fichiers du répertoire, sauf : `/index.js`, `/debug.js`, `/release.js` avec leurs fichiers `.json` et `.pid`, `/bundle.json`, `/package.json`, `/readme.md`, `/license.txt` et les dossiers `/bundles/`, `/tmp/`, `/.src/` et `/.git/`.\n\nExample: Déployer avec un bundle\n```bash\ntotal5 bundle ~/backups/shop\nscp ~/backups/shop.bundle server:/www/shop/bundles/\n```\n\n### GET|POST /notify/{id}/\n\nType: `property`\n\nLa route de notification du moteur Flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | `<flow id>-<instance id>[-param...]`. |\n\nEnvoie une notification à une instance de composant d'un flux en cours d'exécution. L'identifiant est `<flow id>-<instance id>` ; les parties supplémentaires séparées par `-` arrivent dans `params`. Le composant reçoit la méthode, les en-têtes, la query, le corps (jusqu'à 1 MB), l'URL et l'adresse IP. Une valeur de query `REDIRECT` redirige le visiteur ; un navigateur reçoit une page qui se ferme d'elle-même, les autres clients reçoivent une réponse de succès. Consulte [FlowStream](../../guides/flowstream/).\n\nExample: Notifier un composant\n```bash\ncurl -X POST -d '{\"paid\":true}' -H \"Content-Type: application/json\" http://127.0.0.1:8000/notify/orders-c1x8a/\n```\n\n### total5 extract <filename>\n\nType: `command`\n\nDécompresse un bundle dans le répertoire courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le chemin complet du fichier bundle à décompresser. |\n\nRestaure tous les fichiers du bundle dans le répertoire courant, avec leurs sous-répertoires. Les fichiers existants portant les mêmes noms sont écrasés. Quand l'argument est un répertoire, rien ne se passe. Indique le chemin complet du fichier.\n\nExample: Décompresser\n```bash\nmkdir shop-copy && cd shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n### SOCKET /flowstreams/{id}/\n\nType: `property`\n\nLe WebSocket de l'éditeur Flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'identifiant du flux. |\n\nL'éditeur Flow se connecte ici pour afficher et modifier le flux de l'identifiant indiqué (messages jusqu'à 8 MB). Le lien que `flow5` affiche pour chaque flux ouvre `https://flow.totaljs.com/?socket=` avec cette adresse.\n\nExample: Ouvrir l'éditeur\n```text\nhttps://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n","entries":[{"type":"command","name":"total5","signature":"total5 [command] [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 help","signature":"total5 help","since":"","deprecated":false},{"type":"command","name":"total5 --command","signature":"total5 --<command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 minify","signature":"total5 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total5 edit","signature":"total5 edit <url>","since":"","deprecated":false},{"type":"type","name":"Code Editor requests","signature":"TYPE: browse | load | save | ...","since":"","deprecated":false},{"type":"command","name":"total5 <port>","signature":"total5 <port>","since":"","deprecated":false},{"type":"command","name":"total5 proxy","signature":"total5 proxy <endpoint> <port>","since":"0.0.17","deprecated":false},{"type":"command","name":"total5 server","signature":"total5 server [port]","since":"","deprecated":false},{"type":"command","name":"total5 test","signature":"total5 test [name1] [name2] [...]","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5","since":"","deprecated":false},{"type":"type","name":"Directory listing","signature":"GET /{path}/","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate <filename>","since":"","deprecated":false},{"type":"command","name":"flow5 <file>","signature":"flow5 <file> [port]","since":"","deprecated":false},{"type":"command","name":"flow5 <url>","signature":"flow5 <url> [port]","since":"","deprecated":false},{"type":"type","name":"Resource file","signature":"KEY : text","since":"","deprecated":false},{"type":"command","name":"flow5 <port>","signature":"flow5 <files...> <port>","since":"","deprecated":false},{"type":"command","name":"total5 bundle","signature":"total5 bundle <filename>","since":"","deprecated":false},{"type":"type","name":"Flow schema file","signature":"{ id, name, components, design } | { <id>: schema }","since":"","deprecated":false},{"type":"type","name":"Bundle content","signature":".bundle","since":"","deprecated":false},{"type":"property","name":"flow5 /notify/{id}/","signature":"GET|POST /notify/{id}/","since":"","deprecated":false},{"type":"command","name":"total5 extract","signature":"total5 extract <filename>","since":"","deprecated":false},{"type":"property","name":"flow5 /flowstreams/{id}/","signature":"SOCKET /flowstreams/{id}/","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwUK9Zx60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/command-line/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"it","title":"Riga di comando (total5)","summary":"Tutti i comandi e gli argomenti dei programmi total5 e flow5.","markdown":"---\ntitle: Riga di comando (total5)\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/reference/command-line/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Riga di comando (total5)\n\n> Tutti i comandi e gli argomenti dei programmi total5 e flow5.\n\nI comandi dei due programmi che il pacchetto `total5` installa: `total5`, che lavora sulla directory corrente, e `flow5`, che esegue schemi FlowStream. Ogni voce mostra la sintassi, gli argomenti e un esempio. Per un'introduzione leggi [Riga di comando (total5)](../../guides/command-line/).\n\n```bash\nnpm install -g total5\ntotal5 help\nflow5\n```\n\n## API\n\n### total5 [command] [arguments]\n\nType: `command`\n\nLa cassetta degli attrezzi da riga di comando del pacchetto total5.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | no | `help` | Il nome del comando. |\n| `arguments` | `String` | no |  | Gli argomenti del comando, in ordine. |\n\nEsegue un comando sulla directory corrente. Senza comando mostra l'aiuto. Ogni comando stampa prima `* Total.js v5: [Command]`; quelli brevi terminano con una riga `[Done]` con il tempo impiegato. Un comando che il programma non conosce stampa solo quell'intestazione.\n\nExample: Mostrare l'aiuto\n```bash\ntotal5\n```\n\n### total5 help\n\nType: `command`\n\nStampa l'elenco dei comandi.\n\nStampa una riga per ogni comando con i suoi argomenti e ciò che fa: `translate`, `minify`, `bundle`, `extract`, `edit`, `proxy`, `test` e il web server (`8000`). `total5` senza comando fa lo stesso.\n\nExample: Aiuto\n```bash\ntotal5 help\ntotal5 --help\n```\n\n### total5 --<command> [arguments]\n\nType: `command`\n\nI trattini davanti a un comando vengono ignorati.\n\nIl programma rimuove ogni sequenza di due o più trattini dal comando, quindi `--help` è `help` e `--minify` è `minify`. Usa la forma che preferisci.\n\nExample: Lo stesso comando due volte\n```bash\ntotal5 --help\ntotal5 help\n```\n\n### total5 minify <filename>\n\nType: `command`\n\nMinifica un file JavaScript, CSS o HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il percorso completo del file da minificare. |\n\nLegge il file, lo minifica in base alla sua estensione e scrive il risultato accanto a esso come `name.min.ext`. JavaScript e CSS vengono minificati completamente. Il minificatore HTML rimuove i commenti, riduce le sequenze di spazi all'interno del markup e minifica i blocchi `<script>` e `<style>` inline; mantiene le interruzioni di riga e l'indentazione tra i tag. Un file con un'altra estensione viene copiato senza modifiche. Stampa i nomi dei file di input e di output. Indica il percorso completo del file.\n\nExample: Minificare uno script\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"\n# Output    : /home/me/shop/public/js/app.min.js\n```\n\n### total5 edit <url>\n\nType: `command`\n\nApre la directory corrente per la modifica remota nel Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo del progetto nel Code Editor, per esempio `https://code.example.com/?id=project`. |\n\nSi connette all'URL del progetto con un WebSocket (`http` e `https` diventano `ws` e `wss`) e serve le richieste dell'editor sulla directory corrente (vedi Richieste del Code Editor). Quando l'editor accetta la connessione stampa un benvenuto con il nome dell'editor e del progetto. La connessione si ristabilisce ogni 10 secondi e viene interrogata con un ping ogni 30 secondi. `404 project not found` e `409 project is already open` vengono stampati quando l'editor rifiuta il progetto. Senza URL il programma lancia `Invalid URL address`.\n\nExample: Modificare un progetto\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n```\n\n### TYPE: browse | load | save | ...\n\nType: `type`\n\nCosa può fare il Code Editor tramite total5 edit.\n\nL'editor invia richieste e il programma risponde all'interno della directory corrente: `browse` (l'elenco di file e cartelle), `load`, `save`, `create`, `remove`, `rename`, `modify`, `info`, `upload`, `download`, `send`, `import`, `log` e `logclear` (file di log), `wiki`, `ip` (l'indirizzo IP pubblico), `exec` (esegue un file: i file `.js` con Node.js, i file `.sh` con `sh`, oppure un comando inviato dall'editor), `restart` e `ping`. A una richiesta sconosciuta si risponde con un errore 400.\n\nExample: Una richiesta e la sua risposta\n```js\n// sent by the editor\n{ TYPE: 'browse', data: '{}' }\n// answer\n{ TYPE: 'browse', data: '{}', success: true, response: { files: ['/index.js'], directories: ['/controllers/'] } }\n```\n\n### total5 <port>\n\nType: `command`\n\nAvvia un web server statico per la directory corrente sulla porta indicata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | La porta del server. |\n\nUn numero come comando avvia il web server: `total5 8000` equivale a `total5 server 8000`. La directory corrente è la cartella public, minificazione e source map sono disattivate, e le cartelle dell'applicazione non vengono caricate. L'URL di una directory mostra un elenco della directory. Il programma stampa le informazioni di avvio del framework e resta in esecuzione finché non lo fermi.\n\nExample: Servire una cartella\n```bash\ncd ~/projects/landing\ntotal5 8000\n# open http://127.0.0.1:8000/\n```\n\n### total5 proxy <endpoint> <port>\n\nType: `command` · Since: `0.0.17`\n\nCollega una porta locale a un server proxy Total.js remoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | yes |  | L'indirizzo WebSocket del server proxy. |\n| `port` | `String` | yes |  | Una porta locale (su `127.0.0.1`) o una coppia `ip:port`. |\n\nApre un WebSocket verso il proxy server, un'applicazione che chiama `PROXYSERVER()` (`http` e `https` vengono sostituiti con `ws` e `wss`), e inoltra all'indirizzo locale ogni richiesta che arriva attraverso di esso. La risposta torna indietro per la stessa strada. Il programma stampa una riga quando si connette o si disconnette e una riga per ogni richiesta con il suo metodo, l'indirizzo IP del visitatore e l'URL. Senza entrambi gli argomenti stampa `client [WSS proxy server] [port or ip:port]`. È lo stesso client della funzione `PROXYCLIENT()`.\n\nExample: Condividere un server locale\n```bash\ntotal5 proxy wss://proxy.example.com/ 8000\n```\n\nExample: Il lato server\n```js\n// index.js of the proxy server\nrequire('total5');\nPROXYSERVER('/', '/proxy/');\nF.http({ port: 8000, load: 'none' });\n\n// on your machine:\n// total5 proxy wss://proxy.example.com/proxy/ 8000\n```\n\n### total5 server [port]\n\nType: `command`\n\nAvvia un web server statico per la directory corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `8000` | La porta del server. |\n\nLa forma lunga di `total5 <port>`. Senza porta ascolta su `8000`.\n\nExample: Porta predefinita\n```bash\ntotal5 server\n# http://0.0.0.0:8000/\n```\n\nExample: Un'altra porta\n```bash\ntotal5 server 8080\n```\n\n### total5 test [name1] [name2] [...]\n\nType: `command`\n\nEsegue i test unitari della directory corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Il nome di uno script di test senza `.js`; più nomi separati da spazi o virgole. |\n\nPrende la directory `tests` della directory corrente, oppure la directory corrente quando non c'è una directory `tests`. Carica il file `config` di quella directory con `LOADCONFIG()`, crea l'oggetto globale `Test`, carica `init.js` quando esiste e poi gli script indicati nel loro ordine, oppure ogni file `.js` tranne `init.js` in ordine alfabetico quando non viene indicato alcun nome. Poi chiama `Test.run()`. I nomi possono essere separati da spazi o virgole e l'estensione `.js` è facoltativa. Uno script mancante stampa `ERROR: the test \"name\" not found (path)` e termina con exit code 1. L'exit code è 0 quando tutti i gruppi sono completati e 1 quando un controllo fallisce o l'esecuzione si ferma prima della fine. Il comando usa il pacchetto `total5` installato nella directory corrente o in una directory superiore (quindi funziona anche da `tests`), altrimenti il proprio pacchetto. L'applicazione stessa non viene avviata e la directory corrente è la radice (`PATH.root()`). Vedi [Test unitari](../../guides/unit-tests/).\n\nExample: Tutti i test\n```bash\ncd ~/projects/shop\ntotal5 test\n```\n\nExample: Due script\n```bash\ntotal5 test strings orders\ntotal5 test strings,orders\n```\n\n### flow5\n\nType: `command`\n\nStampa l'aiuto del Flow engine.\n\nSenza argomenti `flow5` stampa `[Total.js v5 Flow Engine]` e i modi per chiamarlo.\n\nExample: Aiuto\n```bash\nflow5\n# flow5 [path or URL address] [PORT_NUMBER]\n# flow5 path/to/flowschema.json\n# flow5 flow1.json flow2.json flowN.json 8001\n# flow5 https://yourdomain.com/flowschema.json\n```\n\n### GET /{path}/\n\nType: `type`\n\nCosa mostra il web server per una directory.\n\nPer l'URL di una directory il server mostra una pagina HTML con un link `..` alla directory superiore (tranne che in `/`), le sottodirectory e i file con le relative dimensioni. Ogni link apre l'elemento sullo stesso server; apri `index.html` dall'elenco come qualsiasi altro file.\n\nExample: Sfogliare\n```bash\ntotal5 8000\n# http://127.0.0.1:8000/            -> the listing of the directory\n# http://127.0.0.1:8000/index.html  -> the page\n```\n\n### total5 translate <filename>\n\nType: `command`\n\nRaccoglie i testi @(...) della directory corrente in un file di risorse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il percorso completo del file di risorse da scrivere. |\n\nLegge ogni file `.js` e `.html` della directory corrente e di tutte le sue sottodirectory, trova i testi scritti come `@(text)` (le parentesi annidate vengono mantenute) e li scrive nel file di risorse, una riga `KEY : text` per ogni testo. Lo stesso testo produce una sola riga. Un file esistente viene sovrascritto. Indica il percorso completo del file.\n\nExample: In resources\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n### flow5 <file> [port]\n\nType: `command`\n\nEsegue i flow di un file di schema locale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Il percorso completo del file di schema. |\n| `port` | `Number` | no | `8000` | La porta del server HTTP. |\n\nCarica lo schema FlowStream del file e lo esegue. Il server HTTP parte quando è caricato almeno un flusso. Per ogni flusso il programma stampa un link all'editor Flow. Quando il flusso viene salvato nell'editor, il file viene riscritto come JSON indentato con tabulazioni. Un file che non è JSON valido stampa `ERROR: invalid meta - <path>` e viene saltato. Indica il percorso completo del file.\n\nExample: Un file\n```bash\nflow5 \"$PWD/flowschema.json\"\n# |--- http://127.0.0.1:8000\n# |--- Orders: https://flow.totaljs.com/?socket=...\n```\n\n### flow5 <url> [port]\n\nType: `command`\n\nEsegue i flow di uno schema scaricato da un indirizzo https.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo `https://` dello schema. |\n| `port` | `Number` | no | `8000` | La porta del server HTTP. |\n\nUn argomento che inizia con `https://` viene scaricato con una richiesta `GET` e caricato come un file. Il certificato del server viene verificato. Le modifiche fatte nell'editor non vengono salvate da nessuna parte per questi flow.\n\nExample: Schema remoto\n```bash\nflow5 https://example.com/flowschema.json 8001\n```\n\n### KEY : text\n\nType: `type`\n\nIl file che scrive total5 translate.\n\nUn file di testo semplice con una riga per ogni testo: la chiave, riempita fino a 12 caratteri, poi ` : ` e il testo. La chiave è `T` seguita da un hash del testo in base 36, la chiave che il motore delle viste cerca per `@(text)`. Metti una copia tradotta in `resources/` (per esempio `resources/sk.resource`) e traduci la parte destra. Vedi [Localizzazione](../../guides/localization/).\n\nExample: Contenuto\n```text\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\n### flow5 <files...> <port>\n\nType: `command`\n\nImposta la porta del Flow engine ed esegue più schemi contemporaneamente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String` | yes |  | Uno o più file o indirizzi di schema. |\n| `port` | `Number` | no | `8000` | La porta del server HTTP. |\n\nGli argomenti possono essere in qualsiasi ordine. Ogni argomento composto solo da cifre è la porta (vale l'ultimo); ogni altro è un file di schema, con il suo percorso completo, o un indirizzo `https://`. Tutti i flussi di tutte le sorgenti girano in un unico processo su quella porta.\n\nExample: Più file\n```bash\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\n```\n\n### total5 bundle <filename>\n\nType: `command`\n\nImpacchetta la directory corrente in un file bundle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il percorso completo del file bundle. |\n\nScrive i file della directory corrente e delle sue sottodirectory in un unico file `.bundle`. `.bundle` viene aggiunto al nome se manca. I file della macchina vengono esclusi (vedi Contenuto del bundle). Indica il percorso completo del bundle, fuori dalla directory che impacchetti. Il framework estrae i bundle di `bundles/` all'avvio.\n\nExample: Impacchettare un progetto\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop\n# ~/backups/shop.bundle\n```\n\n### { id, name, components, design } | { <id>: schema }\n\nType: `type`\n\nLe due forme di un file che flow5 legge.\n\nUn file con **un flow** è un oggetto con `components` e `design` (e `id`, `name` e gli altri campi di uno schema FlowStream). Un file con **più flow** è un oggetto le cui chiavi sono gli id dei flow; una chiave `variables` viene saltata. Un flow senza `id` riceve un id ricavato dal percorso. Per salvare le modifiche nel file, dai al flow un `id`, e in un file con più flow usa l'id come sua chiave.\n\nExample: Un flow\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {},\n\t\"design\": {}\n}\n```\n\nExample: Più flow\n```json\n{\n\t\"orders\": { \"id\": \"orders\", \"name\": \"Orders\", \"components\": {}, \"design\": {} },\n\t\"mail\": { \"id\": \"mail\", \"name\": \"Mail\", \"components\": {}, \"design\": {} }\n}\n```\n\n### .bundle\n\nType: `type`\n\nQuali file total5 bundle inserisce in un bundle.\n\nTutti i file della directory, tranne: `/index.js`, `/debug.js`, `/release.js` con i loro file `.json` e `.pid`, `/bundle.json`, `/package.json`, `/readme.md`, `/license.txt` e le cartelle `/bundles/`, `/tmp/`, `/.src/` e `/.git/`.\n\nExample: Distribuire con un bundle\n```bash\ntotal5 bundle ~/backups/shop\nscp ~/backups/shop.bundle server:/www/shop/bundles/\n```\n\n### GET|POST /notify/{id}/\n\nType: `property`\n\nLa route di notifica del Flow engine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | `<flow id>-<instance id>[-param...]`. |\n\nInvia una notifica a un'istanza di componente di un flow in esecuzione. L'id è `<flow id>-<instance id>`; ulteriori parti separate da `-` arrivano come `params`. Il componente riceve il metodo, gli header, la query, il body (fino a 1 MB), l'URL e l'indirizzo IP. Un valore di query `REDIRECT` reindirizza il visitatore; un browser riceve una pagina che si chiude da sola, gli altri client ricevono una risposta di successo. Vedi [FlowStream](../../guides/flowstream/).\n\nExample: Notificare un componente\n```bash\ncurl -X POST -d '{\"paid\":true}' -H \"Content-Type: application/json\" http://127.0.0.1:8000/notify/orders-c1x8a/\n```\n\n### total5 extract <filename>\n\nType: `command`\n\nEstrae un bundle nella directory corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il percorso completo del file bundle da estrarre. |\n\nRipristina tutti i file del bundle nella directory corrente, con le loro sottodirectory. I file esistenti con lo stesso nome vengono sovrascritti. Quando l'argomento è una directory, non succede nulla. Indica il percorso completo del file.\n\nExample: Estrarre\n```bash\nmkdir shop-copy && cd shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n### SOCKET /flowstreams/{id}/\n\nType: `property`\n\nIl WebSocket del Flow editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del flow. |\n\nIl Flow editor si connette qui per mostrare e modificare il flow con l'id indicato (messaggi fino a 8 MB). Il link che `flow5` stampa per ogni flow apre `https://flow.totaljs.com/?socket=` con questo indirizzo.\n\nExample: Aprire l'editor\n```text\nhttps://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n","entries":[{"type":"command","name":"total5","signature":"total5 [command] [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 help","signature":"total5 help","since":"","deprecated":false},{"type":"command","name":"total5 --command","signature":"total5 --<command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 minify","signature":"total5 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total5 edit","signature":"total5 edit <url>","since":"","deprecated":false},{"type":"type","name":"Code Editor requests","signature":"TYPE: browse | load | save | ...","since":"","deprecated":false},{"type":"command","name":"total5 <port>","signature":"total5 <port>","since":"","deprecated":false},{"type":"command","name":"total5 proxy","signature":"total5 proxy <endpoint> <port>","since":"0.0.17","deprecated":false},{"type":"command","name":"total5 server","signature":"total5 server [port]","since":"","deprecated":false},{"type":"command","name":"total5 test","signature":"total5 test [name1] [name2] [...]","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5","since":"","deprecated":false},{"type":"type","name":"Directory listing","signature":"GET /{path}/","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate <filename>","since":"","deprecated":false},{"type":"command","name":"flow5 <file>","signature":"flow5 <file> [port]","since":"","deprecated":false},{"type":"command","name":"flow5 <url>","signature":"flow5 <url> [port]","since":"","deprecated":false},{"type":"type","name":"Resource file","signature":"KEY : text","since":"","deprecated":false},{"type":"command","name":"flow5 <port>","signature":"flow5 <files...> <port>","since":"","deprecated":false},{"type":"command","name":"total5 bundle","signature":"total5 bundle <filename>","since":"","deprecated":false},{"type":"type","name":"Flow schema file","signature":"{ id, name, components, design } | { <id>: schema }","since":"","deprecated":false},{"type":"type","name":"Bundle content","signature":".bundle","since":"","deprecated":false},{"type":"property","name":"flow5 /notify/{id}/","signature":"GET|POST /notify/{id}/","since":"","deprecated":false},{"type":"command","name":"total5 extract","signature":"total5 extract <filename>","since":"","deprecated":false},{"type":"property","name":"flow5 /flowstreams/{id}/","signature":"SOCKET /flowstreams/{id}/","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafwUK9Zx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/command-line/","project":"total-js-v5","version":"0-0-20","section":"reference","language":"sk","title":"Príkazový riadok (total5)","summary":"Každý príkaz a argument programov total5 a flow5.","markdown":"---\ntitle: \"Príkazový riadok (total5)\"\nproject: Total.js V5\nversion: 0.0.20\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/reference/command-line/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Príkazový riadok (total5)\n\n> Každý príkaz a argument programov total5 a flow5.\n\nPríkazy dvoch programov, ktoré inštaluje balík `total5`: `total5`, ktorý pracuje s aktuálnym adresárom, a `flow5`, ktorý spúšťa FlowStream schémy. Každý záznam ukazuje syntax, argumenty a príklad. Úvod nájdeš v [Príkazový riadok (total5)](../../guides/command-line/).\n\n```bash\nnpm install -g total5\ntotal5 help\nflow5\n```\n\n## API\n\n### total5 [command] [arguments]\n\nType: `command`\n\nSúbor nástrojov príkazového riadka z balíka total5.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | no | `help` | Názov príkazu. |\n| `arguments` | `String` | no |  | Argumenty príkazu v danom poradí. |\n\nSpustí jeden príkaz nad aktuálnym adresárom. Bez príkazu zobrazí pomocníka. Každý príkaz najprv vypíše `* Total.js v5: [Command]`; krátke končia riadkom `[Done]` s časom, ktorý trvali. Príkaz, ktorý program nepozná, vypíše iba túto hlavičku.\n\nExample: Zobrazenie pomocníka\n```bash\ntotal5\n```\n\n### total5 help\n\nType: `command`\n\nVypíše zoznam príkazov.\n\nVypíše jeden riadok pre každý príkaz s jeho argumentmi a tým, čo robí: `translate`, `minify`, `bundle`, `extract`, `edit`, `proxy`, `test` a webový server (`8000`). `total5` bez príkazu robí to isté.\n\nExample: Pomoc\n```bash\ntotal5 help\ntotal5 --help\n```\n\n### total5 --<command> [arguments]\n\nType: `command`\n\nPomlčky pred príkazom sa ignorujú.\n\nProgram z príkazu odstráni každú postupnosť dvoch alebo viacerých pomlčiek, takže `--help` je `help` a `--minify` je `minify`. Použi tvar, ktorý ti vyhovuje.\n\nExample: Ten istý príkaz dvakrát\n```bash\ntotal5 --help\ntotal5 help\n```\n\n### total5 minify <filename>\n\nType: `command`\n\nMinifikuje súbor JavaScript, CSS alebo HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Úplná cesta k súboru na minifikáciu. |\n\nPrečíta súbor, minifikuje ho podľa jeho prípony a výsledok zapíše vedľa neho ako `name.min.ext`. JavaScript a CSS sa minifikujú úplne. HTML minifikátor odstráni komentáre, skráti viacnásobné medzery v markupe a minifikuje inline bloky `<script>` a `<style>`; zalomenia riadkov a odsadenie medzi tagmi zachová. Súbor s inou príponou sa skopíruje bez zmeny. Vypíše názvy vstupného a výstupného súboru. Zadaj úplnú cestu k súboru.\n\nExample: Minifikácia skriptu\n```bash\ntotal5 minify \"$PWD/public/js/app.js\"\n# Output    : /home/me/shop/public/js/app.min.js\n```\n\n### total5 edit <url>\n\nType: `command`\n\nOtvorí aktuálny adresár na vzdialenú úpravu v Total.js Code Editore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa projektu v Code Editore, napríklad `https://code.example.com/?id=project`. |\n\nPripojí sa k URL projektu cez WebSocket (`http` a `https` sa zmenia na `ws` a `wss`) a obsluhuje požiadavky editora nad aktuálnym adresárom (pozri Požiadavky Code Editora). Keď editor spojenie prijme, vypíše uvítanie s názvom editora a projektu. Spojenie sa znova pripája každých 10 sekúnd a pinguje sa každých 30 sekúnd. Keď editor projekt odmietne, vypíše sa `404 project not found` alebo `409 project is already open`. Bez URL program vyhodí `Invalid URL address`.\n\nExample: Úprava projektu\n```bash\ncd ~/projects/shop\ntotal5 edit \"https://code.example.com/?id=shop\"\n```\n\n### TYPE: browse | load | save | ...\n\nType: `type`\n\nČo dokáže Code Editor cez total5 edit.\n\nEditor posiela požiadavky a program na ne odpovedá vnútri aktuálneho adresára: `browse` (zoznam súborov a priečinkov), `load`, `save`, `create`, `remove`, `rename`, `modify`, `info`, `upload`, `download`, `send`, `import`, `log` a `logclear` (log súbory), `wiki`, `ip` (verejná IP adresa), `exec` (spustí súbor: súbory `.js` cez Node.js, súbory `.sh` cez `sh` alebo príkaz, ktorý pošle editor), `restart` a `ping`. Na neznámu požiadavku sa odpovie chybou 400.\n\nExample: Požiadavka a odpoveď na ňu\n```js\n// sent by the editor\n{ TYPE: 'browse', data: '{}' }\n// answer\n{ TYPE: 'browse', data: '{}', success: true, response: { files: ['/index.js'], directories: ['/controllers/'] } }\n```\n\n### total5 <port>\n\nType: `command`\n\nSpustí statický webový server pre aktuálny adresár na zadanom porte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | Port servera. |\n\nČíslo ako príkaz spustí webový server: `total5 8000` je `total5 server 8000`. Aktuálny adresár je verejný priečinok, minifikácia a source mapy sú vypnuté a priečinky aplikácie sa nenačítajú. URL adresára zobrazí výpis adresára. Program vypíše štartovacie informácie frameworku a beží, kým ho nezastavíš.\n\nExample: Poskytovanie priečinka\n```bash\ncd ~/projects/landing\ntotal5 8000\n# open http://127.0.0.1:8000/\n```\n\n### total5 proxy <endpoint> <port>\n\nType: `command` · Since: `0.0.17`\n\nPripojí lokálny port k vzdialenému Total.js proxy serveru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `endpoint` | `String` | yes |  | WebSocket adresa proxy servera. |\n| `port` | `String` | yes |  | Lokálny port (na `127.0.0.1`) alebo dvojica `ip:port`. |\n\nOtvorí WebSocket k proxy serveru, aplikácii, ktorá volá `PROXYSERVER()` (`http` a `https` sa nahradia za `ws` a `wss`), a každú požiadavku, ktorá cez neho príde, prepošle na lokálnu adresu. Odpoveď ide späť tou istou cestou. Program vypíše riadok pri pripojení alebo odpojení a jeden riadok pre každú požiadavku s jej metódou, IP adresou návštevníka a URL. Bez oboch argumentov vypíše `client [WSS proxy server] [port or ip:port]`. Je to ten istý klient ako funkcia `PROXYCLIENT()`.\n\nExample: Zdieľanie lokálneho servera\n```bash\ntotal5 proxy wss://proxy.example.com/ 8000\n```\n\nExample: Strana servera\n```js\n// index.js of the proxy server\nrequire('total5');\nPROXYSERVER('/', '/proxy/');\nF.http({ port: 8000, load: 'none' });\n\n// on your machine:\n// total5 proxy wss://proxy.example.com/proxy/ 8000\n```\n\n### total5 server [port]\n\nType: `command`\n\nSpustí statický webový server pre aktuálny adresár.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `8000` | Port servera. |\n\nDlhý tvar `total5 <port>`. Bez portu počúva na `8000`.\n\nExample: Predvolený port\n```bash\ntotal5 server\n# http://0.0.0.0:8000/\n```\n\nExample: Iný port\n```bash\ntotal5 server 8080\n```\n\n### total5 test [name1] [name2] [...]\n\nType: `command`\n\nSpustí unit testy aktuálneho adresára.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Názov testovacieho skriptu bez `.js`; viac názvov oddelených medzerami alebo čiarkami. |\n\nVezme adresár `tests` aktuálneho adresára, alebo aktuálny adresár, keď adresár `tests` neexistuje. Načíta súbor `config` tohto adresára cez `LOADCONFIG()`, vytvorí globálny `Test`, načíta `init.js`, keď existuje, a potom pomenované skripty v ich poradí, alebo každý súbor `.js` okrem `init.js` v abecednom poradí, keď nie je zadaný žiadny názov. Potom zavolá `Test.run()`. Názvy môžu byť oddelené medzerami alebo čiarkami a prípona `.js` je voliteľná. Chýbajúci skript vypíše `ERROR: the test \"name\" not found (path)` a skončí s exit kódom 1. Exit kód je 0, keď sú všetky skupiny hotové, a 1, keď kontrola zlyhá alebo sa beh zastaví pred koncom. Príkaz používa balík `total5` nainštalovaný v aktuálnom adresári alebo v nadradenom adresári (takže beží aj z `tests`), inak svoj vlastný balík. Samotná aplikácia sa nespustí a aktuálny adresár je koreň (`PATH.root()`). Pozri [Unit testy](../../guides/unit-tests/).\n\nExample: Všetky testy\n```bash\ncd ~/projects/shop\ntotal5 test\n```\n\nExample: Dva skripty\n```bash\ntotal5 test strings orders\ntotal5 test strings,orders\n```\n\n### flow5\n\nType: `command`\n\nVypíše pomocníka Flow enginu.\n\nBez argumentov `flow5` vypíše `[Total.js v5 Flow Engine]` a spôsoby, ako ho zavolať.\n\nExample: Pomocník\n```bash\nflow5\n# flow5 [path or URL address] [PORT_NUMBER]\n# flow5 path/to/flowschema.json\n# flow5 flow1.json flow2.json flowN.json 8001\n# flow5 https://yourdomain.com/flowschema.json\n```\n\n### GET /{path}/\n\nType: `type`\n\nČo webový server zobrazí pre adresár.\n\nPre URL adresára server zobrazí HTML stránku s odkazom `..` na nadradený adresár (okrem `/`), podadresármi a súbormi s ich veľkosťami. Každý odkaz otvorí položku na tom istom serveri; `index.html` otvoríš z výpisu ako každý iný súbor.\n\nExample: Prehliadanie\n```bash\ntotal5 8000\n# http://127.0.0.1:8000/            -> the listing of the directory\n# http://127.0.0.1:8000/index.html  -> the page\n```\n\n### total5 translate <filename>\n\nType: `command`\n\nZozbiera texty @(...) aktuálneho adresára do resource súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Úplná cesta k súboru zdrojov, ktorý sa zapíše. |\n\nPrečíta každý súbor `.js` a `.html` aktuálneho adresára a všetkých jeho podadresárov, nájde texty zapísané ako `@(text)` (vnorené zátvorky sa zachovajú) a zapíše ich do súboru zdrojov, jeden riadok `KEY : text` pre každý text. Rovnaký text dá jeden riadok. Existujúci súbor sa prepíše. Zadaj úplnú cestu k súboru.\n\nExample: Do resources\n```bash\ntotal5 translate \"$PWD/resources/default.resource\"\n```\n\n### flow5 <file> [port]\n\nType: `command`\n\nSpustí flows lokálneho súboru so schémou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Úplná cesta k súboru schémy. |\n| `port` | `Number` | no | `8000` | Port HTTP servera. |\n\nNačíta schému FlowStream zo súboru a spustí ju. HTTP server sa spustí, keď je načítaný aspoň jeden tok. Pre každý tok program vypíše odkaz do editora Flow. Keď sa tok uloží v editore, súbor sa znova zapíše ako JSON odsadený tabulátormi. Súbor, ktorý nie je platný JSON, vypíše `ERROR: invalid meta - <path>` a preskočí sa. Zadaj úplnú cestu k súboru.\n\nExample: Jeden súbor\n```bash\nflow5 \"$PWD/flowschema.json\"\n# |--- http://127.0.0.1:8000\n# |--- Orders: https://flow.totaljs.com/?socket=...\n```\n\n### flow5 <url> [port]\n\nType: `command`\n\nSpustí flows schémy stiahnutej z adresy https.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa `https://` schémy. |\n| `port` | `Number` | no | `8000` | Port HTTP servera. |\n\nArgument, ktorý začína `https://`, sa stiahne požiadavkou `GET` a načíta ako súbor. Certifikát servera sa overuje. Zmeny urobené v editore sa pre tieto flows nikam neukladajú.\n\nExample: Vzdialená schéma\n```bash\nflow5 https://example.com/flowschema.json 8001\n```\n\n### KEY : text\n\nType: `type`\n\nSúbor, ktorý zapisuje total5 translate.\n\nObyčajný textový súbor s jedným riadkom pre každý text: kľúč doplnený na 12 znakov, potom ` : ` a text. Kľúč je `T`, za ktorým nasleduje hash textu v sústave so základom 36, kľúč, ktorý view engine hľadá pre `@(text)`. Preloženú kópiu daj do `resources/` (napríklad `resources/sk.resource`) a prelož pravú stranu. Pozri [Lokalizácia](../../guides/localization/).\n\nExample: Obsah\n```text\nT1l964ro     : Hello world\nT1j2ql       : Save\n```\n\n### flow5 <files...> <port>\n\nType: `command`\n\nNastaví port Flow enginu a spustí viac schém naraz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String` | yes |  | Jeden alebo viac súborov so schémou alebo adries. |\n| `port` | `Number` | no | `8000` | Port HTTP servera. |\n\nArgumenty môžu prísť v ľubovoľnom poradí. Každý argument zložený iba z číslic je port (vyhráva posledný); každý iný je súbor schémy s úplnou cestou alebo adresa `https://`. Všetky toky zo všetkých zdrojov bežia v jednom procese na tomto porte.\n\nExample: Viac súborov\n```bash\nflow5 \"$PWD/flow1.json\" \"$PWD/flow2.json\" 8001\n```\n\n### total5 bundle <filename>\n\nType: `command`\n\nZabalí aktuálny adresár do súboru bundlu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Úplná cesta k súboru bundle. |\n\nZapíše súbory aktuálneho adresára a jeho podadresárov do jedného súboru `.bundle`. `.bundle` sa k názvu doplní, keď chýba. Súbory stroja sa vynechajú (pozri Obsah bundlu). Zadaj úplnú cestu k bundlu, mimo adresára, ktorý balíš. Framework pri štarte rozbalí bundly z `bundles/`.\n\nExample: Zabalenie projektu\n```bash\ncd ~/projects/shop\ntotal5 bundle ~/backups/shop\n# ~/backups/shop.bundle\n```\n\n### { id, name, components, design } | { <id>: schema }\n\nType: `type`\n\nDva tvary súboru, ktorý flow5 číta.\n\nSúbor s **jedným flow** je objekt s `components` a `design` (a `id`, `name` a ďalšími poľami FlowStream schémy). Súbor s **viacerými flows** je objekt, ktorého kľúče sú id flows; kľúč `variables` sa preskočí. Flow bez `id` dostane id vytvorené z cesty. Ak chceš zmeny ukladať späť do súboru, daj flow `id` a v súbore s viacerými flows použi id ako jeho kľúč.\n\nExample: Jeden flow\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {},\n\t\"design\": {}\n}\n```\n\nExample: Viac flows\n```json\n{\n\t\"orders\": { \"id\": \"orders\", \"name\": \"Orders\", \"components\": {}, \"design\": {} },\n\t\"mail\": { \"id\": \"mail\", \"name\": \"Mail\", \"components\": {}, \"design\": {} }\n}\n```\n\n### .bundle\n\nType: `type`\n\nKtoré súbory total5 bundle vloží do bundlu.\n\nVšetky súbory adresára okrem: `/index.js`, `/debug.js`, `/release.js` s ich súbormi `.json` a `.pid`, `/bundle.json`, `/package.json`, `/readme.md`, `/license.txt` a priečinkov `/bundles/`, `/tmp/`, `/.src/` a `/.git/`.\n\nExample: Nasadenie cez bundle\n```bash\ntotal5 bundle ~/backups/shop\nscp ~/backups/shop.bundle server:/www/shop/bundles/\n```\n\n### GET|POST /notify/{id}/\n\nType: `property`\n\nNotifikačná route Flow enginu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | `<flow id>-<instance id>[-param...]`. |\n\nPošle notifikáciu inštancii komponentu bežiaceho flow. Id je `<flow id>-<instance id>`; ďalšie časti oddelené `-` prídu ako `params`. Komponent dostane metódu, hlavičky, query, telo (do 1 MB), URL a IP adresu. Hodnota query `REDIRECT` presmeruje návštevníka; prehliadač dostane stránku, ktorá sa sama zatvorí, ostatní klienti dostanú úspešnú odpoveď. Pozri [FlowStream](../../guides/flowstream/).\n\nExample: Notifikácia komponentu\n```bash\ncurl -X POST -d '{\"paid\":true}' -H \"Content-Type: application/json\" http://127.0.0.1:8000/notify/orders-c1x8a/\n```\n\n### total5 extract <filename>\n\nType: `command`\n\nRozbalí bundle do aktuálneho adresára.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Úplná cesta k súboru bundle na rozbalenie. |\n\nObnoví všetky súbory bundlu do aktuálneho adresára aj s ich podadresármi. Existujúce súbory s rovnakými názvami sa prepíšu. Keď je argumentom adresár, nič sa nestane. Zadaj úplnú cestu k súboru.\n\nExample: Rozbalenie\n```bash\nmkdir shop-copy && cd shop-copy\ntotal5 extract ~/backups/shop.bundle\n```\n\n### SOCKET /flowstreams/{id}/\n\nType: `property`\n\nWebSocket Flow editora.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id flow. |\n\nFlow editor sa sem pripája, aby zobrazil a menil flow so zadaným id (správy do 8 MB). Odkaz, ktorý `flow5` vypíše pre každý flow, otvorí `https://flow.totaljs.com/?socket=` s touto adresou.\n\nExample: Otvorenie editora\n```text\nhttps://flow.totaljs.com/?socket=http%3A%2F%2F127.0.0.1%3A8000%2Fflowstreams%2Forders%2F\n```\n","entries":[{"type":"command","name":"total5","signature":"total5 [command] [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 help","signature":"total5 help","since":"","deprecated":false},{"type":"command","name":"total5 --command","signature":"total5 --<command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total5 minify","signature":"total5 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total5 edit","signature":"total5 edit <url>","since":"","deprecated":false},{"type":"type","name":"Code Editor requests","signature":"TYPE: browse | load | save | ...","since":"","deprecated":false},{"type":"command","name":"total5 <port>","signature":"total5 <port>","since":"","deprecated":false},{"type":"command","name":"total5 proxy","signature":"total5 proxy <endpoint> <port>","since":"0.0.17","deprecated":false},{"type":"command","name":"total5 server","signature":"total5 server [port]","since":"","deprecated":false},{"type":"command","name":"total5 test","signature":"total5 test [name1] [name2] [...]","since":"","deprecated":false},{"type":"command","name":"flow5","signature":"flow5","since":"","deprecated":false},{"type":"type","name":"Directory listing","signature":"GET /{path}/","since":"","deprecated":false},{"type":"command","name":"total5 translate","signature":"total5 translate <filename>","since":"","deprecated":false},{"type":"command","name":"flow5 <file>","signature":"flow5 <file> [port]","since":"","deprecated":false},{"type":"command","name":"flow5 <url>","signature":"flow5 <url> [port]","since":"","deprecated":false},{"type":"type","name":"Resource file","signature":"KEY : text","since":"","deprecated":false},{"type":"command","name":"flow5 <port>","signature":"flow5 <files...> <port>","since":"","deprecated":false},{"type":"command","name":"total5 bundle","signature":"total5 bundle <filename>","since":"","deprecated":false},{"type":"type","name":"Flow schema file","signature":"{ id, name, components, design } | { <id>: schema }","since":"","deprecated":false},{"type":"type","name":"Bundle content","signature":".bundle","since":"","deprecated":false},{"type":"property","name":"flow5 /notify/{id}/","signature":"GET|POST /notify/{id}/","since":"","deprecated":false},{"type":"command","name":"total5 extract","signature":"total5 extract <filename>","since":"","deprecated":false},{"type":"property","name":"flow5 /flowstreams/{id}/","signature":"SOCKET /flowstreams/{id}/","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jaftvh1cP61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-20/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"en","title":"0.0.20","summary":"What changed in release 0.0.20.","markdown":"---\ntitle: 0.0.20\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-20/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# 0.0.20\n\n> What changed in release 0.0.20.\n\nRelease 0.0.20 of the npm package `total5`.\n\n## New\n\n- Extended stats by adding `app` property\n- Added `Total.FsPromises` a link to the `node:fs/promises`\n- Added `mcp` module\n\t- `CONF.$mcp = true` activates MCP route `POST /$mcp/`\n\t- Any `NEWACTION` with the `mcp: true` property will be available in the endpoint\n- Added the MCP code mode: `GET /$mcp/client.js` returns a JavaScript client of the MCP tools (one function per tool, with JSDoc for its arguments and result) that calls them through `tools/call`, so an agent can write a script that uses the tools and only the output of the script goes back to the model\n\t- the same `Total.mcp.auth` (`Authorization: Bearer`) and `Total.mcp.filter` apply as for `tools/list`: `Total.mcp.filter(tool, $)` decides which tools a caller sees and may call, and the tools run as the user returned by `Total.mcp.auth`\n\t- `?q=words` returns only the tools whose name or description contain all the words\n\t- it is available whenever `CONF.$mcp` is enabled; nothing runs on the server\n- Added a new method `JSONSchema.toAIObject(name, [description])`\n- Added a new method `JSONSchema.toAITool(name)`\n- Added `QueryBuilder.autoqueryjson($, column, schema, [defsort], [maxlimit])` that works like `autoquery()` but for properties stored in a JSON(B) column; the builder uses the neutral name `json:column:property:type` and the database adapter translates it into SQL\n- Added a new controller method `$.content(value, content_type)`\n- Added a new event `reset` in the FlowStream\n- Added support for the `cache` option of `NEWACTION()` (the response is kept for the same `query`, `params`, `input`, `user` or `language`)\n- Added the compact schema types `json` and `ip` (the values are validated)\n- Added the compact schema type `email2`: it works like `email` and removes the tag of the address (`name+tag@domain.com` becomes `name@domain.com`)\n- Added `U.validhost(host)` that accepts only plain hostnames and canonical IP literals\n- Added `U.tohost(host)` that converts a hostname to the canonical ASCII form (punycode, dotted IPv4) and returns an empty string for an invalid hostname\n- Added a new global class `User`\n- Added a new action method `.env(str)` for definining environment in the action `$.env {String}`\n- Added a new action and controller's method `$.throw(err)` to printing error into the console\n- Added a new action and controller's method `$.touch([url])`\n- Added a new action and controller's method `$.invalidsafe(msg, err)`\n- Added a new command `total5 test [name1] [name2]` that runs the tests from the current directory or from its `tests` directory (it loads `config`, the optional `init.js` and the scripts; without names it runs all scripts)\n- Added `Test.fake(name, action)` that replaces an action with a fake and `Test.restore()` that puts the original actions back\n- Added a native PostgreSQL client + QueryBuilderPG, initialization `DATA.init('connection name', 'connection string?pooling=1')`\n\n## Changed\n\n- Improved `total5 test`: the framework of the tested project is found from its subdirectories too (e.g. from `tests`)\n- Security: hardened the hostnames against the Node.js security release of 2026-10-21 (patched in Node.js 22.23.4, 24.22.1 and 26.12.1); the framework does not require a specific version of Node.js, the hostnames are normalized and validated in the framework itself\n\t- CVE-2026-105482: `dns.resolve*()` truncates a name at a NUL byte (`attacker.example\\0.trusted.example`)\n\t- CVE-2026-105483, CVE-2026-106069, CVE-2026-106072: `tls.checkServerIdentity()` with IPv4 literals written with non-ASCII digits, leading zeros or in a non-canonical form (`0x7f.0.0.1`, `127.1`, `2130706433`)\n- Note: the issue CVE-2026-105481 (unsolicited data on a reused keep-alive socket, `http.Agent`) is fixed only by updating Node.js; the Brotli issue CVE-2026-111497 does not affect the framework (only `gzip` and `deflate` are decompressed)\n\n## Fixed\n\n- Fixed `AIPARSER()` with tool calling\n- Fixed `CRON()` with the step form (`*/15`, `5/20`): it matches the values of the step and not every value\n- Fixed the `limit` argument of `setTimeout2()`\n- Fixed `AJAX()` for the answers with `application/xml` and `text/xml`\n- Fixed `F.python()` without a callback (the promise resolves with the output) and `F.pipinstall()` without a callback\n- Fixed `LOGMAIL()` with an object as the body\n- Fixed `IMPORT()`: an answer with the status 400 or more, or a file that is not a module, gives an error\n- Fixed the tunnel client (`proxy.js`): the types of the messages \"error\" and \"abort\"\n- Fixed the controller method `$.href()`\n- Fixed `QueryBuilder.gridfields()`: the accepted fields are applied\n- Fixed the handling of the pending requests (a single pass instead of `splice()` for each finished request)\n- Fixed the memory under load: a finished request leaves the list of pending requests at once (the list kept every request with its `req` and `res` until the next timeout check, every 5 seconds, so the memory grew with the traffic)\n- Fixed the timeout check of the pending requests: the timeout answer of one request no longer removes another unanswered request from the list (that request never got its timeout answer)\n- Fixed `LDAP()`: a bind with a status other than 0 gives an error even when the server sends no text\n- Fixed `attachmentfs()` in the mail: the file of the storage is read as a Buffer and the message is completed (it threw a `TypeError` and the SMTP connection stayed open)\n- Fixed `attachment()` with a `Buffer` in the mail: the Base64 of the whole Buffer is split into lines (the bytes were split into pieces of 68 bytes and each one got its own padding)\n- Fixed `@{hostname()}` view engine command\n- Fixed `U.resolve()` (used by `REQUEST()`): an invalid hostname gives an error before the DNS query\n- Fixed `U.connect()`: the `host` is normalized and an invalid hostname gives the `Invalid hostname` error\n- Fixed the SMTP `server` in the mail: the hostname is normalized (international names to punycode, IPv4 to the canonical form) and an invalid hostname gives the `Invalid SMTP server hostname.` error\n- Fixed `url` in the view engine\n- Fixed `$.invalidsafe(msg, err)`: in an action it threw a `ReferenceError` (the request ended in a timeout) and in a controller the error for the log was replaced by the message for the user\n- Fixed sending emails through the Total API with `CONF.$tapimail` (the callbacks of `MAIL()`, `HTMLMAIL()` and `LOGMAIL()` run) and the audit logs with `CONF.$tapilogger`\n- Fixed the `X-Priority` and `Sensitivity` headers of `high()`, `low()` and `confidential()` in the mail sent over SMTP\n- Fixed the `writer` option of `REQUEST()`: it was ignored and an empty body was sent\n- Fixed `RESTBuilder.API().get()`: it switched the request to GET and failed with \"write after end\"\n- Fixed `compress()` of `RESTBuilder.API()`: `null` values were still sent\n- Fixed `U.set()` with a path that goes on after an index (`items[0].name` made `items[0]` an array)\n- Fixed the `cache` option of `NEWACTION()`: actions without `id` shared one cache entry, and the caller could change the cached response\n- Fixed the `tls` option of `U.connect()`: the socket was never upgraded\n- Fixed `U.parseURI()`, `REQUEST()`, `RESTBuilder` and proxies with credentials in the URL (`user:pass@`): they failed with \"user is not defined\"\n- Fixed the `>` and `<` prefixes of `update()` and `modify()` in the NoSQL QueryBuilder\n- Fixed the `-`, `*` and `/` prefixes of `update()` and `modify()` in the NoSQL QueryBuilder (they all added the value)\n- Fixed `scalar()` of the NoSQL QueryBuilder: `avg` returns the average, and the aggregates work without a key\n- Fixed `count` and `pages` of `list()` with the NoSQL QueryBuilder\n- Fixed `search()` with `beg` and `end` in the PostgreSQL QueryBuilder, also on columns that are not text\n- Fixed the toggle `!name` of `update()` in the PostgreSQL QueryBuilder (the column is quoted)\n- Fixed `fields()` before `autoquery()` and `autoqueryjson()`: later queries no longer select extra columns\n- Fixed `gridfields()` with an empty or missing value\n- Fixed the `memory` key of FlowStream: it did not limit the heap of forks and worker threads\n- Fixed `$.send(null)` in FlowStream: `end` fired once per output, and an output without a ready target stopped the message for the next outputs\n- Fixed `TRANSFORM()` without a callback: `$.invalid()` threw a `TypeError` and the Promise never settled\n- Fixed `F.worker.isfork`: it was `true` in worker threads and `false` in forks\n- Fixed `NEWFORK()`: `--worker` did not reach the child process, so `F.worker.is` was `false` in forks\n- Fixed `NEWTHREADPOOL()`: `worker.data` was `undefined` in pool threads, `pool.count` was the pool object, and a worker that exited threw a `ReferenceError` and was not replaced\n- Fixed loading the framework from `node -e` (`process.argv[1]` and `process.mainModule` are undefined there)\n- Fixed `async` actions that throw an exception: the action is answered with an error (routes and MCP tools) instead of waiting for the timeout\n- Fixed the errors of JSON schema arrays whose items are objects with properties (wrong path, index and error)\n- Fixed double HTML encoding of the text added by `@{title2()}`\n- Fixed double HTML encoding of the title, description and keywords set by `@{meta(title, description, keywords)}`\n- Fixed `@{language}` in views rendered with `F.view()`\n- Fixed a global variable `language` created by every compiled view\n- Fixed views with more than one `@{}` value in a `<style>` block\n- Fixed `$.href()` with an object or array value, a trailing `&`, and lost parameters when it is called more than once\n- Fixed `$.href({ key: value })` and `@{href({ key: value })}`: they returned the URL without the query\n- Fixed the `filter` argument of `Image.miniature()` (and `.filter()`): it was placed after `-thumbnail`\n- Fixed `Image.background()`: `-background` goes before `-extent` so the color is used\n- Fixed the `[attr]` selector without a value in the HTML parser\n- Fixed `F.TCMS.compile()` with an object of widgets\n- Fixed binary WebSocket messages with compression: they were sent as compressed text frames\n- Fixed WebSocket clients refused by the authorization: they get the close code `4001` (or `4004`) instead of a dropped connection\n- Fixed the compression errors of WebSocket messages: they threw \"self is not defined\" instead of reaching the `error` event\n- Fixed `WEBSOCKETCLIENT` losing a message that arrives together with the `101` answer\n- Fixed `fs.clone(id)` without a new id in the Promise form\n- Fixed `clone()`, `copy()` and `readbuffer()` of `FILESTORAGE` while the storage is paused\n- Fixed `$tms : false`: it did not remove the TMS route when `$tmsurl` stayed the same\n- Fixed MCP tools whose action throws an exception: the request gets an error answer instead of waiting for the timeout\n- Fixed the MCP edit proxy (`options.editmcp`): it lists the `App_*` tools, `App_mkdir` creates the folder inside the project and `App_read` returns the current revision\n- Fixed the MCP edit tools: paths without the leading `/`, `App_delete` removes the revisions of the deleted file or folder and answers for `/`, `App_move` of a folder moves the revisions of its files (and not those of a folder with a longer name)\n- Fixed `App_move` of a folder in the MCP edit tools on Windows: the moved revisions were saved with `\\` in their path and `App_read` did not find them\n- Fixed `AIPARSER('ollama')` with tool calls in separate chunks: it reads `function.index`\n- Fixed the generic `AIPARSER()` with tool calls without id in separate chunks: they no longer overwrite each other\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"Jaftvh1cP61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-20/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"de","title":"0.0.20","summary":"Was sich in Release 0.0.20 geändert hat.","markdown":"---\ntitle: 0.0.20\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-20/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# 0.0.20\n\n> Was sich in Release 0.0.20 geändert hat.\n\nRelease 0.0.20 des npm-Pakets `total5`.\n\n## Neu\n\n- Statistiken um die Eigenschaft `app` erweitert\n- `Total.FsPromises` als Verweis auf `node:fs/promises` hinzugefügt\n- Modul `mcp` hinzugefügt\n\t- `CONF.$mcp = true` aktiviert die MCP-Route `POST /$mcp/`\n\t- Jede `NEWACTION` mit der Eigenschaft `mcp: true` ist im Endpunkt verfügbar\n- MCP-Code-Modus hinzugefügt: `GET /$mcp/client.js` gibt einen JavaScript-Client der MCP-Tools zurück (eine Funktion pro Tool, mit JSDoc für ihre Argumente und ihr Ergebnis), der sie über `tools/call` aufruft, sodass ein Agent ein Skript schreiben kann, das die Tools verwendet, und nur die Ausgabe des Skripts zum Modell zurückgeht\n\t- es gelten dasselbe `Total.mcp.auth` (`Authorization: Bearer`) und `Total.mcp.filter` wie für `tools/list`: `Total.mcp.filter(tool, $)` entscheidet, welche Tools ein Aufrufer sieht und aufrufen darf, und die Tools laufen als der Benutzer, den `Total.mcp.auth` zurückgibt\n\t- `?q=words` gibt nur die Tools zurück, deren Name oder Beschreibung alle Wörter enthält\n\t- er ist verfügbar, sobald `CONF.$mcp` aktiviert ist; auf dem Server läuft nichts\n- Neue Methode `JSONSchema.toAIObject(name, [description])` hinzugefügt\n- Neue Methode `JSONSchema.toAITool(name)` hinzugefügt\n- `QueryBuilder.autoqueryjson($, column, schema, [defsort], [maxlimit])` hinzugefügt, das wie `autoquery()` funktioniert, aber für Eigenschaften, die in einer JSON(B)-Spalte gespeichert sind; der Builder verwendet den neutralen Namen `json:column:property:type`, und der Datenbankadapter übersetzt ihn in SQL\n- Neue Controller-Methode `$.content(value, content_type)` hinzugefügt\n- Neues Event `reset` im FlowStream hinzugefügt\n- Unterstützung für die Option `cache` von `NEWACTION()` hinzugefügt (die Antwort wird für dieselben `query`, `params`, `input`, `user` oder `language` aufbewahrt)\n- Die kompakten Schematypen `json` und `ip` hinzugefügt (die Werte werden validiert)\n- Den kompakten Schematyp `email2` hinzugefügt: Er funktioniert wie `email` und entfernt den Tag der Adresse (`name+tag@domain.com` wird zu `name@domain.com`)\n- `U.validhost(host)` hinzugefügt, das nur reine Hostnamen und kanonische IP-Literale akzeptiert\n- `U.tohost(host)` hinzugefügt, das einen Hostnamen in die kanonische ASCII-Form umwandelt (Punycode, IPv4 in Punktschreibweise) und für einen ungültigen Hostnamen einen leeren String zurückgibt\n- Neue globale Klasse `User` hinzugefügt\n- Neue Aktionsmethode `.env(str)` hinzugefügt, um die Umgebung in der Aktion `$.env {String}` festzulegen\n- Neue Methode `$.throw(err)` für Aktionen und Controller hinzugefügt, die einen Fehler in die Konsole ausgibt\n- Neue Methode `$.touch([url])` für Aktionen und Controller hinzugefügt\n- Neue Methode `$.invalidsafe(msg, err)` für Aktionen und Controller hinzugefügt\n- Neuer Befehl `total5 test [name1] [name2]` hinzugefügt, der die Tests aus dem aktuellen Verzeichnis oder aus seinem Verzeichnis `tests` ausführt (er lädt `config`, das optionale `init.js` und die Skripte; ohne Namen führt er alle Skripte aus)\n- `Test.fake(name, action)` hinzugefügt, das eine Aktion durch einen Fake ersetzt, und `Test.restore()`, das die ursprünglichen Aktionen wiederherstellt\n- Nativen PostgreSQL-Client + QueryBuilderPG hinzugefügt, Initialisierung mit `DATA.init('connection name', 'connection string?pooling=1')`\n\n## Geändert\n\n- `total5 test` verbessert: Das Framework des getesteten Projekts wird auch aus seinen Unterverzeichnissen gefunden (z. B. aus `tests`)\n- Sicherheit: die Hostnamen gegen das Node.js-Sicherheitsrelease vom 2026-10-21 gehärtet (behoben in Node.js 22.23.4, 24.22.1 und 26.12.1); das Framework verlangt keine bestimmte Node.js-Version, die Hostnamen werden im Framework selbst normalisiert und validiert\n\t- CVE-2026-105482: `dns.resolve*()` schneidet einen Namen an einem NUL-Byte ab (`attacker.example\\0.trusted.example`)\n\t- CVE-2026-105483, CVE-2026-106069, CVE-2026-106072: `tls.checkServerIdentity()` mit IPv4-Literalen, die mit Nicht-ASCII-Ziffern, führenden Nullen oder in einer nicht kanonischen Form geschrieben sind (`0x7f.0.0.1`, `127.1`, `2130706433`)\n- Hinweis: Das Problem CVE-2026-105481 (unaufgeforderte Daten auf einem wiederverwendeten Keep-Alive-Socket, `http.Agent`) wird nur durch ein Update von Node.js behoben; das Brotli-Problem CVE-2026-111497 betrifft das Framework nicht (nur `gzip` und `deflate` werden dekomprimiert)\n\n## Behoben\n\n- `AIPARSER()` mit Tool-Aufrufen behoben\n- `CRON()` mit der Schrittform (`*/15`, `5/20`) behoben: Es trifft die Werte der Schrittweite und nicht jeden Wert\n- Das Argument `limit` von `setTimeout2()` behoben\n- `AJAX()` für Antworten mit `application/xml` und `text/xml` behoben\n- `F.python()` ohne Callback (die Promise wird mit der Ausgabe aufgelöst) und `F.pipinstall()` ohne Callback behoben\n- `LOGMAIL()` mit einem Objekt als Body behoben\n- `IMPORT()` behoben: Eine Antwort mit dem Status 400 oder mehr oder eine Datei, die kein Modul ist, führt zu einem Fehler\n- Den Tunnel-Client (`proxy.js`) behoben: die Typen der Nachrichten \"error\" und \"abort\"\n- Die Controller-Methode `$.href()` behoben\n- `QueryBuilder.gridfields()` behoben: Die akzeptierten Felder werden angewendet\n- Die Behandlung der ausstehenden Anfragen behoben (ein einziger Durchlauf statt `splice()` für jede beendete Anfrage)\n- Den Speicher unter Last behoben: Eine beendete Anfrage verlässt die Liste der ausstehenden Anfragen sofort (die Liste behielt jede Anfrage mit ihrem `req` und `res` bis zur nächsten Timeout-Prüfung, alle 5 Sekunden, sodass der Speicher mit dem Traffic wuchs)\n- Die Timeout-Prüfung der ausstehenden Anfragen behoben: Die Timeout-Antwort einer Anfrage entfernt keine andere unbeantwortete Anfrage mehr aus der Liste (diese Anfrage erhielt nie ihre Timeout-Antwort)\n- `LDAP()` behoben: Ein Bind mit einem anderen Status als 0 führt zu einem Fehler, auch wenn der Server keinen Text sendet\n- `attachmentfs()` in der Mail behoben: Die Datei des Speichers wird als Buffer gelesen, und die Nachricht wird fertiggestellt (es warf einen `TypeError`, und die SMTP-Verbindung blieb offen)\n- `attachment()` mit einem `Buffer` in der Mail behoben: Das Base64 des ganzen Buffers wird in Zeilen aufgeteilt (die Bytes wurden in Stücke von 68 Bytes aufgeteilt, und jedes erhielt sein eigenes Padding)\n- Den View-Engine-Befehl `@{hostname()}` behoben\n- `U.resolve()` (verwendet von `REQUEST()`) behoben: Ein ungültiger Hostname führt vor der DNS-Abfrage zu einem Fehler\n- `U.connect()` behoben: Der `host` wird normalisiert, und ein ungültiger Hostname führt zum Fehler `Invalid hostname`\n- Den SMTP-`server` in der Mail behoben: Der Hostname wird normalisiert (internationale Namen zu Punycode, IPv4 in die kanonische Form), und ein ungültiger Hostname führt zum Fehler `Invalid SMTP server hostname.`\n- `url` in der View-Engine behoben\n- `$.invalidsafe(msg, err)` behoben: In einer Aktion warf es einen `ReferenceError` (die Anfrage endete in einem Timeout), und in einem Controller wurde der Fehler für das Log durch die Meldung für den Benutzer ersetzt\n- Das Senden von E-Mails über die Total API mit `CONF.$tapimail` (die Callbacks von `MAIL()`, `HTMLMAIL()` und `LOGMAIL()` laufen) und die Audit-Logs mit `CONF.$tapilogger` behoben\n- Die Header `X-Priority` und `Sensitivity` von `high()`, `low()` und `confidential()` in der über SMTP gesendeten Mail behoben\n- Die Option `writer` von `REQUEST()` behoben: Sie wurde ignoriert, und es wurde ein leerer Body gesendet\n- `RESTBuilder.API().get()` behoben: Es stellte die Anfrage auf GET um und schlug mit \"write after end\" fehl\n- `compress()` von `RESTBuilder.API()` behoben: `null`-Werte wurden trotzdem gesendet\n- `U.set()` mit einem Pfad behoben, der nach einem Index weitergeht (`items[0].name` machte `items[0]` zu einem Array)\n- Die Option `cache` von `NEWACTION()` behoben: Aktionen ohne `id` teilten sich einen Cache-Eintrag, und der Aufrufer konnte die gecachte Antwort ändern\n- Die Option `tls` von `U.connect()` behoben: Der Socket wurde nie auf TLS umgestellt\n- `U.parseURI()`, `REQUEST()`, `RESTBuilder` und Proxys mit Zugangsdaten in der URL (`user:pass@`) behoben: Sie schlugen mit \"user is not defined\" fehl\n- Die Präfixe `>` und `<` von `update()` und `modify()` im NoSQL-QueryBuilder behoben\n- Die Präfixe `-`, `*` und `/` von `update()` und `modify()` im NoSQL-QueryBuilder behoben (sie addierten alle den Wert)\n- `scalar()` des NoSQL-QueryBuilders behoben: `avg` gibt den Durchschnitt zurück, und die Aggregate funktionieren ohne Schlüssel\n- `count` und `pages` von `list()` mit dem NoSQL-QueryBuilder behoben\n- `search()` mit `beg` und `end` im PostgreSQL-QueryBuilder behoben, auch bei Spalten, die kein Text sind\n- Das Umschalten `!name` von `update()` im PostgreSQL-QueryBuilder behoben (die Spalte wird in Anführungszeichen gesetzt)\n- `fields()` vor `autoquery()` und `autoqueryjson()` behoben: Spätere Abfragen wählen keine zusätzlichen Spalten mehr aus\n- `gridfields()` mit einem leeren oder fehlenden Wert behoben\n- Den Schlüssel `memory` von FlowStream behoben: Er begrenzte den Heap von Forks und Worker-Threads nicht\n- `$.send(null)` in FlowStream behoben: `end` wurde einmal pro Ausgang ausgelöst, und ein Ausgang ohne bereites Ziel stoppte die Nachricht für die nächsten Ausgänge\n- `TRANSFORM()` ohne Callback behoben: `$.invalid()` warf einen `TypeError`, und das Promise wurde nie abgeschlossen\n- `F.worker.isfork` behoben: Es war `true` in Worker-Threads und `false` in Forks\n- `NEWFORK()` behoben: `--worker` erreichte den Kindprozess nicht, daher war `F.worker.is` in Forks `false`\n- `NEWTHREADPOOL()` behoben: `worker.data` war in Pool-Threads `undefined`, `pool.count` war das Pool-Objekt, und ein Worker, der sich beendete, warf einen `ReferenceError` und wurde nicht ersetzt\n- Das Laden des Frameworks aus `node -e` behoben (`process.argv[1]` und `process.mainModule` sind dort undefiniert)\n- `async`-Aktionen behoben, die eine Exception werfen: Die Aktion wird mit einem Fehler beantwortet (Routen und MCP-Tools), statt auf das Timeout zu warten\n- Die Fehler von JSON-Schema-Arrays behoben, deren Elemente Objekte mit Eigenschaften sind (falscher Pfad, Index und Fehler)\n- Die doppelte HTML-Kodierung des mit `@{title2()}` hinzugefügten Textes behoben\n- Die doppelte HTML-Kodierung von Titel, Beschreibung und Keywords behoben, die mit `@{meta(title, description, keywords)}` gesetzt werden\n- `@{language}` in Views behoben, die mit `F.view()` gerendert werden\n- Eine globale Variable `language` behoben, die jede kompilierte View erzeugte\n- Views mit mehr als einem `@{}`-Wert in einem `<style>`-Block behoben\n- `$.href()` mit einem Objekt oder Array als Wert, einem abschließenden `&` und verlorenen Parametern bei mehrfachem Aufruf behoben\n- `$.href({ key: value })` und `@{href({ key: value })}` behoben: Sie gaben die URL ohne die Query zurück\n- Das Argument `filter` von `Image.miniature()` (und `.filter()`) behoben: Es wurde nach `-thumbnail` gesetzt\n- `Image.background()` behoben: `-background` steht vor `-extent`, damit die Farbe verwendet wird\n- Den Selektor `[attr]` ohne Wert im HTML-Parser behoben\n- `F.TCMS.compile()` mit einem Objekt von Widgets behoben\n- Binäre WebSocket-Nachrichten mit Komprimierung behoben: Sie wurden als komprimierte Text-Frames gesendet\n- WebSocket-Clients behoben, die von der Autorisierung abgelehnt werden: Sie erhalten den Close-Code `4001` (oder `4004`) statt einer abgebrochenen Verbindung\n- Die Komprimierungsfehler von WebSocket-Nachrichten behoben: Sie warfen \"self is not defined\", statt das Event `error` zu erreichen\n- `WEBSOCKETCLIENT` behoben, das eine Nachricht verlor, die zusammen mit der Antwort `101` eintrifft\n- `fs.clone(id)` ohne neue ID in der Promise-Form behoben\n- `clone()`, `copy()` und `readbuffer()` von `FILESTORAGE` behoben, während der Speicher pausiert ist\n- `$tms : false` behoben: Es entfernte die TMS-Route nicht, wenn `$tmsurl` gleich blieb\n- MCP-Tools behoben, deren Aktion eine Exception wirft: Die Anfrage erhält eine Fehlerantwort, statt auf das Timeout zu warten\n- Den MCP-Bearbeitungs-Proxy (`options.editmcp`) behoben: Er listet die `App_*`-Tools auf, `App_mkdir` erstellt den Ordner innerhalb des Projekts und `App_read` gibt die aktuelle Revision zurück\n- Die MCP-Bearbeitungstools behoben: Pfade ohne führendes `/`, `App_delete` entfernt die Revisionen der gelöschten Datei oder des gelöschten Ordners und antwortet für `/`, `App_move` eines Ordners verschiebt die Revisionen seiner Dateien (und nicht die eines Ordners mit längerem Namen)\n- `App_move` eines Ordners in den MCP-Bearbeitungstools unter Windows behoben: Die verschobenen Revisionen wurden mit `\\` in ihrem Pfad gespeichert, und `App_read` fand sie nicht\n- `AIPARSER('ollama')` mit Tool-Aufrufen in getrennten Chunks behoben: Es liest `function.index`\n- Das generische `AIPARSER()` mit Tool-Aufrufen ohne ID in getrennten Chunks behoben: Sie überschreiben sich nicht mehr gegenseitig\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"Jaftvh1cP61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-20/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"es","title":"0.0.20","summary":"Qué cambió en la versión 0.0.20.","markdown":"---\ntitle: 0.0.20\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-20/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# 0.0.20\n\n> Qué cambió en la versión 0.0.20.\n\nVersión 0.0.20 del paquete npm `total5`.\n\n## Novedades\n\n- Ampliadas las estadísticas con la propiedad `app`\n- Añadido `Total.FsPromises`, un enlace a `node:fs/promises`\n- Añadido el módulo `mcp`\n\t- `CONF.$mcp = true` activa la ruta MCP `POST /$mcp/`\n\t- Cualquier `NEWACTION` con la propiedad `mcp: true` estará disponible en el endpoint\n- Añadido el modo código de MCP: `GET /$mcp/client.js` devuelve un cliente JavaScript de las herramientas MCP (una función por herramienta, con JSDoc para sus argumentos y su resultado) que las llama mediante `tools/call`, así un agente puede escribir un script que usa las herramientas y al modelo solo vuelve la salida del script\n\t- se aplican los mismos `Total.mcp.auth` (`Authorization: Bearer`) y `Total.mcp.filter` que para `tools/list`: `Total.mcp.filter(tool, $)` decide qué herramientas ve y puede llamar quien llama, y las herramientas se ejecutan como el usuario que devuelve `Total.mcp.auth`\n\t- `?q=words` devuelve solo las herramientas cuyo nombre o descripción contienen todas las palabras\n\t- está disponible siempre que `CONF.$mcp` esté activado; en el servidor no se ejecuta nada\n- Añadido un nuevo método `JSONSchema.toAIObject(name, [description])`\n- Añadido un nuevo método `JSONSchema.toAITool(name)`\n- Añadido `QueryBuilder.autoqueryjson($, column, schema, [defsort], [maxlimit])`, que funciona como `autoquery()` pero para propiedades guardadas en una columna JSON(B); el builder usa el nombre neutro `json:column:property:type` y el adaptador de la base de datos lo traduce a SQL\n- Añadido un nuevo método del controlador `$.content(value, content_type)`\n- Añadido un nuevo evento `reset` en FlowStream\n- Añadido soporte para la opción `cache` de `NEWACTION()` (la respuesta se guarda para los mismos `query`, `params`, `input`, `user` o `language`)\n- Añadidos los tipos de esquema compactos `json` e `ip` (los valores se validan)\n- Añadido el tipo de esquema compacto `email2`: funciona como `email` y quita la etiqueta de la dirección (`name+tag@domain.com` se convierte en `name@domain.com`)\n- Añadido `U.validhost(host)`, que acepta solo nombres de host simples y literales IP canónicos\n- Añadido `U.tohost(host)`, que convierte un nombre de host a la forma ASCII canónica (punycode, IPv4 con puntos) y devuelve un string vacío para un nombre de host no válido\n- Añadida una nueva clase global `User`\n- Añadido un nuevo método de acción `.env(str)` para definir el entorno en la acción `$.env {String}`\n- Añadido un nuevo método de acción y de controlador `$.throw(err)` para imprimir un error en la consola\n- Añadido un nuevo método de acción y de controlador `$.touch([url])`\n- Añadido un nuevo método de acción y de controlador `$.invalidsafe(msg, err)`\n- Añadido un nuevo comando `total5 test [name1] [name2]` que ejecuta los tests del directorio actual o de su directorio `tests` (carga `config`, el `init.js` opcional y los scripts; sin nombres ejecuta todos los scripts)\n- Añadidos `Test.fake(name, action)`, que sustituye una acción por una falsa, y `Test.restore()`, que vuelve a poner las acciones originales\n- Añadido un cliente nativo de PostgreSQL + QueryBuilderPG, inicialización `DATA.init('connection name', 'connection string?pooling=1')`\n\n## Cambios\n\n- Mejorado `total5 test`: el framework del proyecto probado también se encuentra desde sus subdirectorios (p. ej. desde `tests`)\n- Seguridad: reforzados los nombres de host frente a la versión de seguridad de Node.js del 2026-10-21 (corregida en Node.js 22.23.4, 24.22.1 y 26.12.1); el framework no exige una versión concreta de Node.js, los nombres de host se normalizan y validan en el propio framework\n\t- CVE-2026-105482: `dns.resolve*()` trunca un nombre en un byte NUL (`attacker.example\\0.trusted.example`)\n\t- CVE-2026-105483, CVE-2026-106069, CVE-2026-106072: `tls.checkServerIdentity()` con literales IPv4 escritos con dígitos no ASCII, ceros iniciales o en una forma no canónica (`0x7f.0.0.1`, `127.1`, `2130706433`)\n- Nota: el problema CVE-2026-105481 (datos no solicitados en un socket keep-alive reutilizado, `http.Agent`) solo se corrige actualizando Node.js; el problema de Brotli CVE-2026-111497 no afecta al framework (solo se descomprimen `gzip` y `deflate`)\n\n## Correcciones\n\n- Corregido `AIPARSER()` con llamadas a herramientas\n- Corregido `CRON()` con la forma de paso (`*/15`, `5/20`): coincide con los valores del paso y no con todos los valores\n- Corregido el argumento `limit` de `setTimeout2()`\n- Corregido `AJAX()` para las respuestas con `application/xml` y `text/xml`\n- Corregido `F.python()` sin callback (la promesa se resuelve con la salida) y `F.pipinstall()` sin callback\n- Corregido `LOGMAIL()` con un objeto como cuerpo\n- Corregido `IMPORT()`: una respuesta con el estado 400 o más, o un archivo que no es un módulo, da un error\n- Corregido el cliente del túnel (`proxy.js`): los tipos de los mensajes \"error\" y \"abort\"\n- Corregido el método del controlador `$.href()`\n- Corregido `QueryBuilder.gridfields()`: se aplican los campos aceptados\n- Corregida la gestión de las peticiones pendientes (una sola pasada en lugar de `splice()` por cada petición terminada)\n- Corregida la memoria bajo carga: una petición terminada sale enseguida de la lista de peticiones pendientes (la lista guardaba cada petición con su `req` y su `res` hasta la siguiente comprobación de timeout, cada 5 segundos, así que la memoria crecía con el tráfico)\n- Corregida la comprobación de timeout de las peticiones pendientes: la respuesta de timeout de una petición ya no quita de la lista otra petición sin responder (esa petición nunca recibía su respuesta de timeout)\n- Corregido `LDAP()`: un bind con un estado distinto de 0 da un error aunque el servidor no envíe texto\n- Corregido `attachmentfs()` en el correo: el archivo del almacenamiento se lee como Buffer y el mensaje se completa (lanzaba un `TypeError` y la conexión SMTP quedaba abierta)\n- Corregido `attachment()` con un `Buffer` en el correo: el Base64 de todo el Buffer se divide en líneas (los bytes se dividían en trozos de 68 bytes y cada uno recibía su propio relleno)\n- Corregido el comando del motor de vistas `@{hostname()}`\n- Corregido `U.resolve()` (usado por `REQUEST()`): un nombre de host no válido da un error antes de la consulta DNS\n- Corregido `U.connect()`: el `host` se normaliza y un nombre de host no válido da el error `Invalid hostname`\n- Corregido el `server` SMTP en el correo: el nombre de host se normaliza (nombres internacionales a punycode, IPv4 a la forma canónica) y un nombre de host no válido da el error `Invalid SMTP server hostname.`\n- Corregido `url` en el motor de vistas\n- Corregido `$.invalidsafe(msg, err)`: en una acción lanzaba un `ReferenceError` (la petición terminaba por timeout) y en un controlador el error para el log se sustituía por el mensaje para el usuario\n- Corregido el envío de correos a través de Total API con `CONF.$tapimail` (se ejecutan los callbacks de `MAIL()`, `HTMLMAIL()` y `LOGMAIL()`) y de los registros de auditoría con `CONF.$tapilogger`\n- Corregidas las cabeceras `X-Priority` y `Sensitivity` de `high()`, `low()` y `confidential()` en el correo enviado por SMTP\n- Corregida la opción `writer` de `REQUEST()`: se ignoraba y se enviaba un cuerpo vacío\n- Corregido `RESTBuilder.API().get()`: cambiaba la petición a GET y fallaba con \"write after end\"\n- Corregido `compress()` de `RESTBuilder.API()`: los valores `null` se seguían enviando\n- Corregido `U.set()` con una ruta que continúa después de un índice (`items[0].name` convertía `items[0]` en un array)\n- Corregida la opción `cache` de `NEWACTION()`: las acciones sin `id` compartían una sola entrada de caché, y quien llamaba podía cambiar la respuesta guardada en caché\n- Corregida la opción `tls` de `U.connect()`: el socket nunca pasaba a TLS\n- Corregidos `U.parseURI()`, `REQUEST()`, `RESTBuilder` y los proxies con credenciales en la URL (`user:pass@`): fallaban con \"user is not defined\"\n- Corregidos los prefijos `>` y `<` de `update()` y `modify()` en el QueryBuilder de NoSQL\n- Corregidos los prefijos `-`, `*` y `/` de `update()` y `modify()` en el QueryBuilder de NoSQL (todos sumaban el valor)\n- Corregido `scalar()` del QueryBuilder de NoSQL: `avg` devuelve la media, y los agregados funcionan sin clave\n- Corregidos `count` y `pages` de `list()` con el QueryBuilder de NoSQL\n- Corregido `search()` con `beg` y `end` en el QueryBuilder de PostgreSQL, también en columnas que no son de texto\n- Corregido el conmutador `!name` de `update()` en el QueryBuilder de PostgreSQL (la columna va entre comillas)\n- Corregido `fields()` antes de `autoquery()` y `autoqueryjson()`: las consultas posteriores ya no seleccionan columnas de más\n- Corregido `gridfields()` con un valor vacío o que falta\n- Corregida la clave `memory` de FlowStream: no limitaba el heap de los forks y de los hilos worker\n- Corregido `$.send(null)` en FlowStream: `end` se disparaba una vez por salida, y una salida sin un destino listo detenía el mensaje para las salidas siguientes\n- Corregido `TRANSFORM()` sin callback: `$.invalid()` lanzaba un `TypeError` y la Promise nunca se resolvía\n- Corregido `F.worker.isfork`: era `true` en los hilos worker y `false` en los forks\n- Corregido `NEWFORK()`: `--worker` no llegaba al proceso hijo, así que `F.worker.is` era `false` en los forks\n- Corregido `NEWTHREADPOOL()`: `worker.data` era `undefined` en los hilos del pool, `pool.count` era el objeto del pool, y un worker que terminaba lanzaba un `ReferenceError` y no se sustituía\n- Corregida la carga del framework desde `node -e` (allí `process.argv[1]` y `process.mainModule` son undefined)\n- Corregidas las acciones `async` que lanzan una excepción: la acción se responde con un error (rutas y herramientas MCP) en lugar de esperar al timeout\n- Corregidos los errores de los arrays de esquemas JSON cuyos elementos son objetos con propiedades (ruta, índice y error incorrectos)\n- Corregida la doble codificación HTML del texto añadido con `@{title2()}`\n- Corregida la doble codificación HTML del título, la descripción y las palabras clave establecidos con `@{meta(title, description, keywords)}`\n- Corregido `@{language}` en las vistas renderizadas con `F.view()`\n- Corregida una variable global `language` que creaba cada vista compilada\n- Corregidas las vistas con más de un valor `@{}` en un bloque `<style>`\n- Corregido `$.href()` con un valor objeto o array, un `&` final y parámetros perdidos cuando se llama más de una vez\n- Corregidos `$.href({ key: value })` y `@{href({ key: value })}`: devolvían la URL sin la query\n- Corregido el argumento `filter` de `Image.miniature()` (y de `.filter()`): se colocaba después de `-thumbnail`\n- Corregido `Image.background()`: `-background` va antes de `-extent`, así se usa el color\n- Corregido el selector `[attr]` sin valor en el parser de HTML\n- Corregido `F.TCMS.compile()` con un objeto de widgets\n- Corregidos los mensajes WebSocket binarios con compresión: se enviaban como frames de texto comprimidos\n- Corregidos los clientes WebSocket rechazados por la autorización: reciben el código de cierre `4001` (o `4004`) en lugar de una conexión cortada\n- Corregidos los errores de compresión de los mensajes WebSocket: lanzaban \"self is not defined\" en lugar de llegar al evento `error`\n- Corregido `WEBSOCKETCLIENT`, que perdía un mensaje que llegaba junto con la respuesta `101`\n- Corregido `fs.clone(id)` sin id nuevo en la forma con Promise\n- Corregidos `clone()`, `copy()` y `readbuffer()` de `FILESTORAGE` mientras el almacenamiento está en pausa\n- Corregido `$tms : false`: no eliminaba la ruta TMS cuando `$tmsurl` seguía igual\n- Corregidas las herramientas MCP cuya acción lanza una excepción: la petición recibe una respuesta de error en lugar de esperar al timeout\n- Corregido el proxy de edición MCP (`options.editmcp`): lista las herramientas `App_*`, `App_mkdir` crea la carpeta dentro del proyecto y `App_read` devuelve la revisión actual\n- Corregidas las herramientas de edición MCP: rutas sin la `/` inicial, `App_delete` elimina las revisiones del archivo o la carpeta eliminados y responde para `/`, `App_move` de una carpeta mueve las revisiones de sus archivos (y no las de una carpeta con un nombre más largo)\n- Corregido `App_move` de una carpeta en las herramientas de edición MCP en Windows: las revisiones movidas se guardaban con `\\` en su ruta y `App_read` no las encontraba\n- Corregido `AIPARSER('ollama')` con llamadas a herramientas en fragmentos separados: lee `function.index`\n- Corregido el `AIPARSER()` genérico con llamadas a herramientas sin id en fragmentos separados: ya no se sobrescriben entre sí\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"Jaftvh1cP61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-20/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"fr","title":"0.0.20","summary":"Ce qui a changé dans la version 0.0.20.","markdown":"---\ntitle: 0.0.20\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-20/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# 0.0.20\n\n> Ce qui a changé dans la version 0.0.20.\n\nVersion 0.0.20 du paquet npm `total5`.\n\n## Nouveautés\n\n- Statistiques étendues avec l'ajout de la propriété `app`\n- Ajout de `Total.FsPromises`, un lien vers `node:fs/promises`\n- Ajout du module `mcp`\n\t- `CONF.$mcp = true` active la route MCP `POST /$mcp/`\n\t- Toute `NEWACTION` avec la propriété `mcp: true` est disponible dans l'endpoint\n- Ajout du mode code MCP : `GET /$mcp/client.js` renvoie un client JavaScript des outils MCP (une fonction par outil, avec du JSDoc pour ses arguments et son résultat) qui les appelle via `tools/call`, de sorte qu'un agent peut écrire un script qui utilise les outils et que seule la sortie du script retourne au modèle\n\t- les mêmes `Total.mcp.auth` (`Authorization: Bearer`) et `Total.mcp.filter` s'appliquent que pour `tools/list` : `Total.mcp.filter(tool, $)` décide quels outils un appelant voit et peut appeler, et les outils s'exécutent avec l'utilisateur renvoyé par `Total.mcp.auth`\n\t- `?q=words` ne renvoie que les outils dont le nom ou la description contiennent tous les mots\n\t- il est disponible dès que `CONF.$mcp` est activé ; rien ne s'exécute sur le serveur\n- Ajout d'une nouvelle méthode `JSONSchema.toAIObject(name, [description])`\n- Ajout d'une nouvelle méthode `JSONSchema.toAITool(name)`\n- Ajout de `QueryBuilder.autoqueryjson($, column, schema, [defsort], [maxlimit])`, qui fonctionne comme `autoquery()` mais pour des propriétés stockées dans une colonne JSON(B) ; le builder utilise le nom neutre `json:column:property:type` et l'adaptateur de base de données le traduit en SQL\n- Ajout d'une nouvelle méthode de contrôleur `$.content(value, content_type)`\n- Ajout d'un nouvel événement `reset` dans FlowStream\n- Ajout de la prise en charge de l'option `cache` de `NEWACTION()` (la réponse est conservée pour les mêmes `query`, `params`, `input`, `user` ou `language`)\n- Ajout des types de schéma compacts `json` et `ip` (les valeurs sont validées)\n- Ajout du type de schéma compact `email2` : il fonctionne comme `email` et supprime le tag de l'adresse (`name+tag@domain.com` devient `name@domain.com`)\n- Ajout de `U.validhost(host)`, qui n'accepte que des noms d'hôte simples et des adresses IP canoniques\n- Ajout de `U.tohost(host)`, qui convertit un nom d'hôte dans la forme ASCII canonique (punycode, IPv4 à points) et renvoie une chaîne vide pour un nom d'hôte non valide\n- Ajout d'une nouvelle classe globale `User`\n- Ajout d'une nouvelle méthode d'action `.env(str)` pour définir l'environnement dans l'action `$.env {String}`\n- Ajout d'une nouvelle méthode d'action et de contrôleur `$.throw(err)` pour afficher une erreur dans la console\n- Ajout d'une nouvelle méthode d'action et de contrôleur `$.touch([url])`\n- Ajout d'une nouvelle méthode d'action et de contrôleur `$.invalidsafe(msg, err)`\n- Ajout d'une nouvelle commande `total5 test [name1] [name2]` qui lance les tests du répertoire courant ou de son répertoire `tests` (elle charge `config`, le fichier facultatif `init.js` et les scripts ; sans noms, elle lance tous les scripts)\n- Ajout de `Test.fake(name, action)`, qui remplace une action par une fausse action, et de `Test.restore()`, qui remet les actions d'origine\n- Ajout d'un client PostgreSQL natif + QueryBuilderPG, initialisation `DATA.init('connection name', 'connection string?pooling=1')`\n\n## Modifications\n\n- Amélioration de `total5 test` : le framework du projet testé est aussi trouvé depuis ses sous-répertoires (par ex. depuis `tests`)\n- Sécurité : renforcement des noms d'hôte face à la version de sécurité de Node.js du 2026-10-21 (corrigée dans Node.js 22.23.4, 24.22.1 et 26.12.1) ; le framework n'exige pas de version précise de Node.js, les noms d'hôte sont normalisés et validés dans le framework lui-même\n\t- CVE-2026-105482 : `dns.resolve*()` tronque un nom à un octet NUL (`attacker.example\\0.trusted.example`)\n\t- CVE-2026-105483, CVE-2026-106069, CVE-2026-106072 : `tls.checkServerIdentity()` avec des adresses IPv4 écrites avec des chiffres non ASCII, des zéros initiaux ou sous une forme non canonique (`0x7f.0.0.1`, `127.1`, `2130706433`)\n- Remarque : le problème CVE-2026-105481 (données non sollicitées sur un socket keep-alive réutilisé, `http.Agent`) n'est corrigé que par une mise à jour de Node.js ; le problème Brotli CVE-2026-111497 ne concerne pas le framework (seuls `gzip` et `deflate` sont décompressés)\n\n## Corrections\n\n- Correction de `AIPARSER()` avec les appels d'outils\n- Correction de `CRON()` avec la forme à pas (`*/15`, `5/20`) : il correspond aux valeurs du pas et non à toutes les valeurs\n- Correction de l'argument `limit` de `setTimeout2()`\n- Correction de `AJAX()` pour les réponses avec `application/xml` et `text/xml`\n- Correction de `F.python()` sans callback (la promesse est résolue avec la sortie) et de `F.pipinstall()` sans callback\n- Correction de `LOGMAIL()` avec un objet comme corps\n- Correction de `IMPORT()` : une réponse avec le statut 400 ou plus, ou un fichier qui n'est pas un module, donne une erreur\n- Correction du client de tunnel (`proxy.js`) : les types des messages « error » et « abort »\n- Correction de la méthode de contrôleur `$.href()`\n- Correction de `QueryBuilder.gridfields()` : les champs acceptés sont appliqués\n- Correction de la gestion des requêtes en attente (un seul passage au lieu de `splice()` pour chaque requête terminée)\n- Correction de la mémoire sous charge : une requête terminée quitte immédiatement la liste des requêtes en attente (la liste gardait chaque requête avec ses `req` et `res` jusqu'à la vérification suivante des timeouts, toutes les 5 secondes, si bien que la mémoire augmentait avec le trafic)\n- Correction de la vérification des timeouts des requêtes en attente : la réponse de timeout d'une requête ne retire plus de la liste une autre requête sans réponse (cette requête ne recevait jamais sa réponse de timeout)\n- Correction de `LDAP()` : un bind avec un statut autre que 0 donne une erreur même quand le serveur n'envoie aucun texte\n- Correction de `attachmentfs()` dans les e-mails : le fichier du stockage est lu comme un Buffer et le message est complété (elle levait une `TypeError` et la connexion SMTP restait ouverte)\n- Correction de `attachment()` avec un `Buffer` dans les e-mails : le Base64 de tout le Buffer est découpé en lignes (les octets étaient découpés en morceaux de 68 octets et chacun recevait son propre padding)\n- Correction de la commande du moteur de vues `@{hostname()}`\n- Correction de `U.resolve()` (utilisée par `REQUEST()`) : un nom d'hôte non valide donne une erreur avant la requête DNS\n- Correction de `U.connect()` : le `host` est normalisé et un nom d'hôte non valide donne l'erreur `Invalid hostname`\n- Correction du `server` SMTP dans les e-mails : le nom d'hôte est normalisé (noms internationaux en punycode, IPv4 dans la forme canonique) et un nom d'hôte non valide donne l'erreur `Invalid SMTP server hostname.`\n- Correction de `url` dans le moteur de vues\n- Correction de `$.invalidsafe(msg, err)` : dans une action, elle levait une `ReferenceError` (la requête se terminait par un timeout) et dans un contrôleur, l'erreur destinée au log était remplacée par le message destiné à l'utilisateur\n- Correction de l'envoi des e-mails via Total API avec `CONF.$tapimail` (les callbacks de `MAIL()`, `HTMLMAIL()` et `LOGMAIL()` s'exécutent) et des journaux d'audit avec `CONF.$tapilogger`\n- Correction des en-têtes `X-Priority` et `Sensitivity` de `high()`, `low()` et `confidential()` dans les e-mails envoyés par SMTP\n- Correction de l'option `writer` de `REQUEST()` : elle était ignorée et un corps vide était envoyé\n- Correction de `RESTBuilder.API().get()` : elle passait la requête en GET et échouait avec « write after end »\n- Correction de `compress()` de `RESTBuilder.API()` : les valeurs `null` étaient quand même envoyées\n- Correction de `U.set()` avec un chemin qui continue après un index (`items[0].name` faisait de `items[0]` un tableau)\n- Correction de l'option `cache` de `NEWACTION()` : les actions sans `id` partageaient une seule entrée de cache, et l'appelant pouvait modifier la réponse en cache\n- Correction de l'option `tls` de `U.connect()` : le socket n'était jamais passé en TLS\n- Correction de `U.parseURI()`, `REQUEST()`, `RESTBuilder` et des proxys avec des identifiants dans l'URL (`user:pass@`) : ils échouaient avec « user is not defined »\n- Correction des préfixes `>` et `<` de `update()` et `modify()` dans le QueryBuilder NoSQL\n- Correction des préfixes `-`, `*` et `/` de `update()` et `modify()` dans le QueryBuilder NoSQL (ils ajoutaient tous la valeur)\n- Correction de `scalar()` du QueryBuilder NoSQL : `avg` renvoie la moyenne, et les agrégats fonctionnent sans clé\n- Correction de `count` et `pages` de `list()` avec le QueryBuilder NoSQL\n- Correction de `search()` avec `beg` et `end` dans le QueryBuilder PostgreSQL, aussi sur des colonnes qui ne sont pas du texte\n- Correction de la bascule `!name` de `update()` dans le QueryBuilder PostgreSQL (la colonne est entre guillemets)\n- Correction de `fields()` avant `autoquery()` et `autoqueryjson()` : les requêtes suivantes ne sélectionnent plus de colonnes en trop\n- Correction de `gridfields()` avec une valeur vide ou absente\n- Correction de la clé `memory` de FlowStream : elle ne limitait pas le heap des forks et des worker threads\n- Correction de `$.send(null)` dans FlowStream : `end` se déclenchait une fois par sortie, et une sortie sans cible prête arrêtait le message pour les sorties suivantes\n- Correction de `TRANSFORM()` sans callback : `$.invalid()` levait une `TypeError` et la Promise n'était jamais réglée\n- Correction de `F.worker.isfork` : il valait `true` dans les worker threads et `false` dans les forks\n- Correction de `NEWFORK()` : `--worker` n'atteignait pas le processus enfant, donc `F.worker.is` valait `false` dans les forks\n- Correction de `NEWTHREADPOOL()` : `worker.data` valait `undefined` dans les threads du pool, `pool.count` était l'objet du pool, et un worker qui se terminait levait une `ReferenceError` et n'était pas remplacé\n- Correction du chargement du framework depuis `node -e` (`process.argv[1]` et `process.mainModule` y sont indéfinis)\n- Correction des actions `async` qui lèvent une exception : l'action reçoit une réponse d'erreur (routes et outils MCP) au lieu d'attendre le timeout\n- Correction des erreurs des tableaux de schémas JSON dont les éléments sont des objets avec des propriétés (chemin, index et erreur incorrects)\n- Correction du double encodage HTML du texte ajouté par `@{title2()}`\n- Correction du double encodage HTML du titre, de la description et des mots-clés définis par `@{meta(title, description, keywords)}`\n- Correction de `@{language}` dans les vues rendues avec `F.view()`\n- Correction d'une variable globale `language` créée par chaque vue compilée\n- Correction des vues avec plus d'une valeur `@{}` dans un bloc `<style>`\n- Correction de `$.href()` avec une valeur objet ou tableau, un `&` final, et des paramètres perdus quand elle est appelée plusieurs fois\n- Correction de `$.href({ key: value })` et `@{href({ key: value })}` : elles renvoyaient l'URL sans la query\n- Correction de l'argument `filter` de `Image.miniature()` (et de `.filter()`) : il était placé après `-thumbnail`\n- Correction de `Image.background()` : `-background` passe avant `-extent`, donc la couleur est utilisée\n- Correction du sélecteur `[attr]` sans valeur dans le parseur HTML\n- Correction de `F.TCMS.compile()` avec un objet de widgets\n- Correction des messages WebSocket binaires avec compression : ils étaient envoyés comme frames texte compressées\n- Correction des clients WebSocket refusés par l'autorisation : ils reçoivent le code de fermeture `4001` (ou `4004`) au lieu d'une connexion coupée\n- Correction des erreurs de compression des messages WebSocket : elles levaient « self is not defined » au lieu d'atteindre l'événement `error`\n- Correction de `WEBSOCKETCLIENT`, qui perdait un message arrivé en même temps que la réponse `101`\n- Correction de `fs.clone(id)` sans nouvel id dans la forme Promise\n- Correction de `clone()`, `copy()` et `readbuffer()` de `FILESTORAGE` pendant que le stockage est en pause\n- Correction de `$tms : false` : il ne supprimait pas la route TMS quand `$tmsurl` restait le même\n- Correction des outils MCP dont l'action lève une exception : la requête reçoit une réponse d'erreur au lieu d'attendre le timeout\n- Correction du proxy d'édition MCP (`options.editmcp`) : il liste les outils `App_*`, `App_mkdir` crée le dossier dans le projet et `App_read` renvoie la révision actuelle\n- Correction des outils d'édition MCP : chemins sans le `/` initial, `App_delete` supprime les révisions du fichier ou du dossier supprimé et répond pour `/`, `App_move` d'un dossier déplace les révisions de ses fichiers (et pas celles d'un dossier au nom plus long)\n- Correction de `App_move` d'un dossier dans les outils d'édition MCP sous Windows : les révisions déplacées étaient enregistrées avec `\\` dans leur chemin et `App_read` ne les trouvait pas\n- Correction de `AIPARSER('ollama')` avec des appels d'outils dans des fragments séparés : il lit `function.index`\n- Correction du `AIPARSER()` générique avec des appels d'outils sans id dans des fragments séparés : ils ne s'écrasent plus les uns les autres\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"Jaftvh1cP61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-20/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"it","title":"0.0.20","summary":"Cosa è cambiato nella release 0.0.20.","markdown":"---\ntitle: 0.0.20\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-20/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# 0.0.20\n\n> Cosa è cambiato nella release 0.0.20.\n\nRelease 0.0.20 del pacchetto npm `total5`.\n\n## Novità\n\n- Statistiche estese con l'aggiunta della proprietà `app`\n- Aggiunto `Total.FsPromises`, un collegamento a `node:fs/promises`\n- Aggiunto il modulo `mcp`\n\t- `CONF.$mcp = true` attiva la route MCP `POST /$mcp/`\n\t- Ogni `NEWACTION` con la proprietà `mcp: true` sarà disponibile nell'endpoint\n- Aggiunta la modalità codice MCP: `GET /$mcp/client.js` restituisce un client JavaScript dei tool MCP (una funzione per tool, con JSDoc per i suoi argomenti e il suo risultato) che li chiama tramite `tools/call`, così un agente può scrivere uno script che usa i tool e al modello torna solo l'output dello script\n\t- valgono gli stessi `Total.mcp.auth` (`Authorization: Bearer`) e `Total.mcp.filter` di `tools/list`: `Total.mcp.filter(tool, $)` decide quali tool un chiamante vede e può chiamare, e i tool vengono eseguiti come l'utente restituito da `Total.mcp.auth`\n\t- `?q=words` restituisce solo i tool il cui nome o la cui descrizione contengono tutte le parole\n\t- è disponibile ogni volta che `CONF.$mcp` è attivo; sul server non viene eseguito nulla\n- Aggiunto un nuovo metodo `JSONSchema.toAIObject(name, [description])`\n- Aggiunto un nuovo metodo `JSONSchema.toAITool(name)`\n- Aggiunto `QueryBuilder.autoqueryjson($, column, schema, [defsort], [maxlimit])` che funziona come `autoquery()` ma per le proprietà salvate in una colonna JSON(B); il builder usa il nome neutro `json:column:property:type` e l'adapter del database lo traduce in SQL\n- Aggiunto un nuovo metodo del controller `$.content(value, content_type)`\n- Aggiunto un nuovo evento `reset` in FlowStream\n- Aggiunto il supporto per l'opzione `cache` di `NEWACTION()` (la risposta viene conservata per gli stessi `query`, `params`, `input`, `user` o `language`)\n- Aggiunti i tipi di schema compatti `json` e `ip` (i valori vengono validati)\n- Aggiunto il tipo di schema compatto `email2`: funziona come `email` e rimuove il tag dell'indirizzo (`name+tag@domain.com` diventa `name@domain.com`)\n- Aggiunto `U.validhost(host)` che accetta solo nomi host semplici e letterali IP canonici\n- Aggiunto `U.tohost(host)` che converte un nome host nella forma ASCII canonica (punycode, IPv4 puntato) e restituisce una stringa vuota per un nome host non valido\n- Aggiunta una nuova classe globale `User`\n- Aggiunto un nuovo metodo delle azioni `.env(str)` per definire l'ambiente nell'azione `$.env {String}`\n- Aggiunto un nuovo metodo delle azioni e del controller `$.throw(err)` per stampare un errore nella console\n- Aggiunto un nuovo metodo delle azioni e del controller `$.touch([url])`\n- Aggiunto un nuovo metodo delle azioni e del controller `$.invalidsafe(msg, err)`\n- Aggiunto un nuovo comando `total5 test [name1] [name2]` che esegue i test della directory corrente o della sua directory `tests` (carica `config`, l'eventuale `init.js` e gli script; senza nomi esegue tutti gli script)\n- Aggiunti `Test.fake(name, action)`, che sostituisce un'azione con una finta, e `Test.restore()`, che rimette le azioni originali\n- Aggiunti un client PostgreSQL nativo + QueryBuilderPG, inizializzazione `DATA.init('connection name', 'connection string?pooling=1')`\n\n## Modifiche\n\n- Migliorato `total5 test`: il framework del progetto testato viene trovato anche dalle sue sottodirectory (es. da `tests`)\n- Sicurezza: rafforzati i nomi host rispetto alla release di sicurezza di Node.js del 2026-10-21 (corretta in Node.js 22.23.4, 24.22.1 e 26.12.1); il framework non richiede una versione specifica di Node.js, i nomi host vengono normalizzati e validati nel framework stesso\n\t- CVE-2026-105482: `dns.resolve*()` tronca un nome a un byte NUL (`attacker.example\\0.trusted.example`)\n\t- CVE-2026-105483, CVE-2026-106069, CVE-2026-106072: `tls.checkServerIdentity()` con letterali IPv4 scritti con cifre non ASCII, zeri iniziali o in forma non canonica (`0x7f.0.0.1`, `127.1`, `2130706433`)\n- Nota: il problema CVE-2026-105481 (dati non richiesti su un socket keep-alive riutilizzato, `http.Agent`) si risolve solo aggiornando Node.js; il problema di Brotli CVE-2026-111497 non riguarda il framework (vengono decompressi solo `gzip` e `deflate`)\n\n## Correzioni\n\n- Corretto `AIPARSER()` con le chiamate di tool\n- Corretto `CRON()` con la forma a passo (`*/15`, `5/20`): corrisponde ai valori del passo e non a ogni valore\n- Corretto l'argomento `limit` di `setTimeout2()`\n- Corretto `AJAX()` per le risposte con `application/xml` e `text/xml`\n- Corretti `F.python()` senza callback (la promise si risolve con l'output) e `F.pipinstall()` senza callback\n- Corretto `LOGMAIL()` con un oggetto come body\n- Corretto `IMPORT()`: una risposta con lo stato 400 o superiore, o un file che non è un modulo, dà un errore\n- Corretto il client del tunnel (`proxy.js`): i tipi dei messaggi \"error\" e \"abort\"\n- Corretto il metodo del controller `$.href()`\n- Corretto `QueryBuilder.gridfields()`: i campi accettati vengono applicati\n- Corretta la gestione delle richieste in sospeso (un solo passaggio invece di `splice()` per ogni richiesta terminata)\n- Corretta la memoria sotto carico: una richiesta terminata lascia subito l'elenco delle richieste in sospeso (l'elenco conservava ogni richiesta con i suoi `req` e `res` fino al controllo dei timeout successivo, ogni 5 secondi, quindi la memoria cresceva con il traffico)\n- Corretto il controllo dei timeout delle richieste in sospeso: la risposta di timeout di una richiesta non rimuove più dall'elenco un'altra richiesta senza risposta (quella richiesta non riceveva mai la sua risposta di timeout)\n- Corretto `LDAP()`: un bind con uno stato diverso da 0 dà un errore anche quando il server non invia alcun testo\n- Corretto `attachmentfs()` nella posta: il file dello storage viene letto come Buffer e il messaggio viene completato (lanciava un `TypeError` e la connessione SMTP restava aperta)\n- Corretto `attachment()` con un `Buffer` nella posta: il Base64 dell'intero Buffer viene diviso in righe (i byte venivano divisi in pezzi da 68 byte e ognuno riceveva il proprio padding)\n- Corretto il comando del view engine `@{hostname()}`\n- Corretto `U.resolve()` (usato da `REQUEST()`): un nome host non valido dà un errore prima della query DNS\n- Corretto `U.connect()`: l'`host` viene normalizzato e un nome host non valido dà l'errore `Invalid hostname`\n- Corretto il `server` SMTP nella posta: il nome host viene normalizzato (nomi internazionali in punycode, IPv4 nella forma canonica) e un nome host non valido dà l'errore `Invalid SMTP server hostname.`\n- Corretto `url` nel view engine\n- Corretto `$.invalidsafe(msg, err)`: in un'azione lanciava un `ReferenceError` (la richiesta terminava in timeout) e in un controller l'errore per il log veniva sostituito dal messaggio per l'utente\n- Corretto l'invio di e-mail tramite Total API con `CONF.$tapimail` (le callback di `MAIL()`, `HTMLMAIL()` e `LOGMAIL()` vengono eseguite) e i log di audit con `CONF.$tapilogger`\n- Corretti gli header `X-Priority` e `Sensitivity` di `high()`, `low()` e `confidential()` nella posta inviata via SMTP\n- Corretta l'opzione `writer` di `REQUEST()`: veniva ignorata e veniva inviato un body vuoto\n- Corretto `RESTBuilder.API().get()`: passava la richiesta a GET e falliva con \"write after end\"\n- Corretto `compress()` di `RESTBuilder.API()`: i valori `null` venivano comunque inviati\n- Corretto `U.set()` con un percorso che continua dopo un indice (`items[0].name` rendeva `items[0]` un array)\n- Corretta l'opzione `cache` di `NEWACTION()`: le azioni senza `id` condividevano una sola voce della cache, e il chiamante poteva modificare la risposta in cache\n- Corretta l'opzione `tls` di `U.connect()`: il socket non passava mai a TLS\n- Corretti `U.parseURI()`, `REQUEST()`, `RESTBuilder` e i proxy con credenziali nell'URL (`user:pass@`): fallivano con \"user is not defined\"\n- Corretti i prefissi `>` e `<` di `update()` e `modify()` nel QueryBuilder NoSQL\n- Corretti i prefissi `-`, `*` e `/` di `update()` e `modify()` nel QueryBuilder NoSQL (tutti aggiungevano il valore)\n- Corretto `scalar()` del QueryBuilder NoSQL: `avg` restituisce la media, e gli aggregati funzionano senza chiave\n- Corretti `count` e `pages` di `list()` con il QueryBuilder NoSQL\n- Corretto `search()` con `beg` e `end` nel QueryBuilder PostgreSQL, anche su colonne che non sono di testo\n- Corretta l'inversione `!name` di `update()` nel QueryBuilder PostgreSQL (la colonna è tra virgolette)\n- Corretto `fields()` prima di `autoquery()` e `autoqueryjson()`: le query successive non selezionano più colonne in più\n- Corretto `gridfields()` con un valore vuoto o mancante\n- Corretta la chiave `memory` di FlowStream: non limitava l'heap dei fork e dei worker thread\n- Corretto `$.send(null)` in FlowStream: `end` scattava una volta per output, e un output senza una destinazione pronta fermava il messaggio per gli output successivi\n- Corretto `TRANSFORM()` senza callback: `$.invalid()` lanciava un `TypeError` e la Promise non si concludeva mai\n- Corretto `F.worker.isfork`: era `true` nei worker thread e `false` nei fork\n- Corretto `NEWFORK()`: `--worker` non arrivava al processo figlio, quindi `F.worker.is` era `false` nei fork\n- Corretto `NEWTHREADPOOL()`: `worker.data` era `undefined` nei thread del pool, `pool.count` era l'oggetto pool, e un worker che terminava lanciava un `ReferenceError` e non veniva sostituito\n- Corretto il caricamento del framework da `node -e` (lì `process.argv[1]` e `process.mainModule` sono undefined)\n- Corrette le azioni `async` che lanciano un'eccezione: all'azione viene risposto con un errore (route e tool MCP) invece di aspettare il timeout\n- Corretti gli errori degli array degli schemi JSON i cui elementi sono oggetti con proprietà (percorso, indice ed errore sbagliati)\n- Corretta la doppia codifica HTML del testo aggiunto da `@{title2()}`\n- Corretta la doppia codifica HTML di titolo, descrizione e parole chiave impostati da `@{meta(title, description, keywords)}`\n- Corretto `@{language}` nelle viste renderizzate con `F.view()`\n- Corretta una variabile globale `language` creata da ogni vista compilata\n- Corrette le viste con più di un valore `@{}` in un blocco `<style>`\n- Corretto `$.href()` con un valore oggetto o array, una `&` finale, e i parametri persi quando viene chiamato più di una volta\n- Corretti `$.href({ key: value })` e `@{href({ key: value })}`: restituivano l'URL senza la query\n- Corretto l'argomento `filter` di `Image.miniature()` (e `.filter()`): veniva messo dopo `-thumbnail`\n- Corretto `Image.background()`: `-background` va prima di `-extent`, così il colore viene usato\n- Corretto il selettore `[attr]` senza valore nel parser HTML\n- Corretto `F.TCMS.compile()` con un oggetto di widget\n- Corretti i messaggi WebSocket binari con compressione: venivano inviati come frame di testo compressi\n- Corretti i client WebSocket rifiutati dall'autorizzazione: ricevono il codice di chiusura `4001` (o `4004`) invece di una connessione interrotta\n- Corretti gli errori di compressione dei messaggi WebSocket: lanciavano \"self is not defined\" invece di arrivare all'evento `error`\n- Corretto `WEBSOCKETCLIENT` che perdeva un messaggio arrivato insieme alla risposta `101`\n- Corretto `fs.clone(id)` senza un nuovo id nella forma con Promise\n- Corretti `clone()`, `copy()` e `readbuffer()` di `FILESTORAGE` mentre lo storage è in pausa\n- Corretto `$tms : false`: non rimuoveva la route TMS quando `$tmsurl` restava uguale\n- Corretti i tool MCP la cui azione lancia un'eccezione: la richiesta riceve una risposta di errore invece di aspettare il timeout\n- Corretto il proxy di modifica MCP (`options.editmcp`): elenca i tool `App_*`, `App_mkdir` crea la cartella all'interno del progetto e `App_read` restituisce la revisione attuale\n- Corretti i tool di modifica MCP: percorsi senza la `/` iniziale, `App_delete` rimuove le revisioni del file o della cartella eliminati e risponde per `/`, `App_move` di una cartella sposta le revisioni dei suoi file (e non quelle di una cartella con un nome più lungo)\n- Corretto `App_move` di una cartella nei tool di modifica MCP su Windows: le revisioni spostate venivano salvate con `\\` nel loro percorso e `App_read` non le trovava\n- Corretto `AIPARSER('ollama')` con chiamate di tool in chunk separati: legge `function.index`\n- Corretto l'`AIPARSER()` generico con chiamate di tool senza id in chunk separati: non si sovrascrivono più a vicenda\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"Jaftvh1cP61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-20/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"sk","title":"0.0.20","summary":"Čo sa zmenilo vo vydaní 0.0.20.","markdown":"---\ntitle: 0.0.20\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-20/\nupdated: 2026-11-19T16:16:52.152Z\n---\n\n# 0.0.20\n\n> Čo sa zmenilo vo vydaní 0.0.20.\n\nVydanie 0.0.20 npm balíka `total5`.\n\n## Novinky\n\n- Rozšírené štatistiky o vlastnosť `app`\n- Pridané `Total.FsPromises`, odkaz na `node:fs/promises`\n- Pridaný modul `mcp`\n\t- `CONF.$mcp = true` aktivuje MCP routu `POST /$mcp/`\n\t- Každá `NEWACTION` s vlastnosťou `mcp: true` bude dostupná v endpointe\n- Pridaný MCP code mode: `GET /$mcp/client.js` vráti JavaScript klienta MCP nástrojov (jednu funkciu pre každý nástroj, s JSDoc pre jej argumenty a výsledok), ktorý ich volá cez `tools/call`, takže agent môže napísať skript, ktorý nástroje používa, a do modelu sa vráti iba výstup skriptu\n\t- platia tie isté `Total.mcp.auth` (`Authorization: Bearer`) a `Total.mcp.filter` ako pre `tools/list`: `Total.mcp.filter(tool, $)` rozhoduje, ktoré nástroje volajúci vidí a smie volať, a nástroje bežia ako používateľ, ktorého vráti `Total.mcp.auth`\n\t- `?q=words` vráti iba nástroje, ktorých názov alebo popis obsahuje všetky slová\n\t- je dostupný vždy, keď je zapnuté `CONF.$mcp`; na serveri sa nič nespúšťa\n- Pridaná nová metóda `JSONSchema.toAIObject(name, [description])`\n- Pridaná nová metóda `JSONSchema.toAITool(name)`\n- Pridané `QueryBuilder.autoqueryjson($, column, schema, [defsort], [maxlimit])`, ktoré funguje ako `autoquery()`, ale pre vlastnosti uložené v JSON(B) stĺpci; builder používa neutrálny názov `json:column:property:type` a databázový adaptér ho preloží do SQL\n- Pridaná nová metóda controllera `$.content(value, content_type)`\n- Pridaná nová udalosť `reset` vo FlowStream\n- Pridaná podpora možnosti `cache` v `NEWACTION()` (odpoveď sa uchová pre rovnaké `query`, `params`, `input`, `user` alebo `language`)\n- Pridané kompaktné typy schémy `json` a `ip` (hodnoty sa validujú)\n- Pridaný kompaktný typ schémy `email2`: funguje ako `email` a odstráni z adresy tag (z `name+tag@domain.com` sa stane `name@domain.com`)\n- Pridané `U.validhost(host)`, ktoré prijíma iba čisté hostnames a kanonické IP literály\n- Pridané `U.tohost(host)`, ktoré skonvertuje hostname na kanonický ASCII tvar (punycode, IPv4 s bodkami) a pre neplatný hostname vráti prázdny reťazec\n- Pridaná nová globálna trieda `User`\n- Pridaná nová metóda akcie `.env(str)` na definovanie prostredia v akcii `$.env {String}`\n- Pridaná nová metóda akcie a controllera `$.throw(err)` na výpis chyby do konzoly\n- Pridaná nová metóda akcie a controllera `$.touch([url])`\n- Pridaná nová metóda akcie a controllera `$.invalidsafe(msg, err)`\n- Pridaný nový príkaz `total5 test [name1] [name2]`, ktorý spustí testy z aktuálneho adresára alebo z jeho adresára `tests` (načíta `config`, voliteľný `init.js` a skripty; bez názvov spustí všetky skripty)\n- Pridané `Test.fake(name, action)`, ktoré nahradí akciu falošnou akciou, a `Test.restore()`, ktoré vráti pôvodné akcie späť\n- Pridaný natívny klient PostgreSQL + QueryBuilderPG, inicializácia `DATA.init('connection name', 'connection string?pooling=1')`\n\n## Zmeny\n\n- Vylepšené `total5 test`: framework testovaného projektu sa nájde aj z jeho podadresárov (napr. z `tests`)\n- Bezpečnosť: hostnames sú zabezpečené voči bezpečnostnému vydaniu Node.js z 2026-10-21 (opravené v Node.js 22.23.4, 24.22.1 a 26.12.1); framework nevyžaduje konkrétnu verziu Node.js, hostnames sa normalizujú a validujú priamo vo frameworku\n\t- CVE-2026-105482: `dns.resolve*()` oreže názov pri NUL bajte (`attacker.example\\0.trusted.example`)\n\t- CVE-2026-105483, CVE-2026-106069, CVE-2026-106072: `tls.checkServerIdentity()` s IPv4 literálmi zapísanými ne-ASCII číslicami, s úvodnými nulami alebo v nekanonickom tvare (`0x7f.0.0.1`, `127.1`, `2130706433`)\n- Poznámka: problém CVE-2026-105481 (nevyžiadané dáta na opakovane použitom keep-alive sockete, `http.Agent`) opraví iba aktualizácia Node.js; problém Brotli CVE-2026-111497 framework neovplyvňuje (dekomprimujú sa iba `gzip` a `deflate`)\n\n## Opravy\n\n- Opravený `AIPARSER()` s volaním nástrojov\n- Opravený `CRON()` s tvarom kroku (`*/15`, `5/20`): zodpovedá hodnotám kroku, a nie každej hodnote\n- Opravený argument `limit` v `setTimeout2()`\n- Opravený `AJAX()` pre odpovede s `application/xml` a `text/xml`\n- Opravené `F.python()` bez callbacku (promise sa vyrieši s výstupom) a `F.pipinstall()` bez callbacku\n- Opravený `LOGMAIL()` s objektom ako telom\n- Opravený `IMPORT()`: odpoveď so stavom 400 alebo vyšším, alebo súbor, ktorý nie je modul, vráti chybu\n- Opravený tunelový klient (`proxy.js`): typy správ „error“ a „abort“\n- Opravená metóda controllera `$.href()`\n- Opravené `QueryBuilder.gridfields()`: prijaté polia sa použijú\n- Opravené spracovanie čakajúcich požiadaviek (jeden prechod namiesto `splice()` pre každú dokončenú požiadavku)\n- Opravená pamäť pod záťažou: dokončená požiadavka hneď opustí zoznam čakajúcich požiadaviek (zoznam držal každú požiadavku s jej `req` a `res` až do ďalšej kontroly timeoutov, každých 5 sekúnd, takže pamäť rástla s prevádzkou)\n- Opravená kontrola timeoutov čakajúcich požiadaviek: timeout odpoveď jednej požiadavky už neodstráni zo zoznamu inú nezodpovedanú požiadavku (tá požiadavka nikdy nedostala svoju timeout odpoveď)\n- Opravený `LDAP()`: bind so stavom iným ako 0 vráti chybu, aj keď server nepošle žiadny text\n- Opravené `attachmentfs()` v pošte: súbor z úložiska sa načíta ako Buffer a správa sa dokončí (vyhadzovalo `TypeError` a SMTP spojenie zostalo otvorené)\n- Opravené `attachment()` s `Buffer` v pošte: Base64 celého Buffera sa rozdelí na riadky (bajty sa delili na kúsky po 68 bajtoch a každý dostal vlastné zarovnanie)\n- Opravený príkaz view enginu `@{hostname()}`\n- Opravené `U.resolve()` (používa ho `REQUEST()`): neplatný hostname vráti chybu pred DNS dopytom\n- Opravené `U.connect()`: `host` sa normalizuje a neplatný hostname vráti chybu `Invalid hostname`\n- Opravený SMTP `server` v pošte: hostname sa normalizuje (medzinárodné názvy na punycode, IPv4 na kanonický tvar) a neplatný hostname vráti chybu `Invalid SMTP server hostname.`\n- Opravené `url` vo view engine\n- Opravené `$.invalidsafe(msg, err)`: v akcii vyhadzovalo `ReferenceError` (požiadavka skončila timeoutom) a v controlleri sa chyba pre log nahradila správou pre používateľa\n- Opravené posielanie e-mailov cez Total API s `CONF.$tapimail` (callbacky `MAIL()`, `HTMLMAIL()` a `LOGMAIL()` sa spustia) a auditné logy s `CONF.$tapilogger`\n- Opravené hlavičky `X-Priority` a `Sensitivity` z `high()`, `low()` a `confidential()` v pošte posielanej cez SMTP\n- Opravená voľba `writer` v `REQUEST()`: ignorovala sa a posielalo sa prázdne telo\n- Opravené `RESTBuilder.API().get()`: prepínalo požiadavku na GET a zlyhalo s „write after end“\n- Opravené `compress()` v `RESTBuilder.API()`: hodnoty `null` sa stále posielali\n- Opravené `U.set()` s cestou, ktorá pokračuje za indexom (`items[0].name` urobilo z `items[0]` pole)\n- Opravená voľba `cache` v `NEWACTION()`: akcie bez `id` zdieľali jeden záznam v cache a volajúci mohol zmeniť odpoveď v cache\n- Opravená voľba `tls` v `U.connect()`: socket sa nikdy nepovýšil\n- Opravené `U.parseURI()`, `REQUEST()`, `RESTBuilder` a proxy s prihlasovacími údajmi v URL (`user:pass@`): zlyhávali s „user is not defined“\n- Opravené prefixy `>` a `<` v `update()` a `modify()` v NoSQL QueryBuilderi\n- Opravené prefixy `-`, `*` a `/` v `update()` a `modify()` v NoSQL QueryBuilderi (všetky hodnotu pripočítavali)\n- Opravené `scalar()` v NoSQL QueryBuilderi: `avg` vráti priemer a agregácie fungujú aj bez kľúča\n- Opravené `count` a `pages` v `list()` s NoSQL QueryBuilderom\n- Opravené `search()` s `beg` a `end` v PostgreSQL QueryBuilderi, aj na stĺpcoch, ktoré nie sú textové\n- Opravené prepínanie `!name` v `update()` v PostgreSQL QueryBuilderi (stĺpec je v úvodzovkách)\n- Opravené `fields()` pred `autoquery()` a `autoqueryjson()`: neskoršie dopyty už nevyberajú stĺpce navyše\n- Opravené `gridfields()` s prázdnou alebo chýbajúcou hodnotou\n- Opravený kľúč `memory` vo FlowStream: neobmedzoval heap forkov a worker vlákien\n- Opravené `$.send(null)` vo FlowStream: `end` sa vyvolal raz pre každý výstup a výstup bez pripraveného cieľa zastavil správu pre ďalšie výstupy\n- Opravené `TRANSFORM()` bez callbacku: `$.invalid()` vyhadzovalo `TypeError` a Promise sa nikdy nevyriešil\n- Opravené `F.worker.isfork`: vo worker vláknach bolo `true` a vo forkoch `false`\n- Opravené `NEWFORK()`: `--worker` sa nedostal do podriadeného procesu, takže `F.worker.is` bolo vo forkoch `false`\n- Opravené `NEWTHREADPOOL()`: `worker.data` bolo vo vláknach poolu `undefined`, `pool.count` bol objekt poolu a worker, ktorý skončil, vyhodil `ReferenceError` a nenahradil sa\n- Opravené načítanie frameworku z `node -e` (`process.argv[1]` a `process.mainModule` tam nie sú definované)\n- Opravené `async` akcie, ktoré vyhodia výnimku: akcia dostane odpoveď s chybou (trasy aj MCP nástroje) namiesto čakania na timeout\n- Opravené chyby polí v JSON schémach, ktorých položky sú objekty s vlastnosťami (nesprávna cesta, index a chyba)\n- Opravené dvojité HTML kódovanie textu pridaného cez `@{title2()}`\n- Opravené dvojité HTML kódovanie titulku, popisu a kľúčových slov nastavených cez `@{meta(title, description, keywords)}`\n- Opravené `@{language}` v pohľadoch vykreslených cez `F.view()`\n- Opravená globálna premenná `language`, ktorú vytváral každý skompilovaný pohľad\n- Opravené pohľady s viac ako jednou hodnotou `@{}` v bloku `<style>`\n- Opravené `$.href()` s hodnotou typu objekt alebo pole, s `&` na konci a so stratenými parametrami pri viacnásobnom volaní\n- Opravené `$.href({ key: value })` a `@{href({ key: value })}`: vracali URL bez query\n- Opravený argument `filter` v `Image.miniature()` (a `.filter()`): umiestňoval sa za `-thumbnail`\n- Opravené `Image.background()`: `-background` ide pred `-extent`, takže sa farba použije\n- Opravený selektor `[attr]` bez hodnoty v HTML parseri\n- Opravené `F.TCMS.compile()` s objektom widgetov\n- Opravené binárne WebSocket správy s kompresiou: posielali sa ako komprimované textové rámce\n- Opravení WebSocket klienti odmietnutí autorizáciou: dostanú kód zatvorenia `4001` (alebo `4004`) namiesto prerušeného spojenia\n- Opravené chyby kompresie WebSocket správ: vyhadzovali „self is not defined“ namiesto toho, aby sa dostali do udalosti `error`\n- Opravený `WEBSOCKETCLIENT`, ktorý strácal správu prichádzajúcu spolu s odpoveďou `101`\n- Opravené `fs.clone(id)` bez nového id vo forme s Promise\n- Opravené `clone()`, `copy()` a `readbuffer()` vo `FILESTORAGE`, keď je úložisko pozastavené\n- Opravené `$tms : false`: neodstránilo TMS routu, keď `$tmsurl` zostalo rovnaké\n- Opravené MCP nástroje, ktorých akcia vyhodí výnimku: požiadavka dostane odpoveď s chybou namiesto čakania na timeout\n- Opravený MCP edit proxy (`options.editmcp`): vypíše nástroje `App_*`, `App_mkdir` vytvorí priečinok vnútri projektu a `App_read` vráti aktuálnu revíziu\n- Opravené MCP edit nástroje: cesty bez úvodného `/`, `App_delete` odstráni revízie vymazaného súboru alebo priečinka a odpovie pre `/`, `App_move` priečinka presunie revízie jeho súborov (a nie revízie priečinka s dlhším názvom)\n- Opravené `App_move` priečinka v MCP edit nástrojoch vo Windows: presunuté revízie sa ukladali s `\\` v ceste a `App_read` ich nenašlo\n- Opravené `AIPARSER('ollama')` s volaniami nástrojov v samostatných častiach: číta `function.index`\n- Opravený všeobecný `AIPARSER()` s volaniami nástrojov bez id v samostatných častiach: už sa navzájom neprepisujú\n","entries":[],"license":"MIT","updated":"2026-11-19T16:16:52.152Z"}
{"id":"JacSJm1tk60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-19/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"en","title":"0.0.19","summary":"What changed in release 0.0.19 (2026-09-29).","markdown":"---\ntitle: 0.0.19\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-19/\nupdated: 2026-11-15T17:28:39.396Z\n---\n\n# 0.0.19\n\n> What changed in release 0.0.19 (2026-09-29).\n\nRelease 0.0.19 of the npm package `total5`, published on 2026-09-29.\n\n```bash\nnpm install total5@0.0.19\n```\n\n## New\n\n- Added an additional `check` for invalid hex values in `F.decrypt()`\n- Added loading stats after loading the framework (due to Flow)\n- Added support for auto-loading `index.flow` file in the plugins folder\n- Extended `NEWACTION` by adding a new handler: `onoutput: function(err, response, $)`\n- Extended `NEWACTION` by adding a new handler: `oninput: function($)`\n- Extended action's `$` by adding `$.input` property (alias for the `$.model`)\n- Extended `flowinstance.save(redraw = true)` method by adding `redraw` argument\n- Extended FlowStream by adding `instance.activity(key, name, [progress])` method\n- Extended `NEWACTION.route` option by adding support for `true` that adds `API ?` value\n- Added `.xhr` property in the `$` Options\n- Extended `SHELL()` method by increasing `maxBuffer` to `100 MB`\n- Added FlowStream node persistent in-memory cache `instance.cache`\n\n## Changed\n\n- Removed watcher for the `.flow` files\n- Improved FlowStream stats by adding `online` editors\n\n## Fixed\n\n- Fixed binding origin in the FlowStream\n- Fixed `restart` FlowStream\n- Fixed handling errors in the `NEWTRANSFORM()` method\n- Fixed CSS compiler\n- Fixed directory in the start information\n- Fixed initializing `TMSCLIENT`\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:39.396Z"}
{"id":"JacSJm1tk60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-19/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"de","title":"0.0.19","summary":"Was sich in Version 0.0.19 (2026-09-29) geändert hat.","markdown":"---\ntitle: 0.0.19\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-19/\nupdated: 2026-11-15T17:28:39.396Z\n---\n\n# 0.0.19\n\n> Was sich in Version 0.0.19 (2026-09-29) geändert hat.\n\nVersion 0.0.19 des npm-Pakets `total5`, veröffentlicht am 2026-09-29.\n\n```bash\nnpm install total5@0.0.19\n```\n\n## Neu\n\n- Zusätzliche Prüfung (`check`) auf ungültige Hex-Werte in `F.decrypt()` hinzugefügt\n- Laden der Statistiken nach dem Laden des Frameworks hinzugefügt (wegen Flow)\n- Unterstützung für das automatische Laden der Datei `index.flow` im Ordner plugins hinzugefügt\n- `NEWACTION` um einen neuen Handler erweitert: `onoutput: function(err, response, $)`\n- `NEWACTION` um einen neuen Handler erweitert: `oninput: function($)`\n- `$` der Aktion um die Eigenschaft `$.input` erweitert (Alias für `$.model`)\n- Methode `flowinstance.save(redraw = true)` um das Argument `redraw` erweitert\n- FlowStream um die Methode `instance.activity(key, name, [progress])` erweitert\n- Option `NEWACTION.route` um die Unterstützung für `true` erweitert, das den Wert `API ?` hinzufügt\n- Eigenschaft `.xhr` in den `$`-Optionen hinzugefügt\n- Methode `SHELL()` erweitert, indem `maxBuffer` auf `100 MB` erhöht wurde\n- Persistenten In-Memory-Cache `instance.cache` für FlowStream-Knoten hinzugefügt\n\n## Geändert\n\n- Watcher für die `.flow`-Dateien entfernt\n- FlowStream-Statistiken um `online`-Editoren verbessert\n\n## Behoben\n\n- Binden des Origins im FlowStream behoben\n- `restart` von FlowStream behoben\n- Fehlerbehandlung in der Methode `NEWTRANSFORM()` behoben\n- CSS-Compiler behoben\n- Verzeichnis in den Startinformationen behoben\n- Initialisierung von `TMSCLIENT` behoben\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:39.396Z"}
{"id":"JacSJm1tk60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-19/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"es","title":"0.0.19","summary":"Qué cambió en la versión 0.0.19 (2026-09-29).","markdown":"---\ntitle: 0.0.19\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-19/\nupdated: 2026-11-15T17:28:39.396Z\n---\n\n# 0.0.19\n\n> Qué cambió en la versión 0.0.19 (2026-09-29).\n\nVersión 0.0.19 del paquete npm `total5`, publicada el 2026-09-29.\n\n```bash\nnpm install total5@0.0.19\n```\n\n## Novedades\n\n- Añadido un `check` adicional para valores hexadecimales no válidos en `F.decrypt()`\n- Añadida la carga de estadísticas después de cargar el framework (por Flow)\n- Añadido soporte para la carga automática del archivo `index.flow` en la carpeta de plugins\n- Ampliado `NEWACTION` con un nuevo handler: `onoutput: function(err, response, $)`\n- Ampliado `NEWACTION` con un nuevo handler: `oninput: function($)`\n- Ampliado el `$` de la acción con la propiedad `$.input` (alias de `$.model`)\n- Ampliado el método `flowinstance.save(redraw = true)` con el argumento `redraw`\n- Ampliado FlowStream con el método `instance.activity(key, name, [progress])`\n- Ampliada la opción `NEWACTION.route` con soporte para `true`, que añade el valor `API ?`\n- Añadida la propiedad `.xhr` en las opciones `$`\n- Ampliado el método `SHELL()` aumentando `maxBuffer` a `100 MB`\n- Añadida la caché persistente en memoria de nodos de FlowStream `instance.cache`\n\n## Cambios\n\n- Eliminado el vigilante de los archivos `.flow`\n- Mejoradas las estadísticas de FlowStream añadiendo los editores `online`\n\n## Correcciones\n\n- Corregido el binding del origen en FlowStream\n- Corregido `restart` de FlowStream\n- Corregido el manejo de errores en el método `NEWTRANSFORM()`\n- Corregido el compilador de CSS\n- Corregido el directorio en la información de inicio\n- Corregida la inicialización de `TMSCLIENT`\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:39.396Z"}
{"id":"JacSJm1tk60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-19/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"fr","title":"0.0.19","summary":"Ce qui a changé dans la version 0.0.19 (2026-09-29).","markdown":"---\ntitle: 0.0.19\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-19/\nupdated: 2026-11-15T17:28:39.396Z\n---\n\n# 0.0.19\n\n> Ce qui a changé dans la version 0.0.19 (2026-09-29).\n\nVersion 0.0.19 du paquet npm `total5`, publiée le 2026-09-29.\n\n```bash\nnpm install total5@0.0.19\n```\n\n## Nouveautés\n\n- Ajout d'une vérification `check` supplémentaire des valeurs hexadécimales invalides dans `F.decrypt()`\n- Ajout du chargement des statistiques après le chargement du framework (à cause de Flow)\n- Ajout de la prise en charge du chargement automatique du fichier `index.flow` dans le dossier des plugins\n- Extension de `NEWACTION` avec un nouveau handler : `onoutput: function(err, response, $)`\n- Extension de `NEWACTION` avec un nouveau handler : `oninput: function($)`\n- Extension du `$` des actions avec la propriété `$.input` (alias de `$.model`)\n- Extension de la méthode `flowinstance.save(redraw = true)` avec l'argument `redraw`\n- Extension de FlowStream avec la méthode `instance.activity(key, name, [progress])`\n- Extension de l'option `NEWACTION.route` avec la prise en charge de `true`, qui ajoute la valeur `API ?`\n- Ajout de la propriété `.xhr` dans les Options `$`\n- Extension de la méthode `SHELL()` avec l'augmentation de `maxBuffer` à `100 MB`\n- Ajout du cache persistant en mémoire `instance.cache` pour les nœuds FlowStream\n\n## Modifications\n\n- Suppression du watcher pour les fichiers `.flow`\n- Amélioration des statistiques FlowStream avec l'ajout des éditeurs `online`\n\n## Corrections\n\n- Correction de l'origine de la liaison dans FlowStream\n- Correction du `restart` de FlowStream\n- Correction de la gestion des erreurs dans la méthode `NEWTRANSFORM()`\n- Correction du compilateur CSS\n- Correction du répertoire dans les informations de démarrage\n- Correction de l'initialisation de `TMSCLIENT`\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:39.396Z"}
{"id":"JacSJm1tk60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-19/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"it","title":"0.0.19","summary":"Cosa è cambiato nella release 0.0.19 (2026-09-29).","markdown":"---\ntitle: 0.0.19\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-19/\nupdated: 2026-11-15T17:28:39.396Z\n---\n\n# 0.0.19\n\n> Cosa è cambiato nella release 0.0.19 (2026-09-29).\n\nRelease 0.0.19 del pacchetto npm `total5`, pubblicata il 2026-09-29.\n\n```bash\nnpm install total5@0.0.19\n```\n\n## Novità\n\n- Aggiunto un `check` aggiuntivo per i valori esadecimali non validi in `F.decrypt()`\n- Aggiunto il caricamento delle statistiche dopo il caricamento del framework (per Flow)\n- Aggiunto il supporto al caricamento automatico del file `index.flow` nella cartella dei plugin\n- Esteso `NEWACTION` con l'aggiunta di un nuovo handler: `onoutput: function(err, response, $)`\n- Esteso `NEWACTION` con l'aggiunta di un nuovo handler: `oninput: function($)`\n- Esteso il `$` delle azioni con l'aggiunta della proprietà `$.input` (alias di `$.model`)\n- Esteso il metodo `flowinstance.save(redraw = true)` con l'aggiunta dell'argomento `redraw`\n- Esteso FlowStream con l'aggiunta del metodo `instance.activity(key, name, [progress])`\n- Estesa l'opzione `NEWACTION.route` con il supporto di `true`, che aggiunge il valore `API ?`\n- Aggiunta la proprietà `.xhr` nelle Options `$`\n- Esteso il metodo `SHELL()` aumentando `maxBuffer` a `100 MB`\n- Aggiunta a FlowStream la cache persistente in memoria dei nodi `instance.cache`\n\n## Modifiche\n\n- Rimosso il watcher per i file `.flow`\n- Migliorate le statistiche di FlowStream con l'aggiunta degli editor `online`\n\n## Correzioni\n\n- Corretto il binding dell'origin in FlowStream\n- Corretto il `restart` di FlowStream\n- Corretta la gestione degli errori nel metodo `NEWTRANSFORM()`\n- Corretto il compilatore CSS\n- Corretta la directory nelle informazioni di avvio\n- Corretta l'inizializzazione di `TMSCLIENT`\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:39.396Z"}
{"id":"JacSJm1tk60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-19/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"sk","title":"0.0.19","summary":"Čo sa zmenilo vo vydaní 0.0.19 (2026-09-29).","markdown":"---\ntitle: 0.0.19\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-19/\nupdated: 2026-11-15T17:28:39.396Z\n---\n\n# 0.0.19\n\n> Čo sa zmenilo vo vydaní 0.0.19 (2026-09-29).\n\nVydanie 0.0.19 npm balíka `total5`, publikované 2026-09-29.\n\n```bash\nnpm install total5@0.0.19\n```\n\n## Nové\n\n- Pridaná ďalšia kontrola (`check`) neplatných hex hodnôt v `F.decrypt()`\n- Pridané načítanie štatistík po načítaní frameworku (kvôli Flow)\n- Pridaná podpora automatického načítania súboru `index.flow` v priečinku pluginov\n- Rozšírená `NEWACTION` o nový handler: `onoutput: function(err, response, $)`\n- Rozšírená `NEWACTION` o nový handler: `oninput: function($)`\n- Rozšírený `$` akcie o vlastnosť `$.input` (alias pre `$.model`)\n- Rozšírená metóda `flowinstance.save(redraw = true)` o argument `redraw`\n- Rozšírený FlowStream o metódu `instance.activity(key, name, [progress])`\n- Rozšírená možnosť `NEWACTION.route` o podporu `true`, ktorá pridá hodnotu `API ?`\n- Pridaná vlastnosť `.xhr` v `$` Options\n- Rozšírená metóda `SHELL()` zvýšením `maxBuffer` na `100 MB`\n- Pridaná trvalá in-memory cache uzla FlowStream `instance.cache`\n\n## Zmenené\n\n- Odstránený watcher pre súbory `.flow`\n- Vylepšené štatistiky FlowStream o `online` editory\n\n## Opravené\n\n- Opravený binding origin vo FlowStream\n- Opravený `restart` FlowStream\n- Opravené spracovanie chýb v metóde `NEWTRANSFORM()`\n- Opravený CSS kompilátor\n- Opravený adresár v štartovacích informáciách\n- Opravená inicializácia `TMSCLIENT`\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:39.396Z"}
{"id":"JaedSj32F61f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-18/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"en","title":"0.0.18","summary":"What changed in release 0.0.18 (2026-06-29).","markdown":"---\ntitle: 0.0.18\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-18/\nupdated: 2026-11-16T07:54:28.030Z\n---\n\n# 0.0.18\n\n> What changed in release 0.0.18 (2026-06-29).\n\nRelease 0.0.18 of the npm package `total5`, published on 2026-06-29.\n\n```bash\nnpm install total5@0.0.18\n```\n\n## New\n\n- Added `flow.proxytimeout {Number}` property\n- Extended the `message.send(output, data, [clone_data], [check(from, to, output, input)])` method by adding `check` argument\n- Extended `LDAP()` options by adding a new option `attributes = { thumbnailPhoto: 'buffer' }` for custom parsing data\n\n## Changed\n\n- Updated Total.js debug watcher to detect incomplete file writes\n\n## Fixed\n\n- Fixed handling static files\n- Fixed Flow error handling\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:28.030Z"}
{"id":"JaedSj32F61f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-18/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"de","title":"0.0.18","summary":"Was sich in Version 0.0.18 (2026-06-29) geändert hat.","markdown":"---\ntitle: 0.0.18\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-18/\nupdated: 2026-11-16T07:54:28.030Z\n---\n\n# 0.0.18\n\n> Was sich in Version 0.0.18 (2026-06-29) geändert hat.\n\nVersion 0.0.18 des npm-Pakets `total5`, veröffentlicht am 2026-06-29.\n\n```bash\nnpm install total5@0.0.18\n```\n\n## Neu\n\n- Eigenschaft `flow.proxytimeout {Number}` hinzugefügt\n- Methode `message.send(output, data, [clone_data], [check(from, to, output, input)])` um das Argument `check` erweitert\n- Optionen von `LDAP()` um die neue Option `attributes = { thumbnailPhoto: 'buffer' }` zum individuellen Parsen von Daten erweitert\n\n## Geändert\n\n- Debug-Watcher von Total.js aktualisiert, damit er unvollständige Dateischreibvorgänge erkennt\n\n## Behoben\n\n- Behandlung statischer Dateien behoben\n- Fehlerbehandlung von Flow behoben\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:28.030Z"}
{"id":"JaedSj32F61f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-18/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"es","title":"0.0.18","summary":"Qué cambió en la versión 0.0.18 (2026-06-29).","markdown":"---\ntitle: 0.0.18\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-18/\nupdated: 2026-11-16T07:54:28.030Z\n---\n\n# 0.0.18\n\n> Qué cambió en la versión 0.0.18 (2026-06-29).\n\nVersión 0.0.18 del paquete npm `total5`, publicada el 2026-06-29.\n\n```bash\nnpm install total5@0.0.18\n```\n\n## Novedades\n\n- Añadida la propiedad `flow.proxytimeout {Number}`\n- Ampliado el método `message.send(output, data, [clone_data], [check(from, to, output, input)])` con el argumento `check`\n- Ampliadas las opciones de `LDAP()` con una nueva opción `attributes = { thumbnailPhoto: 'buffer' }` para parsear datos de forma personalizada\n\n## Cambios\n\n- Actualizado el vigilante de debug de Total.js para detectar escrituras de archivo incompletas\n\n## Correcciones\n\n- Corregido el manejo de archivos estáticos\n- Corregido el manejo de errores de Flow\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:28.030Z"}
{"id":"JaedSj32F61f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-18/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"fr","title":"0.0.18","summary":"Ce qui a changé dans la version 0.0.18 (2026-06-29).","markdown":"---\ntitle: 0.0.18\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-18/\nupdated: 2026-11-16T07:54:28.030Z\n---\n\n# 0.0.18\n\n> Ce qui a changé dans la version 0.0.18 (2026-06-29).\n\nVersion 0.0.18 du paquet npm `total5`, publiée le 2026-06-29.\n\n```bash\nnpm install total5@0.0.18\n```\n\n## Nouveautés\n\n- Ajout de la propriété `flow.proxytimeout {Number}`\n- Extension de la méthode `message.send(output, data, [clone_data], [check(from, to, output, input)])` avec l'ajout de l'argument `check`\n- Extension des options de `LDAP()` avec une nouvelle option `attributes = { thumbnailPhoto: 'buffer' }` pour l'analyse personnalisée des données\n\n## Modifications\n\n- Mise à jour du watcher de debug de Total.js pour détecter les écritures de fichiers incomplètes\n\n## Corrections\n\n- Correction de la gestion des fichiers statiques\n- Correction de la gestion des erreurs de Flow\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:28.030Z"}
{"id":"JaedSj32F61f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-18/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"it","title":"0.0.18","summary":"Cosa è cambiato nella release 0.0.18 (2026-06-29).","markdown":"---\ntitle: 0.0.18\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-18/\nupdated: 2026-11-16T07:54:28.030Z\n---\n\n# 0.0.18\n\n> Cosa è cambiato nella release 0.0.18 (2026-06-29).\n\nRelease 0.0.18 del pacchetto npm `total5`, pubblicata il 2026-06-29.\n\n```bash\nnpm install total5@0.0.18\n```\n\n## Novità\n\n- Aggiunta la proprietà `flow.proxytimeout {Number}`\n- Esteso il metodo `message.send(output, data, [clone_data], [check(from, to, output, input)])` con l'aggiunta dell'argomento `check`\n- Estese le opzioni di `LDAP()` con l'aggiunta di una nuova opzione `attributes = { thumbnailPhoto: 'buffer' }` per il parsing personalizzato dei dati\n\n## Modifiche\n\n- Aggiornato il watcher di debug di Total.js per rilevare le scritture di file incomplete\n\n## Correzioni\n\n- Corretta la gestione dei file statici\n- Corretta la gestione degli errori di Flow\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:28.030Z"}
{"id":"JaedSj32F61f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-18/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"sk","title":"0.0.18","summary":"Čo sa zmenilo vo vydaní 0.0.18 (2026-06-29).","markdown":"---\ntitle: 0.0.18\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-18/\nupdated: 2026-11-16T07:54:28.030Z\n---\n\n# 0.0.18\n\n> Čo sa zmenilo vo vydaní 0.0.18 (2026-06-29).\n\nVydanie 0.0.18 npm balíka `total5`, publikované 2026-06-29.\n\n```bash\nnpm install total5@0.0.18\n```\n\n## Nové\n\n- Pridaná vlastnosť `flow.proxytimeout {Number}`\n- Rozšírená metóda `message.send(output, data, [clone_data], [check(from, to, output, input)])` o argument `check`\n- Rozšírené možnosti `LDAP()` o novú možnosť `attributes = { thumbnailPhoto: 'buffer' }` na vlastné parsovanie dát\n\n## Zmenené\n\n- Aktualizovaný debug watcher Total.js, aby rozpoznal neúplné zápisy súborov\n\n## Opravené\n\n- Opravená obsluha statických súborov\n- Opravené spracovanie chýb vo Flow\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:28.030Z"}
{"id":"JacSJH1lk60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-17/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"en","title":"0.0.17","summary":"What changed in release 0.0.17 (2026-06-01).","markdown":"---\ntitle: 0.0.17\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-17/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.17\n\n> What changed in release 0.0.17 (2026-06-01).\n\nRelease 0.0.17 of the npm package `total5`, published on 2026-06-01.\n\n```bash\nnpm install total5@0.0.17\n```\n\n## New\n\n- Added `PROXYCLIENT(proxyserver, ip:port, [logger])` method\n- Added `PROXYSERVER(endpoint, socketendpoint, [logger])` method\n- Added `AIMODEL().tool(content)` method\n- Added `AIPARSER(provider)` method for parsing AI responses\n- Extended `String.prototype` by adding the `String.parseContext()` method to parse a specific text file format\n- Added `ACTION().config(obj)` method\n- Added a new property `flow.instance.repo = {}` for storing additional data for Flow node instances\n\n## Changed\n\n- Improved returing `origin` in the CORS\n- `DEBUG` is set according to the `process.env.NODE_ENV` variable\n- Improved code\n- Improved `Utils.filestreamer()` method by adding percentage\n\n## Fixed\n\n- Fixed error handling in emails\n- Fixed removing routes via `route.remove()` method\n- Fixed `beautify` and `replacer` arguments in the `controller.json()`\n- Fixed `mail` priority\n- Fixed `kB` and `GB` units in the routing as upload limits\n- Fixed server pinging of all WebSocket connections\n- Fixed typo in send method data assignment\n- Fixed `Utils.filestreamer()` method\n- Fixed sending data to all outputs `$.send(null, [data])` in the FlowStream\n- Fixed sending data to all outputs `instance.send(null, [data])` in the FlowStream\n- Fixed removing WebSocket route\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JacSJH1lk60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-17/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"de","title":"0.0.17","summary":"Was sich in Version 0.0.17 (2026-06-01) geändert hat.","markdown":"---\ntitle: 0.0.17\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-17/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.17\n\n> Was sich in Version 0.0.17 (2026-06-01) geändert hat.\n\nVersion 0.0.17 des npm-Pakets `total5`, veröffentlicht am 2026-06-01.\n\n```bash\nnpm install total5@0.0.17\n```\n\n## Neu\n\n- Methode `PROXYCLIENT(proxyserver, ip:port, [logger])` hinzugefügt\n- Methode `PROXYSERVER(endpoint, socketendpoint, [logger])` hinzugefügt\n- Methode `AIMODEL().tool(content)` hinzugefügt\n- Methode `AIPARSER(provider)` zum Parsen von KI-Antworten hinzugefügt\n- `String.prototype` um die Methode `String.parseContext()` erweitert, die ein bestimmtes Textdateiformat parst\n- Methode `ACTION().config(obj)` hinzugefügt\n- Neue Eigenschaft `flow.instance.repo = {}` zum Speichern zusätzlicher Daten für Instanzen von Flow-Knoten hinzugefügt\n\n## Geändert\n\n- Rückgabe von `origin` bei CORS verbessert\n- `DEBUG` wird anhand der Variable `process.env.NODE_ENV` gesetzt\n- Code verbessert\n- Methode `Utils.filestreamer()` um eine Prozentangabe erweitert\n\n## Behoben\n\n- Fehlerbehandlung bei E-Mails behoben\n- Entfernen von Routen über die Methode `route.remove()` behoben\n- Argumente `beautify` und `replacer` in `controller.json()` behoben\n- Priorität von `mail` behoben\n- Einheiten `kB` und `GB` im Routing als Upload-Limits behoben\n- Ping des Servers an alle WebSocket-Verbindungen behoben\n- Tippfehler bei der Datenzuweisung in der Send-Methode behoben\n- Methode `Utils.filestreamer()` behoben\n- Senden von Daten an alle Ausgänge mit `$.send(null, [data])` im FlowStream behoben\n- Senden von Daten an alle Ausgänge mit `instance.send(null, [data])` im FlowStream behoben\n- Entfernen von WebSocket-Routen behoben\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JacSJH1lk60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-17/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"es","title":"0.0.17","summary":"Qué cambió en la versión 0.0.17 (2026-06-01).","markdown":"---\ntitle: 0.0.17\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-17/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.17\n\n> Qué cambió en la versión 0.0.17 (2026-06-01).\n\nVersión 0.0.17 del paquete npm `total5`, publicada el 2026-06-01.\n\n```bash\nnpm install total5@0.0.17\n```\n\n## Novedades\n\n- Se añadió el método `PROXYCLIENT(proxyserver, ip:port, [logger])`\n- Se añadió el método `PROXYSERVER(endpoint, socketendpoint, [logger])`\n- Se añadió el método `AIMODEL().tool(content)`\n- Se añadió el método `AIPARSER(provider)` para parsear respuestas de IA\n- Se amplió `String.prototype` con el método `String.parseContext()` para parsear un formato de archivo de texto específico\n- Se añadió el método `ACTION().config(obj)`\n- Se añadió una nueva propiedad `flow.instance.repo = {}` para guardar datos adicionales de las instancias de nodos de Flow\n\n## Cambios\n\n- Se mejoró la devolución de `origin` en CORS\n- `DEBUG` se establece según la variable `process.env.NODE_ENV`\n- Se mejoró el código\n- Se mejoró el método `Utils.filestreamer()` añadiendo el porcentaje\n\n## Correcciones\n\n- Se corrigió la gestión de errores en los e-mails\n- Se corrigió la eliminación de rutas mediante el método `route.remove()`\n- Se corrigieron los argumentos `beautify` y `replacer` en `controller.json()`\n- Se corrigió la prioridad de `mail`\n- Se corrigieron las unidades `kB` y `GB` en el enrutamiento como límites de subida\n- Se corrigió el ping del servidor a todas las conexiones WebSocket\n- Se corrigió una errata en la asignación de datos del método send\n- Se corrigió el método `Utils.filestreamer()`\n- Se corrigió el envío de datos a todas las salidas `$.send(null, [data])` en FlowStream\n- Se corrigió el envío de datos a todas las salidas `instance.send(null, [data])` en FlowStream\n- Se corrigió la eliminación de una ruta WebSocket\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JacSJH1lk60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-17/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"fr","title":"0.0.17","summary":"Les changements de la version 0.0.17 (2026-06-01).","markdown":"---\ntitle: 0.0.17\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-17/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.17\n\n> Les changements de la version 0.0.17 (2026-06-01).\n\nVersion 0.0.17 du paquet npm `total5`, publiée le 2026-06-01.\n\n```bash\nnpm install total5@0.0.17\n```\n\n## Nouveautés\n\n- Ajout de la méthode `PROXYCLIENT(proxyserver, ip:port, [logger])`\n- Ajout de la méthode `PROXYSERVER(endpoint, socketendpoint, [logger])`\n- Ajout de la méthode `AIMODEL().tool(content)`\n- Ajout de la méthode `AIPARSER(provider)` pour analyser les réponses d'IA\n- Extension de `String.prototype` avec la méthode `String.parseContext()` pour analyser un format de fichier texte spécifique\n- Ajout de la méthode `ACTION().config(obj)`\n- Ajout d'une nouvelle propriété `flow.instance.repo = {}` pour stocker des données supplémentaires pour les instances de nœuds Flow\n\n## Modifications\n\n- Amélioration du renvoi de `origin` dans le CORS\n- `DEBUG` est défini selon la variable `process.env.NODE_ENV`\n- Amélioration du code\n- Amélioration de la méthode `Utils.filestreamer()` avec l'ajout du pourcentage\n\n## Corrections\n\n- Correction de la gestion des erreurs dans les e-mails\n- Correction de la suppression des routes via la méthode `route.remove()`\n- Correction des arguments `beautify` et `replacer` dans `controller.json()`\n- Correction de la priorité de `mail`\n- Correction des unités `kB` et `GB` dans le routage pour les limites d'upload\n- Correction du ping serveur de toutes les connexions WebSocket\n- Correction d'une faute de frappe dans l'assignation des données de la méthode send\n- Correction de la méthode `Utils.filestreamer()`\n- Correction de l'envoi de données vers toutes les sorties `$.send(null, [data])` dans le FlowStream\n- Correction de l'envoi de données vers toutes les sorties `instance.send(null, [data])` dans le FlowStream\n- Correction de la suppression d'une route WebSocket\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JacSJH1lk60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-17/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"it","title":"0.0.17","summary":"Cosa è cambiato nella release 0.0.17 (2026-06-01).","markdown":"---\ntitle: 0.0.17\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-17/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.17\n\n> Cosa è cambiato nella release 0.0.17 (2026-06-01).\n\nRelease 0.0.17 del pacchetto npm `total5`, pubblicata il 2026-06-01.\n\n```bash\nnpm install total5@0.0.17\n```\n\n## Novità\n\n- Aggiunto il metodo `PROXYCLIENT(proxyserver, ip:port, [logger])`\n- Aggiunto il metodo `PROXYSERVER(endpoint, socketendpoint, [logger])`\n- Aggiunto il metodo `AIMODEL().tool(content)`\n- Aggiunto il metodo `AIPARSER(provider)` per interpretare le risposte AI\n- Esteso `String.prototype` con il metodo `String.parseContext()` per interpretare un formato specifico di file di testo\n- Aggiunto il metodo `ACTION().config(obj)`\n- Aggiunta una nuova proprietà `flow.instance.repo = {}` per conservare dati aggiuntivi per le istanze dei nodi Flow\n\n## Modifiche\n\n- Migliorata la restituzione di `origin` nel CORS\n- `DEBUG` viene impostato in base alla variabile `process.env.NODE_ENV`\n- Codice migliorato\n- Migliorato il metodo `Utils.filestreamer()` con l'aggiunta della percentuale\n\n## Correzioni\n\n- Corretta la gestione degli errori nelle e-mail\n- Corretta la rimozione delle route tramite il metodo `route.remove()`\n- Corretti gli argomenti `beautify` e `replacer` in `controller.json()`\n- Corretta la priorità di `mail`\n- Corrette le unità `kB` e `GB` nel routing come limiti di upload\n- Corretto il ping del server verso tutte le connessioni WebSocket\n- Corretto un refuso nell'assegnazione dei dati del metodo send\n- Corretto il metodo `Utils.filestreamer()`\n- Corretto l'invio dei dati a tutti gli output `$.send(null, [data])` nel FlowStream\n- Corretto l'invio dei dati a tutti gli output `instance.send(null, [data])` nel FlowStream\n- Corretta la rimozione della route WebSocket\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JacSJH1lk60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-17/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"sk","title":"0.0.17","summary":"Čo sa zmenilo vo vydaní 0.0.17 (2026-06-01).","markdown":"---\ntitle: 0.0.17\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-17/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.17\n\n> Čo sa zmenilo vo vydaní 0.0.17 (2026-06-01).\n\nVydanie 0.0.17 npm balíka `total5`, publikované 2026-06-01.\n\n```bash\nnpm install total5@0.0.17\n```\n\n## Novinky\n\n- Pridaná metóda `PROXYCLIENT(proxyserver, ip:port, [logger])`\n- Pridaná metóda `PROXYSERVER(endpoint, socketendpoint, [logger])`\n- Pridaná metóda `AIMODEL().tool(content)`\n- Pridaná metóda `AIPARSER(provider)` na spracovanie AI odpovedí\n- Rozšírený `String.prototype` o metódu `String.parseContext()` na spracovanie špecifického formátu textového súboru\n- Pridaná metóda `ACTION().config(obj)`\n- Pridaná nová vlastnosť `flow.instance.repo = {}` na ukladanie ďalších dát pre inštancie uzlov Flow\n\n## Zmeny\n\n- Vylepšené vracanie `origin` v CORS\n- `DEBUG` sa nastavuje podľa premennej `process.env.NODE_ENV`\n- Vylepšený kód\n- Vylepšená metóda `Utils.filestreamer()` pridaním percent\n\n## Opravy\n\n- Opravené spracovanie chýb v e-mailoch\n- Opravené odstraňovanie trás cez metódu `route.remove()`\n- Opravené argumenty `beautify` a `replacer` v `controller.json()`\n- Opravená priorita `mail`\n- Opravené jednotky `kB` a `GB` v smerovaní ako limity nahrávania\n- Opravené pingovanie všetkých WebSocket spojení serverom\n- Opravený preklep v priradení dát v metóde send\n- Opravená metóda `Utils.filestreamer()`\n- Opravené posielanie dát do všetkých výstupov `$.send(null, [data])` vo FlowStreame\n- Opravené posielanie dát do všetkých výstupov `instance.send(null, [data])` vo FlowStreame\n- Opravené odstraňovanie WebSocket trasy\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JaedSq35F60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-16/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"en","title":"0.0.16","summary":"What changed in release 0.0.16 (2026-03-31).","markdown":"---\ntitle: 0.0.16\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-16/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.16\n\n> What changed in release 0.0.16 (2026-03-31).\n\nRelease 0.0.16 of the npm package `total5`, published on 2026-03-31.\n\n```bash\nnpm install total5@0.0.16\n```\n\n## New\n\n- Added `RESTBuilder.?.logerror()` method for printing errors into the console\n- Added `API.?.logerror()` method for printing errors into the console\n- Added a new config key `CONF.$httpcacheoffset` for extending `last-modified` header\n- Exended `Total.download()` by adding `size {Number}` property to the response\n- Extended FlowStream by adding the ability to execute Total.js actions\n- Added a new global event `ON('flowstream', function(instance) {`\n- Added new action methods `$.progress(percentage)` and `ACTION().progress(console.log)` to measure percentage\n- Added a new method `U.aistreamer(on_line, on_message)`\n- Added `Flow.edit(proxy_socket_url)` method for the remote editing of the FlowStream\n- Added a new global methods `AIMODEL()` and `NEWAIMODEL()`\n- Added `exec` command to the remote editing functionality\n- Added `timeout {Number}` property into the `NEWACTION` method\n- Extended `NEWAPI(type, [config], callback)` by adding the `config` argument\n- Added support for nested inline action schemas in action schemas\n- Extended `data` object in the `DEF.onAudit` delegate by adding `sessionid {String}` property\n- Added `options.timeout {Number}` to the `WebSocketClient`\n- Extended `U.chunker()` by adding `.load([callback])` method for loading existing chunks\n\n## Changed\n\n- Improved loading plugins\n- Framework reads a `/config` file in `plugins`\n- Improved auditlogs by adding `files`\n- Improved compiling navigation in the CMS compiler\n- Always set `cwd` directory for the current executed script\n- Replaced `Url.parse()` with `new URL()`\n- Changed `SIGTERM` for `SIGKILL` in the `NEWFORK()` method\n\n## Fixed\n\n- Fixed handling of unexpected problems in the Flow with the main process becoming disconnected\n- Fixed `uptime` value in the framework stats\n- Fixed unexpected errors when compressing/decompressing data via WebSocket\n- Fixed processing TMS data in the FlowStream\n- Fixed Total error handling\n- Fixed filling of the `template` property in the CMS compiler\n- Fixed `NEWFORK()` method\n- Fixed callback with `$` in the `ACTION().callback($)`\n- Fixed returing a default JSON schema object in actions\n- Fixed loading of `totalapi` key via `LOADCONFIG()`\n- Fixed promise in the `AJAX()` method\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JaedSq35F60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-16/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"de","title":"0.0.16","summary":"Was sich in Version 0.0.16 (2026-03-31) geändert hat.","markdown":"---\ntitle: 0.0.16\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-16/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.16\n\n> Was sich in Version 0.0.16 (2026-03-31) geändert hat.\n\nVersion 0.0.16 des npm-Pakets `total5`, veröffentlicht am 2026-03-31.\n\n```bash\nnpm install total5@0.0.16\n```\n\n## Neu\n\n- Methode `RESTBuilder.?.logerror()` zum Ausgeben von Fehlern in die Konsole hinzugefügt\n- Methode `API.?.logerror()` zum Ausgeben von Fehlern in die Konsole hinzugefügt\n- Neuer Konfigurationsschlüssel `CONF.$httpcacheoffset` zum Verlängern des `last-modified`-Headers hinzugefügt\n- `Total.download()` um die Eigenschaft `size {Number}` in der Antwort erweitert\n- FlowStream um die Möglichkeit erweitert, Total.js-Aktionen auszuführen\n- Neues globales Event `ON('flowstream', function(instance) {` hinzugefügt\n- Neue Aktionsmethoden `$.progress(percentage)` und `ACTION().progress(console.log)` zum Messen des Fortschritts in Prozent hinzugefügt\n- Neue Methode `U.aistreamer(on_line, on_message)` hinzugefügt\n- Methode `Flow.edit(proxy_socket_url)` für die Remote-Bearbeitung des FlowStream hinzugefügt\n- Neue globale Methoden `AIMODEL()` und `NEWAIMODEL()` hinzugefügt\n- Befehl `exec` zur Remote-Bearbeitung hinzugefügt\n- Eigenschaft `timeout {Number}` zur Methode `NEWACTION` hinzugefügt\n- `NEWAPI(type, [config], callback)` um das Argument `config` erweitert\n- Unterstützung für verschachtelte Inline-Aktionsschemas in Aktionsschemas hinzugefügt\n- Objekt `data` im Delegate `DEF.onAudit` um die Eigenschaft `sessionid {String}` erweitert\n- `options.timeout {Number}` zum `WebSocketClient` hinzugefügt\n- `U.chunker()` um die Methode `.load([callback])` zum Laden vorhandener Chunks erweitert\n\n## Geändert\n\n- Laden von Plugins verbessert\n- Das Framework liest eine `/config`-Datei in `plugins`\n- Audit-Logs durch Hinzufügen von `files` verbessert\n- Kompilieren der Navigation im CMS-Compiler verbessert\n- Das `cwd`-Verzeichnis wird immer für das aktuell ausgeführte Skript gesetzt\n- `Url.parse()` durch `new URL()` ersetzt\n- `SIGTERM` in der Methode `NEWFORK()` durch `SIGKILL` ersetzt\n\n## Behoben\n\n- Behandlung unerwarteter Probleme im Flow behoben, wenn die Verbindung zum Hauptprozess getrennt wird\n- Wert `uptime` in den Statistiken des Frameworks behoben\n- Unerwartete Fehler beim Komprimieren/Dekomprimieren von Daten über WebSocket behoben\n- Verarbeitung von TMS-Daten im FlowStream behoben\n- Fehlerbehandlung von Total behoben\n- Befüllen der Eigenschaft `template` im CMS-Compiler behoben\n- Methode `NEWFORK()` behoben\n- Callback mit `$` in `ACTION().callback($)` behoben\n- Rückgabe eines Standard-JSON-Schema-Objekts in Aktionen behoben\n- Laden des Schlüssels `totalapi` über `LOADCONFIG()` behoben\n- Promise in der Methode `AJAX()` behoben\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JaedSq35F60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-16/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"es","title":"0.0.16","summary":"Qué cambió en la versión 0.0.16 (2026-03-31).","markdown":"---\ntitle: 0.0.16\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-16/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.16\n\n> Qué cambió en la versión 0.0.16 (2026-03-31).\n\nVersión 0.0.16 del paquete npm `total5`, publicada el 2026-03-31.\n\n```bash\nnpm install total5@0.0.16\n```\n\n## Novedades\n\n- Añadido el método `RESTBuilder.?.logerror()` para imprimir errores en la consola\n- Añadido el método `API.?.logerror()` para imprimir errores en la consola\n- Añadida una nueva clave de configuración `CONF.$httpcacheoffset` para ampliar la cabecera `last-modified`\n- Ampliado `Total.download()` añadiendo la propiedad `size {Number}` a la respuesta\n- Ampliado FlowStream añadiendo la posibilidad de ejecutar acciones de Total.js\n- Añadido un nuevo evento global `ON('flowstream', function(instance) {`\n- Añadidos nuevos métodos de acción `$.progress(percentage)` y `ACTION().progress(console.log)` para medir el porcentaje\n- Añadido un nuevo método `U.aistreamer(on_line, on_message)`\n- Añadido el método `Flow.edit(proxy_socket_url)` para la edición remota de FlowStream\n- Añadidos los nuevos métodos globales `AIMODEL()` y `NEWAIMODEL()`\n- Añadido el comando `exec` a la funcionalidad de edición remota\n- Añadida la propiedad `timeout {Number}` al método `NEWACTION`\n- Ampliado `NEWAPI(type, [config], callback)` añadiendo el argumento `config`\n- Añadido soporte para esquemas de acción en línea anidados en los esquemas de acción\n- Ampliado el objeto `data` del delegado `DEF.onAudit` añadiendo la propiedad `sessionid {String}`\n- Añadido `options.timeout {Number}` a `WebSocketClient`\n- Ampliado `U.chunker()` añadiendo el método `.load([callback])` para cargar chunks existentes\n\n## Cambios\n\n- Mejorada la carga de plugins\n- El framework lee un archivo `/config` en `plugins`\n- Mejorados los registros de auditoría añadiendo `files`\n- Mejorada la compilación de la navegación en el compilador del CMS\n- Siempre se establece el directorio `cwd` para el script ejecutado actualmente\n- Sustituido `Url.parse()` por `new URL()`\n- Cambiado `SIGTERM` por `SIGKILL` en el método `NEWFORK()`\n\n## Correcciones\n\n- Corregida la gestión de problemas inesperados en Flow cuando el proceso principal se desconecta\n- Corregido el valor `uptime` en las estadísticas del framework\n- Corregidos errores inesperados al comprimir/descomprimir datos mediante WebSocket\n- Corregido el procesamiento de datos TMS en FlowStream\n- Corregida la gestión de errores de Total\n- Corregido el rellenado de la propiedad `template` en el compilador del CMS\n- Corregido el método `NEWFORK()`\n- Corregido el callback con `$` en `ACTION().callback($)`\n- Corregida la devolución de un objeto de esquema JSON por defecto en las acciones\n- Corregida la carga de la clave `totalapi` mediante `LOADCONFIG()`\n- Corregida la promesa en el método `AJAX()`\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JaedSq35F60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-16/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"fr","title":"0.0.16","summary":"Ce qui a changé dans la version 0.0.16 (2026-03-31).","markdown":"---\ntitle: 0.0.16\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-16/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.16\n\n> Ce qui a changé dans la version 0.0.16 (2026-03-31).\n\nVersion 0.0.16 du paquet npm `total5`, publiée le 2026-03-31.\n\n```bash\nnpm install total5@0.0.16\n```\n\n## Nouveautés\n\n- Ajout de la méthode `RESTBuilder.?.logerror()` pour afficher les erreurs dans la console\n- Ajout de la méthode `API.?.logerror()` pour afficher les erreurs dans la console\n- Ajout d'une nouvelle clé de configuration `CONF.$httpcacheoffset` pour prolonger l'en-tête `last-modified`\n- Extension de `Total.download()` avec l'ajout de la propriété `size {Number}` à la réponse\n- Extension de FlowStream avec la possibilité d'exécuter des actions Total.js\n- Ajout d'un nouvel événement global `ON('flowstream', function(instance) {`\n- Ajout des nouvelles méthodes d'action `$.progress(percentage)` et `ACTION().progress(console.log)` pour mesurer le pourcentage\n- Ajout d'une nouvelle méthode `U.aistreamer(on_line, on_message)`\n- Ajout de la méthode `Flow.edit(proxy_socket_url)` pour l'édition à distance de FlowStream\n- Ajout des nouvelles méthodes globales `AIMODEL()` et `NEWAIMODEL()`\n- Ajout de la commande `exec` à la fonctionnalité d'édition à distance\n- Ajout de la propriété `timeout {Number}` dans la méthode `NEWACTION`\n- Extension de `NEWAPI(type, [config], callback)` avec l'ajout de l'argument `config`\n- Ajout de la prise en charge des schémas d'action en ligne imbriqués dans les schémas d'action\n- Extension de l'objet `data` du délégué `DEF.onAudit` avec l'ajout de la propriété `sessionid {String}`\n- Ajout de `options.timeout {Number}` au `WebSocketClient`\n- Extension de `U.chunker()` avec l'ajout de la méthode `.load([callback])` pour charger des chunks existants\n\n## Modifications\n\n- Amélioration du chargement des plugins\n- Le framework lit un fichier `/config` dans `plugins`\n- Amélioration des journaux d'audit avec l'ajout de `files`\n- Amélioration de la compilation de la navigation dans le compilateur CMS\n- Le répertoire `cwd` est toujours défini pour le script en cours d'exécution\n- Remplacement de `Url.parse()` par `new URL()`\n- Remplacement de `SIGTERM` par `SIGKILL` dans la méthode `NEWFORK()`\n\n## Corrections\n\n- Correction de la gestion des problèmes inattendus dans le Flow lorsque le processus principal est déconnecté\n- Correction de la valeur `uptime` dans les statistiques du framework\n- Correction d'erreurs inattendues lors de la compression/décompression de données via WebSocket\n- Correction du traitement des données TMS dans FlowStream\n- Correction de la gestion des erreurs de Total\n- Correction du remplissage de la propriété `template` dans le compilateur CMS\n- Correction de la méthode `NEWFORK()`\n- Correction du callback avec `$` dans `ACTION().callback($)`\n- Correction du renvoi d'un objet de schéma JSON par défaut dans les actions\n- Correction du chargement de la clé `totalapi` via `LOADCONFIG()`\n- Correction de la promesse dans la méthode `AJAX()`\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JaedSq35F60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-16/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"it","title":"0.0.16","summary":"Cosa è cambiato nella versione 0.0.16 (2026-03-31).","markdown":"---\ntitle: 0.0.16\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-16/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.16\n\n> Cosa è cambiato nella versione 0.0.16 (2026-03-31).\n\nVersione 0.0.16 del pacchetto npm `total5`, pubblicata il 2026-03-31.\n\n```bash\nnpm install total5@0.0.16\n```\n\n## Novità\n\n- Aggiunto il metodo `RESTBuilder.?.logerror()` per stampare gli errori nella console\n- Aggiunto il metodo `API.?.logerror()` per stampare gli errori nella console\n- Aggiunta una nuova chiave di configurazione `CONF.$httpcacheoffset` per estendere l'header `last-modified`\n- Esteso `Total.download()` aggiungendo la proprietà `size {Number}` alla risposta\n- Esteso FlowStream aggiungendo la possibilità di eseguire le azioni di Total.js\n- Aggiunto un nuovo evento globale `ON('flowstream', function(instance) {`\n- Aggiunti nuovi metodi delle azioni `$.progress(percentage)` e `ACTION().progress(console.log)` per misurare la percentuale\n- Aggiunto un nuovo metodo `U.aistreamer(on_line, on_message)`\n- Aggiunto il metodo `Flow.edit(proxy_socket_url)` per la modifica remota di FlowStream\n- Aggiunti nuovi metodi globali `AIMODEL()` e `NEWAIMODEL()`\n- Aggiunto il comando `exec` alla funzionalità di modifica remota\n- Aggiunta la proprietà `timeout {Number}` al metodo `NEWACTION`\n- Esteso `NEWAPI(type, [config], callback)` aggiungendo l'argomento `config`\n- Aggiunto il supporto per schemi di azione inline annidati negli schemi di azione\n- Esteso l'oggetto `data` nel delegate `DEF.onAudit` aggiungendo la proprietà `sessionid {String}`\n- Aggiunto `options.timeout {Number}` a `WebSocketClient`\n- Esteso `U.chunker()` aggiungendo il metodo `.load([callback])` per caricare chunk esistenti\n\n## Modifiche\n\n- Migliorato il caricamento dei plugin\n- Il framework legge un file `/config` in `plugins`\n- Migliorati gli audit log aggiungendo `files`\n- Migliorata la compilazione della navigazione nel compilatore CMS\n- Impostata sempre la directory `cwd` per lo script attualmente eseguito\n- Sostituito `Url.parse()` con `new URL()`\n- Sostituito `SIGTERM` con `SIGKILL` nel metodo `NEWFORK()`\n\n## Correzioni\n\n- Corretta la gestione di problemi imprevisti nel Flow quando il processo principale si disconnette\n- Corretto il valore `uptime` nelle statistiche del framework\n- Corretti errori imprevisti durante la compressione/decompressione dei dati tramite WebSocket\n- Corretta l'elaborazione dei dati TMS in FlowStream\n- Corretta la gestione degli errori di Total\n- Corretto il riempimento della proprietà `template` nel compilatore CMS\n- Corretto il metodo `NEWFORK()`\n- Corretta la callback con `$` in `ACTION().callback($)`\n- Corretta la restituzione di un oggetto JSON schema predefinito nelle azioni\n- Corretto il caricamento della chiave `totalapi` tramite `LOADCONFIG()`\n- Corretta la promise nel metodo `AJAX()`\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JaedSq35F60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-16/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"sk","title":"0.0.16","summary":"Čo sa zmenilo vo vydaní 0.0.16 (2026-03-31).","markdown":"---\ntitle: 0.0.16\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-16/\nupdated: 2026-11-16T07:54:33.030Z\n---\n\n# 0.0.16\n\n> Čo sa zmenilo vo vydaní 0.0.16 (2026-03-31).\n\nVydanie 0.0.16 balíka npm `total5`, publikované 2026-03-31.\n\n```bash\nnpm install total5@0.0.16\n```\n\n## Nové\n\n- Pridaná metóda `RESTBuilder.?.logerror()` na výpis chýb do konzoly\n- Pridaná metóda `API.?.logerror()` na výpis chýb do konzoly\n- Pridaný nový konfiguračný kľúč `CONF.$httpcacheoffset` na predĺženie hlavičky `last-modified`\n- Rozšírené `Total.download()` o vlastnosť `size {Number}` v odpovedi\n- Rozšírený FlowStream o možnosť vykonávať akcie Total.js\n- Pridaná nová globálna udalosť `ON('flowstream', function(instance) {`\n- Pridané nové metódy akcií `$.progress(percentage)` a `ACTION().progress(console.log)` na meranie percentuálneho priebehu\n- Pridaná nová metóda `U.aistreamer(on_line, on_message)`\n- Pridaná metóda `Flow.edit(proxy_socket_url)` na vzdialenú úpravu FlowStreamu\n- Pridané nové globálne metódy `AIMODEL()` a `NEWAIMODEL()`\n- Pridaný príkaz `exec` do funkcie vzdialenej úpravy\n- Pridaná vlastnosť `timeout {Number}` do metódy `NEWACTION`\n- Rozšírené `NEWAPI(type, [config], callback)` o argument `config`\n- Pridaná podpora vnorených inline schém akcií v schémach akcií\n- Rozšírený objekt `data` v delegáte `DEF.onAudit` o vlastnosť `sessionid {String}`\n- Pridané `options.timeout {Number}` do `WebSocketClient`\n- Rozšírené `U.chunker()` o metódu `.load([callback])` na načítanie existujúcich chunkov\n\n## Zmenené\n\n- Vylepšené načítavanie pluginov\n- Framework číta súbor `/config` v `plugins`\n- Vylepšené auditné logy pridaním `files`\n- Vylepšená kompilácia navigácie v CMS kompilátore\n- Vždy sa nastaví adresár `cwd` pre aktuálne vykonávaný skript\n- `Url.parse()` nahradené pomocou `new URL()`\n- `SIGTERM` zmenené na `SIGKILL` v metóde `NEWFORK()`\n\n## Opravené\n\n- Opravené spracovanie neočakávaných problémov vo Flow pri odpojení hlavného procesu\n- Opravená hodnota `uptime` v štatistikách frameworku\n- Opravené neočakávané chyby pri kompresii/dekompresii dát cez WebSocket\n- Opravené spracovanie dát TMS vo FlowStreame\n- Opravené spracovanie chýb Total\n- Opravené vypĺňanie vlastnosti `template` v CMS kompilátore\n- Opravená metóda `NEWFORK()`\n- Opravený callback s `$` v `ACTION().callback($)`\n- Opravené vrátenie predvoleného objektu JSON schémy v akciách\n- Opravené načítanie kľúča `totalapi` cez `LOADCONFIG()`\n- Opravený promise v metóde `AJAX()`\n","entries":[],"license":"MIT","updated":"2026-11-16T07:54:33.030Z"}
{"id":"JacSIm1dk60f","url":"https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-15/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"en","title":"0.0.15","summary":"What changed in release 0.0.15 (2025-12-04).","markdown":"---\ntitle: 0.0.15\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v5/0-0-20/changelog/0-0-15/\nupdated: 2026-11-15T17:28:34.394Z\n---\n\n# 0.0.15\n\n> What changed in release 0.0.15 (2025-12-04).\n\nRelease 0.0.15 of the npm package `total5`, published on 2025-12-04.\n\n```bash\nnpm install total5@0.0.15\n```\n\n## New\n\n- Added support for `.webmanifest` file extension\n- Added a new JSON Schema type `DataURI2` that keeps a value as text\n\n## Changed\n\n- Improved `keepalive` option in the `REQUEST()` method (it can contain HttpAgent or options for it)\n- Updated `RESTBuilder.keepalive()` method by adding `val` argument\n- Improved error handling in the Flow engine\n\n## Fixed\n\n- Fixed nested objects in JSON schemas\n- Fixed column indexer in the CSV parser\n- Fixed proxy timeout\n- Fixed string slug method\n- Fixed an issue with generating file names when merging files directly in the view engine\n- Fixed handling of case-sensitive file names\n- Fixed unexpected errors with the stream when handling static files\n- Fixed sending mail attachments\n- Fixed creating an empty object according to the nested JSON schema\n- Fixed handling unexpected errors in the FlowStream\n- Fixed network connection problems in remote editing\n- Fixed throwing of timeout error in WebSocketClient\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:34.394Z"}
{"id":"JacSIm1dk60f-de","url":"https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-15/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"de","title":"0.0.15","summary":"Was sich in Version 0.0.15 (2025-12-04) geändert hat.","markdown":"---\ntitle: 0.0.15\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v5/0-0-20/changelog/0-0-15/\nupdated: 2026-11-15T17:28:34.394Z\n---\n\n# 0.0.15\n\n> Was sich in Version 0.0.15 (2025-12-04) geändert hat.\n\nVersion 0.0.15 des npm-Pakets `total5`, veröffentlicht am 2025-12-04.\n\n```bash\nnpm install total5@0.0.15\n```\n\n## Neu\n\n- Unterstützung für die Dateiendung `.webmanifest` hinzugefügt\n- Neuer JSON-Schema-Typ `DataURI2` hinzugefügt, der einen Wert als Text behält\n\n## Geändert\n\n- Option `keepalive` in der Methode `REQUEST()` verbessert (sie kann einen HttpAgent oder Optionen dafür enthalten)\n- Methode `RESTBuilder.keepalive()` um das Argument `val` erweitert\n- Fehlerbehandlung in der Flow-Engine verbessert\n\n## Behoben\n\n- Verschachtelte Objekte in JSON-Schemas behoben\n- Spaltenindexer im CSV-Parser behoben\n- Proxy-Timeout behoben\n- Slug-Methode für Strings behoben\n- Problem beim Erzeugen von Dateinamen behoben, wenn Dateien direkt in der View-Engine zusammengeführt werden\n- Behandlung von Dateinamen mit Groß- und Kleinschreibung behoben\n- Unerwartete Fehler mit dem Stream bei der Auslieferung statischer Dateien behoben\n- Versand von Mail-Anhängen behoben\n- Erzeugen eines leeren Objekts gemäß dem verschachtelten JSON-Schema behoben\n- Behandlung unerwarteter Fehler im FlowStream behoben\n- Probleme mit der Netzwerkverbindung beim Remote-Editing behoben\n- Auslösen des Timeout-Fehlers in WebSocketClient behoben\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:34.394Z"}
{"id":"JacSIm1dk60f-es","url":"https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-15/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"es","title":"0.0.15","summary":"Qué cambió en la versión 0.0.15 (2025-12-04).","markdown":"---\ntitle: 0.0.15\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v5/0-0-20/changelog/0-0-15/\nupdated: 2026-11-15T17:28:34.394Z\n---\n\n# 0.0.15\n\n> Qué cambió en la versión 0.0.15 (2025-12-04).\n\nVersión 0.0.15 del paquete npm `total5`, publicada el 2025-12-04.\n\n```bash\nnpm install total5@0.0.15\n```\n\n## Novedades\n\n- Se añadió soporte para la extensión de archivo `.webmanifest`\n- Se añadió un nuevo tipo de JSON Schema `DataURI2` que guarda el valor como texto\n\n## Cambios\n\n- Se mejoró la opción `keepalive` del método `REQUEST()` (puede contener un HttpAgent o sus opciones)\n- Se actualizó el método `RESTBuilder.keepalive()` con el argumento `val`\n- Se mejoró el manejo de errores en el motor de Flow\n\n## Correcciones\n\n- Se corrigieron los objetos anidados en los esquemas JSON\n- Se corrigió el indexador de columnas en el parser de CSV\n- Se corrigió el timeout del proxy\n- Se corrigió el método slug de cadenas\n- Se corrigió un problema al generar nombres de archivo al combinar archivos directamente en el motor de vistas\n- Se corrigió el manejo de nombres de archivo que distinguen mayúsculas y minúsculas\n- Se corrigieron errores inesperados con el stream al servir archivos estáticos\n- Se corrigió el envío de adjuntos de correo\n- Se corrigió la creación de un objeto vacío según el esquema JSON anidado\n- Se corrigió el manejo de errores inesperados en el FlowStream\n- Se corrigieron problemas de conexión de red en la edición remota\n- Se corrigió el lanzamiento del error de timeout en WebSocketClient\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:34.394Z"}
{"id":"JacSIm1dk60f-fr","url":"https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-15/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"fr","title":"0.0.15","summary":"Les changements de la version 0.0.15 (2025-12-04).","markdown":"---\ntitle: 0.0.15\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v5/0-0-20/changelog/0-0-15/\nupdated: 2026-11-15T17:28:34.394Z\n---\n\n# 0.0.15\n\n> Les changements de la version 0.0.15 (2025-12-04).\n\nVersion 0.0.15 du paquet npm `total5`, publiée le 2025-12-04.\n\n```bash\nnpm install total5@0.0.15\n```\n\n## Nouveautés\n\n- Ajout de la prise en charge de l'extension de fichier `.webmanifest`\n- Ajout d'un nouveau type JSON Schema `DataURI2` qui conserve une valeur sous forme de texte\n\n## Modifications\n\n- Amélioration de l'option `keepalive` de la méthode `REQUEST()` (elle peut contenir un HttpAgent ou ses options)\n- Mise à jour de la méthode `RESTBuilder.keepalive()` avec l'ajout de l'argument `val`\n- Amélioration de la gestion des erreurs dans le moteur Flow\n\n## Corrections\n\n- Correction des objets imbriqués dans les schémas JSON\n- Correction de l'indexeur de colonnes dans le parseur CSV\n- Correction du timeout du proxy\n- Correction de la méthode slug des chaînes\n- Correction d'un problème de génération des noms de fichiers lors de la fusion de fichiers directement dans le moteur de vues\n- Correction de la gestion des noms de fichiers sensibles à la casse\n- Correction d'erreurs inattendues du flux lors du traitement des fichiers statiques\n- Correction de l'envoi des pièces jointes des e-mails\n- Correction de la création d'un objet vide selon le schéma JSON imbriqué\n- Correction de la gestion des erreurs inattendues dans le FlowStream\n- Correction de problèmes de connexion réseau dans l'édition à distance\n- Correction de la levée de l'erreur de timeout dans WebSocketClient\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:34.394Z"}
{"id":"JacSIm1dk60f-it","url":"https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-15/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"it","title":"0.0.15","summary":"Cosa è cambiato nella release 0.0.15 (2025-12-04).","markdown":"---\ntitle: 0.0.15\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v5/0-0-20/changelog/0-0-15/\nupdated: 2026-11-15T17:28:34.394Z\n---\n\n# 0.0.15\n\n> Cosa è cambiato nella release 0.0.15 (2025-12-04).\n\nRelease 0.0.15 del pacchetto npm `total5`, pubblicata il 2025-12-04.\n\n```bash\nnpm install total5@0.0.15\n```\n\n## Novità\n\n- Aggiunto il supporto per l'estensione di file `.webmanifest`\n- Aggiunto un nuovo tipo di JSON Schema `DataURI2` che mantiene un valore come testo\n\n## Modifiche\n\n- Migliorata l'opzione `keepalive` nel metodo `REQUEST()` (può contenere un HttpAgent o le sue opzioni)\n- Aggiornato il metodo `RESTBuilder.keepalive()` con l'aggiunta dell'argomento `val`\n- Migliorata la gestione degli errori nel motore Flow\n\n## Correzioni\n\n- Corretti gli oggetti annidati negli schemi JSON\n- Corretto l'indicizzatore di colonne nel parser CSV\n- Corretto il timeout del proxy\n- Corretto il metodo slug delle stringhe\n- Corretto un problema nella generazione dei nomi di file quando si uniscono file direttamente nel motore delle viste\n- Corretta la gestione dei nomi di file con distinzione tra maiuscole e minuscole\n- Corretti errori imprevisti dello stream nella gestione dei file statici\n- Corretto l'invio degli allegati email\n- Corretta la creazione di un oggetto vuoto secondo lo schema JSON annidato\n- Corretta la gestione degli errori imprevisti nel FlowStream\n- Corretti problemi di connessione di rete nella modifica remota\n- Corretto il lancio dell'errore di timeout in WebSocketClient\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:34.394Z"}
{"id":"JacSIm1dk60f-sk","url":"https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-15/","project":"total-js-v5","version":"0-0-20","section":"changelog","language":"sk","title":"0.0.15","summary":"Čo sa zmenilo vo vydaní 0.0.15 (2025-12-04).","markdown":"---\ntitle: 0.0.15\nproject: Total.js V5\nversion: 0.0.20\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v5/0-0-20/changelog/0-0-15/\nupdated: 2026-11-15T17:28:34.394Z\n---\n\n# 0.0.15\n\n> Čo sa zmenilo vo vydaní 0.0.15 (2025-12-04).\n\nVydanie 0.0.15 npm balíka `total5`, publikované 2025-12-04.\n\n```bash\nnpm install total5@0.0.15\n```\n\n## Novinky\n\n- Pridaná podpora prípony súborov `.webmanifest`\n- Pridaný nový typ JSON Schema `DataURI2`, ktorý uchováva hodnotu ako text\n\n## Zmeny\n\n- Vylepšená voľba `keepalive` v metóde `REQUEST()` (môže obsahovať HttpAgent alebo jeho voľby)\n- Aktualizovaná metóda `RESTBuilder.keepalive()` pridaním argumentu `val`\n- Vylepšené spracovanie chýb vo Flow engine\n\n## Opravy\n\n- Opravené vnorené objekty v JSON schémach\n- Opravený indexer stĺpcov v CSV parseri\n- Opravený timeout proxy\n- Opravená metóda slug pre reťazce\n- Opravený problém s generovaním názvov súborov pri zlučovaní súborov priamo vo view engine\n- Opravené spracovanie názvov súborov citlivých na veľkosť písmen\n- Opravené neočakávané chyby so streamom pri spracovaní statických súborov\n- Opravené odosielanie príloh e-mailov\n- Opravené vytváranie prázdneho objektu podľa vnorenej JSON schémy\n- Opravené spracovanie neočakávaných chýb vo FlowStream\n- Opravené problémy so sieťovým pripojením pri vzdialenej úprave\n- Opravené vyhadzovanie chyby timeoutu vo WebSocketClient\n","entries":[],"license":"MIT","updated":"2026-11-15T17:28:34.394Z"}
